DatabaseHandler.java 17 KB

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