Browse Source

Merge branch 'master' of https://git.tk.informatik.tu-darmstadt.de/scm-ssi-student-hostagev2

Conflicts:
	src/de/tudarmstadt/informatik/hostage/ui2/fragment/RecordOverviewFragment.java
	src/de/tudarmstadt/informatik/hostage/ui2/fragment/StatisticsFragment.java
Julien Clauter 10 years ago
parent
commit
2c9296d58f
91 changed files with 6497 additions and 4601 deletions
  1. 3 0
      .classpath
  2. 3 3
      .gitignore
  3. 74 76
      AndroidManifest.xml
  4. BIN
      assets/p
  5. 3 3
      native/Makefile
  6. 35 26
      native/bind.c
  7. BIN
      native/p
  8. BIN
      native/p.o
  9. 1 0
      project.properties
  10. 0 0
      res/drawable-hdpi/ic_action_done.png
  11. BIN
      res/drawable-hdpi/ic_action_refresh.png
  12. 0 0
      res/drawable-mdpi/ic_action_done.png
  13. BIN
      res/drawable-mdpi/ic_action_refresh.png
  14. 0 0
      res/drawable-xhdpi/ic_action_done.png
  15. BIN
      res/drawable-xhdpi/ic_action_refresh.png
  16. BIN
      res/drawable-xxhdpi/ic_action_refresh.png
  17. 0 0
      res/drawable-xxxhdpi/ic_launcher.png
  18. 0 0
      res/drawable-xxxhdpi/ic_service_green.png
  19. 0 0
      res/drawable-xxxhdpi/ic_service_red.png
  20. 0 0
      res/drawable-xxxhdpi/ic_service_yellow.png
  21. BIN
      res/drawable/swipe_icon.png
  22. 18 0
      res/layout/activity_bluetooth.xml
  23. 3 3
      res/layout/fragment_home.xml
  24. 7 0
      res/layout/list_view_bluetooth_devices.xml
  25. 15 7
      res/layout/profile_manager_list_item.xml
  26. 36 0
      res/layout/profile_manager_list_item_help.xml
  27. 8 0
      res/menu/home_actions.xml
  28. 2 0
      res/values/protocols.xml
  29. 1 1
      res/values/strings.xml
  30. 3 0
      res/values/strings_gui.xml
  31. 23 46
      src/de/tudarmstadt/informatik/hostage/Handler.java
  32. 67 113
      src/de/tudarmstadt/informatik/hostage/Hostage.java
  33. 27 34
      src/de/tudarmstadt/informatik/hostage/Listener.java
  34. 8 0
      src/de/tudarmstadt/informatik/hostage/commons/HelperUtils.java
  35. 305 0
      src/de/tudarmstadt/informatik/hostage/deprecated/OldLogger.java
  36. 970 1022
      src/de/tudarmstadt/informatik/hostage/deprecated/UglyDbHelper.java
  37. 2 2
      src/de/tudarmstadt/informatik/hostage/location/MyLocationManager.java
  38. 0 30
      src/de/tudarmstadt/informatik/hostage/logging/LogResultReceiver.java
  39. 3 276
      src/de/tudarmstadt/informatik/hostage/logging/Logger.java
  40. 0 34
      src/de/tudarmstadt/informatik/hostage/logging/Record.java
  41. 1 3
      src/de/tudarmstadt/informatik/hostage/logging/formatter/TraCINgFormatter.java
  42. 12 0
      src/de/tudarmstadt/informatik/hostage/model/JSONSerializable.java
  43. 57 5
      src/de/tudarmstadt/informatik/hostage/model/Profile.java
  44. 0 13
      src/de/tudarmstadt/informatik/hostage/model/ProfilesHolder.java
  45. 47 0
      src/de/tudarmstadt/informatik/hostage/net/MyDatagramSocketFactory.java
  46. 14 50
      src/de/tudarmstadt/informatik/hostage/net/MyServerSocketFactory.java
  47. 4 3
      src/de/tudarmstadt/informatik/hostage/nio/Reader.java
  48. 0 1
      src/de/tudarmstadt/informatik/hostage/nio/Writer.java
  49. 44 0
      src/de/tudarmstadt/informatik/hostage/persistence/HostageDBContract.java
  50. 626 0
      src/de/tudarmstadt/informatik/hostage/persistence/HostageDBOpenHelper.java
  51. 214 46
      src/de/tudarmstadt/informatik/hostage/persistence/ProfileManager.java
  52. 11 14
      src/de/tudarmstadt/informatik/hostage/protocol/FTP.java
  53. 2 2
      src/de/tudarmstadt/informatik/hostage/protocol/GHOST.java
  54. 36 12
      src/de/tudarmstadt/informatik/hostage/protocol/HTTP.java
  55. 2 2
      src/de/tudarmstadt/informatik/hostage/protocol/HTTPS.java
  56. 4 4
      src/de/tudarmstadt/informatik/hostage/protocol/MySQL.java
  57. 124 5
      src/de/tudarmstadt/informatik/hostage/protocol/SIP.java
  58. 60 721
      src/de/tudarmstadt/informatik/hostage/protocol/SMB.java
  59. 21 27
      src/de/tudarmstadt/informatik/hostage/protocol/SSH.java
  60. 68 26
      src/de/tudarmstadt/informatik/hostage/protocol/TELNET.java
  61. 51 0
      src/de/tudarmstadt/informatik/hostage/protocol/smbutils/NBDS.java
  62. 12 0
      src/de/tudarmstadt/informatik/hostage/protocol/smbutils/NBDSType.java
  63. 190 0
      src/de/tudarmstadt/informatik/hostage/protocol/smbutils/NBNS.java
  64. 10 0
      src/de/tudarmstadt/informatik/hostage/protocol/smbutils/NBNSService.java
  65. 8 0
      src/de/tudarmstadt/informatik/hostage/protocol/smbutils/NBNSType.java
  66. 229 0
      src/de/tudarmstadt/informatik/hostage/protocol/smbutils/NMB.java
  67. 58 0
      src/de/tudarmstadt/informatik/hostage/protocol/smbutils/NMBStringCoder.java
  68. 802 0
      src/de/tudarmstadt/informatik/hostage/protocol/smbutils/SMBPacket.java
  69. 233 0
      src/de/tudarmstadt/informatik/hostage/provider/HostageContentProvider.java
  70. 368 305
      src/de/tudarmstadt/informatik/hostage/sync/BluetoothSync.java
  71. 169 185
      src/de/tudarmstadt/informatik/hostage/sync/NFCSync.java
  72. 61 0
      src/de/tudarmstadt/informatik/hostage/system/Device.java
  73. 0 68
      src/de/tudarmstadt/informatik/hostage/system/P.java
  74. 80 0
      src/de/tudarmstadt/informatik/hostage/system/PrivilegedPort.java
  75. 177 159
      src/de/tudarmstadt/informatik/hostage/ui/LogFilter.java
  76. 338 419
      src/de/tudarmstadt/informatik/hostage/ui/MainActivity.java
  77. 95 98
      src/de/tudarmstadt/informatik/hostage/ui/PlayGroundActivity.java
  78. 2 2
      src/de/tudarmstadt/informatik/hostage/ui/ViewLogTable.java
  79. 126 163
      src/de/tudarmstadt/informatik/hostage/ui2/activity/MainActivity.java
  80. 118 114
      src/de/tudarmstadt/informatik/hostage/ui2/adapter/ProfileManagerListAdapter.java
  81. 9 12
      src/de/tudarmstadt/informatik/hostage/ui2/adapter/ServicesListAdapter.java
  82. 230 215
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/HomeFragment.java
  83. 1 3
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/ProfileEditFragment.java
  84. 17 1
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/ProfileManagerFragment.java
  85. 108 109
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/RecordDetailFragment.java
  86. 10 14
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/ServicesFragment.java
  87. 4 6
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/SettingsFragment.java
  88. 8 7
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/ThreatMapFragment.java
  89. 0 60
      src/de/tudarmstadt/informatik/hostage/ui2/listeners/OnSwipeTouchListener.java
  90. 0 41
      src/de/tudarmstadt/informatik/hostage/ui2/preference/ImageSelectPreference.java
  91. 19 10
      src/de/tudarmstadt/informatik/hostage/wrapper/Packet.java

+ 3 - 0
.classpath

@@ -6,5 +6,8 @@
 	<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
 	<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
 	<classpathentry kind="lib" path="libs/sshlib-v1.1.jar"/>
+	<classpathentry kind="lib" path="libs/android-support-v4.jar"/>
+	<classpathentry kind="lib" path="libs/nineoldandroids-2.4.0.jar"/>
+	<classpathentry kind="lib" path="libs/swipelistview-1.0.jar"/>
 	<classpathentry kind="output" path="bin/classes"/>
 </classpath>

+ 3 - 3
.gitignore

@@ -24,10 +24,10 @@ proguard/
 *.iws
 .idea/
 
-#Ignore some folders
+# Ignore some folders
 target/
 build/
 .gradle/
 gen-external-apklibs/
-native/p
-native/p.o
+native/build
+native/build.o

+ 74 - 76
AndroidManifest.xml

@@ -1,55 +1,51 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-		  package="de.tudarmstadt.informatik.hostage"
-		  android:versionCode="1"
-		  android:versionName="1.0">
+    package="de.tudarmstadt.informatik.hostage"
+    android:versionCode="1"
+    android:versionName="1.0" >
 
-	<uses-sdk
-			android:minSdkVersion="14"
-			android:targetSdkVersion="19"/>
+    <uses-sdk
+        android:minSdkVersion="14"
+        android:targetSdkVersion="19" />
 
-	<uses-permission android:name="android.permission.VIBRATE"/>
-	<uses-permission android:name="android.permission.INTERNET"/>
-	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
-	<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
-	<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
-	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
-	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
-	<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
-
-	<!-- Tell the system this app requires OpenGL ES 2.0. -->
-	<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
-	<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-permission android:name="android.permission.VIBRATE" />
+    <uses-permission android:name="android.permission.INTERNET" />
+    <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_COARSE_LOCATION" />
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
+	<uses-permission android:name="android.permission.BLUETOOTH" />
 
 	<uses-feature
-			android:name="android.hardware.nfc"
-			android:required="false"/>
+        android:name="android.hardware.nfc"
+        android:required="false" />
+
+    <application
+        android:allowBackup="true"
+        android:allowClearUserData="true"
+        android:hardwareAccelerated="true"
+        android:icon="@drawable/ic_launcher"
+        android:installLocation="preferExternal"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme"
+        android:vmSafeMode="true" >
+        <meta-data
+            android:name="com.google.android.gms.version"
+            android:value="14" />
+        <meta-data
+            android:name="com.google.android.maps.v2.API_KEY"
+            android:value="AIzaSyCqh4bb4aMzvDcpDfiqHyXoAWFTQ6iNxe8" />
+
+        <activity
+            android:name="de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity"
+            android:configChanges="keyboardHidden|orientation|screenSize"
+            android:label="@string/app_name"
+            android:screenOrientation="portrait" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
 
-	<application
-			android:allowBackup="true"
-			android:icon="@drawable/ic_launcher"
-			android:label="@string/app_name"
-			android:theme="@style/AppTheme"
-			android:installLocation="preferExternal"
-			android:vmSafeMode="true"
-			android:allowClearUserData="true"
-			android:hardwareAccelerated="true">
-		<meta-data
-				android:name="com.google.android.gms.version"
-				android:value="14"/>
-		<meta-data
-				android:name="com.google.android.maps.v2.API_KEY"
-				android:value="AIzaSyCqh4bb4aMzvDcpDfiqHyXoAWFTQ6iNxe8"/>
-		<activity
-				android:name="de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity"
-				android:configChanges="keyboardHidden|orientation|screenSize"
-				android:label="@string/app_name"
-				android:screenOrientation="portrait">
-			<intent-filter>
-				<action android:name="android.intent.action.MAIN"/>
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
@@ -66,10 +62,10 @@
             android:name="de.tudarmstadt.informatik.hostage.ui.ViewLogTable"
             android:label="@string/database" >
         </activity>
-	    <activity
-			    android:name=".ui2.activity.ProfileEditActivity"
-			    android:label="Edit Profile" >
-	    </activity>
+        <activity
+            android:name=".ui2.activity.ProfileEditActivity"
+            android:label="Edit Profile" >
+        </activity>
         <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.SettingsActivity"
             android:label="@string/settings" >
@@ -82,36 +78,38 @@
             android:name="de.tudarmstadt.informatik.hostage.ui.PlayGroundActivity"
             android:label="@string/gui_playground" >
         </activity>
+        <activity
+            android:name="de.tudarmstadt.informatik.hostage.sync.BluetoothSync"
+            android:label="@string/gui_bluetooth"
+            android:theme="@android:style/Theme.Dialog" >
+        </activity>
         <activity
             android:name="de.tudarmstadt.informatik.hostage.sync.NFCSync"
-            android:label="@string/gui_playground" >
+            android:label="@string/gui_nfc"
+            android:theme="@android:style/Theme.Dialog" >
             <intent-filter>
                 <action android:name="android.nfc.action.NDEF_DISCOVERED" />
-				<category android:name="android.intent.category.LAUNCHER"/>
-			</intent-filter>
-		</activity>
-		<!--
-		<activity
-			android:name="de.tudarmstadt.informatik.hostage.ui.MainActivity"
-			android:configChanges="keyboardHidden|orientation|screenSize"
-			android:label="@string/app_name" >
-		</activity>
-		<activity
-			android:name="de.tudarmstadt.informatik.hostage.ui.ViewLog"
-			android:label="@string/statistics" >
-		</activity>
-		<activity
-			android:name="de.tudarmstadt.informatik.hostage.ui.ViewLogTable"
-			android:label="@string/database" >
-		</activity>
-		-->
 
-		<service android:name="de.tudarmstadt.informatik.hostage.HoneyService">
-		</service>
-		<service
-				android:name="de.tudarmstadt.informatik.hostage.logging.Logger"
-				android:exported="false">
-		</service>
-	</application>
+                <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.Hostage"
+            android:exported="false" >
+        </service>
+        <service
+            android:name="de.tudarmstadt.informatik.hostage.logging.Logger"
+            android:exported="false" >
+        </service>
+
+        <provider
+            android:name="de.tudarmstadt.informatik.hostage.provider.HostageContentProvider"
+            android:authorities="de.tudarmstadt.informatik.hostage.provider"
+            android:exported="false" >
+        </provider>
+    </application>
 
-</manifest>
+</manifest>

BIN
assets/p


+ 3 - 3
native/Makefile

@@ -3,9 +3,9 @@ x86: CC = i686-linux-android-gcc
 mips: CC = mipsel-linux-android-gcc
 CFLAGS = -Wall -g
 LDFLAGS = -llog
-SRC = p.c
+SRC = bind.c
 OBJ = $(SRC:.c=.o)
-EXE = p
+EXE = bind
 
 arm x86 mips: $(SRC) $(EXE)
 
@@ -19,4 +19,4 @@ clean:
 	rm -f *.o $(EXE)
 
 install:
-	adb push p /data/local
+	adb push bind /data/local

+ 35 - 26
native/p.c → native/bind.c

@@ -1,6 +1,6 @@
-#include <android/log.h>
 #include <errno.h>
 #include <netinet/in.h>
+#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/socket.h>
@@ -9,20 +9,19 @@
 #include <sys/un.h>
 #include <unistd.h>
 
-#define  LOG_TAG "hostage: p"
-#define  LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
-#define  LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
-
 #define CONTROLLEN CMSG_LEN(sizeof(int))
 
 #define UNIX_PATH "hostage"
 
+#define TCP "TCP"
+#define UDP "UDP"
+
 int ipc_sock() {
 	int fd;
 	struct sockaddr_un addr;
 
 	if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
-		LOGE("Unable to create local socket: %d", errno);
+		perror("Unable to create local socket");
 		return -1;
 	}
 
@@ -30,22 +29,21 @@ int ipc_sock() {
 	addr.sun_family = AF_UNIX;
 	strncpy(&addr.sun_path[1], UNIX_PATH, strlen(UNIX_PATH));
 
-	if (connect(fd, (struct sockaddr*) &addr,
-			sizeof(sa_family_t) + strlen(UNIX_PATH) + 1) == -1) {
-		LOGE("Unable to connect local socket: %d", errno);
+	if (connect(fd, (struct sockaddr*) &addr, sizeof(sa_family_t) + strlen(UNIX_PATH) + 1) == -1) {
+		perror("Unable to connect local socket");
 		return -1;
 	}
 
 	return fd;
 }
 
-int net_sock(int port) {
+int net_sock(int type, int port) {
 	int fd;
-	int reuse = 1;
+	int reuseaddr = 1;
 	struct sockaddr_in addr;
 
-	if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
-		LOGE("Unable to create net socket: %d", errno);
+	if ((fd = socket(AF_INET, (type == 1 ? SOCK_STREAM : SOCK_DGRAM), (type == 1 ? IPPROTO_IP : IPPROTO_UDP))) == -1) {
+		perror("Unable to create net socket");
 		return -1;
 	}
 
@@ -54,19 +52,21 @@ int net_sock(int port) {
 	addr.sin_addr.s_addr = INADDR_ANY;
 	addr.sin_port = htons(port);
 
-	if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) == -1) {
-		LOGE("Unable to set socket options: %d", errno);
+	if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr)) == -1) {
+		perror("Unable to set socket options");
 		return -1;
 	}
 
 	if (bind(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
-		LOGE("Unable to bind net socket: %d", errno);
+		perror("Unable to bind net socket");
 		return -1;
 	}
 
-	if (listen(fd, 5) == -1) {
-		LOGE("Unable to listen net socket: %d", errno);
-		return -1;
+	if (type == 1) {
+		if (listen(fd, 5) == -1) {
+			perror("Unable to listen net socket");
+			return -1;
+		}
 	}
 
 	return fd;
@@ -95,21 +95,30 @@ int send_fd(int fd, int fd_to_send) {
 	*(int *) CMSG_DATA(cmptr) = fd_to_send;
 
 	if (sendmsg(fd, &msg, 0) == -1) {
-		LOGE("sendmsg failed: %d", errno);
+		perror("sendmsg failed");
 	}
 
 	return 0;
 }
 
 int main(int argc, char *argv[]) {
+	int type;
 	int port;
 	int ipc_fd, net_fd;
 
-	if (argc < 2) {
+	if (argc < 3) {
+		exit(EXIT_FAILURE);
+	}
+
+	if (strncmp(argv[1], TCP, 3) == 0) {
+		type = 1;
+	} else if (strncmp(argv[1], UDP, 3) == 0) {
+		type = 0;
+	} else {
 		exit(EXIT_FAILURE);
 	}
 
-	if ((port = atoi(argv[1])) < 1 || (port = atoi(argv[1])) > 65535) {
+	if ((port = atoi(argv[2])) < 1 || (port = atoi(argv[2])) > 65535) {
 		exit(EXIT_FAILURE);
 	}
 
@@ -117,18 +126,18 @@ int main(int argc, char *argv[]) {
 		close(ipc_fd);
 		exit(EXIT_FAILURE);
 	}
-	LOGD("ipc_fd: %d", ipc_fd);
+	printf("ipc_fd: %d\n", ipc_fd);
 
-	if ((net_fd = net_sock(port)) == -1) {
+	if ((net_fd = net_sock(type, port)) == -1) {
 		close(ipc_fd);
 		close(net_fd);
 		exit(EXIT_FAILURE);
 	}
-	LOGD("net_fd: %d", net_fd);
+	printf("net_fd: %d\n", net_fd);
 
 	int status;
 	status = send_fd(ipc_fd, net_fd);
-	LOGD("send_fd: %d", status);
+	printf("send_fd: %d\n", status);
 
 	close(ipc_fd);
 	close(net_fd);

BIN
native/p


BIN
native/p.o


+ 1 - 0
project.properties

@@ -15,3 +15,4 @@ target=android-19
 android.library=false
 
 
+android.library.reference.1=../../development/Android/HosTaGe/google-play-services_lib

+ 0 - 0
res/drawable-hdpi/ic_action_done.png


BIN
res/drawable-hdpi/ic_action_refresh.png


+ 0 - 0
res/drawable-mdpi/ic_action_done.png


BIN
res/drawable-mdpi/ic_action_refresh.png


+ 0 - 0
res/drawable-xhdpi/ic_action_done.png


BIN
res/drawable-xhdpi/ic_action_refresh.png


BIN
res/drawable-xxhdpi/ic_action_refresh.png


+ 0 - 0
res/drawable-xxxhdpi/ic_launcher.png


+ 0 - 0
res/drawable-xxxhdpi/ic_service_green.png


+ 0 - 0
res/drawable-xxxhdpi/ic_service_red.png


+ 0 - 0
res/drawable-xxxhdpi/ic_service_yellow.png


BIN
res/drawable/swipe_icon.png


+ 18 - 0
res/layout/activity_bluetooth.xml

@@ -0,0 +1,18 @@
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content"
+    android:orientation="vertical"
+    android:paddingBottom="@dimen/activity_vertical_margin"
+    android:paddingLeft="@dimen/activity_horizontal_margin"
+    android:paddingRight="@dimen/activity_horizontal_margin"
+    android:paddingTop="@dimen/activity_vertical_margin"
+    android:id="@+id/bluetoothLayout" >
+
+    <TextView
+        android:id="@+id/bluetoothInfoText"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        />
+
+</LinearLayout>

+ 3 - 3
res/layout/fragment_home.xml

@@ -91,10 +91,10 @@
                 android:id="@+id/home_button_connection_info"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
-                android:layout_alignParentEnd="true"
+                android:src="@android:drawable/ic_menu_info_details"
+                android:layout_alignTop="@+id/home_text_name"
                 android:layout_alignParentRight="true"
-                android:layout_alignParentTop="true"
-                android:src="@android:drawable/ic_menu_info_details" />
+                android:layout_alignParentEnd="true"/>
         </RelativeLayout>
 
         <TextView

+ 7 - 0
res/layout/list_view_bluetooth_devices.xml

@@ -0,0 +1,7 @@
+<TextView xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@android:id/text1"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content"
+    android:textAppearance="?android:attr/textAppearanceSmall"
+    android:gravity="center_vertical"
+/>

+ 15 - 7
res/layout/profile_manager_list_item.xml

@@ -1,8 +1,14 @@
 <?xml version="1.0" encoding="utf-8"?>
 
-<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
-              android:layout_width="wrap_content"
-              android:layout_height="wrap_content">
+	<FrameLayout
+			xmlns:android="http://schemas.android.com/apk/res/android"
+			  android:layout_width="wrap_content"
+              android:layout_height="wrap_content"
+              android:layout_alignParentLeft="true"
+              android:layout_marginLeft="0dp"
+              android:layout_alignParentTop="true"
+              android:layout_marginTop="0dp"
+			>
 
 	<RelativeLayout
         android:id="@+id/swipelist_backview"
@@ -55,7 +61,7 @@
 	<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 	                android:id="@+id/swipelist_frontview"
 	                android:layout_width="match_parent"
-	                android:layout_height="wrap_content"
+	                android:layout_height="match_parent"
 	                android:padding="5dp"
 	                android:baselineAligned="false"
 	                android:background="@drawable/panel_bg_selector">
@@ -117,13 +123,12 @@
 				android:orientation="horizontal"
 				android:layout_width="fill_parent"
 				android:layout_height="fill_parent"
-				android:layout_alignParentBottom="true"
 				android:layout_below="@+id/profile_manager_item_text"
 				android:padding="10dp"
 				f:horizontalSpacing="10dip"
 				f:verticalSpacing="10dip"
 				android:layout_alignParentRight="true"
-				android:layout_alignParentEnd="true"
+				android:layout_alignParentEnd="false"
 				android:id="@+id/badges_container">
 			<TextView
 					android:layout_width="wrap_content"
@@ -163,5 +168,8 @@
 			          android:textAppearance="?android:attr/textAppearanceSmall" android:text="HTTP" android:id="@+id/textView7" android:layout_gravity="center_vertical"
 			          android:layout_marginLeft="10dp"/>
 		</de.tudarmstadt.informatik.hostage.ui2.layouts.FlowLayout>
+
 	</RelativeLayout>
-</FrameLayout>
+
+
+	</FrameLayout>

+ 36 - 0
res/layout/profile_manager_list_item_help.xml

@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:orientation="vertical"
+              android:layout_width="match_parent"
+              android:layout_height="match_parent"
+              android:id="@+id/swipelist_frontview"
+              android:background="@color/bright_grey"
+              android:padding="10dp">
+
+	<TextView
+			android:layout_width="wrap_content"
+			android:layout_height="wrap_content"
+			android:textAppearance="?android:attr/textAppearanceSmall"
+			android:text="Swipe from the left or right on an item to expose all available actions for an item"
+			android:id="@+id/textView"
+			android:layout_alignParentTop="true"
+			android:layout_toRightOf="@+id/imageView"
+			android:layout_marginLeft="10dp"/>
+
+	<ImageView
+			android:layout_width="wrap_content"
+			android:layout_height="wrap_content"
+			android:id="@+id/imageView"
+			android:src="@drawable/swipe_icon"
+			android:layout_alignParentTop="true"
+			android:layout_alignParentLeft="true"
+			android:layout_alignParentStart="true"
+			android:layout_alignBottom="@+id/textView"/>
+
+	<FrameLayout
+			android:layout_width="wrap_content"
+			android:layout_height="wrap_content"
+			android:id="@+id/swipelist_backview">
+	</FrameLayout>
+</RelativeLayout>

+ 8 - 0
res/menu/home_actions.xml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<menu xmlns:android="http://schemas.android.com/apk/res/android">
+	<item android:id="@+id/home_action_synchronize"
+	      android:icon="@drawable/ic_action_refresh"
+	      android:title="Synchronize"
+	      android:showAsAction="always" />
+</menu>

+ 2 - 0
res/values/protocols.xml

@@ -8,6 +8,7 @@
         <item>HTTP</item>
         <item>HTTPS</item>
         <item>MySQL</item>
+        <item>SIP</item>
         <item>SMB</item>
         <item>SSH</item>
         <item>TELNET</item>
@@ -20,6 +21,7 @@
 		<item>A protocol to exchange or transfer hypertext. It is the foundation of data communication for the World Wide Web</item>
 		<item>The same as HTTP, but using a secure connections based on SSL/TLS</item>
 		<item>The world\'s second most widely used relational database management system</item>
+		<item>A protocol for VoIP (Voice over IP) services</item>
 		<item>A protocol used for providing shared access to files, printers, serial ports, and miscellaneous communications between nodes on a network</item>
 		<item>A network protocol that provides file access, file transfer, and file management functionalities over any reliable data stream</item>
 		<item>A network protocol used on the Internet or local area networks to provide a bidirectional interactive text-oriented communication facility using a virtual terminal connection</item>

+ 1 - 1
res/values/strings.xml

@@ -22,7 +22,7 @@
     <string name="information">Information</string>
 	<string name="wifi_not_connected_msg">You are not connected to a WiFi network. \n\nPlease connect to one, before trying to activate HosTaGe.</string>
 	<string name="no_network_connection_threatmap_msg">Currently you are not connected to the Internet.\n\nPlease establish a connection to use the Threatmap.</string>
-	<string name="profile_no_services_msg">The current active protocol does not seem to monitor any services.\n\nPlease activate some services to monitor in the profile.</string>
+	<string name="profile_no_services_msg">The current active profile does not seem to monitor any services.\n\nPlease activate some services to monitor in the profile.</string>
 
     <string name="monitor_current_connection">Monitor current connection</string>
     <string name="active_profile">Active profile: </string>

+ 3 - 0
res/values/strings_gui.xml

@@ -27,5 +27,8 @@
     <string name="gui_ssid">SSID:</string>
     <string name="gui_statistics">Statistics</string>
     <string name="gui_status">Status</string>
+    <string name="gui_choose_device">Choose Device</string>
+    <string name="gui_nfc">NFC</string>
+    <string name="gui_bluetooth">Bluetooth</string>
     
 </resources>

+ 23 - 46
src/de/tudarmstadt/informatik/hostage/HoneyHandler.java → src/de/tudarmstadt/informatik/hostage/Handler.java

@@ -11,8 +11,8 @@ import android.content.SharedPreferences;
 import android.content.SharedPreferences.Editor;
 import android.preference.PreferenceManager;
 import android.util.Log;
+import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
 import de.tudarmstadt.informatik.hostage.logging.Logger;
-import de.tudarmstadt.informatik.hostage.logging.MyLocationManager;
 import de.tudarmstadt.informatik.hostage.logging.Record;
 import de.tudarmstadt.informatik.hostage.logging.Record.TYPE;
 import de.tudarmstadt.informatik.hostage.nio.Reader;
@@ -28,12 +28,12 @@ import de.tudarmstadt.informatik.hostage.wrapper.Packet;
  * @author Mihai Plasoianu
  * @author Wulf Pfeiffer
  */
-public class HoneyHandler implements Runnable {
+public class Handler implements Runnable {
 
 	/** Time until the socket throws a time out. The time is in milliseconds. */
 	private int TIMEOUT;
 
-	private HoneyService service;
+	private Hostage service;
 	protected Protocol protocol;
 	private Socket client;
 	protected Thread thread;
@@ -44,7 +44,7 @@ public class HoneyHandler implements Runnable {
 	private String BSSID;
 	private String SSID;
 
-	private HoneyListener listener;
+	private Listener listener;
 
 	/**
 	 * Constructor of the class. Initializes class variables for communication
@@ -59,8 +59,7 @@ public class HoneyHandler implements Runnable {
 	 * @param client
 	 *            A Socket for the communication with a remote client.
 	 */
-	public HoneyHandler(HoneyService service, HoneyListener listener,
-			Protocol protocol, Socket client) {
+	public Handler(Hostage service, Listener listener, Protocol protocol, Socket client) {
 		this.service = service;
 		this.listener = listener;
 		this.protocol = protocol;
@@ -70,20 +69,14 @@ public class HoneyHandler implements Runnable {
 		}
 		this.client = client;
 		this.thread = new Thread(this);
-		SharedPreferences pref = PreferenceManager
-				.getDefaultSharedPreferences(service);
+		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(service);
 		TIMEOUT = pref.getInt("timeout", 30) * 1000;
 		// TODO ThreadSicher?
 		getAndIncrementAttackID(pref);
-		SharedPreferences connInfo = service.getSharedPreferences(
-				service.getString(R.string.connection_info),
-				Context.MODE_PRIVATE);
-		BSSID = connInfo.getString(
-				service.getString(R.string.connection_info_bssid), null);
-		SSID = connInfo.getString(
-				service.getString(R.string.connection_info_ssid), null);
-		externalIP = connInfo.getString(
-				service.getString(R.string.connection_info_external_ip), null);
+		SharedPreferences connInfo = service.getSharedPreferences(service.getString(R.string.connection_info), Context.MODE_PRIVATE);
+		BSSID = connInfo.getString(service.getString(R.string.connection_info_bssid), null);
+		SSID = connInfo.getString(service.getString(R.string.connection_info_ssid), null);
+		externalIP = connInfo.getString(service.getString(R.string.connection_info_external_ip), null);
 		setSoTimeout(client);
 		thread.start();
 	}
@@ -101,11 +94,8 @@ public class HoneyHandler implements Runnable {
 	 * Sets the interrupt flag of the thread and tries to close the socket.
 	 */
 	public void kill() {
-		service.notifyUI(
-				this.getClass().getName(),
-				new String[] { service.getString(R.string.broadcast_started),
-						protocol.toString(),
-						Integer.toString(listener.getPort()) });
+		service.notifyUI(this.getClass().getName(),
+				new String[] { service.getString(R.string.broadcast_started), protocol.toString(), Integer.toString(listener.getPort()) });
 		thread.interrupt();
 		try {
 			client.close();
@@ -125,11 +115,8 @@ public class HoneyHandler implements Runnable {
 	 */
 	@Override
 	public void run() {
-		service.notifyUI(
-				this.getClass().getName(),
-				new String[] { service.getString(R.string.broadcast_started),
-						protocol.toString(),
-						Integer.toString(listener.getPort()) });
+		service.notifyUI(this.getClass().getName(),
+				new String[] { service.getString(R.string.broadcast_started), protocol.toString(), Integer.toString(listener.getPort()) });
 		InputStream in;
 		OutputStream out;
 		try {
@@ -190,23 +177,17 @@ public class HoneyHandler implements Runnable {
 		record.setTimestamp(System.currentTimeMillis());
 		record.setExternalIP(externalIP);
 		record.setLocalIP(client.getLocalAddress().getHostAddress());
-		record.setLocalHost(client.getLocalAddress().getHostAddress());
 		record.setLocalPort(protocol.getPort());
 		record.setRemoteIP(client.getInetAddress().getHostAddress());
-		record.setRemoteHost(client.getInetAddress().getHostAddress());
 		record.setRemotePort(client.getPort());
 		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());
+			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);
@@ -226,9 +207,8 @@ public class HoneyHandler implements Runnable {
 	 *            OutputStream of the socket.
 	 * @throws IOException
 	 */
-	protected void talkToClient(InputStream in, OutputStream out)
-			throws IOException {
-		Reader reader = new Reader(in);
+	protected void talkToClient(InputStream in, OutputStream out) throws IOException {
+		Reader reader = new Reader(in, protocol.toString());
 		Writer writer = new Writer(out);
 		Packet inputLine;
 		List<Packet> outputLine;
@@ -236,19 +216,16 @@ public class HoneyHandler implements Runnable {
 			outputLine = protocol.processMessage(null);
 			writer.write(outputLine);
 			for (Packet o : outputLine) {
-				Logger.log(HoneyService.getContext(),
-						createRecord(TYPE.SEND, o.toString()));
+				Logger.log(Hostage.getContext(), createRecord(TYPE.SEND, o.toString()));
 			}
 		}
 		while (!thread.isInterrupted() && (inputLine = reader.read()) != null) {
 			outputLine = protocol.processMessage(inputLine);
-			Logger.log(HoneyService.getContext(),
-					createRecord(TYPE.RECEIVE, inputLine.toString()));
+			Logger.log(Hostage.getContext(), createRecord(TYPE.RECEIVE, inputLine.toString()));
 			if (outputLine != null) {
 				writer.write(outputLine);
 				for (Packet o : outputLine) {
-					Logger.log(HoneyService.getContext(),
-							createRecord(TYPE.SEND, o.toString()));
+					Logger.log(Hostage.getContext(), createRecord(TYPE.SEND, o.toString()));
 				}
 			}
 			if (protocol.isClosed()) {

+ 67 - 113
src/de/tudarmstadt/informatik/hostage/HoneyService.java → src/de/tudarmstadt/informatik/hostage/Hostage.java

@@ -38,8 +38,8 @@ 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.MyLocationManager;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
+import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 import de.tudarmstadt.informatik.hostage.protocol.HTTP;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
@@ -54,13 +54,13 @@ import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
  * @author Lars Pandikow
  * @author Wulf Pfeiffer
  */
-public class HoneyService extends Service {
+public class Hostage extends Service {
 
 	private HashMap<String, Boolean> mProtocolActiveAttacks;
 
 	public class LocalBinder extends Binder {
-		public HoneyService getService() {
-			return HoneyService.this;
+		public Hostage getService() {
+			return Hostage.this;
 		}
 	}
 
@@ -72,14 +72,12 @@ public class HoneyService extends Service {
 	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" };
+			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()));
+				BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
 				while (!in.ready())
 					;
 				while (in.ready()) {
@@ -129,11 +127,9 @@ public class HoneyService extends Service {
 
 		@Override
 		protected void onPostExecute(String result) {
-			connectionInfoEditor.putString(
-					getString(R.string.connection_info_external_ip), result);
+			connectionInfoEditor.putString(getString(R.string.connection_info_external_ip), result);
 			connectionInfoEditor.commit();
-			notifyUI(this.getClass().getName(),
-					new String[] { getString(R.string.broadcast_connectivity) });
+			notifyUI(this.getClass().getName(), new String[] { getString(R.string.broadcast_connectivity) });
 		}
 	}
 
@@ -145,11 +141,11 @@ public class HoneyService extends Service {
 	 * @return context.
 	 */
 	public static Context getContext() {
-		return HoneyService.context;
+		return Hostage.context;
 	}
 
 	private LinkedList<Protocol> implementedProtocols;
-	private ArrayList<HoneyListener> listeners = new ArrayList<HoneyListener>();
+	private ArrayList<Listener> listeners = new ArrayList<Listener>();
 
 	private NotificationCompat.Builder builder;
 
@@ -167,21 +163,18 @@ public class HoneyService extends Service {
 	private BroadcastReceiver netReceiver = new BroadcastReceiver() {
 		@Override
 		public void onReceive(Context context, Intent intent) {
-			String bssid_old = connectionInfo.getString(
-					getString(R.string.connection_info_bssid), "");
+			String bssid_old = connectionInfo.getString(getString(R.string.connection_info_bssid), "");
 			String bssid_new = HelperUtils.getBSSID(context);
 			if (bssid_new == null || !bssid_new.equals(bssid_old)) {
 				deleteConnectionData();
 				updateConnectionInfo();
 				getLocationData();
-				notifyUI(
-						this.getClass().getName(),
-						new String[] { getString(R.string.broadcast_connectivity) });
+				notifyUI(this.getClass().getName(), new String[] { getString(R.string.broadcast_connectivity) });
 			}
 		}
 	};
 
-	public List<HoneyListener> getListeners() {
+	public List<Listener> getListeners() {
 		return listeners;
 	}
 
@@ -209,9 +202,8 @@ public class HoneyService extends Service {
 	 * @return Number of active connections
 	 */
 	public int getNumberOfActiveConnections(String protocolName, int port) {
-		for (HoneyListener listener : listeners) {
-			if (listener.getProtocolName().equals(protocolName)
-					&& listener.getPort() == port) {
+		for (Listener listener : listeners) {
+			if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
 				return listener.getHandlerCount();
 			}
 		}
@@ -224,7 +216,7 @@ public class HoneyService extends Service {
 	 * @return True if there is a running listener, else false.
 	 */
 	public boolean hasRunningListeners() {
-		for (HoneyListener listener : listeners) {
+		for (Listener listener : listeners) {
 			if (listener.isRunning())
 				return true;
 		}
@@ -255,9 +247,8 @@ public class HoneyService extends Service {
 	 * @return True if protocol is running, else false.
 	 */
 	public boolean isRunning(String protocolName, int port) {
-		for (HoneyListener listener : listeners) {
-			if (listener.getProtocolName().equals(protocolName)
-					&& listener.getPort() == port) {
+		for (Listener listener : listeners) {
+			if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
 				return listener.isRunning();
 			}
 		}
@@ -275,10 +266,8 @@ public class HoneyService extends Service {
 	public void notifyUI(String sender, String[] values) {
 		createNotification();
 		// Send Notification
-		if (sender.equals(HoneyHandler.class.getName())
-				&& values[0].equals(getString(R.string.broadcast_started))) {
+		if (sender.equals(Handler.class.getName()) && values[0].equals(getString(R.string.broadcast_started))) {
 			this.mProtocolActiveAttacks.put(values[1], true);
-
 			//attackNotification();
 		}
 		// Inform UI of Preference Change
@@ -297,10 +286,9 @@ public class HoneyService extends Service {
 	@Override
 	public void onCreate() {
 		super.onCreate();
-		HoneyService.context = getApplicationContext();
+		Hostage.context = getApplicationContext();
 		implementedProtocols = getImplementedProtocols();
-		connectionInfo = getSharedPreferences(
-				getString(R.string.connection_info), Context.MODE_PRIVATE);
+		connectionInfo = getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
 		connectionInfoEditor = connectionInfo.edit();
 
 		mProtocolActiveAttacks = new HashMap<String, Boolean>();
@@ -309,10 +297,7 @@ public class HoneyService extends Service {
 		registerNetReceiver();
 		updateConnectionInfo();
 		getLocationData();
-
-		String sharedPreferencePath = getString(R.string.shared_preference_path);
-		boolean useQotd = getSharedPreferences(sharedPreferencePath,
-				MODE_PRIVATE).getBoolean("useQotd", true);
+		boolean useQotd = context.getSharedPreferences(getString(R.string.shared_preference_path), Hostage.MODE_PRIVATE).getBoolean("useQotd", true);
 		if (useQotd) {
 			new QotdTask().execute(new String[] {});
 		}
@@ -353,37 +338,29 @@ public class HoneyService extends Service {
 	 *            The port number in which the listener should run.
 	 */
 	public boolean startListener(String protocolName, int port) {
-		for (HoneyListener listener : listeners) {
-			if (listener.getProtocolName().equals(protocolName)
-					&& listener.getPort() == port) {
+		for (Listener listener : listeners) {
+			if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
 				if (!listener.isRunning()) {
 					if (listener.start()) {
-						/*Toast.makeText(getApplicationContext(),
-								protocolName + " SERVICE STARTED!",
-								Toast.LENGTH_SHORT).show();*/
+						// Toast.makeText(getApplicationContext(), protocolName
+						// + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
 						return true;
 					}
-					/*Toast.makeText(getApplicationContext(),
-							protocolName + " SERVICE COULD NOT BE STARTED!",
-							Toast.LENGTH_SHORT).show();*/
+					Toast.makeText(getApplicationContext(), protocolName + " SERVICE COULD NOT BE STARTED!", Toast.LENGTH_SHORT).show();
 					return false;
 				}
 
 			}
 		}
-
-		HoneyListener listener = createListener(protocolName, port);
+		Listener listener = createListener(protocolName, port);
 		if (listener != null) {
 			if (listener.start()) {
-				/*Toast.makeText(getApplicationContext(),
-						protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT)
-						.show();*/
+				// Toast.makeText(getApplicationContext(), protocolName +
+				// " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
 				return true;
 			}
 		}
-		/*Toast.makeText(getApplicationContext(),
-				protocolName + " SERVICE COULD NOT BE STARTED!",
-				Toast.LENGTH_SHORT).show();*/
+		Toast.makeText(getApplicationContext(), protocolName + " SERVICE COULD NOT BE STARTED!", Toast.LENGTH_SHORT).show();
 		return false;
 	}
 
@@ -391,13 +368,13 @@ public class HoneyService extends Service {
 	 * Starts all listeners which are not already running.
 	 */
 	public void startListeners() {
-		for (HoneyListener listener : listeners) {
+		for (Listener listener : listeners) {
 			if (!listener.isRunning()) {
 				listener.start();
 			}
 		}
-		Toast.makeText(getApplicationContext(), "SERVICES STARTED!",
-				Toast.LENGTH_SHORT).show();
+		// Toast.makeText(getApplicationContext(), "SERVICES STARTED!",
+		// Toast.LENGTH_SHORT).show();
 	}
 
 	/**
@@ -419,61 +396,53 @@ public class HoneyService extends Service {
 	 *            The port number in which the listener is running.
 	 */
 	public void stopListener(String protocolName, int port) {
-		for (HoneyListener listener : listeners) {
-			if (listener.getProtocolName().equals(protocolName)
-					&& listener.getPort() == port) {
+		for (Listener listener : listeners) {
+			if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
 				if (listener.isRunning()) {
 					listener.stop();
 					mProtocolActiveAttacks.remove(protocolName);
 				}
 			}
 		}
-		Toast.makeText(getApplicationContext(),
-				protocolName + " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
+		// Toast.makeText(getApplicationContext(), protocolName +
+		// " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
 	}
 
 	/**
 	 * Stops all running listeners.
 	 */
 	public void stopListeners() {
-		for (HoneyListener listener : listeners) {
+		for (Listener listener : listeners) {
 			if (listener.isRunning()) {
 				listener.stop();
 				mProtocolActiveAttacks.remove(listener.getProtocolName());
 			}
 		}
-		Toast.makeText(getApplicationContext(), "SERVICES STOPPED!",
-				Toast.LENGTH_SHORT).show();
+		// Toast.makeText(getApplicationContext(), "SERVICES STOPPED!",
+		// Toast.LENGTH_SHORT).show();
 	}
 
 	/**
 	 * Updates the notification when a attack is registered.
 	 */
 	private void attackNotification() {
-		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("Honeypot under attack!")
-				.setSmallIcon(R.drawable.ic_service_red).setAutoCancel(true)
-				.setWhen(System.currentTimeMillis())
+		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("Honeypot under attack!").setSmallIcon(R.drawable.ic_service_red).setAutoCancel(true).setWhen(System.currentTimeMillis())
 				.setSound(Uri.parse(strRingtonePreference));
+		Intent launchIntent = new Intent(getApplicationContext(), MainActivity.class);
 		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);
+		stackBuilder.addNextIntent(launchIntent);
+		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
 		builder.setContentIntent(resultPendingIntent);
 		if (defaultPref.getBoolean("pref_vibration", false)) {
 			builder.setVibrate(new long[] { 100, 200, 100, 200 });
 		}
 
 		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
-		mNotificationManager.notify(2, builder.build());
+		mNotificationManager.notify(1, builder.build());
 	}
 
 	/**
@@ -485,21 +454,21 @@ public class HoneyService extends Service {
 	}
 
 	/**
-	 * Creates a Listener for a given protocol on a specific port. After
-	 * creation the Listener is not started. Checks if the protocol is
+	 * Creates a HoneyListener for a given protocol on a specific port. After
+	 * creation the HoneyListener is not started. Checks if the protocol is
 	 * implemented first.
 	 * 
 	 * @param protocolName
 	 *            Name of the protocol
 	 * @param port
-	 *            Port on which to start the Listener
+	 *            Port on which to start the HoneyListener
 	 * @return Returns the created HoneyListener, if creation failed returns
 	 *         null.
 	 */
-	private HoneyListener createListener(String protocolName, int port) {
+	private Listener createListener(String protocolName, int port) {
 		for (Protocol protocol : implementedProtocols) {
 			if (protocolName.equals(protocol.toString())) {
-				HoneyListener listener = new HoneyListener(this, protocol, port);
+				Listener listener = new Listener(this, protocol, port);
 				listeners.add(listener);
 				return listener;
 			}
@@ -511,25 +480,22 @@ public class HoneyService extends Service {
 	 * Creates a Notification in the notification bar.
 	 */
 	private void createNotification() {
-		UglyDbHelper dbh = new UglyDbHelper(this);
+		HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
 		boolean activeHandlers = false;
 		boolean bssidSeen = false;
 		boolean listening = false;
 
-		for (HoneyListener listener : listeners) {
+		for (Listener listener : listeners) {
 			if (listener.isRunning())
 				listening = true;
 			if (listener.getHandlerCount() > 0) {
 				activeHandlers = true;
 			}
-			if (dbh.bssidSeen(listener.getProtocolName(),
-					HelperUtils.getBSSID(getApplicationContext()))) {
+			if (dbh.bssidSeen(listener.getProtocolName(), HelperUtils.getBSSID(getApplicationContext()))) {
 				bssidSeen = true;
 			}
 		}
-		builder = new NotificationCompat.Builder(this).setContentTitle(
-				getString(R.string.app_name)).setWhen(
-				System.currentTimeMillis());
+		builder = new NotificationCompat.Builder(this).setContentTitle(getString(R.string.app_name)).setWhen(System.currentTimeMillis());
 		if (!listening) {
 			builder.setSmallIcon(R.drawable.ic_launcher);
 			builder.setContentText("HosTaGe is not active.");
@@ -543,17 +509,11 @@ public class HoneyService extends Service {
 			builder.setSmallIcon(R.drawable.ic_service_green);
 			builder.setContentText("Everything looks fine!");
 		}
+		Intent launchIntent = new Intent(getApplicationContext(), MainActivity.class);
 		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
 		stackBuilder.addParentStack(MainActivity.class);
-
-		Intent intent = MainActivity.getInstance().getIntent();
-		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
-				Intent.FLAG_ACTIVITY_SINGLE_TOP |
-				Intent.FLAG_ACTIVITY_NEW_TASK);
-		intent.setAction("SHOW_HOME");
-
-		stackBuilder.addNextIntent(intent);
-		PendingIntent resultPendingIntent = PendingIntent.getActivity(MainActivity.context, 0, intent, 0); //stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
+		stackBuilder.addNextIntent(launchIntent);
+		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
 		builder.setContentIntent(resultPendingIntent);
 		builder.setOngoing(true);
 		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
@@ -600,9 +560,7 @@ public class HoneyService extends Service {
 
 		for (String protocol : protocols) {
 			try {
-				implementedProtocols.add((Protocol) Class.forName(
-						String.format("%s.%s", packageName, protocol))
-						.newInstance());
+				implementedProtocols.add((Protocol) Class.forName(String.format("%s.%s", packageName, protocol)).newInstance());
 			} catch (Exception e) {
 				e.printStackTrace();
 			}
@@ -659,15 +617,11 @@ public class HoneyService extends Service {
 	 * @see MainActivity#CONNECTION_INFO
 	 */
 	private void updateConnectionInfo() {
-		SharedPreferences pref = context.getSharedPreferences(
-				getString(R.string.connection_info), Context.MODE_PRIVATE);
+		SharedPreferences pref = context.getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
 		Editor editor = pref.edit();
-		editor.putString(getString(R.string.connection_info_ssid),
-				HelperUtils.getSSID(context));
-		editor.putString(getString(R.string.connection_info_bssid),
-				HelperUtils.getBSSID(context));
-		editor.putString(getString(R.string.connection_info_internal_ip),
-				HelperUtils.getInternalIP(context));
+		editor.putString(getString(R.string.connection_info_ssid), HelperUtils.getSSID(context));
+		editor.putString(getString(R.string.connection_info_bssid), HelperUtils.getBSSID(context));
+		editor.putString(getString(R.string.connection_info_internal_ip), HelperUtils.getInternalIP(context));
 		editor.commit();
 		SetExternalIPTask async = new SetExternalIPTask();
 		async.execute(new String[] { "http://ip2country.sourceforge.net/ip2c.php?format=JSON" });

+ 27 - 34
src/de/tudarmstadt/informatik/hostage/HoneyListener.java → src/de/tudarmstadt/informatik/hostage/Listener.java

@@ -11,27 +11,28 @@ import javax.net.ssl.SSLSocketFactory;
 
 import de.tudarmstadt.informatik.hostage.net.MyServerSocketFactory;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol;
+import de.tudarmstadt.informatik.hostage.protocol.SMB;
 import de.tudarmstadt.informatik.hostage.protocol.SSLProtocol;
 
 /**
  * Protocol listener class:<br>
  * Creates a Socket on the port of a given protocol and listens for incoming
  * connections.<br>
- * For each connection creates a Socket and instantiate an {@link HoneyHandler}.
+ * For each connection creates a Socket and instantiate an {@link Handler}.
  * 
  * @author Mihai Plasoianu
  * 
  */
-public class HoneyListener implements Runnable {
+public class Listener implements Runnable {
 
-	private ArrayList<HoneyHandler> handlers = new ArrayList<HoneyHandler>();
+	private ArrayList<Handler> handlers = new ArrayList<Handler>();
 
 	private Protocol protocol;
 
 	private ServerSocket server;
 	private Thread thread;
 	private int port;
-	private HoneyService service;
+	private Hostage service;
 
 	private ConnectionRegister conReg;
 	private boolean running = false;
@@ -44,14 +45,14 @@ public class HoneyListener implements Runnable {
 	 * @param protocol
 	 *            The Protocol on which the listener is running.
 	 */
-	public HoneyListener(HoneyService service, Protocol protocol) {
+	public Listener(Hostage service, Protocol protocol) {
 		this.service = service;
 		this.protocol = protocol;
 		port = protocol.getPort();
 		conReg = new ConnectionRegister(service);
 	}
 
-	public HoneyListener(HoneyService service, Protocol protocol, int port) {
+	public Listener(Hostage service, Protocol protocol, int port) {
 		this.service = service;
 		this.protocol = protocol;
 		this.port = port;
@@ -98,9 +99,8 @@ public class HoneyListener implements Runnable {
 	 * Remove all terminated handlers from its internal ArrayList.
 	 */
 	public void refreshHandlers() {
-		for (Iterator<HoneyHandler> iterator = handlers.iterator(); iterator
-				.hasNext();) {
-			HoneyHandler handler = iterator.next();
+		for (Iterator<Handler> iterator = handlers.iterator(); iterator.hasNext();) {
+			Handler handler = iterator.next();
 			if (handler.isTerminated()) {
 				conReg.closeConnection();
 				iterator.remove();
@@ -113,7 +113,7 @@ public class HoneyListener implements Runnable {
 		while (!thread.isInterrupted()) {
 			addHandler();
 		}
-		for (HoneyHandler handler : handlers) {
+		for (Handler handler : handlers) {
 			handler.kill();
 		}
 	}
@@ -127,13 +127,13 @@ public class HoneyListener implements Runnable {
 			server = new MyServerSocketFactory().createServerSocket(port);
 			if (server == null)
 				return false;
+			if(protocol.toString().equals("SMB")) {
+				((SMB) protocol).setIP(Hostage.getContext().getSharedPreferences(Hostage.getContext().getString(R.string.connection_info), Hostage.MODE_PRIVATE).getString(Hostage.getContext().getString(R.string.connection_info_internal_ip), ""));
+			}
 			(this.thread = new Thread(this)).start();
 			running = true;
-			service.notifyUI(
-					this.getClass().getName(),
-					new String[] {
-							service.getString(R.string.broadcast_started),
-							protocol.toString(), Integer.toString(port) });
+			service.notifyUI(this.getClass().getName(),
+					new String[] { service.getString(R.string.broadcast_started), protocol.toString(), Integer.toString(port) });
 			return true;
 		} catch (Exception e) {
 			e.printStackTrace();
@@ -150,11 +150,8 @@ public class HoneyListener implements Runnable {
 			server.close();
 			thread.interrupt();
 			running = false;
-			service.notifyUI(
-					this.getClass().getName(),
-					new String[] {
-							service.getString(R.string.broadcast_stopped),
-							protocol.toString(), Integer.toString(port) });
+			service.notifyUI(this.getClass().getName(),
+					new String[] { service.getString(R.string.broadcast_stopped), protocol.toString(), Integer.toString(port) });
 		} catch (Exception e) {
 			e.printStackTrace();
 		}
@@ -162,7 +159,7 @@ public class HoneyListener implements Runnable {
 
 	/**
 	 * Waits for an incoming connection, accepts it and starts a
-	 * {@link HoneyHandler}
+	 * {@link Handler}
 	 */
 	private void addHandler() {
 		if (conReg.isConnectionFree()) {
@@ -182,7 +179,7 @@ public class HoneyListener implements Runnable {
 	}
 
 	/**
-	 * Creates a new instance of an {@link HoneyHandler}.
+	 * Creates a new instance of an {@link Handler}.
 	 * 
 	 * @param service
 	 *            The background service
@@ -192,29 +189,27 @@ public class HoneyListener implements Runnable {
 	 *            The Protocol the handler will run on
 	 * @param client
 	 *            The Socket the handler uses
-	 * @return A Instance of a {@link HoneyHandler} with the specified
+	 * @return A Instance of a {@link Handler} with the specified
 	 *         parameter.
 	 */
-	private HoneyHandler newInstance(HoneyService service,
-			HoneyListener listener, Protocol protocol, Socket client) {
-		return new HoneyHandler(service, listener, protocol, client);
+	private Handler newInstance(Hostage service, Listener listener, Protocol protocol, Socket client) {
+		return new Handler(service, listener, protocol, client);
 	}
 
 	/**
-	 * Starts a {@link HoneyHandler} with the given socket.
+	 * Starts a {@link Handler} with the given socket.
 	 * 
 	 * @param client
 	 *            The socket with the accepted connection.
 	 * @throws Exception
 	 */
 	private void startHandler(Socket client) throws Exception {
-		handlers.add(newInstance(service, this, protocol.getClass()
-				.newInstance(), client));
+		handlers.add(newInstance(service, this, protocol.getClass().newInstance(), client));
 	}
 
 	/**
 	 * Creates a SSLSocket out of the given socket and starts a
-	 * {@link HoneyHandler}.
+	 * {@link Handler}.
 	 * 
 	 * @param client
 	 *            The socket with the accepted connection.
@@ -223,10 +218,8 @@ public class HoneyListener implements Runnable {
 	private void startSecureHandler(Socket client) throws Exception {
 		SSLContext sslContext = ((SSLProtocol) protocol).getSSLContext();
 		SSLSocketFactory factory = sslContext.getSocketFactory();
-		SSLSocket sslClient = (SSLSocket) factory.createSocket(client, null,
-				client.getPort(), false);
+		SSLSocket sslClient = (SSLSocket) factory.createSocket(client, null, client.getPort(), false);
 		sslClient.setUseClientMode(false);
-		handlers.add(newInstance(service, this, protocol.getClass()
-				.newInstance(), sslClient));
+		handlers.add(newInstance(service, this, protocol.getClass().newInstance(), sslClient));
 	}
 }

+ 8 - 0
src/de/tudarmstadt/informatik/hostage/commons/HelperUtils.java

@@ -398,4 +398,12 @@ public final class HelperUtils {
 
 		return mWifi.isConnected();
 	}
+
+	public static boolean isNetworkAvailable(Context context) {
+		if(context == null) return false;
+
+		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
+		NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
+		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
+	}
 }

+ 305 - 0
src/de/tudarmstadt/informatik/hostage/deprecated/OldLogger.java

@@ -0,0 +1,305 @@
+package de.tudarmstadt.informatik.hostage.deprecated;
+
+import java.util.ArrayList;
+
+import android.app.IntentService;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.ResultReceiver;
+import de.tudarmstadt.informatik.hostage.logging.Record;
+
+/**
+ * An {@link IntentService} subclass for handling asynchronous task requests in
+ * a service on a separate handler thread.
+ * 
+ * @author Mihai Plasoianu
+ */
+public class OldLogger 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 deleteAll(Context context) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_CLEAR_ALL);
+		context.startService(intent);
+	}
+
+	public static void deleteByBssid(Context context, String bssid) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_CLEAR_BSSID);
+		intent.putExtra(EXTRA_BSSID, bssid);
+		context.startService(intent);
+	}
+
+	public static void deleteByDate(Context context, long time) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_CLEAR_DATE);
+		intent.putExtra(EXTRA_PRIMITIVE, time);
+		context.startService(intent);
+	}
+
+	public static void getAllBssids(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_GET_BSSID_ALL);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getAllRecords(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_GET_RECORD_ALL);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getAttackCount(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, OldLogger.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, OldLogger.class);
+		intent.setAction(ACTION_GET_COUNT_PROTOCOL);
+		intent.putExtra(EXTRA_PROTOCOL, protocol);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getMaxAttackId(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_GET_ATTACK_MAX);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getMinAttackId(Context context, ResultReceiver receiver) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_GET_ATTACK_MIN);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getRecordOfAttackId(Context context, long attack_id, ResultReceiver receiver) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_GET_RECORD_ID);
+		intent.putExtra(EXTRA_PRIMITIVE, attack_id);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getRecordOfEachAttack(Context context, int lastUploadedAttackId, ResultReceiver receiver) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_GET_RECORD_EACH);
+		intent.putExtra(EXTRA_PRIMITIVE, lastUploadedAttackId);
+		intent.putExtra(RESULT_RECEIVER, receiver);
+		context.startService(intent);
+	}
+
+	public static void getSsid(Context context, String bssid, ResultReceiver receiver) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_GET_SSID_BSSID);
+		intent.putExtra(EXTRA_BSSID, bssid);
+		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, OldLogger.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 log(Context context, Record record) {
+		Intent intent = new Intent(context, OldLogger.class);
+		intent.setAction(ACTION_LOG);
+		intent.putExtra(EXTRA_RECORD, record);
+		context.startService(intent);
+	}
+
+	private UglyDbHelper mDbHelper;
+
+	public OldLogger() {
+		super("Logger");
+	}
+
+	@Override
+	public void onCreate() {
+		super.onCreate();
+		mDbHelper = new UglyDbHelper(getApplicationContext());
+	}
+
+	private boolean handleActionBssidSeen(String protocol, String bssid) {
+		return mDbHelper.bssidSeen(protocol, bssid);
+	}
+
+	/**
+	 * Delete all records.
+	 */
+	private void handleActionDeleteAll() {
+		mDbHelper.clearData();
+	}
+
+	private void handleActionDeleteByBssid(String bssid) {
+		mDbHelper.deleteByBSSID(bssid);
+	}
+
+	private void handleActionDeleteByDate(long time) {
+		mDbHelper.deleteByDate(time);
+	}
+
+	private String[] handleActionGetAllBssids() {
+		return mDbHelper.getAllBSSIDS();
+	}
+
+	private ArrayList<Record> handleActionGetAllRecords() {
+		return mDbHelper.getAllRecords();
+	}
+
+	private int handleActionGetAttackCount() {
+		return mDbHelper.getAttackCount();
+	}
+
+	private int handleActionGetAttackPerProtocolCount(String protocol) {
+		return mDbHelper.getAttackPerProtocolCount(protocol);
+	}
+
+	private long handleActionGetMaxAttackId() {
+		return mDbHelper.getHighestAttackId();
+	}
+
+	private long handleActionGetMinAttackId() {
+		return mDbHelper.getSmallestAttackId();
+	}
+
+	private Record handleActionGetRecordOfAttackId(long attack_id) {
+		return mDbHelper.getRecordOfAttackId(attack_id);
+	}
+
+	private ArrayList<Record> handleActionGetRecordOfEachAttack(int lastUploadedAttackId) {
+		return mDbHelper.getRecordOfEachAttack(lastUploadedAttackId);
+	}
+
+	private String handleActionGetSsid(String bssid) {
+		return mDbHelper.getSSID(bssid);
+	}
+
+	/**
+	 * Log a record.
+	 */
+	private void handleActionLog(Record record) {
+		mDbHelper.addRecord(record);
+	}
+
+	@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();
+			}
+		}
+	}
+
+}

+ 970 - 1022
src/de/tudarmstadt/informatik/hostage/logging/UglyDbHelper.java → src/de/tudarmstadt/informatik/hostage/deprecated/UglyDbHelper.java

@@ -1,1022 +1,970 @@
-package de.tudarmstadt.informatik.hostage.logging;
-
-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;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-
-import de.tudarmstadt.informatik.hostage.logging.Record.TYPE;
-import de.tudarmstadt.informatik.hostage.model.Profile;
-import de.tudarmstadt.informatik.hostage.ui.LogFilter;
-
-/**
- * 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 UglyDbHelper extends SQLiteOpenHelper {
-
-	// All Static variables
-	// Database Version
-	private static final int DATABASE_VERSION = 9;
-
-	// 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_PROFILES = "profiles";
-
-	// 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";
-
-	public static final String KEY_PROFILE_ID = "_profile_id";
-	public static final String KEY_PROFILE_NAME = "profile_name";
-	public static final String KEY_PROFILE_DESCRIPTION = "profile_description";
-	public static final String KEY_PROFILE_ICON = "profile_icon";
-	public static final String KEY_PROFILE_EDITABLE = "profile_editable";
-	public static final String KEY_PROFILE_ACTIVE = "profile_active";
-	public static final String KEY_PROFILE_ICON_NAME = "profile_icon_name";
-
-	// Database sql create statements
-	private static final String CREATE_PROFILE_TABLE = "CREATE TABLE "
-			+ TABLE_PROFILES + "("
-			+ KEY_PROFILE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
-			+ KEY_PROFILE_NAME + " TEXT,"
-			+ KEY_PROFILE_DESCRIPTION + " TEXT,"
-			+ KEY_PROFILE_ICON + " TEXT,"
-			+ KEY_PROFILE_ICON_NAME + " TEXT,"
-			+ KEY_PROFILE_EDITABLE + " INTEGER,"
-			+ KEY_PROFILE_ACTIVE + " INTEGER"
-			+ ")";
-
-	private static final String CREATE_RECORD_TABLE = "CREATE TABLE "
-			+ TABLE_RECORDS + "("
-            + KEY_ID + " INTEGER NOT NULL,"
-			+ KEY_ATTACK_ID + " INTEGER NOT NULL,"
-            + KEY_TYPE + " TEXT,"
-			+ KEY_TIME + " INTEGER,"
-            + KEY_PACKET + " TEXT,"
-            + "FOREIGN KEY("
-			+ KEY_ATTACK_ID + ") REFERENCES " + TABLE_ATTACK_INFO + "("
-			+ KEY_ATTACK_ID + ")," + "PRIMARY KEY(" + KEY_ID + ", "
-			+ KEY_ATTACK_ID + ")" + ")";
-
-	private static final String CREATE_ATTACK_INFO_TABLE = "CREATE TABLE "
-			+ TABLE_ATTACK_INFO + "("
-            + KEY_ATTACK_ID + " INTEGER PRIMARY KEY,"
-			+ KEY_PROTOCOL + " TEXT,"
-            + KEY_EXTERNAL_IP + " TEXT,"
-			+ KEY_LOCAL_IP + " BLOB,"
-            + KEY_LOCAL_HOSTNAME + " TEXT,"
-			+ KEY_LOCAL_PORT + " INTEGER,"
-            + KEY_REMOTE_IP + " BLOB,"
-			+ KEY_REMOTE_HOSTNAME + " TEXT,"
-            + KEY_REMOTE_PORT + " INTEGER,"
-			+ KEY_BSSID + " TEXT,"
-            + "FOREIGN KEY(" + KEY_BSSID
-			+ ") REFERENCES " + TABLE_BSSIDS + "(" + KEY_BSSID + ")" + ")";
-
-	private static final String CREATE_BSSID_TABLE = "CREATE TABLE "
-			+ TABLE_BSSIDS + "("
-            + KEY_BSSID + " TEXT PRIMARY KEY,"
-            + KEY_SSID + " TEXT,"
-            + KEY_LATITUDE + " INTEGER,"
-            + KEY_LONGITUDE + " INTEGER,"
-            + KEY_ACCURACY + " INTEGER,"
-            + KEY_TIME + " INTEGER"
-			+ ")";
-
-	public UglyDbHelper(Context context) {
-		super(context, DATABASE_NAME, null, DATABASE_VERSION);
-	}
-
-	  /*
-    // Contacts Table Columns names
-	private static final String KEY_ID = "_id";
-	private static final String KEY_ATTACK_ID = "_attack_id";
-	private static final String KEY_TYPE = "type";
-	private static final String KEY_TIME = "timestamp";
-	private static final String KEY_PACKET = "packet";
-	private static final String KEY_PROTOCOL = "protocol";
-	private static final String KEY_EXTERNAL_IP ="externalIP";
-	private static final String KEY_LOCAL_IP = "localIP";
-	private static final String KEY_LOCAL_HOSTNAME = "localHostName";
-	private static final String KEY_LOCAL_PORT = "localPort";
-	private static final String KEY_REMOTE_IP = "remoteIP";
-	private static final String KEY_REMOTE_HOSTNAME = "remoteHostName";
-	private static final String KEY_REMOTE_PORT = "remotePort";
-	private static final String KEY_BSSID = "_bssid";
-	private static final String KEY_SSID = "ssid";
-	private static final String KEY_LATITUDE = "latitude";
-	private static final String KEY_LONGITUDE = "longitude";
-	private static final String KEY_ACCURACY = "accuracy";
-	*/
-
-	/**
-	 * Gets all received {@link Record Records} for the specified information in the LogFilter ordered by date.
-	 * @return A ArrayList with all received {@link Record Records} for the LogFilter.
-	 */
-	public ArrayList<Record> getRecordsForFilter(LogFilter filter) {
-		ArrayList<Record> recordList = new ArrayList<Record>();
-		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO +  " JOIN " + TABLE_BSSIDS + " USING "+ "(" + KEY_BSSID + ")";
-
-		// TIMESTAMPS
-		selectQuery = selectQuery + " WHERE " + TABLE_RECORDS +"."+KEY_TIME;
-		selectQuery = selectQuery + " < " + filter.getBelowTimestamp();
-		selectQuery = selectQuery + " AND " + TABLE_RECORDS +"."+KEY_TIME;
-		selectQuery = selectQuery + " > " + filter.getAboveTimestamp();
-
-		if (filter.getBSSIDs() != null && filter.getBSSIDs().size() > 0) {
-			selectQuery = selectQuery + " AND ";
-			selectQuery = selectQuery + filter.getBSSIDQueryStatement(TABLE_BSSIDS, KEY_BSSID);
-		}
-		if (filter.getESSIDs() != null && filter.getESSIDs().size() > 0) {
-			selectQuery = selectQuery + " AND ";
-			selectQuery = selectQuery + filter.getESSIDQueryStatement(TABLE_BSSIDS, KEY_SSID);
-		}
-		if (filter.getProtocols() != null && filter.getProtocols().size() > 0) {
-			selectQuery = selectQuery + " AND ";
-			selectQuery = selectQuery + filter.getProtocolsQueryStatement(TABLE_ATTACK_INFO, KEY_PROTOCOL);
-		}
-
-        selectQuery = selectQuery + " GROUP BY " + TABLE_RECORDS+"."+KEY_ATTACK_ID;
-
-        if (filter.getSorttype() == LogFilter.SortType.timestamp){
-            //DESC
-            selectQuery = selectQuery + " ORDER BY " + filter.getSorttype() + " DESC";
-        } else {
-            selectQuery = selectQuery + " ORDER BY " + filter.getSorttype();
-        }
-
-
-
-		System.out.println(selectQuery);
-		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 all non duplicate Records For the key BSSID.
-	 * @return A ArrayList with received Records.
-	 */
-	public ArrayList<String> getUniqueBSSIDRecords(){
-		return this.getUniqueDataEntryForKeyType(KEY_BSSID, TABLE_BSSIDS);
-	}
-	/**
-	 * Gets all non duplicate Records For the key ESSID.
-	 * @return A ArrayList with received Records.
-	 */
-	public ArrayList<String> getUniqueESSIDRecords(){
-		return this.getUniqueDataEntryForKeyType(KEY_SSID, TABLE_BSSIDS);
-	}
-
-    public ArrayList<String> getUniqueESSIDRecordsForProtocol(String protocol){
-        return this.getUniqueIDForProtocol(KEY_SSID, protocol);
-    }
-    public ArrayList<String> getUniqueBSSIDRecordsForProtocol(String protocol){
-        return this.getUniqueIDForProtocol(KEY_BSSID, protocol);
-    }
-
-    private ArrayList<String> getUniqueIDForProtocol(String id, String protocol){
-        ArrayList<String> recordList = new ArrayList<String>();
-        String selectQuery = "SELECT DISTINCT " + id + " FROM " + TABLE_ATTACK_INFO + " JOIN " + TABLE_BSSIDS + " USING "+ "(" + KEY_BSSID + ") " + " WHERE " + TABLE_ATTACK_INFO + "."+ KEY_PROTOCOL + " = " + "'" + protocol + "'"+ " ORDER BY " + id; // " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS +
-
-
-        // ORDERED BY TIME
-        System.out.println(selectQuery);
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-
-        // looping through all rows and adding to list
-        if (cursor.moveToFirst()) {
-            do {
-                String record = cursor.getString(0);
-                recordList.add(record);
-            } while (cursor.moveToNext());
-        }
-        cursor.close();
-
-        // return record list
-        db.close();
-        return recordList;
-    }
-
-	/**
-	 * Gets all non duplicate Data Entry For a specific KeyType ( e.g. BSSIDs).
-	 * @return A ArrayList with received Records.
-	 */
-	public ArrayList<String> getUniqueDataEntryForKeyType(String keyType, String table) {
-		ArrayList<String> recordList = new ArrayList<String>();
-		//String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS;
-		String selectQuery = "SELECT DISTINCT " + keyType + " FROM " + table + " ORDER BY " + keyType; // " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " + TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS +
-
-
-		// ORDERED BY TIME
-		System.out.println(selectQuery);
-		SQLiteDatabase db = this.getReadableDatabase();
-		Cursor cursor = db.rawQuery(selectQuery, null);
-
-		// looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				String record = cursor.getString(0);
-				recordList.add(record);
-			} while (cursor.moveToNext());
-		}
-		cursor.close();
-
-		// return record list
-		db.close();
-		return recordList;
-	}
-
-	/**
-	 * 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()); // Log Local IP
-		attackValues.put(KEY_LOCAL_HOSTNAME, record.getLocalHost());
-		attackValues.put(KEY_LOCAL_PORT, record.getLocalPort());
-		attackValues.put(KEY_REMOTE_IP, record.getRemoteIP()); // Log Remote IP
-		attackValues.put(KEY_REMOTE_HOSTNAME, record.getRemoteHost());
-		attackValues.put(KEY_REMOTE_PORT, record.getRemotePort()); // Log Remote
-																	// Port
-		attackValues.put(KEY_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);
-	}
-
-	/**
-	 * 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;
-	}
-
-	public int numBssidSeen(String BSSID){
-		String countQuery = "SELECT  COUNT(*) FROM " + TABLE_ATTACK_INFO
-				+ " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE " + TABLE_BSSIDS+ "."+ KEY_BSSID + " = "
-				+ "'" + BSSID + "'";
-		SQLiteDatabase db = this.getReadableDatabase();
-		Cursor cursor = db.rawQuery(countQuery, null);
-		cursor.moveToFirst();
-		int result = cursor.getInt(0);
-		cursor.close();
-		db.close();
-		return result;
-	}
-
-	public int numBssidSeen(String protocol, String BSSID) {
-		String countQuery = "SELECT  COUNT(*) FROM " + TABLE_ATTACK_INFO
-				+ " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE " + TABLE_ATTACK_INFO + "." +  KEY_PROTOCOL
-				+ " = " + "'" + protocol + "'" + " AND " + TABLE_BSSIDS+ "."+ KEY_BSSID + " = "
-				+ "'" + BSSID + "'";
-		SQLiteDatabase db = this.getReadableDatabase();
-		Cursor cursor = db.rawQuery(countQuery, null);
-		cursor.moveToFirst();
-		int result = cursor.getInt(0);
-		cursor.close();
-		db.close();
-		return result;
-	}
-
-	/**
-	 * 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
-				+ " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE " + TABLE_ATTACK_INFO + "." +  KEY_PROTOCOL
-				+ " = " + "'" + protocol + "'" + " AND " + TABLE_BSSIDS+ "."+ KEY_BSSID + " = "
-				+ "'" + BSSID + "'";
-		SQLiteDatabase db = this.getReadableDatabase();
-		Cursor cursor = db.rawQuery(countQuery, null);
-		int result = cursor.getCount();
-		cursor.close();
-		db.close();
-		return result > 0;
-	}
-
-	/**
-	 * 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.delete(TABLE_PROFILES, null, null);
-		db.close();
-	}
-
-	/**
-	 * 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();
-	}
-
-	/**
-	 * 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 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 + " JOIN "
-				+ TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE " + KEY_TYPE + "='RECEIVE'"
-				+ " ORDER BY " + TABLE_RECORDS+ "."+ 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 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 + " JOIN "
-				+ TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")";
-
-		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;
-	}
-
-	/**
-	 * 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 getAttackPerProtocolCount(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 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;
-	}
-
-	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;
-	}
-
-	/**
-	 * 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 + " JOIN "
-				+ TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE " + TABLE_RECORDS+"."+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;
-	}
-
-	/**
-	 * 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;
-	}
-
-	/**
-	 * 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 + " JOIN "
-				+ TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE " + TABLE_RECORDS+"."+KEY_ATTACK_ID + " = " + attack_id
-				+ " GROUP BY " + TABLE_RECORDS+"."+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 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 + " JOIN "
-				+ TABLE_BSSIDS  + " USING " + "(" + KEY_BSSID + ")" + " GROUP BY " + TABLE_RECORDS+ "."+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;
-	}
-
-
-    /*
-    * Returns the Conversation of a specific attack id
-    * @param attack_id
-    *           Tha attack id to match the query against.
-    *
-    *  @return A arraylist with all {@link Record Records}s for an attack id.
-    *
-    * */
-    public ArrayList<Record> getConversationForAttackID(long attack_id) {
-        ArrayList<Record> recordList = new ArrayList<Record>();
-        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS
-                + " NATURAL JOIN " + TABLE_ATTACK_INFO + " JOIN "
-                + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE " + TABLE_RECORDS+"."+KEY_ATTACK_ID + " = " + attack_id;
-
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-
-        if (cursor.moveToFirst()) {
-            do {
-                Record record = createRecord(cursor);
-                recordList.add(record);
-            } while (cursor.moveToNext());
-        }
-        cursor.close();
-
-        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 + " JOIN "
-				+ TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE " + TABLE_RECORDS+"."+KEY_ATTACK_ID + " > " + attack_id
-				+ " GROUP BY " + TABLE_RECORDS+"."+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 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;
-	}
-
-	/**
-	 * 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;
-	}
-
-	// Creating Tables
-	@Override
-	public void onCreate(SQLiteDatabase db) {
-		db.execSQL(CREATE_BSSID_TABLE);
-		db.execSQL(CREATE_ATTACK_INFO_TABLE);
-		db.execSQL(CREATE_RECORD_TABLE);
-		db.execSQL(CREATE_PROFILE_TABLE);
-	}
-
-	// 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_PROFILES);
-
-		// Create tables again
-		onCreate(db);
-	}
-
-	/**
-	 * Retrieves all the profiles from the database
-	 *
-	 * @return list of profiles
-	 */
-	public List<Profile> getAllProfiles(){
-		List<Profile> profiles = new LinkedList<Profile>();
-
-		// Select All Query
-		String selectQuery = "SELECT  * FROM " + TABLE_PROFILES;
-
-		SQLiteDatabase db = this.getWritableDatabase();
-		Cursor cursor = db.rawQuery(selectQuery, null);
-
-		// looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				Profile profile = new Profile(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getInt(5) == 1);
-
-				if(cursor.getInt(6) == 1){
-					profile.mActivated = true;
-				}
-
-				profile.mIconName = cursor.getString(4);
-
-				// Adding record to list
-				profiles.add(profile);
-			} while (cursor.moveToNext());
-		}
-		cursor.close();
-		db.close();
-		// return record list
-		return profiles;
-	}
-
-	/**
-	 * Persists the given profile into the database
-	 *
-	 * @param profile the profile which should be persisted
-	 *
-	 * @return
-	 */
-	public long persistProfile(Profile profile){
-		SQLiteDatabase db = this.getReadableDatabase();
-
-		ContentValues values = new ContentValues();
-
-		if(profile.mId != -1){
-			values.put(KEY_PROFILE_ID, profile.mId);
-		}
-
-		values.put(KEY_PROFILE_NAME, profile.mLabel);
-		values.put(KEY_PROFILE_DESCRIPTION, profile.mText);
-		values.put(KEY_PROFILE_ICON, profile.mIconPath);
-		values.put(KEY_PROFILE_ICON_NAME, profile.mIconName);
-		values.put(KEY_PROFILE_ACTIVE, profile.mActivated);
-		values.put(KEY_PROFILE_EDITABLE, profile.mEditable);
-
-		return db.replace(TABLE_PROFILES, null, values);
-	}
-
-
-	/**
-	 * private static final String CREATE_PROFILE_TABLE = "CREATE TABLE "
-	 + TABLE_PROFILES + "("
-	 + KEY_PROFILE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
-	 + KEY_PROFILE_NAME + " TEXT,"
-	 + KEY_PROFILE_DESCRIPTION + " TEXT,"
-	 + KEY_PROFILE_ICON + " TEXT,"
-	 + KEY_PROFILE_ICON_ID + " INTEGER,"
-	 + KEY_PROFILE_EDITABLE + " INTEGER,"
-	 + KEY_PROFILE_ACTIVE + " INTEGER"
-	 + ")";
-	 */
-	public Profile getProfile(int id) {
-		String selectQuery = "SELECT  * FROM " + TABLE_PROFILES + " WHERE " + TABLE_PROFILES + "." + KEY_PROFILE_ID + " = " + id;
-		SQLiteDatabase db = this.getReadableDatabase();
-
-		Cursor cursor = db.rawQuery(selectQuery, null);
-		Profile profile = null;
-
-		if (cursor.moveToFirst()) {
-			profile = new Profile(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getInt(5) == 1);
-
-			if(cursor.getInt(6) == 1){
-				profile.mActivated = true;
-			}
-
-			profile.mIconName = cursor.getString(5);
-		}
-
-		cursor.close();
-		db.close();
-
-		// return contact
-		return profile;
-	}
-
-	public void deleteProfile(int id){
-		SQLiteDatabase db = this.getReadableDatabase();
-
-		db.delete(TABLE_PROFILES, KEY_PROFILE_ID + "=?", new String[]{String.valueOf(id)});
-	}
-
-	public void updateNetworkInformation(
-			ArrayList<HashMap<String, Object>> networkInformation) {
-		Log.i("DatabaseHandler", "Starte updating");
-		for (HashMap<String, Object> values : networkInformation) {
-			updateNetworkInformation(values);
-		}
-	}
-
-	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();
-	}
-
-	/**
-	 * 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();
-		record.setId(Integer.parseInt(cursor.getString(0)));
-		record.setAttack_id(cursor.getLong(1));
-		record.setType(TYPE.valueOf(cursor.getString(2)));
-		record.setTimestamp(cursor.getLong(3));
-		record.setPacket(cursor.getString(4));
-		record.setProtocol(cursor.getString(5));
-		record.setExternalIP(cursor.getString(6));
-
-		record.setLocalIP(cursor.getString(7));
-		record.setLocalHost(cursor.getString(8));
-		record.setLocalPort(Integer.parseInt(cursor.getString(9)));
-
-		record.setRemoteIP(cursor.getString(10));
-		record.setRemoteHost(cursor.getString(11));
-		record.setRemotePort(Integer.parseInt(cursor.getString(12)));
-
-		record.setBssid(cursor.getString(13));
-		record.setSsid(cursor.getString(14));
-		record.setLatitude(Double.parseDouble(cursor.getString(15)));
-		record.setLongitude(Double.parseDouble(cursor.getString(16)));
-		record.setAccuracy(Float.parseFloat(cursor.getString(17)));
-		record.setTimestampLocation(cursor.getLong(18));
-
-		return record;
-	}
-}
+package de.tudarmstadt.informatik.hostage.deprecated;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+
+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;
+import de.tudarmstadt.informatik.hostage.logging.Record;
+import de.tudarmstadt.informatik.hostage.logging.Record.TYPE;
+import de.tudarmstadt.informatik.hostage.model.Profile;
+import de.tudarmstadt.informatik.hostage.ui.LogFilter;
+
+/**
+ * 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 UglyDbHelper extends SQLiteOpenHelper {
+
+	// All Static variables
+	// Database Version
+	private static final int DATABASE_VERSION = 1;
+
+	// Database Name
+	private static final String DATABASE_NAME = "hostage.db";
+
+	// Contacts table names
+	private static final String TABLE_ATTACK_INFO = "attack";
+	private static final String TABLE_RECORDS = "packet";
+	private static final String TABLE_BSSIDS = "network";
+	private static final String TABLE_PROFILES = "profiles";
+
+	// 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 = "packet_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_PORT = "localPort";
+	public static final String KEY_REMOTE_IP = "remoteIP";
+	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";
+	public static final String KEY_GEO_TIMESTAMP = "geo_timestamp";
+
+	public static final String KEY_PROFILE_ID = "_profile_id";
+	public static final String KEY_PROFILE_NAME = "profile_name";
+	public static final String KEY_PROFILE_DESCRIPTION = "profile_description";
+	public static final String KEY_PROFILE_ICON = "profile_icon";
+	public static final String KEY_PROFILE_EDITABLE = "profile_editable";
+	public static final String KEY_PROFILE_ACTIVE = "profile_active";
+	public static final String KEY_PROFILE_ICON_NAME = "profile_icon_name";
+
+	// Database sql create statements
+	private static final String CREATE_PROFILE_TABLE = "CREATE TABLE " + TABLE_PROFILES + "(" + KEY_PROFILE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+			+ KEY_PROFILE_NAME + " TEXT," + KEY_PROFILE_DESCRIPTION + " TEXT," + KEY_PROFILE_ICON + " TEXT," + KEY_PROFILE_ICON_NAME + " TEXT,"
+			+ KEY_PROFILE_EDITABLE + " INTEGER," + KEY_PROFILE_ACTIVE + " INTEGER" + ")";
+
+	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_PORT + " INTEGER," + KEY_REMOTE_IP + " BLOB," + KEY_REMOTE_PORT
+			+ " INTEGER," + KEY_BSSID + " TEXT," + "FOREIGN KEY(" + KEY_BSSID + ") REFERENCES " + TABLE_BSSIDS + "(" + KEY_BSSID + ")" + ")";
+
+	private static final String CREATE_BSSID_TABLE = "CREATE TABLE " + TABLE_BSSIDS + "(" + KEY_BSSID + " TEXT PRIMARY KEY," + KEY_SSID + " TEXT,"
+			+ KEY_LATITUDE + " INTEGER," + KEY_LONGITUDE + " INTEGER," + KEY_ACCURACY + " INTEGER," + KEY_GEO_TIMESTAMP + " INTEGER" + ")";
+
+	public UglyDbHelper(Context context) {
+		super(context, DATABASE_NAME, null, DATABASE_VERSION);
+	}
+
+	/*
+	 * // Contacts Table Columns names private static final String KEY_ID =
+	 * "_id"; private static final String KEY_ATTACK_ID = "_attack_id"; private
+	 * static final String KEY_TYPE = "type"; private static final String
+	 * KEY_TIME = "timestamp"; private static final String KEY_PACKET =
+	 * "packet"; private static final String KEY_PROTOCOL = "protocol"; private
+	 * static final String KEY_EXTERNAL_IP ="externalIP"; private static final
+	 * String KEY_LOCAL_IP = "localIP"; private static final String
+	 * KEY_LOCAL_HOSTNAME = "localHostName"; private static final String
+	 * KEY_LOCAL_PORT = "localPort"; private static final String KEY_REMOTE_IP =
+	 * "remoteIP"; private static final String KEY_REMOTE_HOSTNAME =
+	 * "remoteHostName"; private static final String KEY_REMOTE_PORT =
+	 * "remotePort"; private static final String KEY_BSSID = "_bssid"; private
+	 * static final String KEY_SSID = "ssid"; private static final String
+	 * KEY_LATITUDE = "latitude"; private static final String KEY_LONGITUDE =
+	 * "longitude"; private static final String KEY_ACCURACY = "accuracy";
+	 */
+
+	/**
+	 * Gets all received {@link Record Records} for the specified information in
+	 * the LogFilter ordered by date.
+	 * 
+	 * @return A ArrayList with all received {@link Record Records} for the
+	 *         LogFilter.
+	 */
+	public ArrayList<Record> getRecordsForFilter(LogFilter filter) {
+		ArrayList<Record> recordList = new ArrayList<Record>();
+		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID
+				+ ")";
+
+		// TIMESTAMPS
+		selectQuery = selectQuery + " WHERE " + TABLE_RECORDS + "." + KEY_TIME;
+		selectQuery = selectQuery + " < " + filter.getBelowTimestamp();
+		selectQuery = selectQuery + " AND " + TABLE_RECORDS + "." + KEY_TIME;
+		selectQuery = selectQuery + " > " + filter.getAboveTimestamp();
+
+		if (filter.getBSSIDs() != null && filter.getBSSIDs().size() > 0) {
+			selectQuery = selectQuery + " AND ";
+			selectQuery = selectQuery + filter.getBSSIDQueryStatement(TABLE_BSSIDS, KEY_BSSID);
+		}
+		if (filter.getESSIDs() != null && filter.getESSIDs().size() > 0) {
+			selectQuery = selectQuery + " AND ";
+			selectQuery = selectQuery + filter.getESSIDQueryStatement(TABLE_BSSIDS, KEY_SSID);
+		}
+		if (filter.getProtocols() != null && filter.getProtocols().size() > 0) {
+			selectQuery = selectQuery + " AND ";
+			selectQuery = selectQuery + filter.getProtocolsQueryStatement(TABLE_ATTACK_INFO, KEY_PROTOCOL);
+		}
+
+		selectQuery = selectQuery + " GROUP BY " + TABLE_RECORDS + "." + KEY_ATTACK_ID;
+
+		if (filter.getSorttype() == LogFilter.SortType.packet_timestamp) {
+			// DESC
+			selectQuery = selectQuery + " ORDER BY " + filter.getSorttype() + " DESC";
+		} else {
+			selectQuery = selectQuery + " ORDER BY " + filter.getSorttype();
+		}
+
+		System.out.println(selectQuery);
+		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 all non duplicate Records For the key BSSID.
+	 * 
+	 * @return A ArrayList with received Records.
+	 */
+	public ArrayList<String> getUniqueBSSIDRecords() {
+		return this.getUniqueDataEntryForKeyType(KEY_BSSID, TABLE_BSSIDS);
+	}
+
+	/**
+	 * Gets all non duplicate Records For the key ESSID.
+	 * 
+	 * @return A ArrayList with received Records.
+	 */
+	public ArrayList<String> getUniqueESSIDRecords() {
+		return this.getUniqueDataEntryForKeyType(KEY_SSID, TABLE_BSSIDS);
+	}
+
+	public ArrayList<String> getUniqueESSIDRecordsForProtocol(String protocol) {
+		return this.getUniqueIDForProtocol(KEY_SSID, protocol);
+	}
+
+	public ArrayList<String> getUniqueBSSIDRecordsForProtocol(String protocol) {
+		return this.getUniqueIDForProtocol(KEY_BSSID, protocol);
+	}
+
+	private ArrayList<String> getUniqueIDForProtocol(String id, String protocol) {
+		ArrayList<String> recordList = new ArrayList<String>();
+		String selectQuery = "SELECT DISTINCT " + id + " FROM " + TABLE_ATTACK_INFO + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ") " + " WHERE "
+				+ TABLE_ATTACK_INFO + "." + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " ORDER BY " + id; // " NATURAL JOIN "
+																												// +
+																												// TABLE_ATTACK_INFO
+																												// +
+																												// " NATURAL JOIN "
+																												// +
+																												// TABLE_BSSIDS
+																												// +
+																												// " NATURAL JOIN "
+																												// +
+																												// TABLE_PORTS
+																												// +
+
+		// ORDERED BY TIME
+		System.out.println(selectQuery);
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+
+		// looping through all rows and adding to list
+		if (cursor.moveToFirst()) {
+			do {
+				String record = cursor.getString(0);
+				recordList.add(record);
+			} while (cursor.moveToNext());
+		}
+		cursor.close();
+
+		// return record list
+		db.close();
+		return recordList;
+	}
+
+	/**
+	 * Gets all non duplicate Data Entry For a specific KeyType ( e.g. BSSIDs).
+	 * 
+	 * @return A ArrayList with received Records.
+	 */
+	public ArrayList<String> getUniqueDataEntryForKeyType(String keyType, String table) {
+		ArrayList<String> recordList = new ArrayList<String>();
+		// String selectQuery = "SELECT  * FROM " + TABLE_RECORDS +
+		// " NATURAL JOIN " + TABLE_ATTACK_INFO + " NATURAL JOIN " +
+		// TABLE_BSSIDS + " NATURAL JOIN " + TABLE_PORTS;
+		String selectQuery = "SELECT DISTINCT " + keyType + " FROM " + table + " ORDER BY " + keyType; // " NATURAL JOIN "
+																										// +
+																										// TABLE_ATTACK_INFO
+																										// +
+																										// " NATURAL JOIN "
+																										// +
+																										// TABLE_BSSIDS
+																										// +
+																										// " NATURAL JOIN "
+																										// +
+																										// TABLE_PORTS
+																										// +
+
+		// ORDERED BY TIME
+		System.out.println(selectQuery);
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+
+		// looping through all rows and adding to list
+		if (cursor.moveToFirst()) {
+			do {
+				String record = cursor.getString(0);
+				recordList.add(record);
+			} while (cursor.moveToNext());
+		}
+		cursor.close();
+
+		// return record list
+		db.close();
+		return recordList;
+	}
+
+	/**
+	 * 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()); // Log Local IP
+		attackValues.put(KEY_LOCAL_PORT, record.getLocalPort());
+		attackValues.put(KEY_REMOTE_IP, record.getRemoteIP()); // Log Remote IP
+		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);
+	}
+
+	/**
+	 * 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;
+	}
+
+	public int numBssidSeen(String BSSID) {
+		String countQuery = "SELECT  COUNT(*) FROM " + TABLE_ATTACK_INFO + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE "
+				+ TABLE_BSSIDS + "." + KEY_BSSID + " = " + "'" + BSSID + "'";
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(countQuery, null);
+		cursor.moveToFirst();
+		int result = cursor.getInt(0);
+		cursor.close();
+		db.close();
+		return result;
+	}
+
+	public int numBssidSeen(String protocol, String BSSID) {
+		String countQuery = "SELECT  COUNT(*) FROM " + TABLE_ATTACK_INFO + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE "
+				+ TABLE_ATTACK_INFO + "." + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " AND " + TABLE_BSSIDS + "." + KEY_BSSID + " = " + "'" + BSSID + "'";
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(countQuery, null);
+		cursor.moveToFirst();
+		int result = cursor.getInt(0);
+		cursor.close();
+		db.close();
+		return result;
+	}
+
+	/**
+	 * 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 + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID + ")" + " WHERE " + TABLE_ATTACK_INFO
+				+ "." + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " AND " + TABLE_BSSIDS + "." + KEY_BSSID + " = " + "'" + BSSID + "'";
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(countQuery, null);
+		int result = cursor.getCount();
+		cursor.close();
+		db.close();
+		return result > 0;
+	}
+
+	/**
+	 * 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.delete(TABLE_PROFILES, null, null);
+		db.close();
+	}
+
+	/**
+	 * 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();
+	}
+
+	/**
+	 * 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 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 + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID
+				+ ")" + " WHERE " + KEY_TYPE + "='RECEIVE'" + " ORDER BY " + TABLE_RECORDS + "." + 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 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 + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID
+				+ ")";
+
+		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;
+	}
+
+	/**
+	 * 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 getAttackPerProtocolCount(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 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;
+	}
+
+	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;
+	}
+
+	/**
+	 * 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 + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID
+				+ ")" + " WHERE " + TABLE_RECORDS + "." + 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;
+	}
+
+	/**
+	 * 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;
+	}
+
+	/**
+	 * 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 + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID
+				+ ")" + " WHERE " + TABLE_RECORDS + "." + KEY_ATTACK_ID + " = " + attack_id + " GROUP BY " + TABLE_RECORDS + "." + 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 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 + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID
+				+ ")" + " GROUP BY " + TABLE_RECORDS + "." + 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;
+	}
+
+	/*
+	 * Returns the Conversation of a specific attack id
+	 * 
+	 * @param attack_id Tha attack id to match the query against.
+	 * 
+	 * @return A arraylist with all {@link Record Records}s for an attack id.
+	 */
+	public ArrayList<Record> getConversationForAttackID(long attack_id) {
+		ArrayList<Record> recordList = new ArrayList<Record>();
+		String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_ATTACK_INFO + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID
+				+ ")" + " WHERE " + TABLE_RECORDS + "." + KEY_ATTACK_ID + " = " + attack_id;
+
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+
+		if (cursor.moveToFirst()) {
+			do {
+				Record record = createRecord(cursor);
+				recordList.add(record);
+			} while (cursor.moveToNext());
+		}
+		cursor.close();
+
+		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 + " JOIN " + TABLE_BSSIDS + " USING " + "(" + KEY_BSSID
+				+ ")" + " WHERE " + TABLE_RECORDS + "." + KEY_ATTACK_ID + " > " + attack_id + " GROUP BY " + TABLE_RECORDS + "." + 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 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;
+	}
+
+	/**
+	 * 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;
+	}
+
+	// Creating Tables
+	@Override
+	public void onCreate(SQLiteDatabase db) {
+		db.execSQL(CREATE_BSSID_TABLE);
+		db.execSQL(CREATE_ATTACK_INFO_TABLE);
+		db.execSQL(CREATE_RECORD_TABLE);
+		db.execSQL(CREATE_PROFILE_TABLE);
+	}
+
+	// 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_PROFILES);
+
+		// Create tables again
+		onCreate(db);
+	}
+
+	/**
+	 * Retrieves all the profiles from the database
+	 * 
+	 * @return list of profiles
+	 */
+	public List<Profile> getAllProfiles() {
+		List<Profile> profiles = new LinkedList<Profile>();
+
+		// Select All Query
+		String selectQuery = "SELECT  * FROM " + TABLE_PROFILES;
+
+		SQLiteDatabase db = this.getWritableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+
+		// looping through all rows and adding to list
+		if (cursor.moveToFirst()) {
+			do {
+				Profile profile = new Profile(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getInt(5) == 1);
+
+				if (cursor.getInt(6) == 1) {
+					profile.mActivated = true;
+				}
+
+				profile.mIconName = cursor.getString(4);
+
+				// Adding record to list
+				profiles.add(profile);
+			} while (cursor.moveToNext());
+		}
+		cursor.close();
+		db.close();
+		// return record list
+		return profiles;
+	}
+
+	/**
+	 * Persists the given profile into the database
+	 * 
+	 * @param profile
+	 *            the profile which should be persisted
+	 * 
+	 * @return
+	 */
+	public long persistProfile(Profile profile) {
+		SQLiteDatabase db = this.getReadableDatabase();
+
+		ContentValues values = new ContentValues();
+
+		if (profile.mId != -1) {
+			values.put(KEY_PROFILE_ID, profile.mId);
+		}
+
+		values.put(KEY_PROFILE_NAME, profile.mLabel);
+		values.put(KEY_PROFILE_DESCRIPTION, profile.mText);
+		values.put(KEY_PROFILE_ICON, profile.mIconPath);
+		values.put(KEY_PROFILE_ICON_NAME, profile.mIconName);
+		values.put(KEY_PROFILE_ACTIVE, profile.mActivated);
+		values.put(KEY_PROFILE_EDITABLE, profile.mEditable);
+
+		return db.replace(TABLE_PROFILES, null, values);
+	}
+
+	/**
+	 * private static final String CREATE_PROFILE_TABLE = "CREATE TABLE " +
+	 * TABLE_PROFILES + "(" + KEY_PROFILE_ID +
+	 * " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_PROFILE_NAME + " TEXT," +
+	 * KEY_PROFILE_DESCRIPTION + " TEXT," + KEY_PROFILE_ICON + " TEXT," +
+	 * KEY_PROFILE_ICON_ID + " INTEGER," + KEY_PROFILE_EDITABLE + " INTEGER," +
+	 * KEY_PROFILE_ACTIVE + " INTEGER" + ")";
+	 */
+	public Profile getProfile(int id) {
+		String selectQuery = "SELECT  * FROM " + TABLE_PROFILES + " WHERE " + TABLE_PROFILES + "." + KEY_PROFILE_ID + " = " + id;
+		SQLiteDatabase db = this.getReadableDatabase();
+
+		Cursor cursor = db.rawQuery(selectQuery, null);
+		Profile profile = null;
+
+		if (cursor.moveToFirst()) {
+			profile = new Profile(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getInt(5) == 1);
+
+			if (cursor.getInt(6) == 1) {
+				profile.mActivated = true;
+			}
+
+			profile.mIconName = cursor.getString(5);
+		}
+
+		cursor.close();
+		db.close();
+
+		// return contact
+		return profile;
+	}
+
+	public void deleteProfile(int id) {
+		SQLiteDatabase db = this.getReadableDatabase();
+
+		db.delete(TABLE_PROFILES, KEY_PROFILE_ID + "=?", new String[] { String.valueOf(id) });
+	}
+
+	public void updateNetworkInformation(ArrayList<HashMap<String, Object>> networkInformation) {
+		Log.i("DatabaseHandler", "Starte updating");
+		for (HashMap<String, Object> values : networkInformation) {
+			updateNetworkInformation(values);
+		}
+	}
+
+	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();
+	}
+
+	/**
+	 * 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();
+		record.setId(Integer.parseInt(cursor.getString(0)));
+		record.setAttack_id(cursor.getLong(1));
+		record.setType(TYPE.valueOf(cursor.getString(2)));
+		record.setTimestamp(cursor.getLong(3));
+		record.setPacket(cursor.getString(4));
+		record.setProtocol(cursor.getString(5));
+		record.setExternalIP(cursor.getString(6));
+
+		record.setLocalIP(cursor.getString(7));
+		record.setLocalPort(Integer.parseInt(cursor.getString(8)));
+
+		record.setRemoteIP(cursor.getString(9));
+		record.setRemotePort(Integer.parseInt(cursor.getString(10)));
+
+		record.setBssid(cursor.getString(11));
+		record.setSsid(cursor.getString(12));
+		record.setLatitude(Double.parseDouble(cursor.getString(13)));
+		record.setLongitude(Double.parseDouble(cursor.getString(14)));
+		record.setAccuracy(Float.parseFloat(cursor.getString(15)));
+		record.setTimestampLocation(cursor.getLong(16));
+
+		return record;
+	}
+}

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/logging/MyLocationManager.java → src/de/tudarmstadt/informatik/hostage/location/MyLocationManager.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.logging;
+package de.tudarmstadt.informatik.hostage.location;
 
 import java.util.Timer;
 import java.util.TimerTask;
@@ -88,7 +88,7 @@ public class MyLocationManager {
 
 	/**
 	 * Start updating
-	 * {@link de.tudarmstadt.informatik.hostage.logging.MyLocationManager#newestLocatio
+	 * {@link de.tudarmstadt.informatik.hostage.location.MyLocationManager#newestLocatio
 	 * newestLocation} if a location provider is enabled and available.
 	 */
 	public void startUpdates() {

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

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

+ 3 - 276
src/de/tudarmstadt/informatik/hostage/logging/Logger.java

@@ -1,143 +1,15 @@
 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;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 
-/**
- * An {@link IntentService} subclass for handling asynchronous task requests in
- * a service on a separate handler thread.
- * 
- * @author Mihai Plasoianu
- */
 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 deleteAll(Context context) {
-		Intent intent = new Intent(context, Logger.class);
-		intent.setAction(ACTION_CLEAR_ALL);
-		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 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 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 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 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 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 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 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 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 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 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 log(Context context, Record record) {
 		Intent intent = new Intent(context, Logger.class);
@@ -146,7 +18,7 @@ public class Logger extends IntentService {
 		context.startService(intent);
 	}
 
-	private UglyDbHelper mDbHelper;
+	private HostageDBOpenHelper mDbHelper;
 
 	public Logger() {
 		super("Logger");
@@ -155,68 +27,9 @@ public class Logger extends IntentService {
 	@Override
 	public void onCreate() {
 		super.onCreate();
-		mDbHelper = new UglyDbHelper(getApplicationContext());
-	}
-
-	private boolean handleActionBssidSeen(String protocol, String bssid) {
-		return mDbHelper.bssidSeen(protocol, bssid);
-	}
-
-	/**
-	 * Delete all records.
-	 */
-	private void handleActionDeleteAll() {
-		mDbHelper.clearData();
-	}
-
-	private void handleActionDeleteByBssid(String bssid) {
-		mDbHelper.deleteByBSSID(bssid);
-	}
-
-	private void handleActionDeleteByDate(long time) {
-		mDbHelper.deleteByDate(time);
-	}
-
-	private String[] handleActionGetAllBssids() {
-		return mDbHelper.getAllBSSIDS();
-	}
-
-	private ArrayList<Record> handleActionGetAllRecords() {
-		return mDbHelper.getAllRecords();
-	}
-
-	private int handleActionGetAttackCount() {
-		return mDbHelper.getAttackCount();
-	}
-
-	private int handleActionGetAttackPerProtocolCount(String protocol) {
-		return mDbHelper.getAttackPerProtocolCount(protocol);
-	}
-
-	private long handleActionGetMaxAttackId() {
-		return mDbHelper.getHighestAttackId();
-	}
-
-	private long handleActionGetMinAttackId() {
-		return mDbHelper.getSmallestAttackId();
-	}
-
-	private Record handleActionGetRecordOfAttackId(long attack_id) {
-		return mDbHelper.getRecordOfAttackId(attack_id);
-	}
-
-	private ArrayList<Record> handleActionGetRecordOfEachAttack(
-			int lastUploadedAttackId) {
-		return mDbHelper.getRecordOfEachAttack(lastUploadedAttackId);
-	}
-
-	private String handleActionGetSsid(String bssid) {
-		return mDbHelper.getSSID(bssid);
+		mDbHelper = new HostageDBOpenHelper(getApplicationContext());
 	}
 
-	/**
-	 * Log a record.
-	 */
 	private void handleActionLog(Record record) {
 		mDbHelper.addRecord(record);
 	}
@@ -228,92 +41,6 @@ public class Logger extends IntentService {
 			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();
 			}
 		}
 	}

+ 0 - 34
src/de/tudarmstadt/informatik/hostage/logging/Record.java

@@ -4,18 +4,6 @@ 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
- * {@link de.tudarmstadt.informatik.hostage.ui.ViewLog ViewLog}
- * 
- * @author Mihai Plasoianu
- * @author Lars Pandikow
- */
 public class Record implements Parcelable {
 
 	public static enum TYPE {
@@ -32,10 +20,8 @@ public class Record implements Parcelable {
 
 	// network
 	private String localIP;
-	private String localHost;
 	private int localPort;
 	private String remoteIP;
-	private String remoteHost;
 	private int remotePort;
 	private String externalIP;
 	private String bssid;
@@ -74,10 +60,8 @@ public class Record implements Parcelable {
 
 		// 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();
@@ -119,10 +103,6 @@ public class Record implements Parcelable {
 		return latitude;
 	}
 
-	public String getLocalHost() {
-		return localHost;
-	}
-
 	public String getLocalIP() {
 		return localIP;
 	}
@@ -143,10 +123,6 @@ public class Record implements Parcelable {
 		return protocol;
 	}
 
-	public String getRemoteHost() {
-		return remoteHost;
-	}
-
 	public String getRemoteIP() {
 		return remoteIP;
 	}
@@ -195,10 +171,6 @@ public class Record implements Parcelable {
 		this.latitude = latitude;
 	}
 
-	public void setLocalHost(String localHost) {
-		this.localHost = localHost;
-	}
-
 	public void setLocalIP(String localIP) {
 		this.localIP = localIP;
 	}
@@ -219,10 +191,6 @@ public class Record implements Parcelable {
 		this.protocol = protocol;
 	}
 
-	public void setRemoteHost(String remoteHost) {
-		this.remoteHost = remoteHost;
-	}
-
 	public void setRemoteIP(String remoteIP) {
 		this.remoteIP = remoteIP;
 	}
@@ -271,10 +239,8 @@ public class Record implements Parcelable {
 
 		// 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);

+ 1 - 3
src/de/tudarmstadt/informatik/hostage/logging/formatter/TraCINgFormatter.java

@@ -17,9 +17,7 @@ public class TraCINgFormatter extends Formatter {
 	public synchronized String format(Record record) {
 		return String
 				.format("{ \"sensor\":{\"type\": \"Honeypot\", \"name\": \"HosTaGe\"}, \"type\": \"%s server access\", \"src\":{\"ip\": \"%s\", \"port\": %d}, \"dst\":{\"ip\": \"%s\", \"port\": %d} }",
-						record.getProtocol(), record.getRemoteIP(),
-						record.getRemotePort(), record.getExternalIP(),
-						record.getLocalPort());
+						record.getProtocol(), record.getRemoteIP(), record.getRemotePort(), record.getExternalIP(), record.getLocalPort());
 	}
 
 }

+ 12 - 0
src/de/tudarmstadt/informatik/hostage/model/JSONSerializable.java

@@ -0,0 +1,12 @@
+package de.tudarmstadt.informatik.hostage.model;
+
+import org.json.JSONObject;
+
+/**
+ * @author Alexander Brakowski
+ * @created 23.03.14 11:45
+ */
+public interface JSONSerializable<T> {
+	public T fromJSON(JSONObject json);
+	public JSONObject toJSON();
+}

+ 57 - 5
src/de/tudarmstadt/informatik/hostage/model/Profile.java

@@ -1,5 +1,8 @@
 package de.tudarmstadt.informatik.hostage.model;
 
+import org.json.JSONException;
+import org.json.JSONObject;
+
 import android.content.Context;
 import android.content.SharedPreferences;
 import android.graphics.Bitmap;
@@ -12,6 +15,7 @@ import android.os.Parcelable;
 
 import java.io.Serializable;
 import java.util.HashMap;
+import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
@@ -22,9 +26,7 @@ import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
  * @author Alexander Brakowski
  * @created 14.01.14 18:04
  */
-public class Profile implements Serializable {
-	private static final long serialVersionUID = 8L;
-
+public class Profile implements JSONSerializable<Profile> {
 	public String mText;
 	public String mLabel;
 	public int mId;
@@ -32,16 +34,15 @@ public class Profile implements Serializable {
 	transient public Bitmap mIcon;
 	transient public int mIconId;
 	public String mIconName;
-
 	public String mIconPath;
 
-	public boolean mIsBackVisible = false;
 	public boolean mEditable = false;
 	public boolean mIsRandom = false;
 
 	public HashMap<String, Boolean> mActiveProtocols = new HashMap<String, Boolean>();
 	public String mGhostPorts = "";
 	public boolean mGhostActive = false;
+	public boolean mShowTooltip = false;
 
 	public Profile(){
 		this.mEditable = true;
@@ -158,4 +159,55 @@ public class Profile implements Serializable {
 
 		return ports;
 	}
+
+	public JSONObject toJSON(){
+		JSONObject jsonObj = new JSONObject();
+
+		try {
+			jsonObj.put("text", mText);
+			jsonObj.put("label", mLabel);
+			jsonObj.put("id", mId);
+			jsonObj.put("activated", mActivated);
+			jsonObj.put("icon_name", mIconName);
+			jsonObj.put("icon_path", mIconPath);
+			jsonObj.put("editable", mEditable);
+			jsonObj.put("random", mIsRandom);
+			jsonObj.put("ghost_active", mGhostActive);
+			jsonObj.put("ghost_ports", mGhostPorts);
+			jsonObj.put("active_protocols", new JSONObject(mActiveProtocols));
+		} catch (JSONException e) {
+			e.printStackTrace();
+		}
+
+		return jsonObj;
+	}
+
+	public Profile fromJSON(JSONObject json){
+		mText = json.optString("text", "");
+		mLabel = json.optString("label", "");
+		mId = json.optInt("id", -1);
+		mActivated = json.optBoolean("activated", false);
+		mIconName = json.optString("icon_name", null);
+		mIconPath = json.optString("icon_path", null);
+		mEditable = json.optBoolean("editable", true);
+		mIsRandom = json.optBoolean("random", false);
+		mGhostActive = json.optBoolean("ghost_active", false);
+		mGhostPorts = json.optString("ghost_ports", "");
+
+		JSONObject activeProtocols = json.optJSONObject("active_protocols");
+		if(activeProtocols != null){
+			Iterator keys = activeProtocols.keys();
+
+			while(keys.hasNext()){
+				String protocol = (String) keys.next();
+				try {
+					mActiveProtocols.put(protocol, activeProtocols.getBoolean(protocol));
+				} catch (JSONException e) {
+					e.printStackTrace();
+				}
+			}
+		}
+
+		return this;
+	}
 }

+ 0 - 13
src/de/tudarmstadt/informatik/hostage/model/ProfilesHolder.java

@@ -1,13 +0,0 @@
-package de.tudarmstadt.informatik.hostage.model;
-
-import java.io.Serializable;
-import java.util.HashMap;
-
-/**
- * @author Alexander Brakowski
- * @created 07.03.14 00:23
- */
-public class ProfilesHolder implements Serializable {
-	public int mIncrementValue = 1;
-	public HashMap<Integer, Profile> mProfiles;
-}

+ 47 - 0
src/de/tudarmstadt/informatik/hostage/net/MyDatagramSocketFactory.java

@@ -0,0 +1,47 @@
+package de.tudarmstadt.informatik.hostage.net;
+
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.net.DatagramSocket;
+import java.net.DatagramSocketImpl;
+
+import de.tudarmstadt.informatik.hostage.system.Device;
+import de.tudarmstadt.informatik.hostage.system.PrivilegedPort;
+import de.tudarmstadt.informatik.hostage.system.PrivilegedPort.TYPE;
+
+public class MyDatagramSocketFactory {
+
+	public DatagramSocket createDatagramSocket(int port) throws IOException {
+		DatagramSocket socket = null;
+		if (port > 1023) {
+			socket = new DatagramSocket(port);
+		} else if (Device.isPorthackInstalled()) {
+			FileDescriptor fd = new PrivilegedPort(TYPE.UDP, port).getFD();
+			socket = new DatagramSocket();
+			try {
+				DatagramSocketImpl impl = getImpl(socket);
+				injectFD(fd, impl);
+			} catch (NoSuchFieldException e) {
+			} catch (IllegalAccessException e) {
+			} catch (IllegalArgumentException e) {
+			}
+		}
+		return socket;
+	}
+
+	private DatagramSocketImpl getImpl(DatagramSocket socket) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
+		Field implField = socket.getClass().getDeclaredField("impl");
+		implField.setAccessible(true);
+		return (DatagramSocketImpl) implField.get(socket);
+	}
+
+	private void injectFD(FileDescriptor fd, DatagramSocketImpl impl) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
+		Class<?> plainDatagramSocketImplClazz = impl.getClass();
+		Class<?> datagramSocketImplClazz = plainDatagramSocketImplClazz.getSuperclass();
+		Field fdField = datagramSocketImplClazz.getDeclaredField("fd");
+		fdField.setAccessible(true);
+		fdField.set(impl, fd);
+	}
+
+}

+ 14 - 50
src/de/tudarmstadt/informatik/hostage/net/MyServerSocketFactory.java

@@ -10,21 +10,13 @@ import java.net.SocketImpl;
 
 import javax.net.ServerSocketFactory;
 
-import de.tudarmstadt.informatik.hostage.system.P;
+import de.tudarmstadt.informatik.hostage.system.Device;
+import de.tudarmstadt.informatik.hostage.system.PrivilegedPort;
+import de.tudarmstadt.informatik.hostage.system.PrivilegedPort.TYPE;
 import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
 
-/**
- * Server Socket Factory using file descriptors.
- * 
- * @author Mihai Plasoianu
- * @author Lars Pandikow
- */
 public class MyServerSocketFactory extends ServerSocketFactory {
 
-	/**
-	 * This method creates and returns a ServerSocket. A custom SocketImpl is
-	 * injected into the ServerSocket.
-	 */
 	@Override
 	public ServerSocket createServerSocket(int port) throws IOException {
 		ServerSocket socket = null;
@@ -32,75 +24,47 @@ public class MyServerSocketFactory extends ServerSocketFactory {
 			socket = new ServerSocket();
 			socket.setReuseAddress(true);
 			socket.bind(new InetSocketAddress(port));
-		} else if (MainActivity.porthackInstalled) {
-			FileDescriptor fd = new P(port).bindAndGetFD();
+		} else if (Device.isPorthackInstalled()) {
+			FileDescriptor fd = new PrivilegedPort(TYPE.TCP, port).getFD();
 			socket = new ServerSocket();
 			try {
 				SocketImpl impl = getImpl(socket);
 				injectFD(fd, impl);
-				injectImpl(impl, socket);
 				setBound(socket);
-			} catch (Exception e) {
-				e.printStackTrace();
+			} catch (NoSuchFieldException e) {
+			} catch (IllegalAccessException e) {
+			} catch (IllegalArgumentException e) {
 			}
 		}
 		return socket;
 	}
 
-	/**
-	 * Must override.
-	 */
 	@Override
-	public ServerSocket createServerSocket(int port, int backlog)
-			throws IOException {
+	public ServerSocket createServerSocket(int port, int backlog) throws IOException {
 		return createServerSocket(port);
 	}
 
-	/**
-	 * Must override.
-	 */
 	@Override
-	public ServerSocket createServerSocket(int port, int backlog,
-			InetAddress iAddress) throws IOException {
+	public ServerSocket createServerSocket(int port, int backlog, InetAddress iAddress) throws IOException {
 		return createServerSocket(port);
 	}
 
-	/**
-	 * Extracts the SocketImpl out of a ServerSocket.
-	 */
-	private SocketImpl getImpl(ServerSocket socket) throws Exception {
+	private SocketImpl getImpl(ServerSocket socket) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
 		Field implField = socket.getClass().getDeclaredField("impl");
 		implField.setAccessible(true);
 		return (SocketImpl) implField.get(socket);
 	}
 
-	/**
-	 * Injects a FileDescriptor into a SocketImpl.
-	 */
-	private void injectFD(FileDescriptor fd, SocketImpl impl) throws Exception {
+	private void injectFD(FileDescriptor fd, SocketImpl impl) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
 		Class<?> plainServerSocketImplClazz = impl.getClass();
-		Class<?> plainSocketImplClazz = plainServerSocketImplClazz
-				.getSuperclass();
+		Class<?> plainSocketImplClazz = plainServerSocketImplClazz.getSuperclass();
 		Class<?> socketImplClazz = plainSocketImplClazz.getSuperclass();
 		Field fdField = socketImplClazz.getDeclaredField("fd");
 		fdField.setAccessible(true);
 		fdField.set(impl, fd);
 	}
 
-	/**
-	 * Injects a SocketImpl into a ServerSocket.
-	 */
-	private void injectImpl(SocketImpl impl, ServerSocket socket)
-			throws Exception {
-		Field implField = socket.getClass().getDeclaredField("impl");
-		implField.setAccessible(true);
-		implField.set(socket, impl);
-	}
-
-	/**
-	 * Sets the isBound Field of a ServerSocket to true.
-	 */
-	private void setBound(ServerSocket socket) throws Exception {
+	private void setBound(ServerSocket socket) throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
 		Field boundField = socket.getClass().getDeclaredField("isBound");
 		boundField.setAccessible(true);
 		boundField.set(socket, true);

+ 4 - 3
src/de/tudarmstadt/informatik/hostage/nio/Reader.java

@@ -10,18 +10,19 @@ import de.tudarmstadt.informatik.hostage.wrapper.Packet;
 public class Reader {
 
 	BufferedInputStream in;
+	String protocol;
 
-	public Reader(InputStream in) {
+	public Reader(InputStream in, String protocol) {
 		this.in = new BufferedInputStream(in);
+		this.protocol = protocol;
 	}
 
 	public Packet read() throws IOException {
 		ByteArrayOutputStream payload = new ByteArrayOutputStream();
 		do {
 			payload.write(in.read());
-			Thread.yield();
 		} while (in.available() > 0);
-		return new Packet(payload.toByteArray());
+		return new Packet(payload.toByteArray(), protocol);
 	}
 
 }

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

@@ -18,7 +18,6 @@ public class Writer {
 	public void write(List<Packet> packets) throws IOException {
 		for (Packet packet : packets) {
 			out.write(packet.getBytes());
-			out.write('\n');
 		}
 		out.flush();
 	}

+ 44 - 0
src/de/tudarmstadt/informatik/hostage/persistence/HostageDBContract.java

@@ -0,0 +1,44 @@
+package de.tudarmstadt.informatik.hostage.persistence;
+
+import android.provider.BaseColumns;
+
+public final class HostageDBContract {
+
+	public static abstract class NetworkEntry implements BaseColumns {
+		public static final String TABLE_NAME = "network";
+		public static final String COLUMN_NAME_BSSID = "_bssid";
+		public static final String COLUMN_NAME_SSID = "ssid";
+		public static final String COLUMN_NAME_LATITUDE = "latitude";
+		public static final String COLUMN_NAME_LONGITUDE = "longitude";
+		public static final String COLUMN_NAME_ACCURACY = "accuracy";
+		public static final String COLUMN_NAME_GEO_TIMESTAMP = "geo_timestamp";
+
+		public static final String KEY_ID = COLUMN_NAME_BSSID;
+	}
+
+	public static abstract class AttackEntry implements BaseColumns {
+		public static final String TABLE_NAME = "attack";
+		public static final String COLUMN_NAME_ATTACK_ID = "_attack_id";
+		public static final String COLUMN_NAME_PROTOCOL = "protocol";
+		public static final String COLUMN_NAME_EXTERNAL_IP = "externalIP";
+		public static final String COLUMN_NAME_LOCAL_IP = "localIP";
+		public static final String COLUMN_NAME_LOCAL_PORT = "localPort";
+		public static final String COLUMN_NAME_REMOTE_IP = "remoteIP";
+		public static final String COLUMN_NAME_REMOTE_PORT = "remotePort";
+		public static final String COLUMN_NAME_BSSID = "_bssid";
+
+		public static final String KEY_ID = COLUMN_NAME_ATTACK_ID;
+	}
+
+	public static abstract class PacketEntry implements BaseColumns {
+		public static final String TABLE_NAME = "packet";
+		public static final String COLUMN_NAME_ID = "_id";
+		public static final String COLUMN_NAME_ATTACK_ID = "_attack_id";
+		public static final String COLUMN_NAME_TYPE = "type";
+		public static final String COLUMN_NAME_PACKET_TIMESTAMP = "packet_timestamp";
+		public static final String COLUMN_NAME_PACKET = "packet";
+
+		public static final String KEY_ID = COLUMN_NAME_ID;
+	}
+
+}

+ 626 - 0
src/de/tudarmstadt/informatik/hostage/persistence/HostageDBOpenHelper.java

@@ -0,0 +1,626 @@
+package de.tudarmstadt.informatik.hostage.persistence;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+
+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;
+import de.tudarmstadt.informatik.hostage.logging.Record;
+import de.tudarmstadt.informatik.hostage.logging.Record.TYPE;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.AttackEntry;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.NetworkEntry;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.PacketEntry;
+
+public class HostageDBOpenHelper extends SQLiteOpenHelper {
+
+	private static final String DATABASE_NAME = "hostage.db";
+	private static final int DATABASE_VERSION = 1;
+
+	static {
+		StringBuilder networkSQLBuilder = new StringBuilder("CREATE TABLE ").append(NetworkEntry.TABLE_NAME).append("(");
+		networkSQLBuilder.append(NetworkEntry.COLUMN_NAME_BSSID).append(" TEXT PRIMARY KEY,");
+		networkSQLBuilder.append(NetworkEntry.COLUMN_NAME_SSID).append(" TEXT,");
+		networkSQLBuilder.append(NetworkEntry.COLUMN_NAME_LATITUDE).append(" INTEGER,");
+		networkSQLBuilder.append(NetworkEntry.COLUMN_NAME_LONGITUDE).append(" INTEGER,");
+		networkSQLBuilder.append(NetworkEntry.COLUMN_NAME_ACCURACY).append(" INTEGER,");
+		networkSQLBuilder.append(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP).append(" INTEGER");
+		networkSQLBuilder.append(")");
+		SQL_CREATE_NETWORK_ENTRIES = networkSQLBuilder.toString();
+
+		StringBuilder attackSQLBuilder = new StringBuilder("CREATE TABLE ").append(AttackEntry.TABLE_NAME).append("(");
+		attackSQLBuilder.append(AttackEntry.COLUMN_NAME_ATTACK_ID).append(" INTEGER PRIMARY KEY,");
+		attackSQLBuilder.append(AttackEntry.COLUMN_NAME_PROTOCOL).append(" TEXT,");
+		attackSQLBuilder.append(AttackEntry.COLUMN_NAME_EXTERNAL_IP).append(" TEXT,");
+		attackSQLBuilder.append(AttackEntry.COLUMN_NAME_LOCAL_IP).append(" BLOB,");
+		attackSQLBuilder.append(AttackEntry.COLUMN_NAME_LOCAL_PORT).append(" INTEGER,");
+		attackSQLBuilder.append(AttackEntry.COLUMN_NAME_REMOTE_IP).append(" BLOB,");
+		attackSQLBuilder.append(AttackEntry.COLUMN_NAME_REMOTE_PORT).append(" INTEGER,");
+		attackSQLBuilder.append(AttackEntry.COLUMN_NAME_BSSID).append(" TEXT,");
+		attackSQLBuilder.append(String.format("FOREIGN KEY(%s) REFERENCES %s(%s)", AttackEntry.COLUMN_NAME_BSSID, NetworkEntry.TABLE_NAME,
+				NetworkEntry.COLUMN_NAME_BSSID));
+		attackSQLBuilder.append(")");
+		SQL_CREATE_ATTACK_ENTRIES = attackSQLBuilder.toString();
+
+		StringBuilder packetSQLBuilder = new StringBuilder("CREATE TABLE ").append(PacketEntry.TABLE_NAME).append("(");
+		packetSQLBuilder.append(PacketEntry.COLUMN_NAME_ID).append(" INTEGER NOT NULL,");
+		packetSQLBuilder.append(PacketEntry.COLUMN_NAME_ATTACK_ID).append(" INTEGER NOT NULL,");
+		packetSQLBuilder.append(PacketEntry.COLUMN_NAME_TYPE).append(" TEXT,");
+		packetSQLBuilder.append(PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP).append(" INTEGER,");
+		packetSQLBuilder.append(PacketEntry.COLUMN_NAME_PACKET).append(" TEXT,");
+		packetSQLBuilder.append(String.format("PRIMARY KEY(%s,%s)", PacketEntry.COLUMN_NAME_ID, PacketEntry.COLUMN_NAME_ATTACK_ID));
+		packetSQLBuilder.append(String.format("FOREIGN KEY(%s) REFERENCES %s(%s)", PacketEntry.COLUMN_NAME_ATTACK_ID, AttackEntry.TABLE_NAME,
+				AttackEntry.COLUMN_NAME_ATTACK_ID));
+		packetSQLBuilder.append(")");
+		SQL_CREATE_PACKET_ENTRIES = packetSQLBuilder.toString();
+	}
+
+	private static final String SQL_CREATE_NETWORK_ENTRIES;
+	private static final String SQL_CREATE_ATTACK_ENTRIES;
+	private static final String SQL_CREATE_PACKET_ENTRIES;
+
+	private static final String SQL_DELETE_PACKET_ENTRIES = "DROP TABLE IF EXISTS " + PacketEntry.TABLE_NAME;
+	private static final String SQL_DELETE_ATTACK_ENTRIES = "DROP TABLE IF EXISTS " + AttackEntry.TABLE_NAME;
+	private static final String SQL_DELETE_NETWORK_ENTRIES = "DROP TABLE IF EXISTS " + NetworkEntry.TABLE_NAME;
+
+	public HostageDBOpenHelper(Context context) {
+		super(context, DATABASE_NAME, null, DATABASE_VERSION);
+	}
+
+	@Override
+	public void onCreate(SQLiteDatabase db) {
+		db.execSQL(SQL_CREATE_PACKET_ENTRIES);
+		db.execSQL(SQL_CREATE_ATTACK_ENTRIES);
+		db.execSQL(SQL_CREATE_NETWORK_ENTRIES);
+	}
+
+	@Override
+	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
+		db.execSQL(SQL_DELETE_PACKET_ENTRIES);
+		db.execSQL(SQL_DELETE_ATTACK_ENTRIES);
+		db.execSQL(SQL_DELETE_NETWORK_ENTRIES);
+		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(NetworkEntry.COLUMN_NAME_BSSID, record.getBssid());
+		bssidValues.put(NetworkEntry.COLUMN_NAME_SSID, record.getSsid());
+		bssidValues.put(NetworkEntry.COLUMN_NAME_LATITUDE, record.getLatitude());
+		bssidValues.put(NetworkEntry.COLUMN_NAME_LONGITUDE, record.getLongitude());
+		bssidValues.put(NetworkEntry.COLUMN_NAME_ACCURACY, record.getAccuracy());
+		bssidValues.put(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP, record.getTimestampLocation());
+
+		ContentValues attackValues = new ContentValues();
+		attackValues.put(AttackEntry.COLUMN_NAME_ATTACK_ID, record.getAttack_id()); // Log
+																					// Attack
+																					// ID
+		attackValues.put(AttackEntry.COLUMN_NAME_PROTOCOL, record.getProtocol().toString());
+		attackValues.put(AttackEntry.COLUMN_NAME_EXTERNAL_IP, record.getExternalIP());
+		attackValues.put(AttackEntry.COLUMN_NAME_LOCAL_IP, record.getLocalIP()); // Log
+																					// Local
+																					// IP
+		attackValues.put(AttackEntry.COLUMN_NAME_LOCAL_PORT, record.getLocalPort());
+		attackValues.put(AttackEntry.COLUMN_NAME_REMOTE_IP, record.getRemoteIP()); // Log
+																					// Remote
+																					// IP
+		attackValues.put(AttackEntry.COLUMN_NAME_REMOTE_PORT, record.getRemotePort()); // Log
+																						// Remote
+																						// Port
+		attackValues.put(AttackEntry.COLUMN_NAME_BSSID, record.getBssid());
+
+		ContentValues recordValues = new ContentValues();
+		recordValues.put(PacketEntry.COLUMN_NAME_ID, record.getId()); // Log
+																		// Message
+																		// Number
+		recordValues.put(PacketEntry.COLUMN_NAME_ATTACK_ID, record.getAttack_id()); // Log
+																					// Attack
+																					// ID
+		recordValues.put(PacketEntry.COLUMN_NAME_TYPE, record.getType().name()); // Log
+																					// Type
+		recordValues.put(PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP, record.getTimestamp()); // Log
+																							// Timestamp
+		recordValues.put(PacketEntry.COLUMN_NAME_PACKET, record.getPacket()); // Log
+																				// Packet
+
+		// Inserting Rows
+		db.insertWithOnConflict(AttackEntry.TABLE_NAME, null, attackValues, SQLiteDatabase.CONFLICT_REPLACE);
+		db.insert(PacketEntry.TABLE_NAME, null, recordValues);
+		db.close(); // Closing database connection
+		// Update Network Information
+		updateNetworkInformation(bssidValues);
+	}
+
+	/**
+	 * 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 " + NetworkEntry.TABLE_NAME + " WHERE " + NetworkEntry.COLUMN_NAME_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 " + AttackEntry.TABLE_NAME + " NATURAL JOIN " + NetworkEntry.TABLE_NAME + " WHERE "
+				+ AttackEntry.COLUMN_NAME_PROTOCOL + " = " + "'" + protocol + "'" + " AND " + NetworkEntry.COLUMN_NAME_BSSID + " = " + "'" + BSSID + "'";
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(countQuery, null);
+		int result = cursor.getCount();
+		cursor.close();
+		db.close();
+		return result > 0;
+	}
+
+	/**
+	 * Deletes all records from {@link #PacketEntry.TABLE_NAME}.
+	 */
+	public void clearData() {
+		SQLiteDatabase db = this.getReadableDatabase();
+		db.delete(PacketEntry.TABLE_NAME, null, null);
+		db.delete(AttackEntry.TABLE_NAME, null, null);
+		db.close();
+	}
+
+	/**
+	 * Deletes all records from {@link #PacketEntry.TABLE_NAME} with a specific BSSID.
+	 * 
+	 * @param bssid
+	 *            The BSSID to match against.
+	 */
+	public void deleteByBSSID(String bssid) {
+		SQLiteDatabase db = this.getReadableDatabase();
+		db.delete(NetworkEntry.TABLE_NAME, NetworkEntry.COLUMN_NAME_BSSID + " = ?", new String[] { bssid });
+		db.delete(AttackEntry.TABLE_NAME, AttackEntry.COLUMN_NAME_BSSID + " = ?", new String[] { bssid });
+		db.close();
+	}
+
+	/**
+	 * Deletes all records from {@link #PacketEntry.TABLE_NAME} 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 " + PacketEntry.TABLE_NAME + " WHERE " + PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP + " < " + date;
+		db.execSQL(deleteQuery);
+		db.close();
+	}
+
+	/**
+	 * Returns a String array with all BSSIDs stored in the database.
+	 * 
+	 * @return String[] of all recorded BSSIDs.
+	 */
+	public String[] getAllBSSIDS() {
+		String selectQuery = "SELECT  * FROM " + NetworkEntry.TABLE_NAME;
+		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 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 " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " NATURAL JOIN "
+				+ NetworkEntry.TABLE_NAME + " WHERE " + PacketEntry.COLUMN_NAME_TYPE + "='RECEIVE'" + " ORDER BY " + PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP;
+		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 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 " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " JOIN " + NetworkEntry.TABLE_NAME
+				+ " USING (_bssid)";
+
+		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;
+	}
+
+	/**
+	 * 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 " + AttackEntry.TABLE_NAME;
+		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 getAttackPerProtocolCount(String protocol) {
+		String countQuery = "SELECT  * FROM " + AttackEntry.TABLE_NAME + " WHERE " + AttackEntry.COLUMN_NAME_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 highest attack id stored in the database.
+	 * 
+	 * @return The highest attack id stored in the database.
+	 */
+	public long getHighestAttackId() {
+		String selectQuery = "SELECT MAX(" + AttackEntry.COLUMN_NAME_ATTACK_ID + ") FROM " + AttackEntry.TABLE_NAME;
+		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;
+	}
+
+	public ArrayList<HashMap<String, Object>> getNetworkInformation() {
+		String selectQuery = "SELECT  * FROM " + NetworkEntry.TABLE_NAME;
+		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(NetworkEntry.COLUMN_NAME_BSSID, cursor.getString(0));
+				values.put(NetworkEntry.COLUMN_NAME_SSID, cursor.getString(1));
+				values.put(NetworkEntry.COLUMN_NAME_LATITUDE, Double.parseDouble(cursor.getString(2)));
+				values.put(NetworkEntry.COLUMN_NAME_LONGITUDE, Double.parseDouble(cursor.getString(3)));
+				values.put(NetworkEntry.COLUMN_NAME_ACCURACY, Float.parseFloat(cursor.getString(4)));
+				values.put(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP, cursor.getLong(5));
+				networkInformation.add(values);
+			} while (cursor.moveToNext());
+		}
+
+		cursor.close();
+		db.close();
+		return networkInformation;
+	}
+
+	/**
+	 * 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 " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " NATURAL JOIN "
+				+ NetworkEntry.TABLE_NAME + " WHERE " + PacketEntry.COLUMN_NAME_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;
+	}
+
+	/**
+	 * 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 " + PacketEntry.TABLE_NAME;
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(countQuery, null);
+		int result = cursor.getCount();
+		cursor.close();
+
+		// return count
+		db.close();
+		return result;
+	}
+
+	/**
+	 * 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 " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " NATURAL JOIN "
+				+ NetworkEntry.TABLE_NAME + " WHERE " + AttackEntry.COLUMN_NAME_ATTACK_ID + " = " + attack_id + " GROUP BY "
+				+ AttackEntry.COLUMN_NAME_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 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 " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " NATURAL JOIN "
+				+ NetworkEntry.TABLE_NAME + " GROUP BY " + AttackEntry.COLUMN_NAME_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 " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " NATURAL JOIN "
+				+ NetworkEntry.TABLE_NAME + " WHERE " + AttackEntry.COLUMN_NAME_ATTACK_ID + " > " + attack_id + " GROUP BY "
+				+ AttackEntry.COLUMN_NAME_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 smallest attack id stored in the database.
+	 * 
+	 * @return The smallest attack id stored in the database.
+	 */
+	public long getSmallestAttackId() {
+		String selectQuery = "SELECT MIN(" + AttackEntry.COLUMN_NAME_ATTACK_ID + ") FROM " + AttackEntry.TABLE_NAME;
+		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;
+	}
+
+	/**
+	 * 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 " + NetworkEntry.COLUMN_NAME_SSID + " FROM " + NetworkEntry.TABLE_NAME + " WHERE " + NetworkEntry.COLUMN_NAME_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;
+	}
+
+	public void updateNetworkInformation(ArrayList<HashMap<String, Object>> networkInformation) {
+		Log.i("DatabaseHandler", "Starte updating");
+		for (HashMap<String, Object> values : networkInformation) {
+			updateNetworkInformation(values);
+		}
+	}
+
+	public void updateNetworkInformation(HashMap<String, Object> networkInformation) {
+		SQLiteDatabase db = this.getReadableDatabase();
+		String bssid = (String) networkInformation.get(NetworkEntry.COLUMN_NAME_BSSID);
+		String bssidQuery = "SELECT  * FROM " + NetworkEntry.TABLE_NAME + " WHERE " + NetworkEntry.COLUMN_NAME_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(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP)))
+			;
+		{
+			ContentValues bssidValues = new ContentValues();
+			bssidValues.put(NetworkEntry.COLUMN_NAME_BSSID, bssid);
+			bssidValues.put(NetworkEntry.COLUMN_NAME_SSID, (String) networkInformation.get(NetworkEntry.COLUMN_NAME_SSID));
+			bssidValues.put(NetworkEntry.COLUMN_NAME_LATITUDE, (double) (Double) networkInformation.get(NetworkEntry.COLUMN_NAME_LATITUDE));
+			bssidValues.put(NetworkEntry.COLUMN_NAME_LONGITUDE, (double) (Double) networkInformation.get(NetworkEntry.COLUMN_NAME_LONGITUDE));
+			bssidValues.put(NetworkEntry.COLUMN_NAME_ACCURACY, (float) (Float) networkInformation.get(NetworkEntry.COLUMN_NAME_ACCURACY));
+			bssidValues.put(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP, (Long) networkInformation.get(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP));
+			db.insertWithOnConflict(NetworkEntry.TABLE_NAME, null, bssidValues, SQLiteDatabase.CONFLICT_REPLACE);
+		}
+		cursor.close();
+		db.close();
+	}
+
+	/**
+	 * 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();
+		record.setId(Integer.parseInt(cursor.getString(0)));
+		record.setAttack_id(cursor.getLong(1));
+		record.setType(TYPE.valueOf(cursor.getString(2)));
+		record.setTimestamp(cursor.getLong(3));
+		record.setPacket(cursor.getString(4));
+		record.setProtocol(cursor.getString(5));
+		record.setExternalIP(cursor.getString(6));
+
+		record.setLocalIP(cursor.getString(7));
+		record.setLocalPort(Integer.parseInt(cursor.getString(8)));
+
+		record.setRemoteIP(cursor.getString(9));
+		record.setRemotePort(Integer.parseInt(cursor.getString(10)));
+
+		record.setBssid(cursor.getString(11));
+		record.setSsid(cursor.getString(12));
+		record.setLatitude(Double.parseDouble(cursor.getString(13)));
+		record.setLongitude(Double.parseDouble(cursor.getString(14)));
+		record.setAccuracy(Float.parseFloat(cursor.getString(15)));
+		record.setTimestampLocation(cursor.getLong(16));
+
+		return record;
+	}
+
+}

+ 214 - 46
src/de/tudarmstadt/informatik/hostage/dao/ProfileManager.java → src/de/tudarmstadt/informatik/hostage/persistence/ProfileManager.java

@@ -1,4 +1,8 @@
-package de.tudarmstadt.informatik.hostage.dao;
+package de.tudarmstadt.informatik.hostage.persistence;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
 
 import android.content.Context;
 
@@ -6,8 +10,7 @@ import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
+import java.io.InputStream;
 import java.io.StreamCorruptedException;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -20,25 +23,59 @@ import java.util.Random;
 
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.model.Profile;
-import de.tudarmstadt.informatik.hostage.model.ProfilesHolder;
 import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
 import de.tudarmstadt.informatik.hostage.ui2.adapter.ProfileManagerListAdapter;
 
 /**
+ * The profile manager is responsible for persisting and deleting profiles
+ *
  * @author Alexander Brakowski
  * @created 10.02.14 20:24
  */
 public class ProfileManager {
+
+	/**
+	 * The singleton instance holder
+	 */
 	private static ProfileManager INSTANCE = null;
 
+	/**
+	 * An list adapter, which the profile manager informs about data changes
+	 */
 	private ProfileManagerListAdapter mProfileListAdapter = null;
-	private Profile mCurrentActivatedProfile = null;
-	private Profile mRandomProfile = null;
 
-	private static final String PERSIST_FILENAME = "hostage_profiles.dat";
+	/**
+	 * Holds a reference to the currently active profile
+	 */
+	private Profile mCurrentActivatedProfile = null;
 
-	private ProfilesHolder holder;
+	/**
+	 * Holds a reference to the random profile
+	 */
+	private Profile mRandomProfile = null;
 
+	/**
+	 * The profiles are being serialized and persisted into this file
+	 */
+	private static final String PERSIST_FILENAME = "hostage_profiles.json";
+
+	/**
+	 * Hold the current profile id, it will be incremented each time a new profile is added.
+	 * The new profile will get the newly incremented value as an id.
+	 */
+	public int mIncrementValue = 1;
+
+	/**
+	 * Holds all the available profiles. The key in the map is the ID of the profile.
+	 */
+	public HashMap<Integer, Profile> mProfiles;
+
+	/**
+	 * Since the profile manager should only have one instance in the whole app, we are using the singleton pattern.
+	 * This method creates a new instance of the profile manager, if no instance already exists, and returns it.
+	 *
+	 * @return the singleton instance
+	 */
 	public static ProfileManager getInstance(){
 		if(INSTANCE == null){
 			INSTANCE = new ProfileManager();
@@ -51,45 +88,82 @@ public class ProfileManager {
 		return INSTANCE;
 	}
 
+	/**
+	 * A private constructor, that can/should only be called by getInstance, since we want to enforce the usage of the singleton.
+	 */
 	private ProfileManager(){
-		holder = new ProfilesHolder();
-		holder.mProfiles = new HashMap<Integer, Profile>();
+		mProfiles = new HashMap<Integer, Profile>();
+	}
+
+	/**
+	 * Reads all data from an inputstream and appends it to a string
+	 *
+	 * @param is The input stream to read the data from
+	 * @return the whole data from the input stream as an string
+	 */
+	public String readAll( final InputStream is ) {
+		if( null == is ) {
+			return "";
+		}
+
+		StringBuilder sb = new StringBuilder();
+		int rc;
+		try {
+			while( (rc = is.read()) >= 0 ){
+				sb.append( (char) rc );
+			}
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+
+		return sb.toString();
 	}
 
+
+	/**
+	 * Reads all the data of the the profiles, that were persisted and unserializes them.
+	 *
+	 * The profiles were serialized into JSON and persisted into the android private file.
+	 * See {@see ProfileManager#persistData}.
+	 */
 	public void loadData(){
 		try {
 			FileInputStream fin = MainActivity.getContext().openFileInput(PERSIST_FILENAME);
-			ObjectInputStream ois = new ObjectInputStream(fin);
-
-			Object obj = ois.readObject();
-			ois.close();
+			JSONArray arr = new JSONArray(readAll(fin));
 			fin.close();
 
-			if(obj != null && obj instanceof ProfilesHolder){
-				this.holder = (ProfilesHolder) obj;
+			for(int i=0; i<arr.length(); i++){
+				JSONObject obj = arr.getJSONObject(i);
+
+				Profile p = new Profile();
+				p.fromJSON(obj);
 
-				for(Map.Entry<Integer, Profile> entry: holder.mProfiles.entrySet()){
-					if(entry.getValue().mActivated){
-						this.mCurrentActivatedProfile = entry.getValue();
-					}
+				mProfiles.put(p.mId, p);
 
-					if(entry.getValue().mIsRandom){
-						this.mRandomProfile = entry.getValue();
-					}
+				if(p.mId > mIncrementValue){
+					mIncrementValue = p.mId;
+				}
+
+				if(p.mActivated){
+					this.mCurrentActivatedProfile = p;
+				}
+
+				if(p.mIsRandom){
+					this.mRandomProfile = p;
 				}
 			}
+
 		} catch (FileNotFoundException e) {
 			e.printStackTrace();
 		} catch (StreamCorruptedException e) {
 			e.printStackTrace();
 		} catch (IOException e) {
 			e.printStackTrace();
-		} catch (ClassNotFoundException e) {
+		} catch (JSONException e) {
 			e.printStackTrace();
 		} finally {
-			if(holder.mProfiles.size() == 0){
+			if(mProfiles.size() == 0){
 				this.fillWithDefaultData();
-				loadData();
 			}
 
 			if(this.mRandomProfile != null){
@@ -98,13 +172,19 @@ public class ProfileManager {
 		}
 	}
 
+	/**
+	 * All the profiles that are hold by the profile manager are being serialized into JSON and then written into an private android file.
+	 */
 	public void persistData(){
 		try {
 			FileOutputStream fout = MainActivity.getContext().openFileOutput(PERSIST_FILENAME, Context.MODE_PRIVATE);
-			ObjectOutputStream oos = new ObjectOutputStream(fout);
 
-			oos.writeObject(holder);
-			oos.close();
+			JSONArray arr = new JSONArray();
+			for(Profile p: mProfiles.values()){
+				arr.put(p.toJSON());
+			}
+
+			fout.write(arr.toString().getBytes());
 			fout.close();
 		} catch (FileNotFoundException e) {
 			e.printStackTrace();
@@ -114,22 +194,39 @@ public class ProfileManager {
 
 	}
 
+	/**
+	 * Retrieves all the profiles as an List
+	 * @return a list that holds all the profiles
+	 */
 	public List<Profile> getProfilesList(){
 		return new ArrayList<Profile>(getProfilesCollection());
 	}
 
+	/**
+	 * Retrieves all the profiles as an collection
+	 * @return a collection of all the profiles
+	 */
 	public Collection<Profile> getProfilesCollection(){
-		if(holder.mProfiles.size() == 0 || holder.mProfiles == null){
+		if(mProfiles.size() == 0 || mProfiles == null){
 			this.loadData();
 		}
 
-		return holder.mProfiles.values();
+		return mProfiles.values();
 	}
 
+	/**
+	 * Retrieves an map of all the profiles. The key in the map is the ID of an profile.
+	 * @return a map of profiles
+	 */
 	public Map<Integer, Profile> getMapProfiles(){
-		return holder.mProfiles;
+		return mProfiles;
 	}
 
+	/**
+	 * Activates and deactivates protocols randomly in the given profile
+	 *
+	 * @param profile the profile to randomize the protocols for
+	 */
 	public void randomizeProtocols(Profile profile){
 		LinkedList<String> protocols = new LinkedList<String>(Arrays.asList(MainActivity.getContext().getResources().getStringArray(R.array.protocols)));
 		protocols.remove("GHOST");
@@ -150,12 +247,18 @@ public class ProfileManager {
 		persistData();
 	}
 
-	public long persistProfile(Profile profile){
+	/**
+	 * Adds or updates a given profile.
+	 *
+	 * @param profile the profile to persist
+	 * @return the id the profile was assigned to
+	 */
+	public int persistProfile(Profile profile){
 		if(profile.mId == -1){
-			profile.mId = ++holder.mIncrementValue;
+			profile.mId = ++mIncrementValue;
 		}
 
-		holder.mProfiles.put(profile.mId, profile);
+		mProfiles.put(profile.mId, profile);
 
 		this.persistData();
 
@@ -166,29 +269,48 @@ public class ProfileManager {
 		return profile.mId;
 	}
 
+	/**
+	 * Retrieves the profile with the given id
+	 *
+	 * @param id the id of the profile
+	 * @return the profile
+	 */
 	public Profile getProfile(int id){
-		if(holder.mProfiles.size() == 0){
+		if(mProfiles.size() == 0){
 			loadData();
 		}
 
-		if(this.holder.mProfiles.containsKey(id)){
-			return this.holder.mProfiles.get(id);
+		if(this.mProfiles.containsKey(id)){
+			return this.mProfiles.get(id);
 		}
 
 		return null;
 	}
 
+	/**
+	 * Adds a profile
+	 *
+	 * @param profile the profile to add
+	 */
 	public void addProfile(Profile profile){
 		this.addProfile(profile, true);
 	}
 
+	/**
+	 * Adds a given profile to the profile manager.
+	 *
+	 * @param profile the profile to add
+	 * @param persist true,  if the profile should also be persisted immediatly,
+	 *                false, if the profile should just be added internally without being persisted
+	 *                       (Note: you can still call persistData later to persist all the profiles)
+	 */
 	public void addProfile(Profile profile, boolean persist){
 
 		if(profile.mId == -1){
-			profile.mId = ++holder.mIncrementValue;
+			profile.mId = ++mIncrementValue;
 		}
 
-		holder.mProfiles.put(profile.mId, profile);
+		mProfiles.put(profile.mId, profile);
 
 		if(persist){
 			persistData();
@@ -200,10 +322,15 @@ public class ProfileManager {
 		}
 	}
 
+	/**
+	 * Deletes a given profile. These changes will be persisted immediatly.
+	 *
+	 * @param profile the profile to delete
+	 */
 	public void deleteProfile(Profile profile){
-		if(this.holder.mProfiles.containsKey(profile.mId)){
+		if(this.mProfiles.containsKey(profile.mId)){
 			Profile p = getProfile(profile.mId);
-			this.holder.mProfiles.remove(profile.mId);
+			this.mProfiles.remove(profile.mId);
 
 			if(p.mActivated || this.mCurrentActivatedProfile.mId == p.mId){
 				mCurrentActivatedProfile = mRandomProfile;
@@ -220,11 +347,19 @@ public class ProfileManager {
 		}
 	}
 
+	/**
+	 * Removes all profiles.
+	 */
 	public void clearProfiles(){
-		holder.mProfiles.clear();
+		mProfiles.clear();
 		persistData();
 	}
 
+	/**
+	 * Makes a given profile active.
+	 *
+	 * @param profile the profile to activate
+	 */
 	public void activateProfile(Profile profile){
 		if(profile.equals(this.mCurrentActivatedProfile)) return;
 
@@ -235,35 +370,68 @@ public class ProfileManager {
 
 		profile.mActivated = true;
 		this.mCurrentActivatedProfile = profile;
-		this.holder.mProfiles.put(profile.mId, profile);
+		this.mProfiles.put(profile.mId, profile);
 		persistData();
 	}
 
+	/**
+	 * Checks if the "random" profile is currently active
+	 *
+	 * @return true,  if active
+	 *         false, otherwise
+	 */
 	public boolean isRandomActive(){
 		return this.mCurrentActivatedProfile.equals(this.mRandomProfile);
 	}
 
+	/**
+	 * Retrieves the "random" profile
+	 *
+	 * @return the "random" profile
+	 */
 	public Profile getRandomProfile(){
 		return this.mRandomProfile;
 	}
 
+	/**
+	 * Retrieves the currently active profile
+	 *
+	 * @return the active profile
+	 */
 	public Profile getCurrentActivatedProfile(){
 		return mCurrentActivatedProfile;
 	}
 
+	/**
+	 * Sets the list adapter that should also be managed by the profile manager
+	 *
+	 * @param profileListAdapter the list adapter to manage
+	 */
 	public void setProfileListAdapter(ProfileManagerListAdapter profileListAdapter){
 		this.mProfileListAdapter = profileListAdapter;
 	}
 
 
+	/**
+	 * Retrieves the list adapter, that is being managed by the profile manager
+	 * @return the list adapter
+	 */
 	public ProfileManagerListAdapter getProfileListAdapter(){
 		return this.mProfileListAdapter;
 	}
 
+	/**
+	 * Retrieves the number of profiles
+	 *
+	 * @return the number of profiles
+	 */
 	public int getNumberOfProfiles(){
-		return holder.mProfiles.size();
+		return mProfiles.size();
 	}
 
+	/**
+	 * Fills the profiles manager with default profiles
+	 */
 	public void fillWithDefaultData(){
 		Profile windowsVista = new Profile(
 				0,
@@ -385,7 +553,7 @@ public class ProfileManager {
 		paranoidProfile.mActivated = true;
 		this.addProfile(paranoidProfile, false);
 
-		holder.mIncrementValue = 8;
+		mIncrementValue = 8;
 		this.mCurrentActivatedProfile = paranoidProfile;
 
 		persistData();

+ 11 - 14
src/de/tudarmstadt/informatik/hostage/protocol/FTP.java

@@ -27,11 +27,8 @@ public class FTP implements Protocol {
 
 	// commands
 	private static final String REPLY_CODE_220 = "220 Service ready for new user.";
-
 	private static final String REPLY_CODE_221 = "221 Service closing control connection.";
-
 	private static final String REPLY_CODE_230 = "230 User logged in.";
-
 	private static final String REPLY_CODE_331 = "331 User name ok, need password.";
 	private static final String REPLY_CODE_332 = "332 Need account for login.";
 	private static final String REPLY_CODE_421 = "421 Service not available, closing control connection.";
@@ -64,10 +61,10 @@ public class FTP implements Protocol {
 		case NONE:
 			if (request == null) {
 				state = STATE.OPEN;
-				responsePackets.add(new Packet(REPLY_CODE_220));
+				responsePackets.add(new Packet(REPLY_CODE_220 + "\r\n", toString()));
 			} else {
 				state = STATE.CLOSED;
-				responsePackets.add(new Packet(REPLY_CODE_421));
+				responsePackets.add(new Packet(REPLY_CODE_421 + "\r\n", toString()));
 			}
 			break;
 		case OPEN:
@@ -75,37 +72,37 @@ public class FTP implements Protocol {
 				state = STATE.CLOSED;
 				return null;
 			} else if (request.equals("USER \r\n")) {
-				responsePackets.add(new Packet(REPLY_CODE_501));
+				responsePackets.add(new Packet(REPLY_CODE_501 + "\r\n", toString()));
 			} else if (request.contains("USER")) {
 				state = STATE.USER;
-				responsePackets.add(new Packet(REPLY_CODE_331));
+				responsePackets.add(new Packet(REPLY_CODE_331 + "\r\n", toString()));
 			} else {
-				responsePackets.add(new Packet(REPLY_CODE_332));
+				responsePackets.add(new Packet(REPLY_CODE_332 + "\r\n", toString()));
 			}
 			break;
 		case USER:
 			if (request.equals("PASS \r\n")) {
 				state = STATE.OPEN;
-				responsePackets.add(new Packet(REPLY_CODE_501));
+				responsePackets.add(new Packet(REPLY_CODE_501 + "\r\n", toString()));
 			} else if (request.contains("PASS")) {
 				state = STATE.LOGGED_IN;
-				responsePackets.add(new Packet(REPLY_CODE_230));
+				responsePackets.add(new Packet(REPLY_CODE_230 + "\r\n", toString()));
 			} else {
 				state = STATE.CLOSED;
-				responsePackets.add(new Packet(REPLY_CODE_221));
+				responsePackets.add(new Packet(REPLY_CODE_221 + "\r\n", toString()));
 			}
 			break;
 		case LOGGED_IN:
 			if (request != null && !request.contains("QUIT")) {
-				responsePackets.add(new Packet(REPLY_CODE_500));
+				responsePackets.add(new Packet(REPLY_CODE_500 + "\r\n", toString()));
 			} else {
 				state = STATE.CLOSED;
-				responsePackets.add(new Packet(REPLY_CODE_221));
+				responsePackets.add(new Packet(REPLY_CODE_221 + "\r\n", toString()));
 			}
 			break;
 		default:
 			state = STATE.CLOSED;
-			responsePackets.add(new Packet(REPLY_CODE_421));
+			responsePackets.add(new Packet(REPLY_CODE_421 + "\r\n", toString()));
 		}
 		return responsePackets;
 	}

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/protocol/GHOST.java

@@ -43,7 +43,7 @@ public class GHOST implements Protocol {
 
 	@Override
 	public int getPort() {
-		return 5050; // TODO whats the default!? (1433)
+		return 1433;
 	}
 
 	@Override
@@ -84,7 +84,7 @@ public class GHOST implements Protocol {
 			}
 			byte[] mirrorResponse = new byte[availableBytes];
 			mirrorInputStream.read(mirrorResponse);
-			responsePackets.add(new Packet(mirrorResponse));
+			responsePackets.add(new Packet(mirrorResponse, toString()));
 		} catch (IOException e) {
 			e.printStackTrace();
 			responsePackets.add(requestPacket);

+ 36 - 12
src/de/tudarmstadt/informatik/hostage/protocol/HTTP.java

@@ -8,6 +8,9 @@ import java.util.List;
 import java.util.Locale;
 import java.util.TimeZone;
 
+import android.content.Context;
+import de.tudarmstadt.informatik.hostage.Hostage;
+import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.wrapper.Packet;
 
@@ -25,7 +28,7 @@ public class HTTP implements Protocol {
 	 * 
 	 * @return the formatted server time.
 	 */
-	private static String getServerTime() {
+	private String getServerTime() {
 		Calendar calendar = Calendar.getInstance();
 		SimpleDateFormat dateFormat = new SimpleDateFormat(
 				"EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
@@ -37,7 +40,7 @@ public class HTTP implements Protocol {
 	private String request = "";
 
 	// version stuff
-	private static String[][][] possibleHttpVersions = {
+	private String[][][] possibleHttpVersions = {
 			{
 					{ "Apache/2.0." },
 					{ "28", "32", "35", "36", "39", "40", "42", "43", "44",
@@ -51,22 +54,40 @@ public class HTTP implements Protocol {
 							"21", "22", "23", "24", "25" } },
 			{ { "Apache/2.3." },
 					{ "4", "5", "6", "8", "10", "11", "12", "14", "15", "16" } },
-			{ { "Apache/2.4." }, { "1", "2", "3", "4", "6" } } };
+			{ { "Apache/2.4." }, { "1", "2", "3", "4", "6" } },
+			{ { "Microsoft-IIS/" }, { "5.1", "7.0", "8.0" } } };
 
-	private static String serverVersion = initServerVersion();
+	private String serverVersion = initServerVersion();
 
-	private static String initServerVersion() {
+	private String initServerVersion() {
 		SecureRandom rndm = new SecureRandom();
 		int majorVersion = rndm.nextInt(possibleHttpVersions.length);
-		return possibleHttpVersions[majorVersion][0][0]
-				+ possibleHttpVersions[majorVersion][1][rndm
-						.nextInt(possibleHttpVersions[majorVersion][1].length)];
+		
+		String version;
+		String sharedPreferencePath = Hostage.getContext().getString(
+				R.string.shared_preference_path);
+		String profile = Hostage
+				.getContext()
+				.getSharedPreferences(sharedPreferencePath,
+						Context.MODE_PRIVATE).getString("os", "");
+		if (profile.equals("Windows 7") || profile.equals("Windows Server 2008")) {
+			version = "Microsoft-IIS/7.5";
+		} else if (profile.equals("Windows Server 2012") || profile.equals("Windows 8")) {
+			version = "Microsoft-IIS/8.0";
+		} else if (profile.equals("Windows XP")) {
+			version = "Microsoft-IIS/5.1";
+		} else {
+			version = possibleHttpVersions[majorVersion][0][0]
+					+ possibleHttpVersions[majorVersion][1][rndm
+					          .nextInt(possibleHttpVersions[majorVersion][1].length)];
+		}
+		
+		return version;
 	}
 
 	private String httpVersion = "HTTP/1.1";
 
-	private static String htmlDocumentContent = HelperUtils.getRandomString(32,
-			false);
+	private static String htmlDocumentContent = HelperUtils.getRandomString(32, false);
 
 	// request codes
 	private static final String OPTIONS = "OPTIONS";
@@ -136,7 +157,10 @@ public class HTTP implements Protocol {
 		List<Packet> responsePackets = new ArrayList<Packet>();
 		this.request = request;
 
-		if (!request.contains(httpVersion)) {
+		if (request.startsWith("G")) {
+			//weird if clause but required for https
+			responsePackets.add(buildPacket(STATUS_CODE_200, GET));
+		} else if (!request.contains(httpVersion)) {
 			responsePackets.add(buildPacket(STATUS_CODE_505, ""));
 		} else if (request.contains(GET)) {
 			responsePackets.add(buildPacket(STATUS_CODE_200, GET));
@@ -192,6 +216,6 @@ public class HTTP implements Protocol {
 		}
 
 		return new Packet(httpVersion + " " + code + headerPrefix
-				+ document.length() + headerSuffix + document);
+				+ document.length() + headerSuffix + document, toString());
 	}
 }

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/protocol/HTTPS.java

@@ -5,7 +5,7 @@ import java.security.KeyStore;
 import javax.net.ssl.KeyManagerFactory;
 import javax.net.ssl.SSLContext;
 
-import de.tudarmstadt.informatik.hostage.HoneyService;
+import de.tudarmstadt.informatik.hostage.Hostage;
 
 /**
  * HTTPS protocol. Extends HTTP. Implementation of RFC document 2818. It can handle the
@@ -30,7 +30,7 @@ public class HTTPS extends HTTP implements SSLProtocol {
 		try {
 			keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
 			keyStore.load(
-					HoneyService.getContext().getAssets().open(keyStoreName),
+					Hostage.getContext().getAssets().open(keyStoreName),
 					keyStorePassword);
 			keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory
 					.getDefaultAlgorithm());

+ 4 - 4
src/de/tudarmstadt/informatik/hostage/protocol/MySQL.java

@@ -30,7 +30,7 @@ public class MySQL implements Protocol {
 	private byte[] lastReceivedMessage;
 
 	// version stuff
-	private static String[][][] possibleMysqlVersions = {
+	private String[][][] possibleMysqlVersions = {
 			{ { "5.7." }, { "1", "2" } },
 			{
 					{ "5.6." },
@@ -38,9 +38,9 @@ public class MySQL implements Protocol {
 							"13", "14" } },
 			{ { "5.5." }, { "27", "28", "29", "30", "31", "32", "33", "34" } } };
 
-	private static String serverVersion = initMysqlVersion();
+	private String serverVersion = initMysqlVersion();
 
-	private static String initMysqlVersion() {
+	private String initMysqlVersion() {
 		SecureRandom rndm = new SecureRandom();
 		int majorVersion = rndm.nextInt(possibleMysqlVersions.length);
 		return possibleMysqlVersions[majorVersion][0][0]
@@ -183,6 +183,6 @@ public class MySQL implements Protocol {
 
 		byte[] wrappedResponse = HelperUtils.concat(packetLength, packetNumber,
 				response);
-		return new Packet(wrappedResponse);
+		return new Packet(wrappedResponse, toString());
 	}
 }

+ 124 - 5
src/de/tudarmstadt/informatik/hostage/protocol/SIP.java

@@ -1,10 +1,35 @@
 package de.tudarmstadt.informatik.hostage.protocol;
 
+import java.util.ArrayList;
 import java.util.List;
 
 import de.tudarmstadt.informatik.hostage.wrapper.Packet;
 
+/**
+ * SIP protocol. Implementation of RFC document 3261 It can handle the
+ * following requests: REGISTER, INVITE, ACK, BYE. For all other requests
+ * '400 Bad Request' will be replied.
+ * @author Wulf Pfeiffer
+ */
 public class SIP implements Protocol {
+	
+	private enum STATE {
+		NONE, CLOSED
+	}
+	
+	private STATE state = STATE.NONE;
+		
+	private static final String VERSION = "SIP/2.0";
+	private static final String REGISTER = "REGISTER";
+	private static final String INVITE = "INVITE";
+	private static final String ACK= "ACK";
+	private static final String BYE = "BYE";
+	private static final String STATUS_CODE_200 = "200 OK";
+	private static final String STATUS_CODE_400 = "400 Bad Request";
+	private static final String STATUS_CODE_505 = "505 Version Not Supported";
+	
+	private String header;
+	private String sdpPayload;
 
 	@Override
 	public int getPort() {
@@ -13,8 +38,7 @@ public class SIP implements Protocol {
 
 	@Override
 	public boolean isClosed() {
-		// TODO Auto-generated method stub
-		return true;
+		return (state == STATE.CLOSED);
 	}
 
 	@Override
@@ -23,14 +47,109 @@ public class SIP implements Protocol {
 	}
 
 	@Override
-	public List<Packet> processMessage(Packet packet) {
-		// TODO Auto-generated method stub
-		return null;
+	public List<Packet> processMessage(Packet requestPacket) {
+		String request = null;
+		if (requestPacket != null) {
+			request = requestPacket.toString();
+		}
+		List<Packet> responsePackets = new ArrayList<Packet>();
+		String[] lines = request.split("\r\n");
+		extractLines(lines);
+		
+		if(!lines[0].contains(VERSION)) {
+			responsePackets.add(getVersionNotSupportedResponse());
+			return responsePackets;
+		} else if(lines[0].contains(REGISTER)) {
+			responsePackets.add(getOkResponse());
+		} else if(lines[0].contains(INVITE)) {
+			responsePackets.add(getOkResponseWithSDP());
+		} else if(lines[0].contains(BYE)) {
+			responsePackets.add(getOkResponse());
+			state = STATE.CLOSED;
+		} else if(lines[0].contains(ACK)) {
+			//nothing to do here
+		} else {
+			responsePackets.add(getBadRequestResponse());
+		}
+		
+		return responsePackets;
 	}
 
 	@Override
 	public TALK_FIRST whoTalksFirst() {
 		return TALK_FIRST.CLIENT;
 	}
+	
+	@Override
+	public String toString() {
+		return "SIP";
+	}
+	
+	private void extractLines(String[] lines) {
+		header = "";
+		sdpPayload = "";
+		StringBuffer sbHeader = new StringBuffer();
+		StringBuffer sbSdp = new StringBuffer();
+		boolean recordHeader = false;
+		boolean recordSdp = false;
+		for (String line : lines) {
+			if (line.startsWith("Via:")) {
+				recordHeader = true;
+			} else if (line.startsWith("Max-Forwards")) {
+				recordHeader = false;
+				header = sbHeader.toString();
+			} else if(line.startsWith("v=")) {
+				recordSdp = true;
+			} else if(line.startsWith("a=")) {
+				sbSdp.append(line + "\r\n");
+				sdpPayload = sbSdp.toString();
+				break;
+			}
+			if(recordHeader) {
+				sbHeader.append(line + "\r\n");
+			} else if(recordSdp) {
+				sbSdp.append(line + "\r\n");
+			}
+		}
+	}
+	
+	private Packet getOkResponseWithSDP() {
+		StringBuffer sb = new StringBuffer();
+		sb.append(VERSION + " " + STATUS_CODE_200 + "\r\n");
+		sb.append(header);
+		sb.append("Content-Type: application/sdp\r\n");
+		sb.append("Content-Length:   " + sdpPayload.length() + "\r\n");
+		sb.append("\r\n");
+		sb.append(sdpPayload);
+
+		return new Packet(sb.toString(), toString());
+	}
+	
+	private Packet getOkResponse() {
+		StringBuffer sb = new StringBuffer();
+		sb.append(VERSION + " " + STATUS_CODE_200 + "\r\n");
+		sb.append(header);
+		sb.append("Content-Length:   0\r\n");
+		
+		return new Packet(sb.toString(), toString());
+	}
+	
+	private Packet getBadRequestResponse() {
+		StringBuffer sb = new StringBuffer();
+		sb.append(VERSION + " " + STATUS_CODE_400 + "\r\n");
+		sb.append(header);
+		sb.append("Content-Length:   0\r\n");
+		
+		return new Packet(sb.toString(), toString());
+	}
+	
+	private Packet getVersionNotSupportedResponse() {
+		StringBuffer sb = new StringBuffer();
+		sb.append(VERSION + " " + STATUS_CODE_505 + "\r\n");
+		sb.append(header);
+		sb.append("Content-Length:   0\r\n");
+		
+		return new Packet(sb.toString(), toString());
+	}
 
 }

+ 60 - 721
src/de/tudarmstadt/informatik/hostage/protocol/SMB.java

@@ -1,17 +1,14 @@
 package de.tudarmstadt.informatik.hostage.protocol;
 
-import java.nio.ByteBuffer;
 import java.security.SecureRandom;
 import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.GregorianCalendar;
 import java.util.List;
-import java.util.TimeZone;
 
-import android.content.Context;
-import de.tudarmstadt.informatik.hostage.HoneyService;
+import de.tudarmstadt.informatik.hostage.Hostage;
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+import de.tudarmstadt.informatik.hostage.protocol.smbutils.NBNS;
+import de.tudarmstadt.informatik.hostage.protocol.smbutils.NMB;
+import de.tudarmstadt.informatik.hostage.protocol.smbutils.SMBPacket;
 import de.tudarmstadt.informatik.hostage.wrapper.Packet;
 
 /**
@@ -23,88 +20,53 @@ import de.tudarmstadt.informatik.hostage.wrapper.Packet;
  * @author Wulf Pfeiffer
  */
 public class SMB implements Protocol {
+	// message constants
+	private static final byte SMB_COM_CLOSE = 0x04;
+	private static final byte SMB_COM_TRANSACTION = 0x25;
+	private static final byte SMB_COM_ECHO = 0x2B;
+	private static final byte SMB_COM_TRANSACTION2 = 0x32;
+	private static final byte SMB_COM_TREE_DISCONNECT = 0x71;
+	private static final byte SMB_COM_NEGOTIATE = 0x72;
+	private static final byte SMB_COM_SESSION_SETUP_ANDX = 0x73;
+	private static final byte SMB_COM_TREE_CONNECT_ANDX = 0x75;
+	private static final byte SMB_COM_NT_CREATE_ANDX = (byte) 0xA2;
+	
 	/**
-	 * Represents the states of the protocol
+	 * Denotes in which state the protocol is right now
 	 */
-	private static enum STATE {
-		NONE, CONNECTED, AUTHENTICATED, LISTING, DISCONNECTED, CLOSED
-	}
+	private STATE state = STATE.NONE;
+	private byte[] lastMessage;
 
 	// version stuff
-	private static String[][] possibleSmbVersions = {
+	private String[][] possibleSmbVersions = {
 			{ "Windows 7 Professional 7600", "Windows 7 Professional 6.1" },
 			{ "Windows 8 Enterprise 9200", "Windows 8 Enterprise 9200" },
 			{ "Windows Server 2008 R2 Enterprise 7600", "Windows Server 2008 R2 Enterprise 6.1" },
 			{ "Windows Server 2012 Standard 6.2", "Windows Server 2012 Standard 6.2" },
 			{ "Unix", "Samba" },
-			{ "Windows 2002 Service Pack 2", "Windows 2002 5.1"}
+			{ "Windows 2002 Service Pack 2", "Windows 2002 5.1" }
 	};
-
+	
 	/**
-	 * Converts the current system time into a byte[] with windows specific time
-	 * 
-	 * @return current system time in windows format as byte[]
+	 * Represents the states of the protocol
 	 */
-	private static byte[] getTimeInBytes() {
-		long time = System.currentTimeMillis();
-		Calendar calend = Calendar.getInstance();
-		calend.setTimeZone(TimeZone.getTimeZone("UTC"));
-		calend.set(1601, 0, 01, 00, 00, 00);
-		time -= calend.getTimeInMillis();
-		time *= 10000;
-
-		byte[] timeInWindowsBytes = new byte[8];
-		byte[] timeInBytes = ByteBuffer.allocate(8).putLong(time).array();
-
-		for (int i = 0, j = 7; i < 8 && j > -1; i++, j--) {
-			timeInWindowsBytes[i] = (byte) (timeInBytes[j] & 0xff);
-		}
-
-		return timeInWindowsBytes;
+	private static enum STATE {
+		NONE, CONNECTED, AUTHENTICATED, LISTING, DISCONNECTED, CLOSED
 	}
-
-	/**
-	 * Converts the current timezone into a byte[] with windows specific format
-	 * 
-	 * @return current timezone in windows format as byte[]
-	 */
-	private static byte[] getTimeZoneInBytes() {
-		Integer offset = new GregorianCalendar().getTimeZone().getRawOffset() / 1000 / 60; // get
-																							// current
-																							// timezone
-																							// offset
-																							// in
-																							// minutes
-		char[] offsetChars = Integer.toBinaryString(offset).toCharArray();
-		boolean invert = false;
-		for (int i = offsetChars.length - 1; i > -1; i--) {
-			if (!invert && offsetChars[i] == '1') {
-				invert = true;
-			} else if (invert) {
-				offsetChars[i] = (offsetChars[i] == '0') ? '1' : '0';
-			}
-		}
-		char[] extendedChars = new char[31];
-		for (int i = 0; i < extendedChars.length - offsetChars.length; i++) {
-			extendedChars[i] = '1';
-		}
-		for (int i = 0; i < offsetChars.length; i++) {
-			extendedChars[i + extendedChars.length - offsetChars.length] = offsetChars[i];
-		}
-		int timezone = Integer.parseInt(new String(extendedChars), 2);
-		byte[] timezoneBytes = new byte[2];
-		timezoneBytes[1] = (byte) (timezone >> 8);
-		timezoneBytes[0] = (byte) (timezone);
-		return timezoneBytes;
+	
+	public void setIP(String ip) {
+		new NMB(ip, "ABCDEFG", "WORKGROUPA").start();
 	}
 
-	private static String[] initServerVersion() {
-		String sharedPreferencePath = HoneyService.getContext().getString(
+	private String[] initServerVersion() {
+		System.out.println("hi");
+		String sharedPreferencePath = Hostage.getContext().getString(
 				R.string.shared_preference_path);
-		String profile = HoneyService
+		System.out.println(sharedPreferencePath);
+		String profile = Hostage
 				.getContext()
 				.getSharedPreferences(sharedPreferencePath,
-						Context.MODE_PRIVATE).getString("profile", "");
+						Hostage.MODE_PRIVATE).getString("os", "");
 		System.out.println(profile);
 		if (profile.equals("Windows 7")) {
 			return possibleSmbVersions[0];
@@ -119,57 +81,13 @@ public class SMB implements Protocol {
 		} else if (profile.equals("Windows XP")) {
 			return possibleSmbVersions[5];
 		} else {
-			return possibleSmbVersions[new SecureRandom()
-					.nextInt(possibleSmbVersions.length)];
+			return possibleSmbVersions[new SecureRandom().nextInt(possibleSmbVersions.length)];
 		}
 	}
-
-	/**
-	 * Denotes in which state the protocol is right now
-	 */
-	private STATE state = STATE.NONE;
-
-	private byte[] lastMessage;
-
-	private static byte[] serverName = HelperUtils.fillWithZero(HelperUtils
-			.getRandomString(16, true).getBytes());
-
-	private static String[] serverVersion = initServerVersion();
-
-	private byte[] message = null;
-
-	private static final byte[] serverGUID = HelperUtils.randomBytes(16);
-
-	private boolean authenticateNext = false;
-
-	// components of a SMB packet
-	private byte[] serverComp = new byte[4];
-
-	private byte[] smbCommand = new byte[1];
-	private byte[] ntStat = new byte[4];
-
-	private byte[] smbFlags = new byte[1];
-	private byte[] smbFlags2 = new byte[2];
-	private byte[] processIDHigh = new byte[2];
-	private byte[] signature = new byte[8];
-	private byte[] reserved = new byte[2];
-	private byte[] treeID = new byte[2];
-	private byte[] processID = new byte[2];
-	private byte[] userID = new byte[2];
-	private byte[] multiplexID = new byte[2];
-	// message constants
-	private static final byte SMB_COM_CLOSE = 0x04;
-	private static final byte SMB_COM_TRANSACTION = 0x25;
-	private static final byte SMB_COM_ECHO = 0x2B;
-	private static final byte SMB_COM_TRANSACTION2 = 0x32;
-	private static final byte SMB_COM_TREE_DISCONNECT = 0x71;
-	private static final byte SMB_COM_NEGOTIATE = 0x72;
-
-	private static final byte SMB_COM_SESSION_SETUP_ANDX = 0x73;
-
-	private static final byte SMB_COM_TREE_CONNECT_ANDX = 0x75;
-
-	private static final byte SMB_COM_NT_CREATE_ANDX = (byte) 0xA2;
+	
+	//required to be declared down here, do not change position over initServerVersion() and possibleServerVersions!!
+	private String[] serverVersion = initServerVersion();
+	private SMBPacket smbPacket = new SMBPacket(serverVersion);
 
 	@Override
 	public int getPort() {
@@ -190,73 +108,75 @@ public class SMB implements Protocol {
 	public List<Packet> processMessage(Packet requestPacket) {
 		if (requestPacket != null)
 			lastMessage = requestPacket.getBytes();
-		parseMessageHeader(lastMessage);
-		byte smbCommand = getSmbCommand();
+		smbPacket.prepareNextResponse(lastMessage);
+		byte smbCommand = smbPacket.getSmbCommand();
+		byte[] response;
 		List<Packet> responsePackets = new ArrayList<Packet>();
 
 		switch (state) {
 		case NONE:
 			if (smbCommand == SMB_COM_NEGOTIATE) {
 				state = STATE.CONNECTED;
-				responsePackets.add(getNego());
+				response = smbPacket.getNego();
 			} else {
 				state = STATE.DISCONNECTED;
-				responsePackets.add(getTreeDisc());
+				response = smbPacket.getTreeDisc();
 			}
 			break;
 		case CONNECTED:
 			if (smbCommand == SMB_COM_SESSION_SETUP_ANDX) {
-				responsePackets.add(getSessSetup());
+				response = smbPacket.getSessSetup();
 			} else if (smbCommand == SMB_COM_TREE_CONNECT_ANDX) {
 				state = STATE.AUTHENTICATED;
-				responsePackets.add(getTreeCon());
+				response = smbPacket.getTreeCon();
 			} else {
 				state = STATE.DISCONNECTED;
-				responsePackets.add(getTreeDisc());
+				response = smbPacket.getTreeDisc();
 			}
 			break;
 		case AUTHENTICATED:
 			if (smbCommand == SMB_COM_NT_CREATE_ANDX) {
 				state = STATE.LISTING;
-				responsePackets.add(getNTCreate());
+				response = smbPacket.getNTCreate();
 			} else if (smbCommand == SMB_COM_ECHO) {
-				responsePackets.add(getEcho());
+				response = smbPacket.getEcho();
 			} else if (smbCommand == SMB_COM_TRANSACTION2) {
-				responsePackets.add(getTrans2());
+				response = smbPacket.getTrans2();
 			} else if (smbCommand == SMB_COM_CLOSE) {
-				responsePackets.add(getClose());
+				response = smbPacket.getClose();
 			} else if (smbCommand == SMB_COM_TREE_DISCONNECT) {
 				state = STATE.CLOSED;
-				responsePackets.add(getTreeDisc());
+				response = smbPacket.getTreeDisc();
 			} else {
 				state = STATE.DISCONNECTED;
-				responsePackets.add(getTreeDisc());
+				response = smbPacket.getTreeDisc();
 			}
 			break;
 		case LISTING:
 			if (smbCommand == SMB_COM_TRANSACTION) {
-				responsePackets.add(getTrans());
+				response = smbPacket.getTrans();
 			} else if (smbCommand == SMB_COM_CLOSE) {
-				responsePackets.add(getClose());
+				response = smbPacket.getClose();
 			} else if (smbCommand == SMB_COM_TREE_DISCONNECT) {
 				state = STATE.CLOSED;
-				responsePackets.add(getTreeDisc());
+				response = smbPacket.getTreeDisc();
 			} else if (smbCommand == SMB_COM_NEGOTIATE) {
 				state = STATE.CONNECTED;
-				responsePackets.add(getNego());
+				response = smbPacket.getNego();
 			} else {
 				state = STATE.DISCONNECTED;
-				responsePackets.add(getTreeDisc());
+				response = smbPacket.getTreeDisc();
 			}
 			break;
 		case DISCONNECTED:
 			state = STATE.CLOSED;
-			responsePackets.add(getTreeDisc());
+			response = smbPacket.getTreeDisc();
 			break;
 		default:
 			state = STATE.CLOSED;
-			responsePackets.add(getTreeDisc());
+			response = smbPacket.getTreeDisc();
 		}
+		responsePackets.add(new Packet(response, toString()));
 		return responsePackets;
 	}
 
@@ -269,585 +189,4 @@ public class SMB implements Protocol {
 	public TALK_FIRST whoTalksFirst() {
 		return TALK_FIRST.CLIENT;
 	}
-
-	/**
-	 * Evaluates what Dialects are offered by the client and which position the
-	 * used NT LM 0.12 dialect is at
-	 * 
-	 * @return position of the NT LM 0.12 dialect
-	 */
-	private byte[] evaluateDialect() {
-		byte[] dialectMsg = new byte[message.length - 39];
-		System.arraycopy(message, 39, dialectMsg, 0, message.length - 39);
-		short dialectNumber = 0;
-		for (int i = 0, start = 0; i < dialectMsg.length; i++) {
-			if (dialectMsg[i] == 0x00) {
-				byte[] dialect = new byte[i - start];
-				System.arraycopy(dialectMsg, start, dialect, 0, i - start);
-				if (HelperUtils.byteToStr(dialect).contains("NT LM 0.12")) {
-					return new byte[] { (byte) dialectNumber,
-							(byte) (dialectNumber >> 8) };
-				}
-				start = i + 1;
-				dialectNumber++;
-			}
-		}
-		return new byte[] { 0x00, 0x00 };
-	}
-
-	/**
-	 * Builds the close packet
-	 * 
-	 * @return close packet
-	 */
-	private Packet getClose() {
-		byte[] wordCount = { 0x00 };
-		byte[] byteCount = { 0x00, 0x00 };
-
-		smbCommand = new byte[] { 0x04 };
-
-		byte[] response = HelperUtils.concat(wordCount, byteCount);
-
-		return new Packet(wrapNetbios(wrapHeader(response)));
-	}
-
-	/**
-	 * Builds the DCERPC packet
-	 * 
-	 * @return DCERPC packet
-	 */
-	private byte[] getDceRpc(byte[] transSub, int length) {
-		byte[] majorVersion = { 0x05 };
-		byte[] minorVersion = { 0x00 };
-		byte[] packetType = null;
-		byte[] packetFlags = { 0x03 };
-		byte[] dataRepres = { 0x10, 0x00, 0x00, 0x00 };
-		byte[] fragLength = null;
-		byte[] authLength = { 0x00, 0x00 };
-		byte[] callID = null;
-		byte[] response = null;
-
-		if (transSub[0] == 0x00 && transSub[1] == 0x0b) {
-			packetType = new byte[] { 0x0c };
-			fragLength = new byte[] { 0x44, 0x00 };
-			callID = new byte[] { 0x01, 0x00, 0x00, 0x00 };
-			byte[] maxXmitFrag = { (byte) 0xb8, 0x10 };
-			byte[] maxRecvFrag = { (byte) 0xb8, 0x10 };
-			byte[] assocGroup = { 0x4a, 0x41, 0x00, 0x00 };
-			byte[] scndryAddrLen = { 0x0d, 0x00 };
-			byte[] scndryAddr = { 0x5c, 0x50, 0x49, 0x50, 0x45, 0x5c, 0x73,
-					0x72, 0x76, 0x73, 0x76, 0x63, 0x00, 0x00 };
-			byte[] numResults = { 0x01, 0x00, 0x00, 0x00 };
-			byte[] ctxItem = { 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, (byte) 0x88,
-					(byte) 0x8a, (byte) 0xeb, 0x1c, (byte) 0xc9, 0x11,
-					(byte) 0x9f, (byte) 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48,
-					0x60, 0x02, 0x00, 0x00, 0x00 };
-
-			response = HelperUtils.concat(majorVersion, minorVersion,
-					packetType, packetFlags, dataRepres, fragLength,
-					authLength, callID, maxXmitFrag, maxRecvFrag, assocGroup,
-					scndryAddrLen, scndryAddr, numResults, ctxItem);
-		} else if (transSub[0] == 0x00 && transSub[1] == 0x00) {
-			packetType = new byte[] { 0x02 };
-			byte[] tmp = ByteBuffer.allocate(4).putInt(length).array();
-			fragLength = new byte[] { tmp[3], tmp[2] };
-			callID = new byte[] { 0x02, 0x00, 0x00, 0x00 };
-			tmp = ByteBuffer.allocate(4).putInt(length - 24).array();
-			byte[] allocHint = new byte[] { tmp[3], tmp[2], tmp[1], tmp[0] };
-			byte[] contextID = { 0x00, 0x00 };
-			byte[] cancelCount = { 0x00, 0x00 };
-
-			response = HelperUtils.concat(majorVersion, minorVersion,
-					packetType, packetFlags, dataRepres, fragLength,
-					authLength, callID, allocHint, contextID, cancelCount);
-		}
-		return response;
-	}
-
-	/**
-	 * Builds the echo packet
-	 * 
-	 * @return echo packet
-	 */
-	private Packet getEcho() {
-		byte[] wordCount = { 0x01 };
-		byte[] echoSeq = { 0x01, 0x00 };
-		byte[] byteCount = { 0x10, 0x00 };
-		byte[] echoData = { (byte) 0xf0, (byte) 0xf0, (byte) 0xf0, (byte) 0xf0,
-				(byte) 0xf0, (byte) 0xf0, (byte) 0xf0, (byte) 0xf0,
-				(byte) 0xf0, (byte) 0xf0, (byte) 0xf0, (byte) 0xf0,
-				(byte) 0xf0, (byte) 0xf0, (byte) 0xf0, (byte) 0xf0 };
-		byte[] response = HelperUtils.concat(wordCount, echoSeq, byteCount,
-				echoData);
-		return new Packet(wrapNetbios(wrapHeader(response)));
-	}
-
-	/**
-	 * Builds the negotiate packet
-	 * 
-	 * @return negotiate packet
-	 */
-	private Packet getNego() {
-		byte[] wordCount = { 0x11 };
-		byte[] dialect = evaluateDialect();
-		byte[] secMode = { 0x03 };
-		byte[] maxMpxC = { 0x32, 0x00 };
-		byte[] maxVcs = { 0x01, 0x00 };
-		byte[] maxBufSize = { 0x04, 0x11, 0x00, 0x00 };
-		byte[] maxRawBuf = { 0x00, 0x00, 0x01, 0x00 };
-		byte[] sessionKey = { 0x00, 0x00, 0x00, 0x00 };
-		byte[] capabilities = { (byte) 0xfc, (byte) 0xe3, 0x01, (byte) 0x80 };
-		byte[] sysTime = getTimeInBytes();
-		byte[] timeZone = getTimeZoneInBytes();
-		byte[] keyLength = { 0x00 };
-		byte[] byteCount = { 0x3a, 0x00 };
-		byte[] guid = serverGUID;
-		byte[] secBlob = { 0x60, 0x28, 0x06, 0x06 };
-		byte[] oid = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x02 };
-		byte[] protectNeg = { (byte) 0xa0, 0x1e };
-		byte[] negToken = { 0x30, 0x1c, (byte) 0xa0, 0x1a, 0x30, 0x18 };
-		byte[] mechType = { 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01,
-				(byte) 0x82, 0x37, 0x02, 0x02, 0x1e };
-		byte[] mechType2 = { 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01,
-				(byte) 0x82, 0x37, 0x02, 0x02, 0x0a };
-
-		byte[] response = HelperUtils.concat(wordCount, dialect, secMode,
-				maxMpxC, maxVcs, maxBufSize, maxRawBuf, sessionKey,
-				capabilities, sysTime, timeZone, keyLength, byteCount, guid,
-				secBlob, oid, protectNeg, negToken, mechType, mechType2);
-		return new Packet(wrapNetbios(wrapHeader(response)));
-	}
-
-	/**
-	 * Builds the nt create packet
-	 * 
-	 * @return nt create packet
-	 */
-	private Packet getNTCreate() {
-		byte[] wordCount = { 0x22 };
-		byte[] andXCommand = { (byte) 0xff };
-		byte[] reserved = { 0x00 };
-		byte[] andXOffset = { 0x67, 0x00 };
-		byte[] oplockLevel = { 0x00 };
-		byte[] fid = { (byte) 0x00, 0x40 };
-		byte[] createAction = { 0x01, 0x00, 0x00, 0x00 };
-		byte[] created = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-		byte[] lastAccess = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-		byte[] lastWrite = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-		byte[] change = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-		byte[] fileAttributes = { (byte) 0x80, 0x00, 0x00, 0x00 };
-		byte[] allocationSize = { 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
-				0x00 };
-		byte[] endOfFile = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-		byte[] fileType = { 0x02, 0x00 };
-		byte[] ipcState = { (byte) 0xff, 0x05 };
-		byte[] isDirectory = { 0x00 };
-		byte[] byteCount = { 0x00, 0x00 };
-
-		byte[] response = HelperUtils.concat(wordCount, andXCommand, reserved,
-				andXOffset, oplockLevel, fid, createAction, created,
-				lastAccess, lastWrite, change, fileAttributes, allocationSize,
-				endOfFile, fileType, ipcState, isDirectory, byteCount);
-		return new Packet(wrapNetbios(wrapHeader(response)));
-	}
-
-	/**
-	 * Builds the session setup packet
-	 * 
-	 * @ret urn session setup packet
-	 */
-	private Packet getSessSetup() {
-		if (authenticateNext) {
-			return new Packet(getSetupAuth());
-		} else {
-			authenticateNext = true;
-			return new Packet(getSetupChal());
-		}
-	}
-
-	/**
-	 * Builds the session setup packet for authentication required
-	 * 
-	 * @return session setup authentication packet
-	 */
-	private byte[] getSetupAuth() {
-		byte[] wordCount = { 0x04 };
-		byte[] andXCommand = { (byte) 0xff };
-		byte[] reserved = { 0x00 };
-		byte[] andXOffset = { (byte) 0xa2, 0x00 };
-		byte[] action = { 0x01, 0x00 };
-		byte[] secBlobLength;
-		byte[] byteCount;
-		byte[] secBlob = { (byte) 0xa1, 0x07, 0x30, 0x05, (byte) 0xa0, 0x03,
-				0x0a, 0x01, 0x00 };
-		byte[] nativOS = HelperUtils.fillWithZeroExtended(serverVersion[0]
-				.getBytes());
-		byte[] nativLanMngr = HelperUtils.fillWithZeroExtended(serverVersion[1]
-				.getBytes());
-
-		byte[] buffer = ByteBuffer.allocate(4).putInt(secBlob.length).array();
-		secBlobLength = new byte[] { buffer[3], buffer[2] };
-		buffer = ByteBuffer.allocate(4)
-				.putInt(secBlob.length + nativOS.length + nativLanMngr.length)
-				.array();
-		byteCount = new byte[] { buffer[3], buffer[2] };
-
-		byte[] response = HelperUtils.concat(wordCount, andXCommand, reserved,
-				andXOffset, action, secBlobLength, byteCount, secBlob, nativOS,
-				nativLanMngr);
-		return wrapNetbios(wrapHeader(response));
-	}
-
-	/**
-	 * Builds the session setup challange packet
-	 * 
-	 * @return session setup challange packet
-	 */
-	private byte[] getSetupChal() {
-		byte[] wordCount = { 0x04 };
-		byte[] andXCommand = { (byte) 0xff };
-		byte[] reserved = { 0x00 };
-		byte[] andXOffset = { 0x60, 0x01 };
-		byte[] action = { 0x00, 0x00 };
-		byte[] secBlobLength;
-		byte[] byteCount;
-		byte[] secBlob = { (byte) 0xa1, (byte) 0x81, (byte) 0xc4 };
-		byte[] negToken = { 0x30, (byte) 0x81, (byte) 0xc1, (byte) 0xa0, 0x03,
-				0x0a, 0x01 };
-		byte[] negResult = { 0x01 };
-		byte[] negToken2 = { (byte) 0xa1, 0x0c, 0x06, 0x0a };
-		byte[] supportedMech = { 0x2b, 0x06, 0x01, 0x04, 0x01, (byte) 0x82,
-				0x37, 0x02, 0x02, 0x0a };
-		byte[] negToken3 = { (byte) 0xa2, (byte) 0x81, (byte) 0xab, 0x04,
-				(byte) 0x81, (byte) 0xa8 };
-		byte[] ntlmsspId = { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00 };
-		byte[] nlmMsgType = { 0x02, 0x00, 0x00, 0x00 };
-		byte[] buffer = ByteBuffer.allocate(4).putInt(serverName.length)
-				.array();
-		byte[] targetNameLength = new byte[] { buffer[3], buffer[2] };
-		byte[] targetNameMaxLength = new byte[] { buffer[3], buffer[2] };
-		byte[] targetNameOffset = { 0x38, 0x00, 0x00, 0x00 };
-		byte[] flags = { 0x15, (byte) 0x82, (byte) 0x8a, 0x60 };
-		if (!serverVersion[0].contains("Unix")) {
-			flags[3] = (byte) (flags[3] | 0x02);
-		}
-		byte[] challenge = HelperUtils.randomBytes(8);
-		byte[] reserved2 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-		byte[] targetInfoLength = { 0x60, 0x00 };
-		byte[] targetInfoMaxLength = { 0x60, 0x00 };
-		byte[] targetInfoOffset = { 0x48, 0x00, 0x00, 0x00 };
-		byte[] version = null;
-		if (serverVersion[0].contains("Windows 7")
-				|| serverVersion[0].contains("Windows Server 2008")) {
-			version = new byte[] { 0x06, 0x01, (byte) 0xb0, 0x1d, 0x00, 0x00,
-					0x00, 0x0f };
-		} else if (serverVersion[0].contains("Windows 8")
-				|| serverVersion[0].contains("Windows Server 2012")) {
-			version = new byte[] { 0x06, 0x02, (byte) 0xf0, 0x23, 0x00, 0x00,
-					0x00, 0x0f };
-		}
-		// serverName
-		byte[] attributeNBDomain = { 0x02, 0x00, 0x10, 0x00 };
-		// serverName
-		byte[] attributeNBcomputer = { 0x01, 0x00, 0x10, 0x00 };
-		// serverName
-		byte[] attributeDNSDomain = { 0x04, 0x00, 0x10, 0x00 };
-		// serverName
-		byte[] attributeDNScomputer = { 0x03, 0x00, 0x10, 0x00 };
-		// serverName
-		byte[] attributeTimeStamp = { 0x07, 0x00, 0x08, 0x00 };
-		byte[] timeStamp = getTimeInBytes();
-		byte[] attributeEnd = { 0x00, 0x00, 0x00, 0x00 };
-		secBlob = HelperUtils.concat(secBlob, negToken, negResult, negToken2,
-				supportedMech, negToken3, ntlmsspId, nlmMsgType,
-				targetNameLength, targetNameMaxLength, targetNameOffset, flags,
-				challenge, reserved2, targetInfoLength, targetInfoMaxLength,
-				targetInfoOffset, version, serverName, attributeNBDomain,
-				serverName, attributeNBcomputer, serverName,
-				attributeDNSDomain, serverName, attributeDNScomputer,
-				serverName, attributeTimeStamp, timeStamp, attributeEnd);
-		byte[] nativOS = HelperUtils.fillWithZeroExtended(serverVersion[0]
-				.getBytes());
-		byte[] nativLanMngr = HelperUtils.fillWithZeroExtended(serverVersion[1]
-				.getBytes());
-		buffer = ByteBuffer.allocate(4).putInt(secBlob.length).array();
-		secBlobLength = new byte[] { buffer[3], buffer[2] };
-		buffer = ByteBuffer.allocate(4)
-				.putInt(secBlob.length + nativOS.length + nativLanMngr.length)
-				.array();
-		byteCount = new byte[] { buffer[3], buffer[2] };
-
-		ntStat = new byte[] { 0x16, 0x00, 0x00, (byte) 0xc0 };
-		userID = new byte[] { 0x00, 0x08 };
-
-		byte[] response = HelperUtils.concat(wordCount, andXCommand, reserved,
-				andXOffset, action, secBlobLength, byteCount, secBlob, nativOS,
-				nativLanMngr);
-		return wrapNetbios(wrapHeader(response));
-	}
-
-	/**
-	 * Returns the command number from the current message
-	 * 
-	 * @return command number
-	 */
-	private byte getSmbCommand() {
-		return smbCommand[0];
-	}
-
-	/**
-	 * Builds the trans packet
-	 * 
-	 * @return trans packet
-	 */
-	private Packet getTrans() {
-		byte[] transSub = getTransSub();
-		byte[] response = null;
-		if (transSub[0] == 0x00 && transSub[1] == 0x0b) { // bind_ack
-			byte[] wordCount = { 0x0a };
-			byte[] totalParamCount = { 0x00, 0x00 };
-			byte[] totalDataCount = { 0x44, 0x00 };
-			byte[] reserved = { 0x00, 0x00 };
-			byte[] paramCount = { 0x00, 0x00 };
-			byte[] paramOffset = { 0x38, 0x00 };
-			byte[] paramDisplace = { 0x00, 0x00 };
-			byte[] dataCount = { 0x44, 0x00 };
-			byte[] dataOffset = { 0x38, 0x00 };
-			byte[] dataDisplace = { 0x00, 0x00 };
-			byte[] setupCount = { 0x00 };
-			byte[] reserved2 = { 0x00 };
-			byte[] byteCount = { 0x45, 0x00 };
-			byte[] padding = { 0x00 };
-
-			byte[] dcerpc = getDceRpc(transSub, 0);
-
-			response = HelperUtils.concat(wordCount, totalParamCount,
-					totalDataCount, reserved, paramCount, paramOffset,
-					paramDisplace, dataCount, dataOffset, dataDisplace,
-					setupCount, reserved2, byteCount, padding, dcerpc);
-
-		} else if (transSub[0] == 0x00 && transSub[1] == 0x00) { // netShareEnumAll
-			byte[] wordCount = { 0x0a };
-			byte[] totalParamCount = { 0x00, 0x00 };
-			byte[] totalDataCount = { 0x20, 0x01 };
-			byte[] reserved = { 0x00, 0x00 };
-			byte[] paramCount = { 0x00, 0x00 };
-			byte[] paramOffset = { 0x38, 0x00 };
-			byte[] paramDisplace = { 0x00, 0x00 };
-			byte[] dataCount = { 0x20, 0x01 };
-			byte[] dataOffset = { 0x38, 0x00 };
-			byte[] dataDisplace = { 0x00, 0x00 };
-			byte[] setupCount = { 0x00 };
-			byte[] reserved2 = { 0x00 };
-			byte[] byteCount = new byte[2]/* = {0x21, 0x01} */;
-			byte[] padding = { 0x00 };
-
-			byte[] dcerpc = new byte[24];
-
-			byte[] levelPointer = { 0x01, 0x00, 0x00, 0x00 };
-			byte[] ctr = { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00 };
-			byte[] ctr1 = { 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00,
-					0x03, 0x00, 0x00, 0x00 };
-			byte[] array1Pointer = { 0x08, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
-					(byte) 0x80, 0x0c, 0x00, 0x02, 0x00 };
-			byte[] array2Pointer = { 0x10, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
-					(byte) 0x80, 0x14, 0x00, 0x02, 0x00 };
-			byte[] array3Pointer = { 0x18, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00,
-					(byte) 0x80, 0x1c, 0x00, 0x02, 0x00 };
-			byte[] array1 = { 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-					0x07, 0x00, 0x00, 0x00, 0x41, 0x00, 0x44, 0x00, 0x4d, 0x00,
-					0x49, 0x00, 0x4e, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00,
-					0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x00,
-					0x00, 0x00, 0x52, 0x00, 0x65, 0x00, 0x6d, 0x00, 0x6f, 0x00,
-					0x74, 0x00, 0x65, 0x00, 0x20, 0x00, 0x41, 0x00, 0x64, 0x00,
-					0x6d, 0x00, 0x69, 0x00, 0x6e, 0x00, 0x00, 0x00 };
-			byte[] array2 = { 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
-					0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x43, 0x00, 0x24, 0x00,
-					0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00,
-					0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x44, 0x00, 0x65, 0x00,
-					0x66, 0x00, 0x61, 0x00, 0x75, 0x00, 0x6c, 0x00, 0x74, 0x00,
-					0x20, 0x00, 0x73, 0x00, 0x68, 0x00, 0x61, 0x00, 0x72, 0x00,
-					0x65, 0x00 };
-			byte[] array3 = { 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00,
-					0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x49, 0x00, 0x50, 0x00,
-					0x43, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00,
-					0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00,
-					0x52, 0x00, 0x65, 0x00, 0x6d, 0x00, 0x6f, 0x00, 0x74, 0x00,
-					0x65, 0x00, 0x20, 0x00, 0x49, 0x00, 0x50, 0x00, 0x43, 0x00,
-					0x00, 0x00 };
-			byte[] totalEntries = { 0x00, 0x00, 0x03, 0x00, 0x00, 0x00 };
-			byte[] referentID = { 0x20, 0x00, 0x02, 0x00 };
-			byte[] resumeHandle = { 0x00, 0x00, 0x00, 0x00 };
-			byte[] windowsError = { 0x00, 0x00, 0x00, 0x00 };
-			int tmp = padding.length + dcerpc.length + levelPointer.length
-					+ ctr.length + ctr1.length + array1Pointer.length
-					+ array2Pointer.length + array3Pointer.length
-					+ array1.length + array2.length + array3.length
-					+ totalEntries.length + referentID.length
-					+ resumeHandle.length + windowsError.length;
-			byte[] tmp2 = ByteBuffer.allocate(4).putInt(tmp).array();
-			byteCount = new byte[] { tmp2[3], tmp2[2] };
-			dcerpc = getDceRpc(transSub, tmp - 1);
-
-			response = HelperUtils.concat(wordCount, totalParamCount,
-					totalDataCount, reserved, paramCount, paramOffset,
-					paramDisplace, dataCount, dataOffset, dataDisplace,
-					setupCount, reserved2, byteCount, padding, dcerpc,
-					levelPointer, ctr, ctr1, array1Pointer, array2Pointer,
-					array3Pointer, array1, array2, array3, totalEntries,
-					referentID, resumeHandle, windowsError);
-		}
-
-		return new Packet(wrapNetbios(wrapHeader(response)));
-	}
-
-	/**
-	 * Builds the trans2 packet
-	 * 
-	 * @return trans2 packet
-	 */
-	private Packet getTrans2() {
-		byte[] response = null;
-		byte[] wordCount = { 0x00 };
-		byte[] andXCommand = { 0x00, 0x00 };
-		ntStat = new byte[] { 0x22, 0x00, 0x00, (byte) 0xc0 };
-		response = HelperUtils.concat(wordCount, andXCommand);
-		return new Packet(wrapNetbios(wrapHeader(response)));
-	}
-
-	/**
-	 * Extracts the trans sub packet from message
-	 * 
-	 * @return trans sub packet
-	 */
-	private byte[] getTransSub() {
-		byte[] transSub = new byte[2];
-		if (smbCommand[0] == 0x32)
-			transSub = new byte[] { message[66], message[65] };
-		else if (smbCommand[0] == 0x25)
-			transSub = new byte[] { 0x00, message[90] };
-		else
-			transSub = new byte[] { 0x00, 0x00 };
-		return transSub;
-	}
-
-	/**
-	 * Builds the tree connect packet
-	 * 
-	 * @return tree connect packet
-	 */
-	private Packet getTreeCon() {
-		String str = HelperUtils.byteToStr(message);
-		byte[] wordCount = { 0x00 };
-		byte[] andXCommand = { 0x00, 0x00 };
-		byte[] response = null;
-		if (str.contains("IPC$") || str.contains("C$")) {
-			wordCount = new byte[] { 0x07 };
-			andXCommand = new byte[] { (byte) 0xff };
-			byte[] reserved = { 0x00 };
-			byte[] andXOffset = { 0x38, 0x00 };
-			byte[] optionalSupport = { 0x01, 0x00 };
-			byte[] maxShareAccess = { (byte) 0xff, (byte) 0xff, 0x1f, 0x00 };
-			byte[] guestMaxShareAccess = { (byte) 0xff, (byte) 0xff, 0x1f, 0x00 };
-			byte[] byteCount = { 0x07, 0x00 };
-			byte[] service = { 0x49, 0x50, 0x43, 0x00 };
-			byte[] extraParameters = { 0x00, 0x00, 0x00 };
-
-			treeID = new byte[] { 0x00, 0x08 };
-
-			response = HelperUtils.concat(wordCount, andXCommand, reserved,
-					andXOffset, optionalSupport, maxShareAccess,
-					guestMaxShareAccess, byteCount, service, extraParameters);
-		} else if (str.contains("ADMIN$")) {
-			ntStat = new byte[] { 0x22, 0x00, 0x00, (byte) 0xc0 };
-			response = HelperUtils.concat(wordCount, andXCommand);
-		} else {
-			ntStat = new byte[] { (byte) 0xcc, 0x00, 0x00, (byte) 0xc0 };
-			response = HelperUtils.concat(wordCount, andXCommand);
-		}
-
-		return new Packet(wrapNetbios(wrapHeader(response)));
-	}
-
-	/**
-	 * Builds the tree disconnect packet
-	 * 
-	 * @return tree disconnect packet
-	 */
-	private Packet getTreeDisc() {
-		byte[] wordCount = { 0x00 };
-		byte[] byteCount = { 0x00, 0x00 };
-
-		smbCommand[0] = 0x71;
-
-		byte[] response = HelperUtils.concat(wordCount, byteCount);
-
-		return new Packet(wrapNetbios(wrapHeader(response)));
-	}
-
-	/**
-	 * Breaks a message from the client down into its components
-	 * 
-	 * @param message
-	 *            that is analyzed
-	 */
-	private void parseMessageHeader(byte[] message) {
-		this.message = message;
-		serverComp = new byte[] { message[4], message[5], message[6],
-				message[7] };
-		smbCommand = new byte[] { message[8] };
-		ntStat = new byte[] { message[9], message[10], message[11], message[12] };
-		smbFlags = new byte[] { (byte) (message[13] | 0x80) }; // | 0x80 for
-																// mark response
-																// bit
-		smbFlags2 = new byte[] { message[14], message[15] };
-		processIDHigh = new byte[] { message[16], message[17] };
-		signature = new byte[] { message[18], message[19], message[20],
-				message[21], message[22], message[23], message[24], message[25] };
-		reserved = new byte[] { message[26], message[27] };
-		treeID = new byte[] { message[28], message[29] };
-		processID = new byte[] { message[30], message[31] };
-		userID = new byte[] { message[32], message[33] };
-		multiplexID = new byte[] { message[34], message[35] };
-	}
-
-	/**
-	 * Wraps the header around a response
-	 * 
-	 * @param response
-	 *            that is wrapped
-	 * @return wrapped response
-	 */
-	private byte[] wrapHeader(byte[] response) {
-		byte[] header = new byte[0];
-		return HelperUtils.concat(header, serverComp, smbCommand, ntStat,
-				smbFlags, smbFlags2, processIDHigh, signature, reserved,
-				treeID, processID, userID, multiplexID, response);
-	}
-
-	/**
-	 * Wraps the Netbios header around a response
-	 * 
-	 * @param response
-	 *            that is wrapped
-	 * @return wrapped response
-	 */
-	private byte[] wrapNetbios(byte[] response) {
-		byte[] netbios = { 0x00 };
-		byte[] buffer = ByteBuffer.allocate(4).putInt(response.length).array(); // allocate(4)
-																				// because
-																				// int
-																				// is
-																				// 4
-																				// bytes
-																				// long
-		byte[] netbiosLength = { buffer[1], buffer[2], buffer[3] }; // only
-																	// bytes 1-3
-																	// needed,
-																	// byte 0 is
-																	// not
-																	// needed
-		return HelperUtils.concat(netbios, netbiosLength, response);
-	}
-
 }

+ 21 - 27
src/de/tudarmstadt/informatik/hostage/protocol/SSH.java

@@ -44,7 +44,7 @@ public class SSH implements Protocol {
 	 *            that are converted
 	 * @return converted byte[] as int
 	 */
-	private static int byteToInt(byte[] bytes) {
+	private int byteToInt(byte[] bytes) {
 		int convertedInteger = 0;
 		for (int i = 0; i < bytes.length; i++) {
 			convertedInteger <<= 8;
@@ -53,7 +53,7 @@ public class SSH implements Protocol {
 		return convertedInteger;
 	}
 
-	private static String initSshType() {
+	private String initSshType() {
 		SecureRandom rnd = new SecureRandom();
 		int majorVersion = rnd.nextInt(possibleSshTypes.length);
 		return "OpenSSH_"
@@ -70,18 +70,18 @@ public class SSH implements Protocol {
 	private boolean useEncryption = false;
 
 	// version stuff
-	private static String[][][] possibleSshTypes = {
+	private String[][][] possibleSshTypes = {
 			{ { "3." }, { "4", "5", "6", "7", "8", "9" } },
 			{ { "4." }, { "0", "1", "2", "3", "4", "5", "6", "7", "9" } },
 			{ { "5." }, { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" } },
 			{ { "6." }, { "0", "1", "2", "3", "4" } } };
 
 	// server infos
-	private static String serverVersion = "SSH-2.0-";
+	private String serverVersion = "SSH-2.0-";
 
-	private static String serverType = initSshType();
+	private String serverType = initSshType();
 
-	private static String serverName = HelperUtils.getRandomString(16, false);
+	private String serverName = HelperUtils.getRandomString(16, false);
 
 	private int packetNumber = 0;
 
@@ -180,7 +180,7 @@ public class SSH implements Protocol {
 		switch (state) {
 		case NONE:
 			responsePackets
-					.add(new Packet(serverVersion + serverType + "\r\n"));
+					.add(new Packet(serverVersion + serverType + "\r\n", toString()));
 			state = STATE.SERVER_VERSION;
 			break;
 		case SERVER_VERSION:
@@ -305,7 +305,7 @@ public class SSH implements Protocol {
 		try {
 			TypesReader tr = new TypesReader(request, 6);
 			userName = tr.readString();
-			terminalPrefix = "[" + userName + "@" + serverName + "]$";
+			terminalPrefix = "[" + userName + "@" + serverName + " ~]$ ";
 		} catch (IOException e) {
 			e.printStackTrace();
 		}
@@ -448,7 +448,7 @@ public class SSH implements Protocol {
 		if (request[5] != 0x14) {
 			position = 1;
 			for (int i = 0; i < request.length; i++, position++) {
-				if (request[i] == 0xa)
+				if (request[i] == 0x0a)
 					break;
 			}
 		}
@@ -583,27 +583,24 @@ public class SSH implements Protocol {
 	 */
 	private Packet terminalReply(byte[] request) {
 		TypesReader tr = new TypesReader(request, 6);
-		String messsage = "";
-		System.out.println(HelperUtils.bytesToHexString(request));
+		String message = "";
 		try {
 			tr.readUINT32();
-			messsage = tr.readString();
-			System.out.println(messsage);
-			if (messsage.contains("\r")) {
-				System.out.println("hi");
+			message = tr.readString();
+			if (message.contains("\r")) {
 				if (command.toString().contains("exit")) {
 					state = STATE.CLOSED; // ugly style
 					return disconnectReply(2);
 				}
-				messsage = "\r\nbash: " + command + " :command not found\r\n"
+				message = "\r\nbash: " + command + " :command not found\r\n"
 						+ terminalPrefix;
 				command = new StringBuffer();
-			} else if (messsage.contains(new String(new char[] { '\u007F' }))
+			} else if (message.contains(new String(new char[] { '\u007F' }))
 					&& command.length() > 0) {
 				command = command
 						.delete(command.length() - 1, command.length());
 			} else {
-				command.append(messsage);
+				command.append(message);
 			}
 		} catch (IOException e) {
 			e.printStackTrace();
@@ -611,7 +608,7 @@ public class SSH implements Protocol {
 		TypesWriter tw = new TypesWriter();
 		tw.writeByte(0x5e); // msgcode
 		tw.writeUINT32(recipientChannel);
-		tw.writeString(messsage);
+		tw.writeString(message);
 		return wrapPacket(tw.getBytes());
 	}
 
@@ -623,9 +620,8 @@ public class SSH implements Protocol {
 	 * @return wrapped packet.
 	 */
 	private Packet wrapPacket(byte[] response) {
-		int packetLength = 5 + response.length; // 4 byte packet length, 1 byte
-												// padding length, payload
-												// length
+		// 4 byte packet length, 1 byte padding length, payload length
+		int packetLength = 5 + response.length;
 		int paddingLengthCBS = cipherBlockSize
 				- (packetLength % cipherBlockSize);
 		int paddingLength8 = 8 - (packetLength % 8);
@@ -633,10 +629,8 @@ public class SSH implements Protocol {
 				: paddingLength8;
 		if (paddingLength < 4)
 			paddingLength += cipherBlockSize;
-		packetLength = packetLength + paddingLength - 4; // add padding string
-															// length to packet
-															// length
-
+		// add padding string length to packet length
+		packetLength = packetLength + paddingLength - 4; 
 		byte[] packetLen = ByteBuffer.allocate(4).putInt(packetLength).array();
 		byte[] paddingLen = { (byte) paddingLength };
 		byte[] paddingString = HelperUtils.randomBytes(paddingLength);
@@ -649,6 +643,6 @@ public class SSH implements Protocol {
 		}
 		packetNumber++;
 
-		return new Packet(wrappedResponse);
+		return new Packet(wrappedResponse, toString());
 	}
 }

+ 68 - 26
src/de/tudarmstadt/informatik/hostage/protocol/TELNET.java

@@ -3,6 +3,10 @@ package de.tudarmstadt.informatik.hostage.protocol;
 import java.util.ArrayList;
 import java.util.List;
 
+import android.content.Context;
+
+import de.tudarmstadt.informatik.hostage.Hostage;
+import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.wrapper.Packet;
 
@@ -12,6 +16,7 @@ import de.tudarmstadt.informatik.hostage.wrapper.Packet;
  * @author Wulf Pfeiffer
  */
 public class TELNET implements Protocol {
+	
 	/**
 	 * Represents the states of the protocol
 	 */
@@ -25,19 +30,26 @@ public class TELNET implements Protocol {
 	private STATE state = STATE.NONE;
 
 	/** user entered by the client */
-	private static byte[] user;
+	private byte[] user;
 
 	/** last command sent by the client */
 	private byte[] command;
 
 	/** name of the server */
-	private static String serverName = HelperUtils.getRandomString(16, false);
+	private String serverName = HelperUtils.getRandomString(16, false);
 
+	private String serverVersion = initServerVersion();
+	
+	private String login = initLogin();
+	
+	private String serverBanner = initServerBanner();
+	
 	/** command line prefix */
 	private static byte[] sessionToken = null;
 
 	/** options requested by the server */
-	private static final byte[] optionRequest = { (byte) 0xff, (byte) 0xfb,
+	private static final byte[] optionRequest = {
+			(byte) 0xff, (byte) 0xfb,
 			0x03, // will suppress go ahead
 			(byte) 0xff, (byte) 0xfb, 0x01 // will echo
 	};
@@ -77,13 +89,13 @@ public class TELNET implements Protocol {
 
 		switch (state) {
 		case NONE:
-			responsePackets.add(new Packet(optionRequest));
+			responsePackets.add(new Packet(optionRequest, toString()));
 			state = STATE.OPEN;
 			break;
 		case OPEN:
 			if (request != null) {
-				responsePackets.add(new Packet(getOptionResponse(request)));
-				responsePackets.add(new Packet(serverName + " login: "));
+				responsePackets.add(new Packet(getOptionResponse(request), toString()));
+				responsePackets.add(new Packet(login + "login: ", toString()));
 				state = STATE.LOGIN;
 			}
 			break;
@@ -95,22 +107,26 @@ public class TELNET implements Protocol {
 					byte[] buffer = new byte[request.length - 2];
 					System.arraycopy(request, 0, buffer, 0, request.length - 2);
 					user = HelperUtils.concat(user, buffer);
-					responsePackets.add(new Packet(buffer));
+					responsePackets.add(new Packet(buffer, toString()));
 				}
-				responsePackets.add(new Packet("\r\n"));
-				responsePackets.add(new Packet("Password: "));
+				responsePackets.add(new Packet("\r\n", toString()));
+				responsePackets.add(new Packet("password: ", toString()));
 				state = STATE.AUTHENTICATE;
-				sessionToken = HelperUtils.concat(sessionPrefix, user,
-						"@".getBytes(), serverName.getBytes(), sessionMiddle,
-						user, "@".getBytes(), serverName.getBytes(),
-						sessionSuffix);
+				if (serverVersion.contains("Windows")) {
+					sessionToken = HelperUtils.concat("C:\\Users\\".getBytes(), user, ">".getBytes());
+				} else {
+					sessionToken = HelperUtils.concat(sessionPrefix, user,
+							"@".getBytes(), serverName.getBytes(), sessionMiddle,
+							user, "@".getBytes(), serverName.getBytes(),
+							sessionSuffix);
+				}
 				break;
 			} else if (checkForByte(request, (byte) 0x7f) && user != null
 					&& user.length != 0) {
 				byte[] tmp = new byte[user.length - 1];
 				System.arraycopy(user, 0, tmp, 0, user.length - 1);
 				user = tmp;
-				responsePackets.add(new Packet("\b \b"));
+				responsePackets.add(new Packet("\b \b", toString()));
 				break;
 			} else if (!checkForByte(request, (byte) 0xff)) {
 				if (user == null)
@@ -124,11 +140,11 @@ public class TELNET implements Protocol {
 			if (request == null)
 				break;
 			else if (checkForByte(request, (byte) 0x0d)) {
-				responsePackets.add(new Packet("\r\n"));
-				responsePackets.add(new Packet(sessionToken));
+				responsePackets.add(new Packet("\r\n"+serverBanner, toString()));
+				responsePackets.add(new Packet(sessionToken, toString()));
 				state = STATE.LOGGED_IN;
 			} else if (checkForByte(request, (byte) 0x7f)) {
-				responsePackets.add(new Packet("\b \b"));
+				responsePackets.add(new Packet("\b \b", toString()));
 			}
 			break;
 		case LOGGED_IN:
@@ -139,20 +155,20 @@ public class TELNET implements Protocol {
 					byte[] buffer = new byte[request.length - 2];
 					System.arraycopy(request, 0, buffer, 0, request.length - 2);
 					command = HelperUtils.concat(command, buffer);
-					responsePackets.add(new Packet(buffer));
+					responsePackets.add(new Packet(buffer, toString()));
 				}
 				if (command == null) {
-					responsePackets.add(new Packet("\r\n"));
-					responsePackets.add(new Packet(sessionToken));
+					responsePackets.add(new Packet("\r\n", toString()));
+					responsePackets.add(new Packet(sessionToken, toString()));
 				} else if (new String(command).contains("exit")) {
-					responsePackets.add(new Packet("\r\nlogout\r\n"));
+					responsePackets.add(new Packet("\r\nlogout\r\n", toString()));
 					state = STATE.CLOSED;
 				} else {
 					String bash = "\r\n-bash: " + new String(command)
 							+ ": command not found";
-					responsePackets.add(new Packet(bash));
-					responsePackets.add(new Packet("\r\n"));
-					responsePackets.add(new Packet(sessionToken));
+					responsePackets.add(new Packet(bash, toString()));
+					responsePackets.add(new Packet("\r\n", toString()));
+					responsePackets.add(new Packet(sessionToken, toString()));
 					command = null;
 				}
 			} else if (checkForByte(request, (byte) 0x7f) && command != null
@@ -160,7 +176,7 @@ public class TELNET implements Protocol {
 				byte[] tmp = new byte[command.length - 1];
 				System.arraycopy(command, 0, tmp, 0, command.length - 1);
 				command = tmp;
-				responsePackets.add(new Packet("\b \b"));
+				responsePackets.add(new Packet("\b \b", toString()));
 				break;
 			} else if (!checkForByte(request, (byte) 0xff)) {
 				if (command == null)
@@ -171,7 +187,7 @@ public class TELNET implements Protocol {
 			}
 			break;
 		default:
-			responsePackets.add(new Packet("\r\nlogout\r\n"));
+			responsePackets.add(new Packet("\r\nlogout\r\n", toString()));
 			state = STATE.CLOSED;
 			break;
 		}
@@ -187,6 +203,32 @@ public class TELNET implements Protocol {
 	public TALK_FIRST whoTalksFirst() {
 		return TALK_FIRST.SERVER;
 	}
+	
+	private static String initServerVersion() {
+		String sharedPreferencePath = Hostage.getContext().getString(
+				R.string.shared_preference_path);
+		String profile = Hostage
+				.getContext()
+				.getSharedPreferences(sharedPreferencePath,
+						Context.MODE_PRIVATE).getString("os", "");
+		return profile;
+	}
+	
+	private String initServerBanner() {
+		if (serverVersion.contains("Windows")) {
+			return "\r\n*===============================================================\r\n"
+					+ "Microsoft Telnet Server.\r\n"
+					+ "*===============================================================\r\n";
+		}
+		return "";
+	}
+	
+	private String initLogin() {
+		if (serverVersion.contains("Windows")) {
+			return "Welcome to Microsoft Telnet Service \r\n\r\n";
+		}
+		return "Debian GNU/Linux 7.0\r\n";
+	}
 
 	/**
 	 * Checks a byte array for occurence of one byte.

+ 51 - 0
src/de/tudarmstadt/informatik/hostage/protocol/smbutils/NBDS.java

@@ -0,0 +1,51 @@
+package de.tudarmstadt.informatik.hostage.protocol.smbutils;
+
+import java.nio.ByteBuffer;
+
+import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+
+
+public class NBDS {
+	
+	private byte[] type;
+	private byte[] flags;
+	private byte[] id;
+	private byte[] srcIP;
+	private byte[] srcPort;
+	private byte[] length;
+	private byte[] offset;
+	private byte[] srcName;
+	private byte[] dstName;
+	private SMBPacket smb;
+	
+	public NBDS(byte[] transactID, byte[] addr, String src, String dst, int nbdstype) {
+		this.type = new byte[]{0x11};
+		flags = new byte[]{0x0a};
+		id = transactID;
+		srcIP = addr;
+		srcPort = new byte[]{0x00, (byte) 0x8a};
+		offset = new byte[]{0x00, 0x00};
+		length = new byte[2];
+		srcName = NMBStringCoder.wrapNBNSName(NMBStringCoder.encodeNBNSName(src.getBytes()), NBNSService.WORKSTATION);
+		if (nbdstype == NBDSType.REQUEST_ANNOUNCEMENT || nbdstype == NBDSType.LOCAL_MASTER_ANNOUNCEMENT_ALL) {
+			dstName = NMBStringCoder.wrapNBNSName(NMBStringCoder.encodeNBNSName(dst.getBytes()), NBNSService.BROWSER_ELECTION);
+		} else if (nbdstype == NBDSType.DOMAIN_ANNOUNCEMENT) {
+			dstName = HelperUtils.concat(new byte[]{0x20, 0x41, 0x42, 0x41, 0x43}, NMBStringCoder.encodeNBNSName("__MSBROWSE__".getBytes()),
+					new byte[]{0x41, 0x43, 0x41, 0x42, 0x00});
+		} else {
+			dstName = NMBStringCoder.wrapNBNSName(NMBStringCoder.encodeNBNSName(dst.getBytes()), NBNSService.LOCAL_MASTER_BROWSER);
+		}
+		smb = new SMBPacket(null);
+		smb.prepareNextResponse(nbdstype, src, dst);
+		byte[] buffer = HelperUtils.concat(srcName, dstName, smb.getTrans());
+		byte[] lengthBuffer = ByteBuffer.allocate(4).putInt(buffer.length).array();
+		length[0] = lengthBuffer[2];
+		length[1] = lengthBuffer[3];
+	}
+	
+	public byte[] getBytes() {
+		return HelperUtils.concat(type, flags, id, srcIP, srcPort, length,
+				offset, srcName, dstName, smb.getTrans());
+	}
+
+}

+ 12 - 0
src/de/tudarmstadt/informatik/hostage/protocol/smbutils/NBDSType.java

@@ -0,0 +1,12 @@
+package de.tudarmstadt.informatik.hostage.protocol.smbutils;
+
+public class NBDSType {
+	
+	public static final int HOST_ANNOUNCEMENT = 0;
+	public static final int HOST_ANNOUNCEMENT_WITH_SERVICES = 1;
+	public static final int BROWSER = 2;
+	public static final int REQUEST_ANNOUNCEMENT = 3;
+	public static final int LOCAL_MASTER_ANNOUNCEMENT_ALL = 4;
+	public static final int DOMAIN_ANNOUNCEMENT = 5;
+	public static final int LOCAL_MASTER_ANNOUNCEMENT = 6;
+}

+ 190 - 0
src/de/tudarmstadt/informatik/hostage/protocol/smbutils/NBNS.java

@@ -0,0 +1,190 @@
+package de.tudarmstadt.informatik.hostage.protocol.smbutils;
+
+import java.nio.ByteBuffer;
+
+import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+
+
+public class NBNS {
+	
+	private byte[] transactID;
+	private byte[] flags;
+	private byte[] questions;
+	private byte[] answerRRs;
+	private byte[] authorityRRs;
+	private byte[] additionalRRs;
+	private byte[] payload;
+	private byte[] additional;
+	private byte[] addr;
+	private byte[] name;
+	private int type;
+	private int service;
+	
+	public NBNS(byte[] packet) {
+		transactID = new byte[]{packet[0], packet[1]};
+		flags = new byte[]{packet[2], packet[3]};
+		questions = new byte[]{packet[4], packet[5]};
+		answerRRs = new byte[]{packet[6], packet[7]};
+		authorityRRs = new byte[]{packet[8], packet[9]};
+		additionalRRs = new byte[]{packet[10], packet[11]};
+		int length = 0;
+		for (int i = 12; i < packet.length; i++, length++) {
+			if (packet[i] == 0x01) {
+				length++;
+				break;
+			}
+		}
+		payload = new byte[length];
+		for (int i = 0; i < payload.length; i++) {
+			payload[i] = packet[i+12];
+		}
+		additional = new byte[packet.length-12-length];
+		for (int i = 0; i < additional.length; i++) {
+			additional[i] = packet[i+12+length];
+		}
+	}
+	
+	public NBNS(byte[] transactID, String addr) {
+		this.transactID = transactID;
+		addressToBytes(addr);
+	}
+	
+	public NBNS(byte[] transactID, int type, int service, String name, String addr) {
+		this(transactID, addr);
+		this.type = type;
+		this.service = service;
+		setName(name);
+	}
+	
+	private void preparePacket() {
+		switch (type) {
+		case NBNSType.REGISTRATION_UNIQUE:
+			prepareRegistrationPacket();
+			break;
+		case NBNSType.REGISTRATION_GROUP:
+			prepareRegistrationPacket();
+			break;
+		case NBNSType.NAME_QUERY:
+			prepareNameQueryPacket();
+			break;
+		case NBNSType.REGISTRATION_MSBROWSE:
+			prepareRegistrationMsBrowse();
+			break;
+		default:
+		}
+	}
+	
+	private void prepareRegistrationPacket() {
+		flags = new byte[]{0x29, 0x10};
+		questions = new byte[]{0x00, 0x01};
+		answerRRs = new byte[]{0x00, 0x00};
+		authorityRRs = new byte[]{0x00, 0x00};
+		additionalRRs = new byte[]{0x00, 0x01};
+		payload = getPayload();
+		additional = getAdditionalRecords();
+	}
+	
+	private void prepareNameQueryPacket() {
+		flags = new byte[] {0x01, 0x10};
+		questions = new byte[]{0x00, 0x01};
+		answerRRs = new byte[]{0x00, 0x00};
+		authorityRRs = new byte[]{0x00, 0x00};
+		additionalRRs = new byte[]{0x00, 0x00};
+		payload = getPayload();
+	}
+	
+	private void prepareRegistrationMsBrowse() {
+		flags = new byte[]{0x29, 0x10};
+		questions = new byte[]{0x00, 0x01};
+		answerRRs = new byte[]{0x00, 0x00};
+		authorityRRs = new byte[]{0x00, 0x00};
+		additionalRRs = new byte[]{0x00, 0x01};
+		payload = HelperUtils.concat(new byte[]{0x20, 0x41, 0x42, 0x41, 0x43}, name,
+				new byte[]{0x41, 0x43, 0x41, 0x42, 0x00, 0x00, 0x20, 0x00, 0x01});
+		additional = getAdditionalRecords();
+	}
+	
+	private byte[] getPayload() {
+		byte[] payload = NMBStringCoder.wrapNBNSName(this.name, service);
+		byte[] type = {0x00, 0x20};
+		byte[] nbnsclass = {0x00, 0x01};
+		return HelperUtils.concat(payload, type, nbnsclass);
+	}
+		
+	private void addressToBytes(String addrString) {
+		String[] addrParts = addrString.split("\\.");
+		addr = new byte[4];
+		addr[0] = (byte)Integer.parseInt(addrParts[0]);
+		addr[1] = (byte)Integer.parseInt(addrParts[1]);
+		addr[2] = (byte)Integer.parseInt(addrParts[2]);
+		addr[3] = (byte)Integer.parseInt(addrParts[3]);
+	}
+	
+	public static byte[] getServiceBytes(int service) {
+		switch (service) {
+		case NBNSService.SERVER:
+			return new byte[]{0x43, 0x41};
+		case NBNSService.MESSENGER:
+			return new byte[]{0x41, 0x44};
+		case NBNSService.WORKSTATION:
+			return new byte[]{0x41, 0x41};
+		case NBNSService.BROWSER_ELECTION:
+			return new byte[]{0x42, 0x4f};
+		case NBNSService.LOCAL_MASTER_BROWSER:
+			return new byte[]{0x42, 0x4e};
+		default:
+			return new byte[]{0x43, 0x41};
+		}
+	}
+
+	private byte[] getAdditionalRecords() {
+		byte[] name = {(byte) 0xc0, 0x0c};
+		byte[] type = {0x00, 0x20};
+		byte[] nbnsclass = {0x00, 0x01};
+		byte[] timeToLive = {0x00, 0x00, 0x00, 0x00};
+		byte[] nameFlags = ((this.type == NBNSType.REGISTRATION_UNIQUE) ? new byte[]{0x00, 0x00} : new byte[]{(byte) 0x80, 0x00});
+		byte[] buffer = ByteBuffer.allocate(4).putInt(nameFlags.length + addr.length).array();
+		byte[] length = {buffer[2], buffer[3]};
+		return HelperUtils.concat(name, type, nbnsclass, timeToLive, length, nameFlags, addr);
+	}
+	
+	public byte[] getNextPacket() {
+		preparePacket();
+		transactID[1] += 0x01;
+		return getBytes();
+	}
+
+	public byte[] getBytes() {
+		return HelperUtils.concat(transactID, flags, questions, answerRRs, authorityRRs, additionalRRs, payload, additional);
+	}
+
+	public void setName(String name) {
+		this.name = name.getBytes();
+		this.name = NMBStringCoder.encodeNBNSName(this.name);
+	}
+
+	public void setType(int type) {
+		this.type = type;
+	}
+
+	public void setService(int service) {
+		this.service = service;
+	}
+
+	public byte[] getAndIncTransactID() {
+		byte[] response = new byte[2];
+		response[0] = transactID[0];
+		response[1] = transactID[1];
+		transactID[1] += 0x01;
+		return response;
+	}
+
+	public byte[] getAddr() {
+		return addr;
+	}
+
+	public byte[] getName() {
+		return name;
+	}
+	
+}

+ 10 - 0
src/de/tudarmstadt/informatik/hostage/protocol/smbutils/NBNSService.java

@@ -0,0 +1,10 @@
+package de.tudarmstadt.informatik.hostage.protocol.smbutils;
+
+public class NBNSService {
+	public static final int SERVER = 0;
+	public static final int MESSENGER = 1;
+	public static final int WORKSTATION = 2;
+	public static final int BROWSER_ELECTION = 3;
+	public static final int LOCAL_MASTER_BROWSER = 4;
+	public static final int BROWSER = 5;
+}

+ 8 - 0
src/de/tudarmstadt/informatik/hostage/protocol/smbutils/NBNSType.java

@@ -0,0 +1,8 @@
+package de.tudarmstadt.informatik.hostage.protocol.smbutils;
+
+public class NBNSType {
+	public static final int REGISTRATION_UNIQUE = 0;
+	public static final int REGISTRATION_GROUP = 1;
+	public static final int NAME_QUERY = 2;
+	public static final int REGISTRATION_MSBROWSE = 3;
+}

+ 229 - 0
src/de/tudarmstadt/informatik/hostage/protocol/smbutils/NMB.java

@@ -0,0 +1,229 @@
+package de.tudarmstadt.informatik.hostage.protocol.smbutils;
+
+import java.io.IOException;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.InetAddress;
+import java.net.SocketTimeoutException;
+import java.net.UnknownHostException;
+
+import de.tudarmstadt.informatik.hostage.net.MyDatagramSocketFactory;
+
+public class NMB extends Thread {
+	
+	private DatagramSocket nbnsSocket;
+	private DatagramSocket nbdsSocket;
+	private DatagramPacket packet;
+	private String ip;
+	private String[] ipParts;
+	private InetAddress dst;
+	private int nbnsPort = 137;
+	private int nbdsPort = 138;
+	private String username;
+	private String workgroup;
+	private NBNS nbns;
+	private NBDS nbds;
+	private volatile boolean smbRunning;
+	private Receiver receiver;
+	
+	public NMB(String ip, String username, String workgroup) {
+		try {
+			smbRunning = true;
+			this.username = username;
+			this.workgroup = workgroup;
+			this.ip = ip;
+			ipParts = ip.split("\\.");
+			String newHostAddr = ipParts[0] + "." + ipParts[1] + "." + ipParts[2] + ".255";
+			dst = InetAddress.getByName(newHostAddr);
+		} catch (UnknownHostException e) {
+			e.printStackTrace();
+		}
+	}
+	
+	private void sendPacket(NBNS nbns) {
+		try {
+			byte[] packetBytes = nbns.getNextPacket();
+			packet = new DatagramPacket(packetBytes, packetBytes.length, dst, nbnsPort);
+			nbnsSocket.send(packet);
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+	}
+	
+	private void sendPacket(NBDS nbds) {
+		try {
+			byte[] packetBytes = nbds.getBytes();
+			packet = new DatagramPacket(packetBytes, packetBytes.length, dst, nbdsPort);
+			nbdsSocket.send(packet);
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+	}
+	
+	private void registrate() {
+		registrateUser();
+		registrateGroup();
+	}
+	
+	private void registrateUser() {
+		nbns = new NBNS(new byte[]{0x50, 0x00}, NBNSType.REGISTRATION_UNIQUE, NBNSService.SERVER, username, ip);
+		sendPacket(nbns);
+		
+		nbns.setService(NBNSService.MESSENGER);
+		sendPacket(nbns);
+				
+		nbns.setService(NBNSService.WORKSTATION);
+		sendPacket(nbns);
+	}
+	
+	private void registrateGroup() {
+		nbns.setName(workgroup);
+		nbns.setType(NBNSType.REGISTRATION_GROUP);
+		sendPacket(nbns);
+		
+		nbns.setService(NBNSService.BROWSER_ELECTION);
+		sendPacket(nbns);
+	}
+	
+	private void browserElection() {
+		nbds = new NBDS(nbns.getAndIncTransactID(), nbns.getAddr(), username, workgroup, NBDSType.BROWSER);
+		sendPacket(nbds);
+	}
+	
+	private void registrateMsBrowse() {
+		nbns.setName("__MSBROWSE__");
+		nbns.setType(NBNSType.REGISTRATION_MSBROWSE);
+		nbns.setService(NBNSService.BROWSER);
+		sendPacket(nbns);
+	}
+	
+	private void registrateLocalMaster() {
+		nbns.setName(workgroup);
+		nbns.setType(NBNSType.REGISTRATION_UNIQUE);
+		nbns.setService(NBNSService.LOCAL_MASTER_BROWSER);
+		sendPacket(nbns);
+	}
+	
+	private void announceHost() {
+		nbds = new NBDS(nbns.getAndIncTransactID(), nbns.getAddr(), username, workgroup, NBDSType.HOST_ANNOUNCEMENT_WITH_SERVICES);
+		sendPacket(nbds);
+	}
+	
+	private void queryName() {
+		nbns.setType(NBNSType.NAME_QUERY);
+		nbns.setService(NBNSService.LOCAL_MASTER_BROWSER);
+		sendPacket(nbns);
+	}
+	
+	private void requestAnnouncement() {
+		nbds = new NBDS(nbns.getAndIncTransactID(), nbns.getAddr(), username, workgroup, NBDSType.REQUEST_ANNOUNCEMENT);
+		sendPacket(nbds);
+	}
+	
+	private void localMasterAnnouncementAll() {
+		nbds = new NBDS(nbns.getAndIncTransactID(), nbns.getAddr(), username, workgroup, NBDSType.LOCAL_MASTER_ANNOUNCEMENT_ALL);
+		sendPacket(nbds);
+	}
+	
+	private void domainAnnouncement() {
+		nbds = new NBDS(nbns.getAndIncTransactID(), nbns.getAddr(), username, workgroup, NBDSType.DOMAIN_ANNOUNCEMENT);
+		sendPacket(nbds);
+	}
+	
+	private void localMasterAnnouncement() {
+		nbds = new NBDS(nbns.getAndIncTransactID(), nbns.getAddr(), username, workgroup, NBDSType.LOCAL_MASTER_ANNOUNCEMENT);
+		sendPacket(nbds);
+	}
+
+	@Override
+	public void run() {		
+		try {
+			nbnsSocket = new MyDatagramSocketFactory().createDatagramSocket(nbnsPort);
+			nbnsSocket.connect(dst, nbnsPort);
+			nbdsSocket = new MyDatagramSocketFactory().createDatagramSocket(nbdsPort);
+			nbdsSocket.connect(dst, nbdsPort);
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+		
+		registrate();
+		receiver = new Receiver();
+		receiver.start();
+		announceHost();
+		queryName();
+		
+		registrate();
+		queryName();
+		
+		registrate();
+		queryName();
+		
+		registrate();
+		queryName();	
+		
+		browserElection();
+		browserElection();
+		browserElection();
+		browserElection();
+		
+		registrateMsBrowse();
+		registrateMsBrowse();
+		registrateMsBrowse();
+		registrateMsBrowse();
+		
+		registrateLocalMaster();
+		registrateLocalMaster();
+		registrateLocalMaster();
+		registrateLocalMaster();
+		
+		requestAnnouncement();
+		localMasterAnnouncementAll();
+		domainAnnouncement();
+		
+//		// domain/workgroup announcement
+//		// local master announcmen
+		
+		announceHost();	
+		
+		nbnsSocket.close();
+		nbdsSocket.close();
+	}
+
+	public synchronized void setSmbRunning(boolean smbRunning) {
+		this.smbRunning = smbRunning;
+	}
+	
+	private class Receiver extends Thread {
+		
+		private DatagramPacket packet;
+		private byte[] buffer;
+		private boolean masterAnswered = false;
+		
+		public Receiver() {
+			buffer = new byte[2048];
+			packet = new DatagramPacket(buffer, buffer.length);
+		}
+		
+		@Override
+		public void run() {
+			try {
+				nbnsSocket.setSoTimeout(1000);
+				try {
+					while (!masterAnswered) {
+						nbnsSocket.receive(packet);
+						if (!(packet.getAddress().toString().equals("/"+ip))) {
+							masterAnswered = true;
+							setSmbRunning(false);
+						}
+					}
+				} catch (SocketTimeoutException e) {
+					setSmbRunning(false);
+					e.printStackTrace();
+				}	
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+	}
+	
+}

+ 58 - 0
src/de/tudarmstadt/informatik/hostage/protocol/smbutils/NMBStringCoder.java

@@ -0,0 +1,58 @@
+package de.tudarmstadt.informatik.hostage.protocol.smbutils;
+
+import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+
+
+public class NMBStringCoder {
+
+	public static String decodeNBNSName(byte[] name) {
+		byte a_ascii = (byte) 'A';
+		byte[] reducedA = new byte[name.length];
+		for (int i = 0; i < name.length; i++) {
+			reducedA[i] = (byte)(name[i] - a_ascii);
+		}
+		byte[] converted = new byte[reducedA.length / 2];
+		for (int i = 0, j = 0; i < name.length && j < converted.length; i+=2, j++) {
+			byte b1 = (byte) (reducedA[i]<<4);
+			byte b2 = reducedA[i+1];
+			converted[j] = (byte) (b1 | b2);
+		}
+		return new String(converted);
+	}
+	
+	public static byte[] encodeNBNSName(byte[] name) {
+		byte a_ascii = (byte) 'A';
+		byte[] bytes = name;
+		byte[] converted = new byte[bytes.length * 2];
+		for (int i = 0, j = 0; i < bytes.length && j < converted.length; i++, j+=2) {
+			converted[j] = (byte)(bytes[i]>>4);
+			converted[j+1] = (byte)(bytes[i] & 0x0F);
+		}
+		byte[] addedA = new byte[converted.length];
+		for (int i = 0; i < converted.length; i++) {
+			addedA[i] = (byte) (converted[i] + a_ascii);
+		}
+		return addedA;
+	}
+	
+	public static byte[] wrapNBNSName(byte[] name, int service) {
+		byte[] nameStart = {0x20};
+		byte[] namePadding = null;
+		if (name.length < 32) {
+			int paddingLen = 32 - name.length;
+			namePadding = new byte[paddingLen];
+			for (int i = 0; i < namePadding.length; i+=2) {
+				if (i == namePadding.length-2) {
+					byte[] serviceBytes = NBNS.getServiceBytes(service);
+					namePadding[i] = serviceBytes[0];
+					namePadding[i+1] = serviceBytes[1];
+				} else {
+					namePadding[i] = 0x43;
+					namePadding[i+1] = 0x041;
+				}
+			}
+		}
+		byte[] nameEnd = {0x00};
+		return HelperUtils.concat(nameStart, name, namePadding, nameEnd);
+	}
+}

+ 802 - 0
src/de/tudarmstadt/informatik/hostage/protocol/smbutils/SMBPacket.java

@@ -0,0 +1,802 @@
+package de.tudarmstadt.informatik.hostage.protocol.smbutils;
+
+import java.nio.ByteBuffer;
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+import java.util.TimeZone;
+
+import javax.net.ssl.HostnameVerifier;
+
+import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+
+/**
+ * SMBPacket
+ * 
+ * @author Wulf Pfeiffer
+ */
+public class SMBPacket {
+	
+	private String[] serverVersion;
+	private static byte[] serverName = HelperUtils.fillWithZero(HelperUtils
+			.getRandomString(16, true).getBytes());
+	private byte[] message = null;
+	private static final byte[] serverGUID = HelperUtils.randomBytes(16);
+	private boolean authenticateNext = false;
+
+	// components of a SMB packet
+	private byte[] serverComp = new byte[4];
+	private byte[] smbCommand = new byte[1];
+	private byte[] ntStat = new byte[4];
+	private byte[] smbFlags = new byte[1];
+	private byte[] smbFlags2 = new byte[2];
+	private byte[] processIDHigh = new byte[2];
+	private byte[] signature = new byte[8];
+	private byte[] reserved = new byte[2];
+	private byte[] treeID = new byte[2];
+	private byte[] processID = new byte[2];
+	private byte[] userID = new byte[2];
+	private byte[] multiplexID = new byte[2];
+	
+	//special nbds stuff
+	private byte[] workgroup;
+	private int type;
+	
+	public SMBPacket(String[] serverVersion) {
+		this.serverVersion = serverVersion;
+	}
+	
+	public void prepareNextResponse(int type, String serverName, String workgroup) {
+		serverComp = new byte[] { (byte) 0xff, 0x53, 0x4d, 0x42 };
+		smbCommand = new byte[] { 0x25 };
+		ntStat = new byte[] { 0x00, 0x00, 0x00, 0x00 };
+		// | 0x80 for mark response bit
+		smbFlags = new byte[] { 0x00 }; 
+		smbFlags2 = new byte[] { 0x00, 0x00 };
+		processIDHigh = new byte[] { 0x00, 0x00 };
+		signature = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+		reserved = new byte[] { 0x00, 0x00 };
+		treeID = new byte[] { 0x00, 0x00 };
+		processID = new byte[] { 0x00, 0x00 };
+		userID = new byte[] { 0x00, 0x00 };
+		multiplexID = new byte[] { 0x00, 0x00 };
+		this.workgroup = workgroup.getBytes();
+		this.type = type;
+		SMBPacket.serverName = serverName.getBytes();
+	}
+	
+	public void prepareNextResponse(byte[] message) {
+		this.message = message;
+		serverComp = new byte[] { message[4], message[5], message[6],message[7] };
+		smbCommand = new byte[] { message[8] };
+		ntStat = new byte[] { message[9], message[10], message[11], message[12] };
+		// | 0x80 for mark response bit
+		smbFlags = new byte[] { (byte) (message[13] | 0x80) }; 
+		smbFlags2 = new byte[] { message[14], message[15] };
+		processIDHigh = new byte[] { message[16], message[17] };
+		signature = new byte[] { message[18], message[19], message[20],
+				message[21], message[22], message[23], message[24], message[25] };
+		reserved = new byte[] { message[26], message[27] };
+		treeID = new byte[] { message[28], message[29] };
+		processID = new byte[] { message[30], message[31] };
+		userID = new byte[] { message[32], message[33] };
+		multiplexID = new byte[] { message[34], message[35] };
+	}
+	
+	/**
+	 * Wraps the header around a response
+	 * 
+	 * @param response
+	 *            that is wrapped
+	 * @return wrapped response
+	 */
+	private byte[] wrapHeader(byte[] response) {
+		byte[] header = new byte[0];
+		return HelperUtils.concat(header, serverComp, smbCommand, ntStat,
+				smbFlags, smbFlags2, processIDHigh, signature, reserved,
+				treeID, processID, userID, multiplexID, response);
+	}
+
+	/**
+	 * Wraps the Netbios header around a response
+	 * 
+	 * @param response
+	 *            that is wrapped
+	 * @return wrapped response
+	 */
+	private byte[] wrapNetbios(byte[] response) {
+		byte[] netbios = { 0x00 };
+		// allocate(4) because int is 4 bytes long
+		byte[] buffer = ByteBuffer.allocate(4).putInt(response.length).array();
+		// only bytes 1-3 needed, byte 0 is not  needed
+		byte[] netbiosLength = { buffer[1], buffer[2], buffer[3] }; 
+		return HelperUtils.concat(netbios, netbiosLength, response);
+	}
+
+	/**
+	 * Evaluates what Dialects are offered by the client and which position the
+	 * used NT LM 0.12 dialect is at
+	 * 
+	 * @return position of the NT LM 0.12 dialect
+	 */
+	private byte[] evaluateDialect() {
+		byte[] dialectMsg = new byte[message.length - 39];
+		System.arraycopy(message, 39, dialectMsg, 0, message.length - 39);
+		short dialectNumber = 0;
+		for (int i = 0, start = 0; i < dialectMsg.length; i++) {
+			if (dialectMsg[i] == 0x00) {
+				byte[] dialect = new byte[i - start];
+				System.arraycopy(dialectMsg, start, dialect, 0, i - start);
+				if (HelperUtils.byteToStr(dialect).contains("NT LM 0.12")) {
+					return new byte[] { (byte) dialectNumber,
+							(byte) (dialectNumber >> 8) };
+				}
+				start = i + 1;
+				dialectNumber++;
+			}
+		}
+		return new byte[] { 0x00, 0x00 };
+	}
+
+	/**
+	 * Builds the close packet
+	 * 
+	 * @return close packet
+	 */
+	public byte[] getClose() {
+		byte[] wordCount = { 0x00 };
+		byte[] byteCount = { 0x00, 0x00 };
+
+		smbCommand = new byte[] { 0x04 };
+
+		byte[] response = HelperUtils.concat(wordCount, byteCount);
+
+		return wrapNetbios(wrapHeader(response));
+	}
+
+	/**
+	 * Builds the DCERPC packet
+	 * 
+	 * @return DCERPC packet
+	 */
+	public byte[] getDceRpc(byte[] transSub, int length) {
+		byte[] majorVersion = { 0x05 };
+		byte[] minorVersion = { 0x00 };
+		byte[] packetType = null;
+		byte[] packetFlags = { 0x03 };
+		byte[] dataRepres = { 0x10, 0x00, 0x00, 0x00 };
+		byte[] fragLength = null;
+		byte[] authLength = { 0x00, 0x00 };
+		byte[] callID = null;
+		byte[] response = null;
+
+		if (transSub[0] == 0x00 && transSub[1] == 0x0b) {
+			packetType = new byte[] { 0x0c };
+			fragLength = new byte[] { 0x44, 0x00 };
+			callID = new byte[] { 0x01, 0x00, 0x00, 0x00 };
+			byte[] maxXmitFrag = { (byte) 0xb8, 0x10 };
+			byte[] maxRecvFrag = { (byte) 0xb8, 0x10 };
+			byte[] assocGroup = { 0x4a, 0x41, 0x00, 0x00 };
+			byte[] scndryAddrLen = { 0x0d, 0x00 };
+			byte[] scndryAddr = { 0x5c, 0x50, 0x49, 0x50, 0x45, 0x5c, 0x73,
+					0x72, 0x76, 0x73, 0x76, 0x63, 0x00, 0x00 };
+			byte[] numResults = { 0x01, 0x00, 0x00, 0x00 };
+			byte[] ctxItem = { 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, (byte) 0x88,
+					(byte) 0x8a, (byte) 0xeb, 0x1c, (byte) 0xc9, 0x11,
+					(byte) 0x9f, (byte) 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48,
+					0x60, 0x02, 0x00, 0x00, 0x00 };
+
+			response = HelperUtils.concat(majorVersion, minorVersion,
+					packetType, packetFlags, dataRepres, fragLength,
+					authLength, callID, maxXmitFrag, maxRecvFrag, assocGroup,
+					scndryAddrLen, scndryAddr, numResults, ctxItem);
+		} else if (transSub[0] == 0x00 && transSub[1] == 0x00) {
+			packetType = new byte[] { 0x02 };
+			byte[] tmp = ByteBuffer.allocate(4).putInt(length).array();
+			fragLength = new byte[] { tmp[3], tmp[2] };
+			callID = new byte[] { 0x02, 0x00, 0x00, 0x00 };
+			tmp = ByteBuffer.allocate(4).putInt(length - 24).array();
+			byte[] allocHint = new byte[] { tmp[3], tmp[2], tmp[1], tmp[0] };
+			byte[] contextID = { 0x00, 0x00 };
+			byte[] cancelCount = { 0x00, 0x00 };
+
+			response = HelperUtils.concat(majorVersion, minorVersion,
+					packetType, packetFlags, dataRepres, fragLength,
+					authLength, callID, allocHint, contextID, cancelCount);
+		}
+		return response;
+	}
+
+	/**
+	 * Builds the echo packet
+	 * 
+	 * @return echo packet
+	 */
+	public byte[] getEcho() {
+		byte[] wordCount = { 0x01 };
+		byte[] echoSeq = { 0x01, 0x00 };
+		byte[] byteCount = { 0x10, 0x00 };
+		byte[] echoData = { (byte) 0xf0, (byte) 0xf0, (byte) 0xf0, (byte) 0xf0,
+				(byte) 0xf0, (byte) 0xf0, (byte) 0xf0, (byte) 0xf0,
+				(byte) 0xf0, (byte) 0xf0, (byte) 0xf0, (byte) 0xf0,
+				(byte) 0xf0, (byte) 0xf0, (byte) 0xf0, (byte) 0xf0 };
+		byte[] response = HelperUtils.concat(wordCount, echoSeq, byteCount,
+				echoData);
+		return wrapNetbios(wrapHeader(response));
+	}
+
+	/**
+	 * Builds the negotiate packet
+	 * 
+	 * @return negotiate packet
+	 */
+	public byte[] getNego() {
+		byte[] wordCount = { 0x11 };
+		byte[] dialect = evaluateDialect();
+		byte[] secMode = { 0x03 };
+		byte[] maxMpxC = { 0x32, 0x00 };
+		byte[] maxVcs = { 0x01, 0x00 };
+		byte[] maxBufSize = { 0x04, 0x11, 0x00, 0x00 };
+		byte[] maxRawBuf = { 0x00, 0x00, 0x01, 0x00 };
+		byte[] sessionKey = { 0x00, 0x00, 0x00, 0x00 };
+		byte[] capabilities = { (byte) 0xfc, (byte) 0xe3, 0x01, (byte) 0x80 };
+		byte[] sysTime = getTimeInBytes();
+		byte[] timeZone = getTimeZoneInBytes();
+		byte[] keyLength = { 0x00 };
+		byte[] byteCount = { 0x3a, 0x00 };
+		byte[] guid = serverGUID;
+		byte[] secBlob = { 0x60, 0x28, 0x06, 0x06 };
+		byte[] oid = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x02 };
+		byte[] protectNeg = { (byte) 0xa0, 0x1e };
+		byte[] negToken = { 0x30, 0x1c, (byte) 0xa0, 0x1a, 0x30, 0x18 };
+		byte[] mechType = { 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01,
+				(byte) 0x82, 0x37, 0x02, 0x02, 0x1e };
+		byte[] mechType2 = { 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01,
+				(byte) 0x82, 0x37, 0x02, 0x02, 0x0a };
+
+		byte[] response = HelperUtils.concat(wordCount, dialect, secMode,
+				maxMpxC, maxVcs, maxBufSize, maxRawBuf, sessionKey,
+				capabilities, sysTime, timeZone, keyLength, byteCount, guid,
+				secBlob, oid, protectNeg, negToken, mechType, mechType2);
+		return wrapNetbios(wrapHeader(response));
+	}
+
+	/**
+	 * Builds the nt create packet
+	 * 
+	 * @return nt create packet
+	 */
+	public byte[] getNTCreate() {
+		byte[] wordCount = { 0x22 };
+		byte[] andXCommand = { (byte) 0xff };
+		byte[] reserved = { 0x00 };
+		byte[] andXOffset = { 0x67, 0x00 };
+		byte[] oplockLevel = { 0x00 };
+		byte[] fid = { (byte) 0x00, 0x40 };
+		byte[] createAction = { 0x01, 0x00, 0x00, 0x00 };
+		byte[] created = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+		byte[] lastAccess = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+		byte[] lastWrite = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+		byte[] change = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+		byte[] fileAttributes = { (byte) 0x80, 0x00, 0x00, 0x00 };
+		byte[] allocationSize = { 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
+				0x00 };
+		byte[] endOfFile = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+		byte[] fileType = { 0x02, 0x00 };
+		byte[] ipcState = { (byte) 0xff, 0x05 };
+		byte[] isDirectory = { 0x00 };
+		byte[] byteCount = { 0x00, 0x00 };
+
+		byte[] response = HelperUtils.concat(wordCount, andXCommand, reserved,
+				andXOffset, oplockLevel, fid, createAction, created,
+				lastAccess, lastWrite, change, fileAttributes, allocationSize,
+				endOfFile, fileType, ipcState, isDirectory, byteCount);
+		return wrapNetbios(wrapHeader(response));
+	}
+
+	/**
+	 * Builds the session setup packet
+	 * 
+	 * @ret urn session setup packet
+	 */
+	public byte[] getSessSetup() {
+		if (authenticateNext) {
+			return getSetupAuth();
+		} else {
+			authenticateNext = true;
+			return getSetupChal();
+		}
+	}
+
+	/**
+	 * Builds the session setup packet for authentication required
+	 * 
+	 * @return session setup authentication packet
+	 */
+	private byte[] getSetupAuth() {
+		byte[] wordCount = { 0x04 };
+		byte[] andXCommand = { (byte) 0xff };
+		byte[] reserved = { 0x00 };
+		byte[] andXOffset = { (byte) 0xa2, 0x00 };
+		byte[] action = { 0x01, 0x00 };
+		byte[] secBlobLength;
+		byte[] byteCount;
+		byte[] secBlob = { (byte) 0xa1, 0x07, 0x30, 0x05, (byte) 0xa0, 0x03,
+				0x0a, 0x01, 0x00 };
+		byte[] nativOS = HelperUtils.fillWithZeroExtended(serverVersion[0]
+				.getBytes());
+		byte[] nativLanMngr = HelperUtils.fillWithZeroExtended(serverVersion[1]
+				.getBytes());
+
+		byte[] buffer = ByteBuffer.allocate(4).putInt(secBlob.length).array();
+		secBlobLength = new byte[] { buffer[3], buffer[2] };
+		buffer = ByteBuffer.allocate(4)
+				.putInt(secBlob.length + nativOS.length + nativLanMngr.length)
+				.array();
+		byteCount = new byte[] { buffer[3], buffer[2] };
+
+		byte[] response = HelperUtils.concat(wordCount, andXCommand, reserved,
+				andXOffset, action, secBlobLength, byteCount, secBlob, nativOS,
+				nativLanMngr);
+		return wrapNetbios(wrapHeader(response));
+	}
+
+	/**
+	 * Builds the session setup challange packet
+	 * 
+	 * @return session setup challange packet
+	 */
+	private byte[] getSetupChal() {
+		byte[] wordCount = { 0x04 };
+		byte[] andXCommand = { (byte) 0xff };
+		byte[] reserved = { 0x00 };
+		byte[] andXOffset = { 0x60, 0x01 };
+		byte[] action = { 0x00, 0x00 };
+		byte[] secBlobLength;
+		byte[] byteCount;
+		byte[] secBlob = { (byte) 0xa1, (byte) 0x81, (byte) 0xc4 };
+		byte[] negToken = { 0x30, (byte) 0x81, (byte) 0xc1, (byte) 0xa0, 0x03,
+				0x0a, 0x01 };
+		byte[] negResult = { 0x01 };
+		byte[] negToken2 = { (byte) 0xa1, 0x0c, 0x06, 0x0a };
+		byte[] supportedMech = { 0x2b, 0x06, 0x01, 0x04, 0x01, (byte) 0x82,
+				0x37, 0x02, 0x02, 0x0a };
+		byte[] negToken3 = { (byte) 0xa2, (byte) 0x81, (byte) 0xab, 0x04,
+				(byte) 0x81, (byte) 0xa8 };
+		byte[] ntlmsspId = { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00 };
+		byte[] nlmMsgType = { 0x02, 0x00, 0x00, 0x00 };
+		byte[] buffer = ByteBuffer.allocate(4).putInt(serverName.length)
+				.array();
+		byte[] targetNameLength = new byte[] { buffer[3], buffer[2] };
+		byte[] targetNameMaxLength = new byte[] { buffer[3], buffer[2] };
+		byte[] targetNameOffset = { 0x38, 0x00, 0x00, 0x00 };
+		byte[] flags = { 0x15, (byte) 0x82, (byte) 0x8a, 0x60 };
+		if (!serverVersion[0].contains("Unix")) {
+			flags[3] = (byte) (flags[3] | 0x02);
+		}
+		byte[] challenge = HelperUtils.randomBytes(8);
+		byte[] reserved2 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
+		byte[] targetInfoLength = { 0x60, 0x00 };
+		byte[] targetInfoMaxLength = { 0x60, 0x00 };
+		byte[] targetInfoOffset = { 0x48, 0x00, 0x00, 0x00 };
+		byte[] version = null;
+		if (serverVersion[0].contains("Windows 7")
+				|| serverVersion[0].contains("Windows Server 2008")) {
+			version = new byte[] { 0x06, 0x01, (byte) 0xb0, 0x1d, 0x00, 0x00,
+					0x00, 0x0f };
+		} else if (serverVersion[0].contains("Windows 8")
+				|| serverVersion[0].contains("Windows Server 2012")) {
+			version = new byte[] { 0x06, 0x02, (byte) 0xf0, 0x23, 0x00, 0x00,
+					0x00, 0x0f };
+		}
+		// serverName
+		byte[] attributeNBDomain = { 0x02, 0x00, 0x10, 0x00 };
+		// serverName
+		byte[] attributeNBcomputer = { 0x01, 0x00, 0x10, 0x00 };
+		// serverName
+		byte[] attributeDNSDomain = { 0x04, 0x00, 0x10, 0x00 };
+		// serverName
+		byte[] attributeDNScomputer = { 0x03, 0x00, 0x10, 0x00 };
+		// serverName
+		byte[] attributeTimeStamp = { 0x07, 0x00, 0x08, 0x00 };
+		byte[] timeStamp = getTimeInBytes();
+		byte[] attributeEnd = { 0x00, 0x00, 0x00, 0x00 };
+		secBlob = HelperUtils.concat(secBlob, negToken, negResult, negToken2,
+				supportedMech, negToken3, ntlmsspId, nlmMsgType,
+				targetNameLength, targetNameMaxLength, targetNameOffset, flags,
+				challenge, reserved2, targetInfoLength, targetInfoMaxLength,
+				targetInfoOffset, version, serverName, attributeNBDomain,
+				serverName, attributeNBcomputer, serverName,
+				attributeDNSDomain, serverName, attributeDNScomputer,
+				serverName, attributeTimeStamp, timeStamp, attributeEnd);
+		byte[] nativOS = HelperUtils.fillWithZeroExtended(serverVersion[0]
+				.getBytes());
+		byte[] nativLanMngr = HelperUtils.fillWithZeroExtended(serverVersion[1]
+				.getBytes());
+		buffer = ByteBuffer.allocate(4).putInt(secBlob.length).array();
+		secBlobLength = new byte[] { buffer[3], buffer[2] };
+		buffer = ByteBuffer.allocate(4)
+				.putInt(secBlob.length + nativOS.length + nativLanMngr.length)
+				.array();
+		byteCount = new byte[] { buffer[3], buffer[2] };
+
+		ntStat = new byte[] { 0x16, 0x00, 0x00, (byte) 0xc0 };
+		userID = new byte[] { 0x00, 0x08 };
+
+		byte[] response = HelperUtils.concat(wordCount, andXCommand, reserved,
+				andXOffset, action, secBlobLength, byteCount, secBlob, nativOS,
+				nativLanMngr);
+		return wrapNetbios(wrapHeader(response));
+	}
+
+	/**
+	 * Returns the command number from the current message
+	 * 
+	 * @return command number
+	 */
+	public byte getSmbCommand() {
+		return smbCommand[0];
+	}
+
+	/**
+	 * Builds the trans packet
+	 * 
+	 * @return trans packet
+	 */
+	public byte[] getTrans() {
+		byte[] transSub = getTransSub();
+		byte[] response = null;
+		
+		if (transSub[0] == (byte) 0xff) { // for NMB in host announcement, NOT smb protocol
+			byte[] wordCount = { 0x11 };
+			byte[] totalParamCount = { 0x00, 0x00 };
+			byte[] totalDataCount = new byte[2]; //TODO
+			byte[] maxParamCount = { 0x00, 0x00 };
+			byte[] maxDataCount = { 0x00, 0x00 };
+			byte[] maxSetupCount = { 0x00 };
+			byte[] reserved = { 0x00 };
+			byte[] flags = { 0x00, 0x00 };
+			byte[] timeout = { 0x00, 0x00, 0x00, 0x00 };
+			byte[] reserved2 = { 0x00, 0x00 };
+			byte[] paramCount = { 0x00, 0x00 };
+			byte[] paramOffset = { 0x00, 0x00 };
+			byte[] dataCount = new byte[2]; //TODO
+			byte[] dataOffset = { 0x56, 0x00 };
+			byte[] setupCount = { 0x03 };
+			byte[] reserved3 = { 0x00 };
+			
+			//SMB MailSlot				
+			byte[] opcode = new byte[]{0x01, 0x00};
+			byte[] priority = new byte[]{0x01, 0x00};
+			byte[] smbclass = new byte[]{0x02, 0x00};
+			byte[] size = new byte[2]; //TODO
+			byte[] name = HelperUtils.concat("\\MAILSLOT\\BROWSE".getBytes(), new byte[]{0x00}); 
+			
+			byte[] windowsBrowser = null;
+			if (type == NBDSType.HOST_ANNOUNCEMENT_WITH_SERVICES || type == NBDSType.HOST_ANNOUNCEMENT
+					|| type == NBDSType.LOCAL_MASTER_ANNOUNCEMENT_ALL || type == NBDSType.DOMAIN_ANNOUNCEMENT) {
+				windowsBrowser = getAnnouncement();
+			} else if (type == NBDSType.BROWSER) {
+				windowsBrowser = getBrowser();
+			} else if (type == NBDSType.REQUEST_ANNOUNCEMENT) {
+				byte[] command = {0x02};
+				byte[] unusedFlags = {0x01, 0x00};
+				byte[] responseCompName = serverName;
+				windowsBrowser = HelperUtils.concat(command, unusedFlags, responseCompName);
+			}
+
+			byte[] buffer = ByteBuffer.allocate(4).putInt(windowsBrowser.length).array();
+			totalDataCount[0] = buffer[3];
+			totalDataCount[1] = buffer[2];
+			dataCount = totalDataCount;
+			
+			buffer = ByteBuffer.allocate(4).putInt(name.length + windowsBrowser.length).array();
+			size[0] = buffer[3];
+			size[1] = buffer[2];
+			byte[] smbMailSlot = HelperUtils.concat(opcode, priority, smbclass, size, name);					
+
+			// no netbios header required for NMB!!
+			return wrapHeader(HelperUtils.concat(wordCount, totalParamCount, totalDataCount,
+					maxParamCount, maxDataCount, maxSetupCount, reserved, flags, timeout, reserved2,
+					paramCount, paramOffset, dataCount, dataOffset, setupCount, reserved3, smbMailSlot,
+					windowsBrowser));
+		} else if (transSub[0] == 0x00 && transSub[1] == 0x0b) { // bind_ack
+			byte[] wordCount = { 0x0a };
+			byte[] totalParamCount = { 0x00, 0x00 };
+			byte[] totalDataCount = { 0x44, 0x00 };
+			byte[] reserved = { 0x00, 0x00 };
+			byte[] paramCount = { 0x00, 0x00 };
+			byte[] paramOffset = { 0x38, 0x00 };
+			byte[] paramDisplace = { 0x00, 0x00 };
+			byte[] dataCount = { 0x44, 0x00 };
+			byte[] dataOffset = { 0x38, 0x00 };
+			byte[] dataDisplace = { 0x00, 0x00 };
+			byte[] setupCount = { 0x00 };
+			byte[] reserved2 = { 0x00 };
+			byte[] byteCount = { 0x45, 0x00 };
+			byte[] padding = { 0x00 };
+
+			byte[] dcerpc = getDceRpc(transSub, 0);
+
+			response = HelperUtils.concat(wordCount, totalParamCount,
+					totalDataCount, reserved, paramCount, paramOffset,
+					paramDisplace, dataCount, dataOffset, dataDisplace,
+					setupCount, reserved2, byteCount, padding, dcerpc);
+
+		} else if (transSub[0] == 0x00 && transSub[1] == 0x00) { // netShareEnumAll
+			byte[] wordCount = { 0x0a };
+			byte[] totalParamCount = { 0x00, 0x00 };
+			byte[] totalDataCount = { 0x20, 0x01 };
+			byte[] reserved = { 0x00, 0x00 };
+			byte[] paramCount = { 0x00, 0x00 };
+			byte[] paramOffset = { 0x38, 0x00 };
+			byte[] paramDisplace = { 0x00, 0x00 };
+			byte[] dataCount = { 0x20, 0x01 };
+			byte[] dataOffset = { 0x38, 0x00 };
+			byte[] dataDisplace = { 0x00, 0x00 };
+			byte[] setupCount = { 0x00 };
+			byte[] reserved2 = { 0x00 };
+			byte[] byteCount = new byte[2]/* = {0x21, 0x01} */;
+			byte[] padding = { 0x00 };
+
+			byte[] dcerpc = new byte[24];
+
+			byte[] levelPointer = { 0x01, 0x00, 0x00, 0x00 };
+			byte[] ctr = { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00 };
+			byte[] ctr1 = { 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00,
+					0x03, 0x00, 0x00, 0x00 };
+			byte[] array1Pointer = { 0x08, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
+					(byte) 0x80, 0x0c, 0x00, 0x02, 0x00 };
+			byte[] array2Pointer = { 0x10, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
+					(byte) 0x80, 0x14, 0x00, 0x02, 0x00 };
+			byte[] array3Pointer = { 0x18, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00,
+					(byte) 0x80, 0x1c, 0x00, 0x02, 0x00 };
+			byte[] array1 = { 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+					0x07, 0x00, 0x00, 0x00, 0x41, 0x00, 0x44, 0x00, 0x4d, 0x00,
+					0x49, 0x00, 0x4e, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00,
+					0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x00,
+					0x00, 0x00, 0x52, 0x00, 0x65, 0x00, 0x6d, 0x00, 0x6f, 0x00,
+					0x74, 0x00, 0x65, 0x00, 0x20, 0x00, 0x41, 0x00, 0x64, 0x00,
+					0x6d, 0x00, 0x69, 0x00, 0x6e, 0x00, 0x00, 0x00 };
+			byte[] array2 = { 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
+					0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x43, 0x00, 0x24, 0x00,
+					0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00,
+					0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x44, 0x00, 0x65, 0x00,
+					0x66, 0x00, 0x61, 0x00, 0x75, 0x00, 0x6c, 0x00, 0x74, 0x00,
+					0x20, 0x00, 0x73, 0x00, 0x68, 0x00, 0x61, 0x00, 0x72, 0x00,
+					0x65, 0x00 };
+			byte[] array3 = { 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00,
+					0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x49, 0x00, 0x50, 0x00,
+					0x43, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00,
+					0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00,
+					0x52, 0x00, 0x65, 0x00, 0x6d, 0x00, 0x6f, 0x00, 0x74, 0x00,
+					0x65, 0x00, 0x20, 0x00, 0x49, 0x00, 0x50, 0x00, 0x43, 0x00,
+					0x00, 0x00 };
+			byte[] totalEntries = { 0x00, 0x00, 0x03, 0x00, 0x00, 0x00 };
+			byte[] referentID = { 0x20, 0x00, 0x02, 0x00 };
+			byte[] resumeHandle = { 0x00, 0x00, 0x00, 0x00 };
+			byte[] windowsError = { 0x00, 0x00, 0x00, 0x00 };
+			int tmp = padding.length + dcerpc.length + levelPointer.length
+					+ ctr.length + ctr1.length + array1Pointer.length
+					+ array2Pointer.length + array3Pointer.length
+					+ array1.length + array2.length + array3.length
+					+ totalEntries.length + referentID.length
+					+ resumeHandle.length + windowsError.length;
+			byte[] tmp2 = ByteBuffer.allocate(4).putInt(tmp).array();
+			byteCount = new byte[] { tmp2[3], tmp2[2] };
+			dcerpc = getDceRpc(transSub, tmp - 1);
+
+			response = HelperUtils.concat(wordCount, totalParamCount,
+					totalDataCount, reserved, paramCount, paramOffset,
+					paramDisplace, dataCount, dataOffset, dataDisplace,
+					setupCount, reserved2, byteCount, padding, dcerpc,
+					levelPointer, ctr, ctr1, array1Pointer, array2Pointer,
+					array3Pointer, array1, array2, array3, totalEntries,
+					referentID, resumeHandle, windowsError);
+		}
+
+		return wrapNetbios(wrapHeader(response));
+	}
+
+	/**
+	 * Builds the trans2 packet
+	 * 
+	 * @return trans2 packet
+	 */
+	public byte[] getTrans2() {
+		byte[] response = null;
+		byte[] wordCount = { 0x00 };
+		byte[] andXCommand = { 0x00, 0x00 };
+		ntStat = new byte[] { 0x22, 0x00, 0x00, (byte) 0xc0 };
+		response = HelperUtils.concat(wordCount, andXCommand);
+		return wrapNetbios(wrapHeader(response));
+	}
+
+	/**
+	 * Extracts the trans sub packet from message
+	 * 
+	 * @return trans sub packet
+	 */
+	private byte[] getTransSub() {
+		byte[] transSub = new byte[2];
+		if (smbCommand[0] == 0x32)
+			transSub = new byte[] { message[66], message[65] };
+		else if (smbCommand[0] == 0x25 && message != null)
+			transSub = new byte[] { 0x00, message[90] };
+		else if (smbCommand[0] == 0x25 && message == null)
+			transSub = new byte[] { (byte) 0xff };
+		else
+			transSub = new byte[] { 0x00, 0x00 };
+		return transSub;
+	}
+	
+	private byte[] getAnnouncement() {
+		//Microsoft Windows Browser
+		byte[] command = null;
+		if(type == NBDSType.LOCAL_MASTER_ANNOUNCEMENT_ALL) {
+			command = new byte[]{0x0f};
+		} else if (type == NBDSType.DOMAIN_ANNOUNCEMENT) {
+			command = new byte[]{0x0c};
+		} else {
+			command = new byte[]{0x01};
+		}
+		byte[] updateCount = new byte[]{0x00};
+		byte[] updatePeriodicity = null;
+		if (type == NBDSType.HOST_ANNOUNCEMENT_WITH_SERVICES) {
+			updatePeriodicity = new byte[]{0x60, (byte) 0xea, 0x00, 0x00};
+		} else if (type == NBDSType.HOST_ANNOUNCEMENT) {
+			updatePeriodicity = new byte[]{0x00, 0x00, 0x00, 0x00};
+		} else if (type == NBDSType.LOCAL_MASTER_ANNOUNCEMENT_ALL || type == NBDSType.DOMAIN_ANNOUNCEMENT) {
+			updatePeriodicity = new byte[]{(byte) 0xc0, (byte) 0xd4, 0x01, 0x00};
+		}
+		byte[] hostName = null;
+		if (type == NBDSType.DOMAIN_ANNOUNCEMENT) {
+			hostName = workgroup;
+		} else {
+			hostName = serverName;
+		}
+		for (int i = hostName.length; i < 16; i++) {
+			hostName = HelperUtils.concat(hostName, new byte[]{0x00});
+		}
+		byte[] osMajorVersion = new byte[]{0x04};
+		byte[] osMinorVersion = new byte[]{0x09};
+		byte[] serverType = null;
+		if (type == NBDSType.HOST_ANNOUNCEMENT_WITH_SERVICES || type == NBDSType.LOCAL_MASTER_ANNOUNCEMENT_ALL) {
+			serverType = new byte[]{0x03, (byte) 0x9a, (byte) 0x81, 0x00};
+		} else if (type == NBDSType.HOST_ANNOUNCEMENT) {
+			serverType = new byte[]{0x00, 0x00, 0x00, 0x00};
+		} else if (type == NBDSType.DOMAIN_ANNOUNCEMENT) {
+			serverType = new byte[]{0x00, 0x10, 0x00, (byte) 0x80};
+		}
+		byte[] browserProtocolMajorVer = new byte[]{0x0f};
+		byte[] browserProtocolMinorVer = new byte[]{0x01};
+		byte[] signature = new byte[]{0x55, (byte) 0xaa};
+		byte[] hostComment = null;
+		if (type == NBDSType.DOMAIN_ANNOUNCEMENT) {
+			hostComment = HelperUtils.concat(serverName, new byte[]{0x00});
+		} else {
+			hostComment = HelperUtils.concat("".getBytes(), new byte[]{0x00});
+		}
+		
+		return HelperUtils.concat(command, updateCount, updatePeriodicity, hostName,
+				osMajorVersion, osMinorVersion, serverType, browserProtocolMajorVer, browserProtocolMinorVer,
+				signature, hostComment);
+	}
+	
+	private byte[] getBrowser() {
+		byte[] command = {0x08};
+		byte[] electionVersion = {0x01};
+		byte[] electionCriteria = {0x02, 0x0f, 0x01, 0x14};
+		byte[] uptime = {(byte) 0xb0, 0x36, 0x00, 0x00, 0x00, 0x00,0x00, 0x00};
+		return HelperUtils.concat(command, electionVersion, electionCriteria, uptime, serverName, new byte[]{0x00});
+	}
+
+	/**
+	 * Builds the tree connect packet
+	 * 
+	 * @return tree connect packet
+	 */
+	public byte[] getTreeCon() {
+		String str = HelperUtils.byteToStr(message);
+		byte[] wordCount = { 0x00 };
+		byte[] andXCommand = { 0x00, 0x00 };
+		byte[] response = null;
+		if (str.contains("IPC$") || str.contains("C$")) {
+			wordCount = new byte[] { 0x07 };
+			andXCommand = new byte[] { (byte) 0xff };
+			byte[] reserved = { 0x00 };
+			byte[] andXOffset = { 0x38, 0x00 };
+			byte[] optionalSupport = { 0x01, 0x00 };
+			byte[] maxShareAccess = { (byte) 0xff, (byte) 0xff, 0x1f, 0x00 };
+			byte[] guestMaxShareAccess = { (byte) 0xff, (byte) 0xff, 0x1f, 0x00 };
+			byte[] byteCount = { 0x07, 0x00 };
+			byte[] service = { 0x49, 0x50, 0x43, 0x00 };
+			byte[] extraParameters = { 0x00, 0x00, 0x00 };
+
+			treeID = new byte[] { 0x00, 0x08 };
+
+			response = HelperUtils.concat(wordCount, andXCommand, reserved,
+					andXOffset, optionalSupport, maxShareAccess,
+					guestMaxShareAccess, byteCount, service, extraParameters);
+		} else if (str.contains("ADMIN$")) {
+			ntStat = new byte[] { 0x22, 0x00, 0x00, (byte) 0xc0 };
+			response = HelperUtils.concat(wordCount, andXCommand);
+		} else {
+			ntStat = new byte[] { (byte) 0xcc, 0x00, 0x00, (byte) 0xc0 };
+			response = HelperUtils.concat(wordCount, andXCommand);
+		}
+
+		return wrapNetbios(wrapHeader(response));
+	}
+
+	/**
+	 * Builds the tree disconnect packet
+	 * 
+	 * @return tree disconnect packet
+	 */
+	public byte[] getTreeDisc() {
+		byte[] wordCount = { 0x00 };
+		byte[] byteCount = { 0x00, 0x00 };
+
+		smbCommand[0] = 0x71;
+
+		byte[] response = HelperUtils.concat(wordCount, byteCount);
+
+		return wrapNetbios(wrapHeader(response));
+	}
+	
+
+	/**
+	 * Converts the current system time into a byte[] with windows specific time
+	 * 
+	 * @return current system time in windows format as byte[]
+	 */
+	private static byte[] getTimeInBytes() {
+		long time = System.currentTimeMillis();
+		Calendar calend = Calendar.getInstance();
+		calend.setTimeZone(TimeZone.getTimeZone("UTC"));
+		calend.set(1601, 0, 01, 00, 00, 00);
+		time -= calend.getTimeInMillis();
+		time *= 10000;
+
+		byte[] timeInWindowsBytes = new byte[8];
+		byte[] timeInBytes = ByteBuffer.allocate(8).putLong(time).array();
+
+		for (int i = 0, j = 7; i < 8 && j > -1; i++, j--) {
+			timeInWindowsBytes[i] = (byte) (timeInBytes[j] & 0xff);
+		}
+
+		return timeInWindowsBytes;
+	}
+
+	/**
+	 * Converts the current timezone into a byte[] with windows specific format
+	 * 
+	 * @return current timezone in windows format as byte[]
+	 */
+	private static byte[] getTimeZoneInBytes() {
+		// get current timezone offset in minutes
+		Integer offset = new GregorianCalendar().getTimeZone().getRawOffset() / 1000 / 60; 
+		char[] offsetChars = Integer.toBinaryString(offset).toCharArray();
+		boolean invert = false;
+		for (int i = offsetChars.length - 1; i > -1; i--) {
+			if (!invert && offsetChars[i] == '1') {
+				invert = true;
+			} else if (invert) {
+				offsetChars[i] = (offsetChars[i] == '0') ? '1' : '0';
+			}
+		}
+		char[] extendedChars = new char[31];
+		for (int i = 0; i < extendedChars.length - offsetChars.length; i++) {
+			extendedChars[i] = '1';
+		}
+		for (int i = 0; i < offsetChars.length; i++) {
+			extendedChars[i + extendedChars.length - offsetChars.length] = offsetChars[i];
+		}
+		int timezone = Integer.parseInt(new String(extendedChars), 2);
+		byte[] timezoneBytes = new byte[2];
+		timezoneBytes[1] = (byte) (timezone >> 8);
+		timezoneBytes[0] = (byte) (timezone);
+		return timezoneBytes;
+	}
+
+}

+ 233 - 0
src/de/tudarmstadt/informatik/hostage/provider/HostageContentProvider.java

@@ -0,0 +1,233 @@
+package de.tudarmstadt.informatik.hostage.provider;
+
+import android.content.ContentProvider;
+import android.content.ContentUris;
+import android.content.ContentValues;
+import android.content.UriMatcher;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteQueryBuilder;
+import android.net.Uri;
+import android.text.TextUtils;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.AttackEntry;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.NetworkEntry;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.PacketEntry;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+
+public class HostageContentProvider extends ContentProvider {
+
+	public static final String AUTHORITY = "de.tudarmstadt.informatik.hostage.provider";
+
+	public static final Uri CONTENT_URI_NETWORK = Uri.parse("content://" + AUTHORITY + "/network");
+	public static final Uri CONTENT_URI_ATTACK = Uri.parse("content://" + AUTHORITY + "/attack");
+	public static final Uri CONTENT_URI_PACKET = Uri.parse("content://" + AUTHORITY + "/packet");
+
+	public static final Uri CONTENT_URI_RECORD_OVERVIEW = Uri.parse("content://" + AUTHORITY + "/record-overview");
+
+	private static final int NETWORK_ALL = 11;
+	private static final int NETWORK_ONE = 12;
+	private static final int ATTACK_ALL = 21;
+	private static final int ATTACK_ONE = 22;
+	private static final int PACKET_ALL = 31;
+	private static final int PACKET_ONE = 32;
+
+	private static final int NETWORK_OVERVIEW_ALL = 101;
+	private static final int NETWORK_OVERVIEW_ONE = 102;
+
+	private static final UriMatcher uriMatcher;
+
+	static {
+		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
+		uriMatcher.addURI(AUTHORITY, "network", NETWORK_ALL);
+		uriMatcher.addURI(AUTHORITY, "network/#", NETWORK_ONE);
+		uriMatcher.addURI(AUTHORITY, "attack", ATTACK_ALL);
+		uriMatcher.addURI(AUTHORITY, "attack/#", ATTACK_ONE);
+		uriMatcher.addURI(AUTHORITY, "packet", PACKET_ALL);
+		uriMatcher.addURI(AUTHORITY, "packet/#", PACKET_ONE);
+		uriMatcher.addURI(AUTHORITY, "record-overview", NETWORK_OVERVIEW_ALL);
+		uriMatcher.addURI(AUTHORITY, "record-overview/#", NETWORK_OVERVIEW_ONE);
+	}
+
+	private HostageDBOpenHelper mDBOpenHelper;
+
+	@Override
+	public boolean onCreate() {
+		mDBOpenHelper = new HostageDBOpenHelper(getContext());
+		return true;
+	}
+
+	@Override
+	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
+		SQLiteDatabase db = mDBOpenHelper.getWritableDatabase();
+		SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
+
+		int uriMatch = uriMatcher.match(uri);
+
+		if (isNetworkUriMatch(uriMatch)) {
+			queryBuilder.setTables(NetworkEntry.TABLE_NAME);
+		} else if (isAttackUriMatch(uriMatch)) {
+			queryBuilder.setTables(AttackEntry.TABLE_NAME);
+		} else if (isPacketUriMatch(uriMatch)) {
+			queryBuilder.setTables(PacketEntry.TABLE_NAME);
+		}
+
+		if (uriMatch == NETWORK_ONE) {
+			String rowID = uri.getPathSegments().get(1);
+			queryBuilder.appendWhere(NetworkEntry.KEY_ID + "=" + rowID);
+		} else if (uriMatch == ATTACK_ONE) {
+			String rowID = uri.getPathSegments().get(1);
+			queryBuilder.appendWhere(AttackEntry.KEY_ID + "=" + rowID);
+		} else if (uriMatch == PACKET_ONE) {
+			String rowID = uri.getPathSegments().get(1);
+			queryBuilder.appendWhere(PacketEntry.KEY_ID + "=" + rowID);
+		}
+
+		Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
+		return cursor;
+	}
+
+	@Override
+	public int delete(Uri uri, String selection, String[] selectionArgs) {
+		SQLiteDatabase db = mDBOpenHelper.getWritableDatabase();
+
+		int uriMatch = uriMatcher.match(uri);
+
+		if (uriMatch == NETWORK_ONE) {
+			String rowID = uri.getPathSegments().get(1);
+			selection = NetworkEntry.KEY_ID + "=" + rowID + (!TextUtils.isEmpty(selection) ? "AND (" + selection + ")" : "");
+		} else if (uriMatch == ATTACK_ONE) {
+			String rowID = uri.getPathSegments().get(1);
+			selection = AttackEntry.KEY_ID + "=" + rowID + (!TextUtils.isEmpty(selection) ? "AND (" + selection + ")" : "");
+		} else if (uriMatch == PACKET_ONE) {
+			String rowID = uri.getPathSegments().get(1);
+			selection = PacketEntry.KEY_ID + "=" + rowID + (!TextUtils.isEmpty(selection) ? "AND (" + selection + ")" : "");
+		}
+
+		if (selection == null) {
+			selection = "1";
+		}
+
+		int deleteCount = 0;
+		if (isNetworkUriMatch(uriMatch)) {
+			deleteCount = db.delete(NetworkEntry.TABLE_NAME, selection, selectionArgs);
+		} else if (isAttackUriMatch(uriMatch)) {
+			deleteCount = db.delete(AttackEntry.TABLE_NAME, selection, selectionArgs);
+		} else if (isPacketUriMatch(uriMatch)) {
+			deleteCount = db.delete(PacketEntry.TABLE_NAME, selection, selectionArgs);
+		}
+
+		getContext().getContentResolver().notifyChange(uri, null);
+
+		return deleteCount;
+	}
+
+	@Override
+	public Uri insert(Uri uri, ContentValues values) {
+		SQLiteDatabase db = mDBOpenHelper.getWritableDatabase();
+
+		int uriMatch = uriMatcher.match(uri);
+
+		long id = -1;
+		Uri insertedId = null;
+		if (isNetworkUriMatch(uriMatch)) {
+			id = db.insert(NetworkEntry.TABLE_NAME, null, values);
+			if (id > -1) {
+				insertedId = ContentUris.withAppendedId(CONTENT_URI_NETWORK, id);
+			}
+		} else if (isAttackUriMatch(uriMatch)) {
+			id = db.insert(AttackEntry.TABLE_NAME, null, values);
+			if (id > -1) {
+				insertedId = ContentUris.withAppendedId(CONTENT_URI_NETWORK, id);
+			}
+		} else if (isPacketUriMatch(uriMatch)) {
+			id = db.insert(PacketEntry.TABLE_NAME, null, values);
+			if (id > -1) {
+				insertedId = ContentUris.withAppendedId(CONTENT_URI_NETWORK, id);
+			}
+		}
+
+		if (id > -1) {
+			getContext().getContentResolver().notifyChange(insertedId, null);
+			return insertedId;
+		}
+
+		return null;
+	}
+
+	@Override
+	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
+		SQLiteDatabase db = mDBOpenHelper.getWritableDatabase();
+
+		int uriMatch = uriMatcher.match(uri);
+
+		if (uriMatch == NETWORK_ONE) {
+			String rowID = uri.getPathSegments().get(1);
+			selection = NetworkEntry.KEY_ID + "=" + rowID + (!TextUtils.isEmpty(selection) ? "AND (" + selection + ")" : "");
+		} else if (uriMatch == ATTACK_ONE) {
+			String rowID = uri.getPathSegments().get(1);
+			selection = AttackEntry.KEY_ID + "=" + rowID + (!TextUtils.isEmpty(selection) ? "AND (" + selection + ")" : "");
+		} else if (uriMatch == PACKET_ONE) {
+			String rowID = uri.getPathSegments().get(1);
+			selection = PacketEntry.KEY_ID + "=" + rowID + (!TextUtils.isEmpty(selection) ? "AND (" + selection + ")" : "");
+		}
+
+		int updateCount = 0;
+		if (isNetworkUriMatch(uriMatch)) {
+			updateCount = db.update(NetworkEntry.TABLE_NAME, values, selection, selectionArgs);
+		} else if (isAttackUriMatch(uriMatch)) {
+			updateCount = db.update(AttackEntry.TABLE_NAME, values, selection, selectionArgs);
+		} else if (isPacketUriMatch(uriMatch)) {
+			updateCount = db.update(PacketEntry.TABLE_NAME, values, selection, selectionArgs);
+		}
+
+		getContext().getContentResolver().notifyChange(uri, null);
+
+		return updateCount;
+	}
+
+	@Override
+	public String getType(Uri uri) {
+		int uriMatch = uriMatcher.match(uri);
+
+		if (isNetworkUriMatch(uriMatch)) {
+			if (uriMatch == NETWORK_ONE) {
+				return "vnd.android.cursor.item/vnd.de.tudarmstadt.informatik.hostage.provider.network";
+			}
+			return "vnd.android.cursor.dir/vnd.de.tudarmstadt.informatik.hostage.provider.network";
+		} else if (isAttackUriMatch(uriMatch)) {
+			if (uriMatch == ATTACK_ONE) {
+				return "vnd.android.cursor.item/vnd.de.tudarmstadt.informatik.hostage.provider.attack";
+			}
+			return "vnd.android.cursor.dir/vnd.de.tudarmstadt.informatik.hostage.provider.attack";
+		} else if (isPacketUriMatch(uriMatch)) {
+			if (uriMatch == PACKET_ONE) {
+				return "vnd.android.cursor.item/vnd.de.tudarmstadt.informatik.hostage.provider.packet";
+			}
+			return "vnd.android.cursor.dir/vnd.de.tudarmstadt.informatik.hostage.provider.packet";
+		}
+
+		return null;
+	}
+
+	private boolean isNetworkUriMatch(int uriMatch) {
+		if (uriMatch == NETWORK_ALL || uriMatch == NETWORK_ONE) {
+			return true;
+		}
+		return false;
+	}
+
+	private boolean isAttackUriMatch(int uriMatch) {
+		if (uriMatch == ATTACK_ALL || uriMatch == ATTACK_ONE) {
+			return true;
+		}
+		return false;
+	}
+
+	private boolean isPacketUriMatch(int uriMatch) {
+		if (uriMatch == PACKET_ALL || uriMatch == PACKET_ONE) {
+			return true;
+		}
+		return false;
+	}
+
+}

+ 368 - 305
src/de/tudarmstadt/informatik/hostage/sync/BluetoothSync.java

@@ -1,305 +1,368 @@
-package de.tudarmstadt.informatik.hostage.sync;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.UUID;
-
-import android.app.AlertDialog;
-import android.bluetooth.BluetoothAdapter;
-import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothServerSocket;
-import android.bluetooth.BluetoothSocket;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.widget.ArrayAdapter;
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
-
-public class BluetoothSync {
-
-	private class ClientThread extends Thread {
-		private final BluetoothSocket socket;
-
-		public ClientThread(BluetoothDevice device) {
-			BluetoothSocket tmp = null;
-			try {
-				tmp = device.createRfcommSocketToServiceRecord(serviceUUID);
-			} catch (IOException e) {
-			}
-			socket = tmp;
-		}
-
-		/** Will cancel an in-progress connection, and close the socket */
-		public void cancel() {
-			try {
-				socket.close();
-			} catch (IOException e) {
-			}
-		}
-
-		@Override
-		public void run() {
-
-			try {
-				socket.connect();
-			} catch (IOException connectException) {
-				// Unable to connect; close the socket and get out
-				try {
-					socket.close();
-				} catch (IOException closeException) {
-				}
-				return;
-			}
-
-			manageConnectedSocket(socket, CLIENT);
-		}
-	}
-
-	private class CommunicationThread extends Thread {
-		private final BluetoothSocket mmSocket;
-		private final ObjectInputStream objectInput;
-		private final ObjectOutputStream objectOuput;
-		private final int identifier;
-
-		public CommunicationThread(BluetoothSocket socket, int identifier) {
-			mmSocket = socket;
-			ObjectInputStream tmpIn = null;
-			ObjectOutputStream tmpOut = null;
-
-			// Get the input and output streams, using temp objects because
-			// member streams are final
-			try {
-				tmpOut = new ObjectOutputStream(socket.getOutputStream());
-				tmpIn = new ObjectInputStream(socket.getInputStream());
-			} catch (IOException e) {
-				e.printStackTrace();
-			}
-
-			objectInput = tmpIn;
-			objectOuput = tmpOut;
-			this.identifier = identifier;
-		}
-
-		/* Call this from the main activity to shutdown the connection */
-		public void cancel() {
-			try {
-				mmSocket.close();
-			} catch (IOException e) {
-			}
-		}
-
-		@Override
-		public void run() {
-			// Keep listening to the InputStream until an exception occurs
-			// while (true) {
-			try {
-				// TODO Ersetze dbh mit Logger
-				UglyDbHelper dbh = new UglyDbHelper(context);
-				ArrayList<HashMap<String, Object>> localNetworkInformation = dbh
-						.getNetworkInformation();
-				if (identifier == SERVER) {
-					// Read from the InputStream
-					ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) objectInput
-							.readObject();
-					;
-					dbh.updateNetworkInformation(remoteNetworkInformation);
-					objectOuput.writeObject(localNetworkInformation);
-				} else {
-					objectOuput.writeObject(localNetworkInformation);
-					// Read from the InputStream
-					ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) objectInput
-							.readObject();
-					dbh.updateNetworkInformation(remoteNetworkInformation);
-					mmSocket.close();
-				}
-			} catch (ClassNotFoundException e) {
-				e.printStackTrace();
-			} catch (IOException e) {
-				e.printStackTrace();
-			}
-			// }
-		}
-
-		/* Call this from the main activity to send data to the remote device */
-		public void write(ArrayList<HashMap<String, Object>> networkInformation) {
-			try {
-				objectOuput.writeObject(networkInformation);
-			} catch (IOException e) {
-				e.printStackTrace();
-			}
-		}
-	}
-
-	private class ServerThread extends Thread {
-		private final BluetoothServerSocket serverSocket;
-
-		public ServerThread() {
-			BluetoothServerSocket tmp = null;
-			try {
-				tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(
-						context.getResources().getString(R.string.app_name),
-						serviceUUID);
-			} catch (IOException e) {
-			}
-			serverSocket = tmp;
-		}
-
-		/** Will cancel the listening socket, and cause the thread to finish */
-		public void cancel() {
-			try {
-				serverSocket.close();
-			} catch (IOException e) {
-			}
-		}
-
-		@Override
-		public void run() {
-			BluetoothSocket socket = null;
-			while (true) {
-				try {
-					socket = serverSocket.accept();
-				} catch (IOException e) {
-					e.printStackTrace();
-					break;
-				}
-
-				if (socket != null) {
-					// Do work to manage the connection (in a separate thread)
-					manageConnectedSocket(socket, SERVER);
-					try {
-						serverSocket.close();
-					} catch (IOException e) {
-						e.printStackTrace();
-					}
-					break;
-				}
-			}
-		}
-	}
-
-	private final UUID serviceUUID;
-	private final int SERVER = 0;
-	private final int CLIENT = 1;
-
-	private BluetoothAdapter mBluetoothAdapter;
-	private Context context;
-
-	private ArrayAdapter<String> arrayAdapter;
-
-	private ServerThread serverThread;
-
-	private AlertDialog ad;
-
-	// Create a BroadcastReceiver for ACTION_FOUND
-	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
-		@Override
-		public void onReceive(Context context, Intent intent) {
-			String action = intent.getAction();
-			// When discovery finds a device
-			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
-				// Get the BluetoothDevice object from the Intent
-				BluetoothDevice device = intent
-						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
-				// Add the name and address to an array adapter to show in a
-				// ListView
-				arrayAdapter.add(device.getName() + "\n" + device.getAddress());
-				arrayAdapter.notifyDataSetChanged();
-			}
-		}
-	};
-
-	public BluetoothSync(Context context) {
-		this.context = context;
-		serviceUUID = UUID.fromString(context.getResources().getString(
-				R.string.UUID));
-		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
-	}
-
-	public boolean syncData() {
-		if (!bluetoothAvaible())
-			return false;
-		syncDataPassive();
-		return syncDataActive();
-	}
-
-	private boolean bluetoothAvaible() {
-		if (mBluetoothAdapter == null) {
-			// Device does not support Bluetooth
-			return false;
-		}
-		if (!mBluetoothAdapter.isEnabled()) {
-			Intent enableBtIntent = new Intent(
-					BluetoothAdapter.ACTION_REQUEST_ENABLE);
-			context.startActivity(enableBtIntent);
-			return false;
-		}
-		return true;
-	}
-
-	private void deviceDialog() {
-		AlertDialog.Builder builder = new AlertDialog.Builder(context);
-		// TODO in resources auslagern
-		builder.setTitle("Choose Device");
-		builder.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
-			@Override
-			public void onClick(DialogInterface dialog, int position) {
-				String deviceInfo = arrayAdapter.getItem(position);
-				String mac = deviceInfo.substring(deviceInfo.indexOf("\n") + 1);
-				ClientThread clientThread = new ClientThread(mBluetoothAdapter
-						.getRemoteDevice(mac));
-				clientThread.start();
-			}
-		});
-		// builder.create();
-		ad = builder.show();
-	}
-
-	private void manageConnectedSocket(BluetoothSocket socket, int identifier) {
-		if (identifier == SERVER) {
-			ad.dismiss();
-		}
-		mBluetoothAdapter.cancelDiscovery();
-		context.unregisterReceiver(mReceiver);
-		CommunicationThread commThread = new CommunicationThread(socket,
-				identifier);
-		commThread.start();
-	}
-
-	// Register the BroadcastReceiver
-	private void registerBroadcastReceiver() {
-		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
-		context.registerReceiver(mReceiver, filter); // Don't forget to
-														// unregister during
-														// onDestroy
-	}
-
-	private boolean syncDataActive() {
-		registerBroadcastReceiver();
-		arrayAdapter = new ArrayAdapter<String>(context,
-				android.R.layout.simple_list_item_1);
-		// Start scanning for devices
-		if (!mBluetoothAdapter.startDiscovery())
-			return false;
-
-		deviceDialog();
-		return true;
-	}
-
-	private void syncDataPassive() {
-		Intent discoverableIntent = new Intent(
-				BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
-		discoverableIntent.putExtra(
-				BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
-		context.startActivity(discoverableIntent);
-
-		serverThread = new ServerThread();
-		serverThread.start();
-	}
-
-}
+package de.tudarmstadt.informatik.hostage.sync;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.UUID;
+
+import android.util.Log;
+import android.app.Activity;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothServerSocket;
+import android.bluetooth.BluetoothSocket;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.view.View;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.LinearLayout;
+import android.widget.ListView;
+import android.widget.TextView;
+import android.widget.AdapterView.OnItemClickListener;
+import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+
+public class BluetoothSync extends Activity{	
+	
+    private static final int CONNECTION_ESTABLISHED = 0x0;
+    private static final int CONNECTION_FAILED = 0x1;
+    private static final int MESSAGE_SENT = 0x2;
+    private static final int MESSAGE_RECIEVED = 0x3;
+    
+	private UUID serviceUUID;
+	
+	private BluetoothAdapter mBluetoothAdapter;
+	private ArrayAdapter<String> arrayAdapter;
+
+	private ServerThread serverThread;	
+	private ClientThread clientThread;
+	CommunicationThread commThread;
+	
+	TextView mInfoText;
+	ListView listView;
+	LinearLayout layout;
+	
+	
+	@Override
+	public void onCreate(Bundle savedInstanceState){
+		super.onCreate(savedInstanceState);
+		setContentView(R.layout.activity_bluetooth);		
+		
+		serviceUUID = UUID.fromString(getResources().getString(R.string.UUID));
+		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();					
+		arrayAdapter = new ArrayAdapter<String>(this, R.layout.list_view_bluetooth_devices);	
+		setLayoutElement();
+		registerBroadcastReceiver();
+				
+		if (mBluetoothAdapter == null) {
+			// Device does not support Bluetooth
+			mInfoText.setText("Bluetooth is not available on this device.");
+		}
+		else if (!mBluetoothAdapter.isEnabled()) {
+			mInfoText.setText("Enable Bluetooth before synchronizing.");
+			Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
+			startActivity(enableBtIntent);
+		} else {
+			startConnectionListener();
+			chooseDevice();
+		}
+	}
+		
+	
+	@Override
+	public void onDestroy(){
+		super.onDestroy();
+		if(mRecieverRegistered){
+			unregisterBroadcastReceiver();
+		}
+		if(commThread != null) {
+			commThread.cancel();
+		}
+		if(clientThread != null){
+			clientThread.cancel();
+		}
+		if(serverThread != null){
+			serverThread.cancel();
+		}
+	}
+	
+	private void chooseDevice(){
+		arrayAdapter.clear();
+		if (!mBluetoothAdapter.startDiscovery())
+			return;
+		mInfoText.setText("Choose Device for synchronizing:\n");
+		layout.addView(listView);
+		setContentView(layout);
+	}
+
+	private void startConnectionListener() {
+		Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
+		discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
+		startActivity(discoverableIntent);
+
+		serverThread = new ServerThread();
+		serverThread.start();
+	}
+		
+
+	private void manageConnectedSocket(BluetoothSocket socket) {
+		mBluetoothAdapter.cancelDiscovery();
+		unregisterBroadcastReceiver();
+		commThread = new CommunicationThread(socket);
+		commThread.start();
+		HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
+		ArrayList<HashMap<String, Object>> localNetworkInformation = dbh.getNetworkInformation();
+		commThread.write(localNetworkInformation);
+	}
+
+	private class ClientThread extends Thread {
+		private final BluetoothSocket socket;
+
+		public ClientThread(BluetoothDevice device) {
+			BluetoothSocket tmp = null;
+			try {
+				tmp = device.createRfcommSocketToServiceRecord(serviceUUID);
+			} catch (IOException e) {
+			}
+			socket = tmp;
+		}
+
+		/** Will cancel an in-progress connection, and close the socket */
+		public void cancel() {
+			try {
+				socket.close();
+			} catch (IOException e) {
+			}
+		}
+
+		@Override
+		public void run() {
+
+			try {
+				socket.connect();
+			} catch (IOException connectException) {
+				mHandler.obtainMessage(CONNECTION_FAILED).sendToTarget();
+				// Unable to connect; close the socket and get out
+				try {
+					socket.close();
+				} catch (IOException closeException) {
+				}
+				return;
+			}
+			mHandler.obtainMessage(CONNECTION_ESTABLISHED, socket).sendToTarget();
+			manageConnectedSocket(socket);
+		}
+	}
+
+	private class ServerThread extends Thread {
+		private final BluetoothServerSocket serverSocket;
+
+		public ServerThread() {
+			BluetoothServerSocket tmp = null;
+			try {
+				tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(getResources().getString(R.string.app_name), serviceUUID);
+			} catch (IOException e) {
+			}
+			serverSocket = tmp;
+		}
+
+		/** Will cancel the listening socket, and cause the thread to finish */
+		public void cancel() {
+			try {
+				serverSocket.close();
+			} catch (IOException e) {
+			}
+		}
+
+		@Override
+		public void run() {
+			BluetoothSocket socket = null;
+			while (true) {
+				try {
+					socket = serverSocket.accept();
+				} catch (IOException e) {
+					e.printStackTrace();
+					mHandler.obtainMessage(CONNECTION_FAILED).sendToTarget();
+					break;
+				}
+
+				if (socket != null) {
+					// Do work to manage the connection (in a separate thread)
+					manageConnectedSocket(socket);
+					mHandler.obtainMessage(CONNECTION_ESTABLISHED, socket).sendToTarget();
+					try {
+						serverSocket.close();
+					} catch (IOException e) {
+						e.printStackTrace();
+					}
+					break;
+				}
+			}
+		}
+	}
+	
+	private class CommunicationThread extends Thread {
+		private final BluetoothSocket mmSocket;
+		private final ObjectInputStream objectInput;
+		private final ObjectOutputStream objectOuput;
+
+		public CommunicationThread(BluetoothSocket socket) {
+			mmSocket = socket;
+			ObjectInputStream tmpIn = null;
+			ObjectOutputStream tmpOut = null;
+
+			// Get the input and output streams, using temp objects because
+			// member streams are final
+			try {
+				tmpOut = new ObjectOutputStream(socket.getOutputStream());
+				tmpIn = new ObjectInputStream(socket.getInputStream());
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+
+			objectInput = tmpIn;
+			objectOuput = tmpOut;
+		}
+
+		/* Call this from the main activity to shutdown the connection */
+		public void cancel() {
+			try {
+				mmSocket.close();
+			} catch (IOException e) {
+			}
+		}
+
+		@Override
+		public void run() {
+			// Keep listening to the InputStream until an exception occurs
+			while (true) {
+			try {
+				// TODO Ersetze dbh mit Logger
+				HostageDBOpenHelper dbh = new HostageDBOpenHelper(getContext());
+				// Read from the InputStream
+				ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) objectInput.readObject();
+				// update database
+				dbh.updateNetworkInformation(remoteNetworkInformation);	
+				mHandler.obtainMessage(MESSAGE_RECIEVED).sendToTarget();
+			} catch (ClassNotFoundException e) {
+				e.printStackTrace();
+			} catch (IOException e) {
+				e.printStackTrace();
+				break;
+			}
+			}
+		}
+
+		/* Call this from the main activity to send data to the remote device */
+		public void write(ArrayList<HashMap<String, Object>> networkInformation) {
+			try {
+				objectOuput.writeObject(networkInformation);
+				mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+	}
+
+
+	// Create a BroadcastReceiver for ACTION_FOUND
+	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
+		@Override
+		public void onReceive(Context context, Intent intent) {
+			String action = intent.getAction();
+			// When discovery finds a device
+			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
+				// Get the BluetoothDevice object from the Intent
+				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
+				// Add the name and address to an array adapter to show in a ListView
+				arrayAdapter.add(device.getName() + "\n" + device.getAddress());
+				arrayAdapter.notifyDataSetChanged();
+			}else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
+				int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
+				Log.i("BluetoothSync", state + "");
+				if(state == BluetoothAdapter.STATE_ON){
+					startConnectionListener();
+					chooseDevice();
+				}else if(state == BluetoothAdapter.STATE_OFF ||  state == BluetoothAdapter.STATE_TURNING_OFF){
+					mInfoText.setText("Enable Bluetooth before synchronizing.");
+					layout.removeView(listView);
+				}
+			}
+		}
+	};
+	
+	private boolean mRecieverRegistered = false;
+
+
+	// Register the BroadcastReceiver
+	private void registerBroadcastReceiver() {
+		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
+		filter.addAction(BluetoothAdapter. ACTION_STATE_CHANGED);
+		registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
+		mRecieverRegistered = true;
+	}
+	
+	private void unregisterBroadcastReceiver(){
+		unregisterReceiver(mReceiver);
+		mRecieverRegistered = false;
+	}
+	
+	private Context getContext(){
+		return this;
+	}
+	
+	private void setLayoutElement(){
+		mInfoText = (TextView) findViewById(R.id.bluetoothInfoText);
+		layout = (LinearLayout) findViewById(R.id.bluetoothLayout);
+		listView = new ListView(this);
+		listView.setAdapter(arrayAdapter);
+		listView.setOnItemClickListener(new OnItemClickListener() {
+			@Override
+			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
+				String deviceInfo = arrayAdapter.getItem(position);
+				String mac = deviceInfo.substring(deviceInfo.indexOf("\n") + 1);
+				clientThread = new ClientThread(mBluetoothAdapter.getRemoteDevice(mac));
+				clientThread.start();
+			}
+		});		
+	}	
+	
+	private boolean message_sent = false;
+	private boolean message_recieved = false;
+	
+	private Handler mHandler = new Handler() {
+
+        @Override
+        public void handleMessage(Message msg) {
+        	switch(msg.what){
+        		case CONNECTION_ESTABLISHED: 
+        			layout.removeView(listView);
+        			BluetoothSocket socket = (BluetoothSocket) msg.obj;
+        			String deviceName = socket.getRemoteDevice().getName();
+        			mInfoText.setText("Synchronizing with " + deviceName + "...");	
+        			break;
+        		case CONNECTION_FAILED: 
+        			mInfoText.setText("Synchronization failed!");
+        			break;
+        		case MESSAGE_SENT: 
+        			message_sent = true;
+        			if(message_recieved)
+        				mInfoText.setText("Synchronization successfull!");
+        			break;	
+        		case MESSAGE_RECIEVED: 
+        			message_recieved = true;
+        			if(message_sent)
+        				mInfoText.setText("Synchronization successfull!");
+        			break;	
+        	}        		
+        }
+};
+}

+ 169 - 185
src/de/tudarmstadt/informatik/hostage/sync/NFCSync.java

@@ -1,185 +1,169 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package de.tudarmstadt.informatik.hostage.sync;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import android.annotation.TargetApi;
-import android.app.Activity;
-import android.content.Intent;
-import android.nfc.NdefMessage;
-import android.nfc.NdefRecord;
-import android.nfc.NfcAdapter;
-import android.nfc.NfcAdapter.CreateNdefMessageCallback;
-import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
-import android.nfc.NfcEvent;
-import android.os.Build;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.os.Parcelable;
-import android.util.Log;
-import android.widget.TextView;
-import android.widget.Toast;
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
-
-@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
-public class NFCSync extends Activity implements CreateNdefMessageCallback,
-		OnNdefPushCompleteCallback {
-	NfcAdapter mNfcAdapter;
-	TextView mInfoText;
-	private static final int MESSAGE_SENT = 1;
-
-	public static Object deserialize(byte[] data) throws IOException,
-			ClassNotFoundException {
-		ByteArrayInputStream in = new ByteArrayInputStream(data);
-		ObjectInputStream is = new ObjectInputStream(in);
-		return is.readObject();
-	}
-
-	public static byte[] serialize(Object obj) throws IOException {
-		ByteArrayOutputStream out = new ByteArrayOutputStream();
-		ObjectOutputStream os = new ObjectOutputStream(out);
-		os.writeObject(obj);
-		return out.toByteArray();
-	}
-
-	/** This handler receives a message from onNdefPushComplete */
-	private final Handler mHandler = new Handler() {
-		@Override
-		public void handleMessage(Message msg) {
-			switch (msg.what) {
-			case MESSAGE_SENT:
-				Toast.makeText(getApplicationContext(), "Message sent!",
-						Toast.LENGTH_LONG).show();
-				Log.i("NFC", "Message sent!");
-				break;
-			}
-		}
-	};
-
-	/**
-	 * Implementation for the CreateNdefMessageCallback interface
-	 */
-	@Override
-	public NdefMessage createNdefMessage(NfcEvent event) {
-		// Get Networkdata
-		UglyDbHelper dbh = new UglyDbHelper(this);
-		ArrayList<HashMap<String, Object>> localNetworkInformation = dbh
-				.getNetworkInformation();
-		Log.i("NFC", "Creating Message");
-		NdefMessage msg = null;
-		try {
-			msg = new NdefMessage(NdefRecord.createMime(
-					"application/de.tudarmstadt.informatik.hostage",
-					serialize(localNetworkInformation))
-			/**
-			 * The Android Application Record (AAR) is commented out. When a
-			 * device receives a push with an AAR in it, the application
-			 * specified in the AAR is guaranteed to run. The AAR overrides the
-			 * tag dispatch system. You can add it back in to guarantee that
-			 * this activity starts when receiving a beamed message. For now,
-			 * this code uses the tag dispatch system.
-			 */
-			// ,NdefRecord.createApplicationRecord("com.example.android.beam")
-			);
-		} catch (IOException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		}
-		return msg;
-	}
-
-	@Override
-	public void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-		setContentView(R.layout.activity_nfc);
-
-		mInfoText = (TextView) findViewById(R.id.record_details_text_ssid);
-		// Check for available NFC Adapter
-		mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
-		if (mNfcAdapter == null) {
-			mInfoText = (TextView) findViewById(R.id.record_details_text_ssid);
-			mInfoText.setText("NFC is not available on this device.");
-		} else {
-			// Register callback to set NDEF message
-			mNfcAdapter.setNdefPushMessageCallback(this, this);
-			// Register callback to listen for message-sent success
-			mNfcAdapter.setOnNdefPushCompleteCallback(this, this);
-		}
-	}
-
-	/**
-	 * Implementation for the OnNdefPushCompleteCallback interface
-	 */
-	@Override
-	public void onNdefPushComplete(NfcEvent arg0) {
-		// A handler is needed to send messages to the activity when this
-		// callback occurs, because it happens from a binder thread
-		mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
-	}
-
-	@Override
-	public void onNewIntent(Intent intent) {
-		// onResume gets called after this to handle the intent
-		setIntent(intent);
-	}
-
-	// HELPER
-
-	@Override
-	public void onResume() {
-		super.onResume();
-		// Check to see that the Activity started due to an Android Beam
-		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
-			processIntent(getIntent());
-		}
-	}
-
-	/**
-	 * Parses the NDEF Message from the intent and prints to the TextView
-	 */
-	void processIntent(Intent intent) {
-		Parcelable[] rawMsgs = intent
-				.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
-		// only one message sent during the beam
-		NdefMessage msg = (NdefMessage) rawMsgs[0];
-		// record 0 contains the MIME type, record 1 is the AAR, if present
-		Object object;
-		Log.i("NFC", "Getting Message!");
-		try {
-			object = deserialize(msg.getRecords()[0].getPayload());
-			ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) object;
-			UglyDbHelper dbh = new UglyDbHelper(this);
-			dbh.updateNetworkInformation(remoteNetworkInformation);
-		} catch (ClassNotFoundException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (IOException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		}
-	}
-
-}
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package de.tudarmstadt.informatik.hostage.sync;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.ArrayList;
+import java.util.HashMap;
+
+import android.annotation.TargetApi;
+import android.app.Activity;
+import android.content.Intent;
+import android.nfc.NdefMessage;
+import android.nfc.NdefRecord;
+import android.nfc.NfcAdapter;
+import android.nfc.NfcAdapter.CreateNdefMessageCallback;
+import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
+import android.nfc.NfcEvent;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.os.Parcelable;
+import android.util.Log;
+import android.widget.TextView;
+import android.widget.Toast;
+import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+
+@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
+public class NFCSync extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback {
+	NfcAdapter mNfcAdapter;
+	TextView mInfoText;
+	private static final int MESSAGE_SENT = 1;
+
+
+
+	/** This handler receives a message from onNdefPushComplete */
+	private final Handler mHandler = new Handler() {
+		@Override
+		public void handleMessage(Message msg) {
+			switch (msg.what) {
+			case MESSAGE_SENT:
+				Toast.makeText(getApplicationContext(), "Message sent!", Toast.LENGTH_LONG).show();
+				Log.i("NFC", "Message sent!");
+				break;
+			}
+		}
+	};
+
+	/**
+	 * Implementation for the CreateNdefMessageCallback interface
+	 */
+	@Override
+	public NdefMessage createNdefMessage(NfcEvent event) {
+		// Get Networkdata
+		HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
+		ArrayList<HashMap<String, Object>> localNetworkInformation = dbh.getNetworkInformation();
+		Log.i("NFC", "Creating Message");
+		NdefMessage msg = null;
+		try {
+			msg = new NdefMessage(NdefRecord.createMime("application/de.tudarmstadt.informatik.hostage", serialize(localNetworkInformation))
+					
+			);
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+		return msg;
+	}
+
+	@Override
+	public void onCreate(Bundle savedInstanceState) {
+		super.onCreate(savedInstanceState);
+		setContentView(R.layout.activity_nfc);
+
+		mInfoText = (TextView) findViewById(R.id.record_details_text_ssid);
+		// Check for available NFC Adapter
+		mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
+		if (mNfcAdapter == null) {
+			mInfoText.setText("NFC is not available on this device.");
+		} else {
+			mInfoText.setText("Hold phones together to synchronize.");
+			// Register callback to set NDEF message
+			mNfcAdapter.setNdefPushMessageCallback(this, this);
+			// Register callback to listen for message-sent success
+			mNfcAdapter.setOnNdefPushCompleteCallback(this, this);
+		}
+	}
+
+	/**
+	 * Implementation for the OnNdefPushCompleteCallback interface
+	 */
+	@Override
+	public void onNdefPushComplete(NfcEvent arg0) {
+		// A handler is needed to send messages to the activity when this
+		// callback occurs, because it happens from a binder thread
+		mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
+	}
+
+	@Override
+	public void onNewIntent(Intent intent) {
+		// onResume gets called after this to handle the intent
+		setIntent(intent);
+	}
+
+	// HELPER
+
+	@Override
+	public void onResume() {
+		super.onResume();
+		// Check to see that the Activity started due to an Android Beam
+		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
+			processIntent(getIntent());
+		}
+	}
+
+	/**
+	 * Parses the NDEF Message from the intent and prints to the TextView
+	 */
+	void processIntent(Intent intent) {
+		Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
+		// only one message sent during the beam
+		NdefMessage msg = (NdefMessage) rawMsgs[0];
+		// record 0 contains the MIME type, record 1 is the AAR, if present
+		Object object;
+		Log.i("NFC", "Getting Message!");
+		try {
+			object = deserialize(msg.getRecords()[0].getPayload());
+			ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) object;
+			HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
+			dbh.updateNetworkInformation(remoteNetworkInformation);
+		} catch (ClassNotFoundException e) {
+			e.printStackTrace();
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+	}
+	
+	private static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
+		ByteArrayInputStream in = new ByteArrayInputStream(data);
+		ObjectInputStream is = new ObjectInputStream(in);
+		return is.readObject();
+	}
+
+	private static byte[] serialize(Object obj) throws IOException {
+		ByteArrayOutputStream out = new ByteArrayOutputStream();
+		ObjectOutputStream os = new ObjectOutputStream(out);
+		os.writeObject(obj);
+		return out.toByteArray();
+	}
+
+}

+ 61 - 0
src/de/tudarmstadt/informatik/hostage/system/Device.java

@@ -0,0 +1,61 @@
+package de.tudarmstadt.informatik.hostage.system;
+
+import java.io.IOException;
+
+import android.util.Log;
+
+public class Device {
+
+	@SuppressWarnings("unused")
+	// DO NOT REMOVE, NEEDED FOR SINGLETON INITIALIZATION
+	private static final Device INSTANCE = new Device();
+
+	private static boolean initialized = false;
+	private static boolean root = false;
+	private static boolean pp = false;
+
+	private Device() {
+		new Thread(new Runnable() {
+			@Override
+			public void run() {
+				try {
+					String test = "[ -e /data/local/bind ]";
+					Process su = new ProcessBuilder("su", "-c", test).start();
+					switch (su.waitFor()) {
+					case 0:
+						root = true;
+						pp = true;
+						break;
+					case 1:
+						root = true;
+						pp = false;
+						break;
+					case 127:
+						root = false;
+						pp = false;
+						break;
+					}
+				} catch (InterruptedException e) {
+				} catch (IOException e) {
+				} finally {
+					initialized = true;
+					Log.d("hostage", "Root: " + Boolean.toString(root));
+					Log.d("hostage", "PP: " + Boolean.toString(pp));
+				}
+			}
+		}).start();
+	}
+
+	public static boolean isRooted() {
+		while (!initialized)
+			;
+		return root;
+	}
+
+	public static boolean isPorthackInstalled() {
+		while (!initialized)
+			;
+		return pp;
+	}
+
+}

+ 0 - 68
src/de/tudarmstadt/informatik/hostage/system/P.java

@@ -1,68 +0,0 @@
-package de.tudarmstadt.informatik.hostage.system;
-
-import java.io.FileDescriptor;
-
-import android.net.LocalServerSocket;
-import android.net.LocalSocket;
-
-/**
- * Receives a file descriptor through a unix domain socket.
- * 
- * @author Mihai Plasoianu
- */
-public class P implements Runnable {
-
-	/**
-	 * Path for UDS in abstract namespace.
-	 */
-	private final static String NAME = "hostage";
-
-	/**
-	 * Port to bind.
-	 */
-	private int port;
-
-	public P(int port) {
-		this.port = port;
-	}
-
-	/**
-	 * Start p, wait for connection and receive a file descriptor.
-	 */
-	public FileDescriptor bindAndGetFD() {
-		FileDescriptor fd = null;
-		try {
-			new Thread(this).start();
-			LocalServerSocket localServer = new LocalServerSocket(NAME);
-			LocalSocket localSocket = localServer.accept();
-			while (localSocket.getInputStream().read() != -1)
-				;
-			FileDescriptor[] fdArray;
-			fdArray = localSocket.getAncillaryFileDescriptors();
-			if (fdArray != null) {
-				fd = fdArray[0];
-			}
-			localSocket.close();
-			localServer.close();
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-		return fd;
-	}
-
-	/**
-	 * Run p in separate Thread.
-	 */
-	@Override
-	public void run() {
-		Process p;
-		try {
-			String command = String.format("/data/local/p %d", port);
-			p = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
-			p.waitFor();
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-	}
-
-}

+ 80 - 0
src/de/tudarmstadt/informatik/hostage/system/PrivilegedPort.java

@@ -0,0 +1,80 @@
+package de.tudarmstadt.informatik.hostage.system;
+
+import java.io.BufferedReader;
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+import android.net.LocalServerSocket;
+import android.net.LocalSocket;
+import android.util.Log;
+
+public class PrivilegedPort implements Runnable {
+
+	public static enum TYPE {
+		TCP, UDP
+	}
+
+	private final static String UNIX_PATH = "hostage";
+
+	private final String LOG_TAG;
+
+	private TYPE type;
+	private int port;
+
+	private FileDescriptor fd;
+
+	public PrivilegedPort(TYPE type, int port) {
+		LOG_TAG = String.format("hostage (porthack %s %d)", type.toString(), port);
+		this.type = type;
+		this.port = port;
+		try {
+			new Thread(this).start();
+			LocalServerSocket localServer = new LocalServerSocket(UNIX_PATH);
+			LocalSocket localSocket = localServer.accept();
+			while (localSocket.getInputStream().read() != -1)
+				;
+			FileDescriptor[] fdArray;
+			fdArray = localSocket.getAncillaryFileDescriptors();
+			if (fdArray != null) {
+				this.fd = fdArray[0];
+			}
+			localSocket.close();
+			localServer.close();
+		} catch (IOException e) {
+		}
+	}
+
+	public FileDescriptor getFD() {
+		return fd;
+	}
+
+	@Override
+	public void run() {
+		String command = String.format("/data/local/bind %s %d", type.toString(), port);
+		try {
+			Process p = new ProcessBuilder("su", "-c", command).start();
+			if (p.waitFor() != 0) {
+				logError(p.getErrorStream());
+			}
+			logOutput(p.getInputStream());
+		} catch (IOException e) {
+		} catch (InterruptedException e) {
+		}
+	}
+
+	private void logOutput(InputStream stdout) throws IOException {
+		BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
+		String line;
+		while ((line = reader.readLine()) != null) {
+			Log.d(LOG_TAG, line);
+		}
+	}
+
+	private void logError(InputStream stderr) throws IOException {
+		BufferedReader reader = new BufferedReader(new InputStreamReader(stderr));
+		Log.e(LOG_TAG, reader.readLine());
+	}
+
+}

+ 177 - 159
src/de/tudarmstadt/informatik/hostage/ui/LogFilter.java

@@ -1,16 +1,15 @@
 package de.tudarmstadt.informatik.hostage.ui;
 
-import android.os.Parcel;
-import android.os.Parcelable;
-
 import java.util.ArrayList;
 import java.util.HashMap;
 
+import android.os.Parcel;
+import android.os.Parcelable;
+
+public class LogFilter implements Parcelable {
 
-public class LogFilter implements Parcelable{
-	
 	public final static String LOG_FILTER_INTENT_KEY = "de.tudarmstadt.informatik.hostage.logfilter";
-	
+
 	private static final String TIMESTAMP_BELOW_KEY = "de.tudarmstadt.informatik.hostage.logfilter.timestampbelow";
 	private static final String TIMESTAMP_ABOVE_KEY = "de.tudarmstadt.informatik.hostage.logfilter.timestampabove";
 	private static final String PROTOCOLS_KEY = "de.tudarmstadt.informatik.hostage.logfilter.protocols";
@@ -18,210 +17,229 @@ public class LogFilter implements Parcelable{
 	private static final String BSSID_KEY = "de.tudarmstadt.informatik.hostage.logfilter.bssid";
 	private static final String SORTTYPE_KEY = "de.tudarmstadt.informatik.hostage.logfilter.sorttype";
 
-	public enum SortType{
-				timestamp(0),
-				protocol(1),
-				_bssid(1),
-				ssid(3),
-				//remoteHostName(5),
-				//lcaolHostName(6),
-				_attack_id(7),
-				_id(8);
-		        private final int id;
-		        SortType(int id) {
-		        	this.id = id;
-		        }
-		        public int getValue() { 
-		        	return id; 
-		        }
-		    }
-	
+	public enum SortType {
+		packet_timestamp(0), protocol(1), _bssid(1), ssid(3), _attack_id(7), _id(8);
+		private final int id;
+
+		SortType(int id) {
+			this.id = id;
+		}
+
+		public int getValue() {
+			return id;
+		}
+	}
+
 	public ArrayList<String> BSSIDs;
 	public ArrayList<String> ESSIDs;
 	public ArrayList<String> protocols;
-	
+
 	public boolean isNotEditable;
-	
+
 	public SortType sorttype;
 
 	public long belowTimestamp;
 	public long aboveTimestamp;
-	
-	
-	public LogFilter(){
+
+	public LogFilter() {
 		this.clear();
 
 	}
 
-    public void clear(){
-        this.belowTimestamp = Long.MAX_VALUE;
-        this.aboveTimestamp = Long.MIN_VALUE;
-        this.sorttype = SortType.timestamp;
-        this.BSSIDs = new ArrayList<String>();
-        this.ESSIDs = new ArrayList<String>();
-        this.protocols = new ArrayList<String>();
-    }
-
-	    public int describeContents() {
-	        return 0;
-	    }
-
-	    // write your object's data to the passed-in Parcel
-	    public void writeToParcel(Parcel out, int flags) {
-	        HashMap<String, ArrayList<String>> values =new HashMap<String,  ArrayList<String>>();
-	        if(this.BSSIDs != null && this.BSSIDs.size() > 0){
-	        	values.put(BSSID_KEY , this.getBSSIDs() );
-	        }
-	        if(this.ESSIDs != null && this.ESSIDs.size() > 0){
-	        	values.put(ESSID_KEY , this.getESSIDs() );
-	        }
-	        if(this.protocols != null && this.protocols.size() > 0){
-	        	values.put(PROTOCOLS_KEY , this.getProtocols() );
-	        }
-	        long timeArray[] = new long[] {this.aboveTimestamp, this.belowTimestamp};
-
-	        out.writeMap(values);
-	        out.writeInt(this.sorttype.getValue());
-	        out.writeDouble(timeArray.length);
-	        out.writeLongArray(timeArray);
-	        out.writeString(this.isNotEditable? "true" : "false");
-	    }
-
-	    
-	    public static final Parcelable.Creator<LogFilter> CREATOR = new Parcelable.Creator<LogFilter>() {
-	        public LogFilter createFromParcel(Parcel in) {
-	            return new LogFilter(in);
-	        }
-
-	        public LogFilter[] newArray(int size) {
-	            return new LogFilter[size];
-	        }
-	    };
-
-	    // example constructor that takes a Parcel and gives you an object populated with it's values
-	    private LogFilter(Parcel in) {
-	        //mData = in.readInt();
-	    	HashMap<String, ArrayList<String>> values = new HashMap<String, ArrayList<String>>();
-	    	in.readMap(values, ArrayList.class.getClassLoader());
-	    	
-	    	this.BSSIDs = values.get(BSSID_KEY);
-	    	this.ESSIDs = values.get(ESSID_KEY);
-	    	this.protocols = values.get(protocols);
-	    	
-	    	if(this.BSSIDs == null) this.BSSIDs = new ArrayList<String>();
-	    	if(this.ESSIDs == null) this.ESSIDs = new ArrayList<String>();
-	    	if(this.protocols == null) this.protocols = new ArrayList<String>();
-	    	
-	    	this.sorttype = SortType.values()[Math.min(in.readInt(), SortType.values().length)];
-	    	
-	    	int size = (int)in.readDouble();
-	    	long timeArray[] = new long[size];
-	    	in.readLongArray(timeArray);
-	    	
-	    	this.belowTimestamp = timeArray[1];
-	    	this.aboveTimestamp = timeArray[0];
-	    	
-	    	String bool = in.readString();
-	    	if(bool.equals("true")) this.isNotEditable = true;
-	    }
-	    
-	public boolean isNotEditable(){
+	public void clear() {
+		this.belowTimestamp = Long.MAX_VALUE;
+		this.aboveTimestamp = Long.MIN_VALUE;
+		this.sorttype = SortType.packet_timestamp;
+		this.BSSIDs = new ArrayList<String>();
+		this.ESSIDs = new ArrayList<String>();
+		this.protocols = new ArrayList<String>();
+	}
+
+	public int describeContents() {
+		return 0;
+	}
+
+	// write your object's data to the passed-in Parcel
+	public void writeToParcel(Parcel out, int flags) {
+		HashMap<String, ArrayList<String>> values = new HashMap<String, ArrayList<String>>();
+		if (this.BSSIDs != null && this.BSSIDs.size() > 0) {
+			values.put(BSSID_KEY, this.getBSSIDs());
+		}
+		if (this.ESSIDs != null && this.ESSIDs.size() > 0) {
+			values.put(ESSID_KEY, this.getESSIDs());
+		}
+		if (this.protocols != null && this.protocols.size() > 0) {
+			values.put(PROTOCOLS_KEY, this.getProtocols());
+		}
+		long timeArray[] = new long[] { this.aboveTimestamp, this.belowTimestamp };
+
+		out.writeMap(values);
+		out.writeInt(this.sorttype.getValue());
+		out.writeDouble(timeArray.length);
+		out.writeLongArray(timeArray);
+		out.writeString(this.isNotEditable ? "true" : "false");
+	}
+
+	public static final Parcelable.Creator<LogFilter> CREATOR = new Parcelable.Creator<LogFilter>() {
+		public LogFilter createFromParcel(Parcel in) {
+			return new LogFilter(in);
+		}
+
+		public LogFilter[] newArray(int size) {
+			return new LogFilter[size];
+		}
+	};
+
+	// example constructor that takes a Parcel and gives you an object populated
+	// with it's values
+	private LogFilter(Parcel in) {
+		// mData = in.readInt();
+		HashMap<String, ArrayList<String>> values = new HashMap<String, ArrayList<String>>();
+		in.readMap(values, ArrayList.class.getClassLoader());
+
+		this.BSSIDs = values.get(BSSID_KEY);
+		this.ESSIDs = values.get(ESSID_KEY);
+		this.protocols = values.get(protocols);
+
+		if (this.BSSIDs == null)
+			this.BSSIDs = new ArrayList<String>();
+		if (this.ESSIDs == null)
+			this.ESSIDs = new ArrayList<String>();
+		if (this.protocols == null)
+			this.protocols = new ArrayList<String>();
+
+		this.sorttype = SortType.values()[Math.min(in.readInt(), SortType.values().length)];
+
+		int size = (int) in.readDouble();
+		long timeArray[] = new long[size];
+		in.readLongArray(timeArray);
+
+		this.belowTimestamp = timeArray[1];
+		this.aboveTimestamp = timeArray[0];
+
+		String bool = in.readString();
+		if (bool.equals("true"))
+			this.isNotEditable = true;
+	}
+
+	public boolean isNotEditable() {
 		return this.isNotEditable;
 	}
-	public SortType getSorttype(){
+
+	public SortType getSorttype() {
 		return this.sorttype;
 	}
-	public ArrayList<String> getBSSIDs(){
+
+	public ArrayList<String> getBSSIDs() {
 		return this.BSSIDs;
 	}
-	public ArrayList<String> getESSIDs(){
+
+	public ArrayList<String> getESSIDs() {
 		return this.ESSIDs;
 	}
-	public ArrayList<String> getProtocols(){
+
+	public ArrayList<String> getProtocols() {
 		return this.protocols;
 	}
-	public void setIsNotEditable(boolean b){
+
+	public void setIsNotEditable(boolean b) {
 		this.isNotEditable = b;
 	}
-	
-	public long getBelowTimestamp(){
+
+	public long getBelowTimestamp() {
 		return this.belowTimestamp;
 	}
-	public long getAboveTimestamp(){
+
+	public long getAboveTimestamp() {
 		return this.aboveTimestamp;
 	}
-	public void setProtocols(ArrayList<String> protocols){
+
+	public void setProtocols(ArrayList<String> protocols) {
 		this.protocols = protocols;
 	}
-	public void setBSSIDs(ArrayList<String> bssids){
+
+	public void setBSSIDs(ArrayList<String> bssids) {
 		this.BSSIDs = bssids;
 	}
-	public void setESSIDs(ArrayList<String> essids){
+
+	public void setESSIDs(ArrayList<String> essids) {
 		this.ESSIDs = essids;
 	}
-	public void setAboveTimestamp(long timestamp){
+
+	public void setAboveTimestamp(long timestamp) {
 		this.aboveTimestamp = timestamp;
 	}
-	public void setBelowTimestamp(long timestamp){
+
+	public void setBelowTimestamp(long timestamp) {
 		this.belowTimestamp = timestamp;
 	}
-	public void setSorttype(SortType type){
+
+	public void setSorttype(SortType type) {
 		this.sorttype = type;
 	}
-	
-	
-	public String getBSSIDQueryStatement(String tablename, String key){
+
+	public String getBSSIDQueryStatement(String tablename, String key) {
 		return this.convertArrayListToQueryString(this.BSSIDs, tablename, key);
 	}
-	public String getESSIDQueryStatement(String tablename, String key){
-		return this.convertArrayListToQueryString(this.ESSIDs,tablename ,key);
-	}
-	public String getProtocolsQueryStatement(String tablename, String key){
-		return this.convertArrayListToQueryString(this.protocols,tablename, key);
-	}
-
-    public boolean isSet(){
-        boolean hasTime = this.hasATimestamp();
-        boolean hasBSSIDs = this.hasBSSIDs();
-        boolean hasESSIDs =this.hasESSIDs();
-        boolean hasProtocols = this.hasProtocols();
-
-        return hasBSSIDs || hasESSIDs || hasProtocols | hasTime;
-    }
-
-    public boolean hasBSSIDs(){
-        return  this.getBSSIDs().size() > 0;
-    }
-    public boolean hasESSIDs(){
-        return  this.getESSIDs().size() > 0;
-    }
-    public boolean hasProtocols(){
-        return  this.getProtocols().size() > 0;
-    }
-    public boolean hasAboveTimestamp(){
-        return this.aboveTimestamp != Long.MIN_VALUE;
-    }
-    public boolean hasBelowTimestamp(){
-        return this.belowTimestamp != Long.MAX_VALUE;
-    }
-    public boolean hasATimestamp(){
-        return this.hasBelowTimestamp()|| this.hasAboveTimestamp();
-    }
-	public String convertArrayListToQueryString(ArrayList<String> list, String table,  String key){
+
+	public String getESSIDQueryStatement(String tablename, String key) {
+		return this.convertArrayListToQueryString(this.ESSIDs, tablename, key);
+	}
+
+	public String getProtocolsQueryStatement(String tablename, String key) {
+		return this.convertArrayListToQueryString(this.protocols, tablename, key);
+	}
+
+	public boolean isSet() {
+		boolean hasTime = this.hasATimestamp();
+		boolean hasBSSIDs = this.hasBSSIDs();
+		boolean hasESSIDs = this.hasESSIDs();
+		boolean hasProtocols = this.hasProtocols();
+
+		return hasBSSIDs || hasESSIDs || hasProtocols | hasTime;
+	}
+
+	public boolean hasBSSIDs() {
+		return this.getBSSIDs().size() > 0;
+	}
+
+	public boolean hasESSIDs() {
+		return this.getESSIDs().size() > 0;
+	}
+
+	public boolean hasProtocols() {
+		return this.getProtocols().size() > 0;
+	}
+
+	public boolean hasAboveTimestamp() {
+		return this.aboveTimestamp != Long.MIN_VALUE;
+	}
+
+	public boolean hasBelowTimestamp() {
+		return this.belowTimestamp != Long.MAX_VALUE;
+	}
+
+	public boolean hasATimestamp() {
+		return this.hasBelowTimestamp() || this.hasAboveTimestamp();
+	}
+
+	public String convertArrayListToQueryString(ArrayList<String> list, String table, String key) {
 		String statement = "";
-		if (list == null) return statement;
+		if (list == null)
+			return statement;
 		statement = " ( ";
 
 		int i = 0, max = list.size();
-		for (String element : list){
+		for (String element : list) {
 			i++;
 			statement = statement + table + "." + key + " = " + "'" + element + "'";
-			if (i == max) continue;
-			statement = statement +" OR ";
+			if (i == max)
+				continue;
+			statement = statement + " OR ";
 		}
 		statement = statement + " ) ";
 
 		return statement;
 	}
-	
+
 }

+ 338 - 419
src/de/tudarmstadt/informatik/hostage/ui/MainActivity.java

@@ -1,10 +1,8 @@
 package de.tudarmstadt.informatik.hostage.ui;
 
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
 import java.util.ArrayList;
 import java.util.HashMap;
-import android.app.Activity;
+
 import android.app.ActivityManager;
 import android.app.ActivityManager.RunningServiceInfo;
 import android.content.BroadcastReceiver;
@@ -15,10 +13,9 @@ import android.content.IntentFilter;
 import android.content.ServiceConnection;
 import android.content.SharedPreferences;
 import android.os.Bundle;
-import android.os.Handler;
 import android.os.IBinder;
+import android.support.v4.app.FragmentActivity;
 import android.support.v4.content.LocalBroadcastManager;
-import android.util.Log;
 import android.view.GestureDetector;
 import android.view.GestureDetector.SimpleOnGestureListener;
 import android.view.Menu;
@@ -36,14 +33,10 @@ import android.widget.ListView;
 import android.widget.TextView;
 import android.widget.ToggleButton;
 import android.widget.ViewAnimator;
-import de.tudarmstadt.informatik.hostage.HoneyService;
-import de.tudarmstadt.informatik.hostage.HoneyService.LocalBinder;
+import de.tudarmstadt.informatik.hostage.Hostage;
+import de.tudarmstadt.informatik.hostage.Hostage.LocalBinder;
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-import de.tudarmstadt.informatik.hostage.logging.LogResultReceiver;
-import de.tudarmstadt.informatik.hostage.logging.LogResultReceiver.Receiver;
-import de.tudarmstadt.informatik.hostage.logging.Logger;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 
 /**
  * MainActivity is the central activity for the GUI of the application.
@@ -58,15 +51,7 @@ import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
  * @author Lars Pandikow
  * @author Wulf Pfeiffer
  */
-public class MainActivity extends Activity implements Receiver {
-	/**
-	 * Flag for root acces. True if phone has root acces, else false.
-	 */
-	public static boolean isRooted = false;
-	/**
-	 * Flag for porthack. True if porthack is installed, else false.
-	 */
-	public static boolean porthackInstalled = false;
+public class MainActivity extends FragmentActivity {
 
 	/**
 	 * Integer representing a grey light.
@@ -85,10 +70,9 @@ public class MainActivity extends Activity implements Receiver {
 	 */
 	public static final int LIGHT_YELLOW = 0x04;
 
-	public LogResultReceiver logResultReceiver;
 	private SharedPreferences connectionInfo;
 
-	private HoneyService mService;
+	private Hostage mService;
 	private boolean serviceBound;
 
 	// variables for the swipe animation
@@ -102,80 +86,65 @@ public class MainActivity extends Activity implements Receiver {
 	private ListView listView;
 	private ListViewAdapter adapter;
 
-	private boolean isBssidSeen = false;
+	/**
+	 * Connection to bind the background service
+	 * 
+	 * @see Hostage
+	 */
+	private ServiceConnection mConnection = new ServiceConnection() {
+		/**
+		 * After the service is bound, check which has been clicked and start
+		 * it.
+		 * 
+		 * @see android.content.ServiceConnection#onServiceConnected(android.content.ComponentName)
+		 */
+		@Override
+		public void onServiceConnected(ComponentName name, IBinder service) {
+			mService = ((LocalBinder) service).getService();
+			serviceBound = true;
+			updateUI();
+		}
 
-	@Override
-	protected void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-		logResultReceiver = new LogResultReceiver(new Handler());
-		setContentView(R.layout.activity_main);
-		connectionInfo = getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
-		
-		// Create dynamic view elements
-		initViewAnimator();
-		initListView();
-		// Initialize Class variables
-		checkRootAndPorthack();
-		startAndBind();
-	}
+		/**
+		 * After the service is unbound, delete reference.
+		 * 
+		 * @see android.content.ServiceConnection#onServiceDisconnected(android.content.ComponentName)
+		 */
+		@Override
+		public void onServiceDisconnected(ComponentName name) {
+			mService = null;
+			serviceBound = false;
+		}
 
-	@Override
-	public boolean onCreateOptionsMenu(Menu menu) {
-		getMenuInflater().inflate(R.menu.main, menu);
-		return true;
-	}
+	};
 
-	@Override
-	public boolean onOptionsItemSelected(MenuItem item) {
-		// Handle item selection
-		switch (item.getItemId()) {
-		case R.id.action_settings:
-			startActivity(new Intent(this, SettingsActivity.class));
-			break;
-		case R.id.action_about:
-			startActivity(new Intent(this, AboutActivity.class));
-			break;
-		default:
+	/**
+	 * Receiver for custom broadcast.
+	 * 
+	 * @see #BROADCAST
+	 */
+	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
+		@Override
+		public void onReceive(Context context, Intent intent) {
+			// Update user interface.
+			updateUI();
+			updateConnectionInfText();
 		}
-		return super.onOptionsItemSelected(item);
-	}
-
-	@Override
-	protected void onStart() {
-		super.onStart();
-		// Register Broadcast Receiver
-		registerReceiver();
-		logResultReceiver.setReceiver(this);
-		// Bind service if running, else check for connection change and delete
-		// sessionData
-		if (isServiceRunning()) {
-			bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
-		} 
-		// Update UI
-		updateConnectionInfText();
-	}
+	};
 
-	@Override
-	protected void onStop() {
-		// Unregister Broadcast Receiver
-		unregisterReceiver();
-		logResultReceiver.setReceiver(null);
-		super.onStop();
-	}
+	SimpleOnGestureListener simpleOnGestureListener = new SimpleOnGestureListener() {
+		@Override
+		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
+			float sensitvity = 50;
+			if ((e1.getX() - e2.getX()) > sensitvity) {
+				swipeRightToLeft();
+			} else if ((e2.getX() - e1.getX()) > sensitvity) {
+				swipeLeftToRight();
+			}
 
-	@Override
-	protected void onDestroy() {
-		// Unbind running service
-		if(!mService.hasRunningListeners()){
-			stopAndUnbind();
+			return true;
 		}
-		super.onDestroy();
-	}
-
-	@Override
-	public void onReceiveResult(int resultCode, Bundle resultData) {
-		isBssidSeen = resultData.getBoolean("result");
-	}
+	};
 
 	/**
 	 * Called when User presses on/off button.
@@ -186,15 +155,15 @@ public class MainActivity extends Activity implements Receiver {
 		if (((ToggleButton) view).isChecked()) {
 			if (isParanoid()) {
 				String[] protocols = getResources().getStringArray(R.array.protocols);
-				for(String protocol: protocols){
-					mService.startListener(protocol);	
-				}						
+				for (String protocol: protocols) {
+					mService.startListener(protocol);
+				}
 			} else {
-				if(mService.isRunning("SMB")){
+				if (mService.isRunning("SMB")) {
 					mService.stopListener("SMB");
-				}else{
+				} else {
 					mService.startListener("SMB");
-				}	
+				}
 			}
 		} else {
 			mService.stopListeners();
@@ -202,6 +171,32 @@ public class MainActivity extends Activity implements Receiver {
 		}
 	}
 
+	@Override
+	public boolean onCreateOptionsMenu(Menu menu) {
+		getMenuInflater().inflate(R.menu.main, menu);
+		return true;
+	}
+
+	@Override
+	public boolean onOptionsItemSelected(MenuItem item) {
+		// Handle item selection
+		switch (item.getItemId()) {
+		case R.id.action_settings:
+			startActivity(new Intent(this, SettingsActivity.class));
+			break;
+		case R.id.action_about:
+			startActivity(new Intent(this, AboutActivity.class));
+			break;
+		default:
+		}
+		return super.onOptionsItemSelected(item);
+	}
+
+	@Override
+	public boolean onTouchEvent(MotionEvent event) {
+		return gestureDetector.onTouchEvent(event);
+	}
+
 	/**
 	 * Starts the ViewLog activity, when the Button is pressed.
 	 * 
@@ -217,126 +212,22 @@ public class MainActivity extends Activity implements Receiver {
 		startActivity(new Intent(this, PlayGroundActivity.class));
 	}
 
-	/**
-	 * If mobile phone is connected to a wireless network starts the background
-	 * service ands binds itself to it. Else notifies the user that service
-	 * could not be started.
-	 */
-	private void startAndBind() {
-		startService(getServiceIntent());
-		bindService();
-	}
-
 	/**
 	 * Binds service to Activity
 	 * 
-	 * @see HoneyService
+	 * @see Hostage
 	 */
 	private void bindService() {
 		bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
 	}
 
-	/**
-	 * Stops service and unbinds it.
-	 * 
-	 * @see HoneyService
-	 */
-	private void stopAndUnbind() {
-		unbindService();
-		stopService(getServiceIntent());
-	}
-
-	/**
-	 * Unbinds service.
-	 * 
-	 * @see HoneyService
-	 */
-	private void unbindService() {
-		unbindService(mConnection);
-	}
-
-	/**
-	 * Connection to bind the background service
-	 * 
-	 * @see HoneyService
-	 */
-	private ServiceConnection mConnection = new ServiceConnection() {
-		/**
-		 * After the service is bound, check which has been clicked and start
-		 * it.
-		 * 
-		 * @see android.content.ServiceConnection#onServiceConnected(android.content.ComponentName)
-		 */
-		@Override
-		public void onServiceConnected(ComponentName name, IBinder service) {
-			mService = ((LocalBinder) service).getService();
-			serviceBound = true;
-			updateUI();
-		}
-
-		/**
-		 * After the service is unbound, delete reference.
-		 * 
-		 * @see android.content.ServiceConnection#onServiceDisconnected(android.content.ComponentName)
-		 */
-		@Override
-		public void onServiceDisconnected(ComponentName name) {
-			mService = null;
-			serviceBound = false;
-		}
-
-	};
-
-	/**
-	 * Checks if the phone ist rooted and if porthack is installed. Sets flags
-	 * {@link isRooted} and {@link porthackInstalled}
-	 */
-	private void checkRootAndPorthack() {
-		isRooted = false;
-		porthackInstalled = false;
-		Process p;
-		try {
-			String found = "Found";
-			String notFound = "Not found";
-			String command = "[ -f /data/local/p ] && echo " + found
-					+ " || echo " + notFound;
-			p = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
-			BufferedReader in = new BufferedReader(new InputStreamReader(
-					p.getInputStream()));
-			/*
-			 * int av = byte[] b = new byte[av]; if (av != 0) { in.read(b); }
-			 */
-			String echoResponse = in.readLine();
-			Log.i("MainAc", echoResponse);
-			if (echoResponse.equals(found)) {
-				isRooted = true;
-				porthackInstalled = true;
-			} else if (echoResponse.equals(notFound)) {
-				isRooted = true;
-			}
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-		Log.i("MainAc", "Rooted: " + isRooted + " Porthack: "
-				+ porthackInstalled);
-	}
-
 	/**
 	 * Returns an intent to start HoneyService.
 	 * 
 	 * @return An Intent to start HoneyService
 	 */
 	private Intent getServiceIntent() {
-		return new Intent(this, HoneyService.class);
-	}
-
-	/**
-	 * Checks if user selected paranoid mode.
-	 * 
-	 * @return True when paranoid mode is selected, else returns false.
-	 */
-	private boolean isParanoid() {
-		return ((CheckBox) findViewById(R.id.checkBoxParanoid)).isChecked();
+		return new Intent(this, Hostage.class);
 	}
 
 	/**
@@ -366,226 +257,130 @@ public class MainActivity extends Activity implements Receiver {
 		listView.setOnItemClickListener(new OnItemClickListener() {
 
 			@Override
-			public void onItemClick(AdapterView<?> parent, View view,
-					int position, long id) {
-				String protocolName = (String) ((HashMap<?, ?>) adapter
-						.getItem(position)).get("protocol");
-				if(mService.isRunning(protocolName)){
+			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
+				String protocolName = (String) ((HashMap<?, ?>) adapter.getItem(position)).get("protocol");
+				if (mService.isRunning(protocolName)) {
 					mService.stopListener(protocolName);
-				}else{
+				} else {
 					mService.startListener(protocolName);
-				}				
+				}
 			}
 		});
 	}
-	
+
+	/**
+	 * Initializes variables for screen animation
+	 */
+	private void initViewAnimator() {
+		viewAnimator = (ViewAnimator) findViewById(R.id.viewAnimator);
+		gestureDetector = new GestureDetector(this, simpleOnGestureListener);
+
+		animFlipInLR = AnimationUtils.loadAnimation(this, R.anim.in_left_to_right);
+		animFlipOutLR = AnimationUtils.loadAnimation(this, R.anim.out_left_to_right);
+		animFlipInRL = AnimationUtils.loadAnimation(this, R.anim.in_right_to_left);
+		animFlipOutRL = AnimationUtils.loadAnimation(this, R.anim.out_right_to_left);
+	}
+
 	/**
-	 * Checks if a {@link HoneyService} instance is running.
+	 * Checks if user selected paranoid mode.
 	 * 
-	 * @return True if {@link HoneyService} is running, else false.
+	 * @return True when paranoid mode is selected, else returns false.
 	 */
-	private boolean isServiceRunning() {
-		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
-		for (RunningServiceInfo service : manager
-				.getRunningServices(Integer.MAX_VALUE)) {
-			if (service.service.getClassName().equals(
-					HoneyService.class.getName())) {
-				return true;
-			}
-		}
-		return false;
+	private boolean isParanoid() {
+		return ((CheckBox) findViewById(R.id.checkBoxParanoid)).isChecked();
 	}
-	
+
 	/**
-	 * Checks if a {@link HoneyService} instance is running.
+	 * Checks if a {@link Hostage} instance is running.
 	 * 
-	 * @return True if {@link HoneyService} is running, else false.
+	 * @return True if {@link Hostage} is running, else false.
 	 */
 	private boolean isServiceBound() {
 		return serviceBound;
 	}
 
 	/**
-	 * Register broadcast receiver for custom broadcast.
+	 * Checks if a {@link Hostage} instance is running.
 	 * 
-	 * @see #BROADCAST
+	 * @return True if {@link Hostage} is running, else false.
 	 */
-	private void registerReceiver() {
-		LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
-				new IntentFilter(getString(R.string.broadcast)));
+	private boolean isServiceRunning() {
+		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
+		for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
+			if (service.service.getClassName().equals(Hostage.class.getName())) {
+				return true;
+			}
+		}
+		return false;
 	}
 
 	/**
-	 * Unregisters broadcast receiver for custom broadcast.
+	 * Register broadcast receiver for custom broadcast.
 	 * 
 	 * @see #BROADCAST
 	 */
-	private void unregisterReceiver() {
-		LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
+	private void registerReceiver() {
+		LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter(getString(R.string.broadcast)));
 	}
 
 	/**
-	 * Receiver for custom broadcast.
-	 * 
-	 * @see #BROADCAST
-	 */
-	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
-		@Override
-		public void onReceive(Context context, Intent intent) {
-			// Update user interface.
-			updateUI();
-			updateConnectionInfText();
-		}
-	};
+	 * If mobile phone is connected to a wireless network starts the background
+	 * service ands binds itself to it. Else notifies the user that service
+	 * could not be started.
+	 */
+	private void startAndBind() {
+		startService(getServiceIntent());
+		bindService();
+	}
 
 	/**
-	 * Updates Information shown by the GUI.
+	 * Stops service and unbinds it.
+	 * 
+	 * @see Hostage
 	 */
-	private void updateUI() {
-		boolean activeListeners = false;
-		boolean activeHandlers = false;
-		boolean yellowLight = false;
-		
-		// Check for all protocols if listeners are active and attacks have been
-		// recorded
-		// Update protocol lights and connection information.
-		for (String protocol : getResources().getStringArray(R.array.protocols)) {
-			if(isServiceBound()){
-				// Check if protocol is active
-				if (mService.isRunning(protocol)) {
-					activeListeners = true;
-					int handlerCount = mService.getNumberOfActiveConnections(protocol);
-					// Check if attacks have been recorded in this session.
-					if (handlerCount > 0) {
-						activeHandlers = true;
-						updateProtocolLight(LIGHT_RED, protocol);
-						updateProtocolConnections(handlerCount, protocol);
-					} else {
-						// Check if the bssid of the wireless network has already
-						// been recorded as infected.
-						Logger.isBssidSeen(getApplicationContext(), protocol,
-								HelperUtils.getBSSID(getApplicationContext()),
-								logResultReceiver);
-						UglyDbHelper dbh = new UglyDbHelper(this);
-						if (dbh.bssidSeen(protocol, connectionInfo.getString(getString(R.string.connection_info_bssid), null))) {
-							updateProtocolLight(LIGHT_YELLOW, protocol);
-							yellowLight = true;
-						} else {
-							updateProtocolLight(LIGHT_GREEN, protocol);
-						}
-						updateProtocolConnections(0, protocol);
-					}
-				} else {
-					updateProtocolLight(LIGHT_GREY, protocol);
-				}
-			}else{
-				updateProtocolLight(LIGHT_GREY, protocol);
-			}				
-		}
+	private void stopAndUnbind() {
+		unbindService();
+		stopService(getServiceIntent());
+	}
 
-		// Update the big attack indicator.
-		if (activeListeners) {
-			if (activeHandlers) {
-				updateStatusLight(LIGHT_RED);
-			} else {
-				if (yellowLight) {
-					updateStatusLight(LIGHT_YELLOW);
-				} else {
-					updateStatusLight(LIGHT_GREEN);
-				}
-			}
-			((ToggleButton) findViewById(R.id.toggleButtonOnOff))
-					.setChecked(true);
-			findViewById(R.id.checkBoxParanoid).setEnabled(false);
-		} else {
-			updateStatusLight(LIGHT_GREY);
-			((ToggleButton) findViewById(R.id.toggleButtonOnOff))
-					.setChecked(false);
-			findViewById(R.id.checkBoxParanoid).setEnabled(true);
+	/**
+	 * Called when a swipe to the Right is registered.
+	 */
+	private void swipeLeftToRight() {
+		if (viewAnimator.getDisplayedChild() == 1) {
+			viewAnimator.setInAnimation(animFlipInLR);
+			viewAnimator.setOutAnimation(animFlipOutLR);
+			viewAnimator.setDisplayedChild(0);
 		}
 	}
 
 	/**
-	 * Sets the big light indicator.
-	 * 
-	 * @param light
-	 *            Integer code to set the light color.
-	 * @see #LIGHT_GREY
-	 * @see #LIGHT_GREEN
-	 * @see #LIGHT_RED
-	 * @see #LIGHT_YELLOW
+	 * Called when a swipe to the Left is registered.
 	 */
-	private void updateStatusLight(int light) {
-		switch (light) {
-		case LIGHT_GREY:
-			((ImageView) findViewById(R.id.imageViewLight))
-					.setImageResource(R.drawable.light_grey_large);
-			break;
-		case LIGHT_GREEN:
-			((ImageView) findViewById(R.id.imageViewLight))
-					.setImageResource(R.drawable.light_green_large);
-			break;
-		case LIGHT_RED:
-			((ImageView) findViewById(R.id.imageViewLight))
-					.setImageResource(R.drawable.light_red_large);
-			break;
-		case LIGHT_YELLOW:
-			((ImageView) findViewById(R.id.imageViewLight))
-					.setImageResource(R.drawable.light_yellow_large);
-			break;
+	private void swipeRightToLeft() {
+		if (viewAnimator.getDisplayedChild() == 0) {
+			viewAnimator.setInAnimation(animFlipInRL);
+			viewAnimator.setOutAnimation(animFlipOutRL);
+			viewAnimator.setDisplayedChild(1);
 		}
 	}
 
 	/**
-	 * Sets the light indicator for a given protocol.
+	 * Unbinds service.
 	 * 
-	 * @param light
-	 *            Integer code to set the light color.
-	 * @param protocolName
-	 *            Name of the protocol which should be updated.
+	 * @see Hostage
 	 */
-	private void updateProtocolLight(int light, String protocolName) {
-		for (int i = 0; i < adapter.getCount(); ++i) {
-			HashMap<String, String> d = (HashMap<String, String>) adapter
-					.getItem(i);
-			if (d.get("protocol").equals(protocolName)) {
-				switch (light) {
-				case LIGHT_GREY:
-					d.put("light", String.valueOf(R.drawable.light_grey));
-					d.put("connections", "-");
-					break;
-				case LIGHT_GREEN:
-					d.put("light", String.valueOf(R.drawable.light_green));
-					break;
-				case LIGHT_RED:
-					d.put("light", String.valueOf(R.drawable.light_red));
-					break;
-				case LIGHT_YELLOW:
-					d.put("light", String.valueOf(R.drawable.light_yellow));
-					break;
-				}
-			}
-		}
-		adapter.notifyDataSetChanged();
+	private void unbindService() {
+		unbindService(mConnection);
 	}
 
 	/**
-	 * Sets the connections count for a given protocol.
+	 * Unregisters broadcast receiver for custom broadcast.
 	 * 
-	 * @param connections
-	 *            New value for recorded connections.
-	 * @param protocolName
-	 *            Name of the protocol which should be updated.
+	 * @see #BROADCAST
 	 */
-	private void updateProtocolConnections(int connections, String protocolName) {
-		for (int i = 0; i < adapter.getCount(); ++i) {
-			HashMap<String, String> d = ((HashMap<String, String>) adapter
-					.getItem(i));
-			if (d.get("protocol").equals(protocolName)) {
-				d.put("connections", String.valueOf(connections));
-			}
-		}
-		adapter.notifyDataSetChanged();
+	private void unregisterReceiver() {
+		LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
 	}
 
 	/**
@@ -597,7 +392,7 @@ public class MainActivity extends Activity implements Receiver {
 		TextView internalIPView = (TextView) findViewById(R.id.textViewInternalIPValue);
 		TextView externalIPView = (TextView) findViewById(R.id.textViewExternalIPValue);
 
-//		externalIPView.setText("Loading...");
+		// externalIPView.setText("Loading...");
 
 		// Get connection information
 		String ssid = connectionInfo.getString(getString(R.string.connection_info_ssid), null);
@@ -620,72 +415,196 @@ public class MainActivity extends Activity implements Receiver {
 			internalIPView.setText(internalIP);
 		else
 			internalIPView.setText("-");
-		
+
 		if (externalIP != null)
 			externalIPView.setText(externalIP);
 		else
 			externalIPView.setText("-");
 	}
 
-	/* ############# Help functions for animation ################## */
-
-	@Override
-	public boolean onTouchEvent(MotionEvent event) {
-		return gestureDetector.onTouchEvent(event);
+	/**
+	 * Sets the connections count for a given protocol.
+	 * 
+	 * @param connections
+	 *            New value for recorded connections.
+	 * @param protocolName
+	 *            Name of the protocol which should be updated.
+	 */
+	private void updateProtocolConnections(int connections, String protocolName) {
+		for (int i = 0; i < adapter.getCount(); ++i) {
+			HashMap<String, String> d = (HashMap<String, String>) adapter.getItem(i);
+			if (d.get("protocol").equals(protocolName)) {
+				d.put("connections", String.valueOf(connections));
+			}
+		}
+		adapter.notifyDataSetChanged();
 	}
 
 	/**
-	 * Initializes variables for screen animation
+	 * Sets the light indicator for a given protocol.
+	 * 
+	 * @param light
+	 *            Integer code to set the light color.
+	 * @param protocolName
+	 *            Name of the protocol which should be updated.
 	 */
-	private void initViewAnimator() {
-		viewAnimator = (ViewAnimator) findViewById(R.id.viewAnimator);
-		gestureDetector = new GestureDetector(this, simpleOnGestureListener);
-
-		animFlipInLR = AnimationUtils.loadAnimation(this,
-				R.anim.in_left_to_right);
-		animFlipOutLR = AnimationUtils.loadAnimation(this,
-				R.anim.out_left_to_right);
-		animFlipInRL = AnimationUtils.loadAnimation(this,
-				R.anim.in_right_to_left);
-		animFlipOutRL = AnimationUtils.loadAnimation(this,
-				R.anim.out_right_to_left);
+	private void updateProtocolLight(int light, String protocolName) {
+		for (int i = 0; i < adapter.getCount(); ++i) {
+			HashMap<String, String> d = (HashMap<String, String>) adapter.getItem(i);
+			if (d.get("protocol").equals(protocolName)) {
+				switch (light) {
+				case LIGHT_GREY:
+					d.put("light", String.valueOf(R.drawable.light_grey));
+					d.put("connections", "-");
+					break;
+				case LIGHT_GREEN:
+					d.put("light", String.valueOf(R.drawable.light_green));
+					break;
+				case LIGHT_RED:
+					d.put("light", String.valueOf(R.drawable.light_red));
+					break;
+				case LIGHT_YELLOW:
+					d.put("light", String.valueOf(R.drawable.light_yellow));
+					break;
+				}
+			}
+		}
+		adapter.notifyDataSetChanged();
 	}
 
 	/**
-	 * Called when a swipe to the Left is registered.
+	 * Sets the big light indicator.
+	 * 
+	 * @param light
+	 *            Integer code to set the light color.
+	 * @see #LIGHT_GREY
+	 * @see #LIGHT_GREEN
+	 * @see #LIGHT_RED
+	 * @see #LIGHT_YELLOW
 	 */
-	private void swipeRightToLeft() {
-		if (viewAnimator.getDisplayedChild() == 0) {
-			viewAnimator.setInAnimation(animFlipInRL);
-			viewAnimator.setOutAnimation(animFlipOutRL);
-			viewAnimator.setDisplayedChild(1);
+	private void updateStatusLight(int light) {
+		switch (light) {
+		case LIGHT_GREY:
+			((ImageView) findViewById(R.id.imageViewLight)).setImageResource(R.drawable.light_grey_large);
+			break;
+		case LIGHT_GREEN:
+			((ImageView) findViewById(R.id.imageViewLight)).setImageResource(R.drawable.light_green_large);
+			break;
+		case LIGHT_RED:
+			((ImageView) findViewById(R.id.imageViewLight)).setImageResource(R.drawable.light_red_large);
+			break;
+		case LIGHT_YELLOW:
+			((ImageView) findViewById(R.id.imageViewLight)).setImageResource(R.drawable.light_yellow_large);
+			break;
 		}
 	}
 
+	/* ############# Help functions for animation ################## */
+
 	/**
-	 * Called when a swipe to the Right is registered.
+	 * Updates Information shown by the GUI.
 	 */
-	private void swipeLeftToRight() {
-		if (viewAnimator.getDisplayedChild() == 1) {
-			viewAnimator.setInAnimation(animFlipInLR);
-			viewAnimator.setOutAnimation(animFlipOutLR);
-			viewAnimator.setDisplayedChild(0);
+	private void updateUI() {
+		boolean activeListeners = false;
+		boolean activeHandlers = false;
+		boolean yellowLight = false;
+
+		// Check for all protocols if listeners are active and attacks have been
+		// recorded
+		// Update protocol lights and connection information.
+		for (String protocol : getResources().getStringArray(R.array.protocols)) {
+			if (isServiceBound()) {
+				// Check if protocol is active
+				if (mService.isRunning(protocol)) {
+					activeListeners = true;
+					int handlerCount = mService.getNumberOfActiveConnections(protocol);
+					// Check if attacks have been recorded in this session.
+					if (handlerCount > 0) {
+						activeHandlers = true;
+						updateProtocolLight(LIGHT_RED, protocol);
+						updateProtocolConnections(handlerCount, protocol);
+					} else {
+						// Check if the bssid of the wireless network has
+						// already
+						// been recorded as infected.
+						HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
+						if (dbh.bssidSeen(protocol, connectionInfo.getString(getString(R.string.connection_info_bssid), null))) {
+							updateProtocolLight(LIGHT_YELLOW, protocol);
+							yellowLight = true;
+						} else {
+							updateProtocolLight(LIGHT_GREEN, protocol);
+						}
+						updateProtocolConnections(0, protocol);
+					}
+				} else {
+					updateProtocolLight(LIGHT_GREY, protocol);
+				}
+			} else {
+				updateProtocolLight(LIGHT_GREY, protocol);
+			}
 		}
-	}
 
-	SimpleOnGestureListener simpleOnGestureListener = new SimpleOnGestureListener() {
-		@Override
-		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
-				float velocityY) {
-			float sensitvity = 50;
-			if ((e1.getX() - e2.getX()) > sensitvity) {
-				swipeRightToLeft();
-			} else if ((e2.getX() - e1.getX()) > sensitvity) {
-				swipeLeftToRight();
+		// Update the big attack indicator.
+		if (activeListeners) {
+			if (activeHandlers) {
+				updateStatusLight(LIGHT_RED);
+			} else {
+				if (yellowLight) {
+					updateStatusLight(LIGHT_YELLOW);
+				} else {
+					updateStatusLight(LIGHT_GREEN);
+				}
 			}
+			((ToggleButton) findViewById(R.id.toggleButtonOnOff)).setChecked(true);
+			findViewById(R.id.checkBoxParanoid).setEnabled(false);
+		} else {
+			updateStatusLight(LIGHT_GREY);
+			((ToggleButton) findViewById(R.id.toggleButtonOnOff)).setChecked(false);
+			findViewById(R.id.checkBoxParanoid).setEnabled(true);
+		}
+	}
 
-			return true;
+	@Override
+	protected void onCreate(Bundle savedInstanceState) {
+		super.onCreate(savedInstanceState);
+		setContentView(R.layout.activity_main);
+		connectionInfo = getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
+
+		// Create dynamic view elements
+		initViewAnimator();
+		initListView();
+		// Initialize Class variables
+		startAndBind();
+	}
+
+	@Override
+	protected void onDestroy() {
+		// Unbind running service
+		if (!mService.hasRunningListeners()) {
+			stopAndUnbind();
 		}
-	};
-	
+		super.onDestroy();
+	}
+
+	@Override
+	protected void onStart() {
+		super.onStart();
+		// Register Broadcast Receiver
+		registerReceiver();
+		// Bind service if running, else check for connection change and delete
+		// sessionData
+		if (isServiceRunning()) {
+			bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
+		}
+		// Update UI
+		updateConnectionInfText();
+	}
+
+	@Override
+	protected void onStop() {
+		// Unregister Broadcast Receiver
+		unregisterReceiver();
+		super.onStop();
+	}
+
 }

+ 95 - 98
src/de/tudarmstadt/informatik/hostage/ui/PlayGroundActivity.java

@@ -1,99 +1,96 @@
-package de.tudarmstadt.informatik.hostage.ui;
-
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Random;
-
-import android.app.Activity;
-import android.content.Intent;
-import android.os.Bundle;
-import android.view.Menu;
-import android.view.View;
-import android.widget.TextView;
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
-import de.tudarmstadt.informatik.hostage.sync.BluetoothSync;
-import de.tudarmstadt.informatik.hostage.sync.NFCSync;
-
-public class PlayGroundActivity extends Activity {
-
-	BluetoothSync bs;
-
-	public void createNetworkData(View view) {
-		Random rnd = new Random();
-		ArrayList<HashMap<String, Object>> fakeNetInfo = new ArrayList<HashMap<String, Object>>();
-		for (int i = 0; i < 25; i++) {
-			HashMap<String, Object> network = new HashMap<String, Object>();
-			network.put(UglyDbHelper.KEY_BSSID, createRandomBSSID());
-			network.put(UglyDbHelper.KEY_SSID,
-					new BigInteger(130, rnd).toString(32));
-			network.put(UglyDbHelper.KEY_LATITUDE, rnd.nextDouble() * 360);
-			network.put(UglyDbHelper.KEY_LONGITUDE, rnd.nextDouble() * 360);
-			network.put(UglyDbHelper.KEY_ACCURACY, rnd.nextFloat());
-			network.put(UglyDbHelper.KEY_TIME, System.currentTimeMillis());
-			fakeNetInfo.add(network);
-		}
-
-		setNetworkInfoText();
-		new UglyDbHelper(this).updateNetworkInformation(fakeNetInfo);
-	}
-
-	@Override
-	public boolean onCreateOptionsMenu(Menu menu) {
-		getMenuInflater().inflate(R.menu.main, menu);
-		return true;
-	}
-
-	public void startNFC(View view) {
-		startActivity(new Intent(this, NFCSync.class));
-	}
-
-	public void syncData(View view) {
-		bs.syncData();
-	}
-
-	private String createRandomBSSID() {
-		Random rnd = new Random();
-		char[] symbols = new char[16];
-		for (int idx = 0; idx < 10; ++idx)
-			symbols[idx] = (char) ('0' + idx);
-		for (int idx = 10; idx < 16; ++idx)
-			symbols[idx] = (char) ('a' + idx - 10);
-
-		char[] buf = new char[17];
-		for (int i = 0; i < 18; i += 3) {
-			buf[i] = symbols[rnd.nextInt(symbols.length)];
-			buf[i + 1] = symbols[rnd.nextInt(symbols.length)];
-			if (i < 15) {
-				buf[i + 2] = ':';
-			}
-		}
-		return new String(buf);
-	}
-
-	private void setNetworkInfoText() {
-		UglyDbHelper dbh = new UglyDbHelper(this);
-		TextView bssids = (TextView) findViewById(R.id.textView1);
-		String text = "";
-		ArrayList<HashMap<String, Object>> netInfo = dbh
-				.getNetworkInformation();
-		for (HashMap<String, Object> network : netInfo) {
-			text = text + (String) network.get(UglyDbHelper.KEY_BSSID) + "\n"
-					+ (String) network.get(UglyDbHelper.KEY_SSID) + "\n"
-					+ network.get(UglyDbHelper.KEY_LATITUDE) + "\n"
-					+ network.get(UglyDbHelper.KEY_LONGITUDE) + "\n"
-					+ network.get(UglyDbHelper.KEY_ACCURACY) + "\n"
-					+ network.get(UglyDbHelper.KEY_TIME) + "\n\n";
-		}
-		bssids.setText(text);
-	}
-
-	@Override
-	protected void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-		setContentView(R.layout.activity_playground);
-		bs = new BluetoothSync(this);
-		setNetworkInfoText();
-	}
+package de.tudarmstadt.informatik.hostage.ui;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Random;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.os.Bundle;
+import android.view.Menu;
+import android.view.View;
+import android.widget.TextView;
+import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+import de.tudarmstadt.informatik.hostage.sync.BluetoothSync;
+import de.tudarmstadt.informatik.hostage.sync.NFCSync;
+
+public class PlayGroundActivity extends Activity {
+
+
+	public void createNetworkData(View view) {
+		Random rnd = new Random();
+		ArrayList<HashMap<String, Object>> fakeNetInfo = new ArrayList<HashMap<String, Object>>();
+		for (int i = 0; i < 25; i++) {
+			HashMap<String, Object> network = new HashMap<String, Object>();
+			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_BSSID, createRandomBSSID());
+			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_SSID, new BigInteger(130, rnd).toString(32));
+			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_LATITUDE, rnd.nextDouble() * 360);
+			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_LONGITUDE, rnd.nextDouble() * 360);
+			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_ACCURACY, rnd.nextFloat());
+			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP, System.currentTimeMillis());
+			fakeNetInfo.add(network);
+		}
+
+		setNetworkInfoText();
+		new HostageDBOpenHelper(this).updateNetworkInformation(fakeNetInfo);
+	}
+
+	@Override
+	public boolean onCreateOptionsMenu(Menu menu) {
+		getMenuInflater().inflate(R.menu.main, menu);
+		return true;
+	}
+
+	public void startNFC(View view) {
+		startActivity(new Intent(this, NFCSync.class));
+	}
+
+	public void syncData(View view) {
+		startActivity(new Intent(this, BluetoothSync.class));
+	}
+
+	private String createRandomBSSID() {
+		Random rnd = new Random();
+		char[] symbols = new char[16];
+		for (int idx = 0; idx < 10; ++idx)
+			symbols[idx] = (char) ('0' + idx);
+		for (int idx = 10; idx < 16; ++idx)
+			symbols[idx] = (char) ('a' + idx - 10);
+
+		char[] buf = new char[17];
+		for (int i = 0; i < 18; i += 3) {
+			buf[i] = symbols[rnd.nextInt(symbols.length)];
+			buf[i + 1] = symbols[rnd.nextInt(symbols.length)];
+			if (i < 15) {
+				buf[i + 2] = ':';
+			}
+		}
+		return new String(buf);
+	}
+
+	private void setNetworkInfoText() {
+		HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
+		TextView bssids = (TextView) findViewById(R.id.textView1);
+		String text = "";
+		ArrayList<HashMap<String, Object>> netInfo = dbh.getNetworkInformation();
+		for (HashMap<String, Object> network : netInfo) {
+			text = text + (String) network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_BSSID) + "\n"
+					+ (String) network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_SSID) + "\n"
+					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_LATITUDE) + "\n"
+					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_LONGITUDE) + "\n"
+					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_ACCURACY) + "\n"
+					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP) + "\n\n";
+		}
+		bssids.setText(text);
+	}
+
+	@Override
+	protected void onCreate(Bundle savedInstanceState) {
+		super.onCreate(savedInstanceState);
+		setContentView(R.layout.activity_playground);
+		setNetworkInfoText();
+	}
 }

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/ui/ViewLogTable.java

@@ -5,7 +5,7 @@ import android.os.Bundle;
 import android.widget.ScrollView;
 import android.widget.TextView;
 import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 
 /**
  * Creates a simple log view. Shows the Information for every attack. The format
@@ -19,7 +19,7 @@ public class ViewLogTable extends Activity {
 	@Override
 	protected void onCreate(Bundle savedInstanceState) {
 		super.onCreate(savedInstanceState);
-		UglyDbHelper dbh = new UglyDbHelper(getBaseContext());
+		HostageDBOpenHelper dbh = new HostageDBOpenHelper(getBaseContext());
 		StringBuffer log = new StringBuffer();
 		// Create a log entry for every attack in the Database
 		for (Record record : dbh.getAllRecords()) {

+ 126 - 163
src/de/tudarmstadt/informatik/hostage/ui2/activity/MainActivity.java

@@ -1,5 +1,8 @@
 package de.tudarmstadt.informatik.hostage.ui2.activity;
 
+import java.util.ArrayList;
+import java.util.HashMap;
+
 import android.app.ActionBar;
 import android.app.Activity;
 import android.app.ActivityManager;
@@ -27,14 +30,7 @@ import android.view.MenuItem;
 import android.view.View;
 import android.widget.AdapterView;
 import android.widget.ListView;
-
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import de.tudarmstadt.informatik.hostage.HoneyHandler;
-import de.tudarmstadt.informatik.hostage.HoneyService;
+import de.tudarmstadt.informatik.hostage.Hostage;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.ui.LogFilter;
 import de.tudarmstadt.informatik.hostage.ui2.adapter.DrawerListAdapter;
@@ -57,16 +53,12 @@ import de.tudarmstadt.informatik.hostage.ui2.model.DrawerListItem;
 public class MainActivity extends Activity {
 	public static volatile Context context;
 
-	public static boolean isRooted = false;
-
-	public static boolean porthackInstalled = false;
-
 	/** singleton instance of the MainActivity **/
 	private static MainActivity sInstance = null;
 
 	public Fragment mDisplayedFragment;
 
-	public HoneyService mHoneyService;
+	public Hostage mHoneyService;
 
 	private DrawerLayout mDrawerLayout;
 
@@ -78,7 +70,7 @@ public class MainActivity extends Activity {
 
 	private CharSequence mTitle;
 
-    private MainMenuItem mSelectedMenuItem = null;
+	private MainMenuItem mSelectedMenuItem = null;
 
 	private ArrayList<DrawerListItem> mDrawerItems;
 
@@ -86,25 +78,26 @@ public class MainActivity extends Activity {
 
 	/**
 	 * Connection to bind the background service
-	 *
+	 * 
 	 * @see HoneyService
 	 */
 	private ServiceConnection mConnection = new ServiceConnection() {
 		/**
 		 * After the service is bound, check which has been clicked and start
 		 * it.
-		 *
-		 * @see android.content.ServiceConnection#onServiceConnected(android.content.ComponentName, android.os.IBinder)
+		 * 
+		 * @see android.content.ServiceConnection#onServiceConnected(android.content.ComponentName,
+		 *      android.os.IBinder)
 		 */
 		@Override
 		public void onServiceConnected(ComponentName name, IBinder service) {
-			mHoneyService = ((HoneyService.LocalBinder) service).getService();
+			mHoneyService = ((Hostage.LocalBinder) service).getService();
 			mServiceBound = true;
 		}
 
 		/**
 		 * After the service is unbound, delete reference.
-		 *
+		 * 
 		 * @see android.content.ServiceConnection#onServiceDisconnected(android.content.ComponentName)
 		 */
 		@Override
@@ -121,28 +114,35 @@ public class MainActivity extends Activity {
 
 	/**
 	 * Retrieve the singleton latest instance of the activity
+	 * 
 	 * @return MainActivity - the singleton instance
 	 */
-	public static MainActivity getInstance(){
-		assert(sInstance != null);
+	public static MainActivity getInstance() {
+		assert (sInstance != null);
 		return sInstance;
 	}
 
-	public static Context getContext(){
+	public static Context getContext() {
 		return MainActivity.context;
 	}
 
 	@Override
-	public void onStart(){
+	public void onStart() {
 		super.onStart();
 
 		registerReceiver();
 
-		if(isServiceRunning()){
+		if (isServiceRunning()) {
 			this.bindService();
 		}
 	}
 
+	@Override
+	public void onStop() {
+		this.unbindService();
+		super.onStop();
+	}
+
 	@Override
 	protected void onCreate(Bundle savedInstanceState) {
 		super.onCreate(savedInstanceState);
@@ -156,14 +156,12 @@ public class MainActivity extends Activity {
 		ThreatIndicatorGLRenderer.assets = getAssets();
 		ThreatIndicatorGLRenderer.setThreatLevel(ThreatIndicatorGLRenderer.ThreatLevel.NOT_MONITORING);
 		// set background color
-		TypedArray arr = getTheme().obtainStyledAttributes(
-				new int[] { android.R.color.background_light });
+		TypedArray arr = getTheme().obtainStyledAttributes(new int[] { android.R.color.background_light });
 		ThreatIndicatorGLRenderer.setBackgroundColor(arr.getColor(0, 0xFFFFFF));
 		arr.recycle();
 
 		ActionBar actionBar = getActionBar();
-		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE
-				| ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP);
+		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP);
 
 		mTitle = mDrawerTitle = getTitle();
 		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
@@ -175,13 +173,9 @@ public class MainActivity extends Activity {
 		mDrawerItems.add(new DrawerListItem(R.string.drawer_records, R.drawable.ic_menu_records));
 		mDrawerItems.add(new DrawerListItem(R.string.drawer_statistics, R.drawable.ic_menu_stats));
 		mDrawerItems.add(new DrawerListItem(R.string.drawer_services, R.drawable.ic_menu_set_as));
-		mDrawerItems.add(
-				new DrawerListItem(R.string.drawer_profile_manager, R.drawable.ic_menu_allfriends));
-		mDrawerItems.add(
-				new DrawerListItem(R.string.drawer_settings, R.drawable.ic_menu_preferences));
-		mDrawerItems.add(
-				new DrawerListItem(R.string.drawer_app_info, R.drawable.ic_menu_info_details));
-
+		mDrawerItems.add(new DrawerListItem(R.string.drawer_profile_manager, R.drawable.ic_menu_allfriends));
+		mDrawerItems.add(new DrawerListItem(R.string.drawer_settings, R.drawable.ic_menu_preferences));
+		mDrawerItems.add(new DrawerListItem(R.string.drawer_app_info, R.drawable.ic_menu_info_details));
 
 		DrawerListAdapter listAdapter = new DrawerListAdapter(this, mDrawerItems);
 
@@ -192,26 +186,29 @@ public class MainActivity extends Activity {
 		getActionBar().setHomeButtonEnabled(true);
 		getActionBar().setDisplayShowHomeEnabled(true);
 
-		mDrawerToggle = new ActionBarDrawerToggle(
-				this,                  /* host Activity */
-				mDrawerLayout,         /* DrawerLayout object */
-				R.drawable.ic_navigation_drawer,  /* nav drawer image to replace 'Up' caret */
-				R.string.drawer_open,  /* "open drawer" description for accessibility */
-				R.string.drawer_close  /* "close drawer" description for accessibility */
+		mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
+		mDrawerLayout, /* DrawerLayout object */
+		R.drawable.ic_navigation_drawer, /*
+										 * nav drawer image to replace 'Up'
+										 * caret
+										 */
+		R.string.drawer_open, /* "open drawer" description for accessibility */
+		R.string.drawer_close /* "close drawer" description for accessibility */
 		) {
 			public void onDrawerClosed(View view) {
 				getActionBar().setTitle(mTitle);
-				invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
+				invalidateOptionsMenu(); // creates call to
+											// onPrepareOptionsMenu()
 			}
 
 			public void onDrawerOpened(View drawerView) {
 				getActionBar().setTitle(mDrawerTitle);
-				invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
+				invalidateOptionsMenu(); // creates call to
+											// onPrepareOptionsMenu()
 			}
 		};
 		mDrawerLayout.setDrawerListener(mDrawerToggle);
 
-		checkRootAndPorthack();
 		startAndBind();
 
 		if (savedInstanceState == null) {
@@ -221,8 +218,7 @@ public class MainActivity extends Activity {
 	}
 
 	private void registerReceiver() {
-		LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
-				new IntentFilter(getString(R.string.broadcast)));
+		LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter(getString(R.string.broadcast)));
 	}
 
 	private void unregisterReceiver() {
@@ -237,20 +233,21 @@ public class MainActivity extends Activity {
 			String sender = extras.getString("SENDER");
 			String[] values = extras.getStringArray("VALUES");
 
-			if(sender.equals(HoneyHandler.class.getName()) && values[0].equals(getString(R.string.broadcast_started))) {
+			if (sender.equals(Hostage.class.getName()) && values[0].equals(getString(R.string.broadcast_started))) {
 				mAttacksOnProtocol.put(values[1], true);
 			}
 		}
 	};
 
-	public boolean hasProtocolAttacks(String protocol){
-		if(!mAttacksOnProtocol.containsKey(protocol)) return false;
+	public boolean hasProtocolAttacks(String protocol) {
+		if (!mAttacksOnProtocol.containsKey(protocol))
+			return false;
 
 		return mAttacksOnProtocol.get(protocol);
 	}
 
 	public void startAndBind() {
-		if(!isServiceRunning()){
+		if (!isServiceRunning()) {
 			startService(getServiceIntent());
 		}
 
@@ -258,7 +255,7 @@ public class MainActivity extends Activity {
 	}
 
 	public void stopAndUnbind() {
-		if(mHoneyService != null){
+		if (mHoneyService != null) {
 			unbindService();
 		}
 
@@ -268,7 +265,7 @@ public class MainActivity extends Activity {
 	public void unbindService() {
 		try {
 			unbindService(mConnection);
-		} catch(IllegalArgumentException ex){
+		} catch (IllegalArgumentException ex) {
 			// somehow already unbound.
 		}
 	}
@@ -276,7 +273,7 @@ public class MainActivity extends Activity {
 	public void bindService() {
 		mAttacksOnProtocol.clear();
 		bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
-		//mServiceBound = true;
+		// mServiceBound = true;
 	}
 
 	@Override
@@ -286,19 +283,19 @@ public class MainActivity extends Activity {
 		unregisterReceiver();
 
 		// Unbind running service
-		if(!mHoneyService.hasRunningListeners()){
+		if (!mHoneyService.hasRunningListeners()) {
 			stopAndUnbind();
 		}
 	}
 
 	@Override
-	protected void onResume(){
+	protected void onResume() {
 		super.onResume();
 
 		String action = getIntent().getAction();
 
-		if(action != null && action.equals("SHOW_HOME")){
-			if(this.mDisplayedFragment != null && !this.mDisplayedFragment.getClass().equals(HomeFragment.class)){
+		if (action != null && action.equals("SHOW_HOME")) {
+			if (this.mDisplayedFragment != null && !this.mDisplayedFragment.getClass().equals(HomeFragment.class)) {
 				getFragmentManager().popBackStackImmediate(HomeFragment.class.getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
 				displayView(MainMenuItem.HOME.getValue());
 
@@ -314,9 +311,9 @@ public class MainActivity extends Activity {
 			return true;
 		}
 
-		if(item.getItemId() == android.R.id.home){
-			if(!mDrawerToggle.isDrawerIndicatorEnabled()){
-				if(!(this.mDisplayedFragment instanceof UpNavigatibleFragment)) {
+		if (item.getItemId() == android.R.id.home) {
+			if (!mDrawerToggle.isDrawerIndicatorEnabled()) {
+				if (!(this.mDisplayedFragment instanceof UpNavigatibleFragment)) {
 					mDrawerToggle.setDrawerIndicatorEnabled(true);
 					return true;
 				}
@@ -326,19 +323,19 @@ public class MainActivity extends Activity {
 				getFragmentManager().popBackStackImmediate(upNav.getUpFragment().getName(), 0);
 				this.mDisplayedFragment = getFragmentManager().findFragmentById(R.id.content_frame);
 				configureFragment();
-				/*Fragment frag = null;
-
-				try{
-					frag = (Fragment) upNav.getUpFragment().newInstance();
-				} catch (InstantiationException e) {
-					Log.i(null, "Could not create new instance of fragment");
-				} catch (IllegalAccessException e) {
-					Log.i(null, "Could not create new instance of fragment");
-				}
-
-				if(frag != null) this.injectFragment(frag);*/
-
-				if(!(this.mDisplayedFragment instanceof UpNavigatibleFragment) || !((UpNavigatibleFragment) this.mDisplayedFragment).isUpNavigatible()){
+				/*
+				 * Fragment frag = null;
+				 * 
+				 * try{ frag = (Fragment) upNav.getUpFragment().newInstance(); }
+				 * catch (InstantiationException e) { Log.i(null,
+				 * "Could not create new instance of fragment"); } catch
+				 * (IllegalAccessException e) { Log.i(null,
+				 * "Could not create new instance of fragment"); }
+				 * 
+				 * if(frag != null) this.injectFragment(frag);
+				 */
+
+				if (!(this.mDisplayedFragment instanceof UpNavigatibleFragment) || !((UpNavigatibleFragment) this.mDisplayedFragment).isUpNavigatible()) {
 					mDrawerToggle.setDrawerIndicatorEnabled(true);
 				} else {
 					mDrawerToggle.setDrawerIndicatorEnabled(false);
@@ -380,19 +377,19 @@ public class MainActivity extends Activity {
 		return this.mDisplayedFragment;
 	}
 
-	public void setDrawerIndicatorEnabled(boolean val){
+	public void setDrawerIndicatorEnabled(boolean val) {
 		mDrawerToggle.setDrawerIndicatorEnabled(val);
 	}
 
 	public void displayView(int position) {
 		MainMenuItem menuItemPosition = MainMenuItem.create(position);
 
-		if(this.mDisplayedFragment != null && this.mDisplayedFragment.getClass() == menuItemPosition.getKlass()) {
+		if (this.mDisplayedFragment != null && this.mDisplayedFragment.getClass() == menuItemPosition.getKlass()) {
 			mDrawerLayout.closeDrawer(mDrawerList);
 			return;
 		}
 
-        Fragment fragment = null;
+		Fragment fragment = null;
 
 		try {
 			fragment = (Fragment) menuItemPosition.getKlass().newInstance();
@@ -403,29 +400,30 @@ public class MainActivity extends Activity {
 		}
 
 		if (fragment != null) {
+			getFragmentManager().popBackStackImmediate(HomeFragment.class.getName(), 0);
 			// update selected item and title, then close the drawer if needed
-            injectFragment(fragment);//, false, menuItemPosition);
+			injectFragment(fragment);// , false, menuItemPosition);
 
-		    mDrawerList.setItemChecked(position, true);
-		    mDrawerList.setSelection(position);
-		    setTitle(mDrawerItems.get(position).text);
-        }
+			mDrawerList.setItemChecked(position, true);
+			mDrawerList.setSelection(position);
+			setTitle(mDrawerItems.get(position).text);
+		}
 
 		mDrawerLayout.closeDrawer(mDrawerList);
 	}
 
-	public void injectFragment(Fragment fragment, boolean enableBack){
+	public void injectFragment(Fragment fragment, boolean enableBack) {
 		injectFragment(fragment);
 	}
 
-	public void injectFragment(Fragment fragment){
+	public void injectFragment(Fragment fragment) {
 		// set orientation fixed to portrait in home fragment
-		if(fragment instanceof UpNavigatibleFragment){
+		if (fragment instanceof UpNavigatibleFragment) {
 			UpNavigatibleFragment upFrag = (UpNavigatibleFragment) fragment;
-			if(upFrag.getUpFragment() == null){
+			if (upFrag.getUpFragment() == null) {
 				upFrag.setUpFragment(this.mDisplayedFragment.getClass());
 			}
-			if(upFrag.isUpNavigatible()){
+			if (upFrag.isUpNavigatible()) {
 				mDrawerToggle.setDrawerIndicatorEnabled(false);
 			}
 		}
@@ -444,21 +442,21 @@ public class MainActivity extends Activity {
 		this.mDisplayedFragment = fragment;
 	}
 
-	private void configureFragment(){
+	private void configureFragment() {
 		configureFragment(this.mDisplayedFragment);
 	}
 
-	private void configureFragment(Fragment fragment){
-		if(fragment == null) return;
+	private void configureFragment(Fragment fragment) {
+		if (fragment == null)
+			return;
 
-		if(fragment instanceof HomeFragment || fragment instanceof AboutFragment){
+		if (fragment instanceof HomeFragment || fragment instanceof AboutFragment) {
 			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT | ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
 		} else {
 			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
 		}
 
-		if(fragment instanceof StatisticsFragment ||
-				fragment instanceof RecordOverviewFragment){
+		if (fragment instanceof StatisticsFragment || fragment instanceof RecordOverviewFragment) {
 
 			Intent intent = this.getIntent();
 			intent.removeExtra(LogFilter.LOG_FILTER_INTENT_KEY);
@@ -467,14 +465,14 @@ public class MainActivity extends Activity {
 
 	@Override
 	public void onBackPressed() {
-		if(getFragmentManager().getBackStackEntryCount() == 1) {
+		if (getFragmentManager().getBackStackEntryCount() == 1) {
 			finish();
 		} else {
 			super.onBackPressed();
 			this.mDisplayedFragment = getFragmentManager().findFragmentById(R.id.content_frame);
 			configureFragment();
 
-			if(!(this.mDisplayedFragment instanceof UpNavigatibleFragment) || !((UpNavigatibleFragment) this.mDisplayedFragment).isUpNavigatible()){
+			if (!(this.mDisplayedFragment instanceof UpNavigatibleFragment) || !((UpNavigatibleFragment) this.mDisplayedFragment).isUpNavigatible()) {
 				mDrawerToggle.setDrawerIndicatorEnabled(true);
 			} else {
 				mDrawerToggle.setDrawerIndicatorEnabled(false);
@@ -484,16 +482,16 @@ public class MainActivity extends Activity {
 
 	@Override
 	public boolean onKeyDown(int keycode, KeyEvent e) {
-		switch(keycode) {
-			case KeyEvent.KEYCODE_MENU:
-				if(this.mDrawerToggle.isDrawerIndicatorEnabled()){
-					if(this.mDrawerLayout.isDrawerOpen(Gravity.LEFT)){
-						this.mDrawerLayout.closeDrawer(Gravity.LEFT);
-						return true;
-					}
-					this.mDrawerLayout.openDrawer(Gravity.LEFT);
+		switch (keycode) {
+		case KeyEvent.KEYCODE_MENU:
+			if (this.mDrawerToggle.isDrawerIndicatorEnabled()) {
+				if (this.mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
+					this.mDrawerLayout.closeDrawer(Gravity.LEFT);
+					return true;
 				}
-				return true;
+				this.mDrawerLayout.openDrawer(Gravity.LEFT);
+			}
+			return true;
 		}
 
 		return super.onKeyDown(keycode, e);
@@ -502,7 +500,7 @@ public class MainActivity extends Activity {
 	public static void displayBackStack(FragmentManager fm) {
 		int count = fm.getBackStackEntryCount();
 		Log.d("Backstack log", "There are " + count + " entries");
-		for(int i = 0; i<count; i++) {
+		for (int i = 0; i < count; i++) {
 			// Display Backstack-entry data like
 			String name = fm.getBackStackEntryAt(i).getName();
 			Log.d("Backstack log", "entry " + i + ": " + name);
@@ -510,61 +508,25 @@ public class MainActivity extends Activity {
 	}
 
 	public Intent getServiceIntent() {
-		return new Intent(this, HoneyService.class);
+		return new Intent(this, Hostage.class);
 	}
 
 	public Fragment getDisplayedFragment() {
 		return this.mDisplayedFragment;
 	}
 
-	/**
-	 * Checks if the phone ist rooted and if porthack is installed. Sets flags
-	 * {@link this.isRooted} and {@link this.porthackInstalled}
-	 */
-	private void checkRootAndPorthack() {
-		isRooted = false;
-		porthackInstalled = false;
-		Process p;
-		try {
-			String found = "Found";
-			String notFound = "Not found";
-			String command = "[ -f /data/local/p ] && echo " + found
-					+ " || echo " + notFound;
-			p = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
-			BufferedReader in = new BufferedReader(new InputStreamReader(
-					p.getInputStream()));
-			/*
-			 * int av = byte[] b = new byte[av]; if (av != 0) { in.read(b); }
-			 */
-			String echoResponse = in.readLine();
-			Log.i("MainAc", echoResponse);
-			if (echoResponse.equals(found)) {
-				isRooted = true;
-				porthackInstalled = true;
-			} else if (echoResponse.equals(notFound)) {
-				isRooted = true;
-			}
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-		Log.i("MainAc", "Rooted: " + isRooted + " Porthack: "
-				+ porthackInstalled);
-	}
-
-	public HoneyService getHoneyService(){
+	public Hostage getHostageService() {
 		return this.mHoneyService;
 	}
 
-	public boolean isServiceBound(){
+	public boolean isServiceBound() {
 		return this.mServiceBound;
 	}
 
 	public boolean isServiceRunning() {
 		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
-		for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(
-				Integer.MAX_VALUE)) {
-			if (service.service.getClassName().equals(
-					HoneyService.class.getName())) {
+		for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
+			if (service.service.getClassName().equals(Hostage.class.getName())) {
 				return true;
 			}
 		}
@@ -572,36 +534,37 @@ public class MainActivity extends Activity {
 	}
 
 	public enum MainMenuItem {
-        HOME(0, HomeFragment.class),
-        THREAT_MAP(1, ThreatMapFragment.class),
-        RECORDS(2, RecordOverviewFragment.class),
+		HOME(0, HomeFragment.class),
+		THREAT_MAP(1, ThreatMapFragment.class),
+		RECORDS(2, RecordOverviewFragment.class),
 		STATISTICS(3, StatisticsFragment.class),
-        SERVICES(4, ServicesFragment.class),
-        PROFILE_MANAGER(5, ProfileManagerFragment.class),
-        SETTINGS(6, SettingsFragment.class),
-        APPLICATION_INFO(7, AboutFragment.class);
+		SERVICES(4, ServicesFragment.class),
+		PROFILE_MANAGER(5, ProfileManagerFragment.class),
+		SETTINGS(6, SettingsFragment.class),
+		APPLICATION_INFO(7, AboutFragment.class);
 
-        private int value;
+		private int value;
 		private Class<?> klass;
 
-        private MainMenuItem(int value, Class<?> klass) {
-            this.value = value;
-            this.klass = klass;
-        }
+		private MainMenuItem(int value, Class<?> klass) {
+			this.value = value;
+			this.klass = klass;
+		}
 
-        static public MainMenuItem create(int value){
-            if (value < 0 || value  >= MainMenuItem.values().length) return MainMenuItem.HOME;
-            return  MainMenuItem.values()[value];
-        }
+		static public MainMenuItem create(int value) {
+			if (value < 0 || value >= MainMenuItem.values().length)
+				return MainMenuItem.HOME;
+			return MainMenuItem.values()[value];
+		}
 
 		public int getValue() {
 			return value;
 		}
 
-		public Class<?> getKlass(){
+		public Class<?> getKlass() {
 			return this.klass;
 		}
-    }
+	}
 
 	private class DrawerItemClickListener implements ListView.OnItemClickListener {
 		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

+ 118 - 114
src/de/tudarmstadt/informatik/hostage/ui2/adapter/ProfileManagerListAdapter.java

@@ -19,7 +19,7 @@ import java.util.LinkedList;
 import java.util.List;
 
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.dao.ProfileManager;
+import de.tudarmstadt.informatik.hostage.persistence.ProfileManager;
 import de.tudarmstadt.informatik.hostage.model.Profile;
 import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
 import de.tudarmstadt.informatik.hostage.ui2.activity.ProfileEditActivity;
@@ -64,123 +64,127 @@ public class ProfileManagerListAdapter extends ArrayAdapter<Profile> {
 
 	    final Profile item = values.get(position);
 
-	    if(rowView == null){
-		    rowView = inflater.inflate(R.layout.profile_manager_list_item, parent, false);
-
-		    holder = new ViewHolder();
-		    holder.labelView = (TextView) rowView.findViewById(R.id.profile_manager_item_label);
-		    holder.textView = (TextView) rowView.findViewById(R.id.profile_manager_item_text);
-		    holder.imageSelected = (ImageView) rowView.findViewById(R.id.profile_manager_item_activated);
-		    holder.itemIcon = (ImageView) rowView.findViewById(R.id.profile_manager_item_image);
-		    holder.buttonEdit = (ImageButton) rowView.findViewById(R.id.profile_manager_item_button_edit);
-		    holder.buttonDelete = (ImageButton) rowView.findViewById(R.id.profile_manager_item_button_delete);
-			holder.seperator = rowView.findViewById(R.id.profile_manager_item_seperator);
-			holder.badgesContainer = (FlowLayout) rowView.findViewById(R.id.badges_container);
-
-		    rowView.setTag(holder);
+	    if(item.mShowTooltip){
+		    rowView = inflater.inflate(R.layout.profile_manager_list_item_help, parent, false);
 	    } else {
-		    holder = (ViewHolder) rowView.getTag();
-	    }
-
-	    ((SwipeListView)parent).recycle(rowView, position);
-
-	    holder.textView.setText(item.mText);
-	    holder.labelView.setText(item.mLabel);
-
-	    if(item.getIconBitmap() != null){
-	        //Bitmap bitmap = Bitmap.createScaledBitmap(item.getIconBitmap(), 32, 32, true);
-	        holder.itemIcon.setImageBitmap(item.getIconBitmap());
-	    } else {
-		    holder.itemIcon.setImageBitmap(BitmapFactory.decodeResource(MainActivity.context.getResources(), R.drawable.ic_launcher));
-	    }
-
-		holder.buttonEdit.setOnClickListener(new View.OnClickListener() {
-			@Override
-			public void onClick(View v) {
-				Intent intent = new Intent(context, ProfileEditActivity.class);
-				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-				intent.putExtra("profile_id", item.mId);
-				//intent.putExtra("profile", item);
-				context.startActivity(intent);
-			}
-		});
-
-		holder.buttonDelete.setOnClickListener(new View.OnClickListener() {
-			@Override
-			public void onClick(View v) {
-				new AlertDialog.Builder(context)
-						.setTitle(R.string.delete_profile)
-						.setMessage(R.string.really_want_delete_profiel)
-						.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
-							@Override
-							public void onClick(DialogInterface dialog, int which) {
-
-							}
-						})
-						.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
-							public void onClick(DialogInterface dialog, int which) {
-								ProfileManager profileManager = ProfileManager.getInstance();
-
-								profileManager.deleteProfile(item);
-								profileManager.getProfileListAdapter().notifyDataSetChanged();
-								list.closeOpenedItems();
-							}
-						})
-						.setIcon(android.R.drawable.ic_dialog_alert)
-						.show();
-			}
-		});
-
-	    holder.badgesContainer.removeAllViews();
-	    boolean hasProtocols = false;
-
-	    List<String> profiles = new LinkedList<String>(item.getActiveProtocols());
-
-	    if(item.mGhostActive){
-		    profiles.add("GHOST");
-	    }
-
-	    for(String protocol: profiles){
-		    hasProtocols = true;
-			TextView textView = new TextView(new ContextThemeWrapper(context, R.style.ProfileManagerListBadge));
-		    textView.setText(protocol);
-		    holder.badgesContainer.addView(textView);
-	    }
+		    if (rowView == null || rowView.getTag() == null) {
+			    rowView = inflater.inflate(R.layout.profile_manager_list_item, parent, false);
+
+			    holder = new ViewHolder();
+			    holder.labelView = (TextView) rowView.findViewById(R.id.profile_manager_item_label);
+			    holder.textView = (TextView) rowView.findViewById(R.id.profile_manager_item_text);
+			    holder.imageSelected = (ImageView) rowView.findViewById(R.id.profile_manager_item_activated);
+			    holder.itemIcon = (ImageView) rowView.findViewById(R.id.profile_manager_item_image);
+			    holder.buttonEdit = (ImageButton) rowView.findViewById(R.id.profile_manager_item_button_edit);
+			    holder.buttonDelete = (ImageButton) rowView.findViewById(R.id.profile_manager_item_button_delete);
+			    holder.seperator = rowView.findViewById(R.id.profile_manager_item_seperator);
+			    holder.badgesContainer = (FlowLayout) rowView.findViewById(R.id.badges_container);
+
+			    rowView.setTag(holder);
+		    } else {
+			    holder = (ViewHolder) rowView.getTag();
+		    }
+
+		    ((SwipeListView) parent).recycle(rowView, position);
+
+		    holder.textView.setText(item.mText);
+		    holder.labelView.setText(item.mLabel);
+
+		    if (item.getIconBitmap() != null) {
+			    //Bitmap bitmap = Bitmap.createScaledBitmap(item.getIconBitmap(), 32, 32, true);
+			    holder.itemIcon.setImageBitmap(item.getIconBitmap());
+		    } else {
+			    holder.itemIcon.setImageBitmap(BitmapFactory.decodeResource(MainActivity.context.getResources(), R.drawable.ic_launcher));
+		    }
+
+		    holder.buttonEdit.setOnClickListener(new View.OnClickListener() {
+			    @Override
+			    public void onClick(View v) {
+				    Intent intent = new Intent(context, ProfileEditActivity.class);
+				    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+				    intent.putExtra("profile_id", item.mId);
+				    //intent.putExtra("profile", item);
+				    context.startActivity(intent);
+			    }
+		    });
+
+		    holder.buttonDelete.setOnClickListener(new View.OnClickListener() {
+			    @Override
+			    public void onClick(View v) {
+				    new AlertDialog.Builder(context)
+						    .setTitle(R.string.delete_profile)
+						    .setMessage(R.string.really_want_delete_profiel)
+						    .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
+							    @Override
+							    public void onClick(DialogInterface dialog, int which) {
+
+							    }
+						    })
+						    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
+							    public void onClick(DialogInterface dialog, int which) {
+								    ProfileManager profileManager = ProfileManager.getInstance();
+
+								    profileManager.deleteProfile(item);
+								    profileManager.getProfileListAdapter().notifyDataSetChanged();
+								    list.closeOpenedItems();
+							    }
+						    })
+						    .setIcon(android.R.drawable.ic_dialog_alert)
+						    .show();
+			    }
+		    });
+
+		    holder.badgesContainer.removeAllViews();
+		    boolean hasProtocols = false;
+
+		    List<String> profiles = new LinkedList<String>(item.getActiveProtocols());
+
+		    if (item.mGhostActive) {
+			    profiles.add("GHOST");
+		    }
+
+		    for (String protocol : profiles) {
+			    hasProtocols = true;
+			    TextView textView = new TextView(new ContextThemeWrapper(context, R.style.ProfileManagerListBadge));
+			    textView.setText(protocol);
+			    holder.badgesContainer.addView(textView);
+		    }
+
+		    if (!hasProtocols) {
+			    holder.badgesContainer.setVisibility(View.INVISIBLE);
+		    } else {
+			    holder.badgesContainer.setVisibility(View.VISIBLE);
+		    }
+
+		    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) holder.textView.getLayoutParams();
+
+		    if (!item.mActivated) {
+			    lp.setMargins(0, 0, 0, 0);
+
+			    holder.textView.setLayoutParams(lp);
+
+			    holder.imageSelected.setVisibility(View.GONE);
+		    } else {
+				/*float d = context.getResources().getDisplayMetrics().density;
+				int dm = (int)(20 * d);
+
+				lp.setMargins(0,0,dm,0);
+
+				holder.textView.setLayoutParams(lp);*/
+
+			    holder.imageSelected.setVisibility(View.VISIBLE);
+		    }
+
+		    if (!item.isEditable()) {
+			    holder.buttonDelete.setVisibility(View.GONE);
+			    holder.seperator.setVisibility(View.GONE);
+		    } else {
+			    holder.buttonDelete.setVisibility(View.VISIBLE);
+			    holder.seperator.setVisibility(View.VISIBLE);
+		    }
 
-	    if(!hasProtocols){
-		    holder.badgesContainer.setVisibility(View.INVISIBLE);
-	    } else {
-		    holder.badgesContainer.setVisibility(View.VISIBLE);
 	    }
 
-		RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) holder.textView.getLayoutParams();
-
-        if(!item.mActivated){
-            lp.setMargins(0, 0, 0, 0);
-
-	        holder.textView.setLayoutParams(lp);
-
-	        holder.imageSelected.setVisibility(View.GONE);
-        } else {
-			/*float d = context.getResources().getDisplayMetrics().density;
-			int dm = (int)(20 * d);
-
-			lp.setMargins(0,0,dm,0);
-
-			holder.textView.setLayoutParams(lp);*/
-
-			holder.imageSelected.setVisibility(View.VISIBLE);
-		}
-
-
-		if(!item.isEditable()){
-			holder.buttonDelete.setVisibility(View.GONE);
-			holder.seperator.setVisibility(View.GONE);
-		} else {
-			holder.buttonDelete.setVisibility(View.VISIBLE);
-			holder.seperator.setVisibility(View.VISIBLE);
-		}
-
         return rowView;
     }
 

+ 9 - 12
src/de/tudarmstadt/informatik/hostage/ui2/adapter/ServicesListAdapter.java

@@ -1,5 +1,6 @@
 package de.tudarmstadt.informatik.hostage.ui2.adapter;
 
+import java.util.List;
 
 import android.app.AlertDialog;
 import android.content.Context;
@@ -12,9 +13,6 @@ import android.widget.ArrayAdapter;
 import android.widget.CompoundButton;
 import android.widget.Switch;
 import android.widget.TextView;
-
-import java.util.List;
-
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
@@ -26,7 +24,6 @@ import de.tudarmstadt.informatik.hostage.ui2.model.ServicesListItem;
  * a list adapter for loading switches and service information asynchronously
  */
 public class ServicesListAdapter extends ArrayAdapter<ServicesListItem> {
-
     private final Context context;
     private final List<ServicesListItem> values;
     int sdk = Build.VERSION.SDK_INT;
@@ -120,20 +117,20 @@ public class ServicesListAdapter extends ArrayAdapter<ServicesListItem> {
                         } else {
                             //check if switch is set to ON and start the concrete listener for the protocol
                             if (isChecked) {
-                                if (!MainActivity.getInstance().getHoneyService().isRunning(item.protocol)) {
-                                    MainActivity.getInstance().getHoneyService().startListener(item.protocol);
+                                if (!MainActivity.getInstance().getHostageService().isRunning(item.protocol)) {
+                                    MainActivity.getInstance().getHostageService().startListener(item.protocol);
 
                                     //set the main switch to null, so that he won't react and starts all protocols
                                     mServicesSwitch.setOnCheckedChangeListener(null);
                                     mServicesSwitch.setChecked(true);
                                     mServicesSwitch.setOnCheckedChangeListener(mListener);
                                     buttonView.setChecked(true);
-                                } else if (MainActivity.getInstance().getHoneyService().isRunning(item.protocol)) {
+                                } else if (MainActivity.getInstance().getHostageService().isRunning(item.protocol)) {
                                     buttonView.setChecked(true);
                                 }
                             } else {
-                                if (MainActivity.getInstance().getHoneyService().isRunning(item.protocol)) {
-                                    MainActivity.getInstance().getHoneyService().stopListener(item.protocol);
+                                if (MainActivity.getInstance().getHostageService().isRunning(item.protocol)) {
+                                    MainActivity.getInstance().getHostageService().stopListener(item.protocol);
                                 }
                                 buttonView.setChecked(false);
                             }
@@ -151,9 +148,9 @@ public class ServicesListAdapter extends ArrayAdapter<ServicesListItem> {
      * @param holder ViewHolder which represents the item in the View
      */
     private void updateStatus(ServicesListItem item, ViewHolder holder) {
-        if (MainActivity.getInstance().getHoneyService().isRunning(item.protocol)) {
+        if (MainActivity.getInstance().getHostageService().isRunning(item.protocol)) {
             holder.activated.setChecked(true);
-            if (!MainActivity.getInstance().getHoneyService().hasProtocolActiveAttacks(item.protocol)) {
+            if (!MainActivity.getInstance().getHostageService().hasProtocolActiveAttacks(item.protocol)) {
                 if (item.attacks > 0) {
                     setBackground(holder, R.drawable.services_circle_yellow);
                 } else {
@@ -161,7 +158,7 @@ public class ServicesListAdapter extends ArrayAdapter<ServicesListItem> {
                 }
 
             } else {
-                if (MainActivity.getInstance().getHoneyService().hasProtocolActiveAttacks(item.protocol)) {
+                if (MainActivity.getInstance().getHostageService().hasProtocolActiveAttacks(item.protocol)) {
                     setBackground(holder, R.drawable.services_circle_red);
                 }
             }

+ 230 - 215
src/de/tudarmstadt/informatik/hostage/ui2/fragment/HomeFragment.java

@@ -1,4 +1,8 @@
 package de.tudarmstadt.informatik.hostage.ui2.fragment;
+
+import java.util.ArrayList;
+
+import android.annotation.SuppressLint;
 import android.app.Activity;
 import android.app.AlertDialog;
 import android.app.Fragment;
@@ -12,22 +16,24 @@ import android.content.SharedPreferences;
 import android.os.Bundle;
 import android.support.v4.content.LocalBroadcastManager;
 import android.view.LayoutInflater;
+import android.view.Menu;
+import android.view.MenuInflater;
+import android.view.MenuItem;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.CompoundButton;
 import android.widget.ImageView;
 import android.widget.Switch;
 import android.widget.TextView;
-
-import java.util.ArrayList;
-
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-import de.tudarmstadt.informatik.hostage.dao.ProfileManager;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
+import de.tudarmstadt.informatik.hostage.persistence.ProfileManager;
+import de.tudarmstadt.informatik.hostage.deprecated.UglyDbHelper;
 import de.tudarmstadt.informatik.hostage.model.Profile;
+import de.tudarmstadt.informatik.hostage.sync.BluetoothSync;
 import de.tudarmstadt.informatik.hostage.ui.LogFilter;
 import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui2.activity.ProfileEditActivity;
 import de.tudarmstadt.informatik.hostage.ui2.fragment.opengl.ThreatIndicatorGLRenderer;
 
 /**
@@ -35,7 +41,6 @@ import de.tudarmstadt.informatik.hostage.ui2.fragment.opengl.ThreatIndicatorGLRe
  * @created 13.01.14 19:06
  */
 
-
 public class HomeFragment extends Fragment {
 	private Switch mHomeSwitchConnection;
 	private TextView mHomeTextName;
@@ -46,85 +51,85 @@ public class HomeFragment extends Fragment {
 	private ImageView mHomeProfileImage;
 	private ImageView mHomeConnectionInfoButton;
 
-	private View rootView;
+	private View mRootView;
 	private BroadcastReceiver mReceiver;
 
-	private CompoundButton.OnCheckedChangeListener switchChangeListener = null;
+	private CompoundButton.OnCheckedChangeListener mSwitchChangeListener = null;
 
-	private int defaultTextColor;
+	private int mDefaultTextColor;
 	private ProfileManager mProfileManager;
 
 	private SharedPreferences mConnectionInfo;
-	private UglyDbHelper dbh;
+	private UglyDbHelper mDbHelper;
 
-	private static ThreatIndicatorGLRenderer.ThreatLevel THREAT_LEVEL = ThreatIndicatorGLRenderer.ThreatLevel.NO_THREAT;
 	private boolean mReceiverRegistered;
 
 	private void assignViews() {
-		mHomeSwitchConnection = (Switch) rootView.findViewById(R.id.home_switch_connection);
-		mHomeTextName = (TextView) rootView.findViewById(R.id.home_text_name);
-		mHomeTextSecurity = (TextView) rootView.findViewById(R.id.home_text_security);
-		mHomeTextAttacks = (TextView) rootView.findViewById(R.id.home_text_attacks);
-		mHomeTextProfile = (TextView) rootView.findViewById(R.id.home_text_profile);
-		mHomeTextProfileHeader = (TextView) rootView.findViewById(R.id.home_text_profile_header);
-		mHomeProfileImage = (ImageView) rootView.findViewById(R.id.home_image_profile);
-		mHomeConnectionInfoButton = (ImageView) rootView.findViewById(R.id.home_button_connection_info);
+		mHomeSwitchConnection = (Switch) mRootView.findViewById(R.id.home_switch_connection);
+		mHomeTextName = (TextView) mRootView.findViewById(R.id.home_text_name);
+		mHomeTextSecurity = (TextView) mRootView.findViewById(R.id.home_text_security);
+		mHomeTextAttacks = (TextView) mRootView.findViewById(R.id.home_text_attacks);
+		mHomeTextProfile = (TextView) mRootView.findViewById(R.id.home_text_profile);
+		mHomeTextProfileHeader = (TextView) mRootView.findViewById(R.id.home_text_profile_header);
+		mHomeProfileImage = (ImageView) mRootView.findViewById(R.id.home_image_profile);
+		mHomeConnectionInfoButton = (ImageView) mRootView.findViewById(R.id.home_button_connection_info);
 	}
 
-	private void registerBroadcastReceiver(){
-		if(!mReceiverRegistered) {
+	private void registerBroadcastReceiver() {
+		if (!mReceiverRegistered) {
 			LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver, new IntentFilter(getString(R.string.broadcast)));
 			this.mReceiverRegistered = true;
 		}
 	}
 
-	private void unregisterBroadcastReceiver(){
-		if(mReceiverRegistered){
+	private void unregisterBroadcastReceiver() {
+		if (mReceiverRegistered) {
 			LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
 			this.mReceiverRegistered = false;
 		}
 	}
 
-	public HomeFragment(){}
+	public HomeFragment() {
+	}
 
-	public void setStateNotActive(boolean initial){
+	public void setStateNotActive(boolean initial) {
 		mHomeTextName.setTextColor(getResources().getColor(R.color.light_grey));
 		mHomeTextSecurity.setTextColor(getResources().getColor(R.color.light_grey));
 		mHomeTextAttacks.setTextColor(getResources().getColor(R.color.light_grey));
 		mHomeTextProfile.setTextColor(getResources().getColor(R.color.light_grey));
 		mHomeTextProfileHeader.setTextColor(getResources().getColor(R.color.light_grey));
 
-		if(!initial){
-	        ThreatIndicatorGLRenderer.setThreatLevel(ThreatIndicatorGLRenderer.ThreatLevel.NOT_MONITORING);
+		if (!initial) {
+			ThreatIndicatorGLRenderer.setThreatLevel(ThreatIndicatorGLRenderer.ThreatLevel.NOT_MONITORING);
 		}
 
 		mHomeSwitchConnection.setChecked(false);
 	}
 
-	public void setStateNotActive(){
+	public void setStateNotActive() {
 		setStateNotActive(false);
 	}
 
-	public void setStateActive(){
+	public void setStateActive() {
 		setStateActive(false);
 	}
 
-	public void setStateActive(boolean initial){
+	public void setStateActive(boolean initial) {
 		mHomeTextAttacks.setVisibility(View.VISIBLE);
 		mHomeTextSecurity.setVisibility(View.VISIBLE);
 
-		mHomeTextName.setTextColor(defaultTextColor);
-		mHomeTextProfile.setTextColor(defaultTextColor);
-		mHomeTextProfileHeader.setTextColor(defaultTextColor);
+		mHomeTextName.setTextColor(mDefaultTextColor);
+		mHomeTextProfile.setTextColor(mDefaultTextColor);
+		mHomeTextProfileHeader.setTextColor(mDefaultTextColor);
 
-		if(!initial){
-	        ThreatIndicatorGLRenderer.setThreatLevel(ThreatIndicatorGLRenderer.ThreatLevel.NO_THREAT);
+		if (!initial) {
+			ThreatIndicatorGLRenderer.setThreatLevel(ThreatIndicatorGLRenderer.ThreatLevel.NO_THREAT);
 		}
 
 		mHomeSwitchConnection.setChecked(true);
 	}
 
-	public void setStateNotConnected(){
+	public void setStateNotConnected() {
 		mHomeTextSecurity.setVisibility(View.INVISIBLE);
 		mHomeTextAttacks.setVisibility(View.INVISIBLE);
 		mHomeTextProfile.setVisibility(View.INVISIBLE);
@@ -135,36 +140,36 @@ public class HomeFragment extends Fragment {
 		mHomeTextName.setText(R.string.not_connected);
 	}
 
-	public void setStateConnected(){
+	public void setStateConnected() {
 		mHomeTextProfile.setVisibility(View.VISIBLE);
 		mHomeTextProfileHeader.setVisibility(View.VISIBLE);
 		mHomeProfileImage.setVisibility(View.VISIBLE);
 		mHomeConnectionInfoButton.setVisibility(View.VISIBLE);
 	}
 
-	public void updateUI(){
+	public void updateUI() {
 		Profile profile = mProfileManager.getCurrentActivatedProfile();
-		if(profile != null){
+		if (profile != null) {
 			mHomeTextProfile.setText(profile.mLabel);
 			mHomeProfileImage.setImageBitmap(profile.getIconBitmap());
 		}
 
-		if(HelperUtils.isWifiConnected(getActivity())){
+		if (HelperUtils.isWifiConnected(getActivity())) {
 			setStateConnected();
 			mHomeTextName.setText(mConnectionInfo.getString(getString(R.string.connection_info_ssid), ""));
 		}
 
 		boolean hasActiveListeners = false;
-		int totalAttacks = dbh.numBssidSeen(mConnectionInfo.getString(getString(R.string.connection_info_bssid), null));
+		int totalAttacks = mDbHelper.numBssidSeen(mConnectionInfo.getString(getString(R.string.connection_info_bssid), null));
 		ThreatIndicatorGLRenderer.ThreatLevel threatLevel = ThreatIndicatorGLRenderer.ThreatLevel.NOT_MONITORING;
 
-		if(MainActivity.getInstance().getHoneyService() != null){
-			if(MainActivity.getInstance().getHoneyService().hasRunningListeners()){
+		if (MainActivity.getInstance().getHostageService() != null) {
+			if (MainActivity.getInstance().getHostageService().hasRunningListeners()) {
 				hasActiveListeners = true;
 
-				if(MainActivity.getInstance().getHoneyService().hasActiveAttacks() && totalAttacks > 0){
+				if (MainActivity.getInstance().getHostageService().hasActiveAttacks() && totalAttacks > 0) {
 					threatLevel = ThreatIndicatorGLRenderer.ThreatLevel.LIVE_THREAT;
-				} else if(totalAttacks > 0){
+				} else if (totalAttacks > 0) {
 					threatLevel = ThreatIndicatorGLRenderer.ThreatLevel.PAST_THREAT;
 				} else {
 					threatLevel = ThreatIndicatorGLRenderer.ThreatLevel.NO_THREAT;
@@ -172,58 +177,61 @@ public class HomeFragment extends Fragment {
 			}
 		}
 
-		if(hasActiveListeners){
+		if (hasActiveListeners) {
 			setStateActive(true);
 
-			switch(threatLevel){
-				case NO_THREAT:
-					mHomeTextAttacks.setText(R.string.zero_attacks);
-					mHomeTextSecurity.setText(R.string.secure);
-					mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_dark_green));
-					mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_dark_green));
-					break;
-				case PAST_THREAT:
-					mHomeTextAttacks.setText(totalAttacks + (totalAttacks == 1 ? getResources().getString(R.string.attack) : getResources().getString(R.string.attacks)) + getResources().getString(R.string.recorded));
-					mHomeTextSecurity.setText(R.string.insecure);
-					mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_yellow));
-					mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_yellow));
-					break;
-				case LIVE_THREAT:
-					mHomeTextAttacks.setText(totalAttacks + (totalAttacks == 1 ? getResources().getString(R.string.attack) : getResources().getString(R.string.attacks)) +  getResources().getString(R.string.recorded));
-					mHomeTextSecurity.setText(R.string.insecure);
-					mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_red));
-					mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_red));
-					break;
+			switch (threatLevel) {
+			case NO_THREAT:
+				mHomeTextAttacks.setText(R.string.zero_attacks);
+				mHomeTextSecurity.setText(R.string.secure);
+				mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_dark_green));
+				mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_dark_green));
+				break;
+			case PAST_THREAT:
+				mHomeTextAttacks.setText(totalAttacks
+						+ (totalAttacks == 1 ? getResources().getString(R.string.attack) : getResources().getString(R.string.attacks))
+						+ getResources().getString(R.string.recorded));
+				mHomeTextSecurity.setText(R.string.insecure);
+				mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_yellow));
+				mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_yellow));
+				break;
+			case LIVE_THREAT:
+				mHomeTextAttacks.setText(totalAttacks
+						+ (totalAttacks == 1 ? getResources().getString(R.string.attack) : getResources().getString(R.string.attacks))
+						+ getResources().getString(R.string.recorded));
+				mHomeTextSecurity.setText(R.string.insecure);
+				mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_red));
+				mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_red));
+				break;
 			}
 
 			ThreatIndicatorGLRenderer.setThreatLevel(threatLevel);
 		} else {
 			setStateNotActive();
 
-			if(!HelperUtils.isWifiConnected(getActivity())){
+			if (!HelperUtils.isWifiConnected(getActivity())) {
 				setStateNotConnected();
 			}
 		}
 	}
 
-    @Override
-    public View onCreateView(LayoutInflater inflater, ViewGroup container,
-                             Bundle savedInstanceState) {
-
-	    super.onCreateView(inflater, container, savedInstanceState);
+	@Override
+	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+		super.onCreateView(inflater, container, savedInstanceState);
+		setHasOptionsMenu(true);
 
 		final Activity activity = getActivity();
 		if (activity != null) {
 			activity.setTitle(getResources().getString(R.string.drawer_overview));
 		}
 
-	    dbh = new UglyDbHelper(getActivity());
+		mDbHelper = new UglyDbHelper(getActivity());
 
-	    mProfileManager = ProfileManager.getInstance();
+		mProfileManager = ProfileManager.getInstance();
 		mConnectionInfo = getActivity().getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
 
-        rootView = inflater.inflate(R.layout.fragment_home, container, false);
-	    assignViews();
+		mRootView = inflater.inflate(R.layout.fragment_home, container, false);
+		assignViews();
 
 		// hook up the connection info button
 		mHomeConnectionInfoButton.setOnClickListener(new View.OnClickListener() {
@@ -237,159 +245,166 @@ public class HomeFragment extends Fragment {
 			}
 		});
 
-	    defaultTextColor = mHomeTextName.getCurrentTextColor();
-
-	    setStateNotActive(true);
-	    setStateNotConnected();
-
-	    mReceiver = new BroadcastReceiver() {
-		    @Override
-		    public void onReceive(Context context, Intent intent) {
-			    if(getUserVisibleHint()) updateUI();
-		    }
-	    };
-	    registerBroadcastReceiver();
-
-	    updateUI();
-
-	    mHomeSwitchConnection = (Switch) rootView.findViewById(R.id.home_switch_connection);
-
-	    if(switchChangeListener == null){
-		    switchChangeListener = new CompoundButton.OnCheckedChangeListener() {
-			    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
-				    if(!HelperUtils.isWifiConnected(getActivity())){
-					    new AlertDialog.Builder(getActivity())
-							    .setTitle(R.string.information)
-							    .setMessage(R.string.wifi_not_connected_msg)
-							    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
-								    public void onClick(DialogInterface dialog, int which) {
-
-								    }
-							    })
-							    .setIcon(android.R.drawable.ic_dialog_info)
-							    .show();
-
-					    setStateNotActive();
-					    setStateNotConnected();
-				    } else {
-					    if(isChecked){
-						    boolean protocolActivated = false;
-						    if(ProfileManager.getInstance().getCurrentActivatedProfile() == null){
-							    for(String protocol: getResources().getStringArray(R.array.protocols)){
-								    if(!MainActivity.getInstance().getHoneyService().isRunning(protocol)){
-									    MainActivity.getInstance().getHoneyService().startListener(protocol);
-									    protocolActivated = true;
-								    }
-							    }
-						    } else {
-							    ProfileManager profileManager = ProfileManager.getInstance();
-
-							    if(profileManager.isRandomActive()){
-								    profileManager.randomizeProtocols(profileManager.getRandomProfile());
-							    }
-
-							    for(String protocol: profileManager.getCurrentActivatedProfile().getActiveProtocols()){
-								    if(protocol.equals("GHOST")) continue;
-
-								    if(!MainActivity.getInstance().getHoneyService().isRunning(protocol)) {
-									    MainActivity.getInstance().getHoneyService().startListener(protocol);
-									    protocolActivated = true;
-								    }
-							    }
-
-							    Profile currentProfile = profileManager.getCurrentActivatedProfile();
-
-							    if(currentProfile.mGhostActive){
-								    for(int port: currentProfile.getGhostPorts()){
-									    MainActivity.getInstance().getHoneyService().startListener("GHOST", port);
-									    protocolActivated = true;
-								    }
-							    }
-						    }
-
-						    if(protocolActivated){
-						        setStateActive();
-						    } else {
-							    new AlertDialog.Builder(getActivity())
-									    .setTitle(R.string.information)
-									    .setMessage(R.string.profile_no_services_msg)
-									    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
-										    public void onClick(DialogInterface dialog, int which) {
-
-										    }
-									    })
-									    .setIcon(android.R.drawable.ic_dialog_info)
-									    .show();
-
-							    setStateNotActive();
-						    }
-					    } else {
-						    if(MainActivity.getInstance().getHoneyService() != null){
-							    MainActivity.getInstance().getHoneyService().stopListeners();
-							    MainActivity.getInstance().stopAndUnbind();
-						    }
-						    setStateNotActive();
-					    }
-				    }
-			    }
-		    };
-	    }
-	    mHomeSwitchConnection.setOnCheckedChangeListener(switchChangeListener);
-
-	    rootView.findViewById(R.id.home_profile_details).setOnClickListener(
-		    new View.OnClickListener() {
-			    @Override
-			    public void onClick(View v) {
-					Fragment fragment = new ProfileManagerFragment();
-				    MainActivity.getInstance().injectFragment(fragment, false);
-			    }
-		    }
-	    );
-
-	    View.OnClickListener attackClickListener = new View.OnClickListener() {
-		    @Override
-		    public void onClick(View v) {
-			    String ssid = mConnectionInfo.getString(getString(R.string.connection_info_ssid), "");
-			    if(!ssid.isEmpty()){
-				    ArrayList<String> ssids = new ArrayList<String>();
-				    ssids.add(ssid);
-
-				    LogFilter filter = new LogFilter();
-				    filter.setESSIDs(ssids);
-
-				    RecordOverviewFragment recordOverviewFragment = new RecordOverviewFragment();
-				    recordOverviewFragment.setFilter(filter);
-				    recordOverviewFragment.setGroupKey("ESSID");
-
-				    MainActivity.getInstance().injectFragment(recordOverviewFragment);
-			    }
-		    }
-	    };
-
-	    mHomeTextAttacks.setOnClickListener(attackClickListener);
-	    mHomeTextSecurity.setOnClickListener(attackClickListener);
-
-        return rootView;
-    }
+		mDefaultTextColor = mHomeTextName.getCurrentTextColor();
+
+		setStateNotActive(true);
+		setStateNotConnected();
+
+		mReceiver = new BroadcastReceiver() {
+			@SuppressLint("NewApi")
+			@Override
+			public void onReceive(Context context, Intent intent) {
+				if (getUserVisibleHint())
+					updateUI();
+			}
+		};
+		registerBroadcastReceiver();
+
+		updateUI();
+
+		mHomeSwitchConnection = (Switch) mRootView.findViewById(R.id.home_switch_connection);
+
+		if (mSwitchChangeListener == null) {
+			mSwitchChangeListener = new CompoundButton.OnCheckedChangeListener() {
+				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+					if (!HelperUtils.isNetworkAvailable(getActivity())) {
+						new AlertDialog.Builder(getActivity()).setTitle(R.string.information).setMessage(R.string.wifi_not_connected_msg)
+								.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
+									public void onClick(DialogInterface dialog, int which) {
+
+									}
+								}).setIcon(android.R.drawable.ic_dialog_info).show();
+
+						setStateNotActive();
+						setStateNotConnected();
+					} else {
+						if (isChecked) {
+							boolean protocolActivated = false;
+							if (ProfileManager.getInstance().getCurrentActivatedProfile() == null) {
+								for (String protocol : getResources().getStringArray(R.array.protocols)) {
+									if (!MainActivity.getInstance().getHostageService().isRunning(protocol)) {
+										MainActivity.getInstance().getHostageService().startListener(protocol);
+										protocolActivated = true;
+									}
+								}
+							} else {
+								ProfileManager profileManager = ProfileManager.getInstance();
+
+								if (profileManager.isRandomActive()) {
+									profileManager.randomizeProtocols(profileManager.getRandomProfile());
+								}
+
+								for (String protocol : profileManager.getCurrentActivatedProfile().getActiveProtocols()) {
+									if (protocol.equals("GHOST"))
+										continue;
+
+									if (!MainActivity.getInstance().getHostageService().isRunning(protocol)) {
+										MainActivity.getInstance().getHostageService().startListener(protocol);
+										protocolActivated = true;
+									}
+								}
+
+								Profile currentProfile = profileManager.getCurrentActivatedProfile();
+
+								if (currentProfile.mGhostActive) {
+									for (int port : currentProfile.getGhostPorts()) {
+										MainActivity.getInstance().getHostageService().startListener("GHOST", port);
+										protocolActivated = true;
+									}
+								}
+							}
+
+							if (protocolActivated) {
+								setStateActive();
+							} else {
+								new AlertDialog.Builder(getActivity()).setTitle(R.string.information).setMessage(R.string.profile_no_services_msg)
+										.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
+											public void onClick(DialogInterface dialog, int which) {
+
+											}
+										}).setIcon(android.R.drawable.ic_dialog_info).show();
+
+								setStateNotActive();
+							}
+						} else {
+							if (MainActivity.getInstance().getHostageService() != null) {
+								MainActivity.getInstance().getHostageService().stopListeners();
+								MainActivity.getInstance().stopAndUnbind();
+							}
+							setStateNotActive();
+						}
+					}
+				}
+			};
+		}
+		mHomeSwitchConnection.setOnCheckedChangeListener(mSwitchChangeListener);
+
+		mRootView.findViewById(R.id.home_profile_details).setOnClickListener(new View.OnClickListener() {
+			@Override
+			public void onClick(View v) {
+				Fragment fragment = new ProfileManagerFragment();
+				MainActivity.getInstance().injectFragment(fragment, false);
+			}
+		});
+
+		View.OnClickListener attackClickListener = new View.OnClickListener() {
+			@Override
+			public void onClick(View v) {
+				String ssid = mConnectionInfo.getString(getString(R.string.connection_info_ssid), "");
+				if (!ssid.isEmpty()) {
+					ArrayList<String> ssids = new ArrayList<String>();
+					ssids.add(ssid);
+
+					LogFilter filter = new LogFilter();
+					filter.setESSIDs(ssids);
+
+					RecordOverviewFragment recordOverviewFragment = new RecordOverviewFragment();
+					recordOverviewFragment.setFilter(filter);
+					recordOverviewFragment.setGroupKey("ESSID");
+
+					MainActivity.getInstance().injectFragment(recordOverviewFragment);
+				}
+			}
+		};
+
+		mHomeTextAttacks.setOnClickListener(attackClickListener);
+		mHomeTextSecurity.setOnClickListener(attackClickListener);
+
+		return mRootView;
+	}
 
 	@Override
-	public void onStop(){
-		super.onStop();
+	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
+		// Inflate the menu items for use in the action bar
+		inflater.inflate(R.menu.home_actions, menu);
+	}
 
+	@Override
+	public boolean onOptionsItemSelected(MenuItem item) {
+		switch(item.getItemId()){
+			case R.id.home_action_synchronize:
+				getActivity().startActivity(new Intent(this.getActivity(), BluetoothSync.class));
+				return true;
+		}
+
+		return false;
+	}
+
+	@Override
+	public void onStop() {
 		unregisterBroadcastReceiver();
-		//mHomeSwitchConnection.setOnCheckedChangeListener(null);
+		super.onStop();
 	}
 
 	@Override
-	public void onStart(){
+	public void onStart() {
 		super.onStart();
 		registerBroadcastReceiver();
 		updateUI();
-		//mHomeSwitchConnection.setOnCheckedChangeListener(switchChangeListener);
 	}
 
 	@Override
-	public void onDestroy(){
+	public void onDestroy() {
 		super.onDestroy();
 		unregisterBroadcastReceiver();
 	}

+ 1 - 3
src/de/tudarmstadt/informatik/hostage/ui2/fragment/ProfileEditFragment.java

@@ -13,12 +13,10 @@ import android.net.Uri;
 import android.os.Bundle;
 import android.preference.CheckBoxPreference;
 import android.preference.EditTextPreference;
-import android.preference.MultiSelectListPreference;
 import android.preference.Preference;
 import android.preference.PreferenceCategory;
 import android.preference.PreferenceFragment;
 import android.preference.PreferenceManager;
-import android.preference.PreferenceScreen;
 import android.provider.MediaStore;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -27,7 +25,7 @@ import android.widget.LinearLayout;
 import java.util.HashMap;
 
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.dao.ProfileManager;
+import de.tudarmstadt.informatik.hostage.persistence.ProfileManager;
 import de.tudarmstadt.informatik.hostage.model.Profile;
 
 /**

+ 17 - 1
src/de/tudarmstadt/informatik/hostage/ui2/fragment/ProfileManagerFragment.java

@@ -15,7 +15,7 @@ import com.fortysevendeg.android.swipelistview.BaseSwipeListViewListener;
 import java.util.List;
 
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.dao.ProfileManager;
+import de.tudarmstadt.informatik.hostage.persistence.ProfileManager;
 import de.tudarmstadt.informatik.hostage.model.Profile;
 import de.tudarmstadt.informatik.hostage.ui2.activity.ProfileEditActivity;
 import de.tudarmstadt.informatik.hostage.ui2.adapter.ProfileManagerListAdapter;
@@ -47,12 +47,28 @@ public class ProfileManagerFragment extends Fragment {
 
         List<Profile> strList = pmanager.getProfilesList();
 
+	    if(strList.size() > 0){
+		    Profile tProfile = new Profile();
+		    tProfile.mShowTooltip = true;
+
+			strList.add(1, tProfile);
+	    }
+
 		mAdapter = new ProfileManagerListAdapter(getActivity(), strList, list);
 		pmanager.setProfileListAdapter(mAdapter);
 
         list.setAdapter(mAdapter);
 
 		list.setSwipeListViewListener(new BaseSwipeListViewListener() {
+			@Override
+			public void onOpened(int position, boolean toRight){
+				Profile profile = mAdapter.getItem(position);
+				if(profile.mShowTooltip){
+					mAdapter.remove(profile);
+					list.dismiss(position);
+				}
+			}
+
 			@Override
 			public void onClickFrontView(int position) {
 				Profile profile = mAdapter.getItem(position);

+ 108 - 109
src/de/tudarmstadt/informatik/hostage/ui2/fragment/RecordDetailFragment.java

@@ -1,9 +1,10 @@
 package de.tudarmstadt.informatik.hostage.ui2.fragment;
 
-import android.annotation.SuppressLint;
+import java.util.ArrayList;
+import java.util.Date;
+
 import android.os.Bundle;
 import android.text.format.DateFormat;
-import android.text.method.ScrollingMovementMethod;
 import android.view.LayoutInflater;
 import android.view.Menu;
 import android.view.MenuInflater;
@@ -13,59 +14,59 @@ import android.view.ViewGroup;
 import android.widget.LinearLayout;
 import android.widget.ScrollView;
 import android.widget.TextView;
-import java.util.ArrayList;
-import java.util.Date;
-
 import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.deprecated.UglyDbHelper;
 import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
 
 /**
  * Created by Julien on 02.03.14.
  */
 public class RecordDetailFragment extends UpNavigatibleFragment {
-    private class Location{
-        private double longitude;
-        private double latitude;
-        private float accuracy;
-
-        public double getLatitude() {
-            return latitude;
-        }
-        public void setLatitude(double latitude) {
-            this.latitude = latitude;
-        }
-        public float getAccuracy() {
-            return accuracy;
-        }
+	private class Location {
+		private double longitude;
+		private double latitude;
+		private float accuracy;
+
+		public double getLatitude() {
+			return latitude;
+		}
+
+		public void setLatitude(double latitude) {
+			this.latitude = latitude;
+		}
+
+		public float getAccuracy() {
+			return accuracy;
+		}
 
 		public void setAccuracy(float accuracy) {
 			this.accuracy = accuracy;
 		}
 
-		public double getLongitude(){
-            return this.longitude;
-        }
-        public void setLongitude(double longitude){
-            this.longitude = longitude;
-        }
-
-        public Location(){
-            super();
-        }
-        public Location(double latitude, double longitude, float accuracy){
-            super();
-            this.latitude = latitude;
-            this.longitude = longitude;
-            this.accuracy = accuracy;
-        }
-    }
-
-    private Record record;
-    private UglyDbHelper dbh;
-    private View rootView;
-	private LayoutInflater mInflater;
+		public double getLongitude() {
+			return this.longitude;
+		}
 
+		public void setLongitude(double longitude) {
+			this.longitude = longitude;
+		}
+
+		public Location() {
+			super();
+		}
+
+		public Location(double latitude, double longitude, float accuracy) {
+			super();
+			this.latitude = latitude;
+			this.longitude = longitude;
+			this.accuracy = accuracy;
+		}
+	}
+
+	private Record record;
+	private UglyDbHelper dbh;
+	private View rootView;
+	private LayoutInflater mInflater;
 
 	private ScrollView mScrollView;
 	private LinearLayout mRecordOverviewConversation;
@@ -74,44 +75,43 @@ public class RecordDetailFragment extends UpNavigatibleFragment {
 	private TextView mRecordDetailsTextRemoteip;
 	private TextView mRecordDetailsTextProtocol;
 
-    public void setRecord(Record rec){
-        this.record = rec;
-    }
-    public Record getRecord(){
-        return this.record;
-    }
+	public void setRecord(Record rec) {
+		this.record = rec;
+	}
 
-    public int getLayoutId(){
-        //return R.layout.fragment_record_detail;
-	    return R.layout.fragment_record_overview;
-    }
+	public Record getRecord() {
+		return this.record;
+	}
 
-    public void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-        setHasOptionsMenu(true);
-    }
+	public int getLayoutId() {
+		// return R.layout.fragment_record_detail;
+		return R.layout.fragment_record_overview;
+	}
 
-    public View onCreateView(LayoutInflater inflater, ViewGroup container,
-                             Bundle savedInstanceState) {
-        super.onCreateView(inflater, container, savedInstanceState);
+	public void onCreate(Bundle savedInstanceState) {
+		super.onCreate(savedInstanceState);
+		setHasOptionsMenu(true);
+	}
 
-	    mInflater = inflater;
-	    getActivity().setTitle(record.getSsid());
+	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+		super.onCreateView(inflater, container, savedInstanceState);
 
-        this.dbh = new UglyDbHelper(this.getActivity().getBaseContext());
+		mInflater = inflater;
+		getActivity().setTitle(record.getSsid());
 
-        this.rootView = inflater.inflate(this.getLayoutId(), container, false);
-	    this.assignViews(rootView);
-        this.configurateRootView(rootView);
+		this.dbh = new UglyDbHelper(this.getActivity().getBaseContext());
 
+		this.rootView = inflater.inflate(this.getLayoutId(), container, false);
+		this.assignViews(rootView);
+		this.configurateRootView(rootView);
 
-        return rootView;
-    }
+		return rootView;
+	}
 
-    public void onStart() {
-        super.onStart();
+	public void onStart() {
+		super.onStart();
 
-    }
+	}
 
 	private void assignViews(View view) {
 		mScrollView = (ScrollView) view.findViewById(R.id.scrollView);
@@ -126,69 +126,68 @@ public class RecordDetailFragment extends UpNavigatibleFragment {
 
 		mRecordDetailsTextBssid.setText(record.getBssid());
 		mRecordDetailsTextSsid.setText(record.getSsid());
-		if(record.getRemoteIP() != null) mRecordDetailsTextRemoteip.setText(record.getRemoteIP() + ":" + record.getRemotePort());
+		if (record.getRemoteIP() != null)
+			mRecordDetailsTextRemoteip.setText(record.getRemoteIP() + ":" + record.getRemotePort());
 		mRecordDetailsTextProtocol.setText(record.getProtocol());
 
-	    ArrayList<Record> conversation = this.dbh.getConversationForAttackID(record.getAttack_id());
+		ArrayList<Record> conversation = this.dbh.getConversationForAttackID(record.getAttack_id());
 
-	    for(Record r: conversation){
-		    View row;
+		for (Record r : conversation) {
+			View row;
 
-		    String from = r.getLocalIP() == null ? "-" : r.getLocalIP() + ":" + r.getLocalPort();
-		    String to = r.getRemoteIP() == null ? "-" : r.getRemoteIP() + ":" + r.getRemotePort();
+			String from = r.getLocalIP() == null ? "-" : r.getLocalIP() + ":" + r.getLocalPort();
+			String to = r.getRemoteIP() == null ? "-" : r.getRemoteIP() + ":" + r.getRemotePort();
 
-		    if(r.getType() == Record.TYPE.SEND){
-			    row = mInflater.inflate(R.layout.fragment_record_conversation_sent, null);
-		    } else {
-			    row = mInflater.inflate(R.layout.fragment_record_conversation_received, null);
+			if (r.getType() == Record.TYPE.SEND) {
+				row = mInflater.inflate(R.layout.fragment_record_conversation_sent, null);
+			} else {
+				row = mInflater.inflate(R.layout.fragment_record_conversation_received, null);
 
-			    String tmp = from;
-			    from = to;
-			    to = tmp;
-		    }
+				String tmp = from;
+				from = to;
+				to = tmp;
+			}
 
-		    TextView conversationInfo = (TextView) row.findViewById(R.id.record_conversation_info);
-		    TextView conversationContent = (TextView) row.findViewById(R.id.record_conversation_content);
+			TextView conversationInfo = (TextView) row.findViewById(R.id.record_conversation_info);
+			TextView conversationContent = (TextView) row.findViewById(R.id.record_conversation_content);
 			conversationContent.setOnTouchListener(new View.OnTouchListener() {
 				@Override
 				public boolean onTouch(final View v, final MotionEvent motionEvent) {
 					if (v.getId() == R.id.record_conversation_content) {
 						v.getParent().requestDisallowInterceptTouchEvent(true);
 						switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
-							case MotionEvent.ACTION_UP:
-								v.getParent().requestDisallowInterceptTouchEvent(
-										false);
-								break;
+						case MotionEvent.ACTION_UP:
+							v.getParent().requestDisallowInterceptTouchEvent(false);
+							break;
 						}
 					}
 					return false;
 				}
 			});
 
-		    Date date = new Date(r.getTimestamp());
-		    conversationInfo.setText(String.format(getString(R.string.record_details_info), from, to, getDateAsString(date), getTimeAsString(date)));
-		    if(r.getPacket() != null) conversationContent.setText(r.getPacket());
-
-		    mRecordOverviewConversation.addView(row);
-	    }
-    }
+			Date date = new Date(r.getTimestamp());
+			conversationInfo.setText(String.format(getString(R.string.record_details_info), from, to, getDateAsString(date), getTimeAsString(date)));
+			if (r.getPacket() != null)
+				conversationContent.setText(r.getPacket());
 
+			mRecordOverviewConversation.addView(row);
+		}
+	}
 
-    /*****************************
-     *
-     *          Date Transform
-     *
-     * ***************************/
-    private String getDateAsString(Date date) {
+	/*****************************
+	 * 
+	 * Date Transform
+	 * 
+	 * ***************************/
+	private String getDateAsString(Date date) {
 		return DateFormat.getDateFormat(getActivity()).format(date);
-    }
+	}
 
-	private String getTimeAsString(Date date){
+	private String getTimeAsString(Date date) {
 		return DateFormat.getTimeFormat(getActivity()).format(date);
 	}
 
-
-    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
-        super.onCreateOptionsMenu(menu, inflater);
-    }
+	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
+		super.onCreateOptionsMenu(menu, inflater);
+	}
 }

+ 10 - 14
src/de/tudarmstadt/informatik/hostage/ui2/fragment/ServicesFragment.java

@@ -1,7 +1,9 @@
 package de.tudarmstadt.informatik.hostage.ui2.fragment;
 
+import java.util.ArrayList;
 
 import android.app.AlertDialog;
+import android.app.Fragment;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.DialogInterface;
@@ -9,7 +11,6 @@ import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.SharedPreferences;
 import android.os.Bundle;
-import android.app.Fragment;
 import android.support.v4.content.LocalBroadcastManager;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -18,18 +19,14 @@ import android.widget.CompoundButton;
 import android.widget.ListView;
 import android.widget.Switch;
 import android.widget.TextView;
-
-import java.util.ArrayList;
-
-import de.tudarmstadt.informatik.hostage.HoneyHandler;
+import de.tudarmstadt.informatik.hostage.Handler;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
+import de.tudarmstadt.informatik.hostage.deprecated.UglyDbHelper;
 import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
 import de.tudarmstadt.informatik.hostage.ui2.adapter.ServicesListAdapter;
 import de.tudarmstadt.informatik.hostage.ui2.model.ServicesListItem;
 
-
 /**
  * @author Daniel Lazar
  * @created 05.02.14
@@ -37,7 +34,6 @@ import de.tudarmstadt.informatik.hostage.ui2.model.ServicesListItem;
  * Also it can de-/activate every protocol by using this switch.
  */
 public class ServicesFragment extends Fragment {
-
     private Switch mServicesSwitchService;
     private TextView mServicesTextName;
 
@@ -90,7 +86,7 @@ public class ServicesFragment extends Fragment {
             setStateNotActive();
             mServicesSwitchService.setOnCheckedChangeListener(switchChangeListener);
         } else {
-            if (MainActivity.getInstance().getHoneyService().hasRunningListeners()) {
+            if (MainActivity.getInstance().getHostageService().hasRunningListeners()) {
                 setStateActive();
             }
 
@@ -111,7 +107,7 @@ public class ServicesFragment extends Fragment {
                     String sender = intent.getStringExtra("SENDER");
                     String[] values = intent.getStringArrayExtra("VALUES");
 
-                    if (sender.equals(HoneyHandler.class.getName()) && values[0].equals(getString(R.string.broadcast_started))) {
+                    if (sender.equals(Handler.class.getName()) && values[0].equals(getString(R.string.broadcast_started))) {
                         for (ServicesListItem item : protocolList) {
                             if (item.protocol.equals(values[1])) {
                                 item.attacks = dbh.numBssidSeen(item.protocol, mConnectionInfo.getString(getString(R.string.connection_info_bssid), null));
@@ -119,7 +115,7 @@ public class ServicesFragment extends Fragment {
                         }
                     }
 
-                    if (!MainActivity.getInstance().getHoneyService().hasRunningListeners()) {
+                    if (!MainActivity.getInstance().getHostageService().hasRunningListeners()) {
                         setStateNotActive();
                     } else {
                         setStateActive();
@@ -191,13 +187,13 @@ public class ServicesFragment extends Fragment {
                         if (MainActivity.getInstance().isServiceBound()) {
                             if (isChecked) {
                                 for (String protocol : protocols) {
-                                    if (!MainActivity.getInstance().getHoneyService().isRunning(protocol)) {
-                                        MainActivity.getInstance().getHoneyService().startListener(protocol);
+                                    if (!MainActivity.getInstance().getHostageService().isRunning(protocol)) {
+                                        MainActivity.getInstance().getHostageService().startListener(protocol);
                                     }
                                 }
                                 setStateActive();
                             } else {
-                                MainActivity.getInstance().getHoneyService().stopListeners();
+                                MainActivity.getInstance().getHostageService().stopListeners();
                                 MainActivity.getInstance().stopAndUnbind();
                                 setStateNotActive();
                             }

+ 4 - 6
src/de/tudarmstadt/informatik/hostage/ui2/fragment/SettingsFragment.java

@@ -1,22 +1,20 @@
 package de.tudarmstadt.informatik.hostage.ui2.fragment;
 
-import android.app.Fragment;
 import android.app.FragmentManager;
 import android.os.Bundle;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.TextView;
-
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.system.Device;
 
 /**
  * @author Alexander Brakowski
  * @created 24.02.14 23:37
  */
 public class SettingsFragment extends UpNavigatibleFragment {
-	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
+	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 		super.onCreateView(inflater, container, savedInstanceState);
 		getActivity().setTitle(getResources().getString(R.string.drawer_settings));
 		View v = inflater.inflate(R.layout.fragment_settings, container, false);
@@ -24,7 +22,7 @@ public class SettingsFragment extends UpNavigatibleFragment {
 		TextView rootedText = (TextView) v.findViewById(R.id.settings_device_rooted);
 		TextView porthackText = (TextView) v.findViewById(R.id.settings_porthack_installed);
 
-		if(MainActivity.isRooted){
+		if (Device.isRooted()) {
 			rootedText.setText(R.string.yes);
 			rootedText.setTextColor(getResources().getColor(R.color.holo_dark_green));
 		} else {
@@ -32,7 +30,7 @@ public class SettingsFragment extends UpNavigatibleFragment {
 			rootedText.setTextColor(getResources().getColor(R.color.holo_red));
 		}
 
-		if(MainActivity.porthackInstalled){
+		if (Device.isPorthackInstalled()) {
 			porthackText.setText(R.string.yes);
 			porthackText.setTextColor(getResources().getColor(R.color.holo_dark_green));
 		} else {

+ 8 - 7
src/de/tudarmstadt/informatik/hostage/ui2/fragment/ThreatMapFragment.java

@@ -1,5 +1,12 @@
 package de.tudarmstadt.informatik.hostage.ui2.fragment;
 
+import static com.google.android.gms.common.GooglePlayServicesUtil.getErrorDialog;
+import static com.google.android.gms.common.GooglePlayServicesUtil.isGooglePlayServicesAvailable;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
 import android.app.Activity;
 import android.app.AlertDialog;
 import android.app.Fragment;
@@ -29,19 +36,13 @@ import com.google.android.gms.maps.model.LatLng;
 import com.google.android.gms.maps.model.Marker;
 import com.google.android.gms.maps.model.MarkerOptions;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+import de.tudarmstadt.informatik.hostage.deprecated.UglyDbHelper;
 import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
 import de.tudarmstadt.informatik.hostage.ui.LogFilter;
 import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
 
-import static com.google.android.gms.common.GooglePlayServicesUtil.*;
-
 /**
  * ThreatMapFragment
  *

+ 0 - 60
src/de/tudarmstadt/informatik/hostage/ui2/listeners/OnSwipeTouchListener.java

@@ -1,60 +0,0 @@
-package de.tudarmstadt.informatik.hostage.ui2.listeners;
-
-import android.view.GestureDetector;
-import android.view.GestureDetector.SimpleOnGestureListener;
-import android.view.MotionEvent;
-import android.view.View;
-import android.view.View.OnTouchListener;
-
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
-
-/**
- * @author Alexander Brakowski
- * @created 27.01.14 23:47
- */
-public class OnSwipeTouchListener implements OnTouchListener {
-
-	private final GestureDetector gestureDetector = new GestureDetector(MainActivity.getContext(), new GestureListener());
-
-	public boolean onTouch(final View view, final MotionEvent motionEvent) {
-		return gestureDetector.onTouchEvent(motionEvent);
-	}
-
-	private final class GestureListener extends SimpleOnGestureListener {
-
-		private static final int SWIPE_THRESHOLD = 50;
-		private static final int SWIPE_VELOCITY_THRESHOLD = 150;
-
-		@Override
-		public boolean onDown(MotionEvent e) {
-			return true;
-		}
-
-		@Override
-		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
-
-			try {
-				float diffX = e2.getX() - e1.getX();
-
-				if (Math.abs(diffX) > SWIPE_THRESHOLD) {
-					if (diffX > 0) {
-						onSwipeRight();
-					} else {
-						onSwipeLeft();
-					}
-				}
-			} catch (Exception exception) {
-				exception.printStackTrace();
-				return false;
-			}
-
-			return true;
-		}
-	}
-
-	public void onSwipeRight() {
-	}
-
-	public void onSwipeLeft() {
-	}
-}

+ 0 - 41
src/de/tudarmstadt/informatik/hostage/ui2/preference/ImageSelectPreference.java

@@ -1,41 +0,0 @@
-package de.tudarmstadt.informatik.hostage.ui2.preference;
-
-import android.content.Context;
-import android.preference.Preference;
-import android.util.AttributeSet;
-import android.view.View;
-import android.view.ViewGroup;
-
-import de.tudarmstadt.informatik.hostage.R;
-
-/**
- * @author Alexander Brakowski
- * @created 08.02.14 18:38
- */
-public class ImageSelectPreference extends Preference {
-
-	private Context context;
-
-	public ImageSelectPreference(Context context, AttributeSet attrs,
-			int defStyle) {
-		super(context, attrs, defStyle);
-
-		this.context = context;
-	}
-
-	public void init(){
-		this.setWidgetLayoutResource(R.layout.preferences_image_widget);
-	}
-
-	@Override
-	protected void onClick() {
-		//context.start
-	}
-
-	/*protected View onCreateView(ViewGroup parent) {
-		View p = super.onCreateView(parent);
-
-
-		return p;
-	}*/
-}

+ 19 - 10
src/de/tudarmstadt/informatik/hostage/wrapper/Packet.java

@@ -1,13 +1,17 @@
 package de.tudarmstadt.informatik.hostage.wrapper;
 
+import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+
 /**
  * Wrapper class for the payload of a network packet.
  * 
  * @author Mihai Plasoianu
+ * @author Wulf Pfeiffer
  */
 public class Packet {
 
 	private byte[] payload;
+	private String protocol;
 
 	/**
 	 * Constructs Packet from byte[]
@@ -15,8 +19,9 @@ public class Packet {
 	 * @param payload
 	 *            The byte[] payload
 	 */
-	public Packet(byte[] payload) {
+	public Packet(byte[] payload, String protocol) {
 		this.payload = payload;
+		this.protocol = protocol;
 	}
 
 	/**
@@ -25,8 +30,9 @@ public class Packet {
 	 * @param payload
 	 *            The String payload
 	 */
-	public Packet(String payload) {
+	public Packet(String payload, String protocol) {
 		this.payload = payload.getBytes();
+		this.protocol = protocol;
 	}
 
 	/**
@@ -40,20 +46,23 @@ public class Packet {
 
 	/**
 	 * Returns a String representation of the payload.
+	 * If the payload contains a ASCII character the whole
+	 * String will be represented as a String of a byte values.
+	 * E.g.: the byte[] {0x01, 0x4A, 0x03} would look like
+	 * the String "01, 4A, 03".
+	 * Otherwise a normal String will be created with the payload.
 	 * 
 	 * @return String representation.
 	 */
 	@Override
 	public String toString() {
-		StringBuilder builder = new StringBuilder(payload.length);
-		for (int i = 0; i < payload.length; ++i) {
-			if (payload[i] < 32) {
-				builder.append("{0x").append(payload[i]).append("}");
-			} else {
-				builder.append(Character.toString((char) payload[i]));
-			}
+		if (protocol.equals("FTP") 
+				|| protocol.equals("HTTP") 
+				|| protocol.equals("HTTPS")) {
+			return new String(payload);
+		} else {
+			return HelperUtils.bytesToHexString(payload);
 		}
-		return builder.toString();
 	}
 
 }