Browse Source

Updated portscan detection
Deleted unnecessary Log outputs

Lars Pandikow 10 years ago
parent
commit
745a674851

+ 5 - 4
AndroidManifest.xml

@@ -45,15 +45,16 @@
             android:configChanges="keyboardHidden|orientation|screenSize"
             android:label="@string/app_name"
             android:screenOrientation="portrait" >
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
+
         </activity>
         <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.MainActivity"
             android:configChanges="keyboardHidden|orientation|screenSize"
             android:label="@string/app_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>            
         </activity>
         <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.ViewLog"

+ 23 - 10
src/de/tudarmstadt/informatik/hostage/ConnectionGuard.java

@@ -1,6 +1,7 @@
 package de.tudarmstadt.informatik.hostage;
 
-import de.tudarmstadt.informatik.hostage.logging.Logger;
+import android.util.Log;
+
 
 public class ConnectionGuard {
 
@@ -9,23 +10,35 @@ public class ConnectionGuard {
 	private ConnectionGuard() {
 	}
 
-	private final static long ONE_SECOND_IN_NANOSECONDS = 1000000000;
+	public final static long ONE_SECOND_IN_NANOSECONDS = 1000000000;
 
 	private static long lastTimestamp = 0;
 	private static String lastIP = "";
 	private static String lastProtocol = "";
 
-	public static void registerConnection(String protocol, String ip) {
-		long timestamp = System.nanoTime();
+	public synchronized static boolean registerConnection(String protocol, String ip) {
+		long timestamp = System.nanoTime();		
+		boolean result = detectedPortscan(protocol, ip, timestamp);
+		lastTimestamp = timestamp;
+		lastIP = ip;
+		lastProtocol = protocol;
+		return result;
+	}
+	
+	public synchronized static boolean detectedPortscan(String protocol, String ip){
+		return detectedPortscan(protocol, ip, System.nanoTime());
+	}
+	
+	public synchronized static boolean detectedPortscan(String protocol, String ip, long timestamp) {
+		boolean result = false;
 		boolean firstConnection = (lastTimestamp == 0);
 		boolean belowThreshold = ((timestamp - lastTimestamp) < ONE_SECOND_IN_NANOSECONDS);
-		boolean sameIP = (lastIP == ip);
-		boolean sameProtocol = (lastProtocol == protocol);
+		boolean sameIP = (lastIP.equals(ip));
+		boolean sameProtocol = (lastProtocol.equals(protocol));
 		if (!firstConnection && sameIP && belowThreshold && !sameProtocol) {
-//TODO LOG PORTSCAN			Logger.logPortscan(Hostage.getContext(), System.currentTimeMillis(), ip);
+			result = true;
 		}
-		lastTimestamp = timestamp;
-		lastIP = ip;
-		lastProtocol = protocol;
+		
+		return result;
 	}
 }

+ 0 - 2
src/de/tudarmstadt/informatik/hostage/Handler.java

@@ -10,7 +10,6 @@ import android.content.Context;
 import android.content.SharedPreferences;
 import android.content.SharedPreferences.Editor;
 import android.preference.PreferenceManager;
-import android.util.Log;
 import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
 import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
 import de.tudarmstadt.informatik.hostage.logging.Logger;
@@ -103,7 +102,6 @@ public class Handler implements Runnable {
 		thread.interrupt();
 		try {
 			client.close();
-			Log.i("HoneyHandler", "Socket closed: " + client.isClosed());
 		} catch (Exception e) {
 			
 		} 

+ 0 - 1
src/de/tudarmstadt/informatik/hostage/Hostage.java

@@ -64,7 +64,6 @@ public class Hostage extends Service {
 	/**
 	 * Task to find out the external IP.
 	 * 
-	 * @author Lars Pandikow
 	 */
 	private class SetExternalIPTask extends AsyncTask<String, Void, String> {
 		@Override

+ 80 - 9
src/de/tudarmstadt/informatik/hostage/Listener.java

@@ -13,8 +13,17 @@ import javax.net.ssl.SSLContext;
 import javax.net.ssl.SSLSocket;
 import javax.net.ssl.SSLSocketFactory;
 
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.content.SharedPreferences.Editor;
 import android.os.AsyncTask;
+import android.preference.PreferenceManager;
+import android.util.Log;
 
+import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
+import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
+import de.tudarmstadt.informatik.hostage.logging.Logger;
+import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
 import de.tudarmstadt.informatik.hostage.net.MyServerSocketFactory;
 import de.tudarmstadt.informatik.hostage.protocol.HTTP;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol;
@@ -171,14 +180,36 @@ public class Listener implements Runnable {
 	private void addHandler() {
 		if (conReg.isConnectionFree()) {
 			try {
-				Socket client = server.accept();
-				ConnectionGuard.registerConnection(this.getProtocolName(), client.getInetAddress().getHostAddress());
-				conReg.newOpenConnection();
-				if (protocol.isSecure()) {
-					startSecureHandler(client);
-				} else {
-					startHandler(client);
-				}
+				final Socket client = server.accept();
+				final String protocolName = this.getProtocolName();
+				new Thread( new Runnable() {
+				    @Override
+				    public void run() {
+				    	try {
+				    		String ip = client.getInetAddress().getHostAddress();
+				    		if (ConnectionGuard.registerConnection(protocolName, ip)){
+				    			Log.i("Listener", "Portscan detected.");
+				    			return;
+				    		}
+				    		
+				    		Thread.sleep(ConnectionGuard.ONE_SECOND_IN_NANOSECONDS / 1000);
+				    		if(ConnectionGuard.detectedPortscan(protocolName, ip)){
+				    			Log.i("Listener", "Portscan detected.");
+				    			logPortscan(client);
+				    		}else{
+								if (protocol.isSecure()) {
+									startSecureHandler(client);
+								} else {
+									startHandler(client);
+								}				  
+								conReg.newOpenConnection();
+				    		}							
+							
+				    	} catch (Exception e) {
+				    		e.printStackTrace();
+				    	}
+				    }
+				}).start();
 			} catch (Exception e) {
 				e.printStackTrace();
 			}
@@ -226,6 +257,46 @@ public class Listener implements Runnable {
 		SSLSocket sslClient = (SSLSocket) factory.createSocket(client, null, client.getPort(), false);
 		sslClient.setUseClientMode(false);
 		handlers.add(newInstance(service, this, protocol.getClass().newInstance(), sslClient));
-	}
+	}	
 	
+	/**
+	 * Starts a Handler with Portscan as Protocol. Afterwards kills it. For Logging purpose only!
+	 */
+	private void logPortscan(Socket client){
+		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(service);
+		SharedPreferences connInfo = service.getSharedPreferences(service.getString(R.string.connection_info), Context.MODE_PRIVATE);
+
+		Editor editor = pref.edit();
+		int attack_id = pref.getInt("ATTACK_ID_COUNTER", 0);
+		editor.putInt("ATTACK_ID_COUNTER", attack_id + 1);
+		editor.commit();
+		
+		AttackRecord attackRecord = new AttackRecord();
+		attackRecord.setAttack_id(attack_id);			
+		attackRecord.setProtocol("PORTSCAN");
+		attackRecord.setExternalIP(connInfo.getString(service.getString(R.string.connection_info_external_ip), null));
+		attackRecord.setLocalIP(client.getLocalAddress().getHostAddress());
+		attackRecord.setLocalPort(0);
+		attackRecord.setRemoteIP(client.getInetAddress().getHostAddress());
+		attackRecord.setRemotePort(client.getPort());
+		attackRecord.setBssid(connInfo.getString(service.getString(R.string.connection_info_bssid), null));
+		
+		NetworkRecord networkRecord = new NetworkRecord();
+		networkRecord.setBssid(connInfo.getString(service.getString(R.string.connection_info_bssid), null));		
+		networkRecord.setSsid(connInfo.getString(service.getString(R.string.connection_info_ssid), null));		
+		if (MyLocationManager.getNewestLocation() != null) {
+			networkRecord.setLatitude(MyLocationManager.getNewestLocation().getLatitude());
+			networkRecord.setLongitude(MyLocationManager.getNewestLocation().getLongitude());
+			networkRecord.setAccuracy(MyLocationManager.getNewestLocation().getAccuracy());
+			networkRecord.setTimestampLocation(MyLocationManager.getNewestLocation().getTime());
+		} else {
+			networkRecord.setLatitude(0.0);
+			networkRecord.setLongitude(0.0);
+			networkRecord.setAccuracy(Float.MAX_VALUE);
+			networkRecord.setTimestampLocation(0);
+		}
+		
+		Logger.log(Hostage.getContext(), attackRecord);
+		Logger.log(Hostage.getContext(), networkRecord);
+	}
 }

+ 168 - 173
src/de/tudarmstadt/informatik/hostage/location/MyLocationManager.java

@@ -1,173 +1,168 @@
-package de.tudarmstadt.informatik.hostage.location;
-
-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;
-
-public class MyLocationManager {
-
-	class StopTask extends TimerTask {
-		@Override
-		public void run() {
-			stopUpdates();
-		}
-	}
-
-	private LocationManager locationManager;
-	/**
-	 * Static variable that always holds the newest location update.
-	 */
-	private static Location newestLocation = null;
-
-	private static final int TWO_MINUTES = 1000 * 60 * 2;
-
-	public static Location getNewestLocation() {
-		return newestLocation;
-	}
-
-	// Define a listener that responds to location updates
-	LocationListener locationListener = new LocationListener() {
-		@Override
-		public void onLocationChanged(Location location) {
-			Log.i("MyLocationManager",
-					location.getLatitude() + " " + location.getLongitude()
-							+ " " + location.getAccuracy());
-
-			// Called when a new location is found by the network location
-			// provider.
-			if (isBetterLocation(location, newestLocation)) {
-				newestLocation = location;
-			}
-		}
-
-		@Override
-		public void onProviderDisabled(String provider) {
-		}
-
-		@Override
-		public void onProviderEnabled(String provider) {
-		}
-
-		@Override
-		public void onStatusChanged(String provider, int status, Bundle extras) {
-		}
-	};
-
-	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);
-	}
-
-	/**
-	 * Starts updating the location data for the given amount of time. Calls
-	 * itself recursive if no location data has been found yet and there are
-	 * still attempts left.
-	 * 
-	 * @param time
-	 *            Time to update location data
-	 * @param attempts
-	 *            Remaining attempts for recieving location data
-	 */
-	public void getUpdates(long time, int attempts) {
-		startUpdates();
-		attempts--;
-		Timer timer1 = new Timer();
-		timer1.schedule(new StopTask(), time);
-		if (newestLocation == null && attempts > 0)
-			getUpdates(time, attempts);
-	}
-
-	/**
-	 * Start updating
-	 * {@link de.tudarmstadt.informatik.hostage.location.MyLocationManager#newestLocatio
-	 * newestLocation} if a location provider is enabled and available.
-	 */
-	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 stopUpdates() {
-		locationManager.removeUpdates(locationListener);
-	}
-
-	/**
-	 * 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 newer or older
-		long timeDelta = location.getTime() - currentBestLocation.getTime();
-		boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
-		boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
-
-		// If it's been more than two minutes since the current location, use
-		// the new location
-		// because the user has likely moved
-		if (isSignificantlyNewer) {
-			return true;
-			// If the new location is more than two minutes older, it must be
-			// worse
-		} else if (isSignificantlyOlder) {
-			return false;
-		}
-
-		// 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;
-	}
-}
+package de.tudarmstadt.informatik.hostage.location;
+
+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;
+
+public class MyLocationManager {
+
+	class StopTask extends TimerTask {
+		@Override
+		public void run() {
+			stopUpdates();
+		}
+	}
+
+	private LocationManager locationManager;
+	/**
+	 * Static variable that always holds the newest location update.
+	 */
+	private static Location newestLocation = null;
+
+	private static final int TWO_MINUTES = 1000 * 60 * 2;
+
+	public static Location getNewestLocation() {
+		return newestLocation;
+	}
+
+	// Define a listener that responds to location updates
+	LocationListener locationListener = new LocationListener() {
+		@Override
+		public void onLocationChanged(Location location) {
+			// Called when a new location is found by the network location
+			// provider.
+			if (isBetterLocation(location, newestLocation)) {
+				newestLocation = location;
+			}
+		}
+
+		@Override
+		public void onProviderDisabled(String provider) {
+		}
+
+		@Override
+		public void onProviderEnabled(String provider) {
+		}
+
+		@Override
+		public void onStatusChanged(String provider, int status, Bundle extras) {
+		}
+	};
+
+	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);
+	}
+
+	/**
+	 * Starts updating the location data for the given amount of time. Calls
+	 * itself recursive if no location data has been found yet and there are
+	 * still attempts left.
+	 * 
+	 * @param time
+	 *            Time to update location data
+	 * @param attempts
+	 *            Remaining attempts for recieving location data
+	 */
+	public void getUpdates(long time, int attempts) {
+		startUpdates();
+		attempts--;
+		Timer timer1 = new Timer();
+		timer1.schedule(new StopTask(), time);
+		if (newestLocation == null && attempts > 0)
+			getUpdates(time, attempts);
+	}
+
+	/**
+	 * Start updating
+	 * {@link de.tudarmstadt.informatik.hostage.location.MyLocationManager#newestLocatio
+	 * newestLocation} if a location provider is enabled and available.
+	 */
+	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 stopUpdates() {
+		locationManager.removeUpdates(locationListener);
+	}
+
+	/**
+	 * 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 newer or older
+		long timeDelta = location.getTime() - currentBestLocation.getTime();
+		boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
+		boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
+
+		// If it's been more than two minutes since the current location, use
+		// the new location
+		// because the user has likely moved
+		if (isSignificantlyNewer) {
+			return true;
+			// If the new location is more than two minutes older, it must be
+			// worse
+		} else if (isSignificantlyOlder) {
+			return false;
+		}
+
+		// 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;
+	}
+}

+ 19 - 7
src/de/tudarmstadt/informatik/hostage/persistence/HostageDBOpenHelper.java

@@ -10,7 +10,6 @@ import android.content.Context;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
-import android.util.Log;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
 import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
@@ -167,7 +166,6 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 	 *            The added {@link AttackRecord} .
 	 */
 	public void addAttackRecord(AttackRecord record) {
-		Log.i("DBHelper", "Add Attack Record with id: " + record.getAttack_id());
 		SQLiteDatabase db = this.getWritableDatabase();
 
 		ContentValues attackValues = new ContentValues();
@@ -210,7 +208,6 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 			portscanCount++;
 		}else { attackCount++; }
 			
-		Log.i("DBHelper", "Update number of attack: " + attackCount);
 		
 		ContentValues synInfoValues = new ContentValues();
 		synInfoValues.put(SyncInfoEntry.COLUMN_NAME_BSSID, record.getBssid());
@@ -651,8 +648,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 		return networkInformation;
 	}
 
-	public void updateNetworkInformation(ArrayList<NetworkRecord> networkInformation) {
-		Log.i("DatabaseHandler", "Starte updating");
+	public void updateNetworkInformation(ArrayList<NetworkRecord> networkInformation) {;
 		for (NetworkRecord record : networkInformation) {
 			updateNetworkInformation(record);
 		}
@@ -678,6 +674,24 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 	}
 	
 	
+	/**
+	 * Updates the the timestamp of a single device id
+	 * @param devices The Device id
+	 * @param timestamp The synchronization timestamp
+	 */
+	public void updateSyncDevice(String devices, long timestamp){
+		SQLiteDatabase db = this.getReadableDatabase();		
+		ContentValues deviceValues = new ContentValues();
+		deviceValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_ID, devices);
+		deviceValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_TIMESTAMP, timestamp);
+		db.insertWithOnConflict(SyncDeviceEntry.TABLE_NAME, null, deviceValues, SQLiteDatabase.CONFLICT_REPLACE);
+		db.close();
+	}
+	
+	/**
+	 * Updates the Timestamps of synchronization devices from a HashMap.
+	 * @param devices HashMap of device ids and their synchronization timestamps.
+	 */
 	public void updateSyncDevices(HashMap<String, Long> devices){
 		SQLiteDatabase db = this.getReadableDatabase();		
 		for(String key : devices.keySet()){
@@ -1023,11 +1037,9 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 		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);

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/sync/tracing/TracingSyncService.java

@@ -80,8 +80,8 @@ public class TracingSyncService extends IntentService{
 			if (ACTION_START_SYNC.equals(action)) {
 				receiver = intent.getParcelableExtra(EXTRA_RECEIVER);
 				uploadNewRecords();
-				getRemoteData();
 				//TODO add: dbh.clearSyncInfos();
+				getRemoteData();
 				if(receiver != null){
 					receiver.send(SYNC_COMPLETE, null);
 				}