Browse Source

Logging-System überarbeitet und als IntentService implementiert.
Performance deutlich gesteigert. Aufgabentrennung im Code viel
deutlicher. Record ist Parcelable statt Serializable (über 10x höhere
Performance auf Android). Formatter für logging überarbeitet, Singleton,
ressourcenschonend implementiert.
TODO: ViewLog und ViewLogTable kaputt, da Antworten vom IntentService
noch nicht richtig empfangen werden.

MiP 10 years ago
parent
commit
8b36e01daa
30 changed files with 2668 additions and 1972 deletions
  1. 26 21
      AndroidManifest.xml
  2. 4 0
      lint.xml
  3. 82 48
      src/de/tudarmstadt/informatik/hostage/HoneyHandler.java
  4. 161 126
      src/de/tudarmstadt/informatik/hostage/HoneyService.java
  5. 111 66
      src/de/tudarmstadt/informatik/hostage/commons/HelperUtils.java
  6. 0 14
      src/de/tudarmstadt/informatik/hostage/format/DefaultFormatter.java
  7. 0 46
      src/de/tudarmstadt/informatik/hostage/format/LogViewFormatter.java
  8. 0 64
      src/de/tudarmstadt/informatik/hostage/format/MySQLFormatter.java
  9. 0 17
      src/de/tudarmstadt/informatik/hostage/format/ProtocolFormatter.java
  10. 0 135
      src/de/tudarmstadt/informatik/hostage/format/SMBFormatter.java
  11. 0 99
      src/de/tudarmstadt/informatik/hostage/format/TELNETFormatter.java
  12. 0 597
      src/de/tudarmstadt/informatik/hostage/logging/DatabaseHandler.java
  13. 30 0
      src/de/tudarmstadt/informatik/hostage/logging/LogResultReceiver.java
  14. 311 80
      src/de/tudarmstadt/informatik/hostage/logging/Logger.java
  15. 162 183
      src/de/tudarmstadt/informatik/hostage/logging/Record.java
  16. 0 89
      src/de/tudarmstadt/informatik/hostage/logging/SQLLogger.java
  17. 694 0
      src/de/tudarmstadt/informatik/hostage/logging/UglyDbHelper.java
  18. 28 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/DefaultFormatter.java
  19. 23 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/Formatter.java
  20. 25 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/TraCINgFormatter.java
  21. 103 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/protocol/MySQL.java
  22. 45 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/protocol/ProtocolFormatter.java
  23. 225 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/protocol/SMB.java
  24. 149 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/protocol/TELNET.java
  25. 2 2
      src/de/tudarmstadt/informatik/hostage/sync/BluetoothSync.java
  26. 3 3
      src/de/tudarmstadt/informatik/hostage/sync/NFCSync.java
  27. 268 212
      src/de/tudarmstadt/informatik/hostage/ui/MainActivity.java
  28. 15 15
      src/de/tudarmstadt/informatik/hostage/ui/PlayGroundActivity.java
  29. 189 145
      src/de/tudarmstadt/informatik/hostage/ui/ViewLog.java
  30. 12 10
      src/de/tudarmstadt/informatik/hostage/ui/ViewLogTable.java

+ 26 - 21
AndroidManifest.xml

@@ -13,13 +13,14 @@
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
-    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
     <uses-permission android:name="android.permission.BLUETOOTH" />
     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
     <uses-permission android:name="android.permission.NFC" />
-    
+
     <uses-feature
-    android:name="android.hardware.nfc" android:required="false" />
+        android:name="android.hardware.nfc"
+        android:required="false" />
 
     <application
         android:allowBackup="true"
@@ -28,49 +29,53 @@
         android:theme="@style/AppTheme" >
         <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.MainActivity"
-            android:label="@string/app_name" 
-            android:configChanges="keyboardHidden|orientation|screenSize">
+            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"
             android:label="@string/statistics" >
         </activity>
-       	<activity
+        <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.ViewLogTable"
             android:label="@string/database" >
         </activity>
-        
-       	<activity
+        -->
+        <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.SettingsActivity"
             android:label="@string/settings" >
         </activity>
-        
-       	<activity
+        <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.AboutActivity"
             android:label="@string/action_about" >
         </activity>
-       
-       	<activity
+        <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.PlayGroundActivity"
             android:label="@string/playground" >
         </activity>
-       	
-       <activity
+        <activity
             android:name="de.tudarmstadt.informatik.hostage.sync.NFCSync"
             android:label="@string/playground" >
             <intent-filter>
-  				<action android:name="android.nfc.action.NDEF_DISCOVERED" />
-  				<category android:name="android.intent.category.DEFAULT" />
-  				<data android:mimeType="application/de.tudarmstadt.informatik.hostage" />
-			</intent-filter>
+                <action android:name="android.nfc.action.NDEF_DISCOVERED" />
+
+                <category android:name="android.intent.category.DEFAULT" />
+
+                <data android:mimeType="application/de.tudarmstadt.informatik.hostage" />
+            </intent-filter>
         </activity>
-       	
-        <service 
-            android:name="de.tudarmstadt.informatik.hostage.HoneyService" >
+
+        <service android:name="de.tudarmstadt.informatik.hostage.HoneyService" >
+        </service>
+        <service
+            android:name="de.tudarmstadt.informatik.hostage.logging.Logger"
+            android:exported="false" >
         </service>
     </application>
 

+ 4 - 0
lint.xml

@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<lint>
+    <issue id="DefaultLocale" severity="ignore" />
+</lint>

+ 82 - 48
src/de/tudarmstadt/informatik/hostage/HoneyHandler.java

@@ -21,16 +21,21 @@ import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol.TALK_FIRST;
 import de.tudarmstadt.informatik.hostage.ui.MainActivity;
 import de.tudarmstadt.informatik.hostage.wrapper.Packet;
