HostageDBOpenHelper.java 80 KB

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