HostageDBOpenHelper.java 83 KB

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