HostageDBOpenHelper.java 81 KB

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