HostageDBOpenHelper.java 84 KB

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