DatabaseHandler.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. import android.util.Log;
  12. /**
  13. * This class creates SQL tables and handles all access to the database.<br>
  14. * It contains several methods with predefined queries to extract different kinds of information from the database.<br>
  15. * The database contains two tables: {@link #TABLE_RECORDS} and {@link #TABLE_BSSIDS}:<br>
  16. * {@link #TABLE_RECORDS} contains all logging information of a single message record except the SSID.<br>
  17. * {@link #TABLE_BSSIDS} contains the BSSID of all recorded Networks and the corresponding SSID.<br>
  18. * @author Lars Pandikow
  19. *
  20. */
  21. public class DatabaseHandler extends SQLiteOpenHelper {
  22. // All Static variables
  23. // Database Version
  24. private static final int DATABASE_VERSION = 1;
  25. // Database Name
  26. private static final String DATABASE_NAME = "recordManager";
  27. // Contacts table names
  28. private static final String TABLE_RECORDS = "records";
  29. private static final String TABLE_BSSIDS = "bssids";
  30. // Contacts Table Columns names
  31. private static final String KEY_ID = "_id";
  32. private static final String KEY_ATTACK_ID = "attack_id";
  33. private static final String KEY_PROTOCOL = "protocol";
  34. private static final String KEY_TYPE = "type";
  35. private static final String KEY_TIME = "timestamp";
  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_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 record to the database.
  75. * @param record The added 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_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 {@link 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 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.setLocalIP(InetAddress.getByAddress(cursor.getString(6), cursor.getBlob(5)));
  114. record.setLocalPort(Integer.parseInt(cursor.getString(7)));
  115. record.setRemoteIP(InetAddress.getByAddress(cursor.getString(9), cursor.getBlob(8)));
  116. record.setRemotePort(Integer.parseInt(cursor.getString(10)));
  117. record.setBSSID(cursor.getString(11));
  118. record.setPacket(cursor.getString(12));
  119. record.setSSID(cursor.getString(13));
  120. } catch (UnknownHostException e) {
  121. // TODO Auto-generated catch block
  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 a representative {@link Record} for every attack identified by its attack id.
  187. * @return A ArrayList with one {@link Record Records} for each attack id in the Database.
  188. */
  189. public ArrayList<Record> getRecordOfEachAttack() {
  190. ArrayList<Record> recordList = new ArrayList<Record>();
  191. String selectQuery = "SELECT * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " GROUP BY " + KEY_ATTACK_ID;
  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 with a higher attack id than the specified.
  209. * @param attack_id The attack id to match the query against.
  210. * @return A ArrayList with one {@link Record Records} for each attack id higher than the given.
  211. */
  212. public ArrayList<Record> getRecordOfEachAttack(long attack_id) {
  213. ArrayList<Record> recordList = new ArrayList<Record>();
  214. String selectQuery = "SELECT * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " WHERE " + KEY_ATTACK_ID + " > " + attack_id + " 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 count
  227. db.close();
  228. return recordList;
  229. }
  230. /**
  231. * Determines the number of {@link Record Records} in the database.
  232. * @return The number of {@link Record Records} in the database.
  233. */
  234. public int getRecordCount() {
  235. String countQuery = "SELECT * FROM " + TABLE_RECORDS;
  236. SQLiteDatabase db = this.getReadableDatabase();
  237. Cursor cursor = db.rawQuery(countQuery, null);
  238. int result = cursor.getCount();
  239. cursor.close();
  240. // return count
  241. db.close();
  242. return result;
  243. }
  244. /**
  245. * Determines the number of different attack_ids in the database.
  246. * @return The number of different attack_ids in the database.
  247. */
  248. public int getAttackCount() {
  249. String countQuery = "SELECT * FROM " + TABLE_RECORDS + " GROUP BY " + KEY_ATTACK_ID;
  250. SQLiteDatabase db = this.getReadableDatabase();
  251. Cursor cursor = db.rawQuery(countQuery, null);
  252. int result = cursor.getCount();
  253. cursor.close();
  254. // return count
  255. db.close();
  256. return result;
  257. }
  258. /**
  259. * Determines the number of different attack_ids for a specific protocol in the database.
  260. * @param protocol The String representation of the {@link de.tudarmstadt.informatik.hostage.protocol.Protocol Protocol}
  261. * @return The number of different attack_ids in the database.
  262. */
  263. public int getAttackPerProtokolCount(String protocol) {
  264. String countQuery = "SELECT * FROM " + TABLE_RECORDS + " WHERE " + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " GROUP BY " + KEY_ATTACK_ID;
  265. SQLiteDatabase db = this.getReadableDatabase();
  266. Cursor cursor = db.rawQuery(countQuery, null);
  267. int result = cursor.getCount();
  268. cursor.close();
  269. // return count
  270. db.close();
  271. return result;
  272. }
  273. /**
  274. * Determines the smallest attack id stored in the database.
  275. * @return The smallest attack id stored in the database.
  276. */
  277. public long getSmallestAttackId(){
  278. String selectQuery = "SELECT MIN(" + KEY_ATTACK_ID +") FROM " + TABLE_RECORDS;
  279. SQLiteDatabase db = this.getReadableDatabase();
  280. Cursor cursor = db.rawQuery(selectQuery, null);
  281. int result;
  282. if (cursor.moveToFirst()) {
  283. result = cursor.getInt(0);
  284. } else{
  285. result = -1;
  286. }
  287. cursor.close();
  288. db.close();
  289. return result;
  290. }
  291. /**
  292. * Determines the highest attack id stored in the database.
  293. * @return The highest attack id stored in the database.
  294. */
  295. public long getHighestAttackId(){
  296. String selectQuery = "SELECT MAX(" + KEY_ATTACK_ID +") FROM " + TABLE_RECORDS;
  297. SQLiteDatabase db = this.getReadableDatabase();
  298. Cursor cursor = db.rawQuery(selectQuery, null);
  299. int result;
  300. if (cursor.moveToFirst()) {
  301. result = cursor.getInt(0);
  302. } else{
  303. result = -1;
  304. }
  305. cursor.close();
  306. db.close();
  307. return result;
  308. }
  309. /**
  310. * Determines if an attack has been recorded on a specific protocol in a network with a given BSSID.
  311. * @param protocol The {@link de.tudarmstadt.informatik.hostage.protocol.Protocol Protocol} to inspect.
  312. * @param BSSID The BSSID of the network.
  313. * @return True if an attack on the given protocol has been recorded in a network with the given BSSID, else false.
  314. */
  315. public boolean bssidSeen(String protocol, String BSSID){
  316. String countQuery = "SELECT * FROM " + TABLE_RECORDS + " WHERE " + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " AND " + KEY_BSSID + " = " + "'" + BSSID + "'";
  317. SQLiteDatabase db = this.getReadableDatabase();
  318. Cursor cursor = db.rawQuery(countQuery, null);
  319. int result = cursor.getCount();
  320. cursor.close();
  321. db.close();
  322. return result > 0;
  323. }
  324. /**
  325. * Returns a String array with all BSSIDs stored in the database.
  326. * @return String[] of all recorded BSSIDs.
  327. */
  328. public String[] getAllBSSIDS(){
  329. String selectQuery = "SELECT * FROM " + TABLE_BSSIDS;
  330. SQLiteDatabase db = this.getReadableDatabase();
  331. Cursor cursor = db.rawQuery(selectQuery, null);
  332. String[] bssidList = new String[cursor.getCount()];
  333. int counter = 0;
  334. // looping through all rows and adding to list
  335. if (cursor.moveToFirst()) {
  336. do {
  337. bssidList[counter] = cursor.getString(0);
  338. counter++;
  339. } while (cursor.moveToNext());
  340. }
  341. cursor.close();
  342. db.close();
  343. return bssidList;
  344. }
  345. /**
  346. * Gets the last recorded SSID to a given BSSID.
  347. * @param bssid The BSSID to match against.
  348. * @return A String of the last SSID or null if the BSSID is not in the database.
  349. */
  350. public String getSSID(String bssid){
  351. String selectQuery = "SELECT "+ KEY_SSID +" FROM " + TABLE_BSSIDS + " WHERE " + KEY_BSSID + " = " + "'" + bssid + "'";
  352. SQLiteDatabase db = this.getReadableDatabase();
  353. Cursor cursor = db.rawQuery(selectQuery, null);
  354. String ssid = null;
  355. if(cursor.moveToFirst()){
  356. ssid = cursor.getString(0);
  357. }
  358. cursor.close();
  359. db.close();
  360. return ssid;
  361. }
  362. /**
  363. * Deletes all records from {@link TABLE_RECORDS} with a specific BSSID.
  364. * @param bssid The BSSID to match against.
  365. */
  366. public void deleteByBSSID(String bssid){
  367. SQLiteDatabase db = this.getReadableDatabase();
  368. db.delete(TABLE_RECORDS, KEY_BSSID + " = ?", new String[]{bssid});
  369. db.close();
  370. }
  371. /**
  372. * Deletes all records from {@link TABLE_RECORDS} with a time stamp smaller then the given
  373. * @param date A Date represented in milliseconds.
  374. */
  375. public void deleteByDate(long date){
  376. SQLiteDatabase db = this.getReadableDatabase();
  377. String deleteQuery = "DELETE FROM " + TABLE_RECORDS + " WHERE " + KEY_TIME + " < " + date;
  378. db.execSQL(deleteQuery);
  379. db.close();
  380. }
  381. /**
  382. * Deletes all records from {@link TABLE_RECORDS}.
  383. */
  384. public void clearData(){
  385. SQLiteDatabase db = this.getReadableDatabase();
  386. db.delete(TABLE_RECORDS, null, null);
  387. db.close();
  388. }
  389. }