HostageDBOpenHelper.java 84 KB

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