HostageDBOpenHelper.java 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190
  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 deletePacketQuery = "DELETE FROM " +PacketEntry.TABLE_NAME + " WHERE "+ PacketEntry.TABLE_NAME + "."+ PacketEntry.COLUMN_NAME_ATTACK_ID+" in ( ";
  1157. deletePacketQuery = deletePacketQuery + selectQuery + " )";
  1158. String deleteAttacksQuery = "DELETE FROM " +AttackEntry.TABLE_NAME + " WHERE "+ AttackEntry.TABLE_NAME + "."+ AttackEntry.COLUMN_NAME_ATTACK_ID+" in ( ";
  1159. deleteAttacksQuery =deleteAttacksQuery + selectQuery + " )";
  1160. SQLiteDatabase db = this.getReadableDatabase();
  1161. db.execSQL(deletePacketQuery);
  1162. db.execSQL(deleteAttacksQuery);
  1163. db.close();
  1164. }
  1165. public ArrayList<MessageRecord> getMessageRecords(AttackRecord attackRecord , SQLiteDatabase db){
  1166. ArrayList<MessageRecord> mr = new ArrayList<MessageRecord>();
  1167. String selectQuery = "SELECT * FROM " + PacketEntry.TABLE_NAME + " WHERE " + PacketEntry.COLUMN_NAME_ATTACK_ID + " = " + attackRecord.getAttack_id();
  1168. boolean createdDB = false;
  1169. if (db == null){
  1170. db = this.getReadableDatabase();
  1171. createdDB = true;
  1172. }
  1173. Cursor cursor = db.rawQuery(selectQuery, null);
  1174. if (cursor.moveToFirst()) {
  1175. do {
  1176. MessageRecord record = createMessageRecord(cursor);
  1177. mr.add(record);
  1178. } while (cursor.moveToNext());
  1179. }
  1180. cursor.close();
  1181. if (createdDB) db.close();
  1182. return mr;
  1183. }
  1184. /**
  1185. * Creates a {@link MessageRecord} from a Cursor. If the cursor does not show to a
  1186. * valid data structure a runtime exception is thrown.
  1187. *
  1188. * @param cursor
  1189. * @return Returns the created {@link MessageRecord} .
  1190. */
  1191. private synchronized MessageRecord createMessageRecord(Cursor cursor) {
  1192. MessageRecord record = new MessageRecord();
  1193. record.setId(Integer.parseInt(cursor.getString(0)));
  1194. record.setAttack_id(cursor.getLong(1));
  1195. record.setType(MessageRecord.TYPE.valueOf(cursor.getString(2)));
  1196. record.setTimestamp(cursor.getLong(3));
  1197. record.setPacket(cursor.getString(4));
  1198. return record;
  1199. }
  1200. /**
  1201. * Creates a {@link AttackRecord} from a Cursor. If the cursor does not show to a
  1202. * valid data structure a runtime exception is thrown.
  1203. *
  1204. * @param cursor
  1205. * @return Returns the created {@link AttackRecord} .
  1206. */
  1207. private synchronized AttackRecord createAttackRecord(Cursor cursor) {
  1208. AttackRecord record = new AttackRecord();
  1209. record.setAttack_id(cursor.getLong(0));
  1210. record.setProtocol(cursor.getString(1));
  1211. record.setExternalIP(cursor.getString(2));
  1212. record.setLocalIP(cursor.getString(3));
  1213. record.setLocalPort(Integer.parseInt(cursor.getString(4)));
  1214. record.setRemoteIP(cursor.getString(5));
  1215. record.setRemotePort(Integer.parseInt(cursor.getString(6)));
  1216. record.setWasInternalAttack(cursor.getInt(7) == 1);
  1217. record.setBssid(cursor.getString(8));
  1218. record.setSync_id(cursor.getLong(9));
  1219. record.setDevice(cursor.getString(10));
  1220. return record;
  1221. }
  1222. /**
  1223. * Creates a {@link SyncRecord} from a Cursor. If the cursor does not show to a
  1224. * valid data structure a runtime exception is thrown.
  1225. *
  1226. * @param cursor
  1227. * @return Returns the created {@link SyncRecord} .
  1228. */
  1229. private synchronized SyncRecord createSyncRecord(Cursor cursor, SQLiteDatabase db){
  1230. AttackRecord attackRecord = this.createAttackRecord(cursor);
  1231. SyncRecord record = new SyncRecord(attackRecord);
  1232. ArrayList<MessageRecord> mr = this.getMessageRecords(attackRecord,db);
  1233. record.setMessageRecords(mr);
  1234. return record;
  1235. }
  1236. /**
  1237. * Creates a {@link Record} from a Cursor. If the cursor does not show to a
  1238. * valid data structure a runtime exception is thrown.
  1239. *
  1240. * @param cursor
  1241. * @return Returns the created {@link Record} .
  1242. */
  1243. private synchronized Record createRecord(Cursor cursor) {
  1244. Record record = new Record();
  1245. record.setId(Integer.parseInt(cursor.getString(0)));
  1246. record.setAttack_id(cursor.getLong(1));
  1247. record.setType(TYPE.valueOf(cursor.getString(2)));
  1248. record.setTimestamp(cursor.getLong(3));
  1249. record.setPacket(cursor.getString(4));
  1250. record.setProtocol(cursor.getString(5));
  1251. record.setExternalIP(cursor.getString(6));
  1252. record.setLocalIP(cursor.getString(7));
  1253. record.setLocalPort(Integer.parseInt(cursor.getString(8)));
  1254. record.setRemoteIP(cursor.getString(9));
  1255. record.setRemotePort(Integer.parseInt(cursor.getString(10)));
  1256. record.setWasInternalAttack(Integer.parseInt(cursor.getString(11)) == 1);
  1257. record.setBssid(cursor.getString(12));
  1258. record.setDevice(cursor.getString(cursor.getColumnIndex(AttackEntry.COLUMN_NAME_DEVICE)));
  1259. record.setSync_ID(cursor.getLong(cursor.getColumnIndex(AttackEntry.COLUMN_NAME_SYNC_ID)));
  1260. record.setSsid(cursor.getString(15));
  1261. record.setLatitude(Double.parseDouble(cursor.getString(16)));
  1262. record.setLongitude(Double.parseDouble(cursor.getString(17)));
  1263. record.setAccuracy(Float.parseFloat(cursor.getString(18)));
  1264. record.setTimestampLocation(cursor.getLong(19));
  1265. return record;
  1266. }
  1267. /**
  1268. * Gets all received {@link Record Records} for the specified information in
  1269. * the LogFilter ordered by date.
  1270. *
  1271. * @return A ArrayList with all received {@link Record Records} for the
  1272. * LogFilter.
  1273. */
  1274. public synchronized ArrayList<Record> getRecordsForFilter(LogFilter filter) {
  1275. ArrayList<Record> recordList = new ArrayList<Record>();
  1276. String selectQuery = this.selectionQueryFromFilter(filter, "*");
  1277. SQLiteDatabase db = this.getReadableDatabase();
  1278. Cursor cursor = db.rawQuery(selectQuery, null);
  1279. // looping through all rows and adding to list
  1280. if (cursor.moveToFirst()) {
  1281. do {
  1282. Record record = createRecord(cursor);
  1283. // Adding record to list
  1284. recordList.add(record);
  1285. } while (cursor.moveToNext());
  1286. }
  1287. cursor.close();
  1288. // return record list
  1289. db.close();
  1290. return recordList;
  1291. }
  1292. /**
  1293. * Returns the query for the given filter.
  1294. * @param filter (LogFilter)
  1295. * @param selectionString (String) for everything: "*"
  1296. * @return (String) query string
  1297. */
  1298. public String selectionQueryFromFilter(LogFilter filter, String selectionString)
  1299. {
  1300. String selectQuery = "SELECT " + selectionString + " FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " JOIN " + NetworkEntry.TABLE_NAME + " USING " + "(" + NetworkEntry.COLUMN_NAME_BSSID
  1301. + ")";
  1302. if (filter == null) return selectQuery;
  1303. // TIMESTAMPS
  1304. selectQuery = selectQuery + " WHERE " + PacketEntry.TABLE_NAME + "." + PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP;
  1305. selectQuery = selectQuery + " < " + filter.getBelowTimestamp();
  1306. selectQuery = selectQuery + " AND " + PacketEntry.TABLE_NAME + "." + PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP;
  1307. selectQuery = selectQuery + " > " + filter.getAboveTimestamp();
  1308. if (filter.getBSSIDs() != null && filter.getBSSIDs().size() > 0) {
  1309. selectQuery = selectQuery + " AND ";
  1310. selectQuery = selectQuery + filter.getBSSIDQueryStatement(NetworkEntry.TABLE_NAME, NetworkEntry.COLUMN_NAME_BSSID);
  1311. }
  1312. if (filter.getESSIDs() != null && filter.getESSIDs().size() > 0) {
  1313. selectQuery = selectQuery + " AND ";
  1314. selectQuery = selectQuery + filter.getESSIDQueryStatement(NetworkEntry.TABLE_NAME, NetworkEntry.COLUMN_NAME_SSID);
  1315. }
  1316. if (filter.getProtocols() != null && filter.getProtocols().size() > 0) {
  1317. selectQuery = selectQuery + " AND ";
  1318. selectQuery = selectQuery + filter.getProtocolsQueryStatement(AttackEntry.TABLE_NAME, AttackEntry.COLUMN_NAME_PROTOCOL);
  1319. }
  1320. selectQuery = selectQuery + " GROUP BY " + PacketEntry.TABLE_NAME + "." + PacketEntry.COLUMN_NAME_ATTACK_ID;
  1321. if (filter.getSorttype() == LogFilter.SortType.packet_timestamp) {
  1322. // DESC
  1323. selectQuery = selectQuery + " ORDER BY " + filter.getSorttype() + " DESC";
  1324. } else {
  1325. selectQuery = selectQuery + " ORDER BY " + filter.getSorttype();
  1326. }
  1327. System.out.println(selectQuery);
  1328. return selectQuery;
  1329. }
  1330. /**
  1331. * Returns the Conversation of a specific attack id
  1332. *
  1333. * @param attack_id Tha attack id to match the query against.
  1334. *
  1335. * @return A arraylist with all {@link Record Records}s for an attack id.
  1336. */
  1337. public synchronized ArrayList<Record> getConversationForAttackID(long attack_id) {
  1338. ArrayList<Record> recordList = new ArrayList<Record>();
  1339. String selectQuery = "SELECT * FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " JOIN " + NetworkEntry.TABLE_NAME + " USING " + "(" + NetworkEntry.COLUMN_NAME_BSSID
  1340. + ")" + " WHERE " + PacketEntry.TABLE_NAME + "." + PacketEntry.COLUMN_NAME_ATTACK_ID + " = " + attack_id;
  1341. SQLiteDatabase db = this.getReadableDatabase();
  1342. Cursor cursor = db.rawQuery(selectQuery, null);
  1343. if (cursor.moveToFirst()) {
  1344. do {
  1345. Record record = createRecord(cursor);
  1346. recordList.add(record);
  1347. } while (cursor.moveToNext());
  1348. }
  1349. cursor.close();
  1350. db.close();
  1351. return recordList;
  1352. }
  1353. /**
  1354. * Gets a single {@link Record} with the given attack id from the database.
  1355. *
  1356. * @param attack_id
  1357. * The attack id of the {@link Record};
  1358. * @return The {@link Record}.
  1359. */
  1360. public synchronized Record getRecordOfAttackId(long attack_id) {
  1361. String selectQuery = "SELECT * FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " JOIN " + NetworkEntry.TABLE_NAME + " USING " + "(" + NetworkEntry.COLUMN_NAME_BSSID
  1362. + ")" + " WHERE " + PacketEntry.TABLE_NAME + "." + PacketEntry.COLUMN_NAME_ATTACK_ID + " = " + attack_id + " GROUP BY " + PacketEntry.TABLE_NAME + "." + PacketEntry.COLUMN_NAME_ID;
  1363. SQLiteDatabase db = this.getReadableDatabase();
  1364. Cursor cursor = db.rawQuery(selectQuery, null);
  1365. Record record = null;
  1366. if (cursor.moveToFirst()) {
  1367. record = createRecord(cursor);
  1368. }
  1369. cursor.close();
  1370. // return record list
  1371. db.close();
  1372. return record;
  1373. }
  1374. /**
  1375. * Gets a single {@link Record} with the given ID from the database.
  1376. *
  1377. * @param id
  1378. * The ID of the {@link Record};
  1379. * @return The {@link Record}.
  1380. */
  1381. public synchronized Record getRecord(int id) {
  1382. String selectQuery = "SELECT * FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " JOIN " + NetworkEntry.TABLE_NAME + " USING " + "(" + PacketEntry.COLUMN_NAME_ATTACK_ID
  1383. + ")" + " WHERE " + PacketEntry.TABLE_NAME + "." + PacketEntry.COLUMN_NAME_ID + " = " + id;
  1384. SQLiteDatabase db = this.getReadableDatabase();
  1385. Cursor cursor = db.rawQuery(selectQuery, null);
  1386. Record record = null;
  1387. if (cursor.moveToFirst()) {
  1388. record = createRecord(cursor);
  1389. }
  1390. cursor.close();
  1391. db.close();
  1392. // return contact
  1393. return record;
  1394. }
  1395. /**
  1396. * Gets all {@link Record Records} saved in the database.
  1397. *
  1398. * @return A ArrayList of all the {@link Record Records} in the Database.
  1399. */
  1400. public synchronized ArrayList<Record> getAllRecords() {
  1401. ArrayList<Record> recordList = new ArrayList<Record>();
  1402. // Select All Query
  1403. String selectQuery = "SELECT * FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " JOIN " + NetworkEntry.TABLE_NAME + " USING " + "(" + NetworkEntry.COLUMN_NAME_BSSID
  1404. + ")";
  1405. SQLiteDatabase db = this.getWritableDatabase();
  1406. Cursor cursor = db.rawQuery(selectQuery, null);
  1407. Log.i("Database", "Start loop");
  1408. // looping through all rows and adding to list
  1409. if (cursor.moveToFirst()) {
  1410. do {
  1411. Log.i("Database", "Add Record");
  1412. Record record = createRecord(cursor);
  1413. // Adding record to list
  1414. recordList.add(record);
  1415. } while (cursor.moveToNext());
  1416. }
  1417. cursor.close();
  1418. db.close();
  1419. // return record list
  1420. return recordList;
  1421. }
  1422. /**
  1423. * Gets all non duplicate Records For the key BSSID.
  1424. *
  1425. * @return A ArrayList with received Records.
  1426. */
  1427. public synchronized ArrayList<String> getUniqueBSSIDRecords() {
  1428. return this.getUniqueDataEntryForKeyType(NetworkEntry.COLUMN_NAME_BSSID, NetworkEntry.TABLE_NAME);
  1429. }
  1430. /**
  1431. * Gets all non duplicate Records For the key ESSID.
  1432. *
  1433. * @return A ArrayList with received Records.
  1434. */
  1435. public synchronized ArrayList<String> getUniqueESSIDRecords() {
  1436. return this.getUniqueDataEntryForKeyType(NetworkEntry.COLUMN_NAME_SSID, NetworkEntry.TABLE_NAME);
  1437. }
  1438. public synchronized ArrayList<String> getUniqueESSIDRecordsForProtocol(String protocol) {
  1439. return this.getUniqueIDForProtocol(NetworkEntry.COLUMN_NAME_SSID, protocol);
  1440. }
  1441. public synchronized ArrayList<String> getUniqueBSSIDRecordsForProtocol(String protocol) {
  1442. return this.getUniqueIDForProtocol(NetworkEntry.COLUMN_NAME_BSSID, protocol);
  1443. }
  1444. private synchronized ArrayList<String> getUniqueIDForProtocol(String id, String protocol) {
  1445. ArrayList<String> recordList = new ArrayList<String>();
  1446. String selectQuery = "SELECT DISTINCT " + id + " FROM " + AttackEntry.TABLE_NAME + " JOIN " + NetworkEntry.TABLE_NAME + " USING " + "(" + NetworkEntry.COLUMN_NAME_BSSID + ") " + " WHERE "
  1447. + AttackEntry.TABLE_NAME + "." + AttackEntry.COLUMN_NAME_PROTOCOL + " = " + "'" + protocol + "'" + " ORDER BY " + "'"+id+"'"; // " NATURAL JOIN "
  1448. // +
  1449. // TABLE_ATTACK_INFO
  1450. // +
  1451. // " NATURAL JOIN "
  1452. // +
  1453. // TABLE_BSSIDS
  1454. // +
  1455. // " NATURAL JOIN "
  1456. // +
  1457. // TABLE_PORTS
  1458. // +
  1459. // ORDERED BY TIME
  1460. System.out.println(selectQuery);
  1461. SQLiteDatabase db = this.getReadableDatabase();
  1462. Cursor cursor = db.rawQuery(selectQuery, null);
  1463. // looping through all rows and adding to list
  1464. if (cursor.moveToFirst()) {
  1465. do {
  1466. String record = cursor.getString(0);
  1467. recordList.add(record);
  1468. } while (cursor.moveToNext());
  1469. }
  1470. cursor.close();
  1471. // return record list
  1472. db.close();
  1473. return recordList;
  1474. }
  1475. /**
  1476. * Gets all non duplicate Data Entry For a specific KeyType ( e.g. BSSIDs).
  1477. *
  1478. * @return A ArrayList with received Records.
  1479. */
  1480. public synchronized ArrayList<String> getUniqueDataEntryForKeyType(String keyType, String table) {
  1481. ArrayList<String> recordList = new ArrayList<String>();
  1482. // String selectQuery = "SELECT * FROM " + TABLE_RECORDS +
  1483. // " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " +
  1484. // TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS;
  1485. String selectQuery = "SELECT DISTINCT " + keyType + " FROM " + table + " ORDER BY " + keyType; // " NATURAL JOIN "
  1486. // +
  1487. // TABLE_ATTACK_INFO
  1488. // +
  1489. // " NATURAL JOIN "
  1490. // +
  1491. // TABLE_BSSIDS
  1492. // +
  1493. // " NATURAL JOIN "
  1494. // +
  1495. // TABLE_PORTS
  1496. // +
  1497. // ORDERED BY TIME
  1498. System.out.println(selectQuery);
  1499. SQLiteDatabase db = this.getReadableDatabase();
  1500. Cursor cursor = db.rawQuery(selectQuery, null);
  1501. // looping through all rows and adding to list
  1502. if (cursor.moveToFirst()) {
  1503. do {
  1504. String record = cursor.getString(0);
  1505. recordList.add(record);
  1506. } while (cursor.moveToNext());
  1507. }
  1508. cursor.close();
  1509. // return record list
  1510. db.close();
  1511. return recordList;
  1512. }
  1513. //TODO PROFILE DATABASE QUERIES - STILL NEEDED?
  1514. /**
  1515. * Retrieves all the profiles from the database
  1516. *
  1517. * @return list of profiles
  1518. */
  1519. public synchronized List<Profile> getAllProfiles() {
  1520. List<Profile> profiles = new LinkedList<Profile>();
  1521. // Select All Query
  1522. String selectQuery = "SELECT * FROM " + ProfileEntry.TABLE_NAME;
  1523. SQLiteDatabase db = this.getWritableDatabase();
  1524. Cursor cursor = db.rawQuery(selectQuery, null);
  1525. // looping through all rows and adding to list
  1526. if (cursor.moveToFirst()) {
  1527. do {
  1528. Profile profile = new Profile(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getInt(5) == 1);
  1529. if (cursor.getInt(6) == 1) {
  1530. profile.mActivated = true;
  1531. }
  1532. profile.mIconName = cursor.getString(4);
  1533. // Adding record to list
  1534. profiles.add(profile);
  1535. } while (cursor.moveToNext());
  1536. }
  1537. cursor.close();
  1538. db.close();
  1539. // return record list
  1540. return profiles;
  1541. }
  1542. /**
  1543. * Persists the given profile into the database
  1544. *
  1545. * @param profile
  1546. * the profile which should be persisted
  1547. *
  1548. * @return
  1549. */
  1550. public synchronized long persistProfile(Profile profile) {
  1551. SQLiteDatabase db = this.getWritableDatabase();
  1552. ContentValues values = new ContentValues();
  1553. if (profile.mId != -1) {
  1554. values.put(ProfileEntry.COLUMN_NAME_PROFILE_ID, profile.mId);
  1555. }
  1556. values.put(ProfileEntry.COLUMN_NAME_PROFILE_NAME, profile.mLabel);
  1557. values.put(ProfileEntry.COLUMN_NAME_PROFILE_DESCRIPTION, profile.mText);
  1558. values.put(ProfileEntry.COLUMN_NAME_PROFILE_ICON, profile.mIconPath);
  1559. values.put(ProfileEntry.COLUMN_NAME_PROFILE_ICON_NAME, profile.mIconName);
  1560. values.put(ProfileEntry.COLUMN_NAME_PROFILE_ACTIVE, profile.mActivated);
  1561. values.put(ProfileEntry.COLUMN_NAME_PROFILE_EDITABLE, profile.mEditable);
  1562. return db.replace(ProfileEntry.TABLE_NAME, null, values);
  1563. }
  1564. /**
  1565. * private static final String CREATE_PROFILE_TABLE = "CREATE TABLE " +
  1566. * TABLE_PROFILES + "(" + KEY_PROFILE_ID +
  1567. * " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_PROFILE_NAME + " TEXT," +
  1568. * KEY_PROFILE_DESCRIPTION + " TEXT," + KEY_PROFILE_ICON + " TEXT," +
  1569. * KEY_PROFILE_ICON_ID + " INTEGER," + KEY_PROFILE_EDITABLE + " INTEGER," +
  1570. * KEY_PROFILE_ACTIVE + " INTEGER" + ")";
  1571. */
  1572. public synchronized Profile getProfile(int id) {
  1573. String selectQuery = "SELECT * FROM " + ProfileEntry.TABLE_NAME + " WHERE " + ProfileEntry.TABLE_NAME + "." + ProfileEntry.COLUMN_NAME_PROFILE_ID + " = " + id;
  1574. SQLiteDatabase db = this.getReadableDatabase();
  1575. Cursor cursor = db.rawQuery(selectQuery, null);
  1576. Profile profile = null;
  1577. if (cursor.moveToFirst()) {
  1578. profile = new Profile(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getInt(5) == 1);
  1579. if (cursor.getInt(6) == 1) {
  1580. profile.mActivated = true;
  1581. }
  1582. profile.mIconName = cursor.getString(5);
  1583. }
  1584. cursor.close();
  1585. db.close();
  1586. // return contact
  1587. return profile;
  1588. }
  1589. public synchronized void deleteProfile(int id) {
  1590. SQLiteDatabase db = this.getWritableDatabase();
  1591. db.delete(ProfileEntry.TABLE_NAME, ProfileEntry.COLUMN_NAME_PROFILE_ID + "=?", new String[] { String.valueOf(id) });
  1592. db.close();
  1593. }
  1594. /**
  1595. * Gets all received {@link Record Records} for every attack identified by
  1596. * its attack id and ordered by date.
  1597. *
  1598. * @return A ArrayList with all received {@link Record Records} for each
  1599. * attack id in the Database.
  1600. */
  1601. public synchronized ArrayList<Record> getAllReceivedRecordsOfEachAttack() {
  1602. ArrayList<Record> recordList = new ArrayList<Record>();
  1603. String selectQuery = "SELECT * FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " JOIN " + NetworkEntry.TABLE_NAME + " USING " + "(" + NetworkEntry.COLUMN_NAME_BSSID
  1604. + ")" + " WHERE " + PacketEntry.COLUMN_NAME_TYPE + "='RECEIVE'" + " ORDER BY " + PacketEntry.TABLE_NAME + "." + PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP;
  1605. SQLiteDatabase db = this.getReadableDatabase();
  1606. Cursor cursor = db.rawQuery(selectQuery, null);
  1607. // looping through all rows and adding to list
  1608. if (cursor.moveToFirst()) {
  1609. do {
  1610. Record record = createRecord(cursor);
  1611. // Adding record to list
  1612. recordList.add(record);
  1613. } while (cursor.moveToNext());
  1614. }
  1615. cursor.close();
  1616. // return record list
  1617. db.close();
  1618. return recordList;
  1619. }
  1620. /**
  1621. * Returns PlotComparisionItems for attacks per essid.
  1622. * @param filter (LogFilter) filter object
  1623. * @return ArrayList<PlotComparisonItem>
  1624. */
  1625. public synchronized ArrayList<PlotComparisonItem> attacksPerESSID(LogFilter filter) {
  1626. String filterQuery = this.selectionQueryFromFilter(filter, AttackEntry.COLUMN_NAME_ATTACK_ID);
  1627. filterQuery = filterQuery.split("GROUP BY")[0];
  1628. String attackPerESSID_Query = "SELECT " + NetworkEntry.COLUMN_NAME_SSID + " , " + "COUNT( " + " * " + " ) " + " "
  1629. + " FROM " + AttackEntry.TABLE_NAME + " NATURAL JOIN " + NetworkEntry.TABLE_NAME //AttackEntry.TABLE_NAME + " a " + " , " + NetworkEntry.TABLE_NAME
  1630. + " WHERE " + AttackEntry.COLUMN_NAME_ATTACK_ID + " IN " + " ( " + filterQuery + " ) "
  1631. + " GROUP BY " + NetworkEntry.TABLE_NAME+"."+NetworkEntry.COLUMN_NAME_SSID;
  1632. SQLiteDatabase db = this.getReadableDatabase();
  1633. Cursor cursor = db.rawQuery(attackPerESSID_Query, null);
  1634. ArrayList<PlotComparisonItem> plots = new ArrayList<PlotComparisonItem>();
  1635. int counter = 0;
  1636. if (cursor.moveToFirst()) {
  1637. do {
  1638. String title = cursor.getString(0); // COLUMN_NAME_SSID
  1639. double value = cursor.getDouble(1); // COUNT
  1640. if (value == 0.) continue;
  1641. PlotComparisonItem plotItem = new PlotComparisonItem(title, this.getColor(counter), 0. , value);
  1642. plots.add(plotItem);
  1643. counter++;
  1644. } while (cursor.moveToNext());
  1645. }
  1646. cursor.close();
  1647. db.close();
  1648. return plots;
  1649. }
  1650. /**
  1651. * Creates a {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice} from a Cursor. If the cursor does not show to a
  1652. * valid data structure a runtime exception is thrown.
  1653. *
  1654. * @param cursor the cursor
  1655. * @return Returns the created {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice} .
  1656. */
  1657. private synchronized SyncDevice createSyncDevice(Cursor cursor) {
  1658. SyncDevice record = new SyncDevice();
  1659. record.setDeviceID(cursor.getString(0));
  1660. record.setLast_sync_timestamp(cursor.getLong(1));
  1661. record.setHighest_attack_id(cursor.getLong(2));
  1662. return record;
  1663. }
  1664. /**
  1665. * Returns all missing / newly inserted and updated {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s.
  1666. * @param oldDevices array of {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s
  1667. * @param includeMissing boolean
  1668. * @return array of {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s
  1669. */
  1670. /*
  1671. public ArrayList<SyncDevice> getUpdatedDevicesFor(List<SyncDevice> oldDevices, boolean includeMissing){
  1672. HashMap<String, Long> oldDeviceMap = new HashMap<String, Long>();
  1673. for (SyncDevice d : oldDevices){
  1674. oldDeviceMap.put(d.getDeviceID(),d.getHighest_attack_id());
  1675. }
  1676. ArrayList<SyncDevice> recordList = new ArrayList<SyncDevice>();
  1677. String selectQuery = "SELECT * FROM " + SyncDeviceEntry.TABLE_NAME;
  1678. SQLiteDatabase db = this.getReadableDatabase();
  1679. Cursor cursor = db.rawQuery(selectQuery, null);
  1680. // looping through all rows and adding to list
  1681. if (cursor.moveToFirst()) {
  1682. do {
  1683. SyncDevice record = createSyncDevice(cursor);
  1684. // Adding record to list
  1685. if (oldDeviceMap.containsKey(record.getDeviceID())){
  1686. Long oldSyncId = oldDeviceMap.get(record.getDeviceID());
  1687. if (oldSyncId < record.getHighest_attack_id()){
  1688. recordList.add(record);
  1689. }
  1690. } else {
  1691. if (includeMissing)
  1692. recordList.add(record);
  1693. }
  1694. } while (cursor.moveToNext());
  1695. }
  1696. cursor.close();
  1697. // return record list
  1698. db.close();
  1699. return recordList;
  1700. }*/
  1701. /**
  1702. * Returns all missing / newly inserted and updated {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s.
  1703. * @param oldDeviceMap map with device id and max sync_id for the device
  1704. * @param includeMissing boolean
  1705. * @return array of {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s
  1706. */
  1707. public synchronized ArrayList<SyncDevice> getUpdatedDevicesFor(HashMap<String, Long> oldDeviceMap, boolean includeMissing){
  1708. ArrayList<SyncDevice> recordList = new ArrayList<SyncDevice>();
  1709. String selectQuery = "SELECT * FROM " + SyncDeviceEntry.TABLE_NAME;
  1710. SQLiteDatabase db = this.getReadableDatabase();
  1711. Cursor cursor = db.rawQuery(selectQuery, null);
  1712. boolean actualiseOwnDevice = false;
  1713. if (oldDeviceMap.keySet().contains(currentDevice().getDeviceID()) || includeMissing){
  1714. actualiseOwnDevice = true;
  1715. }
  1716. // looping through all rows and adding to list
  1717. if (cursor.moveToFirst()) {
  1718. do {
  1719. SyncDevice record = createSyncDevice(cursor);
  1720. // Adding record to list
  1721. if (currentDevice().getDeviceID().equals(record.getDeviceID()) && actualiseOwnDevice)
  1722. record.setHighest_attack_id(currentDevice().getHighest_attack_id());
  1723. if (oldDeviceMap.containsKey(record.getDeviceID())){
  1724. Long oldSyncId = oldDeviceMap.get(record.getDeviceID());
  1725. if (oldSyncId < record.getHighest_attack_id()){
  1726. recordList.add(record);
  1727. }
  1728. } else {
  1729. if (includeMissing)
  1730. recordList.add(record);
  1731. }
  1732. } while (cursor.moveToNext());
  1733. }
  1734. cursor.close();
  1735. // return record list
  1736. db.close();
  1737. return recordList;
  1738. }
  1739. /**
  1740. * Returns all device ids.
  1741. * @return list of all device ids.
  1742. */
  1743. public synchronized ArrayList<String> getAllDevicesIds(){
  1744. String selectQuery = "SELECT "+ SyncDeviceEntry.COLUMN_NAME_DEVICE_ID+" FROM " + SyncDeviceEntry.TABLE_NAME;
  1745. SQLiteDatabase db = this.getReadableDatabase();
  1746. Cursor cursor = db.rawQuery(selectQuery, null);
  1747. ArrayList<String> ids = new ArrayList<String>();
  1748. // looping through all rows and adding to list
  1749. if (cursor.moveToFirst()) {
  1750. do {
  1751. String s = cursor.getString(0);
  1752. ids.add(s);
  1753. } while (cursor.moveToNext());
  1754. }
  1755. cursor.close();
  1756. // return record list
  1757. db.close();
  1758. return ids;
  1759. }
  1760. /***
  1761. * Returns all missing devices ids
  1762. * @param devices owned device ids
  1763. * @return list of missing devices ids
  1764. */
  1765. public synchronized ArrayList<String> getMissingDeviceIds(ArrayList<String> devices){
  1766. ArrayList<String> ids = new ArrayList<String>();
  1767. String prefix = " D WHERE " + SyncDeviceEntry.COLUMN_NAME_DEVICE_ID + " NOT IN ";
  1768. String selectQuery = "SELECT "+ SyncDeviceEntry.COLUMN_NAME_DEVICE_ID +" FROM " + SyncDeviceEntry.TABLE_NAME + this.arrayToSQLString(devices,prefix);
  1769. SQLiteDatabase db = this.getReadableDatabase();
  1770. Cursor cursor = db.rawQuery(selectQuery, null);
  1771. if (cursor.moveToFirst()) {
  1772. do {
  1773. String deviceID = cursor.getString(0);
  1774. ids.add(deviceID);
  1775. } while (cursor.moveToNext());
  1776. }
  1777. cursor.close();
  1778. db.close();
  1779. return ids;
  1780. }
  1781. /**
  1782. * Returns all new {@link de.tudarmstadt.informatik.hostage.logging.AttackRecord}s for the given devices (including all missing devices).
  1783. * @param deviceMap map of device id and max sync_id of it
  1784. * @param includeMissingDevices boolean
  1785. * @return list of {@link de.tudarmstadt.informatik.hostage.logging.AttackRecord}s
  1786. */
  1787. public synchronized ArrayList<SyncRecord> getUnsyncedAttacksFor(HashMap<String,Long> deviceMap, boolean includeMissingDevices){
  1788. ArrayList<SyncDevice> updatedDevices = this.getUpdatedDevicesFor(deviceMap, includeMissingDevices);
  1789. ArrayList<SyncRecord> recordList = new ArrayList<SyncRecord>();
  1790. SQLiteDatabase db = this.getReadableDatabase();
  1791. SyncDevice currentDevice = currentDevice();
  1792. String own_device_id = currentDevice.getDeviceID();
  1793. for (SyncDevice sDevice : updatedDevices){
  1794. String deviceID = sDevice.getDeviceID();
  1795. Long maxID = deviceMap.get(deviceID);
  1796. long checkId = -1;
  1797. if (maxID != null) checkId = maxID.longValue();
  1798. String selectQuery = "SELECT * FROM " + AttackEntry.TABLE_NAME + " A "
  1799. + " WHERE "
  1800. +" ( "
  1801. + " A." + AttackEntry.COLUMN_NAME_DEVICE + " = " + "'" + deviceID + "'"
  1802. + " AND " + " A." + AttackEntry.COLUMN_NAME_SYNC_ID + " > " + checkId
  1803. + " ) "
  1804. //+ " GROUP BY " + AttackEntry.TABLE_NAME + "." + AttackEntry.COLUMN_NAME_DEVICE
  1805. + " ORDER BY " + " A" + "." + AttackEntry.COLUMN_NAME_SYNC_ID + " DESC ";
  1806. Cursor cursor = db.rawQuery(selectQuery, null);
  1807. // looping through all rows and adding to list
  1808. if (cursor != null){
  1809. if (cursor.moveToFirst()) {
  1810. do {
  1811. SyncRecord record = createSyncRecord(cursor , db);
  1812. recordList.add(record);
  1813. } while (cursor.moveToNext());
  1814. }
  1815. cursor.close();
  1816. }
  1817. }
  1818. // return record list
  1819. db.close();
  1820. return recordList;
  1821. }
  1822. /**
  1823. * Attacks per BSSID
  1824. * @param filter (LogFilter) query filter
  1825. * @return ArrayList<PlotComparisonItem>
  1826. */
  1827. public synchronized ArrayList<PlotComparisonItem> attacksPerBSSID(LogFilter filter) {
  1828. String filterQuery = this.selectionQueryFromFilter(filter, AttackEntry.COLUMN_NAME_ATTACK_ID);
  1829. filterQuery = filterQuery.split("GROUP BY")[0];
  1830. String attackPerBSSID_Query = "SELECT " + AttackEntry.COLUMN_NAME_BSSID + " , " + "COUNT( " + "*" + " ) " + " "
  1831. + " FROM " + AttackEntry.TABLE_NAME + " a "
  1832. + " WHERE " + " a." + AttackEntry.COLUMN_NAME_ATTACK_ID + " IN " + " ( " + filterQuery + " ) "
  1833. + " GROUP BY " + AttackEntry.COLUMN_NAME_BSSID;
  1834. SQLiteDatabase db = this.getReadableDatabase();
  1835. Cursor cursor = db.rawQuery(attackPerBSSID_Query, null);
  1836. ArrayList<PlotComparisonItem> plots = new ArrayList<PlotComparisonItem>();
  1837. int counter = 0;
  1838. if (cursor.moveToFirst()) {
  1839. do {
  1840. String title = cursor.getString(0); // COLUMN_NAME_BSSID
  1841. double value = cursor.getDouble(1); // COUNT
  1842. if (value == 0.) continue;
  1843. PlotComparisonItem plotItem = new PlotComparisonItem(title, this.getColor(counter), 0. , value);
  1844. plots.add(plotItem);
  1845. counter++;
  1846. } while (cursor.moveToNext());
  1847. }
  1848. cursor.close();
  1849. db.close();
  1850. return plots;
  1851. }
  1852. /**
  1853. * Inserts the given devices in the database with save.
  1854. * @param devices list of {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s
  1855. */
  1856. public synchronized void insertSyncDevices(List<SyncDevice> devices){
  1857. SQLiteDatabase db = this.getWritableDatabase();
  1858. db.beginTransaction();
  1859. try {
  1860. for (SyncDevice device : devices){
  1861. insertSyncDevice(device, db);
  1862. }
  1863. db.setTransactionSuccessful();
  1864. } finally {
  1865. db.endTransaction();
  1866. }
  1867. db.close(); // Closing database connection
  1868. }
  1869. /**
  1870. * Inserts the given dives in the given SQLite Database without save.
  1871. * @param device {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}
  1872. * @param db {@link android.database.sqlite.SQLiteDatabase}
  1873. */
  1874. private void insertSyncDevice(SyncDevice device, SQLiteDatabase db){
  1875. ContentValues recordValues = new ContentValues();
  1876. recordValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_ID, device.getDeviceID());
  1877. recordValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_TIMESTAMP, device.getLast_sync_timestamp());
  1878. recordValues.put(SyncDeviceEntry.COLUMN_NAME_HIGHEST_ATTACK_ID, device.getHighest_attack_id());
  1879. // Inserting Rows
  1880. db.insertWithOnConflict(SyncDeviceEntry.TABLE_NAME, null, recordValues, SQLiteDatabase.CONFLICT_REPLACE);
  1881. }
  1882. /** Returns the color for the given index
  1883. * @return int color*/
  1884. public Integer getColor(int index) {
  1885. return ColorSequenceGenerator.getColorForIndex(index);
  1886. }
  1887. }