DatabaseHandler.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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_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_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_LOCAL_IP, record.getLocalIP().getAddress()); // Log Local IP
  87. recordValues.put(KEY_LOCAL_HOSTNAME, record.getLocalIP().getHostName());
  88. recordValues.put(KEY_LOCAL_PORT, record.getLocalPort()); // Log Local Port
  89. recordValues.put(KEY_REMOTE_IP, record.getRemoteIP().getAddress()); // Log Remote IP
  90. recordValues.put(KEY_REMOTE_HOSTNAME, record.getRemoteIP().getHostName());
  91. recordValues.put(KEY_REMOTE_PORT, record.getRemotePort()); // Log Remote Port
  92. recordValues.put(KEY_BSSID, record.getBSSID());
  93. recordValues.put(KEY_PACKET, record.getPacket()); // Log Packet
  94. // Inserting Rows
  95. db.insertWithOnConflict(TABLE_BSSIDS, null, bssidValues, SQLiteDatabase.CONFLICT_REPLACE);
  96. db.insert(TABLE_RECORDS, null, recordValues);
  97. db.close(); // Closing database connection
  98. }
  99. /**
  100. * Creates a {@link Record} from a Cursor. If the cursor does not show to a valid data structure a runtime exception is thrown.
  101. * @param cursor
  102. * @return Returns the created {@link Record} .
  103. */
  104. private Record createRecord(Cursor cursor){
  105. Record record = new Record();
  106. try {
  107. record.setId(Integer.parseInt(cursor.getString(0)));
  108. record.setAttack_id(cursor.getLong(1));
  109. record.setProtocol(cursor.getString(2));
  110. record.setType(cursor.getString(3).equals("SEND") ? TYPE.SEND : TYPE.RECEIVE);
  111. record.setTimestamp(cursor.getLong(4));
  112. record.setLocalIP(InetAddress.getByAddress(cursor.getString(6), cursor.getBlob(5)));
  113. record.setLocalPort(Integer.parseInt(cursor.getString(7)));
  114. record.setRemoteIP(InetAddress.getByAddress(cursor.getString(9), cursor.getBlob(8)));
  115. record.setRemotePort(Integer.parseInt(cursor.getString(10)));
  116. record.setBSSID(cursor.getString(11));
  117. record.setPacket(cursor.getString(12));
  118. record.setSSID(cursor.getString(13));
  119. } catch (UnknownHostException e) {
  120. e.printStackTrace();
  121. }
  122. return record;
  123. }
  124. /**
  125. * Gets a single {@link Record} with the given ID from the database.
  126. * @param id The ID of the {@link Record};
  127. * @return The {@link Record}.
  128. */
  129. public Record getRecord(int id) {
  130. String selectQuery = "SELECT * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " WHERE " + KEY_ID + " = " + id;
  131. SQLiteDatabase db = this.getReadableDatabase();
  132. Cursor cursor = db.rawQuery(selectQuery, null);
  133. Record record = null;
  134. if (cursor.moveToFirst()){
  135. record = createRecord(cursor);
  136. }
  137. cursor.close();
  138. db.close();
  139. // return contact
  140. return record;
  141. }
  142. /**
  143. * Gets all {@link Record Records} saved in the database.
  144. * @return A ArrayList of all the {@link Record Records} in the Database.
  145. */
  146. public ArrayList<Record> getAllRecords() {
  147. ArrayList<Record> recordList = new ArrayList<Record>();
  148. // Select All Query
  149. String selectQuery = "SELECT * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS;
  150. SQLiteDatabase db = this.getWritableDatabase();
  151. Cursor cursor = db.rawQuery(selectQuery, null);
  152. // looping through all rows and adding to list
  153. if (cursor.moveToFirst()) {
  154. do {
  155. Record record = createRecord(cursor);
  156. // Adding record to list
  157. recordList.add(record);
  158. } while (cursor.moveToNext());
  159. }
  160. cursor.close();
  161. db.close();
  162. // return record list
  163. return recordList;
  164. }
  165. /**
  166. * Gets a single {@link Record} with the given attack id from the database.
  167. * @param attack_id The attack id of the {@link Record};
  168. * @return The {@link Record}.
  169. */
  170. public Record getRecordOfAttackId(long attack_id) {
  171. String selectQuery = "SELECT * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " WHERE " + KEY_ATTACK_ID + " = " + attack_id + " GROUP BY " + KEY_ATTACK_ID;
  172. SQLiteDatabase db = this.getReadableDatabase();
  173. Cursor cursor = db.rawQuery(selectQuery, null);
  174. Record record = null;
  175. if (cursor.moveToFirst()) {
  176. record = createRecord(cursor);
  177. }
  178. cursor.close();
  179. // return record list
  180. db.close();
  181. return record;
  182. }
  183. /**
  184. * Gets a representative {@link Record} for every attack identified by its attack id.
  185. * @return A ArrayList with one {@link Record Records} for each attack id in the Database.
  186. */
  187. public ArrayList<Record> getRecordOfEachAttack() {
  188. ArrayList<Record> recordList = new ArrayList<Record>();
  189. String selectQuery = "SELECT * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " GROUP BY " + KEY_ATTACK_ID;
  190. SQLiteDatabase db = this.getReadableDatabase();
  191. Cursor cursor = db.rawQuery(selectQuery, null);
  192. // looping through all rows and adding to list
  193. if (cursor.moveToFirst()) {
  194. do {
  195. Record record = createRecord(cursor);
  196. // Adding record to list
  197. recordList.add(record);
  198. } while (cursor.moveToNext());
  199. }
  200. cursor.close();
  201. // return record list
  202. db.close();
  203. return recordList;
  204. }
  205. /**
  206. * Gets a representative {@link Record} for every attack with a higher attack id than the specified.
  207. * @param attack_id The attack id to match the query against.
  208. * @return A ArrayList with one {@link Record Records} for each attack id higher than the given.
  209. */
  210. public ArrayList<Record> getRecordOfEachAttack(long attack_id) {
  211. ArrayList<Record> recordList = new ArrayList<Record>();
  212. String selectQuery = "SELECT * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " WHERE " + KEY_ATTACK_ID + " > " + attack_id + " GROUP BY " + KEY_ATTACK_ID;
  213. SQLiteDatabase db = this.getReadableDatabase();
  214. Cursor cursor = db.rawQuery(selectQuery, null);
  215. // looping through all rows and adding to list
  216. if (cursor.moveToFirst()) {
  217. do {
  218. Record record = createRecord(cursor);
  219. // Adding record to list
  220. recordList.add(record);
  221. } while (cursor.moveToNext());
  222. }
  223. cursor.close();
  224. // return count
  225. db.close();
  226. return recordList;
  227. }
  228. /**
  229. * Determines the number of {@link Record Records} in the database.
  230. * @return The number of {@link Record Records} in the database.
  231. */
  232. public int getRecordCount() {
  233. String countQuery = "SELECT * FROM " + TABLE_RECORDS;
  234. SQLiteDatabase db = this.getReadableDatabase();
  235. Cursor cursor = db.rawQuery(countQuery, null);
  236. int result = cursor.getCount();
  237. cursor.close();
  238. // return count
  239. db.close();
  240. return result;
  241. }
  242. /**
  243. * Determines the number of different attack_ids in the database.
  244. * @return The number of different attack_ids in the database.
  245. */
  246. public int getAttackCount() {
  247. String countQuery = "SELECT * FROM " + TABLE_RECORDS + " GROUP BY " + KEY_ATTACK_ID;
  248. SQLiteDatabase db = this.getReadableDatabase();
  249. Cursor cursor = db.rawQuery(countQuery, null);
  250. int result = cursor.getCount();
  251. cursor.close();
  252. // return count
  253. db.close();
  254. return result;
  255. }
  256. /**
  257. * Determines the number of different attack_ids for a specific protocol in the database.
  258. * @param protocol The String representation of the {@link de.tudarmstadt.informatik.hostage.protocol.Protocol Protocol}
  259. * @return The number of different attack_ids in the database.
  260. */
  261. public int getAttackPerProtokolCount(String protocol) {
  262. String countQuery = "SELECT * FROM " + TABLE_RECORDS + " WHERE " + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " GROUP BY " + KEY_ATTACK_ID;
  263. SQLiteDatabase db = this.getReadableDatabase();
  264. Cursor cursor = db.rawQuery(countQuery, null);
  265. int result = cursor.getCount();
  266. cursor.close();
  267. // return count
  268. db.close();
  269. return result;
  270. }
  271. /**
  272. * Determines the smallest attack id stored in the database.
  273. * @return The smallest attack id stored in the database.
  274. */
  275. public long getSmallestAttackId(){
  276. String selectQuery = "SELECT MIN(" + KEY_ATTACK_ID +") FROM " + TABLE_RECORDS;
  277. SQLiteDatabase db = this.getReadableDatabase();
  278. Cursor cursor = db.rawQuery(selectQuery, null);
  279. int result;
  280. if (cursor.moveToFirst()) {
  281. result = cursor.getInt(0);
  282. } else{
  283. result = -1;
  284. }
  285. cursor.close();
  286. db.close();
  287. return result;
  288. }
  289. /**
  290. * Determines the highest attack id stored in the database.
  291. * @return The highest attack id stored in the database.
  292. */
  293. public long getHighestAttackId(){
  294. String selectQuery = "SELECT MAX(" + KEY_ATTACK_ID +") FROM " + TABLE_RECORDS;
  295. SQLiteDatabase db = this.getReadableDatabase();
  296. Cursor cursor = db.rawQuery(selectQuery, null);
  297. int result;
  298. if (cursor.moveToFirst()) {
  299. result = cursor.getInt(0);
  300. } else{
  301. result = -1;
  302. }
  303. cursor.close();
  304. db.close();
  305. return result;
  306. }
  307. /**
  308. * Determines if an attack has been recorded on a specific protocol in a network with a given BSSID.
  309. * @param protocol The {@link de.tudarmstadt.informatik.hostage.protocol.Protocol Protocol} to inspect.
  310. * @param BSSID The BSSID of the network.
  311. * @return True if an attack on the given protocol has been recorded in a network with the given BSSID, else false.
  312. */
  313. public boolean bssidSeen(String protocol, String BSSID){
  314. String countQuery = "SELECT * FROM " + TABLE_RECORDS + " WHERE " + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " AND " + KEY_BSSID + " = " + "'" + BSSID + "'";
  315. SQLiteDatabase db = this.getReadableDatabase();
  316. Cursor cursor = db.rawQuery(countQuery, null);
  317. int result = cursor.getCount();
  318. cursor.close();
  319. db.close();
  320. return result > 0;
  321. }
  322. /**
  323. * Returns a String array with all BSSIDs stored in the database.
  324. * @return String[] of all recorded BSSIDs.
  325. */
  326. public String[] getAllBSSIDS(){
  327. String selectQuery = "SELECT * FROM " + TABLE_BSSIDS;
  328. SQLiteDatabase db = this.getReadableDatabase();
  329. Cursor cursor = db.rawQuery(selectQuery, null);
  330. String[] bssidList = new String[cursor.getCount()];
  331. int counter = 0;
  332. // looping through all rows and adding to list
  333. if (cursor.moveToFirst()) {
  334. do {
  335. bssidList[counter] = cursor.getString(0);
  336. counter++;
  337. } while (cursor.moveToNext());
  338. }
  339. cursor.close();
  340. db.close();
  341. return bssidList;
  342. }
  343. /**
  344. * Gets the last recorded SSID to a given BSSID.
  345. * @param bssid The BSSID to match against.
  346. * @return A String of the last SSID or null if the BSSID is not in the database.
  347. */
  348. public String getSSID(String bssid){
  349. String selectQuery = "SELECT "+ KEY_SSID +" FROM " + TABLE_BSSIDS + " WHERE " + KEY_BSSID + " = " + "'" + bssid + "'";
  350. SQLiteDatabase db = this.getReadableDatabase();
  351. Cursor cursor = db.rawQuery(selectQuery, null);
  352. String ssid = null;
  353. if(cursor.moveToFirst()){
  354. ssid = cursor.getString(0);
  355. }
  356. cursor.close();
  357. db.close();
  358. return ssid;
  359. }
  360. /**
  361. * Deletes all records from {@link #TABLE_RECORDS} with a specific BSSID.
  362. * @param bssid The BSSID to match against.
  363. */
  364. public void deleteByBSSID(String bssid){
  365. SQLiteDatabase db = this.getReadableDatabase();
  366. db.delete(TABLE_RECORDS, KEY_BSSID + " = ?", new String[]{bssid});
  367. db.close();
  368. }
  369. /**
  370. * Deletes all records from {@link #TABLE_RECORDS} with a time stamp smaller then the given
  371. * @param date A Date represented in milliseconds.
  372. */
  373. public void deleteByDate(long date){
  374. SQLiteDatabase db = this.getReadableDatabase();
  375. String deleteQuery = "DELETE FROM " + TABLE_RECORDS + " WHERE " + KEY_TIME + " < " + date;
  376. db.execSQL(deleteQuery);
  377. db.close();
  378. }
  379. /**
  380. * Deletes all records from {@link #TABLE_RECORDS}.
  381. */
  382. public void clearData(){
  383. SQLiteDatabase db = this.getReadableDatabase();
  384. db.delete(TABLE_RECORDS, null, null);
  385. db.close();
  386. }
  387. }