HostageDBOpenHelper.java 72 KB

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