Browse Source

Normalized Database.
Added Location Information to Database.
Added first version of LocationManager.
Fixed stopping of service at connection change(Warning: GUI does not
display this correctly)

lp-tu 10 years ago
parent
commit
44dd3a7dc9

+ 31 - 47
src/de/tudarmstadt/informatik/hostage/HoneyService.java

@@ -20,10 +20,12 @@ import android.preference.PreferenceManager;
 import android.support.v4.app.NotificationCompat;
 import android.support.v4.app.TaskStackBuilder;
 import android.support.v4.content.LocalBroadcastManager;
+import android.util.Log;
 import android.widget.Toast;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.logging.DatabaseHandler;
 import de.tudarmstadt.informatik.hostage.logging.Logger;
+import de.tudarmstadt.informatik.hostage.logging.MyLocationManager;
 import de.tudarmstadt.informatik.hostage.logging.SQLLogger;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 import de.tudarmstadt.informatik.hostage.ui.MainActivity;
@@ -41,7 +43,6 @@ public class HoneyService extends Service {
 	private NotificationCompat.Builder builder;
 	private SharedPreferences sessionPref;
 	private Editor editor;
-	private boolean stopped = false;
 
 	public List<HoneyListener> getListeners() {
 		return listeners;
@@ -77,6 +78,7 @@ public class HoneyService extends Service {
 			listeners.add(new HoneyListener(this, protocol));
 		}
 		registerNetReceiver();
+		getLocationData();
 	}
 	
     @Override
@@ -93,6 +95,13 @@ public class HoneyService extends Service {
 		unregisterNetReceiver();
 	}
 	
+	/** Starts an Instance of MyLocationManager to set the location within this class.
+	 */
+	private void getLocationData(){
+		MyLocationManager locationManager = new MyLocationManager(this);
+		locationManager.getUpdates(60 * 1000);
+	}
+	
 	/**
 	 * Deletes all session related data.
 	 */
@@ -102,8 +111,7 @@ public class HoneyService extends Service {
 	}
 	
 	/**
-	 * Register broadcast receiver for custom broadcast.
-	 * @see MainActivity#BROADCAST
+	 * Register broadcast receiver for connectivity changes
 	 */
 	private void registerNetReceiver() {
 	    // register BroadcastReceiver on network state changes	    
@@ -113,15 +121,14 @@ public class HoneyService extends Service {
 	}
 
 	/**
-	 * Unregister broadcast receiver for custom broadcast.
-	 * @see MainActivity#BROADCAST
+	 *  Unregister broadcast receiver for connectivity changes
 	 */
 	private void unregisterNetReceiver() {
 		unregisterReceiver(netReceiver);
 	}
 
 	/**
-	 * Receiver for custom broadcast.
+	 * Receiver for connectivity change broadcast.
 	 * @see MainActivity#BROADCAST
 	 */
 	private BroadcastReceiver netReceiver = new BroadcastReceiver() {
@@ -129,23 +136,19 @@ public class HoneyService extends Service {
 		public void onReceive(Context context, Intent intent) {
 				String bssid_old = sessionPref.getString(MainActivity.BSSID, "");
 				String bssid_new = HelperUtils.getBSSID(context);
-				if(!stopped && (bssid_new == null || !bssid_new.equals(bssid_old))){
-					wifiChangeNotification();
-					stopListeners();
-					deleteSessionData();
-					notifyUI("SERVICE", "STOPPED");
-					mStopSelf();
+				//TODO INFORM UI
+				//TODO CHECK IF OTHER NETWORKS WORK TOO
+				if(bssid_new == null || !bssid_new.equals(bssid_old)){
+					getLocationData();
+					String[] protocols = getResources().getStringArray(R.array.protocols);
+					for (String protocol : protocols) {
+						editor.remove(protocol + MainActivity.HANDLER_COUNT);
+					}						
+					notifyUI("SERVICE", "CONNECTIVITY_CHANGE");
 				}
 		}
 	};	
-	
-	/**
-	 * Service stops himself.
-	 */
-	private void mStopSelf(){
-		stopped = true;
-		stopSelf();	
-	}
+
 
 	/**
 	 * Creates a Notification in the notification bar.
@@ -222,31 +225,7 @@ public class HoneyService extends Service {
 		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
 		mNotificationManager.cancel(1);
 	}
-	
-	private void wifiChangeNotification(){
-		SharedPreferences defaultPref = PreferenceManager.getDefaultSharedPreferences(this);
-		String strRingtonePreference = defaultPref.getString("pref_notification_sound", "content://settings/system/notification_sound");  
-		
-		NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
-						  .setContentTitle(getString(R.string.app_name))
-						  .setWhen(System.currentTimeMillis())
-						  .setTicker("HOsTaGe stopped due Connection change!")
-						  .setContentText("HOsTaGe stopped due Connection change!")
-						  .setSmallIcon(R.drawable.ic_launcher)
-						  .setAutoCancel(true)
-						  .setSound(Uri.parse(strRingtonePreference)); 
-		if(defaultPref.getBoolean("pref_vibration", true)){
-			builder.setVibrate(new long[]{100, 200, 100, 200});
-		}
-		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
-		stackBuilder.addParentStack(MainActivity.class);
-		stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
-		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
-				PendingIntent.FLAG_UPDATE_CURRENT);
-		builder.setContentIntent(resultPendingIntent);
-		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
-		mNotificationManager.notify(2, builder.build());
-	}
+
 
 	/**
 	 * Creates a instance of each protocol defined in /res/values/protocols.xml and puts it in a List
@@ -283,16 +262,21 @@ public class HoneyService extends Service {
 
 	/**
 	 * Notifies the GUI about a event.
-	 * @param protocol The protocol where the event happend.
+	 * @param protocol The protocol where the event happened.
 	 * @param key The key for the event.
 	 */
-	public void notifyUI(String protocol, String key) {
+	public void notifyUI(String sender, String key) {
 		// Send Notification
 		if (key.equals(MainActivity.HANDLER_COUNT)){
 			updateNotification();
+		}else if(key.equals("CONNECTIVITY_CHANGE")){
+			createNotification();
 		}
+		Log.i("HoneyService", key);
 		// Inform UI of Preference Change
 		Intent intent = new Intent(MainActivity.BROADCAST);
+		intent.putExtra("SENDER", sender);
+		intent.putExtra("SENDER", key);
 		LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
 	}	
 	

+ 102 - 41
src/de/tudarmstadt/informatik/hostage/logging/DatabaseHandler.java

@@ -3,12 +3,16 @@ package de.tudarmstadt.informatik.hostage.logging;
 import java.net.InetAddress;
 import java.net.UnknownHostException;
 import java.util.ArrayList;
+
+import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.logging.Record.TYPE;
+import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 import android.content.ContentValues;
 import android.content.Context;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
+import android.util.Log;
 /**
  * This class creates SQL tables and handles all access to the database.<br>
  * It contains several methods with predefined queries to extract different kinds of information from the database.<br>
@@ -27,15 +31,18 @@ public class DatabaseHandler extends SQLiteOpenHelper {
 	private static final String DATABASE_NAME = "recordManager";
 
 	// Contacts table names
+	private static final String TABLE_ATTACK_INFO = "attack_info";
 	private static final String TABLE_RECORDS = "records";
 	private static final String TABLE_BSSIDS = "bssids";
+	private static final String TABLE_PORTS = "ports";
 
 	// Contacts Table Columns names
 	private static final String KEY_ID = "_id";
-	private static final String KEY_ATTACK_ID = "attack_id";
-	private static final String KEY_PROTOCOL = "protocol";
+	private static final String KEY_ATTACK_ID = "_attack_id";
 	private static final String KEY_TYPE = "type";
 	private static final String KEY_TIME = "timestamp";
+	private static final String KEY_PACKET = "packet";
+	private static final String KEY_PROTOCOL = "protocol";
 	private static final String KEY_EXTERNAL_IP ="externalIP";
 	private static final String KEY_LOCAL_IP = "localIP";
 	private static final String KEY_LOCAL_HOSTNAME = "localHostName";
@@ -45,37 +52,73 @@ public class DatabaseHandler extends SQLiteOpenHelper {
 	private static final String KEY_REMOTE_PORT = "remotePort";
 	private static final String KEY_BSSID = "_bssid";
 	private static final String KEY_SSID = "ssid";
-	private static final String KEY_PACKET = "packet";
+	private static final String KEY_LATITUDE = "latitude";
+	private static final String KEY_LONGITUDE = "longitude";
+	private static final String KEY_ACCURACY = "accuracy";
+
 	
 	// Database sql create statements
-	private static final String CREATE_RECORD_TABLE = "CREATE TABLE " + TABLE_RECORDS + "(" + KEY_ID
-			+ " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_ATTACK_ID + " INTEGER," + KEY_PROTOCOL + " TEXT,"
-			+ KEY_TYPE + " TEXT," + KEY_TIME + " INTEGER," + KEY_EXTERNAL_IP + " TEXT," + KEY_LOCAL_IP
-			+ " BLOB," + KEY_LOCAL_HOSTNAME + " TEXT," + KEY_LOCAL_PORT + " INTEGER," + KEY_REMOTE_IP
-			+ " BLOB," + KEY_REMOTE_HOSTNAME + " TEXT," + KEY_REMOTE_PORT + " INTEGER," 
-			+ KEY_BSSID + " TEXT," +  KEY_PACKET + " TEXT," 
-			+ "FOREIGN KEY("+ KEY_BSSID +") REFERENCES " + TABLE_BSSIDS + "("+KEY_BSSID+")" + ")";
+	private static final String CREATE_RECORD_TABLE = "CREATE TABLE " + TABLE_RECORDS + "(" 
+			+ KEY_ID + " INTEGER NOT NULL," + KEY_ATTACK_ID + " INTEGER NOT NULL," 
+			+ KEY_TYPE + " TEXT," + KEY_TIME + " INTEGER," +  KEY_PACKET + " TEXT," 
+			+ "FOREIGN KEY("+ KEY_ATTACK_ID +") REFERENCES " + TABLE_ATTACK_INFO + "("+KEY_ATTACK_ID+")" 
+			+ "PRIMARY KEY("+ KEY_ID + ", " + KEY_ATTACK_ID + ")"
+			+ ")";
+	
+	private static final String CREATE_ATTACK_INFO_TABLE = "CREATE TABLE " + TABLE_ATTACK_INFO + "(" 
+			+ KEY_ATTACK_ID + " INTEGER PRIMARY KEY," + KEY_PROTOCOL + " TEXT,"
+			+ KEY_EXTERNAL_IP + " TEXT," + KEY_LOCAL_IP + " BLOB," + KEY_LOCAL_HOSTNAME + " TEXT," 
+			+ KEY_REMOTE_IP + " BLOB," + KEY_REMOTE_HOSTNAME + " TEXT," + KEY_REMOTE_PORT + " INTEGER," + KEY_BSSID + " TEXT," 
+			+ "FOREIGN KEY("+ KEY_BSSID +") REFERENCES " + TABLE_BSSIDS + "("+KEY_BSSID+")" 
+			+ "FOREIGN KEY("+ KEY_PROTOCOL +") REFERENCES " + TABLE_PORTS + "("+KEY_PROTOCOL+")" 
+			+ ")";
+	
+	private static final String CREATE_BSSID_TABLE = "CREATE TABLE " + TABLE_BSSIDS + "(" 
+			+ KEY_BSSID + " TEXT PRIMARY KEY," + KEY_SSID + " TEXT," + KEY_LATITUDE + " INTEGER,"
+			+ KEY_LONGITUDE + " INTEGER," + KEY_ACCURACY + " INTEGER"
+			+ ")";
 	
-	private static final String CREATE_BSSID_TABLE = "CREATE TABLE " + TABLE_BSSIDS + "(" + KEY_BSSID
-			+ " TEXT PRIMARY KEY," + KEY_SSID + " TEXT" + ")";
+	private static final String CREATE_PORT_TABLE = "CREATE TABLE " + TABLE_PORTS + "(" 
+			+ KEY_PROTOCOL + " TEXT PRIMARY KEY," + KEY_LOCAL_PORT + " INTEGER"
+			+ ")";
 
+	private Context context;
+	
 	public DatabaseHandler(Context context) {
 		super(context, DATABASE_NAME, null, DATABASE_VERSION);
+		this.context = context;
 	}
 
 	// Creating Tables
 	@Override
 	public void onCreate(SQLiteDatabase db) {
+		db.execSQL(CREATE_PORT_TABLE);
 		db.execSQL(CREATE_BSSID_TABLE);
+		db.execSQL(CREATE_ATTACK_INFO_TABLE);
 		db.execSQL(CREATE_RECORD_TABLE);
-	}
+				
+		String[] protocols = context.getResources().getStringArray(R.array.protocols);
+		String packageName = Protocol.class.getPackage().getName();
 
+		//Initialize Port Table
+		for (String protocol : protocols) {
+			try {				
+				int port = ((Protocol<?>) Class.forName(String.format("%s.%s", packageName, protocol)).newInstance()).getPort();
+		        db.execSQL("INSERT INTO " + TABLE_PORTS + " VALUES ( '" + protocol + "'," + port + ")");
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+		}
+	}
+	
 	// Upgrading database
 	@Override
 	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 		// Drop older table if existed
 		db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECORDS);
+		db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTACK_INFO);
 		db.execSQL("DROP TABLE IF EXISTS " + TABLE_BSSIDS);
+		db.execSQL("DROP TABLE IF EXISTS " + TABLE_PORTS);
 		
 		// Create tables again
 		onCreate(db);
@@ -91,24 +134,32 @@ public class DatabaseHandler extends SQLiteOpenHelper {
 		ContentValues bssidValues = new ContentValues();
 		bssidValues.put(KEY_BSSID, record.getBSSID());
 		bssidValues.put(KEY_SSID, record.getSSID());
+		bssidValues.put(KEY_LATITUDE, record.getLatitude());
+		bssidValues.put(KEY_LONGITUDE, record.getLongitude());
+		bssidValues.put(KEY_ACCURACY, record.getAccuracy());
+		
+		ContentValues attackValues = new ContentValues();
+		attackValues.put(KEY_ATTACK_ID, record.getAttack_id()); // Log Attack ID
+		attackValues.put(KEY_PROTOCOL, record.getProtocol().toString());
+		attackValues.put(KEY_EXTERNAL_IP, record.getExternalIP());
+		attackValues.put(KEY_LOCAL_IP, record.getLocalIP().getAddress()); // Log Local IP
+		attackValues.put(KEY_LOCAL_HOSTNAME, record.getLocalIP().getHostName());
+		attackValues.put(KEY_REMOTE_IP, record.getRemoteIP().getAddress()); // Log Remote IP
+		attackValues.put(KEY_REMOTE_HOSTNAME, record.getRemoteIP().getHostName());
+		attackValues.put(KEY_REMOTE_PORT, record.getRemotePort()); // Log Remote Port
+		attackValues.put(KEY_BSSID, record.getBSSID());
 		
 		ContentValues recordValues = new ContentValues();
+		recordValues.put(KEY_ID, record.getId()); // Log Message Number
 		recordValues.put(KEY_ATTACK_ID, record.getAttack_id()); // Log Attack ID
-		recordValues.put(KEY_PROTOCOL, record.getProtocol().toString());
 		recordValues.put(KEY_TYPE, record.getType().name()); // Log Type
 		recordValues.put(KEY_TIME, record.getTimestamp()); // Log Timestamp
-		recordValues.put(KEY_EXTERNAL_IP, record.getExternalIP());
-		recordValues.put(KEY_LOCAL_IP, record.getLocalIP().getAddress()); // Log Local IP
-		recordValues.put(KEY_LOCAL_HOSTNAME, record.getLocalIP().getHostName());
-		recordValues.put(KEY_LOCAL_PORT, record.getLocalPort()); // Log Local Port
-		recordValues.put(KEY_REMOTE_IP, record.getRemoteIP().getAddress()); // Log Remote IP
-		recordValues.put(KEY_REMOTE_HOSTNAME, record.getRemoteIP().getHostName());
-		recordValues.put(KEY_REMOTE_PORT, record.getRemotePort()); // Log Remote Port
-		recordValues.put(KEY_BSSID, record.getBSSID());
 		recordValues.put(KEY_PACKET, record.getPacket()); // Log Packet
+		
 
 		// Inserting Rows
 		db.insertWithOnConflict(TABLE_BSSIDS, null, bssidValues, SQLiteDatabase.CONFLICT_REPLACE);
+		db.insertWithOnConflict(TABLE_ATTACK_INFO, null, attackValues, SQLiteDatabase.CONFLICT_REPLACE);
 		db.insert(TABLE_RECORDS, null, recordValues);
 		db.close(); // Closing database connection
 	}
@@ -123,17 +174,20 @@ public class DatabaseHandler extends SQLiteOpenHelper {
 		try {
 		record.setId(Integer.parseInt(cursor.getString(0)));
 		record.setAttack_id(cursor.getLong(1));
-		record.setProtocol(cursor.getString(2));
-		record.setType(cursor.getString(3).equals("SEND") ? TYPE.SEND : TYPE.RECEIVE);
-		record.setTimestamp(cursor.getLong(4));
-		record.setExternalIP(cursor.getString(5));
-		record.setLocalIP(InetAddress.getByAddress(cursor.getString(7), cursor.getBlob(6)));
-		record.setLocalPort(Integer.parseInt(cursor.getString(8)));
+		record.setType(cursor.getString(2).equals("SEND") ? TYPE.SEND : TYPE.RECEIVE);
+		record.setTimestamp(cursor.getLong(3));
+		record.setPacket(cursor.getString(4));
+		record.setProtocol(cursor.getString(5));
+		record.setExternalIP(cursor.getString(6));
+		record.setLocalIP(InetAddress.getByAddress(cursor.getString(8), cursor.getBlob(7)));
 		record.setRemoteIP(InetAddress.getByAddress(cursor.getString(10), cursor.getBlob(9)));
 		record.setRemotePort(Integer.parseInt(cursor.getString(11)));
 		record.setBSSID(cursor.getString(12));
-		record.setPacket(cursor.getString(13));
-		record.setSSID(cursor.getString(14));
+		record.setSSID(cursor.getString(13));
+		record.setLatitude(Double.parseDouble(cursor.getString(14)));
+		record.setLongitude(Double.parseDouble(cursor.getString(15)));
+		record.setAccuracy(Float.parseFloat(cursor.getString(16)));
+		record.setLocalPort(Integer.parseInt(cursor.getString(17)));
 		} catch (UnknownHostException e) {
 			e.printStackTrace();
 		}
@@ -146,7 +200,7 @@ public class DatabaseHandler extends SQLiteOpenHelper {
 	 * @return The {@link Record}.
 	 */
 	public Record getRecord(int id) {
-		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " WHERE " + KEY_ID + " = " + id;
+		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS + " WHERE " + KEY_ID + " = " + id;
 		SQLiteDatabase db = this.getReadableDatabase();
 
 		Cursor cursor = db.rawQuery(selectQuery, null);
@@ -168,14 +222,16 @@ public class DatabaseHandler extends SQLiteOpenHelper {
 	public ArrayList<Record> getAllRecords() {
 		ArrayList<Record> recordList = new ArrayList<Record>();
 		// Select All Query
-		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS;
+		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS;
 
 		SQLiteDatabase db = this.getWritableDatabase();
 		Cursor cursor = db.rawQuery(selectQuery, null);
 
+		Log.i("Database", "Start loop");
 		// looping through all rows and adding to list
 		if (cursor.moveToFirst()) {
 			do {
+				Log.i("Database", "Add Record");
 				Record record = createRecord(cursor);				
 				// Adding record to list
 				recordList.add(record);
@@ -193,7 +249,7 @@ public class DatabaseHandler extends SQLiteOpenHelper {
 	 * @return The {@link Record}.
 	 */
     public Record getRecordOfAttackId(long attack_id) {
-        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " WHERE " + KEY_ATTACK_ID + " = " + attack_id + " GROUP BY " + KEY_ATTACK_ID;
+        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS + " WHERE " + KEY_ATTACK_ID + " = " + attack_id + " GROUP BY " + KEY_ATTACK_ID;
         SQLiteDatabase db = this.getReadableDatabase();
         Cursor cursor = db.rawQuery(selectQuery, null);
         Record record = null;
@@ -214,7 +270,7 @@ public class DatabaseHandler extends SQLiteOpenHelper {
 	 */
     public ArrayList<Record> getAllReceivedRecordsOfEachAttack() {
     	ArrayList<Record> recordList = new ArrayList<Record>();
-        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " WHERE " + KEY_TYPE + "='RECEIVE'" + " ORDER BY " + KEY_TIME;
+        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS + " WHERE " + KEY_TYPE + "='RECEIVE'" + " ORDER BY " + KEY_TIME;
         SQLiteDatabase db = this.getReadableDatabase();
         Cursor cursor = db.rawQuery(selectQuery, null);
 		
@@ -239,7 +295,7 @@ public class DatabaseHandler extends SQLiteOpenHelper {
 	 */
     public ArrayList<Record> getRecordOfEachAttack() {
     	ArrayList<Record> recordList = new ArrayList<Record>();
-        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " GROUP BY " + KEY_ATTACK_ID;
+        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS + " GROUP BY " + KEY_ATTACK_ID;
         SQLiteDatabase db = this.getReadableDatabase();
         Cursor cursor = db.rawQuery(selectQuery, null);
 		
@@ -265,7 +321,7 @@ public class DatabaseHandler extends SQLiteOpenHelper {
 	 */
     public ArrayList<Record> getRecordOfEachAttack(long attack_id) {
     	ArrayList<Record> recordList = new ArrayList<Record>();
-        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " WHERE " + KEY_ATTACK_ID + " > " + attack_id + " GROUP BY " + KEY_ATTACK_ID;
+        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS + " WHERE " + KEY_ATTACK_ID + " > " + attack_id + " GROUP BY " + KEY_ATTACK_ID;
         SQLiteDatabase db = this.getReadableDatabase();
         Cursor cursor = db.rawQuery(selectQuery, null);
 		
@@ -305,7 +361,7 @@ public class DatabaseHandler extends SQLiteOpenHelper {
 	 * @return The number of different attack_ids in the database.
 	 */
     public int getAttackCount() {
-        String countQuery = "SELECT  * FROM " + TABLE_RECORDS + " GROUP BY " + KEY_ATTACK_ID;
+        String countQuery = "SELECT  * FROM " + TABLE_ATTACK_INFO;
         SQLiteDatabase db = this.getReadableDatabase();
         Cursor cursor = db.rawQuery(countQuery, null);
         int result = cursor.getCount();
@@ -322,7 +378,7 @@ public class DatabaseHandler extends SQLiteOpenHelper {
 	 * @return The number of different attack_ids in the database.
 	 */
     public int getAttackPerProtokolCount(String protocol) {
-        String countQuery = "SELECT  * FROM " + TABLE_RECORDS + " WHERE " + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " GROUP BY " + KEY_ATTACK_ID;
+        String countQuery = "SELECT  * FROM " + TABLE_ATTACK_INFO + " WHERE " + KEY_PROTOCOL + " = " + "'" + protocol + "'";
         SQLiteDatabase db = this.getReadableDatabase();
         Cursor cursor = db.rawQuery(countQuery, null);
         int result = cursor.getCount();
@@ -338,7 +394,7 @@ public class DatabaseHandler extends SQLiteOpenHelper {
     * @return The smallest attack id stored in the database.
     */
     public long getSmallestAttackId(){
-    	String selectQuery = "SELECT MIN(" + KEY_ATTACK_ID +") FROM " + TABLE_RECORDS;
+    	String selectQuery = "SELECT MIN(" + KEY_ATTACK_ID +") FROM " + TABLE_ATTACK_INFO;
         SQLiteDatabase db = this.getReadableDatabase();
         Cursor cursor = db.rawQuery(selectQuery, null);        
         int result;
@@ -358,7 +414,7 @@ public class DatabaseHandler extends SQLiteOpenHelper {
      * @return The highest attack id stored in the database.
      */
     public long getHighestAttackId(){
-    	String selectQuery = "SELECT MAX(" + KEY_ATTACK_ID +") FROM " + TABLE_RECORDS;
+    	String selectQuery = "SELECT MAX(" + KEY_ATTACK_ID +") FROM " + TABLE_ATTACK_INFO;
         SQLiteDatabase db = this.getReadableDatabase();
         Cursor cursor = db.rawQuery(selectQuery, null);
         int result;
@@ -380,7 +436,7 @@ public class DatabaseHandler extends SQLiteOpenHelper {
      * @return True if an attack on the given protocol has been recorded in a network with the given BSSID, else false.
      */
     public boolean bssidSeen(String protocol, String BSSID){
-        String countQuery = "SELECT  * FROM " + TABLE_RECORDS + " WHERE " + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " AND " + KEY_BSSID + " = " + "'" + BSSID + "'";
+        String countQuery = "SELECT  * FROM " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS+ " WHERE " + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " AND " + KEY_BSSID + " = " + "'" + BSSID + "'";
         SQLiteDatabase db = this.getReadableDatabase();
         Cursor cursor = db.rawQuery(countQuery, null);
         int result = cursor.getCount();
@@ -436,9 +492,11 @@ public class DatabaseHandler extends SQLiteOpenHelper {
     public void deleteByBSSID(String bssid){
     	SQLiteDatabase db = this.getReadableDatabase();
     	db.delete(TABLE_RECORDS, KEY_BSSID + " = ?", new String[]{bssid});
+    	db.delete(TABLE_ATTACK_INFO, KEY_BSSID + " = ?", new String[]{bssid});
     	db.close();
     }
     
+  //TODO Delete statement überarbeiten
     /**
      * Deletes all records from {@link #TABLE_RECORDS} with a time stamp smaller then the given
      * @param date A Date represented in milliseconds.
@@ -446,6 +504,8 @@ public class DatabaseHandler extends SQLiteOpenHelper {
     public void deleteByDate(long date){
     	SQLiteDatabase db = this.getReadableDatabase();
     	String deleteQuery = "DELETE  FROM " + TABLE_RECORDS + " WHERE " + KEY_TIME + " < " + date;
+    	//TODO Delete statement überarbeiten
+//    	String deleteQuery2 = "DELETE "
     	db.execSQL(deleteQuery);
     	db.close();
     }
@@ -456,6 +516,7 @@ public class DatabaseHandler extends SQLiteOpenHelper {
     public void clearData(){
     	SQLiteDatabase db = this.getReadableDatabase();
         db.delete(TABLE_RECORDS, null, null);
+        db.delete(TABLE_ATTACK_INFO, null, null);
         db.close();
     }
 }

+ 112 - 0
src/de/tudarmstadt/informatik/hostage/logging/MyLocationManager.java

@@ -0,0 +1,112 @@
+package de.tudarmstadt.informatik.hostage.logging;
+
+import java.util.Timer;
+import java.util.TimerTask;
+
+import android.content.Context;
+import android.location.Location;
+import android.location.LocationListener;
+import android.location.LocationManager;
+import android.os.Bundle;
+import android.util.Log;
+import android.widget.Toast;
+
+public class MyLocationManager {
+	
+	private LocationManager locationManager;
+	private static Location newestLocation;
+	private Context context;
+	
+	
+	public MyLocationManager(Context context){
+		// Acquire a reference to the system Location Manager
+		locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
+		newestLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
+		this.context = context;
+	}
+
+	// Define a listener that responds to location updates
+	LocationListener locationListener = new LocationListener() {
+	    public void onLocationChanged(Location location) {
+			Toast.makeText(context, location.getLatitude() +  " " + location.getLongitude() + " " + location.getAccuracy(), Toast.LENGTH_SHORT).show();
+
+
+	      // Called when a new location is found by the network location provider.
+	      if(isBetterLocation(location, newestLocation)){
+	    	  newestLocation = location;
+	      }
+	    }
+
+	    public void onStatusChanged(String provider, int status, Bundle extras) {}
+
+	    public void onProviderEnabled(String provider) {}
+
+	    public void onProviderDisabled(String provider) {}
+	  };
+	
+
+
+	  /** Determines whether one Location reading is better than the current Location fix
+	    * @param location  The new Location that you want to evaluate
+	    * @param currentBestLocation  The current Location fix, to which you want to compare the new one
+	    */
+	  private boolean isBetterLocation(Location location, Location currentBestLocation) {
+	      if (currentBestLocation == null) {
+	          // A new location is always better than no location
+	          return true;
+	      }
+
+	      // Check whether the new location fix is more or less accurate
+	      int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
+	      boolean isMoreAccurate = accuracyDelta < 0;
+
+
+	      // Determine location quality using a combination of timeliness and accuracy
+	      if (isMoreAccurate) {
+	          return true;
+	      }
+	      return false;
+	  }
+	  
+	  public void startUpdates(){
+		  	boolean gpsEnabled = false;
+		  	boolean networkEnabled = false;
+	        //exceptions will be thrown if provider is not permitted.
+	        try{
+	        	gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
+	        }catch(Exception ex){}
+	        try{
+	        	networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
+	        }catch(Exception ex){}
+	         
+	        //don't start listeners if no provider is enabled
+	        if(!gpsEnabled && !networkEnabled)
+	        	return;	        
+
+			// Register the listener with the Location Manager to receive location updates
+	        if(gpsEnabled)
+	        	locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
+	        if(networkEnabled)
+	        	locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
+	  }
+	  
+	  public void getUpdates(long time){
+		  	startUpdates();
+	        Timer timer1=new Timer();
+	        timer1.schedule(new StopTask() , time);
+	  }
+	   
+	  class StopTask extends TimerTask {
+	        public void run() {
+	        	 stopUpdates();
+	        }
+	    }
+	  
+	  public void stopUpdates(){
+		  locationManager.removeUpdates(locationListener);
+	  }
+
+	  public static Location getNewestLocation(){
+		  return newestLocation;
+	  }
+}

+ 46 - 1
src/de/tudarmstadt/informatik/hostage/logging/Record.java

@@ -34,6 +34,9 @@ public class Record implements Serializable {
 	private int remotePort;
 	private String BSSID;
 	private String SSID;
+	private double latitude;
+	private double longitude;
+	private float accuracy;
 	private String packet;	
 
 
@@ -206,6 +209,48 @@ public class Record implements Serializable {
 		SSID = sSID;
 	}
 
+	/**
+	 * @return the latitude
+	 */
+	public double getLatitude() {
+		return latitude;
+	}
+
+	/**
+	 * @param latitude the latitude to set
+	 */
+	public void setLatitude(double latitude) {
+		this.latitude = latitude;
+	}
+
+	/**
+	 * @return the longitude
+	 */
+	public double getLongitude() {
+		return longitude;
+	}
+
+	/**
+	 * @param longitude the longitude to set
+	 */
+	public void setLongitude(double longitude) {
+		this.longitude = longitude;
+	}
+
+	/**
+	 * @return the accuracy
+	 */
+	public float getAccuracy() {
+		return accuracy;
+	}
+
+	/**
+	 * @param accuracy the accuracy to set
+	 */
+	public void setAccuracy(float accuracy) {
+		this.accuracy = accuracy;
+	}
+
 	/**
 	 * @return the packet
 	 */
@@ -239,7 +284,7 @@ public class Record implements Serializable {
 		switch (format){
 			// ViewLogTable format: contains all important information about an attack.
 			case 0: 
-				return String.format("%d: %s %s\nIn %s\n(%s)\nFrom [%s:%d]\nTo [%s:%d]\n%s\n\n", attack_id, protocol, ((type == TYPE.SEND) ? "SEND" : "RECEIVE"), SSID, BSSID, remoteIP.getHostAddress(), remotePort, localIP.getHostAddress(), localPort, LogViewFormatter.format(getProtocol(), getPacket()));	
+				return String.format("%d: %s %s\nIn %s\n(%s)\nFrom [%s:%d]\nTo [%s:%d]\nLatitude: %f\nLongitude: %f\n%s\n\n", attack_id, protocol, ((type == TYPE.SEND) ? "SEND" : "RECEIVE"), SSID, BSSID, remoteIP.getHostAddress(), remotePort, localIP.getHostAddress(), localPort, getLatitude(), getLongitude(), LogViewFormatter.format(getProtocol(), getPacket()));	
 			// TraCINg Upload format, replaces internal ip's with external ip of network
 			case 1: 
 				return String.format("{ \"sensor\":{\"type\": \"Honeypot\", \"name\": \"HOsTaGe\"}, \"type\": \"%s\", \"src\":{\"ip\": \"%s\", \"port\": %d}, \"dst\":{\"ip\": \"%s\", \"port\": %d} }", protocol + " server access", externalIP, remotePort, externalIP, localPort);

+ 21 - 25
src/de/tudarmstadt/informatik/hostage/ui/MainActivity.java

@@ -120,7 +120,7 @@ public class MainActivity extends Activity {
 	private String protocolClicked;
 	
 	
-	
+	@Override
 	protected void onCreate(Bundle savedInstanceState) {
 		super.onCreate(savedInstanceState);
         MainActivity.context = getApplicationContext();	//set context
@@ -135,13 +135,13 @@ public class MainActivity extends Activity {
 		sessionEditor = sessionPref.edit();
 	}
 
-	
+	@Override
 	public boolean onCreateOptionsMenu(Menu menu) {
 		getMenuInflater().inflate(R.menu.main, menu);
 		return true;
 	}
 	
-	
+	@Override
 	public boolean onOptionsItemSelected(MenuItem item) {
 	    // Handle item selection
 	    switch (item.getItemId()) {
@@ -156,7 +156,7 @@ public class MainActivity extends Activity {
         return super.onOptionsItemSelected(item);
 	}
 
-	
+	@Override
 	protected void onStart() {
 		super.onStart();
 		//Register Broadcast Receiver
@@ -177,7 +177,7 @@ public class MainActivity extends Activity {
 		updateConnectionInfText();
 	}
 
-	
+	@Override
 	protected void onStop() {
 		//Unbind running service
 		if (isServiceRunning()) {
@@ -189,7 +189,7 @@ public class MainActivity extends Activity {
 		super.onStop();
 	}
 	
-	
+	@Override
 	protected void onDestroy(){
 		super.onDestroy();
 		// If service not running delete session data
@@ -230,14 +230,8 @@ public class MainActivity extends Activity {
 	 * Else notifies the user that service could not be started.
 	 */
 	private void startAndBind() {
-		if(HelperUtils.getBSSID(this) != null){
-			startService(getServiceIntent());
-			bindService();			
-		} else{
-			ToggleButton button = (ToggleButton) findViewById(R.id.toggleButtonOnOff);
-			button.setChecked(false);
-			Toast.makeText(getApplicationContext(), "To start a service, first connect to a wireless network.", Toast.LENGTH_SHORT).show();
-		}
+		startService(getServiceIntent());
+		bindService();	
 	}
 	
 	/**
@@ -276,7 +270,7 @@ public class MainActivity extends Activity {
 		 * After the service is bound, check which has been clicked and start it.
 		 * @see android.content.ServiceConnection#onServiceConnected(android.content.ComponentName)
 		 */
-		
+		@Override
 		public void onServiceConnected(ComponentName name, IBinder service) {
 			mService = ((LocalBinder) service).getService();
 			if(protocolClicked != null && protocolClicked.equals("PANIC")){
@@ -291,7 +285,7 @@ public class MainActivity extends Activity {
 		 * After the service is unbound, delete reference.
 		 * @see android.content.ServiceConnection#onServiceDisconnected(android.content.ComponentName)
 		 */
-		
+		@Override
 		public void onServiceDisconnected(ComponentName name) {
 			mService = null;			
 		}
@@ -331,7 +325,7 @@ public class MainActivity extends Activity {
 		listView.setAdapter(adapter);
 		listView.setOnTouchListener(new OnTouchListener() {
 
-			
+			@Override
 			public boolean onTouch(View v, MotionEvent event) {
 				return gestureDetector.onTouchEvent(event);
 			}
@@ -339,7 +333,7 @@ public class MainActivity extends Activity {
 		});
 		listView.setOnItemClickListener(new OnItemClickListener() {
 
-			
+			@Override
 			public void onItemClick(AdapterView<?> parent, View view,
 					int position, long id) {
 				String protocolName = (String) ((HashMap<?, ?>) adapter
@@ -401,7 +395,7 @@ public class MainActivity extends Activity {
 	 * @see #BROADCAST
 	 */
 	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
-		
+		@Override
 		public void onReceive(Context context, Intent intent) {
 			// Update user interface.
 			updateUI();
@@ -429,14 +423,16 @@ public class MainActivity extends Activity {
 	 * Receiver for network state change events.
 	 */
 	private BroadcastReceiver netReceiver = new BroadcastReceiver() {
-		
+		@Override
 		public void onReceive(Context context, Intent intent) {
-			String bssid_old = sessionPref.getString(BSSID, "");
+/*			String bssid_old = sessionPref.getString(BSSID, "");
 			String bssid_new = HelperUtils.getBSSID(context);
+
 			if ((bssid_new == null || !bssid_new.equals(bssid_old)) && serviceBound) {
 				Toast.makeText(getApplicationContext(),"Connection changed! Services stopped!", Toast.LENGTH_LONG).show();
 				unbindService();
 			}	
+*/			
 			updateConnectionInfText();
 		}
 	};	
@@ -630,7 +626,7 @@ public class MainActivity extends Activity {
 	 * @author Lars Pandikow
 	 */
 	private class SetExternalIPTask extends AsyncTask<String, Void, String>{	
-		 
+		 @Override
 		    protected String doInBackground(String... url) {
 		   	 String ipAddress = null;
 					try {
@@ -651,7 +647,7 @@ public class MainActivity extends Activity {
 			return ipAddress;
 		    }
 			 
-			
+			@Override
 			protected void onPostExecute(String result){
 				sessionEditor.putString(MainActivity.EXTERNAL_IP, result);
 				sessionEditor.commit();
@@ -666,7 +662,7 @@ public class MainActivity extends Activity {
 
 	/*############# Help functions for animation ##################*/
 	
-	
+	@Override
 	public boolean onTouchEvent(MotionEvent event) {
 		return gestureDetector.onTouchEvent(event);
 	}
@@ -711,7 +707,7 @@ public class MainActivity extends Activity {
 	}
 
 	SimpleOnGestureListener simpleOnGestureListener = new SimpleOnGestureListener() {
-		
+		@Override
 		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
 				float velocityY) {
 			float sensitvity = 50;