DatabaseHandler.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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 a representative {@link Record} for every attack identified by its attack id.
  188. * @return A ArrayList with one {@link Record Records} for each attack id in the Database.
  189. */
  190. public ArrayList<Record> getRecordOfEachAttack() {
  191. ArrayList<Record> recordList = new ArrayList<Record>();
  192. String selectQuery = "SELECT * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " GROUP BY " + KEY_ATTACK_ID + " 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 with a higher attack id than the specified.
  210. * @param attack_id The attack id to match the query against.
  211. * @return A ArrayList with one {@link Record Records} for each attack id higher than the given.
  212. */
  213. public ArrayList<Record> getRecordOfEachAttack(long attack_id) {
  214. ArrayList<Record> recordList = new ArrayList<Record>();
  215. String selectQuery = "SELECT * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " WHERE " + KEY_ATTACK_ID + " > " + attack_id + " GROUP BY " + KEY_ATTACK_ID;
  216. SQLiteDatabase db = this.getReadableDatabase();
  217. Cursor cursor = db.rawQuery(selectQuery, null);
  218. // looping through all rows and adding to list
  219. if (cursor.moveToFirst()) {
  220. do {
  221. Record record = createRecord(cursor);
  222. // Adding record to list
  223. recordList.add(record);
  224. } while (cursor.moveToNext());
  225. }
  226. cursor.close();
  227. // return count
  228. db.close();
  229. return recordList;
  230. }
  231. /**
  232. * Determines the number of {@link Record Records} in the database.
  233. * @return The number of {@link Record Records} in the database.
  234. */
  235. public int getRecordCount() {
  236. String countQuery = "SELECT * FROM " + TABLE_RECORDS;
  237. SQLiteDatabase db = this.getReadableDatabase();
  238. Cursor cursor = db.rawQuery(countQuery, null);
  239. int result = cursor.getCount();
  240. cursor.close();
  241. // return count
  242. db.close();
  243. return result;
  244. }
  245. /**
  246. * Determines the number of different attack_ids in the database.
  247. * @return The number of different attack_ids in the database.
  248. */
  249. public int getAttackCount() {
  250. String countQuery = "SELECT * FROM " + TABLE_RECORDS + " GROUP BY " + KEY_ATTACK_ID;
  251. SQLiteDatabase db = this.getReadableDatabase();
  252. Cursor cursor = db.rawQuery(countQuery, null);
  253. int result = cursor.getCount();
  254. cursor.close();
  255. // return count
  256. db.close();
  257. return result;
  258. }
  259. /**
  260. * Determines the number of different attack_ids for a specific protocol in the database.
  261. * @param protocol The String representation of the {@link de.tudarmstadt.informatik.hostage.protocol.Protocol Protocol}
  262. * @return The number of different attack_ids in the database.
  263. */
  264. public int getAttackPerProtokolCount(String protocol) {
  265. String countQuery = "SELECT * FROM " + TABLE_RECORDS + " WHERE " + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " GROUP BY " + KEY_ATTACK_ID;
  266. SQLiteDatabase db = this.getReadableDatabase();
  267. Cursor cursor = db.rawQuery(countQuery, null);
  268. int result = cursor.getCount();
  269. cursor.close();
  270. // return count
  271. db.close();
  272. return result;
  273. }
  274. /**
  275. * Determines the smallest attack id stored in the database.
  276. * @return The smallest attack id stored in the database.
  277. */
  278. public long getSmallestAttackId(){
  279. String selectQuery = "SELECT MIN(" + KEY_ATTACK_ID +") FROM " + TABLE_RECORDS;
  280. SQLiteDatabase db = this.getReadableDatabase();
  281. Cursor cursor = db.rawQuery(selectQuery, null);
  282. int result;
  283. if (cursor.moveToFirst()) {
  284. result = cursor.getInt(0);
  285. } else{
  286. result = -1;
  287. }
  288. cursor.close();
  289. db.close();
  290. return result;
  291. }
  292. /**
  293. * Determines the highest attack id stored in the database.
  294. * @return The highest attack id stored in the database.
  295. */
  296. public long getHighestAttackId(){
  297. String selectQuery = "SELECT MAX(" + KEY_ATTACK_ID +") FROM " + TABLE_RECORDS;
  298. SQLiteDatabase db = this.getReadableDatabase();
  299. Cursor cursor = db.rawQuery(selectQuery, null);
  300. int result;
  301. if (cursor.moveToFirst()) {
  302. result = cursor.getInt(0);
  303. } else{
  304. result = -1;
  305. }
  306. cursor.close();
  307. db.close();
  308. return result;
  309. }
  310. /**
  311. * Determines if an attack has been recorded on a specific protocol in a network with a given BSSID.
  312. * @param protocol The {@link de.tudarmstadt.informatik.hostage.protocol.Protocol Protocol} to inspect.
  313. * @param BSSID The BSSID of the network.
  314. * @return True if an attack on the given protocol has been recorded in a network with the given BSSID, else false.
  315. */
  316. public boolean bssidSeen(String protocol, String BSSID){
  317. String countQuery = "SELECT * FROM " + TABLE_RECORDS + " WHERE " + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " AND " + KEY_BSSID + " = " + "'" + BSSID + "'";
  318. SQLiteDatabase db = this.getReadableDatabase();
  319. Cursor cursor = db.rawQuery(countQuery, null);
  320. int result = cursor.getCount();
  321. cursor.close();
  322. db.close();
  323. return result > 0;
  324. }
  325. /**
  326. * Returns a String array with all BSSIDs stored in the database.
  327. * @return String[] of all recorded BSSIDs.
  328. */
  329. public String[] getAllBSSIDS(){
  330. String selectQuery = "SELECT * FROM " + TABLE_BSSIDS;
  331. SQLiteDatabase db = this.getReadableDatabase();
  332. Cursor cursor = db.rawQuery(selectQuery, null);
  333. String[] bssidList = new String[cursor.getCount()];
  334. int counter = 0;
  335. // looping through all rows and adding to list
  336. if (cursor.moveToFirst()) {
  337. do {
  338. bssidList[counter] = cursor.getString(0);
  339. counter++;
  340. } while (cursor.moveToNext());
  341. }
  342. cursor.close();
  343. db.close();
  344. return bssidList;
  345. }
  346. /**
  347. * Gets the last recorded SSID to a given BSSID.
  348. * @param bssid The BSSID to match against.
  349. * @return A String of the last SSID or null if the BSSID is not in the database.
  350. */
  351. public String getSSID(String bssid){
  352. String selectQuery = "SELECT "+ KEY_SSID +" FROM " + TABLE_BSSIDS + " WHERE " + KEY_BSSID + " = " + "'" + bssid + "'";
  353. SQLiteDatabase db = this.getReadableDatabase();
  354. Cursor cursor = db.rawQuery(selectQuery, null);
  355. String ssid = null;
  356. if(cursor.moveToFirst()){
  357. ssid = cursor.getString(0);
  358. }
  359. cursor.close();
  360. db.close();
  361. return ssid;
  362. }
  363. /**
  364. * Deletes all records from {@link #TABLE_RECORDS} with a specific BSSID.
  365. * @param bssid The BSSID to match against.
  366. */
  367. public void deleteByBSSID(String bssid){
  368. SQLiteDatabase db = this.getReadableDatabase();
  369. db.delete(TABLE_RECORDS, KEY_BSSID + " = ?", new String[]{bssid});
  370. db.close();
  371. }
  372. /**
  373. * Deletes all records from {@link #TABLE_RECORDS} with a time stamp smaller then the given
  374. * @param date A Date represented in milliseconds.
  375. */
  376. public void deleteByDate(long date){
  377. SQLiteDatabase db = this.getReadableDatabase();
  378. String deleteQuery = "DELETE FROM " + TABLE_RECORDS + " WHERE " + KEY_TIME + " < " + date;
  379. db.execSQL(deleteQuery);
  380. db.close();
  381. }
  382. /**
  383. * Deletes all records from {@link #TABLE_RECORDS}.
  384. */
  385. public void clearData(){
  386. SQLiteDatabase db = this.getReadableDatabase();
  387. db.delete(TABLE_RECORDS, null, null);
  388. db.close();
  389. }
  390. }