Browse Source

- Protocols can be started on specified port
- Ports over 1023 will not use porthack
- Replaced session preference with method calls in HoneyService
- Deleted port table from database

Lars 10 years ago
parent
commit
0def62f3fa

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/HoneyHandler.java

@@ -75,7 +75,7 @@ public class HoneyHandler implements Runnable {
 		TIMEOUT = pref.getInt("timeout", 30) * 1000;
 		// TODO ThreadSicher?
 		getAndIncrementAttackID(pref);
-		SharedPreferences sessionPref = service.getSharedPreferences(MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
+		SharedPreferences sessionPref = service.getSharedPreferences(MainActivity.CONNECTION_INFO, Context.MODE_PRIVATE);
 		BSSID = sessionPref.getString(MainActivity.BSSID, null);
 		SSID = sessionPref.getString(MainActivity.SSID, null);
 		externalIP = sessionPref.getString(MainActivity.EXTERNAL_IP, null);

+ 33 - 25
src/de/tudarmstadt/informatik/hostage/HoneyListener.java

@@ -43,15 +43,11 @@ public class HoneyListener implements Runnable {
 	private Protocol protocol;
 	private ServerSocket server;
 	private Thread thread;
+	private int port;
 
 	private HoneyService service;
-	// Shared Preferences
-	private SharedPreferences sessionPref;
 	private ConnectionRegister conReg;
 
-	// Editor for Shared preferences
-	private Editor sessionEditor;
-
 	private boolean running = false;
 
 	/**
@@ -74,8 +70,15 @@ public class HoneyListener implements Runnable {
 	public HoneyListener(HoneyService service, Protocol protocol) {
 		this.service = service;
 		this.protocol = protocol;
-		sessionPref = service.getApplicationContext().getSharedPreferences(MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
-		sessionEditor = sessionPref.edit();
+		port = protocol.getPort();
+		conReg = new ConnectionRegister(service);
+	}
+	
+	public HoneyListener(HoneyService service, Protocol protocol, int port) {
+		this.service = service;
+		this.protocol = protocol;
+		this.port = port;
+
 		conReg = new ConnectionRegister(service);
 	}
 
@@ -92,17 +95,22 @@ public class HoneyListener implements Runnable {
 	 * Starts the listener. Creates a server socket runs itself in a new Thread
 	 * and notifies the background service.
 	 */
-	public void start() {
+	public boolean start() {
 		try {
-			server = new MyServerSocketFactory().createServerSocket(protocol
-					.getPort());
+			if(port < 1024){
+				if(!MainActivity.porthackInstalled)
+					return false;
+				server = new MyServerSocketFactory().createServerSocket(port);
+			} else{
+				server = new ServerSocket(port);
+			}
 			(this.thread = new Thread(this)).start();
-			sessionEditor.putBoolean(protocol + MainActivity.LISTENER, true);
-			sessionEditor.commit();
-			service.notifyUI(protocol.toString(), MainActivity.LISTENER);
+			service.notifyUI(this.getClass().getName(), protocol.toString() + MainActivity.LISTENER);
 			running = true;
+			return true;
 		} catch (Exception e) {
 			e.printStackTrace();
+			return false;
 		}
 	}
 
@@ -114,9 +122,7 @@ public class HoneyListener implements Runnable {
 		try {
 			server.close();
 			thread.interrupt();
-			sessionEditor.putBoolean(protocol + MainActivity.LISTENER, false);
-			sessionEditor.commit();
-			service.notifyUI(protocol.toString(), MainActivity.LISTENER);
+			service.notifyUI(this.getClass().getName(), protocol.toString() + MainActivity.LISTENER);
 			running = false;
 		} catch (Exception e) {
 			e.printStackTrace();
@@ -131,6 +137,15 @@ public class HoneyListener implements Runnable {
 	public String getProtocolName() {
 		return protocol.toString();
 	}
+	
+	/**
+	 * Return the port number on which the listener listening.
+	 * 
+	 * @return Used port number.
+	 */
+	public int getPort() {
+		return port;
+	}
 
 	/**
 	 * Remove all terminated handlers from its internal ArrayList.
@@ -142,10 +157,7 @@ public class HoneyListener implements Runnable {
 			if (handler.isTerminated()) {
 				conReg.closeConnection();
 				iterator.remove();
-				int handlerCount = sessionPref.getInt(protocol + MainActivity.HANDLER_COUNT, 0);
-				sessionEditor.putInt(protocol + MainActivity.HANDLER_COUNT, handlerCount - 1);
-				sessionEditor.commit();
-				service.notifyUI(protocol.toString(), MainActivity.HANDLER_COUNT);
+				service.notifyUI(this.getClass().getName(), protocol.toString() + MainActivity.HANDLER_COUNT);
 			}
 		}
 	}
@@ -164,11 +176,7 @@ public class HoneyListener implements Runnable {
 				} else {
 					startHandler(client);
 				}
-				int handlerCount = sessionPref.getInt(protocol + MainActivity.HANDLER_COUNT, 0);
-				sessionEditor.putInt(protocol + MainActivity.HANDLER_COUNT, handlerCount + 1);
-				sessionEditor.commit();
-				service.notifyUI(protocol.toString(),
-						MainActivity.HANDLER_COUNT);
+				service.notifyUI(this.getClass().getName(), protocol.toString() + MainActivity.HANDLER_COUNT);
 			} catch (Exception e) {
 				e.printStackTrace();
 			}

+ 310 - 136
src/de/tudarmstadt/informatik/hostage/HoneyService.java

@@ -5,8 +5,17 @@ import java.io.InputStreamReader;
 import java.net.Socket;
 import java.security.SecureRandom;
 import java.util.ArrayList;
+import java.util.LinkedList;
 import java.util.List;
 
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.util.EntityUtils;
+import org.json.JSONObject;
+
 import android.app.NotificationManager;
 import android.app.PendingIntent;
 import android.app.Service;
@@ -26,6 +35,7 @@ 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.TextView;
 import android.widget.Toast;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.logging.MyLocationManager;
@@ -57,10 +67,11 @@ public class HoneyService extends Service {
 		return HoneyService.context;
 	}
 
+	private LinkedList<Protocol> implementedProtocols;
 	private ArrayList<HoneyListener> listeners = new ArrayList<HoneyListener>();
 	private NotificationCompat.Builder builder;
-	private SharedPreferences sessionPref;
-	private Editor editor;
+	private SharedPreferences connectionInfo;
+	private Editor connectionInfoEditor;
 
 	public List<HoneyListener> getListeners() {
 		return listeners;
@@ -83,14 +94,12 @@ public class HoneyService extends Service {
 	public void onCreate() {
 		super.onCreate();
 		HoneyService.context = getApplicationContext();
-		sessionPref = getSharedPreferences(MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
-		editor = sessionPref.edit();
-		deleteSessionData();
+		implementedProtocols = getImplementedProtocols();
+		connectionInfo = getSharedPreferences(MainActivity.CONNECTION_INFO, Context.MODE_PRIVATE);
+		connectionInfoEditor = connectionInfo.edit();
 		createNotification();
-		for (Protocol protocol : getProtocolArray()) {
-			listeners.add(new HoneyListener(this, protocol));
-		}
 		registerNetReceiver();
+		updateConnectionInfo();
 		getLocationData();
 		new QotdTask().execute(new String[] {});
 	}
@@ -106,7 +115,6 @@ public class HoneyService extends Service {
 	public void onDestroy() {
 		cancelNotification();
 		unregisterNetReceiver();
-		deleteSessionData();
 		super.onDestroy();
 	}
 
@@ -123,9 +131,9 @@ public class HoneyService extends Service {
 	/**
 	 * Deletes all session related data.
 	 */
-	private void deleteSessionData() {
-		editor.clear();
-		editor.commit();
+	private void deleteConnectionData() {
+		connectionInfoEditor.clear();
+		connectionInfoEditor.commit();
 	}
 
 	/**
@@ -153,118 +161,75 @@ public class HoneyService extends Service {
 	private BroadcastReceiver netReceiver = new BroadcastReceiver() {
 		@Override
 		public void onReceive(Context context, Intent intent) {
-			String bssid_old = sessionPref.getString(MainActivity.BSSID, "");
+			String bssid_old = connectionInfo.getString(MainActivity.BSSID, "");
 			String bssid_new = HelperUtils.getBSSID(context);
 			if (bssid_new == null || !bssid_new.equals(bssid_old)) {
+				deleteConnectionData();
+				updateConnectionInfo();
 				getLocationData();
-				notifyUI("SERVICE", "CONNECTIVITY_CHANGE");
+				notifyUI(this.getClass().getName(), "CONNECTIVITY_CHANGE");
 			}
 		}
 	};
+	
 
 	/**
-	 * Creates a Notification in the notification bar.
-	 */
-	private void createNotification() {
-		UglyDbHelper dbh = new UglyDbHelper(this);
-		boolean activeHandlers = false;
-		boolean bssidSeen = false;
-
-		for (String protocol : getResources().getStringArray(R.array.protocols)) {
-			int handlerCount = sessionPref.getInt(protocol
-					+ MainActivity.HANDLER_COUNT, 0);
-			if (handlerCount > 0) {
-				activeHandlers = true;
-			}
-			if (dbh.bssidSeen(protocol,
-					HelperUtils.getBSSID(getApplicationContext()))) {
-				bssidSeen = true;
-			}
-		}
-		builder = new NotificationCompat.Builder(this).setContentTitle(
-				getString(R.string.app_name)).setWhen(
-				System.currentTimeMillis());
-		if (activeHandlers) {
-			builder.setSmallIcon(R.drawable.ic_service_red);
-			builder.setContentText("Network is infected!");
-		} else if (bssidSeen) {
-			builder.setSmallIcon(R.drawable.ic_service_yellow);
-			builder.setContentText("Network has been infected in previous session!");
-		} else {
-			builder.setSmallIcon(R.drawable.ic_service_green);
-			builder.setContentText("Everything looks fine!");
-		}
-		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(1, builder.build());
-	}
-
-	/**
-	 * Updates the notification when a attack is registered.
+	 * Notifies the GUI about a event.
+	 * 
+	 * @param protocol
+	 *            The protocol where the event happened.
+	 * @param key
+	 *            The key for the event.
 	 */
-	private void updateNotification() {
-		SharedPreferences defaultPref = PreferenceManager
-				.getDefaultSharedPreferences(this);
-		String strRingtonePreference = defaultPref.getString(
-				"pref_notification_sound",
-				"content://settings/system/notification_sound");
-		builder = new NotificationCompat.Builder(this)
-				.setContentTitle(getString(R.string.app_name))
-				.setTicker("Honeypot under attack!")
-				.setContentText("Network is infected!")
-				.setSmallIcon(R.drawable.ic_service_red).setAutoCancel(true)
-				.setWhen(System.currentTimeMillis())
-				.setSound(Uri.parse(strRingtonePreference));
-		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);
-		if (defaultPref.getBoolean("pref_vibration", false)) {
-			builder.setVibrate(new long[] { 100, 200, 100, 200 });
+	public void notifyUI(String sender, String key) {
+		// Send Notification
+		if (key.equals(MainActivity.HANDLER_COUNT)) {
+			updateNotification();
 		}
-
-		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
-		mNotificationManager.notify(1, builder.build());
+		Log.i("HoneyService", sender + key);
+		// Inform UI of Preference Change
+		Intent intent = new Intent(MainActivity.BROADCAST);
+		intent.putExtra("SENDER", sender);
+		intent.putExtra("KEY", key);
+		LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
 	}
+	
 
-	/**
-	 * Cancels the Notification
-	 */
-	private void cancelNotification() {
-		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
-		mNotificationManager.cancel(1);
-	}
 
 	/**
-	 * Creates a instance of each protocol defined in /res/values/protocols.xml
-	 * and puts it in a List
+	 * Returns an LinkedList<String> with the names of all implemented protocols.
 	 * 
 	 * @return ArrayList of
 	 *         {@link de.tudarmstadt.informatik.hostage.protocol.Protocol
 	 *         Protocol}
 	 */
-	private ArrayList<Protocol> getProtocolArray() {
+	private LinkedList<Protocol> getImplementedProtocols() {
 		String[] protocols = getResources().getStringArray(R.array.protocols);
 		String packageName = Protocol.class.getPackage().getName();
-		ArrayList<Protocol> protocolArray = new ArrayList<Protocol>();
+		LinkedList<Protocol> implementedProtocols = new LinkedList<Protocol>();
 
 		for (String protocol : protocols) {
 			try {
-				protocolArray.add((Protocol) Class.forName(
-						String.format("%s.%s", packageName, protocol))
-						.newInstance());
+				implementedProtocols.add((Protocol) Class.forName(String.format("%s.%s", packageName, protocol)).newInstance());
 			} catch (Exception e) {
 				e.printStackTrace();
 			}
 		}
-		return protocolArray;
+		return implementedProtocols;
+	}
+	
+	/**
+	 * Returns the default port number, if the protocol is implemented.
+	 * @param protocolName The name of the protocol
+	 * @return Returns the default port number, if the protocol is implemented. Else returns -1.
+	 */
+	private int getDefaultPort(String protocolName){
+		for (Protocol protocol : implementedProtocols) {
+			if(protocolName.equals(protocol.toString())){
+				return protocol.getPort();
+			}
+		}
+		return -1;
 	}
 
 	/**
@@ -279,30 +244,81 @@ public class HoneyService extends Service {
 		}
 		return false;
 	}
+	
+	/**
+	 * Determines if a protocol with the given name is running on its default port.
+	 * @param protocolName The protocol name
+	 * @return True if protocol is running, else false.
+	 */
+	public boolean isRunning(String protocolName){
+		int port = getDefaultPort(protocolName);
+		if(port >= 0) return isRunning(protocolName, port);
+		return false;
+	}
+	
+	/**
+	 * Determines if a protocol with the given name is running on the given port.
+	 * @param protocolName The protocol name
+	 * @param port Specific port
+	 * @return True if protocol is running, else false.
+	 */
+	public boolean isRunning(String protocolName, int port){
+		for (HoneyListener listener : listeners) {
+			if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
+				return listener.isRunning();
+			}
+		}	
+		return false;
+	}
+	
+	/**
+	 * Determines the number of active connections for a protocol running on its default port.
+	 * @param protocolName The protocol name
+	 * @return Number of active connections if protocol is implemented, else -1.
+	 */
+	public int getHandlerCount(String protocolName){
+		int port = getDefaultPort(protocolName);
+		if(port >= 0) return getHandlerCount(protocolName, port);
+		return -1;
+	}
+	
+	/**
+	 * Determines the number of active connections for a protocol running on the given port.
+	 * @param protocolName The protocol name
+	 * @param port Specific port
+	 * @return Number of active connections if protocol is implemented, else -1.
+	 */
+	public int getHandlerCount(String protocolName, int port){
+		for (HoneyListener listener : listeners) {
+			if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
+				return listener.getHandlerCount();
+			}
+		}	
+		return -1;
+	}
 
 	/**
-	 * Notifies the GUI about a event.
+	 * Creates a Listener for a given protocol on a specific port. 
+	 * After creation the Listener is not started.
+	 * Checks if the protocol is implemented first.
 	 * 
-	 * @param protocol
-	 *            The protocol where the event happened.
-	 * @param key
-	 *            The key for the event.
+	 * @param protocolName Name of the protocol
+	 * @param port Port on which to start the Listener
+	 * @return Returns the created HoneyListener, if creation failed returns null.
 	 */
-	public void notifyUI(String sender, String key) {
-		// Send Notification
-		if (key.equals(MainActivity.HANDLER_COUNT)) {
-			updateNotification();
+	private HoneyListener createListener(String protocolName, int port){
+		for(Protocol protocol : implementedProtocols){
+			if(protocolName.equals(protocol.toString())){
+				HoneyListener listener = new HoneyListener(this, protocol, port);
+				listeners.add(listener);
+				return listener;
+			} 
 		}
-		Log.i("HoneyService", sender + key);
-		// Inform UI of Preference Change
-		Intent intent = new Intent(MainActivity.BROADCAST);
-		intent.putExtra("SENDER", sender);
-		intent.putExtra("KEY", key);
-		LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
+		return null;
 	}
 
 	/**
-	 * Starts all listeners which are not already running
+	 * Starts all listeners which are not already running.
 	 */
 	public void startListeners() {
 		for (HoneyListener listener : listeners) {
@@ -328,21 +344,49 @@ public class HoneyService extends Service {
 	}
 
 	/**
-	 * Starts the listener for the specified protocol.
+	 * Starts the listener for the specified protocol. 
+	 * Creates a new HoneyService if no matching HoneyListener is found.
 	 * 
 	 * @param protocolName
 	 *            Name of the protocol that should be started.
 	 */
-	public void startListener(String protocolName) {
+	public boolean startListener(String protocolName) {
+		int port = getDefaultPort(protocolName);
+		if(port >= 0) return startListener(protocolName, port);
+		return false;
+	}
+	
+	/**
+	 * Starts the listener for the specified protocol and port.
+	 * Creates a new HoneyService if no matching HoneyListener is found.
+	 * 
+	 * @param protocolName
+	 *            Name of the protocol that should be started.
+	 * @param port The port number in which the listener should run.
+	 */
+	public boolean startListener(String protocolName, int port) {
 		for (HoneyListener listener : listeners) {
-			if (listener.getProtocolName().equals(protocolName)) {
+			if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
 				if (!listener.isRunning()) {
-					listener.start();
+					if(listener.start()){
+						Toast.makeText(getApplicationContext(),protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
+						return true;
+					}
+					Toast.makeText(getApplicationContext(),protocolName + " SERVICE COULD NOT BE STARTED!", Toast.LENGTH_SHORT).show();
+					return false;
 				}
+				
 			}
 		}
-		Toast.makeText(getApplicationContext(),
-				protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
+		HoneyListener listener = createListener(protocolName, port);
+		if(listener != null){
+			if(listener.start()){
+				Toast.makeText(getApplicationContext(), protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
+				return true;
+			}
+		}	
+		Toast.makeText(getApplicationContext(),protocolName + " SERVICE COULD NOT BE STARTED!", Toast.LENGTH_SHORT).show();
+		return false;
 	}
 
 	/**
@@ -352,37 +396,30 @@ public class HoneyService extends Service {
 	 *            Name of the protocol that should be stopped.
 	 */
 	public void stopListener(String protocolName) {
-		for (HoneyListener listener : listeners) {
-			if (listener.getProtocolName().equals(protocolName)) {
-				if (listener.isRunning()) {
-					listener.stop();
-				}
-			}
-		}
-		Toast.makeText(getApplicationContext(),
-				protocolName + " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
+		int port = getDefaultPort(protocolName);
+		if(port >= 0) stopListener(protocolName, port);
 	}
-
+	
 	/**
-	 * Toggles a listener for specified protocol.
+	 * Stops the listener for the specified protocol.
 	 * 
 	 * @param protocolName
-	 *            Name of the protocol that should be toggled.
+	 *            Name of the protocol that should be stopped.
+	 * @param port The port number in which the listener is running.
 	 */
-	public void toggleListener(String protocolName) {
+	public void stopListener(String protocolName, int port) {
 		for (HoneyListener listener : listeners) {
-			if (listener.getProtocolName().equals(protocolName)) {
+			if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
 				if (listener.isRunning()) {
-					stopListener(protocolName);
-				} else {
-					startListener(protocolName);
+					listener.stop();
 				}
 			}
 		}
+		Toast.makeText(getApplicationContext(), protocolName + " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
 	}
 
 	/**
-	 * Task for accuiring a qotd from one of four possible servers.
+	 * Task for acquiring a qotd from one of four possible servers.
 	 * 
 	 * @author Wulf Pfeiffer
 	 */
@@ -419,4 +456,141 @@ public class HoneyService extends Service {
 						.getRandomString(100, false)));
 		}
 	};
+	
+	/**
+	 * Updates the connection info and saves them in the the SharedPreferences
+	 * for session data.
+	 * 
+	 * @param context
+	 *            Needs a context to get system recourses.
+	 * @see MainActivity#CONNECTION_INFO
+	 */
+	private void updateConnectionInfo() {
+		SharedPreferences pref = context.getSharedPreferences(
+				MainActivity.CONNECTION_INFO, Context.MODE_PRIVATE);
+		Editor editor = pref.edit();
+		editor.putString(MainActivity.SSID, HelperUtils.getSSID(context));
+		editor.putString(MainActivity.BSSID, HelperUtils.getBSSID(context));
+		editor.putString(MainActivity.INTERNAL_IP,
+				HelperUtils.getInternalIP(context));
+		editor.commit();
+		SetExternalIPTask async = new SetExternalIPTask();
+		async.execute(new String[] { "http://ip2country.sourceforge.net/ip2c.php?format=JSON" });
+	}
+	
+	/**
+	 * Task to find out the external IP.
+	 * 
+	 * @author Lars Pandikow
+	 */
+	private class SetExternalIPTask extends AsyncTask<String, Void, String> {
+		@Override
+		protected String doInBackground(String... url) {
+			String ipAddress = null;
+			try {
+				HttpClient httpclient = new DefaultHttpClient();
+				HttpGet httpget = new HttpGet(url[0]);
+				HttpResponse response;
+
+				response = httpclient.execute(httpget);
+
+				HttpEntity entity = response.getEntity();
+				entity.getContentLength();
+				String str = EntityUtils.toString(entity);
+				JSONObject json_data = new JSONObject(str);
+				ipAddress = json_data.getString("ip");
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+			return ipAddress;
+		}
+
+		@Override
+		protected void onPostExecute(String result) {
+			connectionInfoEditor.putString(MainActivity.EXTERNAL_IP, result);
+			connectionInfoEditor.commit();
+			notifyUI(this.getClass().getName(), MainActivity.EXTERNAL_IP);
+		}
+	};
+	
+	// Notifications
+	
+	/**
+	 * Creates a Notification in the notification bar.
+	 */
+	private void createNotification() {
+		UglyDbHelper dbh = new UglyDbHelper(this);
+		boolean activeHandlers = false;
+		boolean bssidSeen = false;
+
+		for (HoneyListener listener : listeners) {
+			if(listener.isRunning())
+			if (listener.getHandlerCount() > 0) {
+				activeHandlers = true;
+			}
+			if (dbh.bssidSeen(listener.getProtocolName(), HelperUtils.getBSSID(getApplicationContext()))) {
+				bssidSeen = true;
+			}
+		}
+		builder = new NotificationCompat.Builder(this).setContentTitle(
+				getString(R.string.app_name)).setWhen(
+				System.currentTimeMillis());
+		if (activeHandlers) {
+			builder.setSmallIcon(R.drawable.ic_service_red);
+			builder.setContentText("Network is infected!");
+		} else if (bssidSeen) {
+			builder.setSmallIcon(R.drawable.ic_service_yellow);
+			builder.setContentText("Network has been infected in previous session!");
+		} else {
+			builder.setSmallIcon(R.drawable.ic_service_green);
+			builder.setContentText("Everything looks fine!");
+		}
+		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(1, builder.build());
+	}
+
+	/**
+	 * Updates the notification when a attack is registered.
+	 */
+	private void updateNotification() {
+		SharedPreferences defaultPref = PreferenceManager
+				.getDefaultSharedPreferences(this);
+		String strRingtonePreference = defaultPref.getString(
+				"pref_notification_sound",
+				"content://settings/system/notification_sound");
+		builder = new NotificationCompat.Builder(this)
+				.setContentTitle(getString(R.string.app_name))
+				.setTicker("Honeypot under attack!")
+				.setContentText("Network is infected!")
+				.setSmallIcon(R.drawable.ic_service_red).setAutoCancel(true)
+				.setWhen(System.currentTimeMillis())
+				.setSound(Uri.parse(strRingtonePreference));
+		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);
+		if (defaultPref.getBoolean("pref_vibration", false)) {
+			builder.setVibrate(new long[] { 100, 200, 100, 200 });
+		}
+
+		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
+		mNotificationManager.notify(1, builder.build());
+	}
+
+	/**
+	 * Cancels the Notification
+	 */
+	private void cancelNotification() {
+		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
+		mNotificationManager.cancel(1);
+	}
+
 }

+ 74 - 85
src/de/tudarmstadt/informatik/hostage/logging/UglyDbHelper.java

@@ -9,9 +9,7 @@ import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.util.Log;
-import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.logging.Record.TYPE;
-import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 
 /**
  * This class creates SQL tables and handles all access to the database.<br>
@@ -39,7 +37,6 @@ public class UglyDbHelper extends SQLiteOpenHelper {
 	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
 	public static final String KEY_ID = "_id";
@@ -62,65 +59,52 @@ public class UglyDbHelper extends SQLiteOpenHelper {
 	public static final String KEY_ACCURACY = "accuracy";
 
 	// Database sql create statements
-	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," + KEY_TIME + " INTEGER"
-			+ ")";
-
-	private static final String CREATE_PORT_TABLE = "CREATE TABLE "
-			+ TABLE_PORTS + "(" + KEY_PROTOCOL + " TEXT PRIMARY KEY,"
-			+ KEY_LOCAL_PORT + " INTEGER" + ")";
-
-	private Context context;
+	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_LOCAL_PORT + " INTEGER," 
+		   + KEY_REMOTE_IP + " BLOB," 
+		   + KEY_REMOTE_HOSTNAME + " TEXT,"
+		   + KEY_REMOTE_PORT + " INTEGER," 
+		   + KEY_BSSID + " TEXT,"
+		   + "FOREIGN KEY(" + KEY_BSSID + ") REFERENCES " + TABLE_BSSIDS + "(" + KEY_BSSID + ")"
+		   + ")";
+
+	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," 
+	       + KEY_TIME + " INTEGER"
+	       + ")";
 
 	public UglyDbHelper(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
@@ -130,8 +114,7 @@ public class UglyDbHelper extends SQLiteOpenHelper {
 		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);
 	}
@@ -159,10 +142,10 @@ public class UglyDbHelper extends SQLiteOpenHelper {
 		attackValues.put(KEY_EXTERNAL_IP, record.getExternalIP());
 		attackValues.put(KEY_LOCAL_IP, record.getLocalIP()); // Log Local IP
 		attackValues.put(KEY_LOCAL_HOSTNAME, record.getLocalHost());
+		attackValues.put(KEY_LOCAL_PORT, record.getLocalPort());
 		attackValues.put(KEY_REMOTE_IP, record.getRemoteIP()); // Log Remote IP
 		attackValues.put(KEY_REMOTE_HOSTNAME, record.getRemoteHost());
-		attackValues.put(KEY_REMOTE_PORT, record.getRemotePort()); // Log Remote
-																	// Port
+		attackValues.put(KEY_REMOTE_PORT, record.getRemotePort()); // Log Remote Port
 		attackValues.put(KEY_BSSID, record.getBssid());
 
 		ContentValues recordValues = new ContentValues();
@@ -192,22 +175,27 @@ public class UglyDbHelper extends SQLiteOpenHelper {
 		Record record = new Record();
 		record.setId(Integer.parseInt(cursor.getString(0)));
 		record.setAttack_id(cursor.getLong(1));
-		record.setType(cursor.getString(2).equals("SEND") ? TYPE.SEND
-				: TYPE.RECEIVE);
+		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(cursor.getString(7));
-		record.setRemoteIP(cursor.getString(9));
-		record.setRemotePort(Integer.parseInt(cursor.getString(11)));
-		record.setBssid(cursor.getString(12));
-		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.setTimestampLocation(cursor.getLong(17));
-		record.setLocalPort(Integer.parseInt(cursor.getString(18)));
+		record.setLocalHost(cursor.getString(8));
+		record.setLocalPort(Integer.parseInt(cursor.getString(9)));
+		
+		record.setRemoteIP(cursor.getString(10));
+		record.setRemoteHost(cursor.getString(11));
+		record.setRemotePort(Integer.parseInt(cursor.getString(12)));
+		
+		record.setBssid(cursor.getString(13));
+		record.setSsid(cursor.getString(14));
+		record.setLatitude(Double.parseDouble(cursor.getString(15)));
+		record.setLongitude(Double.parseDouble(cursor.getString(16)));
+		record.setAccuracy(Float.parseFloat(cursor.getString(17)));
+		record.setTimestampLocation(cursor.getLong(18));
+
 		return record;
 	}
 
@@ -220,9 +208,9 @@ public class UglyDbHelper extends SQLiteOpenHelper {
 	 */
 	public Record getRecord(int id) {
 		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS
-				+ " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN "
-				+ TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS + " WHERE "
-				+ KEY_ID + " = " + id;
+						  + " NATURAL JOIN " + TABLE_ATTACK_INFO 
+						  + " NATURAL JOIN "+ TABLE_BSSIDS 
+						  + " WHERE " + KEY_ID + " = " + id;
 		SQLiteDatabase db = this.getReadableDatabase();
 
 		Cursor cursor = db.rawQuery(selectQuery, null);
@@ -246,8 +234,8 @@ public class UglyDbHelper extends SQLiteOpenHelper {
 		ArrayList<Record> recordList = new ArrayList<Record>();
 		// Select All Query
 		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS
-				+ " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN "
-				+ TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS;
+						  + " NATURAL JOIN " + TABLE_ATTACK_INFO 
+						  + " NATURAL JOIN " + TABLE_BSSIDS;
 
 		SQLiteDatabase db = this.getWritableDatabase();
 		Cursor cursor = db.rawQuery(selectQuery, null);
@@ -277,10 +265,10 @@ public class UglyDbHelper extends SQLiteOpenHelper {
 	 */
 	public Record getRecordOfAttackId(long 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;
+						  + " NATURAL JOIN " + TABLE_ATTACK_INFO 
+						  + " NATURAL JOIN " + TABLE_BSSIDS 
+						  + " WHERE " + KEY_ATTACK_ID + " = " + attack_id 
+						  + " GROUP BY " + KEY_ATTACK_ID;
 		SQLiteDatabase db = this.getReadableDatabase();
 		Cursor cursor = db.rawQuery(selectQuery, null);
 		Record record = null;
@@ -305,9 +293,10 @@ public class UglyDbHelper extends SQLiteOpenHelper {
 	public ArrayList<Record> getAllReceivedRecordsOfEachAttack() {
 		ArrayList<Record> recordList = new ArrayList<Record>();
 		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;
+						  + " NATURAL JOIN " + TABLE_ATTACK_INFO 
+						  + " NATURAL JOIN " + TABLE_BSSIDS 
+						  + " WHERE " + KEY_TYPE + "='RECEIVE'" 
+						  + " ORDER BY " + KEY_TIME;
 		SQLiteDatabase db = this.getReadableDatabase();
 		Cursor cursor = db.rawQuery(selectQuery, null);
 
@@ -336,9 +325,9 @@ public class UglyDbHelper extends SQLiteOpenHelper {
 	public ArrayList<Record> getRecordOfEachAttack() {
 		ArrayList<Record> recordList = new ArrayList<Record>();
 		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS
-				+ " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN "
-				+ TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS + " GROUP BY "
-				+ KEY_ATTACK_ID;
+						  + " NATURAL JOIN " + TABLE_ATTACK_INFO 
+						  + " NATURAL JOIN " + TABLE_BSSIDS 
+						  + " GROUP BY " + KEY_ATTACK_ID;
 		SQLiteDatabase db = this.getReadableDatabase();
 		Cursor cursor = db.rawQuery(selectQuery, null);
 
@@ -369,10 +358,10 @@ public class UglyDbHelper extends SQLiteOpenHelper {
 	public ArrayList<Record> getRecordOfEachAttack(long attack_id) {
 		ArrayList<Record> recordList = new ArrayList<Record>();
 		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;
+						  + " NATURAL JOIN " + TABLE_ATTACK_INFO 
+						  + " NATURAL JOIN " + TABLE_BSSIDS 
+						  + " WHERE " + KEY_ATTACK_ID + " > " + attack_id 
+						  + " GROUP BY " + KEY_ATTACK_ID;
 		SQLiteDatabase db = this.getReadableDatabase();
 		Cursor cursor = db.rawQuery(selectQuery, null);
 

+ 2 - 3
src/de/tudarmstadt/informatik/hostage/sync/BluetoothSync.java

@@ -85,9 +85,7 @@ public class BluetoothSync{
 		if (!mBluetoothAdapter.isEnabled()) {
 		    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
 		    context.startActivity(enableBtIntent);
-		    //TODO CHECK
-//		    if(!mBluetoothAdapter.isEnabled())
-//		    	return false;
+		    return false;
 		}
 		return true;
 	}
@@ -233,6 +231,7 @@ public class BluetoothSync{
 	        // Keep listening to the InputStream until an exception occurs
 //	        while (true) {
 	            try {
+	            	//TODO Ersetze dbh mit Logger
 	            	UglyDbHelper dbh = new UglyDbHelper(context);
             		ArrayList<HashMap<String, Object>> localNetworkInformation = dbh.getNetworkInformation();
 	            	if(identifier == SERVER){

+ 71 - 173
src/de/tudarmstadt/informatik/hostage/ui/MainActivity.java

@@ -3,7 +3,9 @@ package de.tudarmstadt.informatik.hostage.ui;
 import java.io.BufferedReader;
 import java.io.InputStreamReader;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.HashMap;
+import java.util.LinkedList;
 
 import org.apache.http.HttpEntity;
 import org.apache.http.HttpResponse;
@@ -80,7 +82,7 @@ public class MainActivity extends Activity implements Receiver {
 	 * Used to store session related data in a SharedPrefereces. String:
 	 * "de.tudarmstadt.informatik.hostage.SESSION_DATA"
 	 */
-	public static final String SESSION_DATA = "de.tudarmstadt.informatik.hostage.SESSION_DATA";
+	public static final String CONNECTION_INFO = "de.tudarmstadt.informatik.hostage.CONNECTION_INFO";
 	public static final String LISTENER = "_LISTENER";
 	public static final String HANDLER_COUNT = "_HANDLER_COUNT";
 	public static final String SSID = "SSID";
@@ -114,14 +116,11 @@ public class MainActivity extends Activity implements Receiver {
 	 */
 	public static final int LIGHT_YELLOW = 0x04;
 
-	private static Context context;
-
 	public LogResultReceiver logResultReceiver;
+	private SharedPreferences connectionInfo;
 
 	private HoneyService mService;
 	private boolean serviceBound;
-	private SharedPreferences sessionPref;
-	private Editor sessionEditor;
 
 	// variables for the swipe animation
 	private ViewAnimator viewAnimator;
@@ -134,24 +133,21 @@ public class MainActivity extends Activity implements Receiver {
 	private ListView listView;
 	private ListViewAdapter adapter;
 
-	private String protocolClicked;
-
 	private boolean isBssidSeen = false;
 
 	@Override
 	protected void onCreate(Bundle savedInstanceState) {
 		super.onCreate(savedInstanceState);
-		MainActivity.context = getApplicationContext(); // set context
 		logResultReceiver = new LogResultReceiver(new Handler());
 		setContentView(R.layout.activity_main);
-
+		connectionInfo = getSharedPreferences(MainActivity.CONNECTION_INFO, Context.MODE_PRIVATE);
+		
 		// Create dynamic view elements
 		initViewAnimator();
 		initListView();
 		// Initialize Class variables
-		sessionPref = getSharedPreferences(MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
-		sessionEditor = sessionPref.edit();
 		checkRootAndPorthack();
+		startAndBind();
 	}
 
 	@Override
@@ -180,32 +176,19 @@ public class MainActivity extends Activity implements Receiver {
 		super.onStart();
 		// Register Broadcast Receiver
 		registerReceiver();
-		registerNetReceiver();
 		logResultReceiver.setReceiver(this);
 		// Bind service if running, else check for connection change and delete
 		// sessionData
 		if (isServiceRunning()) {
 			bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
-		} else {
-			String bssid_old = sessionPref.getString(MainActivity.BSSID, "");
-			String bssid_new = HelperUtils.getBSSID(this);
-			if (bssid_new == null || !bssid_new.equals(bssid_old)) {
-				deleteSessionData();
-			}
-		}
+		} 
 		// Update UI
-		updateUI();
 		updateConnectionInfText();
 	}
 
 	@Override
 	protected void onStop() {
-		// Unbind running service
-		if (isServiceRunning()) {
-			unbindService(mConnection);
-		}
 		// Unregister Broadcast Receiver
-		unregisterNetReceiver();
 		unregisterReceiver();
 		logResultReceiver.setReceiver(null);
 		super.onStop();
@@ -213,11 +196,11 @@ public class MainActivity extends Activity implements Receiver {
 
 	@Override
 	protected void onDestroy() {
-		super.onDestroy();
-		// If service not running delete session data
-		if (!isServiceRunning()) {
-			deleteSessionData();
+		// Unbind running service
+		if(!mService.hasRunningListeners()){
+			stopAndUnbind();
 		}
+		super.onDestroy();
 	}
 
 	@Override
@@ -233,11 +216,15 @@ public class MainActivity extends Activity implements Receiver {
 	public void buttonOnOffClick(View view) {
 		if (((ToggleButton) view).isChecked()) {
 			if (isParanoid()) {
-				protocolClicked = "PANIC";
+				String[] protocols = getResources().getStringArray(R.array.protocols);
+//				startListener((LinkedList<String>) Arrays.asList(protocols));				
 			} else {
-				protocolClicked = "SMB";
+				if(mService.isRunning("SMB")){
+					mService.stopListener("SMB");
+				}else{
+					mService.startListener("SMB");
+				}	
 			}
-			startAndBind();
 		} else {
 			mService.stopListeners();
 			stopAndUnbind();
@@ -276,7 +263,6 @@ public class MainActivity extends Activity implements Receiver {
 	 */
 	private void bindService() {
 		bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
-		serviceBound = true;
 	}
 
 	/**
@@ -296,7 +282,6 @@ public class MainActivity extends Activity implements Receiver {
 	 */
 	private void unbindService() {
 		unbindService(mConnection);
-		serviceBound = false;
 	}
 
 	/**
@@ -314,12 +299,8 @@ public class MainActivity extends Activity implements Receiver {
 		@Override
 		public void onServiceConnected(ComponentName name, IBinder service) {
 			mService = ((LocalBinder) service).getService();
-			if (protocolClicked != null && protocolClicked.equals("PANIC")) {
-				mService.startListeners();
-			} else if (protocolClicked != null) {
-				mService.toggleListener(protocolClicked);
-			}
-			protocolClicked = null;
+			serviceBound = true;
+			updateUI();
 		}
 
 		/**
@@ -330,6 +311,7 @@ public class MainActivity extends Activity implements Receiver {
 		@Override
 		public void onServiceDisconnected(ComponentName name) {
 			mService = null;
+			serviceBound = false;
 		}
 
 	};
@@ -417,19 +399,15 @@ public class MainActivity extends Activity implements Receiver {
 					int position, long id) {
 				String protocolName = (String) ((HashMap<?, ?>) adapter
 						.getItem(position)).get("protocol");
-				if (isServiceRunning()) {
-					mService.toggleListener(protocolName);
-					if (!mService.hasRunningListeners()) {
-						stopAndUnbind();
-					}
-				} else {
-					protocolClicked = protocolName;
-					startAndBind();
-				}
+				if(mService.isRunning(protocolName)){
+					mService.stopListener(protocolName);
+				}else{
+					mService.startListener(protocolName);
+				}				
 			}
 		});
 	}
-
+	
 	/**
 	 * Checks if a {@link HoneyService} instance is running.
 	 * 
@@ -446,13 +424,14 @@ public class MainActivity extends Activity implements Receiver {
 		}
 		return false;
 	}
-
+	
 	/**
-	 * Deletes all session related Data.
+	 * Checks if a {@link HoneyService} instance is running.
+	 * 
+	 * @return True if {@link HoneyService} is running, else false.
 	 */
-	private void deleteSessionData() {
-		sessionEditor.clear();
-		sessionEditor.commit();
+	private boolean isServiceBound() {
+		return serviceBound;
 	}
 
 	/**
@@ -484,33 +463,6 @@ public class MainActivity extends Activity implements Receiver {
 		public void onReceive(Context context, Intent intent) {
 			// Update user interface.
 			updateUI();
-		}
-	};
-
-	/**
-	 * Register broadcast receiver for network state changes.
-	 * 
-	 * @see ConnectivityManager#CONNECTIVITY_ACTION
-	 */
-	private void registerNetReceiver() {
-		IntentFilter intent = new IntentFilter();
-		intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // "android.net.conn.CONNECTIVITY_CHANGE"
-		registerReceiver(netReceiver, intent);
-	}
-
-	/**
-	 * Unregister broadcast receiver for network state changes.
-	 */
-	private void unregisterNetReceiver() {
-		unregisterReceiver(netReceiver);
-	}
-
-	/**
-	 * Receiver for network state change events.
-	 */
-	private BroadcastReceiver netReceiver = new BroadcastReceiver() {
-		@Override
-		public void onReceive(Context context, Intent intent) {
 			updateConnectionInfText();
 		}
 	};
@@ -522,38 +474,41 @@ public class MainActivity extends Activity implements Receiver {
 		boolean activeListeners = false;
 		boolean activeHandlers = false;
 		boolean yellowLight = false;
-
+		
 		// Check for all protocols if listeners are active and attacks have been
 		// recorded
 		// Update protocol lights and connection information.
 		for (String protocol : getResources().getStringArray(R.array.protocols)) {
-			// Check if protocol is active
-			if (sessionPref.getBoolean(protocol + LISTENER, false)) {
-				activeListeners = true;
-				int handlerCount = sessionPref.getInt(protocol + HANDLER_COUNT,
-						0);
-				// Check if attacks have been recorded in this session.
-				if (handlerCount > 0) {
-					activeHandlers = true;
-					updateProtocolLight(LIGHT_RED, protocol);
-					updateProtocolConnections(handlerCount, protocol);
+			if(isServiceBound()){
+				// Check if protocol is active
+				if (mService.isRunning(protocol)) {
+					activeListeners = true;
+					int handlerCount = mService.getHandlerCount(protocol);
+					// Check if attacks have been recorded in this session.
+					if (handlerCount > 0) {
+						activeHandlers = true;
+						updateProtocolLight(LIGHT_RED, protocol);
+						updateProtocolConnections(handlerCount, protocol);
 				} else {
-					// Check if the bssid of the wireless network has already
-					// been recorded as infected.
-					Logger.isBssidSeen(getApplicationContext(), protocol,
-							HelperUtils.getBSSID(getApplicationContext()),
-							logResultReceiver);
-					if (isBssidSeen) {
-						updateProtocolLight(LIGHT_YELLOW, protocol);
-						yellowLight = true;
-					} else {
-						updateProtocolLight(LIGHT_GREEN, protocol);
+						// Check if the bssid of the wireless network has already
+						// been recorded as infected.
+						Logger.isBssidSeen(getApplicationContext(), protocol,
+								HelperUtils.getBSSID(getApplicationContext()),
+								logResultReceiver);
+						if (isBssidSeen) {
+							updateProtocolLight(LIGHT_YELLOW, protocol);
+							yellowLight = true;
+						} else {
+							updateProtocolLight(LIGHT_GREEN, protocol);
+						}
+						updateProtocolConnections(0, protocol);
 					}
-					updateProtocolConnections(0, protocol);
+				} else {
+					updateProtocolLight(LIGHT_GREY, protocol);
 				}
-			} else {
+			}else{
 				updateProtocolLight(LIGHT_GREY, protocol);
-			}
+			}				
 		}
 
 		// Update the big attack indicator.
@@ -670,17 +625,13 @@ public class MainActivity extends Activity implements Receiver {
 		TextView internalIPView = (TextView) findViewById(R.id.textViewInternalIPValue);
 		TextView externalIPView = (TextView) findViewById(R.id.textViewExternalIPValue);
 
-		externalIPView.setText("Loading...");
-
-		// Update the connection information
-		updateConnectionInfo();
-		SetExternalIPTask async = new SetExternalIPTask();
-		async.execute(new String[] { "http://ip2country.sourceforge.net/ip2c.php?format=JSON" });
+//		externalIPView.setText("Loading...");
 
 		// Get connection information
-		String ssid = sessionPref.getString(SSID, null);
-		String bssid = sessionPref.getString(BSSID, null);
-		String internalIP = sessionPref.getString(INTERNAL_IP, null);
+		String ssid = connectionInfo.getString(SSID, null);
+		String bssid = connectionInfo.getString(BSSID, null);
+		String internalIP = connectionInfo.getString(INTERNAL_IP, null);
+		String externalIP = connectionInfo.getString(EXTERNAL_IP, null);
 
 		// Set text fields
 		if (ssid != null)
@@ -697,66 +648,13 @@ public class MainActivity extends Activity implements Receiver {
 			internalIPView.setText(internalIP);
 		else
 			internalIPView.setText("-");
+		
+		if (externalIP != null)
+			externalIPView.setText(externalIP);
+		else
+			externalIPView.setText("-");
 	}
 
-	/**
-	 * Updates the connection info and saves them in the the SharedPreferences
-	 * for session data.
-	 * 
-	 * @param context
-	 *            Needs a context to get system recourses.
-	 * @see MainActivity#SESSION_DATA
-	 */
-	private void updateConnectionInfo() {
-		SharedPreferences pref = context.getSharedPreferences(
-				MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
-		Editor editor = pref.edit();
-		editor.putString(MainActivity.SSID, HelperUtils.getSSID(context));
-		editor.putString(MainActivity.BSSID, HelperUtils.getBSSID(context));
-		editor.putString(MainActivity.INTERNAL_IP,
-				HelperUtils.getInternalIP(context));
-		editor.commit();
-	}
-
-	/**
-	 * Task to find out the external IP.
-	 * 
-	 * @author Lars Pandikow
-	 */
-	private class SetExternalIPTask extends AsyncTask<String, Void, String> {
-		@Override
-		protected String doInBackground(String... url) {
-			String ipAddress = null;
-			try {
-				HttpClient httpclient = new DefaultHttpClient();
-				HttpGet httpget = new HttpGet(url[0]);
-				HttpResponse response;
-
-				response = httpclient.execute(httpget);
-
-				HttpEntity entity = response.getEntity();
-				entity.getContentLength();
-				String str = EntityUtils.toString(entity);
-				JSONObject json_data = new JSONObject(str);
-				ipAddress = json_data.getString("ip");
-			} catch (Exception e) {
-				e.printStackTrace();
-			}
-			return ipAddress;
-		}
-
-		@Override
-		protected void onPostExecute(String result) {
-			sessionEditor.putString(MainActivity.EXTERNAL_IP, result);
-			sessionEditor.commit();
-			TextView externalIPView = (TextView) findViewById(R.id.textViewExternalIPValue);
-			if (result != null)
-				externalIPView.setText(result);
-			else
-				externalIPView.setText("-");
-		}
-	};
-
 	/* ############# Help functions for animation ################## */
 
 	@Override