HostageDBOpenHelper.java 66 KB

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