HostageDBOpenHelper.java 81 KB

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