DatabaseHandler.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. package de.tudarmstadt.informatik.hostage.logging;
  2. import java.net.InetAddress;
  3. import java.net.UnknownHostException;
  4. import java.util.ArrayList;
  5. import de.tudarmstadt.informatik.hostage.logging.Record.TYPE;
  6. import android.content.ContentValues;
  7. import android.content.Context;
  8. import android.database.Cursor;
  9. import android.database.sqlite.SQLiteDatabase;
  10. import android.database.sqlite.SQLiteOpenHelper;
  11. /**
  12. * This class creates SQL tables and handles all access to the database.<br>
  13. * It contains several methods with predefined queries to extract different kinds of information from the database.<br>
  14. * The database contains two tables: {@link #TABLE_RECORDS} and {@link #TABLE_BSSIDS}:<br>
  15. * {@link #TABLE_RECORDS} contains all logging information of a single message record except the SSID.<br>
  16. * {@link #TABLE_BSSIDS} contains the BSSID of all recorded Networks and the corresponding SSID.<br>
  17. * @author Lars Pandikow
  18. *
  19. */
  20. public class DatabaseHandler extends SQLiteOpenHelper {
  21. // All Static variables
  22. // Database Version
  23. private static final int DATABASE_VERSION = 1;
  24. // Database Name
  25. private static final String DATABASE_NAME = "recordManager";
  26. // Contacts table names
  27. private static final String TABLE_RECORDS = "records";
  28. private static final String TABLE_BSSIDS = "bssids";
  29. // Contacts Table Columns names
  30. private static final String KEY_ID = "_id";
  31. private static final String KEY_ATTACK_ID = "attack_id";
  32. private static final String KEY_PROTOCOL = "protocol";
  33. private static final String KEY_TYPE = "type";
  34. private static final String KEY_TIME = "timestamp";
  35. private static final String KEY_EXTERNAL_IP ="externalIP";
  36. private static final String KEY_LOCAL_IP = "localIP";
  37. private static final String KEY_LOCAL_HOSTNAME = "localHostName";
  38. private static final String KEY_LOCAL_PORT = "localPort";
  39. private static final String KEY_REMOTE_IP = "remoteIP";
  40. private static final String KEY_REMOTE_HOSTNAME = "remoteHostName";
  41. private static final String KEY_REMOTE_PORT = "remotePort";
  42. private static final String KEY_BSSID = "_bssid";
  43. private static final String KEY_SSID = "ssid";
  44. private static final String KEY_PACKET = "packet";
  45. // Database sql create statements
  46. private static final String CREATE_RECORD_TABLE = "CREATE TABLE " + TABLE_RECORDS + "(" + KEY_ID
  47. + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_ATTACK_ID + " INTEGER," + KEY_PROTOCOL + " TEXT,"
  48. + KEY_TYPE + " TEXT," + KEY_TIME + " INTEGER," + KEY_EXTERNAL_IP + " TEXT," + KEY_LOCAL_IP
  49. + " BLOB," + KEY_LOCAL_HOSTNAME + " TEXT," + KEY_LOCAL_PORT + " INTEGER," + KEY_REMOTE_IP
  50. + " BLOB," + KEY_REMOTE_HOSTNAME + " TEXT," + KEY_REMOTE_PORT + " INTEGER,"
  51. + KEY_BSSID + " TEXT," + KEY_PACKET + " TEXT,"
  52. + "FOREIGN KEY("+ KEY_BSSID +") REFERENCES " + TABLE_BSSIDS + "("+KEY_BSSID+")" + ")";
  53. private static final String CREATE_BSSID_TABLE = "CREATE TABLE " + TABLE_BSSIDS + "(" + KEY_BSSID
  54. + " TEXT PRIMARY KEY," + KEY_SSID + " TEXT" + ")";
  55. public DatabaseHandler(Context context) {
  56. super(context, DATABASE_NAME, null, DATABASE_VERSION);
  57. }
  58. // Creating Tables
  59. @Override
  60. public void onCreate(SQLiteDatabase db) {
  61. db.execSQL(CREATE_BSSID_TABLE);
  62. db.execSQL(CREATE_RECORD_TABLE);
  63. }
  64. // Upgrading database
  65. @Override
  66. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  67. // Drop older table if existed
  68. db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECORDS);
  69. db.execSQL("DROP TABLE IF EXISTS " + TABLE_BSSIDS);
  70. // Create tables again
  71. onCreate(db);
  72. }
  73. /**
  74. * Adds a given {@link Record} to the database.
  75. * @param record The added {@link Record} .
  76. */
  77. public void addRecord(Record record) {
  78. SQLiteDatabase db = this.getWritableDatabase();
  79. ContentValues bssidValues = new ContentValues();
  80. bssidValues.put(KEY_BSSID, record.getBSSID());
  81. bssidValues.put(KEY_SSID, record.getSSID());
  82. ContentValues recordValues = new ContentValues();
  83. recordValues.put(KEY_ATTACK_ID, record.getAttack_id()); // Log Attack ID
  84. recordValues.put(KEY_PROTOCOL, record.getProtocol().toString());
  85. recordValues.put(KEY_TYPE, record.getType().name()); // Log Type
  86. recordValues.put(KEY_TIME, record.getTimestamp()); // Log Timestamp
  87. recordValues.put(KEY_EXTERNAL_IP, record.getExternalIP());
  88. recordValues.put(KEY_LOCAL_IP, record.getLocalIP().getAddress()); // Log Local IP
  89. recordValues.put(KEY_LOCAL_HOSTNAME, record.getLocalIP().getHostName());
  90. recordValues.put(KEY_LOCAL_PORT, record.getLocalPort()); // Log Local Port
  91. recordValues.put(KEY_REMOTE_IP, record.getRemoteIP().getAddress()); // Log Remote IP
  92. recordValues.put(KEY_REMOTE_HOSTNAME, record.getRemoteIP().getHostName());
  93. recordValues.put(KEY_REMOTE_PORT, record.getRemotePort()); // Log Remote Port
  94. recordValues.put(KEY_BSSID, record.getBSSID());
  95. recordValues.put(KEY_PACKET, record.getPacket()); // Log Packet
  96. // Inserting Rows
  97. db.insertWithOnConflict(TABLE_BSSIDS, null, bssidValues, SQLiteDatabase.CONFLICT_REPLACE);
  98. db.insert(TABLE_RECORDS, null, recordValues);
  99. db.close(); // Closing database connection
  100. }
  101. /**
  102. * Creates a {@link Record} from a Cursor. If the cursor does not show to a valid data structure a runtime exception is thrown.
  103. * @param cursor
  104. * @return Returns the created {@link Record} .
  105. */
  106. private Record createRecord(Cursor cursor){
  107. Record record = new Record();
  108. try {
  109. record.setId(Integer.parseInt(cursor.getString(0)));
  110. record.setAttack_id(cursor.getLong(1));
  111. record.setProtocol(cursor.getString(2));
  112. record.setType(cursor.getString(3).equals("SEND") ? TYPE.SEND : TYPE.RECEIVE);
  113. record.setTimestamp(cursor.getLong(4));
  114. record.setExternalIP(cursor.getString(5));
  115. record.setLocalIP(InetAddress.getByAddress(cursor.getString(7), cursor.getBlob(6)));
  116. record.setLocalPort(Integer.parseInt(cursor.getString(8)));
  117. record.setRemoteIP(InetAddress.getByAddress(cursor.getString(10), cursor.getBlob(9)));
  118. record.setRemotePort(Integer.parseInt(cursor.getString(11)));
  119. record.setBSSID(cursor.getString(12));
  120. record.setPacket(cursor.getString(13));
  121. record.setSSID(cursor.getString(14));
  122. } catch (UnknownHostException e) {
  123. e.printStackTrace();
  124. }
  125. return record;
  126. }
  127. /**
  128. * Gets a single {@link Record} with the given ID from the database.
  129. * @param id The ID of the {@link Record};
  130. * @return The {@link Record}.
  131. */
  132. public Record getRecord(int id) {
  133. String selectQuery = "SELECT * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " WHERE " + KEY_ID + " = " + id;
  134. SQLiteDatabase db = this.getReadableDatabase();
  135. Cursor cursor = db.rawQuery(selectQuery, null);
  136. Record record = null;
  137. if (cursor.moveToFirst()){
  138. record = createRecord(cursor);
  139. }
  140. cursor.close();
  141. db.close();
  142. // return contact
  143. return record;
  144. }
  145. /**
  146. * Gets all {@link Record Records} saved in the database.
  147. * @return A ArrayList of all the {@link Record Records} in the Database.
  148. */
  149. public ArrayList<Record> getAllRecords() {
  150. ArrayList<Record> recordList = new ArrayList<Record>();
  151. // Select All Query
  152. String selectQuery = "SELECT * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS;
  153. SQLiteDatabase db = this.getWritableDatabase();
  154. Cursor cursor = db.rawQuery(selectQuery, null);
  155. // looping through all rows and adding to list
  156. if (cursor.moveToFirst()) {
  157. do {
  158. Record record = createRecord(cursor);
  159. // Adding record to list
  160. recordList.add(record);
  161. } while (cursor.moveToNext());
  162. }
  163. cursor.close();
  164. db.close();
  165. // return record list
  166. return recordList;
  167. }
  168. /**
  169. * Gets a single {@link Record} with the given attack id from the database.
  170. * @param attack_id The attack id of the {@link Record};
  171. * @return The {@link Record}.
  172. */
  173. public Record getRecordOfAttackId(long attack_id) {
  174. String selectQuery = "SELECT * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " WHERE " + KEY_ATTACK_ID + " = " + attack_id + " GROUP BY " + KEY_ATTACK_ID;
  175. SQLiteDatabase db = this.getReadableDatabase();
  176. Cursor cursor = db.rawQuery(selectQuery, null);
  177. Record record = null;
  178. if (cursor.moveToFirst()) {
  179. record = createRecord(cursor);
  180. }
  181. cursor.close();
  182. // return record list
  183. db.close();
  184. return record;
  185. }
  186. /**
  187. * Gets all received {@link Record Records} for every attack identified by its attack id and ordered by date.
  188. * @return A ArrayList with one {@link Record Records} for each attack id in the Database.
  189. */
  190. public ArrayList<Record> getAllReceivedRecordsOfEachAttack() {
  191. ArrayList<Record> recordList = new ArrayList<Record>();
  192. String selectQuery = "SELECT * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " WHERE " + KEY_TYPE + "='RECEIVE'" + " ORDER BY " + KEY_TIME;
  193. SQLiteDatabase db = this.getReadableDatabase();
  194. Cursor cursor = db.rawQuery(selectQuery, null);
  195. // looping through all rows and adding to list
  196. if (cursor.moveToFirst()) {
  197. do {
  198. Record record = createRecord(cursor);
  199. // Adding record to list
  200. recordList.add(record);
  201. } while (cursor.moveToNext());
  202. }
  203. cursor.close();
  204. // return record list
  205. db.close();
  206. return recordList;
  207. }
  208. /**
  209. * Gets a representative {@link Record} for every attack identified by its attack id.
  210. * @return A ArrayList with one {@link Record Records} for each attack id in the Database.
  211. */
  212. public ArrayList<Record> getRecordOfEachAttack() {
  213. ArrayList<Record> recordList = new ArrayList<Record>();
  214. String selectQuery = "SELECT * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " GROUP BY " + KEY_ATTACK_ID;
  215. SQLiteDatabase db = this.getReadableDatabase();
  216. Cursor cursor = db.rawQuery(selectQuery, null);
  217. // looping through all rows and adding to list
  218. if (cursor.moveToFirst()) {
  219. do {
  220. Record record = createRecord(cursor);
  221. // Adding record to list
  222. recordList.add(record);
  223. } while (cursor.moveToNext());
  224. }
  225. cursor.close();
  226. // return record list
  227. db.close();
  228. return recordList;
  229. }
  230. /**
  231. * Gets a representative {@link Record} for every attack with a higher attack id than the specified.
  232. * @param attack_id The attack id to match the query against.
  233. * @return A ArrayList with one {@link Record Records} for each attack id higher than the given.
  234. */
  235. public ArrayList<Record> getRecordOfEachAttack(long attack_id) {
  236. ArrayList<Record> recordList = new ArrayList<Record>();
  237. String selectQuery = "SELECT * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " WHERE " + KEY_ATTACK_ID + " > " + attack_id + " GROUP BY " + KEY_ATTACK_ID;
  238. SQLiteDatabase db = this.getReadableDatabase();
  239. Cursor cursor = db.rawQuery(selectQuery, null);
  240. // looping through all rows and adding to list
  241. if (cursor.moveToFirst()) {
  242. do {
  243. Record record = createRecord(cursor);
  244. // Adding record to list
  245. recordList.add(record);
  246. } while (cursor.moveToNext());
  247. }
  248. cursor.close();
  249. // return count
  250. db.close();
  251. return recordList;
  252. }
  253. /**
  254. * Determines the number of {@link Record Records} in the database.
  255. * @return The number of {@link Record Records} in the database.
  256. */
  257. public int getRecordCount() {
  258. String countQuery = "SELECT * FROM " + TABLE_RECORDS;
  259. SQLiteDatabase db = this.getReadableDatabase();
  260. Cursor cursor = db.rawQuery(countQuery, null);
  261. int result = cursor.getCount();
  262. cursor.close();
  263. // return count
  264. db.close();
  265. return result;
  266. }
  267. /**
  268. * Determines the number of different attack_ids in the database.
  269. * @return The number of different attack_ids in the database.
  270. */
  271. public int getAttackCount() {
  272. String countQuery = "SELECT * FROM " + TABLE_RECORDS + " GROUP BY " + KEY_ATTACK_ID;
  273. SQLiteDatabase db = this.getReadableDatabase();
  274. Cursor cursor = db.rawQuery(countQuery, null);
  275. int result = cursor.getCount();
  276. cursor.close();
  277. // return count
  278. db.close();
  279. return result;
  280. }
  281. /**
  282. * Determines the number of different attack_ids for a specific protocol in the database.
  283. * @param protocol The String representation of the {@link de.tudarmstadt.informatik.hostage.protocol.Protocol Protocol}
  284. * @return The number of different attack_ids in the database.
  285. */
  286. public int getAttackPerProtokolCount(String protocol) {
  287. String countQuery = "SELECT * FROM " + TABLE_RECORDS + " WHERE " + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " GROUP BY " + KEY_ATTACK_ID;
  288. SQLiteDatabase db = this.getReadableDatabase();
  289. Cursor cursor = db.rawQuery(countQuery, null);
  290. int result = cursor.getCount();
  291. cursor.close();
  292. // return count
  293. db.close();
  294. return result;
  295. }
  296. /**
  297. * Determines the smallest attack id stored in the database.
  298. * @return The smallest attack id stored in the database.
  299. */
  300. public long getSmallestAttackId(){
  301. String selectQuery = "SELECT MIN(" + KEY_ATTACK_ID +") FROM " + TABLE_RECORDS;
  302. SQLiteDatabase db = this.getReadableDatabase();
  303. Cursor cursor = db.rawQuery(selectQuery, null);
  304. int result;
  305. if (cursor.moveToFirst()) {
  306. result = cursor.getInt(0);
  307. } else{
  308. result = -1;
  309. }
  310. cursor.close();
  311. db.close();
  312. return result;
  313. }
  314. /**
  315. * Determines the highest attack id stored in the database.
  316. * @return The highest attack id stored in the database.
  317. */
  318. public long getHighestAttackId(){
  319. String selectQuery = "SELECT MAX(" + KEY_ATTACK_ID +") FROM " + TABLE_RECORDS;
  320. SQLiteDatabase db = this.getReadableDatabase();
  321. Cursor cursor = db.rawQuery(selectQuery, null);
  322. int result;
  323. if (cursor.moveToFirst()) {
  324. result = cursor.getInt(0);
  325. } else{
  326. result = -1;
  327. }
  328. cursor.close();
  329. db.close();
  330. return result;
  331. }
  332. /**
  333. * Determines if an attack has been recorded on a specific protocol in a network with a given BSSID.
  334. * @param protocol The {@link de.tudarmstadt.informatik.hostage.protocol.Protocol Protocol} to inspect.
  335. * @param BSSID The BSSID of the network.
  336. * @return True if an attack on the given protocol has been recorded in a network with the given BSSID, else false.
  337. */
  338. public boolean bssidSeen(String protocol, String BSSID){
  339. String countQuery = "SELECT * FROM " + TABLE_RECORDS + " WHERE " + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " AND " + KEY_BSSID + " = " + "'" + BSSID + "'";
  340. SQLiteDatabase db = this.getReadableDatabase();
  341. Cursor cursor = db.rawQuery(countQuery, null);
  342. int result = cursor.getCount();
  343. cursor.close();
  344. db.close();
  345. return result > 0;
  346. }
  347. /**
  348. * Returns a String array with all BSSIDs stored in the database.
  349. * @return String[] of all recorded BSSIDs.
  350. */
  351. public String[] getAllBSSIDS(){
  352. String selectQuery = "SELECT * FROM " + TABLE_BSSIDS;
  353. SQLiteDatabase db = this.getReadableDatabase();
  354. Cursor cursor = db.rawQuery(selectQuery, null);
  355. String[] bssidList = new String[cursor.getCount()];
  356. int counter = 0;
  357. // looping through all rows and adding to list
  358. if (cursor.moveToFirst()) {
  359. do {
  360. bssidList[counter] = cursor.getString(0);
  361. counter++;
  362. } while (cursor.moveToNext());
  363. }
  364. cursor.close();
  365. db.close();
  366. return bssidList;
  367. }
  368. /**
  369. * Gets the last recorded SSID to a given BSSID.
  370. * @param bssid The BSSID to match against.
  371. * @return A String of the last SSID or null if the BSSID is not in the database.
  372. */
  373. public String getSSID(String bssid){
  374. String selectQuery = "SELECT "+ KEY_SSID +" FROM " + TABLE_BSSIDS + " WHERE " + KEY_BSSID + " = " + "'" + bssid + "'";
  375. SQLiteDatabase db = this.getReadableDatabase();
  376. Cursor cursor = db.rawQuery(selectQuery, null);
  377. String ssid = null;
  378. if(cursor.moveToFirst()){
  379. ssid = cursor.getString(0);
  380. }
  381. cursor.close();
  382. db.close();
  383. return ssid;
  384. }
  385. /**
  386. * Deletes all records from {@link #TABLE_RECORDS} with a specific BSSID.
  387. * @param bssid The BSSID to match against.
  388. */
  389. public void deleteByBSSID(String bssid){
  390. SQLiteDatabase db = this.getReadableDatabase();
  391. db.delete(TABLE_RECORDS, KEY_BSSID + " = ?", new String[]{bssid});
  392. db.close();
  393. }
  394. /**
  395. * Deletes all records from {@link #TABLE_RECORDS} with a time stamp smaller then the given
  396. * @param date A Date represented in milliseconds.
  397. */
  398. public void deleteByDate(long date){
  399. SQLiteDatabase db = this.getReadableDatabase();
  400. String deleteQuery = "DELETE FROM " + TABLE_RECORDS + " WHERE " + KEY_TIME + " < " + date;
  401. db.execSQL(deleteQuery);
  402. db.close();
  403. }
  404. /**
  405. * Deletes all records from {@link #TABLE_RECORDS}.
  406. */
  407. public void clearData(){
  408. SQLiteDatabase db = this.getReadableDatabase();
  409. db.delete(TABLE_RECORDS, null, null);
  410. db.close();
  411. }
  412. }