HostageDBOpenHelper.java 81 KB

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