+
 /**
  * Abstract class for a connection handler using a given protocol.
- * @author Mihai Plasoianu 
+ * 
+ * @author Mihai Plasoianu
  * @author Wulf Pfeiffer
  */
 public class HoneyHandler implements Runnable {
 
 	/** Time until the socket throws a time out. The time is in milliseconds. */
 	private int TIMEOUT;
-	/** Time that a inputstream waits if no content is available to read again from stream. */
+	/**
+	 * Time that a inputstream waits if no content is available to read again
+	 * from stream.
+	 */
 	private int SLEEPTIME;
 
 	protected Protocol protocol;
@@ -44,31 +49,35 @@ public class HoneyHandler implements Runnable {
 	private String SSID;
 
 	private HoneyListener listener;
-	protected Logger log;
-	
+
 	/**
-	 * Constructor of the class.
-	 * Initializes class variables for communication and logging.
-	 * Then starts itself in a new Thread.
-	 * @param service The background service.
-	 * @param listener The Listener that called the service.
-	 * @param protocol The protocol on which the handler is running.
-	 * @param client A Socket for the communication with a remote client.
+	 * Constructor of the class. Initializes class variables for communication
+	 * and logging. Then starts itself in a new Thread.
+	 * 
+	 * @param service
+	 *            The background service.
+	 * @param listener
+	 *            The Listener that called the service.
+	 * @param protocol
+	 *            The protocol on which the handler is running.
+	 * @param client
+	 *            A Socket for the communication with a remote client.
 	 */
 	public HoneyHandler(HoneyService service, HoneyListener listener,
 			Protocol protocol, Socket client) {
 		this.listener = listener;
-		this.log = service.getLog();
 		this.protocol = protocol;
 		this.client = client;
 		this.thread = new Thread(this);
-		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(service);
+		SharedPreferences pref = PreferenceManager
+				.getDefaultSharedPreferences(service);
 		SLEEPTIME = pref.getInt("sleeptime", 500);
 		TIMEOUT = pref.getInt("timeout", 30) * 1000;
-		//TODO ThreadSicher?
+		// TODO ThreadSicher?
 		attack_id = getAndIncrementAttackID(pref);
 		message_id = 0;
-		SharedPreferences sessionPref = service.getSharedPreferences(MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
+		SharedPreferences sessionPref = service.getSharedPreferences(
+				MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
 		BSSID = sessionPref.getString(MainActivity.BSSID, null);
 		SSID = sessionPref.getString(MainActivity.SSID, null);
 		externalIP = sessionPref.getString(MainActivity.EXTERNAL_IP, null);
@@ -78,7 +87,9 @@ public class HoneyHandler implements Runnable {
 
 	/**
 	 * Set the timeout of the socket to the hard coded time out variable.
-	 * @param client The socket
+	 * 
+	 * @param client
+	 *            The socket
 	 * @see #TIMEOUT
 	 */
 	private void setSoTimeout(Socket client) {
@@ -90,9 +101,9 @@ public class HoneyHandler implements Runnable {
 	}
 
 	/**
-	 * Creates InputStream and OutputStream for the socket.
-	 * Starts communication with client.
-	 * When the client closes the connection or a time out occurs the handler is finished.
+	 * Creates InputStream and OutputStream for the socket. Starts communication
+	 * with client. When the client closes the connection or a time out occurs
+	 * the handler is finished.
 	 */
 	@Override
 	public void run() {
@@ -123,6 +134,7 @@ public class HoneyHandler implements Runnable {
 
 	/**
 	 * Determines if the interrupt flag of the thread is set.
+	 * 
 	 * @return True when the flag is set, else false.
 	 */
 	public boolean isTerminated() {
@@ -130,14 +142,19 @@ public class HoneyHandler implements Runnable {
 	}
 
 	/**
-	 * Communicates with a client using the corresponding protocol implementation.
-	 * @param in InputStream of the socket.
-	 * @param out OutputStream of the socket.
+	 * Communicates with a client using the corresponding protocol
+	 * implementation.
+	 * 
+	 * @param in
+	 *            InputStream of the socket.
+	 * @param out
+	 *            OutputStream of the socket.
 	 * @throws IOException
 	 */
-	protected void talkToClient(InputStream in, OutputStream out) throws IOException {
+	protected void talkToClient(InputStream in, OutputStream out)
+			throws IOException {
 		ReaderWriter stream;
-		if(protocol.getType().equals(byte[].class)) {
+		if (protocol.getType().equals(byte[].class)) {
 			stream = new ByteArrayReaderWriter(in, out, SLEEPTIME);
 		} else {
 			stream = new StringReaderWriter(in, out);
@@ -148,16 +165,19 @@ public class HoneyHandler implements Runnable {
 			outputLine = protocol.processMessage(null);
 			stream.write(outputLine);
 			for (Packet o : outputLine) {
-				log.write(createRecord(TYPE.SEND, o.toString()));
+				Logger.log(HoneyService.getContext(),
+						createRecord(TYPE.SEND, o.toString()));
 			}
 		}
 		while (!thread.isInterrupted() && (inputLine = stream.read()) != null) {
 			outputLine = protocol.processMessage(inputLine);
-			log.write(createRecord(TYPE.RECEIVE, inputLine.toString()));
+			Logger.log(HoneyService.getContext(),
+					createRecord(TYPE.RECEIVE, inputLine.toString()));
 			if (outputLine != null) {
 				stream.write(outputLine);
 				for (Packet o : outputLine) {
-					log.write(createRecord(TYPE.SEND, o.toString()));
+					Logger.log(HoneyService.getContext(),
+							createRecord(TYPE.SEND, o.toString()));
 				}
 			}
 			if (protocol.isClosed()) {
@@ -168,57 +188,71 @@ public class HoneyHandler implements Runnable {
 
 	/**
 	 * Creates a Record for a message exchanged with a client.
-	 * @param type The type of the message.
-	 * @param packet The content of the message.
+	 * 
+	 * @param type
+	 *            The type of the message.
+	 * @param packet
+	 *            The content of the message.
 	 * @return The Record representing the communication message.
 	 */
 	protected Record createRecord(TYPE type, String packet) {
 		Record record = new Record();
-		record.setId(getAndIncrementMessageCounter());		
+		record.setId(getAndIncrementMessageCounter());
 		record.setAttack_id(attack_id);
 		record.setProtocol(protocol.toString());
 		record.setType(type);
 		record.setTimestamp(System.currentTimeMillis());
 		record.setExternalIP(externalIP);
-		record.setLocalIP(client.getLocalAddress());
+		record.setLocalIP(client.getLocalAddress().getHostAddress());
+		record.setLocalHost(client.getLocalAddress().getHostName());
 		record.setLocalPort(protocol.getPort());
-		record.setRemoteIP(client.getInetAddress());
+		record.setRemoteIP(client.getInetAddress().getHostAddress());
+		record.setRemoteHost(client.getInetAddress().getHostName());
 		record.setRemotePort(client.getPort());
-		record.setBSSID(BSSID);
-		record.setSSID(SSID);
+		record.setBssid(BSSID);
+		record.setSsid(SSID);
 		record.setPacket(packet);
-		if(MyLocationManager.getNewestLocation() != null){
-			record.setLatitude(MyLocationManager.getNewestLocation().getLatitude() );		
-			record.setLongitude(MyLocationManager.getNewestLocation().getLongitude() );
-			record.setAccuracy(MyLocationManager.getNewestLocation().getAccuracy() );
-			record.setTimestampLocation(MyLocationManager.getNewestLocation().getTime() );
-		}else {
-			record.setLatitude(0.0);		
+		if (MyLocationManager.getNewestLocation() != null) {
+			record.setLatitude(MyLocationManager.getNewestLocation()
+					.getLatitude());
+			record.setLongitude(MyLocationManager.getNewestLocation()
+					.getLongitude());
+			record.setAccuracy(MyLocationManager.getNewestLocation()
+					.getAccuracy());
+			record.setTimestampLocation(MyLocationManager.getNewestLocation()
+					.getTime());
+		} else {
+			record.setLatitude(0.0);
 			record.setLongitude(0.0);
 			record.setAccuracy(Float.MAX_VALUE);
 			record.setTimestampLocation(0);
 		}
 		return record;
 	}
-	
+
 	/**
-	 * Gets attack ID for the attack. Also increases the attack ID counter by one. Method is synchronized for thread safety.
-	 * @param pref The default SharedPreference of the application
+	 * Gets attack ID for the attack. Also increases the attack ID counter by
+	 * one. Method is synchronized for thread safety.
+	 * 
+	 * @param pref
+	 *            The default SharedPreference of the application
 	 * @return Unique integer attack ID
 	 */
-	private synchronized int getAndIncrementAttackID(SharedPreferences pref){
+	private synchronized int getAndIncrementAttackID(SharedPreferences pref) {
 		Editor editor = pref.edit();
 		int attackID = pref.getInt("ATTACK_ID_COUNTER", 0);
 		editor.putInt("ATTACK_ID_COUNTER", attack_id + 1);
 		editor.commit();
 		return attackID;
 	}
-	
+
 	/**
-	 * Gets current message ID for the record. Also increases the message ID counter by one. Method is synchronized for thread safety.
+	 * Gets current message ID for the record. Also increases the message ID
+	 * counter by one. Method is synchronized for thread safety.
+	 * 
 	 * @return Unique integer message ID
 	 */
-	private synchronized int getAndIncrementMessageCounter(){
+	private synchronized int getAndIncrementMessageCounter() {
 		int msgID = message_id;
 		message_id++;
 		return msgID;

+ 161 - 126
src/de/tudarmstadt/informatik/hostage/HoneyService.java

@@ -28,24 +28,35 @@ 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.logging.UglyDbHelper;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 import de.tudarmstadt.informatik.hostage.protocol.ProtocolSettings;
 import de.tudarmstadt.informatik.hostage.ui.MainActivity;
+
 /**
  * Background service running as long as at least one protocol is active.
- * Service controls start and stop of protocol listener.
- * Notifies GUI about events happening in the background.
- * Creates Notifications to inform the user what it happening.
- * @author Mihai Plasoianu 
+ * Service controls start and stop of protocol listener. Notifies GUI about
+ * events happening in the background. Creates Notifications to inform the user
+ * what it happening.
+ * 
+ * @author Mihai Plasoianu
  * @author Lars Pandikow
  * @author Wulf Pfeiffer
  */
 public class HoneyService extends Service {
 
+	private static Context context;
+
+	/**
+	 * Returns the application context.
+	 * 
+	 * @return context.
+	 */
+	public static Context getContext() {
+		return HoneyService.context;
+	}
+
 	private ArrayList<HoneyListener> listeners = new ArrayList<HoneyListener>();
 	private NotificationCompat.Builder builder;
 	private SharedPreferences sessionPref;
@@ -55,12 +66,6 @@ public class HoneyService extends Service {
 		return listeners;
 	}
 
-	private Logger log;
-
-	public Logger getLog() {
-		return log;
-	}
-
 	private final IBinder mBinder = new LocalBinder();
 
 	public class LocalBinder extends Binder {
@@ -77,8 +82,9 @@ public class HoneyService extends Service {
 	@Override
 	public void onCreate() {
 		super.onCreate();
-		log = new SQLLogger(getApplicationContext());
-		sessionPref = getSharedPreferences(MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
+		HoneyService.context = getApplicationContext();
+		sessionPref = getSharedPreferences(MainActivity.SESSION_DATA,
+				Context.MODE_PRIVATE);
 		editor = sessionPref.edit();
 		createNotification();
 		for (Protocol protocol : getProtocolArray()) {
@@ -86,15 +92,15 @@ public class HoneyService extends Service {
 		}
 		registerNetReceiver();
 		getLocationData();
-		new QotdTask().execute(new String[]{});
+		new QotdTask().execute(new String[] {});
+	}
+
+	@Override
+	public int onStartCommand(Intent intent, int flags, int startId) {
+		// We want this service to continue running until it is explicitly
+		// stopped, so return sticky.
+		return START_STICKY;
 	}
-	
-    @Override
-    public int onStartCommand(Intent intent, int flags, int startId) {
-        // We want this service to continue running until it is explicitly
-        // stopped, so return sticky.
-        return START_STICKY;
-    }	
 
 	@Override
 	public void onDestroy() {
@@ -102,35 +108,37 @@ public class HoneyService extends Service {
 		super.onDestroy();
 		unregisterNetReceiver();
 	}
-	
-	/** Starts an Instance of MyLocationManager to set the location within this class.
+
+	/**
+	 * Starts an Instance of MyLocationManager to set the location within this
+	 * class.
 	 */
-	private void getLocationData(){
-		//TODO Put time and attempts in settings
+	private void getLocationData() {
+		// TODO Put time and attempts in settings
 		MyLocationManager locationManager = new MyLocationManager(this);
 		locationManager.getUpdates(60 * 1000, 3);
 	}
-	
+
 	/**
 	 * Deletes all session related data.
 	 */
-	private void deleteSessionData(){
-    	editor.clear();
-    	editor.commit();
+	private void deleteSessionData() {
+		editor.clear();
+		editor.commit();
 	}
-	
+
 	/**
 	 * Register broadcast receiver for connectivity changes
 	 */
 	private void registerNetReceiver() {
-	    // register BroadcastReceiver on network state changes	    
+		// register BroadcastReceiver on network state changes
 		IntentFilter intent = new IntentFilter();
-	    intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); //"android.net.conn.CONNECTIVITY_CHANGE"
-	    registerReceiver(netReceiver, intent);
+		intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // "android.net.conn.CONNECTIVITY_CHANGE"
+		registerReceiver(netReceiver, intent);
 	}
 
 	/**
-	 *  Unregister broadcast receiver for connectivity changes
+	 * Unregister broadcast receiver for connectivity changes
 	 */
 	private void unregisterNetReceiver() {
 		unregisterReceiver(netReceiver);
@@ -138,57 +146,60 @@ public class HoneyService extends Service {
 
 	/**
 	 * Receiver for connectivity change broadcast.
+	 * 
 	 * @see MainActivity#BROADCAST
 	 */
 	private BroadcastReceiver netReceiver = new BroadcastReceiver() {
 		@Override
 		public void onReceive(Context context, Intent intent) {
-				String bssid_old = sessionPref.getString(MainActivity.BSSID, "");
-				String bssid_new = HelperUtils.getBSSID(context);
-				//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");
+			String bssid_old = sessionPref.getString(MainActivity.BSSID, "");
+			String bssid_new = HelperUtils.getBSSID(context);
+			// 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");
+			}
 		}
-	};	
-
+	};
 
 	/**
 	 * Creates a Notification in the notification bar.
 	 */
 	private void createNotification() {
-		DatabaseHandler dbh = new DatabaseHandler(this);
+		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){
+
+		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()))){
+			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 = 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){
+		} else if (bssidSeen) {
 			builder.setSmallIcon(R.drawable.ic_service_yellow);
 			builder.setContentText("Network has been infected in previous session!");
-		} else{
+		} 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));
@@ -198,30 +209,32 @@ public class HoneyService extends Service {
 		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");  
+		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)
+				.setSmallIcon(R.drawable.ic_service_red).setAutoCancel(true)
 				.setWhen(System.currentTimeMillis())
-				.setSound(Uri.parse(strRingtonePreference)); 
+				.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});
-		} 
+		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());
@@ -235,10 +248,13 @@ public class HoneyService extends Service {
 		mNotificationManager.cancel(1);
 	}
 
-
 	/**
-	 * Creates a instance of each protocol defined in /res/values/protocols.xml and puts it in a List
-	 * @return ArrayList of {@link de.tudarmstadt.informatik.hostage.protocol.Protocol Protocol}
+	 * Creates a instance of each protocol defined in /res/values/protocols.xml
+	 * and puts it in a List
+	 * 
+	 * @return ArrayList of
+	 *         {@link de.tudarmstadt.informatik.hostage.protocol.Protocol
+	 *         Protocol}
 	 */
 	private ArrayList<Protocol> getProtocolArray() {
 		String[] protocols = getResources().getStringArray(R.array.protocols);
@@ -256,29 +272,33 @@ public class HoneyService extends Service {
 		}
 		return protocolArray;
 	}
-	
+
 	/**
 	 * Determines if there are running listeners.
+	 * 
 	 * @return True if there is a running listener, else false.
 	 */
-	public boolean hasRunningListeners(){
+	public boolean hasRunningListeners() {
 		for (HoneyListener listener : listeners) {
-				if (listener.isRunning())
-					return true;
+			if (listener.isRunning())
+				return true;
 		}
 		return false;
 	}
 
 	/**
 	 * Notifies the GUI about a event.
-	 * @param protocol The protocol where the event happened.
-	 * @param key The key for the event.
+	 * 
+	 * @param protocol
+	 *            The protocol where the event happened.
+	 * @param key
+	 *            The key for the event.
 	 */
 	public void notifyUI(String sender, String key) {
 		// Send Notification
-		if (key.equals(MainActivity.HANDLER_COUNT)){
+		if (key.equals(MainActivity.HANDLER_COUNT)) {
 			updateNotification();
-		}else if(key.equals("CONNECTIVITY_CHANGE")){
+		} else if (key.equals("CONNECTIVITY_CHANGE")) {
 			createNotification();
 		}
 		Log.i("HoneyService", key);
@@ -287,18 +307,19 @@ public class HoneyService extends Service {
 		intent.putExtra("SENDER", sender);
 		intent.putExtra("SENDER", key);
 		LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
-	}	
-	
+	}
+
 	/**
 	 * Starts all listeners which are not already running
 	 */
 	public void startListeners() {
 		for (HoneyListener listener : listeners) {
-			if(!listener.isRunning()){
+			if (!listener.isRunning()) {
 				listener.start();
 			}
 		}
-		Toast.makeText(getApplicationContext(), "SERVICES STARTED!", Toast.LENGTH_SHORT).show();
+		Toast.makeText(getApplicationContext(), "SERVICES STARTED!",
+				Toast.LENGTH_SHORT).show();
 	}
 
 	/**
@@ -306,46 +327,55 @@ public class HoneyService extends Service {
 	 */
 	public void stopListeners() {
 		for (HoneyListener listener : listeners) {
-			if(listener.isRunning()){
+			if (listener.isRunning()) {
 				listener.stop();
 			}
 		}
-		Toast.makeText(getApplicationContext(), "SERVICES STOPPED!", Toast.LENGTH_SHORT).show();
+		Toast.makeText(getApplicationContext(), "SERVICES STOPPED!",
+				Toast.LENGTH_SHORT).show();
 	}
 
 	/**
 	 * Starts the listener for the specified protocol.
-	 * @param protocolName Name of the protocol that should be started.
-	 */ 
+	 * 
+	 * @param protocolName
+	 *            Name of the protocol that should be started.
+	 */
 	public void startListener(String protocolName) {
 		for (HoneyListener listener : listeners) {
 			if (listener.getProtocolName().equals(protocolName)) {
-				if(!listener.isRunning()){
+				if (!listener.isRunning()) {
 					listener.start();
 				}
 			}
 		}
-		Toast.makeText(getApplicationContext(), protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
+		Toast.makeText(getApplicationContext(),
+				protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
 	}
 
 	/**
 	 * Stops the listener for the specified protocol.
-	 * @param protocolName Name of the protocol that should be stopped.
-	 */ 
+	 * 
+	 * @param protocolName
+	 *            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()){
+				if (listener.isRunning()) {
 					listener.stop();
 				}
 			}
 		}
-		Toast.makeText(getApplicationContext(), protocolName + " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
+		Toast.makeText(getApplicationContext(),
+				protocolName + " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
 	}
 
 	/**
 	 * Toggles a listener for specified protocol.
-	 * @param protocolName Name of the protocol that should be toggled.
+	 * 
+	 * @param protocolName
+	 *            Name of the protocol that should be toggled.
 	 */
 	public void toggleListener(String protocolName) {
 		for (HoneyListener listener : listeners) {
@@ -358,38 +388,43 @@ public class HoneyService extends Service {
 			}
 		}
 	}
-	
+
 	/**
 	 * Task for accuiring a qotd from one of four possible servers.
+	 * 
 	 * @author Wulf Pfeiffer
 	 */
-	private class QotdTask extends AsyncTask<String, Void, String>{	
-		 @Override
-		 protected String doInBackground(String... unused) {
-			 String[] sources = new String[]{"djxmmx.net", "ota.iambic.com", "alpha.mike-r.com", "electricbiscuit.org"};
-			 SecureRandom rndm = new SecureRandom();
-			 StringBuffer sb = new StringBuffer();
-			 try {
-				 Socket client = new Socket(sources[rndm.nextInt(4)], 17);
-				 BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));		
-				 while(!in.ready());
-				 while(in.ready()) {
-					 sb.append(in.readLine());
-				 }
-				 in.close();
-				 client.close();
-			 } catch (Exception e) {
-				 e.printStackTrace();
-			 }
-			 return sb.toString();
-		 }
-			 
-		 @Override
-		 protected void onPostExecute(String result){
-			 if (result != null)
-				 ProtocolSettings.setHttpQotd(result);
-			 else
-				 ProtocolSettings.setHttpQotd(new String(HelperUtils.getRandomString(100, false)));
-		 }
+	private class QotdTask extends AsyncTask<String, Void, String> {
+		@Override
+		protected String doInBackground(String... unused) {
+			String[] sources = new String[] { "djxmmx.net", "ota.iambic.com",
+					"alpha.mike-r.com", "electricbiscuit.org" };
+			SecureRandom rndm = new SecureRandom();
+			StringBuffer sb = new StringBuffer();
+			try {
+				Socket client = new Socket(sources[rndm.nextInt(4)], 17);
+				BufferedReader in = new BufferedReader(new InputStreamReader(
+						client.getInputStream()));
+				while (!in.ready())
+					;
+				while (in.ready()) {
+					sb.append(in.readLine());
+				}
+				in.close();
+				client.close();
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+			return sb.toString();
+		}
+
+		@Override
+		protected void onPostExecute(String result) {
+			if (result != null)
+				ProtocolSettings.setHttpQotd(result);
+			else
+				ProtocolSettings.setHttpQotd(new String(HelperUtils
+						.getRandomString(100, false)));
+		}
 	};
 }

+ 111 - 66
src/de/tudarmstadt/informatik/hostage/commons/HelperUtils.java

@@ -30,19 +30,23 @@ import android.os.Environment;
 import android.preference.PreferenceManager;
 import android.text.TextUtils;
 import de.tudarmstadt.informatik.hostage.logging.Record;
+import de.tudarmstadt.informatik.hostage.logging.formatter.TraCINgFormatter;
 import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
 
 /**
  * Helper class with some static methods for general usage.
+ * 
  * @author Lars Pandikow
  * @author Wulf Pfeiffer
- *
+ * 
  */
 public final class HelperUtils {
 
 	/**
 	 * Gets SSID of the wireless network.
-	 * @param context Needs a context to get system recourses
+	 * 
+	 * @param context
+	 *            Needs a context to get system recourses
 	 * @return SSID of wireless network if connected, else null.
 	 */
 	public static String getSSID(Context context) {
@@ -65,7 +69,9 @@ public final class HelperUtils {
 
 	/**
 	 * Gets BSSID of the wireless network.
-	 * @param context Needs a context to get system recourses.
+	 * 
+	 * @param context
+	 *            Needs a context to get system recourses.
 	 * @return BSSID of wireless network if connected, else null.
 	 */
 	public static String getBSSID(Context context) {
@@ -88,8 +94,11 @@ public final class HelperUtils {
 
 	/**
 	 * Gets internal IP address of the device in a wireless network.
-	 * @param context Needs a context to get system recourses.
-	 * @return internal IP of the device in a wireless network if connected, else null.
+	 * 
+	 * @param context
+	 *            Needs a context to get system recourses.
+	 * @return internal IP of the device in a wireless network if connected,
+	 *         else null.
 	 */
 	public static String getInternalIP(Context context) {
 		String ipAddress = null;
@@ -118,11 +127,13 @@ public final class HelperUtils {
 		return new byte[] { (byte) ((bytes) & 0xff),
 				(byte) ((bytes >>> 8) & 0xff), (byte) ((bytes >>> 16) & 0xff),
 				(byte) ((bytes >>> 24) & 0xff) };
-	} 
+	}
 
 	/**
 	 * Checks if external storage is available for read and write.
-	 * @return True if external storage is available for read and write, else false.
+	 * 
+	 * @return True if external storage is available for read and write, else
+	 *         false.
 	 */
 	public static boolean isExternalStorageWritable() {
 		String state = Environment.getExternalStorageState();
@@ -134,6 +145,7 @@ public final class HelperUtils {
 
 	/**
 	 * Creates a HttpClient with an own SSL Socket.
+	 * 
 	 * @return HttpsClient who accepts accepts all certificates.
 	 * @see MySSLSocketFactory
 	 */
@@ -164,46 +176,56 @@ public final class HelperUtils {
 			return new DefaultHttpClient();
 		}
 	}
-	
+
 	/**
 	 * Uploads a single Record to a server, specified in the settings.
-	 * @param record The Record to upload.
+	 * 
+	 * @param record
+	 *            The Record to upload.
 	 * @return True if the upload was successful, else false.
 	 */
-	public static boolean uploadSingleRecord(Context context, Record record){
-	  	// Create a https client. Uses MySSLSocketFactory to accept all certificates
+	public static boolean uploadSingleRecord(Context context, Record record) {
+		// Create a https client. Uses MySSLSocketFactory to accept all
+		// certificates
 		HttpClient httpclient = HelperUtils.createHttpClient();
 		HttpPost httppost;
 		try {
 			// Create HttpPost
-			httppost = new HttpPost(PreferenceManager.getDefaultSharedPreferences(context).getString("pref_upload", "https://ssi.cased.de"));
+			httppost = new HttpPost(PreferenceManager
+					.getDefaultSharedPreferences(context).getString(
+							"pref_upload", "https://ssi.cased.de"));
 			// Create JSON String of Record
-			StringEntity se = new StringEntity(record.toString(0x01));
+			StringEntity se = new StringEntity(record.toString(TraCINgFormatter
+					.getInstance()));
 			httppost.setEntity(se);
 			// Execute HttpPost
 			httpclient.execute(httppost);
 		} catch (Exception e) {
 			e.printStackTrace();
 			return false;
-		}		
+		}
 		return true;
 	}
-	
+
 	/**
 	 * Concatenates several byte arrays.
-	 * @param bytes The byte arrays.
-	 * @return A single byte arrays containing all the bytes from the given arrays in the order they are given.
+	 * 
+	 * @param bytes
+	 *            The byte arrays.
+	 * @return A single byte arrays containing all the bytes from the given
+	 *         arrays in the order they are given.
 	 */
 	public static byte[] concat(byte[]... bytes) {
 		int newSize = 0;
 		for (byte[] b : bytes)
-			if(b != null) newSize += b.length;
+			if (b != null)
+				newSize += b.length;
 		byte[] dst = new byte[newSize];
 
 		int currentPos = 0;
 		int newPos;
 		for (byte[] b : bytes) {
-			if(b != null) {
+			if (b != null) {
 				newPos = b.length;
 				System.arraycopy(b, 0, dst, currentPos, newPos);
 				currentPos += newPos;
@@ -211,10 +233,13 @@ public final class HelperUtils {
 		}
 		return dst;
 	}
-	
+
 	/**
-	 * Converts a byte[] to a String, but only characters in ASCII between 32 and 127
-	 * @param bytes that are converted
+	 * Converts a byte[] to a String, but only characters in ASCII between 32
+	 * and 127
+	 * 
+	 * @param bytes
+	 *            that are converted
 	 * @return converted String
 	 */
 	public static String byteToStr(byte[] bytes) {
@@ -230,97 +255,117 @@ public final class HelperUtils {
 
 	/**
 	 * Determines if a character is in ASCII between 32 and 126
-	 * @param character that is checked 
+	 * 
+	 * @param character
+	 *            that is checked
 	 * @return true if the character is between 32 and 126, else false
 	 */
 	private static boolean isLetter(char character) {
 		return (character > 31 && character < 127);
 	}
-	
+
 	/**
-	 * Converts a byte array into a hexadecimal String, e.g. {0x00, 0x01} to "00, 01". 
-	 * @param bytes that will be converted.
+	 * Converts a byte array into a hexadecimal String, e.g. {0x00, 0x01} to
+	 * "00, 01".
+	 * 
+	 * @param bytes
+	 *            that will be converted.
 	 * @return converted String.
 	 */
 	public static String bytesToHexString(byte[] bytes) {
 		char[] hexArray = "0123456789ABCDEF".toCharArray();
-	    int v;
-	    StringBuffer buffer = new StringBuffer();
-	    for(int j = 0; j < bytes.length; j++ ) {
-	        v = bytes[j] & 0xFF;
-	        buffer.append(hexArray[v >>> 4]);
-	        buffer.append(hexArray[v & 0x0F]);
-	        if(j < bytes.length-1) buffer.append(", ");
-	    }
-	    return buffer.toString();
+		int v;
+		StringBuffer buffer = new StringBuffer();
+		for (int j = 0; j < bytes.length; j++) {
+			v = bytes[j] & 0xFF;
+			buffer.append(hexArray[v >>> 4]);
+			buffer.append(hexArray[v & 0x0F]);
+			if (j < bytes.length - 1)
+				buffer.append(", ");
+		}
+		return buffer.toString();
 	}
-	
+
 	/**
-	 * Converts a String into a byte array, e.g. "00, 01" to {0x00, 0x01}. 
-	 * @param string that will be converted.
+	 * Converts a String into a byte array, e.g. "00, 01" to {0x00, 0x01}.
+	 * 
+	 * @param string
+	 *            that will be converted.
 	 * @return converted byte array.
 	 */
 	public static byte[] hexStringToBytes(String string) {
-	    String[] hexStrings = string.split(", ");
-	    byte[] bytes = new byte[hexStrings.length];
-	    for(int j = 0; j < hexStrings.length; j++ ) {
-	    	bytes[j] = (byte) ((Character.digit(hexStrings[j].charAt(0), 16) << 4)
-                    + Character.digit(hexStrings[j].charAt(1), 16));
-	    }
-	    return bytes;
+		String[] hexStrings = string.split(", ");
+		byte[] bytes = new byte[hexStrings.length];
+		for (int j = 0; j < hexStrings.length; j++) {
+			bytes[j] = (byte) ((Character.digit(hexStrings[j].charAt(0), 16) << 4) + Character
+					.digit(hexStrings[j].charAt(1), 16));
+		}
+		return bytes;
 	}
-	
+
 	/**
-	 * Produces a random String.
-	 * The String can be of random length with a maximum length, or it can be forced to have the length that was given.
-	 * @param length maximal / forced length of String.
-	 * @param forceLength forces the String to be exact the given length instead of maximum
+	 * Produces a random String. The String can be of random length with a
+	 * maximum length, or it can be forced to have the length that was given.
+	 * 
+	 * @param length
+	 *            maximal / forced length of String.
+	 * @param forceLength
+	 *            forces the String to be exact the given length instead of
+	 *            maximum
 	 * @return random String.
 	 */
 	public static String getRandomString(int length, boolean forceLength) {
 		SecureRandom rndm = new SecureRandom();
 		char[] c = new char[forceLength ? length : rndm.nextInt(length)];
-		for(int i = 0; i < c.length; i++) {
-			c[i] = (char) (rndm.nextInt(95)+32);
+		for (int i = 0; i < c.length; i++) {
+			c[i] = (char) (rndm.nextInt(95) + 32);
 		}
 		return new String(c);
 	}
-	
+
 	/**
-	 * Puts a 0x00 byte between each byte and another 2 0x00 bytes at the end of a byte array.
-	 * @param bytes that need to be filled with 0x00.
+	 * Puts a 0x00 byte between each byte and another 2 0x00 bytes at the end of
+	 * a byte array.
+	 * 
+	 * @param bytes
+	 *            that need to be filled with 0x00.
 	 * @return filled byte array.
 	 */
 	public static byte[] fillWithZeroExtended(byte[] bytes) {
 		byte[] zeroBytes = fillWithZero(bytes);
-		byte[] newBytes = new byte[zeroBytes.length+2];
-		newBytes = HelperUtils.concat(zeroBytes, new byte[]{0x00, 0x00});
+		byte[] newBytes = new byte[zeroBytes.length + 2];
+		newBytes = HelperUtils.concat(zeroBytes, new byte[] { 0x00, 0x00 });
 		return newBytes;
 	}
-	
+
 	/**
 	 * Puts a 0x00 byte between each byte in a byte array.
-	 * @param bytes that need to be filled with 0x00.
+	 * 
+	 * @param bytes
+	 *            that need to be filled with 0x00.
 	 * @return filled byte array.
 	 */
 	public static byte[] fillWithZero(byte[] bytes) {
 		byte[] newBytes = new byte[(bytes.length * 2)];
-		for(int i = 0, j = 0; i < bytes.length && j < newBytes.length; i++, j=j+2) {
+		for (int i = 0, j = 0; i < bytes.length && j < newBytes.length; i++, j = j + 2) {
 			newBytes[j] = bytes[i];
-			newBytes[j+1] = 0x00;
+			newBytes[j + 1] = 0x00;
 		}
 		return newBytes;
 	}
-	
+
 	/**
-	 * Turns around the values of an byte[], e.g. {0x00, 0x01, 0x02} turns into {0x02, 0x01, 0x00}.
-	 * @param bytes array that is turned.
+	 * Turns around the values of an byte[], e.g. {0x00, 0x01, 0x02} turns into
+	 * {0x02, 0x01, 0x00}.
+	 * 
+	 * @param bytes
+	 *            array that is turned.
 	 * @return turned array.
 	 */
 	public static byte[] turnByteArray(byte[] bytes) {
 		byte[] tmp = new byte[bytes.length];
-		for(int i = 0; i < bytes.length; i++) {
-			tmp[i] = bytes[bytes.length-1-i];
+		for (int i = 0; i < bytes.length; i++) {
+			tmp[i] = bytes[bytes.length - 1 - i];
 		}
 		return tmp;
 	}

+ 0 - 14
src/de/tudarmstadt/informatik/hostage/format/DefaultFormatter.java

@@ -1,14 +0,0 @@
-package de.tudarmstadt.informatik.hostage.format;
-
-/**
- * Default log view formatter.
- * 
- * @author Wulf Pfeiffer
- */
-public class DefaultFormatter implements ProtocolFormatter {
-
-	public String format(String packet) {
-		return packet;
-	}
-
-}

+ 0 - 46
src/de/tudarmstadt/informatik/hostage/format/LogViewFormatter.java

@@ -1,46 +0,0 @@
-package de.tudarmstadt.informatik.hostage.format;
-
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.ui.MainActivity;
-
-/**
- * Log view formatter used to format packet contents for the log view.
- * @author Wulf Pfeiffer
- */
-public class LogViewFormatter {
-	
-	/**
-	 * Formats the content of a packet giving it a specific format specified by a ProtocolFormatter. 
-	 * @param protocol that is used for packet.
-	 * @param packet content.
-	 * @return formatted String of the packet content.
-	 */
-	public static String format(String protocol, String packet) {		
-		return getFormatter(protocol).format(packet);
-	}
-	
-	/**
-	 * Loads a ProtocolFormatter for a protocol.
-	 * If the protocol has its own formatter, with the name *protocol name*Formatter and it is located in .format package, it is loaded,
-	 * else a default formatter is loaded.
-	 * @param protocol that a formatter should be loaded for.
-	 * @return the loaded formatter.
-	 */
-	private static ProtocolFormatter getFormatter(String protocol) {
-		String[] protocols = MainActivity.getContext().getResources().getStringArray(R.array.protocols);
-		String packageName = ProtocolFormatter.class.getPackage().getName();
-		ProtocolFormatter formatter = new DefaultFormatter();
-
-		for (String prot : protocols) {
-			try {
-				if(protocol.equals(prot)) formatter = (ProtocolFormatter) Class.forName(
-						String.format("%s.%s", packageName, protocol+"Formatter"))
-						.newInstance();
-			} catch (Exception e) {
-				e.printStackTrace();
-			}
-		}
-		return formatter;
-	}
-
-}

+ 0 - 64
src/de/tudarmstadt/informatik/hostage/format/MySQLFormatter.java

@@ -1,64 +0,0 @@
-package de.tudarmstadt.informatik.hostage.format;
-
-import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-
-/**
- * MySQL log view formatter.
- * @author Wulf Pfeiffer
- */
-public class MySQLFormatter implements ProtocolFormatter {
-
-	public String format(String packet) {
-		byte[] bytes = HelperUtils.hexStringToBytes(packet);
-		String command = "Command: " + getCommand(bytes) + "\n";
-		String content = "Content: " + HelperUtils.byteToStr(bytes) + "\n";
-		return command + content;
-	}
-	
-	/**
-	 * Checks a packet for its command code and returns the name of this command.
-	 * @param bytes to check.
-	 * @return name of the command.
-	 */
-	private String getCommand(byte[] bytes) {
-		//if packet number is 1 server started conversation so it must be login
-		if(bytes.length < 5) return "";
-		if(bytes[3] == 0x01) return "Login request"; 
-		//else check for command code
-		switch(bytes[4]) {
-		case 0x00: return "COM_SLEEP";
-		case 0x01: return "COM_QUIT";
-		case 0x02: return "COM_INIT_DB";
-		case 0x03: return "COM_QUERY";
-		case 0x04: return "COM_FIELD_LIST";
-		case 0x05: return "COM_CREATE_DB";
-		case 0x06: return "COM_DROP_DB";
-		case 0x07: return "COM_REFRESH";
-		case 0x08: return "COM_SHUTDOWN";
-		case 0x09: return "COM_STATISTICS";
-		case 0x0a: return "COM_PROCESS_INFO";
-		case 0x0b: return "COM_CONNECT";
-		case 0x0c: return "COM_PROCESS_KILL";
-		case 0x0d: return "COM_DEBUG";
-		case 0x0e: return "COM_PING";
-		case 0x0f: return "COM_TIME";
-		case 0x10: return "COM_DELAYED_INSERT";
-		case 0x11: return "COM_CHANGE_USER";
-		case 0x12: return "COM_BINLOG_DUMP";
-		case 0x13: return "COM_TABLE_DUMP";
-		case 0x14: return "COM_CONNECT_OUT";
-		case 0x15: return "COM_REGISTER_SLAVE";
-		case 0x16: return "COM_STMT_PREPARE";
-		case 0x17: return "COM_STMT_EXECUTE";
-		case 0x18: return "COM_STMT_SEND_LONG_DATA";
-		case 0x19: return "COM_STMT_CLOSE";
-		case 0x1a: return "COM_STMT_RESET";
-		case 0x1b: return "COM_SET_OPTION";
-		case 0x1c: return "COM_STMT_FETCH";
-		case 0x1d: return "COM_DAEMON";
-		case 0x1e: return "COM_BINLOG_DUMP_GTID";
-		default: return "unkown command";
-		}
-	}
-
-}

+ 0 - 17
src/de/tudarmstadt/informatik/hostage/format/ProtocolFormatter.java

@@ -1,17 +0,0 @@
-package de.tudarmstadt.informatik.hostage.format;
-
-/**
- * Interface for log view formatter.
- * This class provides functionality to format the presentation of specific protocols.
- * @author Wulf Pfeiffer
- */
-public interface ProtocolFormatter {
-
-	/**
-	 * Formats the content of packet. The packet content can be a normal String or a hexadecimal String,
-	 * depending of the type of the protocol. ByteArray protocols receive hexdecimal String, else normal Strings.
-	 * @param packet that should be formatted.
-	 * @return new format of the packet content.
-	 */
-	String format(String packet);
-}

+ 0 - 135
src/de/tudarmstadt/informatik/hostage/format/SMBFormatter.java

@@ -1,135 +0,0 @@
-package de.tudarmstadt.informatik.hostage.format;
-
-import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-
-/**
- * SMB log view formatter.
- * @author Wulf Pfeiffer
- */
-public class SMBFormatter implements ProtocolFormatter {
-
-	public String format(String packet) {
-		byte[] bytes = HelperUtils.hexStringToBytes(packet);
-		byte cmd = bytes[8]; //command code located at 8
-		StringBuffer buffer = new StringBuffer();
-		buffer.append("Command: ");
-		buffer.append(getCommandString(cmd));
-		buffer.append("\n");
-		buffer.append("Content: ");
-		buffer.append(getContent(cmd, bytes));
-		
-		return buffer.toString();
-	}
-	
-	/**
-	 * Checks command code for its command code and returns the name of this command.
-	 * @param command as byte.
-	 * @return command name as String.
-	 */
-	private String getCommandString(byte command) {
-		switch(command) {
-		case 0x00: return "SMB_COM_CREATE_DIRECTORY";
-		case 0x01: return "SMB_COM_DELETE_DIRECTORY";
-		case 0x02: return "SMB_COM_OPEN";
-		case 0x03: return "SMB_COM_CREATE";
-		case 0x04: return "SMB_COM_CLOSE";
-		case 0x05: return "SMB_COM_FLUSH";
-		case 0x06: return "SMB_COM_DELETE";
-		case 0x07: return "SMB_COM_RENAME";
-		case 0x08: return "SMB_COM_QUERY_INFORMATION";
-		case 0x09: return "SMB_COM_SET_INFORMATION";
-		case 0x0A: return "SMB_COM_READ";
-		case 0x0B: return "SMB_COM_WRITE";
-		case 0x0C: return "SMB_COM_LOCK_BYTE_RANGE";
-		case 0x0D: return "SMB_COM_UNLOCK_BYTE_RANGE";
-		case 0x0E: return "SMB_COM_CREATE_TEMPORARY";
-		case 0x0F: return "SMB_COM_CREATE_NEW";
-		case 0x10: return "SMB_COM_CHECK_DIRECTORY";
-		case 0x11: return "SMB_COM_PROCESS_EXIT";
-		case 0x12: return "SMB_COM_SEEK";
-		case 0x13: return "SMB_COM_LOCK_AND_READ";
-		case 0x14: return "SMB_COM_WRITE_AND_UNLOCK";
-		case 0x1A: return "SMB_COM_READ_RAW";
-		case 0x1B: return "SMB_COM_READ_MPX";
-		case 0x1C: return "SMB_COM_READ_MPX_SECONDARY";
-		case 0x1D: return "SMB_COM_WRITE_RAW";
-		case 0x1E: return "SMB_COM_WRITE_MPX";
-		case 0x1F: return "SMB_COM_WRITE_MPX_SECONDARY";
-		case 0x20: return "SMB_COM_WRITE_COMPLETE";
-		case 0x21: return "SMB_COM_QUERY_SERVER";
-		case 0x22: return "SMB_COM_SET_INFORMATION2";
-		case 0x23: return "SMB_COM_QUERY_INFORMATION2";
-		case 0x24: return "SMB_COM_LOCKING_ANDX";
-		case 0x25: return "SMB_COM_TRANSACTION";
-		case 0x26: return "SMB_COM_TRANSACTION_SECONDARY";
-		case 0x27: return "SMB_COM_IOCTL";
-		case 0x28: return "SMB_COM_IOCTL_SECONDARY";
-		case 0x29: return "SMB_COM_COPY";
-		case 0x2A: return "SMB_COM_MOVE";
-		case 0x2B: return "SMB_COM_ECHO";
-		case 0x2C: return "SMB_COM_WRITE_AND_CLOSE";
-		case 0x2D: return "SMB_COM_OPEN_ANDX";
-		case 0x2E: return "SMB_COM_READ_ANDX";
-		case 0x2F: return "SMB_COM_WRITE_ANDX";
-		case 0x30: return "SMB_COM_NEW_FILE_SIZE";
-		case 0x31: return "SMB_COM_CLOSE_AND_TREE_DISC";
-		case 0x32: return "SMB_COM_TRANSACTION2";
-		case 0x33: return "SMB_COM_TRANSACTION2_SECONDARY";
-		case 0x34: return "SMB_COM_FIND_CLOSE2";
-		case 0x35: return "SMB_COM_FIND_NOTIFY_CLOSE";
-		case 0x70: return "SMB_COM_TREE_CONNECT";
-		case 0x71: return "SMB_COM_TREE_DISCONNECT";
-		case 0x72: return "SMB_COM_NEGOTIATE";
-		case 0x73: return "SMB_COM_SESSION_SETUP_ANDX";
-		case 0x74: return "SMB_COM_LOGOFF_ANDX";
-		case 0x75: return "SMB_COM_TREE_CONNECT_ANDX";
-		case (byte)0x80: return "SMB_COM_QUERY_INFORMATION_DISK";
-		case (byte)0x81: return "SMB_COM_SEARCH";
-		case (byte)0x82: return "SMB_COM_FIND";
-		case (byte)0x83: return "SMB_COM_FIND_UNIQUE";
-		case (byte)0x84: return "SMB_COM_FIND_CLOSE";
-		case (byte)0xA0: return "SMB_COM_NT_TRANSACT";
-		case (byte)0xA1: return "SMB_COM_NT_TRANSACT_SECONDARY";
-		case (byte)0xA2: return "SMB_COM_NT_CREATE_ANDX";
-		case (byte)0xA4: return "SMB_COM_NT_CANCEL";
-		case (byte)0xA5: return "SMB_COM_NT_RENAME";
-		case (byte)0xC0: return "SMB_COM_OPEN_PRINT_FILE";
-		case (byte)0xC1: return "SMB_COM_WRITE_PRINT_FILE";
-		case (byte)0xC2: return "SMB_COM_CLOSE_PRINT_FILE";
-		case (byte)0xC3: return "SMB_COM_GET_PRINT_QUEUE";
-		case (byte)0xD8: return "SMB_COM_READ_BULK";
-		case (byte)0xD9: return "SMB_COM_WRITE_BULK";
-		case (byte)0xDA: return "SMB_COM_WRITE_BULK_DATA";
-		case (byte)0xFF: return "SMB_COM_NONE";
-		default: return "Unknown Command";
-		}
-	}
-	
-	/**
-	 * Returns the content of a packet as a String value, depending on its command code
-	 * @param command of the packet.
-	 * @param packet content as byte array. 
-	 * @return content as a String.
-	 */
-	private String getContent(byte command, byte[] packet) {
-		switch(command) {
-		case 0x72: return get0x72content(packet);
-		case 0x73: return HelperUtils.byteToStr(packet);
-		case (byte) 0xa2: return HelperUtils.byteToStr(packet);
-		case 0x25: return HelperUtils.byteToStr(packet);
-		default: return "";
-		}
-	}
-	
-	/**
-	 * Returns the content of a packet with command code 0x72.
-	 * @param packet content as byte array.
-	 * @return content as String.
-	 */
-	private String get0x72content(byte[] packet) {
-		byte[] content = new byte[packet.length-39];
-		System.arraycopy(packet, 39, content, 0, content.length);
-		return HelperUtils.byteToStr(content);
-	}
-
-}

+ 0 - 99
src/de/tudarmstadt/informatik/hostage/format/TELNETFormatter.java

@@ -1,99 +0,0 @@
-package de.tudarmstadt.informatik.hostage.format;
-
-import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-
-/**
- * Telnet log view formatter.
- * 
- * @author Wulf Pfeiffer
- */
-public class TELNETFormatter implements ProtocolFormatter {
-
-	public String format(String packet) {
-		byte[] bytes = HelperUtils.hexStringToBytes(packet);
-		String options = "Options:\n" + checkForOptions(bytes) + "\n";
-		String content = "Content: " + HelperUtils.byteToStr(bytes);
-		return options + content;
-	}
-
-	/**
-	 * Checks a packet for option commands and returns their names as Strings.
-	 * @param bytes that are checked.
-	 * @return names of the option commands as String.
-	 */
-	private String checkForOptions(byte[] bytes) {
-		StringBuffer options = new StringBuffer();
-		for (int i = 0; i < bytes.length; i++) {
-			if (bytes[i] == (byte) 0xff && i + 2 < bytes.length) {
-				options.append(checkMode(bytes[i + 1]));
-				// option name
-				options.append(checkCommand(bytes[i + 2]));
-			}
-		}
-		return options.toString();
-	}
-	
-	/**
-	 * Checks a byte for its mode value.
-	 * @param b byte that is checked.
-	 * @return name of the mode.
-	 */
-	private String checkMode(byte b) {
-		switch (b) {
-		case (byte) 0xfb:	return " WILL ";
-		case (byte) 0xfc:	return " WON'T ";
-		case (byte) 0xfd:	return " DO ";
-		case (byte) 0xfe:	return " DON'T ";
-		default:			return " unkown command ";
-		}
-	}
-	
-	/**
-	 * Checks a byte for its command value.
-	 * @param b byte that is checked.
-	 * @return name of the command.
-	 */
-	private String checkCommand(byte b) {
-		switch (b) {
-		case 0x00:	return "Binary Transmission\n";
-		case 0x01:	return "Echo\n";
-		case 0x02:	return "Reconnection\n";
-		case 0x03:	return "Suppress Go Ahead\n";
-		case 0x04:	return "Approx Message Size Negotiation\n";
-		case 0x05:	return "Status\n";
-		case 0x06:	return "Timing Mark\n";
-		case 0x07:	return "Remote Controlled Trans and Echo\n";
-		case 0x08:	return "Output Line Width\n";
-		case 0x09:	return "Output Page Size\n";
-		case 0x0a:	return "Output Carriage-Return Disposition\n";
-		case 0x0b:	return "Output Horizontal Tab Stops\n";
-		case 0x0c:	return "Output Horizontal Tab Disposition\n";
-		case 0x0d:	return "Output Formfeed Disposition\n";
-		case 0x0e:	return "Output Vertical Tabstops\n";
-		case 0x0f:	return "Output Vertical Tab Disposition\n";
-		case 0x10:	return "Output Linefeed Disposition\n";
-		case 0x11:	return "Extended ASCII\n";
-		case 0x12:	return "Logout\n";
-		case 0x13:	return "Byte Macro\n";
-		case 0x14:	return "Data Entry Terminal\n";
-		case 0x15:	return "SUPDUP\n";
-		case 0x16:	return "SUPDUP Output\n";
-		case 0x17:	return "Send Location\n";
-		case 0x18:	return "Terminal Type\n";
-		case 0x19:	return "End of Record\n";
-		case 0x1a:	return "TACACS User Identification\n";
-		case 0x1b:	return "Output Marking\n";
-		case 0x1c:	return "Terminal Location Number\n";
-		case 0x1d:	return "Telnet 3270 Regime\n";
-		case 0x1e:	return "X.3 PAD\n";
-		case 0x1f:	return "Negotiate About Window Size\n";
-		case 0x20:	return "Terminal Speed\n";
-		case 0x21:	return "Remote Flow Control\n";
-		case 0x22:	return "Linemode\n";
-		case 0x23:	return "X Display Location\n";
-		case (byte) 0xff:	return "Extended-Options-List\n";
-		default:	return "unknown option\n";
-		}
-	}
-
-}

+ 0 - 597
src/de/tudarmstadt/informatik/hostage/logging/DatabaseHandler.java

@@ -1,597 +0,0 @@
-package de.tudarmstadt.informatik.hostage.logging;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-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>
- * The database contains two tables: {@link #TABLE_RECORDS} and {@link #TABLE_BSSIDS}:<br>
- * {@link #TABLE_RECORDS} contains all logging information of a single message record except the SSID.<br>
- * {@link #TABLE_BSSIDS} contains the BSSID of all recorded Networks and the corresponding SSID.<br>
- * @author Lars Pandikow
- */
-public class DatabaseHandler extends SQLiteOpenHelper {
-
-	// All Static variables
-	// Database Version
-	private static final int DATABASE_VERSION = 1;
-
-	// Database Name
-	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
-	public static final String KEY_ID = "_id";
-	public static final String KEY_ATTACK_ID = "_attack_id";
-	public static final String KEY_TYPE = "type";
-	public static final String KEY_TIME = "timestamp";
-	public static final String KEY_PACKET = "packet";
-	public static final String KEY_PROTOCOL = "protocol";
-	public static final String KEY_EXTERNAL_IP ="externalIP";
-	public static final String KEY_LOCAL_IP = "localIP";
-	public static final String KEY_LOCAL_HOSTNAME = "localHostName";
-	public static final String KEY_LOCAL_PORT = "localPort";
-	public static final String KEY_REMOTE_IP = "remoteIP";
-	public static final String KEY_REMOTE_HOSTNAME = "remoteHostName";
-	public static final String KEY_REMOTE_PORT = "remotePort";
-	public static final String KEY_BSSID = "_bssid";
-	public static final String KEY_SSID = "ssid";
-	public static final String KEY_LATITUDE = "latitude";
-	public static final String KEY_LONGITUDE = "longitude";
-	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;
-	
-	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);
-	}
-
-	/**
-	 * Adds a given {@link Record}  to the database.
-	 * @param record The added {@link Record} .
-	 */
-	public void addRecord(Record record) {
-		SQLiteDatabase db = this.getWritableDatabase();
-
-		HashMap<String, Object> bssidValues = new HashMap<String, Object>();
-		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());
-		bssidValues.put(KEY_TIME, record.getTimestampLocation());
-		
-		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_TYPE, record.getType().name()); // Log Type
-		recordValues.put(KEY_TIME, record.getTimestamp()); // Log Timestamp
-		recordValues.put(KEY_PACKET, record.getPacket()); // Log Packet
-		
-
-		
-		
-		// Inserting Rows		
-		db.insertWithOnConflict(TABLE_ATTACK_INFO, null, attackValues, SQLiteDatabase.CONFLICT_REPLACE);
-		db.insert(TABLE_RECORDS, null, recordValues);
-		db.close(); // Closing database connection
-		// Update Network Information
-		updateNetworkInformation(bssidValues);
-	}
-	
-	/**
-	 * Creates a {@link Record} from a Cursor. If the cursor does not show to a valid data structure a runtime exception is thrown.
-	 * @param cursor
-	 * @return Returns the created {@link Record} .
-	 */
-	private Record createRecord(Cursor cursor){
-		Record record = new Record();
-		try {
-		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.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.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)));
-		} catch (UnknownHostException e) {
-			e.printStackTrace();
-		}
-		return record;
-	}
-
-	/**
-	 * Gets a single {@link Record} with the given ID from the database.
-	 * @param id The ID of the {@link Record};
-	 * @return The {@link Record}.
-	 */
-	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;
-		SQLiteDatabase db = this.getReadableDatabase();
-
-		Cursor cursor = db.rawQuery(selectQuery, null);
-		Record record = null;
-		if (cursor.moveToFirst()){
-			record = createRecord(cursor);
-		} 
-		
-        cursor.close();
-		db.close();
-		// return contact
-		return record;
-	}
-
-	/**
-	 * Gets all {@link Record Records} saved in the database. 
-	 * @return A ArrayList of all the {@link Record Records} in the Database.
-	 */
-	public ArrayList<Record> getAllRecords() {
-		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;
-
-		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);
-			} while (cursor.moveToNext());
-		}
-        cursor.close();
-		db.close();
-		// return record list
-		return recordList;
-	}
-    
-	/**
-	 * Gets a single {@link Record} with the given attack id from the database.
-	 * @param attack_id The attack id of the {@link Record};
-	 * @return The {@link Record}.
-	 */
-    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;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-        Record record = null;
-        
-		if (cursor.moveToFirst()) {
-				record = createRecord(cursor);
-		}
-        cursor.close();
- 
-        // return record list
-        db.close();
-        return record;
-    }
-    
-	/**
-	 * Gets all received {@link Record Records} for every attack identified by its attack id and ordered by date.
-	 * @return A ArrayList with all received {@link Record Records} for each attack id in the Database.
-	 */
-    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;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-		
-        // looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				Record record = createRecord(cursor);
-				// Adding record to list
-				recordList.add(record);
-			} while (cursor.moveToNext());
-		}       
-        cursor.close();
- 
-        // return record list
-        db.close();
-        return recordList;
-    }
-    
-	/**
-	 * Gets a representative {@link Record} for every attack identified by its attack id.
-	 * @return A ArrayList with one {@link Record Records} for each attack id in the Database.
-	 */
-    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;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-		
-        // looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				Record record = createRecord(cursor);
-				// Adding record to list
-				recordList.add(record);
-			} while (cursor.moveToNext());
-		}       
-        cursor.close();
- 
-        // return record list
-        db.close();
-        return recordList;
-    }
-    
-	/**
-	 * Gets a representative {@link Record} for every attack with a higher attack id than the specified.
-	 * @param attack_id The attack id to match the query against.
-	 * @return A ArrayList with one {@link Record Records} for each attack id higher than the given.
-	 */
-    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;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-		
-        // looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				Record record = createRecord(cursor);
-				// Adding record to list
-				recordList.add(record);
-			} while (cursor.moveToNext()); 
-		}       
-        cursor.close();
- 
-        // return count
-        db.close();
-        return recordList;
-    }
-	
-	/**
-	 * Determines the number of {@link Record Records} in the database.
-	 * @return The number of {@link Record Records} in the database.
-	 */
-    public int getRecordCount() {
-        String countQuery = "SELECT  * FROM " + TABLE_RECORDS;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(countQuery, null);
-       int result = cursor.getCount();
-       cursor.close();
- 
-        // return count
-        db.close();
-        return result;
-    }
-    
-	/**
-	 * Determines the number of different attack_ids in the database.
-	 * @return The number of different attack_ids in the database.
-	 */
-    public int getAttackCount() {
-        String countQuery = "SELECT  * FROM " + TABLE_ATTACK_INFO;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(countQuery, null);
-        int result = cursor.getCount();
-        cursor.close();
- 
-        // return count
-        db.close();
-        return result;
-    }
-    
-	/**
-	 * Determines the number of different attack_ids for a specific protocol in the database.
-	 * @param protocol The String representation of the {@link de.tudarmstadt.informatik.hostage.protocol.Protocol Protocol}
-	 * @return The number of different attack_ids in the database.
-	 */
-    public int getAttackPerProtokolCount(String protocol) {
-        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();
-        cursor.close();
- 
-        // return count
-        db.close();
-        return result;
-    }
-    
-   /**
-    * Determines the smallest attack id stored in the database.
-    * @return The smallest attack id stored in the database.
-    */
-    public long getSmallestAttackId(){
-    	String selectQuery = "SELECT MIN(" + KEY_ATTACK_ID +") FROM " + TABLE_ATTACK_INFO;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);        
-        int result;
-        
-        if (cursor.moveToFirst()) {
-        	result = cursor.getInt(0);
-        } else{
-        	result = -1;
-        }        
-    	cursor.close();
-    	db.close();
-    	return result;
-    }
-    
-    /**
-     * Determines the highest attack id stored in the database.
-     * @return The highest attack id stored in the database.
-     */
-    public long getHighestAttackId(){
-    	String selectQuery = "SELECT MAX(" + KEY_ATTACK_ID +") FROM " + TABLE_ATTACK_INFO;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-        int result;
-        
-        if (cursor.moveToFirst()) {
-        	result = cursor.getInt(0);
-        } else{
-        	result = -1;
-        }        
-    	cursor.close();
-    	db.close();
-    	return result;
-    }
-   
-    /**
-     * Determines if a network with given BSSID has already been recorded as malicious.
-     * @param BSSID The BSSID of the network.
-     * @return True if an attack has been recorded in a network with the given BSSID, else false.
-     */
-    public boolean bssidSeen(String BSSID){
-        String countQuery = "SELECT  * FROM " + TABLE_BSSIDS + " WHERE "  + KEY_BSSID + " = " + "'" + BSSID + "'";
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(countQuery, null);
-        int result = cursor.getCount();
-        cursor.close();
-        db.close();
-        return result > 0;        
-    }
-    
-    
-    /**
-     * Determines if an attack has been recorded on a specific protocol in a network with a given BSSID.
-     * @param protocol The {@link de.tudarmstadt.informatik.hostage.protocol.Protocol Protocol} to inspect.
-     * @param BSSID The BSSID of the network.
-     * @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_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();
-        cursor.close();
-        db.close();
-        return result > 0;        
-    }
-    
-    /**
-     * Returns a String array with all BSSIDs stored in the database.
-     * @return String[] of all recorded BSSIDs.
-     */
-    public String[] getAllBSSIDS(){
-        String selectQuery = "SELECT  * FROM " + TABLE_BSSIDS;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-        String[] bssidList = new String[cursor.getCount()];
-        int counter = 0;
-        // looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				bssidList[counter] = cursor.getString(0);
-				counter++;
-			} while (cursor.moveToNext());
-		}       
-        cursor.close();
-        db.close();
-        return bssidList;
-    }
-    
-    /**
-     * Gets the last recorded SSID to a given BSSID.
-     * @param bssid The BSSID to match against.
-     * @return A String of the last SSID or null if the BSSID is not in the database.
-     */
-    public String getSSID(String bssid){
-    	String selectQuery = "SELECT "+ KEY_SSID +" FROM " + TABLE_BSSIDS + " WHERE " + KEY_BSSID + " = " + "'" + bssid + "'";
-    	SQLiteDatabase db = this.getReadableDatabase();
-    	Cursor cursor = db.rawQuery(selectQuery, null);
-    	String ssid = null;
-    	if(cursor.moveToFirst()){
-    		ssid = cursor.getString(0);
-    	}
-        cursor.close();
-        db.close();
-        return ssid;
-    }
-    
-    /**
-     * Deletes all records from {@link #TABLE_RECORDS} with a specific BSSID.
-     * @param bssid The BSSID to match against.
-     */
-    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.
-     */
-    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();
-    }
-    
-    /**
-     *  Deletes all records from {@link #TABLE_RECORDS}.
-     */
-    public void clearData(){
-    	SQLiteDatabase db = this.getReadableDatabase();
-        db.delete(TABLE_RECORDS, null, null);
-        db.delete(TABLE_ATTACK_INFO, null, null);
-        db.close();
-    }
-    
-    public ArrayList<HashMap<String, Object>> getNetworkInformation(){
-        String selectQuery = "SELECT  * FROM " + TABLE_BSSIDS;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-    	
-        ArrayList<HashMap<String, Object>> networkInformation = new ArrayList<HashMap<String, Object>>();
-    	
-        // looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				HashMap<String, Object> values = new HashMap<String, Object>();
-				values.put(KEY_BSSID, cursor.getString(0));
-				values.put(KEY_SSID, cursor.getString(1));
-				values.put(KEY_LATITUDE, Double.parseDouble(cursor.getString(2)));
-				values.put(KEY_LONGITUDE, Double.parseDouble(cursor.getString(3)));
-				values.put(KEY_ACCURACY, Float.parseFloat(cursor.getString(4)));
-				values.put(KEY_TIME, cursor.getLong(5));
-				networkInformation.add(values);
-			} while (cursor.moveToNext());
-		}              
-		
-		cursor.close();        
-        db.close();        
-    	return networkInformation;
-    }
-    
-    public void updateNetworkInformation(HashMap<String, Object> networkInformation){ 
-        SQLiteDatabase db = this.getReadableDatabase();
-		String bssid = (String) networkInformation.get(KEY_BSSID);
-		String bssidQuery = "SELECT  * FROM " + TABLE_BSSIDS + " WHERE "  + KEY_BSSID + " = " + "'" + bssid + "'";
-        Cursor cursor = db.rawQuery(bssidQuery, null);
-        int result = cursor.getCount();
-        if( cursor != null && cursor.moveToFirst() && (result <= 0 || cursor.getLong(5) < (Long) networkInformation.get(KEY_TIME)));{
-        	ContentValues bssidValues = new ContentValues();
-    		bssidValues.put(KEY_BSSID, bssid);
-    		bssidValues.put(KEY_SSID, (String) networkInformation.get(KEY_SSID));
-    		bssidValues.put(KEY_LATITUDE, (double)(Double) networkInformation.get(KEY_LATITUDE));
-    		bssidValues.put(KEY_LONGITUDE, (double)(Double) networkInformation.get(KEY_LONGITUDE));
-    		bssidValues.put(KEY_ACCURACY, (float)(Float) networkInformation.get(KEY_ACCURACY));
-    		bssidValues.put(KEY_TIME, (Long) networkInformation.get(KEY_TIME));
-        	db.insertWithOnConflict(TABLE_BSSIDS, null, bssidValues, SQLiteDatabase.CONFLICT_REPLACE);
-        }    		
-        cursor.close();  
-        db.close();
-    }
-    
-    public void updateNetworkInformation(ArrayList<HashMap<String, Object>> networkInformation){ 
-    	Log.i("DatabaseHandler", "Starte updating");
-    	for(HashMap<String, Object> values : networkInformation){
-    		updateNetworkInformation(values);
-    	}	        
-    }
-}

+ 30 - 0
src/de/tudarmstadt/informatik/hostage/logging/LogResultReceiver.java

@@ -0,0 +1,30 @@
+package de.tudarmstadt.informatik.hostage.logging;
+
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.ResultReceiver;
+
+public class LogResultReceiver extends ResultReceiver {
+
+	private Receiver mReceiver;
+
+	public void setReceiver(Receiver receiver) {
+		mReceiver = receiver;
+	}
+
+	public LogResultReceiver(Handler handler) {
+		super(handler);
+	}
+
+	public interface Receiver {
+		public void onReceiveResult(int resultCode, Bundle resultData);
+	}
+
+	@Override
+	protected void onReceiveResult(int resultCode, Bundle resultData) {
+		if (mReceiver != null) {
+			mReceiver.onReceiveResult(resultCode, resultData);
+		}
+	}
+
+}

+ 311 - 80
src/de/tudarmstadt/informatik/hostage/logging/Logger.java

@@ -1,90 +1,321 @@
 package de.tudarmstadt.informatik.hostage.logging;
 
 import java.util.ArrayList;
+
+import android.app.IntentService;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.ResultReceiver;
+
 /**
- * Interface to define which functionality is needed for a Logger in this application.
- * @author Mihai Plasoianu 
- * @author Lars Pandikow
- *
+ * An {@link IntentService} subclass for handling asynchronous task requests in
+ * a service on a separate handler thread.
+ * 
+ * @author Mihai Plasoianu
  */
-public interface Logger {
-	/**
-	 * Write a single Record to the log.
-	 * @param record The Record that has to be added.
-	 */
-	void write(Record record);
-	
-	/**
-	 * Returns all saved Records.
-	 * @return ArrayList which contains all Records from the log.
-	 */
-	ArrayList<Record> getAllRecords();
-	/**
-	 * Returns a single Record as representative for each attack with an attack id higher then the given.
-	 * @param lastUploadedAttackId The threshold value for attack id's
-	 * @return ArrayList which contains one Record for each attack.
-	 */
-	ArrayList<Record> getRecordOfEachAttack(int lastUploadedAttackId);
-	/**
-	 * 
-	 * @param attack_id Attack id of the record
-	 * @return A Record with a specific attack id, or null if there is no Record with such an attack id.
-	 */
-	Record getRecordOfAttackId(long attack_id);
-	
-	/**
-	 * Determines the number of recorded attacks.
-	 * @return he Number of Attacks.
-	 */
-	int getAttackCount();	
-	/**
-	 * Returns the number of recorded attack for a specific protocol.
-	 * @param protocol The considered protocol.
-	 * @return The Number of recorded attacks per protocol.
-	 */
-	int getAttackPerProtokolCount(String protocol);
-	/**
-	 * Finds the smallest saved attack id.
-	 * @return The smallest saved attack id.
-	 */
-	long getSmallestAttackId();
-	/**
-	 * Finds the highest saved attack id.
-	 * @return The highest saved attack id.
-	 */
-	long getHighestAttackId();
-	
-	/**
-	 * Determines if an attack on a given protocol has already been recorded in a network with a specific BSSID.
-	 * @param protocol The considered protocol.
-	 * @param bssid The considered BSSID.
-	 * @return True if there has been a attack on a protocol in a network with the given BSSID, else returns false.
-	 */
-	boolean bssidSeen(String protocol, String bssid);
-	/**
-	 * Returns all BSSIDs in which an attack has been recorded.
-	 * @return String arrays with all recorded BSSIDs
-	 */
-	String[] getAllBSSIDS();
-	/**
-	 * Returns the last known SSID of a network with a specific BSSID.
-	 * @param bssid The considered BSSID.
-	 * @return String representation of the searched SSID, or null if there is no entry with the given BSSID
-	 */
-	String getSSID(String bssid);
-	
-	/**
-	 * Deletes all Records with a smaller time stamp than the given.
-	 * @param time The time stamp to compare with.
-	 */
-	void deleteByDate(long time);
+public class Logger extends IntentService {
+
+	private static final String ACTION_LOG = "de.tudarmstadt.informatik.hostage.action.LOG";
+	private static final String ACTION_GET_RECORD_ALL = "de.tudarmstadt.informatik.hostage.action.GET_RECORD_ALL";
+	private static final String ACTION_GET_RECORD_EACH = "de.tudarmstadt.informatik.hostage.action.GET_RECORD_EACH";
+	private static final String ACTION_GET_RECORD_ID = "de.tudarmstadt.informatik.hostage.action.GET_RECORD_ID";
+	private static final String ACTION_GET_COUNT_ALL = "de.tudarmstadt.informatik.hostage.action.GET_COUNT_ALL";
+	private static final String ACTION_GET_COUNT_PROTOCOL = "de.tudarmstadt.informatik.hostage.action.GET_COUNT_PROTOCOL";
+	private static final String ACTION_GET_ATTACK_MIN = "de.tudarmstadt.informatik.hostage.action.GET_ATTACK_MIN";
+	private static final String ACTION_GET_ATTACK_MAX = "de.tudarmstadt.informatik.hostage.action.GET_ATTACK_MAX";
+	private static final String ACTION_IS_BSSID_SEEN = "de.tudarmstadt.informatik.hostage.action.IS_BSSID_SEEN";
+	private static final String ACTION_GET_BSSID_ALL = "de.tudarmstadt.informatik.hostage.action.GET_BSSID_ALL";
+	private static final String ACTION_GET_SSID_BSSID = "de.tudarmstadt.informatik.hostage.action.GET_SSID_BSSID";
+	private static final String ACTION_CLEAR_DATE = "de.tudarmstadt.informatik.hostage.action.CLEAR_DATE";
+	private static final String ACTION_CLEAR_BSSID = "de.tudarmstadt.informatik.hostage.action.CLEAR_BSSID";
+	private static final String ACTION_CLEAR_ALL = "de.tudarmstadt.informatik.hostage.action.CLEAR_ALL";
+
+	private static final String EXTRA_RECORD = "de.tudarmstadt.informatik.hostage.extra.RECORD";
+	private static final String EXTRA_PROTOCOL = "de.tudarmstadt.informatik.hostage.extra.PROTOCOL";
+	private static final String EXTRA_BSSID = "de.tudarmstadt.informatik.hostage.extra.BSSID";
+	private static final String EXTRA_PRIMITIVE = "de.tudarmstadt.informatik.hostage.extra.PRIMITIVE";
+
+	private static final String RESULT_RECEIVER = "de.tudarmstadt.informatik.hostage.RESULT_RECEIVER";
+
+	public static void log(Context context, Record record) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_LOG);
+		intent.putExtra(EXTRA_RECORD, record);
+		context.startService(intent);
+	}
+
+	public static void getAllRecords(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_GET_RECORD_ALL);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getRecordOfEachAttack(Context context,
+			int lastUploadedAttackId, ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_GET_RECORD_EACH);
+		intent.putExtra(EXTRA_PRIMITIVE, lastUploadedAttackId);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getRecordOfAttackId(Context context, long attack_id,
+			ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_GET_RECORD_ID);
+		intent.putExtra(EXTRA_PRIMITIVE, attack_id);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getAttackCount(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_GET_COUNT_ALL);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getAttackPerProtocolCount(Context context,
+			String protocol, ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_GET_COUNT_PROTOCOL);
+		intent.putExtra(EXTRA_PROTOCOL, protocol);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getMinAttackId(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_GET_ATTACK_MIN);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getMaxAttackId(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_GET_ATTACK_MAX);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void isBssidSeen(Context context, String protocol,
+			String bssid, ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_IS_BSSID_SEEN);
+		intent.putExtra(EXTRA_PROTOCOL, protocol);
+		intent.putExtra(EXTRA_BSSID, bssid);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getAllBssids(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_GET_BSSID_ALL);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getSsid(Context context, String bssid,
+			ResultReceiver receiver) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_GET_SSID_BSSID);
+		intent.putExtra(EXTRA_BSSID, bssid);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void deleteByDate(Context context, long time) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_CLEAR_DATE);
+		intent.putExtra(EXTRA_PRIMITIVE, time);
+		context.startService(intent);
+	}
+
+	public static void deleteByBssid(Context context, String bssid) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_CLEAR_BSSID);
+		intent.putExtra(EXTRA_BSSID, bssid);
+		context.startService(intent);
+	}
+
+	public static void deleteAll(Context context) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_CLEAR_ALL);
+		context.startService(intent);
+	}
+
+	private UglyDbHelper mDbHelper;
+
+	public Logger() {
+		super("Logger");
+	}
+
+	@Override
+	public void onCreate() {
+		super.onCreate();
+		mDbHelper = new UglyDbHelper(getApplicationContext());
+	}
+
+	@Override
+	protected void onHandleIntent(Intent intent) {
+		if (intent != null) {
+			final String action = intent.getAction();
+			if (ACTION_LOG.equals(action)) {
+				final Record record = intent.getParcelableExtra(EXTRA_RECORD);
+				handleActionLog(record);
+			} else if (ACTION_GET_RECORD_ALL.equals(action)) {
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				ArrayList<Record> r = handleActionGetAllRecords();
+				Bundle result = new Bundle();
+				result.putParcelableArrayList("result", r);
+				receiver.send(0, result);
+			} else if (ACTION_GET_RECORD_EACH.equals(action)) {
+				final int lastUploadedAttackId = intent.getIntExtra(
+						EXTRA_PRIMITIVE, -1);
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				ArrayList<Record> r = handleActionGetRecordOfEachAttack(lastUploadedAttackId);
+				Bundle result = new Bundle();
+				result.putParcelableArrayList("result", r);
+				receiver.send(0, result);
+			} else if (ACTION_GET_RECORD_ID.equals(action)) {
+				final int attack_id = intent.getIntExtra(EXTRA_PRIMITIVE, -1);
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				Record r = handleActionGetRecordOfAttackId(attack_id);
+				Bundle result = new Bundle();
+				result.putParcelable("result", r);
+				receiver.send(0, result);
+			} else if (ACTION_GET_COUNT_ALL.equals(action)) {
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				int r = handleActionGetAttackCount();
+				Bundle result = new Bundle();
+				result.putInt("result", r);
+				receiver.send(0, result);
+			} else if (ACTION_GET_COUNT_PROTOCOL.equals(action)) {
+				final String protocol = intent.getStringExtra(EXTRA_PROTOCOL);
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				int r = handleActionGetAttackPerProtocolCount(protocol);
+				Bundle result = new Bundle();
+				result.putInt("result", r);
+				receiver.send(0, result);
+			} else if (ACTION_GET_ATTACK_MIN.equals(action)) {
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				long r = handleActionGetMinAttackId();
+				Bundle result = new Bundle();
+				result.putLong("result", r);
+				receiver.send(0, result);
+				handleActionGetMinAttackId();
+			} else if (ACTION_GET_ATTACK_MAX.equals(action)) {
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				long r = handleActionGetMaxAttackId();
+				Bundle result = new Bundle();
+				result.putLong("result", r);
+				receiver.send(0, result);
+			} else if (ACTION_IS_BSSID_SEEN.equals(action)) {
+				final String protocol = intent.getStringExtra(EXTRA_PROTOCOL);
+				final String bssid = intent.getStringExtra(EXTRA_BSSID);
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				boolean r = handleActionBssidSeen(protocol, bssid);
+				Bundle result = new Bundle();
+				result.putBoolean("result", r);
+				receiver.send(0, result);
+			} else if (ACTION_GET_BSSID_ALL.equals(action)) {
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				String[] r = handleActionGetAllBssids();
+				Bundle result = new Bundle();
+				result.putStringArray("result", r);
+				receiver.send(0, result);
+			} else if (ACTION_GET_SSID_BSSID.equals(action)) {
+				final String bssid = intent.getStringExtra(EXTRA_BSSID);
+				ResultReceiver receiver = intent
+						.getParcelableExtra(RESULT_RECEIVER);
+				String r = handleActionGetSsid(bssid);
+				Bundle result = new Bundle();
+				result.putString("result", r);
+				receiver.send(0, result);
+			} else if (ACTION_CLEAR_DATE.equals(action)) {
+				final long time = intent.getLongExtra(EXTRA_PRIMITIVE, -1L);
+				handleActionDeleteByDate(time);
+			} else if (ACTION_CLEAR_BSSID.equals(action)) {
+				final String bssid = intent.getStringExtra(EXTRA_BSSID);
+				handleActionDeleteByBssid(bssid);
+			} else if (ACTION_CLEAR_ALL.equals(action)) {
+				handleActionDeleteAll();
+			}
+		}
+	}
+
 	/**
-	 * Deletes all Record which contain the given BSSID.
-	 * @param bssid The BSSID to compare with.
+	 * Log a record.
 	 */
-	void deleteByBSSID(String bssid);
+	private void handleActionLog(Record record) {
+		mDbHelper.addRecord(record);
+	}
+
+	private ArrayList<Record> handleActionGetAllRecords() {
+		return mDbHelper.getAllRecords();
+	}
+
+	private ArrayList<Record> handleActionGetRecordOfEachAttack(
+			int lastUploadedAttackId) {
+		return mDbHelper.getRecordOfEachAttack(lastUploadedAttackId);
+	}
+
+	private Record handleActionGetRecordOfAttackId(long attack_id) {
+		return mDbHelper.getRecordOfAttackId(attack_id);
+	}
+
+	private int handleActionGetAttackCount() {
+		return mDbHelper.getAttackCount();
+	}
+
+	private int handleActionGetAttackPerProtocolCount(String protocol) {
+		return mDbHelper.getAttackPerProtocolCount(protocol);
+	}
+
+	private long handleActionGetMinAttackId() {
+		return mDbHelper.getSmallestAttackId();
+	}
+
+	private long handleActionGetMaxAttackId() {
+		return mDbHelper.getHighestAttackId();
+	}
+
+	private boolean handleActionBssidSeen(String protocol, String bssid) {
+		return mDbHelper.bssidSeen(protocol, bssid);
+	}
+
+	private String[] handleActionGetAllBssids() {
+		return mDbHelper.getAllBSSIDS();
+	}
+
+	private String handleActionGetSsid(String bssid) {
+		return mDbHelper.getSSID(bssid);
+	}
+
+	private void handleActionDeleteByDate(long time) {
+		mDbHelper.deleteByDate(time);
+	}
+
+	private void handleActionDeleteByBssid(String bssid) {
+		mDbHelper.deleteByBSSID(bssid);
+	}
+
 	/**
-	 * Resets complete log file.
+	 * Delete all records.
 	 */
-	void clearData();
+	private void handleActionDeleteAll() {
+		mDbHelper.clearData();
+	}
+
 }

+ 162 - 183
src/de/tudarmstadt/informatik/hostage/logging/Record.java

@@ -1,311 +1,290 @@
 package de.tudarmstadt.informatik.hostage.logging;
 
-import java.io.Serializable;
-import java.net.InetAddress;
-
-import de.tudarmstadt.informatik.hostage.format.LogViewFormatter;
+import android.os.Parcel;
+import android.os.Parcelable;
+import de.tudarmstadt.informatik.hostage.logging.formatter.Formatter;
 
 /**
  * This class defines the attributes of a record.<br>
- * A Record is a single message exchanged between the application and an attacker.<br>
- * The class has no own functionality except for getter and setter methods.
- * To change the logging mechanism you have to to change the logger in {@link de.tudarmstadt.informatik.hostage.HoneyService HoneyService} and 
+ * A Record is a single message exchanged between the application and an
+ * attacker.<br>
+ * The class has no own functionality except for getter and setter methods. To
+ * change the logging mechanism you have to to change the logger in
+ * {@link de.tudarmstadt.informatik.hostage.HoneyService HoneyService} and
  * {@link de.tudarmstadt.informatik.hostage.ui.ViewLog ViewLog}
- * @author Mihai Plasoianu 
+ * 
+ * @author Mihai Plasoianu
  * @author Lars Pandikow
  */
-public class Record implements Serializable {
-
-	private static final long serialVersionUID = 1L;
+public class Record implements Parcelable {
 
 	public static enum TYPE {
 		SEND, RECEIVE
 	};
 
+	// attack
 	private int id;
 	private long attack_id;
+	private long timestamp;
 	private String protocol;
 	private TYPE type;
-	private long timestamp;
-	private String externalIP;
-	private InetAddress localIP;
+	private String packet;
+
+	// network
+	private String localIP;
+	private String localHost;
 	private int localPort;
-	private InetAddress remoteIP;
+	private String remoteIP;
+	private String remoteHost;
 	private int remotePort;
-	private String BSSID;
-	private String SSID;
+	private String externalIP;
+	private String bssid;
+	private String ssid;
+
+	// location
+	private long timestampLocation;
 	private double latitude;
 	private double longitude;
 	private float accuracy;
-	private long timestampLocation;
-	private String packet;	
 
+	@Override
+	public int describeContents() {
+		return 0;
+	}
+
+	@Override
+	public void writeToParcel(Parcel dest, int flags) {
+		// attack
+		dest.writeInt(id);
+		dest.writeLong(attack_id);
+		dest.writeLong(timestamp);
+		dest.writeString(protocol);
+		dest.writeString(type.name());
+		dest.writeString(packet);
+
+		// network
+		dest.writeString(localIP);
+		dest.writeString(localHost);
+		dest.writeInt(localPort);
+		dest.writeString(remoteIP);
+		dest.writeString(remoteHost);
+		dest.writeInt(remotePort);
+		dest.writeString(externalIP);
+		dest.writeString(bssid);
+		dest.writeString(ssid);
+
+		// location
+		dest.writeLong(timestampLocation);
+		dest.writeDouble(latitude);
+		dest.writeDouble(longitude);
+		dest.writeFloat(accuracy);
+	}
+
+	public static final Parcelable.Creator<Record> CREATOR = new Parcelable.Creator<Record>() {
+
+		@Override
+		public Record createFromParcel(Parcel source) {
+			return new Record(source);
+		}
 
+		@Override
+		public Record[] newArray(int size) {
+			return new Record[size];
+		}
+	};
+
+	public Record() {
+	}
+
+	public Record(Parcel source) {
+		// attack
+		this.id = source.readInt();
+		this.attack_id = source.readLong();
+		this.timestamp = source.readLong();
+		this.protocol = source.readString();
+		this.type = TYPE.valueOf(source.readString());
+		this.packet = source.readString();
+
+		// network
+		this.localIP = source.readString();
+		this.localHost = source.readString();
+		this.localPort = source.readInt();
+		this.remoteIP = source.readString();
+		this.remoteHost = source.readString();
+		this.remotePort = source.readInt();
+		this.externalIP = source.readString();
+		this.bssid = source.readString();
+		this.ssid = source.readString();
+
+		// location
+		this.timestampLocation = source.readLong();
+		this.latitude = source.readDouble();
+		this.longitude = source.readDouble();
+		this.accuracy = source.readFloat();
+	}
 
-	/**
-	 * @return the id
-	 */
 	public int getId() {
 		return id;
 	}
 
-	/**
-	 * @param id the id to set
-	 */
 	public void setId(int id) {
 		this.id = id;
 	}
 
-	/**
-	 * @return the attack_id
-	 */
 	public long getAttack_id() {
 		return attack_id;
 	}
 
-	/**
-	 * @param attack_id the attack_id to set
-	 */
 	public void setAttack_id(long attack_id) {
 		this.attack_id = attack_id;
 	}
 
-	/**
-	 * @return the protocol
-	 */
+	public long getTimestamp() {
+		return timestamp;
+	}
+
+	public void setTimestamp(long timestamp) {
+		this.timestamp = timestamp;
+	}
+
 	public String getProtocol() {
 		return protocol;
 	}