HostageDBOpenHelper.java 82 KB

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