HostageDBOpenHelper.java 73 KB

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