HostageDBOpenHelper.java 81 KB

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