HostageDBOpenHelper.java 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011
  1. package de.tudarmstadt.informatik.hostage.persistence;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.LinkedList;
  5. import java.util.List;
  6. import android.content.ContentValues;
  7. import android.content.Context;
  8. import android.database.Cursor;
  9. import android.database.CursorIndexOutOfBoundsException;
  10. import android.database.sqlite.SQLiteDatabase;
  11. import android.database.sqlite.SQLiteOpenHelper;
  12. import android.util.Log;
  13. import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
  14. import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
  15. import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
  16. import de.tudarmstadt.informatik.hostage.logging.Record;
  17. import de.tudarmstadt.informatik.hostage.logging.SyncDevice;
  18. import de.tudarmstadt.informatik.hostage.logging.SyncInfo;
  19. import de.tudarmstadt.informatik.hostage.logging.SyncInfoRecord;
  20. import de.tudarmstadt.informatik.hostage.logging.MessageRecord.TYPE;
  21. import de.tudarmstadt.informatik.hostage.logging.SyncRecord;
  22. import de.tudarmstadt.informatik.hostage.model.Profile;
  23. import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.AttackEntry;
  24. import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.NetworkEntry;
  25. import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.PacketEntry;
  26. import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.ProfileEntry;
  27. import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.SyncDeviceEntry;
  28. import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.SyncInfoEntry;
  29. import de.tudarmstadt.informatik.hostage.ui.helper.ColorSequenceGenerator;
  30. import de.tudarmstadt.informatik.hostage.ui.model.LogFilter;
  31. import de.tudarmstadt.informatik.hostage.ui.model.PlotComparisonItem;
  32. /**
  33. * Database Helper class to create, read and write the database.
  34. * @author Mihai Plasoianu
  35. * @author Lars Pandikow
  36. *
  37. */
  38. public class HostageDBOpenHelper extends SQLiteOpenHelper {
  39. private static final String DATABASE_NAME = "hostage.db";
  40. private static final int DATABASE_VERSION = 3;
  41. private Context context;
  42. static {
  43. // NETWORK
  44. StringBuilder networkSQLBuilder = new StringBuilder("CREATE TABLE ").append(NetworkEntry.TABLE_NAME).append("(");
  45. networkSQLBuilder.append(NetworkEntry.COLUMN_NAME_BSSID).append(" TEXT PRIMARY KEY,");
  46. networkSQLBuilder.append(NetworkEntry.COLUMN_NAME_SSID).append(" TEXT,");
  47. networkSQLBuilder.append(NetworkEntry.COLUMN_NAME_LATITUDE).append(" INTEGER,");
  48. networkSQLBuilder.append(NetworkEntry.COLUMN_NAME_LONGITUDE).append(" INTEGER,");
  49. networkSQLBuilder.append(NetworkEntry.COLUMN_NAME_ACCURACY).append(" INTEGER,");
  50. networkSQLBuilder.append(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP).append(" INTEGER");
  51. networkSQLBuilder.append(")");
  52. SQL_CREATE_NETWORK_ENTRIES = networkSQLBuilder.toString();
  53. // ATTACK
  54. StringBuilder attackSQLBuilder = new StringBuilder("CREATE TABLE ").append(AttackEntry.TABLE_NAME).append("(");
  55. attackSQLBuilder.append(AttackEntry.COLUMN_NAME_ATTACK_ID).append(" INTEGER PRIMARY KEY,");
  56. attackSQLBuilder.append(AttackEntry.COLUMN_NAME_PROTOCOL).append(" TEXT,");
  57. attackSQLBuilder.append(AttackEntry.COLUMN_NAME_EXTERNAL_IP).append(" TEXT,");
  58. attackSQLBuilder.append(AttackEntry.COLUMN_NAME_LOCAL_IP).append(" BLOB,");
  59. attackSQLBuilder.append(AttackEntry.COLUMN_NAME_LOCAL_PORT).append(" INTEGER,");
  60. attackSQLBuilder.append(AttackEntry.COLUMN_NAME_REMOTE_IP).append(" BLOB,");
  61. attackSQLBuilder.append(AttackEntry.COLUMN_NAME_REMOTE_PORT).append(" INTEGER,");
  62. attackSQLBuilder.append(AttackEntry.COLUMN_NAME_INTERNAL_ATTACK).append(" INTEGER,");
  63. attackSQLBuilder.append(AttackEntry.COLUMN_NAME_BSSID).append(" TEXT,");
  64. attackSQLBuilder.append(AttackEntry.COLUMN_NAME_SYNC_ID).append(" INTEGER,");
  65. attackSQLBuilder.append(AttackEntry.COLUMN_NAME_DEVICE).append(" TEXT,");
  66. attackSQLBuilder.append(String.format("FOREIGN KEY(%s) REFERENCES %s(%s) ON DELETE CASCADE ON UPDATE CASCADE,", AttackEntry.COLUMN_NAME_BSSID, NetworkEntry.TABLE_NAME,
  67. NetworkEntry.COLUMN_NAME_BSSID));
  68. attackSQLBuilder.append(String.format("FOREIGN KEY(%s) REFERENCES %s(%s) ON DELETE CASCADE ON UPDATE CASCADE", AttackEntry.COLUMN_NAME_DEVICE, SyncDeviceEntry.TABLE_NAME,
  69. SyncDeviceEntry.COLUMN_NAME_DEVICE_ID));
  70. attackSQLBuilder.append(")");
  71. SQL_CREATE_ATTACK_ENTRIES = attackSQLBuilder.toString();
  72. // PACKET
  73. StringBuilder packetSQLBuilder = new StringBuilder("CREATE TABLE ").append(PacketEntry.TABLE_NAME).append("(");
  74. packetSQLBuilder.append(PacketEntry.COLUMN_NAME_ID).append(" INTEGER NOT NULL,");
  75. packetSQLBuilder.append(PacketEntry.COLUMN_NAME_ATTACK_ID).append(" INTEGER NOT NULL,");
  76. packetSQLBuilder.append(PacketEntry.COLUMN_NAME_TYPE).append(" TEXT,");
  77. packetSQLBuilder.append(PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP).append(" INTEGER,");
  78. packetSQLBuilder.append(PacketEntry.COLUMN_NAME_PACKET).append(" TEXT,");
  79. packetSQLBuilder.append(String.format("PRIMARY KEY(%s,%s)", PacketEntry.COLUMN_NAME_ID, PacketEntry.COLUMN_NAME_ATTACK_ID));
  80. packetSQLBuilder.append(String.format("FOREIGN KEY(%s) REFERENCES %s(%s)", PacketEntry.COLUMN_NAME_ATTACK_ID, AttackEntry.TABLE_NAME,
  81. AttackEntry.COLUMN_NAME_ATTACK_ID));
  82. packetSQLBuilder.append(")");
  83. SQL_CREATE_PACKET_ENTRIES = packetSQLBuilder.toString();
  84. // SyncDeviceEntry
  85. StringBuilder syncDevicesSQLBuilder = new StringBuilder("CREATE TABLE ").append(SyncDeviceEntry.TABLE_NAME).append("(");
  86. syncDevicesSQLBuilder.append(SyncDeviceEntry.COLUMN_NAME_DEVICE_ID).append(" TEXT PRIMARY KEY,");
  87. syncDevicesSQLBuilder.append(SyncDeviceEntry.COLUMN_NAME_DEVICE_TIMESTAMP).append(" INTEGER,");
  88. syncDevicesSQLBuilder.append(SyncDeviceEntry.COLUMN_NAME_HIGHEST_ATTACK_ID).append(" INTEGER");
  89. syncDevicesSQLBuilder.append(")");
  90. SQL_CREATE_SYNC_DEVICES_ENTRIES = syncDevicesSQLBuilder.toString();
  91. // SyncInfoEntry
  92. StringBuilder syncInfoSQLBuilder = new StringBuilder("CREATE TABLE ").append(SyncInfoEntry.TABLE_NAME).append("(");
  93. syncInfoSQLBuilder.append(SyncInfoEntry.COLUMN_NAME_DEVICE_ID).append(" TEXT,");
  94. syncInfoSQLBuilder.append(SyncInfoEntry.COLUMN_NAME_BSSID).append(" TEXT,");
  95. syncInfoSQLBuilder.append(SyncInfoEntry.COLUMN_NAME_NUMBER_ATTACKS).append(" INTEGER,");
  96. syncInfoSQLBuilder.append(SyncInfoEntry.COLUMN_NAME_NUMBER_PORTSCANS).append(" INTEGER,");
  97. syncInfoSQLBuilder.append(String.format("PRIMARY KEY(%s,%s)", SyncInfoEntry.COLUMN_NAME_DEVICE_ID, SyncInfoEntry.COLUMN_NAME_BSSID));
  98. syncInfoSQLBuilder.append(String.format("FOREIGN KEY(%s) REFERENCES %s(%s)", SyncInfoEntry.COLUMN_NAME_BSSID, NetworkEntry.TABLE_NAME,
  99. NetworkEntry.COLUMN_NAME_BSSID));
  100. syncInfoSQLBuilder.append(")");
  101. SQL_CREATE_SYNC_INFO_ENTRIES = syncInfoSQLBuilder.toString();
  102. // ProfileEntry
  103. StringBuilder profilSQLBuilder = new StringBuilder("CREATE TABLE ").append(ProfileEntry.TABLE_NAME).append("(");
  104. profilSQLBuilder.append(ProfileEntry.COLUMN_NAME_PROFILE_ID).append(" INTEGER PRIMARY KEY AUTOINCREMENT,");
  105. profilSQLBuilder.append(ProfileEntry.COLUMN_NAME_PROFILE_NAME).append(" TEXT,");
  106. profilSQLBuilder.append(ProfileEntry.COLUMN_NAME_PROFILE_DESCRIPTION ).append(" TEXT,");
  107. profilSQLBuilder.append(ProfileEntry.COLUMN_NAME_PROFILE_ICON).append(" TEXT,");
  108. profilSQLBuilder.append(ProfileEntry.COLUMN_NAME_PROFILE_ICON_NAME).append(" TEXT,");
  109. profilSQLBuilder.append(ProfileEntry.COLUMN_NAME_PROFILE_EDITABLE).append(" INTEGER,");
  110. profilSQLBuilder.append(ProfileEntry.COLUMN_NAME_PROFILE_ACTIVE).append(" INTEGER");
  111. profilSQLBuilder.append(")");
  112. SQL_CREATE_PROFILE_ENTRIES = profilSQLBuilder.toString();
  113. }
  114. private static final String SQL_CREATE_NETWORK_ENTRIES;
  115. private static final String SQL_CREATE_ATTACK_ENTRIES;
  116. private static final String SQL_CREATE_PACKET_ENTRIES;
  117. private static final String SQL_CREATE_PROFILE_ENTRIES;
  118. private static final String SQL_CREATE_SYNC_DEVICES_ENTRIES;
  119. private static final String SQL_CREATE_SYNC_INFO_ENTRIES;
  120. private static final String SQL_DELETE_PACKET_ENTRIES = "DROP TABLE IF EXISTS " + PacketEntry.TABLE_NAME;
  121. private static final String SQL_DELETE_ATTACK_ENTRIES = "DROP TABLE IF EXISTS " + AttackEntry.TABLE_NAME;
  122. private static final String SQL_DELETE_NETWORK_ENTRIES = "DROP TABLE IF EXISTS " + NetworkEntry.TABLE_NAME;
  123. private static final String SQL_DELETE_PROFILE_ENTRIES = "DROP TABLE IF EXISTS " + ProfileEntry.TABLE_NAME;
  124. private static final String SQL_DELETE_SYNC_DEVICES_ENTRIES = "DROP TABLE IF EXISTS " + SyncDeviceEntry.TABLE_NAME;
  125. private static final String SQL_DELETE_SYNC_INFO_ENTRIES = "DROP TABLE IF EXISTS " + SyncInfoEntry.TABLE_NAME;
  126. public HostageDBOpenHelper(Context context) {
  127. super(context, DATABASE_NAME, null, DATABASE_VERSION);
  128. this.context = context;
  129. }
  130. @Override
  131. public void onCreate(SQLiteDatabase db) {
  132. db.execSQL(SQL_CREATE_SYNC_DEVICES_ENTRIES);
  133. db.execSQL(SQL_CREATE_NETWORK_ENTRIES);
  134. db.execSQL(SQL_CREATE_ATTACK_ENTRIES);
  135. db.execSQL(SQL_CREATE_PACKET_ENTRIES);
  136. db.execSQL(SQL_CREATE_PROFILE_ENTRIES);
  137. db.execSQL(SQL_CREATE_SYNC_INFO_ENTRIES);
  138. }
  139. @Override
  140. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  141. db.execSQL(SQL_DELETE_SYNC_DEVICES_ENTRIES);
  142. db.execSQL(SQL_DELETE_SYNC_INFO_ENTRIES);
  143. db.execSQL(SQL_DELETE_PACKET_ENTRIES);
  144. db.execSQL(SQL_DELETE_ATTACK_ENTRIES);
  145. db.execSQL(SQL_DELETE_PROFILE_ENTRIES);
  146. db.execSQL(SQL_DELETE_NETWORK_ENTRIES);
  147. onCreate(db);
  148. }
  149. /**
  150. * Adds a given {@link MessageRecord} to the database.
  151. *
  152. * @param record
  153. * The added {@link MessageRecord} .
  154. */
  155. public void addMessageRecord(MessageRecord record) {
  156. SQLiteDatabase db = this.getWritableDatabase();
  157. this.insertMessageRecordWithOnConflict(record, db);
  158. db.close(); // Closing database connection
  159. }
  160. /**
  161. * Adds a given {@link de.tudarmstadt.informatik.hostage.logging.MessageRecord}s to the database.
  162. *
  163. * @param records {@link List}<MessageRecord>
  164. * The added {@link de.tudarmstadt.informatik.hostage.logging.MessageRecord}s .
  165. */
  166. public void insertMessageRecords(List<MessageRecord> records){
  167. SQLiteDatabase db = this.getWritableDatabase();
  168. db.beginTransaction();
  169. try {
  170. for (MessageRecord record : records){
  171. this.insertMessageRecordWithOnConflict(record,db);
  172. }
  173. db.setTransactionSuccessful();
  174. } finally {
  175. db.endTransaction();
  176. }
  177. db.close();
  178. }
  179. private void insertMessageRecordWithOnConflict(MessageRecord record, SQLiteDatabase db){
  180. ContentValues recordValues = new ContentValues();
  181. recordValues.put(PacketEntry.COLUMN_NAME_ID, record.getId()); // Log Message Number
  182. recordValues.put(PacketEntry.COLUMN_NAME_ATTACK_ID, record.getAttack_id()); // Log Attack ID
  183. recordValues.put(PacketEntry.COLUMN_NAME_TYPE, record.getType().name()); // Log Type
  184. recordValues.put(PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP, record.getTimestamp()); // Log Timestamp
  185. recordValues.put(PacketEntry.COLUMN_NAME_PACKET, record.getPacket()); // Log Packet
  186. // Inserting Rows
  187. db.insertWithOnConflict(PacketEntry.TABLE_NAME, null, recordValues, SQLiteDatabase.CONFLICT_REPLACE);
  188. }
  189. /**
  190. * Adds a given {@link AttackRecord} to the database.
  191. *
  192. * @param record
  193. * The added {@link AttackRecord} .
  194. */
  195. public void addAttackRecord(AttackRecord record) {
  196. //Log.i("DBHelper", "Add Attack Record with id: " + record.getAttack_id());
  197. SQLiteDatabase db = this.getWritableDatabase();
  198. this.insertAttackRecordWithOnConflict(record,db);
  199. db.close(); // Closing database connection
  200. ArrayList<SyncDevice> devices = new ArrayList<SyncDevice>();
  201. devices.add(SyncDevice.currentDevice());
  202. this.updateSyncDevices(devices);
  203. }
  204. /**
  205. * Adds a given {@link AttackRecord}s to the database.
  206. *
  207. * @param records {@link List}<AttackRecord>
  208. * The added {@link AttackRecord}s .
  209. */
  210. public void insertAttackRecords(List<AttackRecord> records) {
  211. //Log.i("DBHelper", "Add Attack Record with id: " + record.getAttack_id());
  212. SQLiteDatabase db = this.getWritableDatabase();
  213. db.beginTransaction();
  214. try {
  215. for (AttackRecord record : records){
  216. this.insertAttackRecordWithOnConflict(record,db);
  217. }
  218. db.setTransactionSuccessful();
  219. } finally {
  220. db.endTransaction();
  221. }
  222. db.close(); // Closing database connection
  223. ArrayList<SyncDevice> devices = new ArrayList<SyncDevice>();
  224. devices.add(SyncDevice.currentDevice());
  225. this.updateSyncDevices(devices);
  226. }
  227. private void insertAttackRecordWithOnConflict(AttackRecord record, SQLiteDatabase db){
  228. ContentValues attackValues = new ContentValues();
  229. attackValues.put(AttackEntry.COLUMN_NAME_ATTACK_ID, record.getAttack_id()); // Log Attack ID
  230. attackValues.put(AttackEntry.COLUMN_NAME_PROTOCOL, record.getProtocol().toString());
  231. attackValues.put(AttackEntry.COLUMN_NAME_EXTERNAL_IP, record.getExternalIP());
  232. attackValues.put(AttackEntry.COLUMN_NAME_LOCAL_IP, record.getLocalIP()); // Log Local IP
  233. attackValues.put(AttackEntry.COLUMN_NAME_LOCAL_PORT, record.getLocalPort());
  234. attackValues.put(AttackEntry.COLUMN_NAME_REMOTE_IP, record.getRemoteIP()); // Log Remote IP
  235. attackValues.put(AttackEntry.COLUMN_NAME_REMOTE_PORT, record.getRemotePort()); // Log Remote Port
  236. attackValues.put(AttackEntry.COLUMN_NAME_INTERNAL_ATTACK, record.getWasInternalAttack());
  237. attackValues.put(AttackEntry.COLUMN_NAME_BSSID, record.getBssid());
  238. attackValues.put(AttackEntry.COLUMN_NAME_DEVICE, record.getDevice());
  239. attackValues.put(AttackEntry.COLUMN_NAME_SYNC_ID, record.getSync_id());
  240. // Inserting Rows
  241. db.insertWithOnConflict(AttackEntry.TABLE_NAME, null, attackValues, SQLiteDatabase.CONFLICT_REPLACE);
  242. }
  243. /**
  244. * Adds a given {@link SyncRecord}s to the database.
  245. *
  246. * @param records {@link List}<AttackRecord>
  247. * The added {@link SyncRecord}s .
  248. */
  249. public void insertSyncRecords(List<SyncRecord> records) {
  250. //Log.i("DBHelper", "Add Attack Record with id: " + record.getAttack_id());
  251. SQLiteDatabase db = this.getWritableDatabase();
  252. db.beginTransaction();
  253. try {
  254. for (SyncRecord record : records){
  255. this.insertAttackRecordWithOnConflict(record.getAttackRecord(), db);
  256. this.insertMessageRecordWithOnConflict(record.getMessageRecord(), db);
  257. }
  258. db.setTransactionSuccessful();
  259. } finally {
  260. db.endTransaction();
  261. }
  262. this.updateSyncDevicesMaxID(db);
  263. db.close(); // Closing database connection
  264. }
  265. /**
  266. * Updates the sync devices max sync id.
  267. */
  268. public void updateSyncDevicesMaxID(SQLiteDatabase db){
  269. HashMap<String, Long> deviceIDmap = new HashMap<String, Long>();
  270. String selectQuery = "SELECT "+AttackEntry.COLUMN_NAME_DEVICE+ ","+ AttackEntry.COLUMN_NAME_SYNC_ID+" FROM " + AttackEntry.TABLE_NAME + " A " + " GROUP BY " + AttackEntry.COLUMN_NAME_DEVICE + " HAVING " + AttackEntry.COLUMN_NAME_SYNC_ID + " = MAX( " + AttackEntry.COLUMN_NAME_SYNC_ID + " )";
  271. {
  272. Cursor cursor = db.rawQuery(selectQuery, null);
  273. // looping through all rows and adding to list
  274. if (cursor.moveToFirst()) {
  275. do {
  276. String device_id = cursor.getString(0);
  277. long sync_id = cursor.getLong(1);
  278. deviceIDmap.put(device_id, sync_id);
  279. } while (cursor.moveToNext());
  280. }
  281. cursor.close();
  282. }
  283. {
  284. ArrayList<SyncDevice> allDevices = this.getSyncDevices(db);
  285. for (SyncDevice device : allDevices){
  286. long sync_id = deviceIDmap.get(device.getDeviceID());
  287. device.setHighest_attack_id(sync_id);
  288. }
  289. this.updateSyncDevices(allDevices, db);
  290. }
  291. }
  292. public void updateSyncAttackCounter(AttackRecord record){
  293. SQLiteDatabase db = this.getWritableDatabase();
  294. //String mac = HelperUtils.getMacAdress(context);
  295. SyncDevice currentDevice = SyncDevice.currentDevice();
  296. ContentValues syncDeviceValues = new ContentValues();
  297. syncDeviceValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_ID, currentDevice.getDeviceID());
  298. syncDeviceValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_TIMESTAMP, System.currentTimeMillis());
  299. syncDeviceValues.put(SyncDeviceEntry.COLUMN_NAME_HIGHEST_ATTACK_ID, record.getAttack_id());
  300. //String query = "SELECT * FROM " + SyncInfoEntry.TABLE_NAME +
  301. // " WHERE " + SyncInfoEntry.COLUMN_NAME_DEVICE_ID + " = ? " +
  302. // "AND " + SyncInfoEntry.COLUMN_NAME_BSSID + " = ?";
  303. //Cursor cursor = db.rawQuery(query, new String[] {mac, record.getBssid()});
  304. //long attackCount = 0;
  305. //long portscanCount = 0;
  306. //if (cursor.moveToFirst()){
  307. // attackCount = cursor.getLong(2);
  308. // portscanCount = cursor.getLong(3);
  309. //}
  310. //if("PORTSCAN".equals(record.getProtocol())){
  311. // portscanCount++;
  312. //}else { attackCount++; }
  313. //Log.i("DBHelper", "Update number of attack: " + attackCount);
  314. //ContentValues synInfoValues = new ContentValues();
  315. //synInfoValues.put(SyncInfoEntry.COLUMN_NAME_BSSID, record.getBssid());
  316. //synInfoValues.put(SyncInfoEntry.COLUMN_NAME_DEVICE_ID, mac);
  317. //synInfoValues.put(SyncInfoEntry.COLUMN_NAME_NUMBER_ATTACKS, attackCount);
  318. //synInfoValues.put(SyncInfoEntry.COLUMN_NAME_NUMBER_PORTSCANS, portscanCount);
  319. // Inserting Rows
  320. //db.insertWithOnConflict(SyncInfoEntry.TABLE_NAME, null, synInfoValues, SQLiteDatabase.CONFLICT_REPLACE);
  321. db.insertWithOnConflict(SyncDeviceEntry.TABLE_NAME, null, syncDeviceValues, SQLiteDatabase.CONFLICT_REPLACE);
  322. db.close(); // Closing database connection
  323. }
  324. /**
  325. * Determines if a network with given BSSID has already been recorded as malicious.
  326. *
  327. * @param BSSID
  328. * The BSSID of the network.
  329. * @return True if an attack has been recorded in a network with the given
  330. * BSSID, else false.
  331. */
  332. public synchronized boolean bssidSeen(String BSSID) {
  333. String countQuery = "SELECT * FROM " + NetworkEntry.TABLE_NAME + " WHERE " + NetworkEntry.COLUMN_NAME_BSSID + " = ?";
  334. SQLiteDatabase db = this.getReadableDatabase();
  335. Cursor cursor = db.rawQuery(countQuery, new String[] {BSSID});
  336. int result = cursor.getCount();
  337. cursor.close();
  338. db.close();
  339. return result > 0;
  340. }
  341. /**
  342. * Determines if an attack has been recorded on a specific protocol in a
  343. * network with a given BSSID.
  344. *
  345. * @param protocol
  346. * The
  347. * {@link de.tudarmstadt.informatik.hostage.protocol.Protocol
  348. * Protocol} to inspect.
  349. * @param BSSID
  350. * The BSSID of the network.
  351. * @return True if an attack on the given protocol has been recorded in a
  352. * network with the given BSSID, else false.
  353. */
  354. public synchronized boolean bssidSeen(String protocol, String BSSID) {
  355. if(BSSID == null || protocol == null){
  356. return false;
  357. }
  358. String countQuery = "SELECT * FROM " + AttackEntry.TABLE_NAME + " NATURAL JOIN " + NetworkEntry.TABLE_NAME + " WHERE "
  359. + AttackEntry.COLUMN_NAME_PROTOCOL + " = ? AND " + NetworkEntry.COLUMN_NAME_BSSID + " = ?";
  360. SQLiteDatabase db = this.getReadableDatabase();
  361. Cursor cursor = db.rawQuery(countQuery, new String[]{protocol, BSSID});
  362. int result = cursor.getCount();
  363. cursor.close();
  364. db.close();
  365. return result > 0;
  366. }
  367. public synchronized int numBssidSeen(String BSSID) {
  368. String countQuery = "SELECT COUNT(*) FROM " + AttackEntry.TABLE_NAME + " WHERE "
  369. + AttackEntry.TABLE_NAME + "." + AttackEntry.COLUMN_NAME_BSSID + " = " + "'" + BSSID + "'";
  370. SQLiteDatabase db = this.getReadableDatabase();
  371. Cursor cursor = db.rawQuery(countQuery, null);
  372. cursor.moveToFirst();
  373. int result = cursor.getInt(0);
  374. cursor.close();
  375. db.close();
  376. return result;
  377. }
  378. public int numBssidSeen(String protocol, String BSSID) {
  379. String countQuery = "SELECT COUNT(*) FROM " + AttackEntry.TABLE_NAME
  380. + " WHERE " + AttackEntry.TABLE_NAME + "." + AttackEntry.COLUMN_NAME_PROTOCOL + " = " + "'" + protocol + "'"
  381. + " AND " + AttackEntry.TABLE_NAME + "." + AttackEntry.COLUMN_NAME_BSSID + " = " + "'" + BSSID + "'";
  382. SQLiteDatabase db = this.getReadableDatabase();
  383. Cursor cursor = db.rawQuery(countQuery, null);
  384. cursor.moveToFirst();
  385. int result = cursor.getInt(0);
  386. cursor.close();
  387. db.close();
  388. return result;
  389. }
  390. /**
  391. * Returns a String array with all BSSIDs stored in the database.
  392. *
  393. * @return ArrayList<String> of all recorded BSSIDs.
  394. */
  395. public synchronized ArrayList<String> getAllBSSIDS() {
  396. String selectQuery = "SELECT "+NetworkEntry.COLUMN_NAME_BSSID+" FROM " + NetworkEntry.TABLE_NAME;
  397. SQLiteDatabase db = this.getReadableDatabase();
  398. Cursor cursor = db.rawQuery(selectQuery, null);
  399. ArrayList<String> bssidList = new ArrayList<String>();
  400. // looping through all rows and adding to list
  401. if (cursor.moveToFirst()) {
  402. do {
  403. String s = cursor.getString(0);
  404. bssidList.add(s);
  405. } while (cursor.moveToNext());
  406. }
  407. cursor.close();
  408. db.close();
  409. return bssidList;
  410. }
  411. /**
  412. * Returns all missing network records.
  413. *
  414. * @return a list of missing network records.
  415. */
  416. public synchronized ArrayList<NetworkRecord> getMissingNetworkRecords(ArrayList<String> otherBSSIDs) {
  417. String prefix = " WHERE " + "N."+NetworkEntry.COLUMN_NAME_BSSID + " NOT IN ";
  418. String selectQuery = "SELECT * FROM " + NetworkEntry.TABLE_NAME + " N " + this.arrayToSQLString(otherBSSIDs, prefix);
  419. SQLiteDatabase db = this.getReadableDatabase();
  420. Cursor cursor = db.rawQuery(selectQuery, null);
  421. ArrayList<NetworkRecord> networkInformation = new ArrayList<NetworkRecord>();
  422. // looping through all rows and adding to list
  423. if (cursor.moveToFirst()) {
  424. do {
  425. NetworkRecord record = this.createNetworkRecord(cursor);
  426. networkInformation.add(record);
  427. } while (cursor.moveToNext());
  428. }
  429. cursor.close();
  430. db.close();
  431. return networkInformation;
  432. }
  433. private String arrayToSQLString(ArrayList<String> a, String prefix)
  434. {
  435. String sql = "";
  436. if (a.size() !=0){
  437. sql = sql + prefix;
  438. sql = sql + " ( ";
  439. int i = 0;
  440. for (String s : a){
  441. i++;
  442. sql = sql + "'" +s + "'";
  443. if (i != a.size()){
  444. sql = sql + ",";
  445. }
  446. }
  447. sql = sql + " ) ";
  448. }
  449. return sql;
  450. }
  451. /**
  452. * Determines the number of different attacks in the database.
  453. *
  454. * @return The number of different attacks in the database.
  455. */
  456. public synchronized int getAttackCount() {
  457. SQLiteDatabase db = this.getReadableDatabase();
  458. String countQuery = "SELECT * FROM " + AttackEntry.TABLE_NAME +
  459. " WHERE " + AttackEntry.COLUMN_NAME_PROTOCOL + " <> ?";
  460. Cursor cursor = db.rawQuery(countQuery, new String[]{"PORTSCAN"});
  461. int result = cursor.getCount();
  462. cursor.close();
  463. // return count
  464. db.close();
  465. return result;
  466. }
  467. /**
  468. * Determines the number of different recorded attacks in a specific access point since the given attack_id.
  469. * The given attack_id is not included.
  470. * @param attack_id The attack id to match the query against.
  471. * @param bssid The BSSID of the access point.
  472. * @return The number of different attacks in the database since the given attack_id.
  473. */
  474. public synchronized int getAttackCount(int attack_id, String bssid) {
  475. SQLiteDatabase db = this.getReadableDatabase();
  476. String countQuery = "SELECT * FROM " + AttackEntry.TABLE_NAME +
  477. " WHERE "+ AttackEntry.COLUMN_NAME_PROTOCOL + " <> ? " +
  478. "AND " + AttackEntry.COLUMN_NAME_ATTACK_ID + " > ? " +
  479. "AND " + AttackEntry.COLUMN_NAME_BSSID + " = ?";
  480. String[] selectArgs = new String[]{"PORTSCAN", attack_id + "", bssid};
  481. Cursor cursor = db.rawQuery(countQuery, selectArgs);
  482. int result = cursor.getCount();
  483. cursor.close();
  484. // return count
  485. db.close();
  486. return result;
  487. }
  488. /**
  489. * Determines the number of different attacks for a specific protocol in
  490. * the database.
  491. *
  492. * @param protocol
  493. * The String representation of the
  494. * {@link de.tudarmstadt.informatik.hostage.protocol.Protocol
  495. * Protocol}
  496. * @return The number of different attacks in the database.
  497. */
  498. public synchronized int getAttackPerProtocolCount(String protocol) {
  499. SQLiteDatabase db = this.getReadableDatabase();
  500. String countQuery = "SELECT * FROM " + AttackEntry.TABLE_NAME +
  501. " WHERE "+ AttackEntry.COLUMN_NAME_PROTOCOL + " = ? ";
  502. Cursor cursor = db.rawQuery(countQuery, new String[]{protocol});
  503. int result = cursor.getCount();
  504. cursor.close();
  505. // return count
  506. db.close();
  507. return result;
  508. }
  509. /**
  510. * Determines the number of attacks for a specific protocol in
  511. * the database since the given attack_id.
  512. *
  513. * @param protocol
  514. * The String representation of the
  515. * {@link de.tudarmstadt.informatik.hostage.protocol.Protocol
  516. * Protocol}
  517. * @param attack_id The attack id to match the query against.
  518. * @return The number of different attacks in the database since the given attack_id.
  519. */
  520. public synchronized int getAttackPerProtocolCount(String protocol, int attack_id) {
  521. SQLiteDatabase db = this.getReadableDatabase();
  522. String countQuery = "SELECT * FROM " + AttackEntry.TABLE_NAME +
  523. " WHERE "+ AttackEntry.COLUMN_NAME_PROTOCOL + " = ? " +
  524. "AND " + AttackEntry.COLUMN_NAME_ATTACK_ID + " > ? ";
  525. Cursor cursor = db.rawQuery(countQuery, new String[]{protocol, attack_id + ""});
  526. int result = cursor.getCount();
  527. cursor.close();
  528. // return count
  529. db.close();
  530. return result;
  531. }
  532. /**
  533. * Determines the number of recorded attacks for a specific protocol and accesss point since the given attack_id.
  534. *
  535. * @param protocol
  536. * The String representation of the
  537. * {@link de.tudarmstadt.informatik.hostage.protocol.Protocol
  538. * Protocol}
  539. * @param attack_id The attack id to match the query against.
  540. * @param bssid The BSSID of the access point.
  541. * @return The number of different attacks in the database since the given attack_id.
  542. */
  543. public synchronized int getAttackPerProtocolCount(String protocol, int attack_id, String bssid) {
  544. SQLiteDatabase db = this.getReadableDatabase();
  545. String countQuery = "SELECT * FROM " + AttackEntry.TABLE_NAME +
  546. " WHERE "+ AttackEntry.COLUMN_NAME_PROTOCOL + " = ? " +
  547. "AND " + AttackEntry.COLUMN_NAME_ATTACK_ID + " > ? " +
  548. "AND " + AttackEntry.COLUMN_NAME_BSSID + " = ?";
  549. Cursor cursor = db.rawQuery(countQuery, new String[]{protocol, attack_id + "", bssid});
  550. int result = cursor.getCount();
  551. cursor.close();
  552. // return count
  553. db.close();
  554. return result;
  555. }
  556. /**
  557. * Determines the number of portscans stored in the database.
  558. *
  559. * @return The number of portscans stored in the database.
  560. */
  561. public synchronized int getPortscanCount() {
  562. return getAttackPerProtocolCount("PORTSCAN");
  563. }
  564. /**
  565. * Determines the number of recorded portscans since the given attack_id.
  566. * @param attack_id The attack id to match the query against.
  567. * @return The number of portscans stored in the database since the given attack_id.
  568. */
  569. public synchronized int getPortscanCount(int attack_id) {
  570. return getAttackPerProtocolCount("PORTSCAN", attack_id);
  571. }
  572. /**
  573. * Determines the number of recorded portscans in a specific access point since the given attack_id.
  574. * @param attack_id The attack id to match the query against.
  575. * @param bssid The BSSID of the access point.
  576. * @return The number of portscans stored in the database since the given attack_id.
  577. */
  578. public synchronized int getPortscanCount(int attack_id, String bssid) {
  579. return getAttackPerProtocolCount("PORTSCAN", attack_id, bssid);
  580. }
  581. /**
  582. * Determines the number of {@link Record Records} in the database.
  583. *
  584. * @return The number of {@link Record Records} in the database.
  585. */
  586. public synchronized int getRecordCount() {
  587. String countQuery = "SELECT * FROM " + PacketEntry.TABLE_NAME;
  588. SQLiteDatabase db = this.getReadableDatabase();
  589. Cursor cursor = db.rawQuery(countQuery, null);
  590. int result = cursor.getCount();
  591. cursor.close();
  592. // return count
  593. db.close();
  594. return result;
  595. }
  596. //TODO ADD AGAIN ?
  597. /**
  598. * Returns the {@link AttackRecord} with the given attack id from the database.
  599. *
  600. * @param attack_id
  601. * The attack id of the {@link Record};
  602. * @return The {@link Record}.
  603. */
  604. /*
  605. public AttackRecord getRecordOfAttackId(long attack_id) {
  606. String selectQuery = "SELECT * FROM " + AttackEntry.TABLE_NAME + " WHERE " + AttackEntry.COLUMN_NAME_ATTACK_ID + " = " + attack_id;
  607. SQLiteDatabase db = this.getReadableDatabase();
  608. Cursor cursor = db.rawQuery(selectQuery, null);
  609. AttackRecord record = null;
  610. if (cursor.moveToFirst()) {
  611. record = createAttackRecord(cursor);
  612. }
  613. cursor.close();
  614. // return record list
  615. db.close();
  616. return record;
  617. } */
  618. /**
  619. * Gets a {@link AttackRecord} for every attack identified by its attack id.
  620. *
  621. * @return A ArrayList with a {@link AttackRecord} for each attack id in the Database.
  622. */
  623. public synchronized ArrayList<AttackRecord> getRecordOfEachAttack() {
  624. ArrayList<AttackRecord> recordList = new ArrayList<AttackRecord>();
  625. String selectQuery = "SELECT * FROM " + AttackEntry.TABLE_NAME;
  626. SQLiteDatabase db = this.getReadableDatabase();
  627. Cursor cursor = db.rawQuery(selectQuery, null);
  628. // looping through all rows and adding to list
  629. if (cursor.moveToFirst()) {
  630. do {
  631. AttackRecord record = createAttackRecord(cursor);
  632. // Adding record to list
  633. recordList.add(record);
  634. } while (cursor.moveToNext());
  635. }
  636. cursor.close();
  637. // return record list
  638. db.close();
  639. return recordList;
  640. }
  641. /**
  642. * Gets a AttackRecord for every attack with a higher attack id than the specified.
  643. *
  644. * @param attack_id
  645. * The attack id to match the query against.
  646. * @return A ArrayList with one {@link AttackRecord} for each attack id
  647. * higher than the given.
  648. */
  649. public synchronized ArrayList<AttackRecord> getRecordOfEachAttack(long attack_id) {
  650. ArrayList<AttackRecord> recordList = new ArrayList<AttackRecord>();
  651. String selectQuery = "SELECT * FROM " + AttackEntry.TABLE_NAME + " WHERE " + AttackEntry.COLUMN_NAME_ATTACK_ID + " > " + attack_id;
  652. SQLiteDatabase db = this.getReadableDatabase();
  653. Cursor cursor = db.rawQuery(selectQuery, null);
  654. // looping through all rows and adding to list
  655. if (cursor.moveToFirst()) {
  656. do {
  657. AttackRecord record = createAttackRecord(cursor);
  658. // Adding record to list
  659. recordList.add(record);
  660. } while (cursor.moveToNext());
  661. }
  662. cursor.close();
  663. // return count
  664. db.close();
  665. return recordList;
  666. }
  667. /**
  668. * Determines the highest attack id stored in the database.
  669. *
  670. * @return The highest attack id stored in the database.
  671. */
  672. public synchronized long getHighestAttackId() {
  673. String selectQuery = "SELECT MAX(" + AttackEntry.COLUMN_NAME_ATTACK_ID + ") FROM " + AttackEntry.TABLE_NAME;
  674. SQLiteDatabase db = this.getReadableDatabase();
  675. Cursor cursor = db.rawQuery(selectQuery, null);
  676. int result;
  677. if (cursor.moveToFirst()) {
  678. result = cursor.getInt(0);
  679. } else {
  680. result = -1;
  681. }
  682. cursor.close();
  683. db.close();
  684. return result;
  685. }
  686. /**
  687. * Determines the smallest attack id stored in the database.
  688. *
  689. * @return The smallest attack id stored in the database.
  690. */
  691. public synchronized long getSmallestAttackId() {
  692. String selectQuery = "SELECT MIN(" + AttackEntry.COLUMN_NAME_ATTACK_ID + ") FROM " + AttackEntry.TABLE_NAME;
  693. SQLiteDatabase db = this.getReadableDatabase();
  694. Cursor cursor = db.rawQuery(selectQuery, null);
  695. int result;
  696. if (cursor.moveToFirst()) {
  697. result = cursor.getInt(0);
  698. } else {
  699. result = -1;
  700. }
  701. cursor.close();
  702. db.close();
  703. return result;
  704. }
  705. /**
  706. * Gets the last recorded SSID to a given BSSID.
  707. *
  708. * @param bssid
  709. * The BSSID to match against.
  710. * @return A String of the last SSID or null if the BSSID is not in the
  711. * database.
  712. */
  713. public synchronized String getSSID(String bssid) {
  714. String selectQuery = "SELECT " + NetworkEntry.COLUMN_NAME_SSID + " FROM " + NetworkEntry.TABLE_NAME + " WHERE " + NetworkEntry.COLUMN_NAME_BSSID
  715. + " = " + "'" + bssid + "'";
  716. SQLiteDatabase db = this.getReadableDatabase();
  717. Cursor cursor = db.rawQuery(selectQuery, null);
  718. String ssid = null;
  719. if (cursor.moveToFirst()) {
  720. ssid = cursor.getString(0);
  721. }
  722. cursor.close();
  723. db.close();
  724. return ssid;
  725. }
  726. /**
  727. * Gets all network related data stored in the database
  728. * @return An ArrayList with an Network for all Entry in the network table.
  729. */
  730. public synchronized ArrayList<NetworkRecord> getNetworkInformation() {
  731. String selectQuery = "SELECT * FROM " + NetworkEntry.TABLE_NAME;
  732. SQLiteDatabase db = this.getReadableDatabase();
  733. Cursor cursor = db.rawQuery(selectQuery, null);
  734. ArrayList<NetworkRecord> networkInformation = new ArrayList<NetworkRecord>();
  735. // looping through all rows and adding to list
  736. if (cursor.moveToFirst()) {
  737. do {
  738. NetworkRecord record = this.createNetworkRecord(cursor);
  739. networkInformation.add(record);
  740. } while (cursor.moveToNext());
  741. }
  742. cursor.close();
  743. db.close();
  744. return networkInformation;
  745. }
  746. private synchronized NetworkRecord createNetworkRecord(Cursor cursor){
  747. NetworkRecord record = new NetworkRecord();
  748. record.setBssid(cursor.getString(0));
  749. record.setSsid(cursor.getString(1));
  750. record.setLatitude(Double.parseDouble(cursor.getString(2)));
  751. record.setLongitude(Double.parseDouble(cursor.getString(3)));
  752. record.setAccuracy(Float.parseFloat(cursor.getString(4)));
  753. record.setTimestampLocation(cursor.getLong(5));
  754. return record;
  755. }
  756. /**
  757. * Updates the network table with the information contained in the parameter.
  758. * @param networkInformation ArrayList of {@link NetworkRecord NetworkRecords}
  759. * @see {@link HostageDBOpenHelper#updateNetworkInformation(NetworkRecord record)}
  760. */
  761. public synchronized void updateNetworkInformation(ArrayList<NetworkRecord> networkInformation) {
  762. SQLiteDatabase db = this.getWritableDatabase();
  763. db.beginTransaction();
  764. try {
  765. for (NetworkRecord record : networkInformation) {
  766. String bssid = record.getBssid();
  767. String bssidQuery = "SELECT * FROM " + NetworkEntry.TABLE_NAME + " WHERE " + NetworkEntry.COLUMN_NAME_BSSID + " = ?";
  768. Cursor cursor = db.rawQuery(bssidQuery, new String[] {bssid});
  769. if (!cursor.moveToFirst() || cursor.getLong(5) < record.getTimestampLocation()){
  770. ContentValues bssidValues = new ContentValues();
  771. bssidValues.put(NetworkEntry.COLUMN_NAME_BSSID, bssid);
  772. bssidValues.put(NetworkEntry.COLUMN_NAME_SSID, record.getSsid());
  773. bssidValues.put(NetworkEntry.COLUMN_NAME_LATITUDE, record.getLatitude());
  774. bssidValues.put(NetworkEntry.COLUMN_NAME_LONGITUDE, record.getLongitude());
  775. bssidValues.put(NetworkEntry.COLUMN_NAME_ACCURACY, record.getAccuracy());
  776. bssidValues.put(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP, record.getTimestampLocation());
  777. db.insertWithOnConflict(NetworkEntry.TABLE_NAME, null, bssidValues, SQLiteDatabase.CONFLICT_REPLACE);
  778. }
  779. cursor.close();
  780. }
  781. db.setTransactionSuccessful();
  782. } finally {
  783. db.endTransaction();
  784. }
  785. db.close();
  786. }
  787. /**
  788. * Updated the network table with a new {@link NetworkRecord}.
  789. * If information about this BSSID are already in the database,
  790. * the table will only be updated if the new {@link NetworkRecord }
  791. * has a newer location time stamp.
  792. * @param record The new {@link NetworkRecord}.
  793. */
  794. public synchronized void updateNetworkInformation(NetworkRecord record) {
  795. SQLiteDatabase db = this.getWritableDatabase();
  796. String bssid = record.getBssid();
  797. String bssidQuery = "SELECT * FROM " + NetworkEntry.TABLE_NAME + " WHERE " + NetworkEntry.COLUMN_NAME_BSSID + " = ?";
  798. Cursor cursor = db.rawQuery(bssidQuery, new String[] {bssid});
  799. if (!cursor.moveToFirst() || cursor.getLong(5) < record.getTimestampLocation()){
  800. ContentValues bssidValues = new ContentValues();
  801. bssidValues.put(NetworkEntry.COLUMN_NAME_BSSID, bssid);
  802. bssidValues.put(NetworkEntry.COLUMN_NAME_SSID, record.getSsid());
  803. bssidValues.put(NetworkEntry.COLUMN_NAME_LATITUDE, record.getLatitude());
  804. bssidValues.put(NetworkEntry.COLUMN_NAME_LONGITUDE, record.getLongitude());
  805. bssidValues.put(NetworkEntry.COLUMN_NAME_ACCURACY, record.getAccuracy());
  806. bssidValues.put(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP, record.getTimestampLocation());
  807. db.insertWithOnConflict(NetworkEntry.TABLE_NAME, null, bssidValues, SQLiteDatabase.CONFLICT_REPLACE);
  808. }
  809. cursor.close();
  810. db.close();
  811. }
  812. /**
  813. * Updates the the timestamp of a single device id
  814. * @param deviceID The Device id
  815. * @param timestamp The synchronization timestamp
  816. */
  817. public synchronized void updateTimestampOfSyncDevice(String deviceID, long timestamp){
  818. SQLiteDatabase db = this.getWritableDatabase();
  819. ContentValues deviceValues = new ContentValues();
  820. deviceValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_ID, deviceID);
  821. deviceValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_TIMESTAMP, timestamp);
  822. db.insertWithOnConflict(SyncDeviceEntry.TABLE_NAME, null, deviceValues, SQLiteDatabase.CONFLICT_REPLACE);
  823. db.close();
  824. }
  825. /**
  826. * Updates the Timestamps of synchronization devices from a HashMap.
  827. * @param devices HashMap of device ids and their synchronization timestamps.
  828. */
  829. public synchronized void updateSyncDevices(HashMap<String, Long> devices){
  830. SQLiteDatabase db = this.getWritableDatabase();
  831. db.beginTransaction();
  832. try {
  833. for(String key : devices.keySet()){
  834. ContentValues deviceValues = new ContentValues();
  835. deviceValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_ID, key);
  836. deviceValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_TIMESTAMP, devices.get(key));
  837. db.insertWithOnConflict(SyncDeviceEntry.TABLE_NAME, null, deviceValues, SQLiteDatabase.CONFLICT_REPLACE);
  838. }
  839. db.setTransactionSuccessful();
  840. } finally {
  841. db.endTransaction();
  842. }
  843. db.close();
  844. }
  845. public synchronized void updateSyncDevices(ArrayList<SyncDevice> devices){
  846. SQLiteDatabase db = this.getWritableDatabase();
  847. this.updateSyncDevices(devices, db);
  848. db.close();
  849. }
  850. public synchronized void updateSyncDevices(ArrayList<SyncDevice> devices, SQLiteDatabase db){
  851. db.beginTransaction();
  852. try {
  853. for(SyncDevice device : devices){
  854. ContentValues deviceValues = new ContentValues();
  855. deviceValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_ID, device.getDeviceID());
  856. deviceValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_TIMESTAMP, device.getLast_sync_timestamp());
  857. deviceValues.put(SyncDeviceEntry.COLUMN_NAME_HIGHEST_ATTACK_ID, device.getHighest_attack_id());
  858. db.insertWithOnConflict(SyncDeviceEntry.TABLE_NAME, null, deviceValues, SQLiteDatabase.CONFLICT_REPLACE);
  859. }
  860. db.setTransactionSuccessful();
  861. } finally {
  862. db.endTransaction();
  863. }
  864. }
  865. /**
  866. * Returns the own state containing all registered devices ids and their max sync_id
  867. * @return {@link de.tudarmstadt.informatik.hostage.logging.SyncInfo}
  868. */
  869. public synchronized SyncInfo getOwnState(){
  870. ArrayList<SyncDevice> devices = this.getSyncDevices();
  871. HashMap<String, Long> deviceMap = new HashMap<String, Long>();
  872. for (SyncDevice device : devices){
  873. deviceMap.put(device.getDeviceID(), device.getHighest_attack_id());
  874. }
  875. SyncInfo syncInfo = new SyncInfo();
  876. syncInfo.deviceMap = deviceMap;
  877. syncInfo.bssids = this.getAllBSSIDS();
  878. return syncInfo;
  879. }
  880. /**
  881. * Returns a HashMap of all devices that were previously synchronized with.
  882. * @return HashMap containing device id's and the last synchronization timestamp.
  883. */
  884. public synchronized HashMap<String, Long> getSyncDeviceHashMap(){
  885. SQLiteDatabase db = this.getReadableDatabase();
  886. HashMap<String, Long> devices = new HashMap<String, Long>();
  887. String query = "SELECT * FROM " + SyncDeviceEntry.TABLE_NAME;
  888. Cursor cursor = db.rawQuery(query, null);
  889. if (cursor.moveToFirst()) {
  890. do {
  891. devices.put(cursor.getString(0), cursor.getLong(1));
  892. } while (cursor.moveToNext());
  893. }
  894. cursor.close();
  895. db.close();
  896. return devices;
  897. }
  898. /**
  899. * Returns a HashMap of all devices that were previously synchronized with.
  900. * @return HashMap containing device id's and the last synchronization timestamp.
  901. */
  902. public synchronized ArrayList<SyncDevice> getSyncDevices(){
  903. SQLiteDatabase db = this.getReadableDatabase();
  904. ArrayList<SyncDevice> devices = this.getSyncDevices(db);
  905. db.close();
  906. return devices;
  907. }
  908. public synchronized ArrayList<SyncDevice> getSyncDevices(SQLiteDatabase db){
  909. ArrayList<SyncDevice> devices = new ArrayList<SyncDevice>();
  910. String query = "SELECT * FROM " + SyncDeviceEntry.TABLE_NAME;
  911. Cursor cursor = db.rawQuery(query, null);
  912. if (cursor.moveToFirst()) {
  913. do {
  914. SyncDevice device = this.createSyncDevice(cursor);
  915. devices.add(device);
  916. } while (cursor.moveToNext());
  917. }
  918. cursor.close();
  919. return devices;
  920. }
  921. /**
  922. * Returns a ArrayList containing all information stored in the SyncInfo table.
  923. * @return ArrayList<SyncInfo>
  924. */
  925. public synchronized ArrayList<SyncInfoRecord> getSyncInfo(){
  926. SQLiteDatabase db = this.getReadableDatabase();
  927. ArrayList<SyncInfoRecord> syncInfo = new ArrayList<SyncInfoRecord>();
  928. String query = "SELECT * FROM " + SyncInfoEntry.TABLE_NAME;
  929. Cursor cursor = db.rawQuery(query, null);
  930. if (cursor.moveToFirst()) {
  931. do {
  932. SyncInfoRecord info = new SyncInfoRecord();
  933. info.setDeviceID(cursor.getString(0));
  934. info.setBSSID(cursor.getString(1));
  935. info.setNumber_of_attacks(cursor.getLong(2));
  936. info.setNumber_of_portscans(cursor.getLong(3));
  937. syncInfo.add(info);
  938. } while (cursor.moveToNext());
  939. }
  940. cursor.close();
  941. db.close();
  942. return syncInfo;
  943. }
  944. /**
  945. * Updates the sync_info table with the information contained in the parameter.
  946. * @param syncInfos ArrayList of {@link SyncInfoRecord SyncInfoRecords}
  947. * @see {@link HostageDBOpenHelper#updateSyncInfo(SyncInfoRecord syncInfo)}
  948. */
  949. public synchronized void updateSyncInfo(ArrayList<SyncInfoRecord> syncInfos){
  950. SQLiteDatabase db = this.getWritableDatabase();
  951. db.beginTransaction();
  952. try {
  953. for(SyncInfoRecord syncInfo : syncInfos){
  954. ContentValues syncValues = new ContentValues();
  955. syncValues.put(SyncInfoEntry.COLUMN_NAME_BSSID, syncInfo.getBSSID());
  956. syncValues.put(SyncInfoEntry.COLUMN_NAME_DEVICE_ID, syncInfo.getDeviceID());
  957. syncValues.put(SyncInfoEntry.COLUMN_NAME_NUMBER_ATTACKS, syncInfo.getNumber_of_attacks());
  958. syncValues.put(SyncInfoEntry.COLUMN_NAME_NUMBER_PORTSCANS, syncInfo.getNumber_of_portscans());
  959. db.insertWithOnConflict(SyncInfoEntry.TABLE_NAME, null, syncValues, SQLiteDatabase.CONFLICT_REPLACE);
  960. }
  961. db.setTransactionSuccessful();
  962. } finally {
  963. db.endTransaction();
  964. }
  965. db.close();
  966. }
  967. /**
  968. * Updated the network table with a new {@link SyncInfoRecord}.
  969. * Conflicting rows will be replaced.
  970. * @param syncInfo The new {@link NetworkRecord}.
  971. */
  972. public synchronized void updateSyncInfo(SyncInfoRecord syncInfo){
  973. SQLiteDatabase db = this.getWritableDatabase();
  974. ContentValues syncValues = new ContentValues();
  975. syncValues.put(SyncInfoEntry.COLUMN_NAME_BSSID, syncInfo.getBSSID());
  976. syncValues.put(SyncInfoEntry.COLUMN_NAME_DEVICE_ID, syncInfo.getDeviceID());
  977. syncValues.put(SyncInfoEntry.COLUMN_NAME_NUMBER_ATTACKS, syncInfo.getNumber_of_attacks());
  978. syncValues.put(SyncInfoEntry.COLUMN_NAME_NUMBER_PORTSCANS, syncInfo.getNumber_of_portscans());
  979. db.insertWithOnConflict(SyncInfoEntry.TABLE_NAME, null, syncValues, SQLiteDatabase.CONFLICT_REPLACE);
  980. db.close();
  981. }
  982. /**
  983. * Deletes a device with given id from the device {@link de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.SyncDeviceEntry} and also all data captured by this device in {@link SyncInfoEntry}
  984. */
  985. public synchronized void clearSyncInfos(){
  986. SQLiteDatabase db = this.getWritableDatabase();
  987. db.delete(SyncDeviceEntry.TABLE_NAME, null, null);
  988. db.delete(SyncInfoEntry.TABLE_NAME, null, null);
  989. db.close();
  990. }
  991. /**
  992. * Deletes all records from {@link PacketEntry}s and {@link de.tudarmstadt.informatik.hostage.logging.AttackRecord}.
  993. */
  994. public synchronized void clearData() {
  995. SQLiteDatabase db = this.getWritableDatabase();
  996. db.delete(PacketEntry.TABLE_NAME, null, null);
  997. db.delete(AttackEntry.TABLE_NAME, null, null);
  998. db.close();
  999. }
  1000. /**
  1001. * Deletes all records from {@link PacketEntry}s with a specific BSSID.
  1002. *
  1003. * @param bssid
  1004. * The BSSID to match against.
  1005. */
  1006. public synchronized void deleteByBSSID(String bssid) {
  1007. SQLiteDatabase db = this.getWritableDatabase();
  1008. db.delete(NetworkEntry.TABLE_NAME, NetworkEntry.COLUMN_NAME_BSSID + " = ?", new String[] { bssid });
  1009. db.delete(AttackEntry.TABLE_NAME, AttackEntry.COLUMN_NAME_BSSID + " = ?", new String[] { bssid });
  1010. db.close();
  1011. }
  1012. /**
  1013. * Deletes all records from {@link de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.PacketEntry}s with a time stamp smaller
  1014. * then the given
  1015. *
  1016. * @param date
  1017. * A Date represented in milliseconds.
  1018. */
  1019. public synchronized void deleteByDate(long date) {
  1020. SQLiteDatabase db = this.getWritableDatabase();
  1021. String deleteQuery = "DELETE FROM " + PacketEntry.TABLE_NAME + " WHERE " + PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP + " < " + date;
  1022. db.execSQL(deleteQuery);
  1023. db.close();
  1024. }
  1025. /**
  1026. * Deletes all {@link de.tudarmstadt.informatik.hostage.logging.AttackRecord} with a specific Attack ID.
  1027. *
  1028. * @param attackID
  1029. * The Attack ID to match against.
  1030. */
  1031. public synchronized void deleteByAttackID(long attackID) {
  1032. SQLiteDatabase db = this.getWritableDatabase();
  1033. db.delete(AttackEntry.TABLE_NAME, AttackEntry.COLUMN_NAME_ATTACK_ID + " = ?", new String[] { String.valueOf(attackID) });
  1034. db.delete(PacketEntry.TABLE_NAME, PacketEntry.COLUMN_NAME_ATTACK_ID + " = ?", new String[] { String.valueOf(attackID) });
  1035. db.close();
  1036. }
  1037. /**
  1038. * Creates a {@link MessageRecord} from a Cursor. If the cursor does not show to a
  1039. * valid data structure a runtime exception is thrown.
  1040. *
  1041. * @param cursor
  1042. * @return Returns the created {@link MessageRecord} .
  1043. */
  1044. private synchronized MessageRecord createMessageRecord(Cursor cursor) {
  1045. MessageRecord record = new MessageRecord();
  1046. record.setId(Integer.parseInt(cursor.getString(0)));
  1047. record.setAttack_id(cursor.getLong(1));
  1048. record.setType(MessageRecord.TYPE.valueOf(cursor.getString(2)));
  1049. record.setTimestamp(cursor.getLong(3));
  1050. record.setPacket(cursor.getString(4));
  1051. return record;
  1052. }
  1053. /**
  1054. * Creates a {@link AttackRecord} from a Cursor. If the cursor does not show to a
  1055. * valid data structure a runtime exception is thrown.
  1056. *
  1057. * @param cursor
  1058. * @return Returns the created {@link AttackRecord} .
  1059. */
  1060. private synchronized AttackRecord createAttackRecord(Cursor cursor) {
  1061. AttackRecord record = new AttackRecord();
  1062. record.setAttack_id(cursor.getLong(0));
  1063. record.setProtocol(cursor.getString(1));
  1064. record.setExternalIP(cursor.getString(2));
  1065. record.setLocalIP(cursor.getString(3));
  1066. record.setLocalPort(Integer.parseInt(cursor.getString(4)));
  1067. record.setRemoteIP(cursor.getString(5));
  1068. record.setRemotePort(Integer.parseInt(cursor.getString(6)));
  1069. record.setWasInternalAttack(cursor.getInt(7) == 1);
  1070. record.setBssid(cursor.getString(8));
  1071. record.setSync_id(cursor.getLong(9));
  1072. record.setDevice(cursor.getString(10));
  1073. return record;
  1074. }
  1075. /**
  1076. * Creates a {@link SyncRecord} from a Cursor. If the cursor does not show to a
  1077. * valid data structure a runtime exception is thrown.
  1078. *
  1079. * @param cursor
  1080. * @return Returns the created {@link SyncRecord} .
  1081. */
  1082. private synchronized SyncRecord createSyncRecord(Cursor cursor){
  1083. SyncRecord record = new SyncRecord();
  1084. record.setAttack_id(cursor.getLong(0));
  1085. record.setProtocol(cursor.getString(1));
  1086. record.setExternalIP(cursor.getString(2));
  1087. record.setLocalIP(cursor.getString(3));
  1088. record.setLocalPort(Integer.parseInt(cursor.getString(4)));
  1089. record.setRemoteIP(cursor.getString(5));
  1090. record.setRemotePort(Integer.parseInt(cursor.getString(6)));
  1091. record.setWasInternalAttack(cursor.getInt(7) == 1);
  1092. record.setBssid(cursor.getString(8));
  1093. record.setSync_id(cursor.getLong(9));
  1094. record.setDevice(cursor.getString(10));
  1095. record.setId(Integer.parseInt(cursor.getString(11)));
  1096. //record.setAttack_id(cursor.getLong(12));
  1097. String v = cursor.getString(13);
  1098. if (v != null && !v.equals("RECEIVE")) {
  1099. record.setType(TYPE.SEND);
  1100. //record.setType(MessageRecord.TYPE.valueOf(v));
  1101. } else {
  1102. record.setType(TYPE.RECEIVE);
  1103. }
  1104. record.setTimestamp(cursor.getLong(14));
  1105. record.setPacket(cursor.getString(15));
  1106. return record;
  1107. }
  1108. /**
  1109. * Creates a {@link Record} from a Cursor. If the cursor does not show to a
  1110. * valid data structure a runtime exception is thrown.
  1111. *
  1112. * @param cursor
  1113. * @return Returns the created {@link Record} .
  1114. */
  1115. private synchronized Record createRecord(Cursor cursor) {
  1116. Record record = new Record();
  1117. record.setId(Integer.parseInt(cursor.getString(0)));
  1118. record.setAttack_id(cursor.getLong(1));
  1119. record.setType(TYPE.valueOf(cursor.getString(2)));
  1120. record.setTimestamp(cursor.getLong(3));
  1121. record.setPacket(cursor.getString(4));
  1122. record.setProtocol(cursor.getString(5));
  1123. record.setExternalIP(cursor.getString(6));
  1124. record.setLocalIP(cursor.getString(7));
  1125. record.setLocalPort(Integer.parseInt(cursor.getString(8)));
  1126. record.setRemoteIP(cursor.getString(9));
  1127. record.setRemotePort(Integer.parseInt(cursor.getString(10)));
  1128. record.setWasInternalAttack(Integer.parseInt(cursor.getString(11)) == 1);
  1129. record.setBssid(cursor.getString(12));
  1130. record.setDevice(cursor.getString(13));
  1131. record.setSync_ID(cursor.getLong(14));
  1132. record.setSsid(cursor.getString(15));
  1133. record.setLatitude(Double.parseDouble(cursor.getString(16)));
  1134. record.setLongitude(Double.parseDouble(cursor.getString(17)));
  1135. record.setAccuracy(Float.parseFloat(cursor.getString(18)));
  1136. record.setTimestampLocation(cursor.getLong(19));
  1137. return record;
  1138. }
  1139. /**
  1140. * Gets all received {@link Record Records} for the specified information in
  1141. * the LogFilter ordered by date.
  1142. *
  1143. * @return A ArrayList with all received {@link Record Records} for the
  1144. * LogFilter.
  1145. */
  1146. public synchronized ArrayList<Record> getRecordsForFilter(LogFilter filter) {
  1147. ArrayList<Record> recordList = new ArrayList<Record>();
  1148. String selectQuery = this.selectionQueryFromFilter(filter, "*");
  1149. SQLiteDatabase db = this.getReadableDatabase();
  1150. Cursor cursor = db.rawQuery(selectQuery, null);
  1151. // looping through all rows and adding to list
  1152. if (cursor.moveToFirst()) {
  1153. do {
  1154. Record record = createRecord(cursor);
  1155. // Adding record to list
  1156. recordList.add(record);
  1157. } while (cursor.moveToNext());
  1158. }
  1159. cursor.close();
  1160. // return record list
  1161. db.close();
  1162. return recordList;
  1163. }
  1164. /**
  1165. * Returns the query for the given filter.
  1166. * @param filter (LogFilter)
  1167. * @param selectionString (String) for everything: "*"
  1168. * @return (String) query string
  1169. */
  1170. public String selectionQueryFromFilter(LogFilter filter, String selectionString)
  1171. {
  1172. String selectQuery = "SELECT " + selectionString + " FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " JOIN " + NetworkEntry.TABLE_NAME + " USING " + "(" + NetworkEntry.COLUMN_NAME_BSSID
  1173. + ")";
  1174. if (filter == null) return selectQuery;
  1175. // TIMESTAMPS
  1176. selectQuery = selectQuery + " WHERE " + PacketEntry.TABLE_NAME + "." + PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP;
  1177. selectQuery = selectQuery + " < " + filter.getBelowTimestamp();
  1178. selectQuery = selectQuery + " AND " + PacketEntry.TABLE_NAME + "." + PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP;
  1179. selectQuery = selectQuery + " > " + filter.getAboveTimestamp();
  1180. if (filter.getBSSIDs() != null && filter.getBSSIDs().size() > 0) {
  1181. selectQuery = selectQuery + " AND ";
  1182. selectQuery = selectQuery + filter.getBSSIDQueryStatement(NetworkEntry.TABLE_NAME, NetworkEntry.COLUMN_NAME_BSSID);
  1183. }
  1184. if (filter.getESSIDs() != null && filter.getESSIDs().size() > 0) {
  1185. selectQuery = selectQuery + " AND ";
  1186. selectQuery = selectQuery + filter.getESSIDQueryStatement(NetworkEntry.TABLE_NAME, NetworkEntry.COLUMN_NAME_SSID);
  1187. }
  1188. if (filter.getProtocols() != null && filter.getProtocols().size() > 0) {
  1189. selectQuery = selectQuery + " AND ";
  1190. selectQuery = selectQuery + filter.getProtocolsQueryStatement(AttackEntry.TABLE_NAME, AttackEntry.COLUMN_NAME_PROTOCOL);
  1191. }
  1192. selectQuery = selectQuery + " GROUP BY " + PacketEntry.TABLE_NAME + "." + PacketEntry.COLUMN_NAME_ATTACK_ID;
  1193. if (filter.getSorttype() == LogFilter.SortType.packet_timestamp) {
  1194. // DESC
  1195. selectQuery = selectQuery + " ORDER BY " + filter.getSorttype() + " DESC";
  1196. } else {
  1197. selectQuery = selectQuery + " ORDER BY " + filter.getSorttype();
  1198. }
  1199. System.out.println(selectQuery);
  1200. return selectQuery;
  1201. }
  1202. /**
  1203. * Returns the Conversation of a specific attack id
  1204. *
  1205. * @param attack_id Tha attack id to match the query against.
  1206. *
  1207. * @return A arraylist with all {@link Record Records}s for an attack id.
  1208. */
  1209. public synchronized ArrayList<Record> getConversationForAttackID(long attack_id) {
  1210. ArrayList<Record> recordList = new ArrayList<Record>();
  1211. String selectQuery = "SELECT * FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " JOIN " + NetworkEntry.TABLE_NAME + " USING " + "(" + NetworkEntry.COLUMN_NAME_BSSID
  1212. + ")" + " WHERE " + PacketEntry.TABLE_NAME + "." + PacketEntry.COLUMN_NAME_ATTACK_ID + " = " + attack_id;
  1213. SQLiteDatabase db = this.getReadableDatabase();
  1214. Cursor cursor = db.rawQuery(selectQuery, null);
  1215. if (cursor.moveToFirst()) {
  1216. do {
  1217. Record record = createRecord(cursor);
  1218. recordList.add(record);
  1219. } while (cursor.moveToNext());
  1220. }
  1221. cursor.close();
  1222. db.close();
  1223. return recordList;
  1224. }
  1225. /**
  1226. * Gets a single {@link Record} with the given attack id from the database.
  1227. *
  1228. * @param attack_id
  1229. * The attack id of the {@link Record};
  1230. * @return The {@link Record}.
  1231. */
  1232. public synchronized Record getRecordOfAttackId(long attack_id) {
  1233. String selectQuery = "SELECT * FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " JOIN " + NetworkEntry.TABLE_NAME + " USING " + "(" + NetworkEntry.COLUMN_NAME_BSSID
  1234. + ")" + " WHERE " + PacketEntry.TABLE_NAME + "." + PacketEntry.COLUMN_NAME_ATTACK_ID + " = " + attack_id + " GROUP BY " + PacketEntry.TABLE_NAME + "." + PacketEntry.COLUMN_NAME_ID;
  1235. SQLiteDatabase db = this.getReadableDatabase();
  1236. Cursor cursor = db.rawQuery(selectQuery, null);
  1237. Record record = null;
  1238. if (cursor.moveToFirst()) {
  1239. record = createRecord(cursor);
  1240. }
  1241. cursor.close();
  1242. // return record list
  1243. db.close();
  1244. return record;
  1245. }
  1246. /**
  1247. * Gets a single {@link Record} with the given ID from the database.
  1248. *
  1249. * @param id
  1250. * The ID of the {@link Record};
  1251. * @return The {@link Record}.
  1252. */
  1253. public synchronized Record getRecord(int id) {
  1254. String selectQuery = "SELECT * FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " JOIN " + NetworkEntry.TABLE_NAME + " USING " + "(" + PacketEntry.COLUMN_NAME_ATTACK_ID
  1255. + ")" + " WHERE " + PacketEntry.TABLE_NAME + "." + PacketEntry.COLUMN_NAME_ID + " = " + id;
  1256. SQLiteDatabase db = this.getReadableDatabase();
  1257. Cursor cursor = db.rawQuery(selectQuery, null);
  1258. Record record = null;
  1259. if (cursor.moveToFirst()) {
  1260. record = createRecord(cursor);
  1261. }
  1262. cursor.close();
  1263. db.close();
  1264. // return contact
  1265. return record;
  1266. }
  1267. /**
  1268. * Gets all {@link Record Records} saved in the database.
  1269. *
  1270. * @return A ArrayList of all the {@link Record Records} in the Database.
  1271. */
  1272. public synchronized ArrayList<Record> getAllRecords() {
  1273. ArrayList<Record> recordList = new ArrayList<Record>();
  1274. // Select All Query
  1275. String selectQuery = "SELECT * FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " JOIN " + NetworkEntry.TABLE_NAME + " USING " + "(" + NetworkEntry.COLUMN_NAME_BSSID
  1276. + ")";
  1277. SQLiteDatabase db = this.getWritableDatabase();
  1278. Cursor cursor = db.rawQuery(selectQuery, null);
  1279. Log.i("Database", "Start loop");
  1280. // looping through all rows and adding to list
  1281. if (cursor.moveToFirst()) {
  1282. do {
  1283. Log.i("Database", "Add Record");
  1284. Record record = createRecord(cursor);
  1285. // Adding record to list
  1286. recordList.add(record);
  1287. } while (cursor.moveToNext());
  1288. }
  1289. cursor.close();
  1290. db.close();
  1291. // return record list
  1292. return recordList;
  1293. }
  1294. /**
  1295. * Gets all non duplicate Records For the key BSSID.
  1296. *
  1297. * @return A ArrayList with received Records.
  1298. */
  1299. public synchronized ArrayList<String> getUniqueBSSIDRecords() {
  1300. return this.getUniqueDataEntryForKeyType(NetworkEntry.COLUMN_NAME_BSSID, NetworkEntry.TABLE_NAME);
  1301. }
  1302. /**
  1303. * Gets all non duplicate Records For the key ESSID.
  1304. *
  1305. * @return A ArrayList with received Records.
  1306. */
  1307. public synchronized ArrayList<String> getUniqueESSIDRecords() {
  1308. return this.getUniqueDataEntryForKeyType(NetworkEntry.COLUMN_NAME_SSID, NetworkEntry.TABLE_NAME);
  1309. }
  1310. public synchronized ArrayList<String> getUniqueESSIDRecordsForProtocol(String protocol) {
  1311. return this.getUniqueIDForProtocol(NetworkEntry.COLUMN_NAME_SSID, protocol);
  1312. }
  1313. public synchronized ArrayList<String> getUniqueBSSIDRecordsForProtocol(String protocol) {
  1314. return this.getUniqueIDForProtocol(NetworkEntry.COLUMN_NAME_BSSID, protocol);
  1315. }
  1316. private synchronized ArrayList<String> getUniqueIDForProtocol(String id, String protocol) {
  1317. ArrayList<String> recordList = new ArrayList<String>();
  1318. String selectQuery = "SELECT DISTINCT " + id + " FROM " + AttackEntry.TABLE_NAME + " JOIN " + NetworkEntry.TABLE_NAME + " USING " + "(" + NetworkEntry.COLUMN_NAME_BSSID + ") " + " WHERE "
  1319. + AttackEntry.TABLE_NAME + "." + AttackEntry.COLUMN_NAME_PROTOCOL + " = " + "'" + protocol + "'" + " ORDER BY " + "'"+id+"'"; // " NATURAL JOIN "
  1320. // +
  1321. // TABLE_ATTACK_INFO
  1322. // +
  1323. // " NATURAL JOIN "
  1324. // +
  1325. // TABLE_BSSIDS
  1326. // +
  1327. // " NATURAL JOIN "
  1328. // +
  1329. // TABLE_PORTS
  1330. // +
  1331. // ORDERED BY TIME
  1332. System.out.println(selectQuery);
  1333. SQLiteDatabase db = this.getReadableDatabase();
  1334. Cursor cursor = db.rawQuery(selectQuery, null);
  1335. // looping through all rows and adding to list
  1336. if (cursor.moveToFirst()) {
  1337. do {
  1338. String record = cursor.getString(0);
  1339. recordList.add(record);
  1340. } while (cursor.moveToNext());
  1341. }
  1342. cursor.close();
  1343. // return record list
  1344. db.close();
  1345. return recordList;
  1346. }
  1347. /**
  1348. * Gets all non duplicate Data Entry For a specific KeyType ( e.g. BSSIDs).
  1349. *
  1350. * @return A ArrayList with received Records.
  1351. */
  1352. public synchronized ArrayList<String> getUniqueDataEntryForKeyType(String keyType, String table) {
  1353. ArrayList<String> recordList = new ArrayList<String>();
  1354. // String selectQuery = "SELECT * FROM " + TABLE_RECORDS +
  1355. // " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " +
  1356. // TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS;
  1357. String selectQuery = "SELECT DISTINCT " + keyType + " FROM " + table + " ORDER BY " + keyType; // " NATURAL JOIN "
  1358. // +
  1359. // TABLE_ATTACK_INFO
  1360. // +
  1361. // " NATURAL JOIN "
  1362. // +
  1363. // TABLE_BSSIDS
  1364. // +
  1365. // " NATURAL JOIN "
  1366. // +
  1367. // TABLE_PORTS
  1368. // +
  1369. // ORDERED BY TIME
  1370. System.out.println(selectQuery);
  1371. SQLiteDatabase db = this.getReadableDatabase();
  1372. Cursor cursor = db.rawQuery(selectQuery, null);
  1373. // looping through all rows and adding to list
  1374. if (cursor.moveToFirst()) {
  1375. do {
  1376. String record = cursor.getString(0);
  1377. recordList.add(record);
  1378. } while (cursor.moveToNext());
  1379. }
  1380. cursor.close();
  1381. // return record list
  1382. db.close();
  1383. return recordList;
  1384. }
  1385. //TODO PROFILE DATABASE QUERIES - STILL NEEDED?
  1386. /**
  1387. * Retrieves all the profiles from the database
  1388. *
  1389. * @return list of profiles
  1390. */
  1391. public synchronized List<Profile> getAllProfiles() {
  1392. List<Profile> profiles = new LinkedList<Profile>();
  1393. // Select All Query
  1394. String selectQuery = "SELECT * FROM " + ProfileEntry.TABLE_NAME;
  1395. SQLiteDatabase db = this.getWritableDatabase();
  1396. Cursor cursor = db.rawQuery(selectQuery, null);
  1397. // looping through all rows and adding to list
  1398. if (cursor.moveToFirst()) {
  1399. do {
  1400. Profile profile = new Profile(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getInt(5) == 1);
  1401. if (cursor.getInt(6) == 1) {
  1402. profile.mActivated = true;
  1403. }
  1404. profile.mIconName = cursor.getString(4);
  1405. // Adding record to list
  1406. profiles.add(profile);
  1407. } while (cursor.moveToNext());
  1408. }
  1409. cursor.close();
  1410. db.close();
  1411. // return record list
  1412. return profiles;
  1413. }
  1414. /**
  1415. * Persists the given profile into the database
  1416. *
  1417. * @param profile
  1418. * the profile which should be persisted
  1419. *
  1420. * @return
  1421. */
  1422. public synchronized long persistProfile(Profile profile) {
  1423. SQLiteDatabase db = this.getWritableDatabase();
  1424. ContentValues values = new ContentValues();
  1425. if (profile.mId != -1) {
  1426. values.put(ProfileEntry.COLUMN_NAME_PROFILE_ID, profile.mId);
  1427. }
  1428. values.put(ProfileEntry.COLUMN_NAME_PROFILE_NAME, profile.mLabel);
  1429. values.put(ProfileEntry.COLUMN_NAME_PROFILE_DESCRIPTION, profile.mText);
  1430. values.put(ProfileEntry.COLUMN_NAME_PROFILE_ICON, profile.mIconPath);
  1431. values.put(ProfileEntry.COLUMN_NAME_PROFILE_ICON_NAME, profile.mIconName);
  1432. values.put(ProfileEntry.COLUMN_NAME_PROFILE_ACTIVE, profile.mActivated);
  1433. values.put(ProfileEntry.COLUMN_NAME_PROFILE_EDITABLE, profile.mEditable);
  1434. return db.replace(ProfileEntry.TABLE_NAME, null, values);
  1435. }
  1436. /**
  1437. * private static final String CREATE_PROFILE_TABLE = "CREATE TABLE " +
  1438. * TABLE_PROFILES + "(" + KEY_PROFILE_ID +
  1439. * " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_PROFILE_NAME + " TEXT," +
  1440. * KEY_PROFILE_DESCRIPTION + " TEXT," + KEY_PROFILE_ICON + " TEXT," +
  1441. * KEY_PROFILE_ICON_ID + " INTEGER," + KEY_PROFILE_EDITABLE + " INTEGER," +
  1442. * KEY_PROFILE_ACTIVE + " INTEGER" + ")";
  1443. */
  1444. public synchronized Profile getProfile(int id) {
  1445. String selectQuery = "SELECT * FROM " + ProfileEntry.TABLE_NAME + " WHERE " + ProfileEntry.TABLE_NAME + "." + ProfileEntry.COLUMN_NAME_PROFILE_ID + " = " + id;
  1446. SQLiteDatabase db = this.getReadableDatabase();
  1447. Cursor cursor = db.rawQuery(selectQuery, null);
  1448. Profile profile = null;
  1449. if (cursor.moveToFirst()) {
  1450. profile = new Profile(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getInt(5) == 1);
  1451. if (cursor.getInt(6) == 1) {
  1452. profile.mActivated = true;
  1453. }
  1454. profile.mIconName = cursor.getString(5);
  1455. }
  1456. cursor.close();
  1457. db.close();
  1458. // return contact
  1459. return profile;
  1460. }
  1461. public synchronized void deleteProfile(int id) {
  1462. SQLiteDatabase db = this.getWritableDatabase();
  1463. db.delete(ProfileEntry.TABLE_NAME, ProfileEntry.COLUMN_NAME_PROFILE_ID + "=?", new String[] { String.valueOf(id) });
  1464. db.close();
  1465. }
  1466. /**
  1467. * Gets all received {@link Record Records} for every attack identified by
  1468. * its attack id and ordered by date.
  1469. *
  1470. * @return A ArrayList with all received {@link Record Records} for each
  1471. * attack id in the Database.
  1472. */
  1473. public synchronized ArrayList<Record> getAllReceivedRecordsOfEachAttack() {
  1474. ArrayList<Record> recordList = new ArrayList<Record>();
  1475. String selectQuery = "SELECT * FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " JOIN " + NetworkEntry.TABLE_NAME + " USING " + "(" + NetworkEntry.COLUMN_NAME_BSSID
  1476. + ")" + " WHERE " + PacketEntry.COLUMN_NAME_TYPE + "='RECEIVE'" + " ORDER BY " + PacketEntry.TABLE_NAME + "." + PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP;
  1477. SQLiteDatabase db = this.getReadableDatabase();
  1478. Cursor cursor = db.rawQuery(selectQuery, null);
  1479. // looping through all rows and adding to list
  1480. if (cursor.moveToFirst()) {
  1481. do {
  1482. Record record = createRecord(cursor);
  1483. // Adding record to list
  1484. recordList.add(record);
  1485. } while (cursor.moveToNext());
  1486. }
  1487. cursor.close();
  1488. // return record list
  1489. db.close();
  1490. return recordList;
  1491. }
  1492. /**
  1493. * Returns PlotComparisionItems for attacks per essid.
  1494. * @param filter (LogFilter) filter object
  1495. * @return ArrayList<PlotComparisonItem>
  1496. */
  1497. public synchronized ArrayList<PlotComparisonItem> attacksPerESSID(LogFilter filter) {
  1498. String filterQuery = this.selectionQueryFromFilter(filter, AttackEntry.COLUMN_NAME_ATTACK_ID);
  1499. String attackPerESSID_Query = "SELECT " + NetworkEntry.COLUMN_NAME_SSID + " , " + "COUNT( " + AttackEntry.COLUMN_NAME_ATTACK_ID + " ) " + " "
  1500. + " FROM " + AttackEntry.TABLE_NAME + " a " + " , " + NetworkEntry.TABLE_NAME
  1501. + " WHERE " + " a." + AttackEntry.COLUMN_NAME_ATTACK_ID + " IN " + " ( " + filterQuery + " ) "
  1502. + " GROUP BY " + NetworkEntry.TABLE_NAME+"."+NetworkEntry.COLUMN_NAME_SSID;
  1503. SQLiteDatabase db = this.getReadableDatabase();
  1504. Cursor cursor = db.rawQuery(attackPerESSID_Query, null);
  1505. ArrayList<PlotComparisonItem> plots = new ArrayList<PlotComparisonItem>();
  1506. int counter = 0;
  1507. if (cursor.moveToFirst()) {
  1508. do {
  1509. String title = cursor.getString(0); // COLUMN_NAME_SSID
  1510. double value = cursor.getDouble(1); // COUNT
  1511. if (value == 0.) continue;
  1512. PlotComparisonItem plotItem = new PlotComparisonItem(title, this.getColor(counter), 0. , value);
  1513. plots.add(plotItem);
  1514. counter++;
  1515. } while (cursor.moveToNext());
  1516. }
  1517. cursor.close();
  1518. db.close();
  1519. return plots;
  1520. }
  1521. /**
  1522. * Creates a {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice} from a Cursor. If the cursor does not show to a
  1523. * valid data structure a runtime exception is thrown.
  1524. *
  1525. * @param cursor the cursor
  1526. * @return Returns the created {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice} .
  1527. */
  1528. private synchronized SyncDevice createSyncDevice(Cursor cursor) {
  1529. SyncDevice record = new SyncDevice();
  1530. record.setDeviceID(cursor.getString(0));
  1531. record.setLast_sync_timestamp(cursor.getLong(1));
  1532. record.setHighest_attack_id(cursor.getLong(2));
  1533. return record;
  1534. }
  1535. /**
  1536. * Returns all missing / newly inserted and updated {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s.
  1537. * @param oldDevices array of {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s
  1538. * @param includeMissing boolean
  1539. * @return array of {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s
  1540. */
  1541. public ArrayList<SyncDevice> getUpdatedDevicesFor(List<SyncDevice> oldDevices, boolean includeMissing){
  1542. HashMap<String, Long> oldDeviceMap = new HashMap<String, Long>();
  1543. for (SyncDevice d : oldDevices){
  1544. oldDeviceMap.put(d.getDeviceID(),d.getHighest_attack_id());
  1545. }
  1546. ArrayList<SyncDevice> recordList = new ArrayList<SyncDevice>();
  1547. String selectQuery = "SELECT * FROM " + SyncDeviceEntry.TABLE_NAME;
  1548. SQLiteDatabase db = this.getReadableDatabase();
  1549. Cursor cursor = db.rawQuery(selectQuery, null);
  1550. // looping through all rows and adding to list
  1551. if (cursor.moveToFirst()) {
  1552. do {
  1553. SyncDevice record = createSyncDevice(cursor);
  1554. // Adding record to list
  1555. if (oldDeviceMap.containsKey(record.getDeviceID())){
  1556. Long oldSyncId = oldDeviceMap.get(record.getDeviceID());
  1557. if (oldSyncId < record.getHighest_attack_id()){
  1558. recordList.add(record);
  1559. }
  1560. } else {
  1561. if (includeMissing)
  1562. recordList.add(record);
  1563. }
  1564. } while (cursor.moveToNext());
  1565. }
  1566. cursor.close();
  1567. // return record list
  1568. db.close();
  1569. return recordList;
  1570. }
  1571. /**
  1572. * Returns all missing / newly inserted and updated {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s.
  1573. * @param oldDeviceMap map with device id and max sync_id for the device
  1574. * @param includeMissing boolean
  1575. * @return array of {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s
  1576. */
  1577. public synchronized ArrayList<SyncDevice> getUpdatedDevicesFor(HashMap<String, Long> oldDeviceMap, boolean includeMissing){
  1578. ArrayList<SyncDevice> recordList = new ArrayList<SyncDevice>();
  1579. String selectQuery = "SELECT * FROM " + SyncDeviceEntry.TABLE_NAME;
  1580. SQLiteDatabase db = this.getReadableDatabase();
  1581. Cursor cursor = db.rawQuery(selectQuery, null);
  1582. // looping through all rows and adding to list
  1583. if (cursor.moveToFirst()) {
  1584. do {
  1585. SyncDevice record = createSyncDevice(cursor);
  1586. // Adding record to list
  1587. if (oldDeviceMap.containsKey(record.getDeviceID())){
  1588. Long oldSyncId = oldDeviceMap.get(record.getDeviceID());
  1589. if (oldSyncId < record.getHighest_attack_id()){
  1590. recordList.add(record);
  1591. }
  1592. } else {
  1593. if (includeMissing)
  1594. recordList.add(record);
  1595. }
  1596. } while (cursor.moveToNext());
  1597. }
  1598. cursor.close();
  1599. // return record list
  1600. db.close();
  1601. return recordList;
  1602. }
  1603. /**
  1604. * Returns all device ids.
  1605. * @return list of all device ids.
  1606. */
  1607. public synchronized ArrayList<String> getAllDevicesIds(){
  1608. String selectQuery = "SELECT "+ SyncDeviceEntry.COLUMN_NAME_DEVICE_ID+" FROM " + SyncDeviceEntry.TABLE_NAME;
  1609. SQLiteDatabase db = this.getReadableDatabase();
  1610. Cursor cursor = db.rawQuery(selectQuery, null);
  1611. ArrayList<String> ids = new ArrayList<String>();
  1612. // looping through all rows and adding to list
  1613. if (cursor.moveToFirst()) {
  1614. do {
  1615. String s = cursor.getString(0);
  1616. ids.add(s);
  1617. } while (cursor.moveToNext());
  1618. }
  1619. cursor.close();
  1620. // return record list
  1621. db.close();
  1622. return ids;
  1623. }
  1624. /***
  1625. * Returns all missing devices ids
  1626. * @param devices owned device ids
  1627. * @return list of missing devices ids
  1628. */
  1629. public synchronized ArrayList<String> getMissingDeviceIds(ArrayList<String> devices){
  1630. ArrayList<String> ids = new ArrayList<String>();
  1631. String prefix = " D WHERE " + SyncDeviceEntry.COLUMN_NAME_DEVICE_ID + " NOT IN ";
  1632. String selectQuery = "SELECT "+ SyncDeviceEntry.COLUMN_NAME_DEVICE_ID +" FROM " + SyncDeviceEntry.TABLE_NAME + this.arrayToSQLString(devices,prefix);
  1633. SQLiteDatabase db = this.getReadableDatabase();
  1634. Cursor cursor = db.rawQuery(selectQuery, null);
  1635. if (cursor.moveToFirst()) {
  1636. do {
  1637. String deviceID = cursor.getString(0);
  1638. ids.add(deviceID);
  1639. } while (cursor.moveToNext());
  1640. }
  1641. cursor.close();
  1642. db.close();
  1643. return ids;
  1644. }
  1645. /**
  1646. * Returns all new {@link de.tudarmstadt.informatik.hostage.logging.AttackRecord}s for the given devices (including all missing devices).
  1647. * @param deviceMap map of device id and max sync_id of it
  1648. * @param includeMissingDevices boolean
  1649. * @return list of {@link de.tudarmstadt.informatik.hostage.logging.AttackRecord}s
  1650. */
  1651. public synchronized ArrayList<SyncRecord> getUnsyncedAttacksFor(HashMap<String,Long> deviceMap, boolean includeMissingDevices){
  1652. ArrayList<SyncDevice> updatedDevices = this.getUpdatedDevicesFor(deviceMap, includeMissingDevices);
  1653. ArrayList<SyncRecord> recordList = new ArrayList<SyncRecord>();
  1654. SQLiteDatabase db = this.getReadableDatabase();
  1655. for (SyncDevice sDevice : updatedDevices){
  1656. String deviceID = sDevice.getDeviceID();
  1657. Long maxID = deviceMap.get(deviceID);
  1658. String selectQuery = "SELECT * FROM " + AttackEntry.TABLE_NAME + " A " + " , " + PacketEntry.TABLE_NAME + " P "
  1659. + " WHERE "
  1660. +" ( "
  1661. + "A." + AttackEntry.COLUMN_NAME_ATTACK_ID + " = " + " P."+ PacketEntry.COLUMN_NAME_ATTACK_ID
  1662. + " AND " + " A." + AttackEntry.COLUMN_NAME_DEVICE + " = " + "'" + deviceID + "'"
  1663. + " AND " + " A." + AttackEntry.COLUMN_NAME_SYNC_ID + " > " + maxID
  1664. + " ) "
  1665. //+ " GROUP BY " + AttackEntry.TABLE_NAME + "." + AttackEntry.COLUMN_NAME_DEVICE
  1666. + " ORDER BY " + " A" + "." + AttackEntry.COLUMN_NAME_SYNC_ID + " DESC ";
  1667. Cursor cursor = db.rawQuery(selectQuery, null);
  1668. // looping through all rows and adding to list
  1669. if (cursor != null){
  1670. if (cursor.moveToFirst()) {
  1671. do {
  1672. SyncRecord record = createSyncRecord(cursor);
  1673. recordList.add(record);
  1674. } while (cursor.moveToNext());
  1675. }
  1676. cursor.close();
  1677. }
  1678. }
  1679. // return record list
  1680. db.close();
  1681. return recordList;
  1682. }
  1683. /**
  1684. * Attacks per BSSID
  1685. * @param filter (LogFilter) query filter
  1686. * @return ArrayList<PlotComparisonItem>
  1687. */
  1688. public synchronized ArrayList<PlotComparisonItem> attacksPerBSSID(LogFilter filter) {
  1689. String filterQuery = this.selectionQueryFromFilter(filter, AttackEntry.COLUMN_NAME_ATTACK_ID);
  1690. String attackPerBSSID_Query = "SELECT " + NetworkEntry.COLUMN_NAME_BSSID + " , " + "COUNT( " + AttackEntry.COLUMN_NAME_ATTACK_ID + " ) " + " "
  1691. + " FROM " + AttackEntry.TABLE_NAME + " a " + " , " + NetworkEntry.TABLE_NAME
  1692. + " WHERE " + " a." + AttackEntry.COLUMN_NAME_ATTACK_ID + " IN " + " ( " + filterQuery + " ) "
  1693. + " GROUP BY " + NetworkEntry.TABLE_NAME + "." + NetworkEntry.COLUMN_NAME_BSSID;
  1694. SQLiteDatabase db = this.getReadableDatabase();
  1695. Cursor cursor = db.rawQuery(attackPerBSSID_Query, null);
  1696. ArrayList<PlotComparisonItem> plots = new ArrayList<PlotComparisonItem>();
  1697. int counter = 0;
  1698. if (cursor.moveToFirst()) {
  1699. do {
  1700. String title = cursor.getString(0); // COLUMN_NAME_BSSID
  1701. double value = cursor.getDouble(1); // COUNT
  1702. if (value == 0.) continue;
  1703. PlotComparisonItem plotItem = new PlotComparisonItem(title, this.getColor(counter), 0. , value);
  1704. plots.add(plotItem);
  1705. counter++;
  1706. } while (cursor.moveToNext());
  1707. }
  1708. cursor.close();
  1709. db.close();
  1710. return plots;
  1711. }
  1712. /**
  1713. * Inserts the given devices in the database with save.
  1714. * @param devices list of {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s
  1715. */
  1716. public synchronized void insertSyncDevices(List<SyncDevice> devices){
  1717. SQLiteDatabase db = this.getWritableDatabase();
  1718. db.beginTransaction();
  1719. try {
  1720. for (SyncDevice device : devices){
  1721. insertSyncDevice(device, db);
  1722. }
  1723. db.setTransactionSuccessful();
  1724. } finally {
  1725. db.endTransaction();
  1726. }
  1727. db.close(); // Closing database connection
  1728. }
  1729. /**
  1730. * Inserts the given dives in the given SQLite Database without save.
  1731. * @param device {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}
  1732. * @param db {@link android.database.sqlite.SQLiteDatabase}
  1733. */
  1734. private void insertSyncDevice(SyncDevice device, SQLiteDatabase db){
  1735. ContentValues recordValues = new ContentValues();
  1736. recordValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_ID, device.getDeviceID());
  1737. recordValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_TIMESTAMP, device.getLast_sync_timestamp());
  1738. recordValues.put(SyncDeviceEntry.COLUMN_NAME_HIGHEST_ATTACK_ID, device.getHighest_attack_id());
  1739. // Inserting Rows
  1740. db.insertWithOnConflict(SyncDeviceEntry.TABLE_NAME, null, recordValues, SQLiteDatabase.CONFLICT_REPLACE);
  1741. }
  1742. /** Returns the color for the given index
  1743. * @return int color*/
  1744. public Integer getColor(int index) {
  1745. return ColorSequenceGenerator.getColorForIndex(index);
  1746. }
  1747. }