HostageDBOpenHelper.java 81 KB

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