HostageDBOpenHelper.java 80 KB

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