HostageDBOpenHelper.java 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010
  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 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 void updateNetworkInformation(ArrayList<NetworkRecord> networkInformation) {
  762. SQLiteDatabase db = this.getReadableDatabase();
  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 void updateNetworkInformation(NetworkRecord record) {
  795. SQLiteDatabase db = this.getReadableDatabase();
  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 void updateTimestampOfSyncDevice(String deviceID, long timestamp){
  818. SQLiteDatabase db = this.getReadableDatabase();
  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 void updateSyncDevices(HashMap<String, Long> devices){
  830. SQLiteDatabase db = this.getReadableDatabase();
  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 void updateSyncDevices(ArrayList<SyncDevice> devices){
  846. SQLiteDatabase db = this.getReadableDatabase();
  847. this.updateSyncDevices(devices, db);
  848. db.close();
  849. }
  850. public 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 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.getReadableDatabase();
  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.getReadableDatabase();
  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 void clearSyncInfos(){
  986. SQLiteDatabase db = this.getReadableDatabase();
  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 void clearData() {
  995. SQLiteDatabase db = this.getReadableDatabase();
  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.getReadableDatabase();
  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.getReadableDatabase();
  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.getReadableDatabase();
  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.getReadableDatabase();
  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.getReadableDatabase();
  1463. db.delete(ProfileEntry.TABLE_NAME, ProfileEntry.COLUMN_NAME_PROFILE_ID + "=?", new String[] { String.valueOf(id) });
  1464. }
  1465. /**
  1466. * Gets all received {@link Record Records} for every attack identified by
  1467. * its attack id and ordered by date.
  1468. *
  1469. * @return A ArrayList with all received {@link Record Records} for each
  1470. * attack id in the Database.
  1471. */
  1472. public synchronized ArrayList<Record> getAllReceivedRecordsOfEachAttack() {
  1473. ArrayList<Record> recordList = new ArrayList<Record>();
  1474. String selectQuery = "SELECT * FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " JOIN " + NetworkEntry.TABLE_NAME + " USING " + "(" + NetworkEntry.COLUMN_NAME_BSSID
  1475. + ")" + " WHERE " + PacketEntry.COLUMN_NAME_TYPE + "='RECEIVE'" + " ORDER BY " + PacketEntry.TABLE_NAME + "." + PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP;
  1476. SQLiteDatabase db = this.getReadableDatabase();
  1477. Cursor cursor = db.rawQuery(selectQuery, null);
  1478. // looping through all rows and adding to list
  1479. if (cursor.moveToFirst()) {
  1480. do {
  1481. Record record = createRecord(cursor);
  1482. // Adding record to list
  1483. recordList.add(record);
  1484. } while (cursor.moveToNext());
  1485. }
  1486. cursor.close();
  1487. // return record list
  1488. db.close();
  1489. return recordList;
  1490. }
  1491. /**
  1492. * Returns PlotComparisionItems for attacks per essid.
  1493. * @param filter (LogFilter) filter object
  1494. * @return ArrayList<PlotComparisonItem>
  1495. */
  1496. public synchronized ArrayList<PlotComparisonItem> attacksPerESSID(LogFilter filter) {
  1497. String filterQuery = this.selectionQueryFromFilter(filter, AttackEntry.COLUMN_NAME_ATTACK_ID);
  1498. String attackPerESSID_Query = "SELECT " + NetworkEntry.COLUMN_NAME_SSID + " , " + "COUNT( " + AttackEntry.COLUMN_NAME_ATTACK_ID + " ) " + " "
  1499. + " FROM " + AttackEntry.TABLE_NAME + " a " + " , " + NetworkEntry.TABLE_NAME
  1500. + " WHERE " + " a." + AttackEntry.COLUMN_NAME_ATTACK_ID + " IN " + " ( " + filterQuery + " ) "
  1501. + " GROUP BY " + NetworkEntry.TABLE_NAME+"."+NetworkEntry.COLUMN_NAME_SSID;
  1502. SQLiteDatabase db = this.getReadableDatabase();
  1503. Cursor cursor = db.rawQuery(attackPerESSID_Query, null);
  1504. ArrayList<PlotComparisonItem> plots = new ArrayList<PlotComparisonItem>();
  1505. int counter = 0;
  1506. if (cursor.moveToFirst()) {
  1507. do {
  1508. String title = cursor.getString(0); // COLUMN_NAME_SSID
  1509. double value = cursor.getDouble(1); // COUNT
  1510. if (value == 0.) continue;
  1511. PlotComparisonItem plotItem = new PlotComparisonItem(title, this.getColor(counter), 0. , value);
  1512. plots.add(plotItem);
  1513. counter++;
  1514. } while (cursor.moveToNext());
  1515. }
  1516. cursor.close();
  1517. db.close();
  1518. return plots;
  1519. }
  1520. /**
  1521. * Creates a {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice} from a Cursor. If the cursor does not show to a
  1522. * valid data structure a runtime exception is thrown.
  1523. *
  1524. * @param cursor the cursor
  1525. * @return Returns the created {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice} .
  1526. */
  1527. private synchronized SyncDevice createSyncDevice(Cursor cursor) {
  1528. SyncDevice record = new SyncDevice();
  1529. record.setDeviceID(cursor.getString(0));
  1530. record.setLast_sync_timestamp(cursor.getLong(1));
  1531. record.setHighest_attack_id(cursor.getLong(2));
  1532. return record;
  1533. }
  1534. /**
  1535. * Returns all missing / newly inserted and updated {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s.
  1536. * @param oldDevices array of {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s
  1537. * @param includeMissing boolean
  1538. * @return array of {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s
  1539. */
  1540. public ArrayList<SyncDevice> getUpdatedDevicesFor(List<SyncDevice> oldDevices, boolean includeMissing){
  1541. HashMap<String, Long> oldDeviceMap = new HashMap<String, Long>();
  1542. for (SyncDevice d : oldDevices){
  1543. oldDeviceMap.put(d.getDeviceID(),d.getHighest_attack_id());
  1544. }
  1545. ArrayList<SyncDevice> recordList = new ArrayList<SyncDevice>();
  1546. String selectQuery = "SELECT * FROM " + SyncDeviceEntry.TABLE_NAME;
  1547. SQLiteDatabase db = this.getReadableDatabase();
  1548. Cursor cursor = db.rawQuery(selectQuery, null);
  1549. // looping through all rows and adding to list
  1550. if (cursor.moveToFirst()) {
  1551. do {
  1552. SyncDevice record = createSyncDevice(cursor);
  1553. // Adding record to list
  1554. if (oldDeviceMap.containsKey(record.getDeviceID())){
  1555. Long oldSyncId = oldDeviceMap.get(record.getDeviceID());
  1556. if (oldSyncId < record.getHighest_attack_id()){
  1557. recordList.add(record);
  1558. }
  1559. } else {
  1560. if (includeMissing)
  1561. recordList.add(record);
  1562. }
  1563. } while (cursor.moveToNext());
  1564. }
  1565. cursor.close();
  1566. // return record list
  1567. db.close();
  1568. return recordList;
  1569. }
  1570. /**
  1571. * Returns all missing / newly inserted and updated {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s.
  1572. * @param oldDeviceMap map with device id and max sync_id for the device
  1573. * @param includeMissing boolean
  1574. * @return array of {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s
  1575. */
  1576. public ArrayList<SyncDevice> getUpdatedDevicesFor(HashMap<String, Long> oldDeviceMap, boolean includeMissing){
  1577. ArrayList<SyncDevice> recordList = new ArrayList<SyncDevice>();
  1578. String selectQuery = "SELECT * FROM " + SyncDeviceEntry.TABLE_NAME;
  1579. SQLiteDatabase db = this.getReadableDatabase();
  1580. Cursor cursor = db.rawQuery(selectQuery, null);
  1581. // looping through all rows and adding to list
  1582. if (cursor.moveToFirst()) {
  1583. do {
  1584. SyncDevice record = createSyncDevice(cursor);
  1585. // Adding record to list
  1586. if (oldDeviceMap.containsKey(record.getDeviceID())){
  1587. Long oldSyncId = oldDeviceMap.get(record.getDeviceID());
  1588. if (oldSyncId < record.getHighest_attack_id()){
  1589. recordList.add(record);
  1590. }
  1591. } else {
  1592. if (includeMissing)
  1593. recordList.add(record);
  1594. }
  1595. } while (cursor.moveToNext());
  1596. }
  1597. cursor.close();
  1598. // return record list
  1599. db.close();
  1600. return recordList;
  1601. }
  1602. /**
  1603. * Returns all device ids.
  1604. * @return list of all device ids.
  1605. */
  1606. public ArrayList<String> getAllDevicesIds(){
  1607. String selectQuery = "SELECT "+ SyncDeviceEntry.COLUMN_NAME_DEVICE_ID+" FROM " + SyncDeviceEntry.TABLE_NAME;
  1608. SQLiteDatabase db = this.getReadableDatabase();
  1609. Cursor cursor = db.rawQuery(selectQuery, null);
  1610. ArrayList<String> ids = new ArrayList<String>();
  1611. // looping through all rows and adding to list
  1612. if (cursor.moveToFirst()) {
  1613. do {
  1614. String s = cursor.getString(0);
  1615. ids.add(s);
  1616. } while (cursor.moveToNext());
  1617. }
  1618. cursor.close();
  1619. // return record list
  1620. db.close();
  1621. return ids;
  1622. }
  1623. /***
  1624. * Returns all missing devices ids
  1625. * @param devices owned device ids
  1626. * @return list of missing devices ids
  1627. */
  1628. public ArrayList<String> getMissingDeviceIds(ArrayList<String> devices){
  1629. ArrayList<String> ids = new ArrayList<String>();
  1630. String prefix = " D WHERE " + SyncDeviceEntry.COLUMN_NAME_DEVICE_ID + " NOT IN ";
  1631. String selectQuery = "SELECT "+ SyncDeviceEntry.COLUMN_NAME_DEVICE_ID +" FROM " + SyncDeviceEntry.TABLE_NAME + this.arrayToSQLString(devices,prefix);
  1632. SQLiteDatabase db = this.getReadableDatabase();
  1633. Cursor cursor = db.rawQuery(selectQuery, null);
  1634. if (cursor.moveToFirst()) {
  1635. do {
  1636. String deviceID = cursor.getString(0);
  1637. ids.add(deviceID);
  1638. } while (cursor.moveToNext());
  1639. }
  1640. cursor.close();
  1641. db.close();
  1642. return ids;
  1643. }
  1644. /**
  1645. * Returns all new {@link de.tudarmstadt.informatik.hostage.logging.AttackRecord}s for the given devices (including all missing devices).
  1646. * @param deviceMap map of device id and max sync_id of it
  1647. * @param includeMissingDevices boolean
  1648. * @return list of {@link de.tudarmstadt.informatik.hostage.logging.AttackRecord}s
  1649. */
  1650. public ArrayList<SyncRecord> getUnsyncedAttacksFor(HashMap<String,Long> deviceMap, boolean includeMissingDevices){
  1651. ArrayList<SyncDevice> updatedDevices = this.getUpdatedDevicesFor(deviceMap, includeMissingDevices);
  1652. ArrayList<SyncRecord> recordList = new ArrayList<SyncRecord>();
  1653. SQLiteDatabase db = this.getReadableDatabase();
  1654. for (SyncDevice sDevice : updatedDevices){
  1655. String deviceID = sDevice.getDeviceID();
  1656. Long maxID = deviceMap.get(deviceID);
  1657. String selectQuery = "SELECT * FROM " + AttackEntry.TABLE_NAME + " A " + " , " + PacketEntry.TABLE_NAME + " P "
  1658. + " WHERE "
  1659. +" ( "
  1660. + "A." + AttackEntry.COLUMN_NAME_ATTACK_ID + " = " + " P."+ PacketEntry.COLUMN_NAME_ATTACK_ID
  1661. + " AND " + " A." + AttackEntry.COLUMN_NAME_DEVICE + " = " + "'" + deviceID + "'"
  1662. + " AND " + " A." + AttackEntry.COLUMN_NAME_SYNC_ID + " > " + maxID
  1663. + " ) "
  1664. //+ " GROUP BY " + AttackEntry.TABLE_NAME + "." + AttackEntry.COLUMN_NAME_DEVICE
  1665. + " ORDER BY " + " A" + "." + AttackEntry.COLUMN_NAME_SYNC_ID + " DESC ";
  1666. Cursor cursor = db.rawQuery(selectQuery, null);
  1667. // looping through all rows and adding to list
  1668. if (cursor != null){
  1669. if (cursor.moveToFirst()) {
  1670. do {
  1671. SyncRecord record = createSyncRecord(cursor);
  1672. recordList.add(record);
  1673. } while (cursor.moveToNext());
  1674. }
  1675. cursor.close();
  1676. }
  1677. }
  1678. // return record list
  1679. db.close();
  1680. return recordList;
  1681. }
  1682. /**
  1683. * Attacks per BSSID
  1684. * @param filter (LogFilter) query filter
  1685. * @return ArrayList<PlotComparisonItem>
  1686. */
  1687. public synchronized ArrayList<PlotComparisonItem> attacksPerBSSID(LogFilter filter) {
  1688. String filterQuery = this.selectionQueryFromFilter(filter, AttackEntry.COLUMN_NAME_ATTACK_ID);
  1689. String attackPerBSSID_Query = "SELECT " + NetworkEntry.COLUMN_NAME_BSSID + " , " + "COUNT( " + AttackEntry.COLUMN_NAME_ATTACK_ID + " ) " + " "
  1690. + " FROM " + AttackEntry.TABLE_NAME + " a " + " , " + NetworkEntry.TABLE_NAME
  1691. + " WHERE " + " a." + AttackEntry.COLUMN_NAME_ATTACK_ID + " IN " + " ( " + filterQuery + " ) "
  1692. + " GROUP BY " + NetworkEntry.TABLE_NAME + "." + NetworkEntry.COLUMN_NAME_BSSID;
  1693. SQLiteDatabase db = this.getReadableDatabase();
  1694. Cursor cursor = db.rawQuery(attackPerBSSID_Query, null);
  1695. ArrayList<PlotComparisonItem> plots = new ArrayList<PlotComparisonItem>();
  1696. int counter = 0;
  1697. if (cursor.moveToFirst()) {
  1698. do {
  1699. String title = cursor.getString(0); // COLUMN_NAME_BSSID
  1700. double value = cursor.getDouble(1); // COUNT
  1701. if (value == 0.) continue;
  1702. PlotComparisonItem plotItem = new PlotComparisonItem(title, this.getColor(counter), 0. , value);
  1703. plots.add(plotItem);
  1704. counter++;
  1705. } while (cursor.moveToNext());
  1706. }
  1707. cursor.close();
  1708. db.close();
  1709. return plots;
  1710. }
  1711. /**
  1712. * Inserts the given devices in the database with save.
  1713. * @param devices list of {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s
  1714. */
  1715. public void insertSyncDevices(List<SyncDevice> devices){
  1716. SQLiteDatabase db = this.getWritableDatabase();
  1717. db.beginTransaction();
  1718. try {
  1719. for (SyncDevice device : devices){
  1720. insertSyncDevice(device, db);
  1721. }
  1722. db.setTransactionSuccessful();
  1723. } finally {
  1724. db.endTransaction();
  1725. }
  1726. db.close(); // Closing database connection
  1727. }
  1728. /**
  1729. * Inserts the given dives in the given SQLite Database without save.
  1730. * @param device {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}
  1731. * @param db {@link android.database.sqlite.SQLiteDatabase}
  1732. */
  1733. private void insertSyncDevice(SyncDevice device, SQLiteDatabase db){
  1734. ContentValues recordValues = new ContentValues();
  1735. recordValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_ID, device.getDeviceID());
  1736. recordValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_TIMESTAMP, device.getLast_sync_timestamp());
  1737. recordValues.put(SyncDeviceEntry.COLUMN_NAME_HIGHEST_ATTACK_ID, device.getHighest_attack_id());
  1738. // Inserting Rows
  1739. db.insertWithOnConflict(SyncDeviceEntry.TABLE_NAME, null, recordValues, SQLiteDatabase.CONFLICT_REPLACE);
  1740. }
  1741. /** Returns the color for the given index
  1742. * @return int color*/
  1743. public Integer getColor(int index) {
  1744. return ColorSequenceGenerator.getColorForIndex(index);
  1745. }
  1746. }