HostageDBOpenHelper.java 82 KB

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