Browse Source

merged all the changes of hostage v1

Alexander Brakowski 9 years ago
parent
commit
b75cceb1b0
78 changed files with 5868 additions and 4027 deletions
  1. 1 0
      .classpath
  2. 1 0
      .gitignore
  3. 12 0
      .settings/org.eclipse.jdt.core.prefs
  4. 30 1
      AndroidManifest.xml
  5. BIN
      assets/p
  6. BIN
      libs/sshlib-v1.1.jar
  7. 4 0
      lint.xml
  8. 1 1
      native/Makefile
  9. BIN
      native/p
  10. 7 1
      native/p.c
  11. BIN
      native/p.o
  12. 18 11
      res/layout/activity_main.xml
  13. 17 0
      res/layout/activity_nfc.xml
  14. 52 0
      res/layout/activity_playground.xml
  15. 5 5
      res/layout/activity_viewlog.xml
  16. 1 1
      res/layout/list_view_protocols_row.xml
  17. 2 2
      res/menu/main.xml
  18. 2 0
      res/values/protocols.xml
  19. 5 3
      res/values/strings.xml
  20. 11 0
      res/values/strings_broadcast.xml
  21. 13 0
      res/values/strings_connection_info.xml
  22. 31 0
      res/values/strings_gui.xml
  23. 6 1
      res/values/strings_preferences.xml
  24. 13 1
      res/xml/preferences.xml
  25. 251 0
      src/de/tudarmstadt/informatik/hostage/HoneyHandler.java
  26. 42 55
      src/de/tudarmstadt/informatik/hostage/HoneyListener.java
  27. 426 181
      src/de/tudarmstadt/informatik/hostage/HoneyService.java
  28. 160 47
      src/de/tudarmstadt/informatik/hostage/commons/HelperUtils.java
  29. 0 14
      src/de/tudarmstadt/informatik/hostage/format/DefaultFormatter.java
  30. 0 46
      src/de/tudarmstadt/informatik/hostage/format/LogViewFormatter.java
  31. 0 64
      src/de/tudarmstadt/informatik/hostage/format/MySQLFormatter.java
  32. 0 17
      src/de/tudarmstadt/informatik/hostage/format/ProtocolFormatter.java
  33. 0 135
      src/de/tudarmstadt/informatik/hostage/format/SMBFormatter.java
  34. 0 169
      src/de/tudarmstadt/informatik/hostage/format/TELNETFormatter.java
  35. 0 156
      src/de/tudarmstadt/informatik/hostage/handler/AbstractHandler.java
  36. 0 69
      src/de/tudarmstadt/informatik/hostage/handler/ByteArrayHandler.java
  37. 0 59
      src/de/tudarmstadt/informatik/hostage/handler/StringHandler.java
  38. 8 7
      src/de/tudarmstadt/informatik/hostage/io/ByteArrayReaderWriter.java
  39. 6 5
      src/de/tudarmstadt/informatik/hostage/io/ReaderWriter.java
  40. 9 6
      src/de/tudarmstadt/informatik/hostage/io/StringReaderWriter.java
  41. 0 645
      src/de/tudarmstadt/informatik/hostage/logging/DatabaseHandler.java
  42. 30 0
      src/de/tudarmstadt/informatik/hostage/logging/LogResultReceiver.java
  43. 311 80
      src/de/tudarmstadt/informatik/hostage/logging/Logger.java
  44. 38 10
      src/de/tudarmstadt/informatik/hostage/logging/MyLocationManager.java
  45. 162 168
      src/de/tudarmstadt/informatik/hostage/logging/Record.java
  46. 0 89
      src/de/tudarmstadt/informatik/hostage/logging/SQLLogger.java
  47. 798 0
      src/de/tudarmstadt/informatik/hostage/logging/UglyDbHelper.java
  48. 28 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/DefaultFormatter.java
  49. 23 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/Formatter.java
  50. 25 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/TraCINgFormatter.java
  51. 103 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/protocol/MySQL.java
  52. 45 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/protocol/ProtocolFormatter.java
  53. 225 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/protocol/SMB.java
  54. 149 0
      src/de/tudarmstadt/informatik/hostage/logging/formatter/protocol/TELNET.java
  55. 21 11
      src/de/tudarmstadt/informatik/hostage/net/MyServerSocketFactory.java
  56. 20 20
      src/de/tudarmstadt/informatik/hostage/protocol/ECHO.java
  57. 48 39
      src/de/tudarmstadt/informatik/hostage/protocol/FTP.java
  58. 96 0
      src/de/tudarmstadt/informatik/hostage/protocol/GhostProtocol.java
  59. 115 64
      src/de/tudarmstadt/informatik/hostage/protocol/HTTP.java
  60. 24 139
      src/de/tudarmstadt/informatik/hostage/protocol/HTTPS.java
  61. 111 75
      src/de/tudarmstadt/informatik/hostage/protocol/MySQL.java
  62. 10 8
      src/de/tudarmstadt/informatik/hostage/protocol/Protocol.java
  63. 41 0
      src/de/tudarmstadt/informatik/hostage/protocol/SIP.java
  64. 599 483
      src/de/tudarmstadt/informatik/hostage/protocol/SMB.java
  65. 490 306
      src/de/tudarmstadt/informatik/hostage/protocol/SSH.java
  66. 1 2
      src/de/tudarmstadt/informatik/hostage/protocol/SSLProtocol.java
  67. 69 71
      src/de/tudarmstadt/informatik/hostage/protocol/TELNET.java
  68. 275 0
      src/de/tudarmstadt/informatik/hostage/sync/BluetoothSync.java
  69. 182 0
      src/de/tudarmstadt/informatik/hostage/sync/NFCSync.java
  70. 4 0
      src/de/tudarmstadt/informatik/hostage/ui/ListViewAdapter.java
  71. 244 284
      src/de/tudarmstadt/informatik/hostage/ui/MainActivity.java
  72. 96 0
      src/de/tudarmstadt/informatik/hostage/ui/PlayGroundActivity.java
  73. 34 0
      src/de/tudarmstadt/informatik/hostage/ui/SettingsActivity.java
  74. 199 162
      src/de/tudarmstadt/informatik/hostage/ui/ViewLog.java
  75. 15 240
      src/de/tudarmstadt/informatik/hostage/ui/ViewLogTable.java
  76. 12 19
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/RecordOverviewFragment.java
  77. 0 55
      src/de/tudarmstadt/informatik/hostage/wrapper/ByteArray.java
  78. 91 0
      src/de/tudarmstadt/informatik/hostage/wrapper/Packet.java

+ 1 - 0
.classpath

@@ -5,5 +5,6 @@
 	<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
 	<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="output" path="bin/classes"/>
 </classpath>

+ 1 - 0
.gitignore

@@ -29,3 +29,4 @@ target/
 build/
 .gradle/
 gen-external-apklibs/
+

+ 12 - 0
.settings/org.eclipse.jdt.core.prefs

@@ -0,0 +1,12 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
+org.eclipse.jdt.core.compiler.source=1.6

+ 30 - 1
AndroidManifest.xml

@@ -18,6 +18,14 @@
     
     <!-- 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-feature
+        android:name="android.hardware.nfc"
+        android:required="false" />
 
     <application
         android:allowBackup="true"
@@ -37,6 +45,7 @@
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
+        <!--
         <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.MainActivity"
             android:configChanges="keyboardHidden|orientation|screenSize"
@@ -50,17 +59,37 @@
             android:name="de.tudarmstadt.informatik.hostage.ui.ViewLogTable"
             android:label="@string/database" >
         </activity>
+        -->
         <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.SettingsActivity"
             android:label="@string/settings" >
         </activity>
         <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.AboutActivity"
-            android:label="@string/action_about" >
+            android:label="@string/gui_action_about" >
+        </activity>
+        <activity
+            android:name="de.tudarmstadt.informatik.hostage.ui.PlayGroundActivity"
+            android:label="@string/gui_playground" >
+        </activity>
+        <activity
+            android:name="de.tudarmstadt.informatik.hostage.sync.NFCSync"
+            android:label="@string/gui_playground" >
+            <intent-filter>
+                <action android:name="android.nfc.action.NDEF_DISCOVERED" />
+
+                <category android:name="android.intent.category.DEFAULT" />
+
+                <data android:mimeType="application/de.tudarmstadt.informatik.hostage" />
+            </intent-filter>
         </activity>
 
         <service android:name="de.tudarmstadt.informatik.hostage.HoneyService" >
         </service>
+        <service
+            android:name="de.tudarmstadt.informatik.hostage.logging.Logger"
+            android:exported="false" >
+        </service>
     </application>
 
 </manifest>

BIN
assets/p


BIN
libs/sshlib-v1.1.jar


+ 4 - 0
lint.xml

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

+ 1 - 1
native/Makefile

@@ -17,4 +17,4 @@ clean:
 	rm -f *.o $(EXE)
 
 install:
-	cp $(EXE) ../assets
+	adb push p /data/local

BIN
native/p


+ 7 - 1
native/p.c

@@ -12,7 +12,7 @@
 
 #include <android/log.h>
 
-#define  LOG_TAG "hostage: bindport"
+#define  LOG_TAG "hostage: p"
 #define  LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
 #define  LOGW(...) __android_log_print(ANDROID_LOG_WARN,LOG_TAG,__VA_ARGS__)
 #define  LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
@@ -45,6 +45,7 @@ int ipc_sock() {
 
 int net_sock(int port) {
 	int fd;
+	int reuse = 1;
 	struct sockaddr_in addr;
 
 	if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
@@ -57,6 +58,11 @@ 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 socketopt: %d", errno); 
+		return -1; 
+	}
+
 	if (bind(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
 		LOGE("Unable to bind net socket: %d", errno);
 		return -1;

BIN
native/p.o


+ 18 - 11
res/layout/activity_main.xml

@@ -23,7 +23,7 @@
                 android:layout_height="wrap_content"
                 android:layout_above="@+id/imageViewLight"
                 android:layout_centerHorizontal="true"
-                android:text="@string/status"
+                android:text="@string/gui_status"
                 android:textAppearance="?android:attr/textAppearanceLarge" />
 
             <ImageView
@@ -40,7 +40,7 @@
                 android:layout_height="wrap_content"
                 android:layout_alignParentBottom="true"
                 android:layout_alignParentLeft="true"
-                android:text="@string/paranoid" />
+                android:text="@string/gui_paranoid" />
 
             <ToggleButton
                 android:id="@+id/toggleButtonOnOff"
@@ -49,8 +49,8 @@
                 android:layout_alignParentBottom="true"
                 android:layout_alignParentRight="true"
                 android:onClick="buttonOnOffClick"
-                android:textOff="@string/capital_off"
-                android:textOn="@string/capital_on" />
+                android:textOff="@string/gui_capital_off"
+                android:textOn="@string/gui_capital_on" />
 
             <Button
                 android:id="@+id/buttonShowLog"
@@ -61,7 +61,14 @@
                 android:onClick="showLog"
                 android:text="Show Log" />
 
-
+            <Button
+                android:id="@+id/buttonPlayGround"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_alignParentTop="true"
+                android:layout_toRightOf="@+id/buttonShowLog"
+                android:onClick="startPlayGround"
+                android:text="PlayGround" />
 
         </RelativeLayout>
 
@@ -74,7 +81,7 @@
                 android:id="@+id/textViewDetails"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
-                android:text="@string/details"
+                android:text="@string/gui_details"
                 android:textAppearance="?android:attr/textAppearanceLarge" />
 
             <LinearLayout
@@ -86,7 +93,7 @@
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:paddingLeft="20dp"
-                    android:text="@string/ssid"
+                    android:text="@string/gui_ssid"
                     android:textAppearance="?android:attr/textAppearanceMedium" />
 
                 <TextView
@@ -107,7 +114,7 @@
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:paddingLeft="20dp"
-                    android:text="@string/bssid"
+                    android:text="@string/gui_bssid"
                     android:textAppearance="?android:attr/textAppearanceMedium" />
 
                 <TextView
@@ -128,7 +135,7 @@
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:paddingLeft="20dp"
-                    android:text="@string/internal_ip"
+                    android:text="@string/gui_internal_ip"
                     android:textAppearance="?android:attr/textAppearanceMedium" />
 
                 <TextView
@@ -149,7 +156,7 @@
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:paddingLeft="20dp"
-                    android:text="@string/external_ip"
+                    android:text="@string/gui_external_ip"
                     android:textAppearance="?android:attr/textAppearanceMedium" />
 
                 <TextView
@@ -165,7 +172,7 @@
                 android:id="@+id/TextViewServices"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
-                android:text="@string/services"
+                android:text="@string/gui_services"
                 android:textAppearance="?android:attr/textAppearanceLarge" />
 
             <ListView

+ 17 - 0
res/layout/activity_nfc.xml

@@ -0,0 +1,17 @@
+<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" >
+
+    <TextView
+        android:id="@+id/textView"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text="NFC - SYNC" />
+
+</LinearLayout>

+ 52 - 0
res/layout/activity_playground.xml

@@ -0,0 +1,52 @@
+<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" >
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:orientation="horizontal" >
+
+        <Button
+            android:id="@+id/buttonSyncServer"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:onClick="syncData"
+            android:text="Sync Data" />
+        
+        <Button
+            android:id="@+id/buttonStartNFC"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:onClick="startNFC"
+            android:text="start NFC" />
+
+    </LinearLayout>
+
+    <Button
+        android:id="@+id/buttonCreateNetwork"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:onClick="createNetworkData"
+        android:text="Create Network Data" />
+
+    <ScrollView
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        >
+
+        <TextView
+            android:id="@+id/textView1"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="TextView" />
+         
+    </ScrollView>
+
+</LinearLayout>

+ 5 - 5
res/layout/activity_viewlog.xml

@@ -17,7 +17,7 @@
             android:id="@+id/textStatistics"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
-            android:text="@string/statistics"
+            android:text="@string/gui_statistics"
             android:textAppearance="?android:attr/textAppearanceLarge" />
 
         <TableLayout
@@ -36,7 +36,7 @@
                 android:id="@+id/textFirstAttack"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
-                android:text="@string/firstAttack"
+                android:text="@string/gui_firstAttack"
                 android:textAppearance="?android:attr/textAppearanceMedium" />
 
             <TextView
@@ -57,7 +57,7 @@
                 android:id="@+id/textLastAttack"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
-                android:text="@string/lastAttack"
+                android:text="@string/gui_lastAttack"
                 android:textAppearance="?android:attr/textAppearanceMedium" />
 
             <TextView
@@ -73,7 +73,7 @@
             android:id="@+id/textLogFile"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
-            android:text="@string/log_actions"
+            android:text="@string/gui_log_actions"
             android:textAppearance="?android:attr/textAppearanceLarge" />
 
         <LinearLayout
@@ -124,4 +124,4 @@
             android:orientation="vertical" >
         </TableLayout>
 
-</RelativeLayout>
+</RelativeLayout>

+ 1 - 1
res/layout/list_view_protocols_row.xml

@@ -30,7 +30,7 @@
                 android:id="@+id/textViewConnections"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
-                android:text="@string/connections"
+                android:text="@string/gui_connections"
                 android:textAppearance="?android:attr/textAppearanceSmall" />
 
             <TextView

+ 2 - 2
res/menu/main.xml

@@ -4,12 +4,12 @@
         android:id="@+id/action_settings"
         android:orderInCategory="100"
         android:showAsAction="never"
-        android:title="@string/action_settings"/>
+        android:title="@string/gui_action_settings"/>
     
     <item
         android:id="@+id/action_about"
         android:orderInCategory="100"
         android:showAsAction="never"
-        android:title="@string/action_about"/>
+        android:title="@string/gui_action_about"/>
 
 </menu>

+ 2 - 0
res/values/protocols.xml

@@ -4,10 +4,12 @@
     <string-array name="protocols">
 		<item>ECHO</item>
         <item>FTP</item>
+        <item>GhostProtocol</item>
         <item>HTTP</item>
         <item>HTTPS</item>
         <item>MySQL</item>
         <item>SMB</item>
+        <item>SSH</item>
         <item>TELNET</item>
     </string-array>
 

+ 5 - 3
res/values/strings.xml

@@ -44,7 +44,9 @@
     <string name="drawer_profile_manager">Profile Manager</string>
     <string name="drawer_app_info">Application info</string>
 
-        <string name="button_title_apply">Apply</string>
-            <string name="button_title_cancel">Cancel</string>
-        
+    <string name="button_title_apply">Apply</string>
+    <string name="button_title_cancel">Cancel</string>
+    <string name="shared_preference_path">de.tudarmstadt.informatik.hostage.preferences</string>
+    <string name="UUID">9fc4f490-659e-11e3-949a-0800200c9a66</string>
+
 </resources>

+ 11 - 0
res/values/strings_broadcast.xml

@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+    
+    <string name="broadcast">de.tudarmstadt.informatik.hostage.BROADCAST</string>    
+    <string name="broadcast_connectivity">de.tudarmstadt.informatik.hostage.BROADCAST.CONNECTIVITY_CHANGE</string>
+    <string name="broadcast_started">de.tudarmstadt.informatik.hostage.BROADCAST.STARTED</string>
+    <string name="broadcast_stopped">de.tudarmstadt.informatik.hostage.BROADCAST.STOPPED</string>
+
+    
+</resources>

+ 13 - 0
res/values/strings_connection_info.xml

@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+    
+   
+    <string name="connection_info">de.tudarmstadt.informatik.hostage.CONNECTION_INFO</string>
+    <string name="connection_info_bssid">de.tudarmstadt.informatik.hostage.CONNECTION_INFO.BSSID</string>
+    <string name="connection_info_ssid">de.tudarmstadt.informatik.hostage.CONNECTION_INFO.SSID</string>
+    <string name="connection_info_internal_ip">de.tudarmstadt.informatik.hostage.CONNECTION_INFO.INTERNAL_IP</string>
+ 	<string name="connection_info_external_ip">de.tudarmstadt.informatik.hostage.CONNECTION_INFO.EXTERNAL_IP</string>  
+
+    
+</resources>

+ 31 - 0
res/values/strings_gui.xml

@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+    <string name="gui_action_about">About</string>
+    <string name="gui_action_settings">Settings</string>
+    <string name="gui_bssid">BSSID:</string>
+    <string name="gui_cancel">Cancel</string>
+    <string name="gui_capital_off">ON</string>
+    <string name="gui_capital_on">OFF</string>
+    <string name="gui_clear">Clear</string>
+    <string name="gui_connections">Recorded connections:</string>
+    <string name="gui_database">Database</string>
+    <string name="gui_delete">Delete</string>
+    <string name="gui_delete_dialog_title">Delete data sets by:</string>
+    <string name="gui_details">Connection info</string>
+    <string name="gui_dialog_clear_database">Clear all data?</string>
+    <string name="gui_dialog_clear_database_date">Delete all data before:</string>
+    <string name="gui_export_dialog_title">Choose Export Format</string>
+    <string name="gui_external_ip">External IP:</string>
+    <string name="gui_firstAttack">First Attack:</string>
+    <string name="gui_internal_ip">Internal IP:</string>
+    <string name="gui_lastAttack">Last Attack:</string>
+    <string name="gui_log_actions">Actions</string>
+    <string name="gui_paranoid">Paranoid Mode</string>
+    <string name="gui_playground">Playground</string>
+    <string name="gui_services">Services</string>
+    <string name="gui_ssid">SSID:</string>
+    <string name="gui_statistics">Statistics</string>
+    <string name="gui_status">Status</string>
+    
+</resources>

+ 6 - 1
res/values/strings_preferences.xml

@@ -14,12 +14,17 @@
 	<string name="pref_vibration_summ">Enable Vibration</string>
 	<string name="pref_upload">Upload of Records</string>	
 	<string name="pref_upload_server">Server address</string>	
+	<string name="pref_connection_settings">Connection Settings</string>
 	<string name="pref_max_connections">Max Connections</string>	
 	<string name="pref_max_connections_default">5</string>	
 	<string name="pref_timeout">SocketTimeout(in seconds)</string>	
 	<string name="pref_timeout_default">30</string>	
 	<string name="pref_sleeptime">Stream Sleeptime(in mseconds)</string>
 	<string name="pref_sleeptime_default">500</string>
-	<string name="pref_connection_settings">Connection Settings</string>
+	<string name="pref_location_settings">Location Settings</string>
+	<string name="pref_location_time">Time to get Location Data(in mseconds)</string>
+	<string name="pref_location_time_default">60000</string>
+	<string name="pref_location_retries">Retries</string>
+	<string name="pref_location_retries_default">3</string>
 	
 </resources>

+ 13 - 1
res/xml/preferences.xml

@@ -11,7 +11,7 @@
         <EditTextPreference
             android:key="pref_external_location"
             android:dependency="pref_external_storage"
-            android:defaultValue="/HOsTaGe/LogFiles/"
+            android:defaultValue="/HosTaGe/LogFiles/"
             android:title="@string/pref_external_location_title"
             />
         
@@ -55,6 +55,18 @@
             android:defaultValue="@string/pref_sleeptime_default"
             android:title="@string/pref_sleeptime" />
     </PreferenceCategory>
+        <PreferenceCategory android:title="@string/pref_location_settings" >
+        <EditTextPreference
+            android:key="pref_location_time"
+            android:defaultValue="@string/pref_location_time_default"
+            android:title="@string/pref_location_time" />
+               
+          <EditTextPreference
+            android:key="pref_location_retries"
+            android:defaultValue="@string/pref_location_retries_default"
+            android:title="@string/pref_location_retries" />
+          
+    </PreferenceCategory>
 
 
 </PreferenceScreen>

+ 251 - 0
src/de/tudarmstadt/informatik/hostage/HoneyHandler.java

@@ -0,0 +1,251 @@
+package de.tudarmstadt.informatik.hostage;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.Socket;
+import java.util.List;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.content.SharedPreferences.Editor;
+import android.preference.PreferenceManager;
+import android.util.Log;
+import de.tudarmstadt.informatik.hostage.io.ByteArrayReaderWriter;
+import de.tudarmstadt.informatik.hostage.io.ReaderWriter;
+import de.tudarmstadt.informatik.hostage.io.StringReaderWriter;
+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.protocol.Protocol;
+import de.tudarmstadt.informatik.hostage.protocol.Protocol.TALK_FIRST;
+import de.tudarmstadt.informatik.hostage.wrapper.Packet;
+
+/**
+ * Abstract class for a connection handler using a given protocol.
+ * 
+ * @author Mihai Plasoianu
+ * @author Wulf Pfeiffer
+ */
+public class HoneyHandler implements Runnable {
+
+	/** Time until the socket throws a time out. The time is in milliseconds. */
+	private int TIMEOUT;
+	/**
+	 * Time that a inputstream waits if no content is available to read again
+	 * from stream.
+	 */
+	private int SLEEPTIME;
+
+	private HoneyService service;
+	protected Protocol protocol;
+	private Socket client;
+	protected Thread thread;
+
+	private int attack_id;
+	private int message_id = 0;
+	private String externalIP;
+	private String BSSID;
+	private String SSID;
+
+	private HoneyListener listener;
+
+	/**
+	 * Constructor of the class. Initializes class variables for communication
+	 * and logging. Then starts itself in a new Thread.
+	 * 
+	 * @param service
+	 *            The background service.
+	 * @param listener
+	 *            The Listener that called the service.
+	 * @param protocol
+	 *            The protocol on which the handler is running.
+	 * @param client
+	 *            A Socket for the communication with a remote client.
+	 */
+	public HoneyHandler(HoneyService service, HoneyListener listener,
+			Protocol protocol, Socket client) {
+		this.service = service;
+		this.listener = listener;
+		this.protocol = protocol;
+		this.client = client;
+		this.thread = new Thread(this);
+		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(service);
+		SLEEPTIME = pref.getInt("sleeptime", 1); // 1 ms already removes ressource leak
+		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);
+		setSoTimeout(client);
+		thread.start();
+	}
+
+	/**
+	 * Set the timeout of the socket to the hard coded time out variable.
+	 * 
+	 * @param client
+	 *            The socket
+	 * @see #TIMEOUT
+	 */
+	private void setSoTimeout(Socket client) {
+		try {
+			client.setSoTimeout(TIMEOUT);
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+	}
+
+	/**
+	 * Creates InputStream and OutputStream for the socket. Starts communication
+	 * with client. When the client closes the connection or a time out occurs
+	 * the handler is finished.
+	 */
+	@Override
+	public void run() {
+		service.notifyUI(this.getClass().getName(), new String[]{service.getString(R.string.broadcast_started), protocol.toString(), Integer.toString(listener.getPort())});
+		InputStream in;
+		OutputStream out;
+		try {
+			in = client.getInputStream();
+			out = client.getOutputStream();
+			talkToClient(in, out);
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+		kill();
+	}
+
+	/**
+	 * 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())});
+		thread.interrupt();
+		try {
+			client.close();
+			Log.i("HoneyHandler", "Socket closed: " + client.isClosed());
+		} catch (Exception e) {
+			e.printStackTrace();
+		} finally {
+
+		}
+		listener.refreshHandlers();
+	}
+
+	/**
+	 * Determines if the interrupt flag of the thread is set.
+	 * 
+	 * @return True when the flag is set, else false.
+	 */
+	public boolean isTerminated() {
+		return thread.isInterrupted();
+	}
+
+	/**
+	 * Communicates with a client using the corresponding protocol
+	 * implementation.
+	 * 
+	 * @param in
+	 *            InputStream of the socket.
+	 * @param out
+	 *            OutputStream of the socket.
+	 * @throws IOException
+	 */
+	protected void talkToClient(InputStream in, OutputStream out)
+			throws IOException {
+		ReaderWriter stream;
+		if (protocol.getType().equals(byte[].class)) {
+			stream = new ByteArrayReaderWriter(in, out, SLEEPTIME);
+		} else {
+			stream = new StringReaderWriter(in, out);
+		}
+		Packet inputLine;
+		List<Packet> outputLine;
+		if (protocol.whoTalksFirst() == TALK_FIRST.SERVER) {
+			outputLine = protocol.processMessage(null);
+			stream.write(outputLine);
+			for (Packet o : outputLine) {
+				Logger.log(HoneyService.getContext(),
+						createRecord(TYPE.SEND, o.toString()));
+			}
+		}
+		while (!thread.isInterrupted() && (inputLine = stream.read()) != null) {
+			outputLine = protocol.processMessage(inputLine);
+			Logger.log(HoneyService.getContext(),
+					createRecord(TYPE.RECEIVE, inputLine.toString()));
+			if (outputLine != null) {
+				stream.write(outputLine);
+				for (Packet o : outputLine) {
+					Logger.log(HoneyService.getContext(),
+							createRecord(TYPE.SEND, o.toString()));
+				}
+			}
+			if (protocol.isClosed()) {
+				break;
+			}
+		}
+	}
+
+	/**
+	 * Creates a Record for a message exchanged with a client.
+	 * 
+	 * @param type
+	 *            The type of the message.
+	 * @param packet
+	 *            The content of the message.
+	 * @return The Record representing the communication message.
+	 */
+	protected Record createRecord(TYPE type, String packet) {
+		Record record = new Record();
+		record.setId(message_id++);
+		record.setAttack_id(attack_id);
+		record.setProtocol(protocol.toString());
+		record.setType(type);
+		record.setTimestamp(System.currentTimeMillis());
+		record.setExternalIP(externalIP);
+		record.setLocalIP(client.getLocalAddress().getHostAddress());
+		record.setLocalHost(client.getLocalAddress().getHostName());
+		record.setLocalPort(protocol.getDefaultPort());
+		record.setRemoteIP(client.getInetAddress().getHostAddress());
+		record.setRemoteHost(client.getInetAddress().getHostName());
+		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());
+		} else {
+			record.setLatitude(0.0);
+			record.setLongitude(0.0);
+			record.setAccuracy(Float.MAX_VALUE);
+			record.setTimestampLocation(0);
+		}
+		return record;
+	}
+
+	/**
+	 * Gets attack ID for the attack. Also increases the attack ID counter by
+	 * one. Method is synchronized for thread safety.
+	 * 
+	 * @param pref
+	 *            The default SharedPreference of the application
+	 * @return Unique integer attack ID
+	 */
+	private synchronized void getAndIncrementAttackID(SharedPreferences pref) {
+		Editor editor = pref.edit();
+		attack_id = pref.getInt("ATTACK_ID_COUNTER", 0);
+		editor.putInt("ATTACK_ID_COUNTER", attack_id + 1);
+		editor.commit();
+	}
+}

+ 42 - 55
src/de/tudarmstadt/informatik/hostage/HoneyListener.java

@@ -9,31 +9,23 @@ import javax.net.ssl.SSLContext;
 import javax.net.ssl.SSLSocket;
 import javax.net.ssl.SSLSocketFactory;
 
-import android.content.Context;
-import android.content.SharedPreferences;
-import android.content.SharedPreferences.Editor;
-import de.tudarmstadt.informatik.hostage.handler.AbstractHandler;
-import de.tudarmstadt.informatik.hostage.handler.ByteArrayHandler;
-import de.tudarmstadt.informatik.hostage.handler.StringHandler;
 import de.tudarmstadt.informatik.hostage.net.MyServerSocketFactory;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 import de.tudarmstadt.informatik.hostage.protocol.SSLProtocol;
-import de.tudarmstadt.informatik.hostage.ui.MainActivity;
-import de.tudarmstadt.informatik.hostage.wrapper.ByteArray;
 
 /**
  * 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 AbstractHandler}.
+ * {@link HoneyHandler}.
  * 
  * @author Mihai Plasoianu
  * 
  */
 public class HoneyListener implements Runnable {
 
-	private ArrayList<AbstractHandler> handlers = new ArrayList<AbstractHandler>();
+	private ArrayList<HoneyHandler> handlers = new ArrayList<HoneyHandler>();
 
 	/**
 	 * Determines the amount of active handlers.
@@ -44,18 +36,14 @@ public class HoneyListener implements Runnable {
 		return handlers.size();
 	}
 
-	private Protocol<?> protocol;
+	private Protocol protocol;
 	private ServerSocket server;
 	private Thread thread;
+	private int port;
 
 	private HoneyService service;
-	// Shared Preferences
-	private SharedPreferences pref;
 	private ConnectionRegister conReg;
 
-	// Editor for Shared preferences
-	private Editor editor;
-
 	private boolean running = false;
 
 	/**
@@ -75,12 +63,17 @@ public class HoneyListener implements Runnable {
 	 * @param protocol
 	 *            The Protocol on which the listener is running.
 	 */
-	public HoneyListener(HoneyService service, Protocol<?> protocol) {
+	public HoneyListener(HoneyService service, Protocol protocol) {
+		this.service = service;
+		this.protocol = protocol;
+		port = protocol.getDefaultPort();
+		conReg = new ConnectionRegister(service);
+	}
+	
+	public HoneyListener(HoneyService service, Protocol protocol, int port) {
 		this.service = service;
 		this.protocol = protocol;
-		pref = service.getApplicationContext().getSharedPreferences(
-				MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
-		editor = pref.edit();
+		this.port = port;
 		conReg = new ConnectionRegister(service);
 	}
 
@@ -88,7 +81,7 @@ public class HoneyListener implements Runnable {
 		while (!thread.isInterrupted()) {
 			addHandler();
 		}
-		for (AbstractHandler handler : handlers) {
+		for (HoneyHandler handler : handlers) {
 			handler.kill();
 		}
 	}
@@ -97,17 +90,17 @@ public class HoneyListener implements Runnable {
 	 * Starts the listener. Creates a server socket runs itself in a new Thread
 	 * and notifies the background service.
 	 */
-	public void start() {
+	public boolean start() {
 		try {
-			server = new MyServerSocketFactory().createServerSocket(protocol
-					.getPort());
-			(this.thread = new Thread(this)).start();
-			editor.putBoolean(protocol + MainActivity.LISTENER, true);
-			editor.commit();
-			service.notifyUI(protocol.toString(), MainActivity.LISTENER);
+			server = new MyServerSocketFactory().createServerSocket(port);
+			if(server == null) return false;
+			(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)});
+			return true;
 		} catch (Exception e) {
 			e.printStackTrace();
+			return false;
 		}
 	}
 
@@ -119,10 +112,8 @@ public class HoneyListener implements Runnable {
 		try {
 			server.close();
 			thread.interrupt();
-			editor.putBoolean(protocol + MainActivity.LISTENER, false);
-			editor.commit();
-			service.notifyUI(protocol.toString(), MainActivity.LISTENER);
 			running = false;
+			service.notifyUI(this.getClass().getName(), new String[]{service.getString(R.string.broadcast_stopped), protocol.toString(), Integer.toString(port)});
 		} catch (Exception e) {
 			e.printStackTrace();
 		}
@@ -136,14 +127,23 @@ public class HoneyListener implements Runnable {
 	public String getProtocolName() {
 		return protocol.toString();
 	}
+	
+	/**
+	 * Return the port number on which the listener listening.
+	 * 
+	 * @return Used port number.
+	 */
+	public int getPort() {
+		return port;
+	}
 
 	/**
 	 * Remove all terminated handlers from its internal ArrayList.
 	 */
 	public void refreshHandlers() {
-		for (Iterator<AbstractHandler> iterator = handlers.iterator(); iterator
+		for (Iterator<HoneyHandler> iterator = handlers.iterator(); iterator
 				.hasNext();) {
-			AbstractHandler handler = iterator.next();
+			HoneyHandler handler = iterator.next();
 			if (handler.isTerminated()) {
 				conReg.closeConnection();
 				iterator.remove();
@@ -153,7 +153,7 @@ public class HoneyListener implements Runnable {
 
 	/**
 	 * Waits for an incoming connection, accepts it and starts a
-	 * {@link AbstractHandler}
+	 * {@link HoneyHandler}
 	 */
 	private void addHandler() {
 		if (conReg.isConnectionFree()) {
@@ -165,13 +165,6 @@ public class HoneyListener implements Runnable {
 				} else {
 					startHandler(client);
 				}
-				int handlerCount = pref.getInt(protocol
-						+ MainActivity.HANDLER_COUNT, 0);
-				editor.putInt(protocol + MainActivity.HANDLER_COUNT,
-						handlerCount + 1);
-				editor.commit();
-				service.notifyUI(protocol.toString(),
-						MainActivity.HANDLER_COUNT);
 			} catch (Exception e) {
 				e.printStackTrace();
 			}
@@ -180,14 +173,14 @@ public class HoneyListener implements Runnable {
 
 	/**
 	 * Creates a SSLSocket out of the given socket and starts a
-	 * {@link AbstractHandler}.
+	 * {@link HoneyHandler}.
 	 * 
 	 * @param client
 	 *            The socket with the accepted connection.
 	 * @throws Exception
 	 */
 	private void startSecureHandler(Socket client) throws Exception {
-		SSLContext sslContext = ((SSLProtocol<?>) protocol).getSSLContext();
+		SSLContext sslContext = ((SSLProtocol) protocol).getSSLContext();
 		SSLSocketFactory factory = sslContext.getSocketFactory();
 		SSLSocket sslClient = (SSLSocket) factory.createSocket(client, null,
 				client.getPort(), false);
@@ -197,7 +190,7 @@ public class HoneyListener implements Runnable {
 	}
 
 	/**
-	 * Starts a {@link AbstractHandler} with the given socket.
+	 * Starts a {@link HoneyHandler} with the given socket.
 	 * 
 	 * @param client
 	 *            The socket with the accepted connection.
@@ -209,7 +202,7 @@ public class HoneyListener implements Runnable {
 	}
 
 	/**
-	 * Creates a new instance of an {@link AbstractHandler}.
+	 * Creates a new instance of an {@link HoneyHandler}.
 	 * 
 	 * @param service
 	 *            The background service
@@ -219,17 +212,11 @@ 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 AbstractHandler} with the specified
+	 * @return A Instance of a {@link HoneyHandler} with the specified
 	 *         parameter.
 	 */
-	private AbstractHandler newInstance(HoneyService service,
-			HoneyListener listener, Protocol<?> protocol, Socket client) {
-		if (protocol.getType().equals(String.class)) {
-			return new StringHandler(service, listener, protocol, client);
-		} else if (protocol.getType().equals(ByteArray.class)) {
-			return new ByteArrayHandler(service, listener, protocol, client);
-		} else {
-			return null;
-		}
+	private HoneyHandler newInstance(HoneyService service,
+			HoneyListener listener, Protocol protocol, Socket client) {
+		return new HoneyHandler(service, listener, protocol, client);
 	}
 }

+ 426 - 181
src/de/tudarmstadt/informatik/hostage/HoneyService.java

@@ -1,8 +1,21 @@
 package de.tudarmstadt.informatik.hostage;
 
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.net.Socket;
+import java.security.SecureRandom;
 import java.util.ArrayList;
+import java.util.LinkedList;
 import java.util.List;
 
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.util.EntityUtils;
+import org.json.JSONObject;
+
 import android.app.NotificationManager;
 import android.app.PendingIntent;
 import android.app.Service;
@@ -14,6 +27,7 @@ import android.content.SharedPreferences;
 import android.content.SharedPreferences.Editor;
 import android.net.ConnectivityManager;
 import android.net.Uri;
+import android.os.AsyncTask;
 import android.os.Binder;
 import android.os.IBinder;
 import android.preference.PreferenceManager;
@@ -23,37 +37,45 @@ import android.support.v4.content.LocalBroadcastManager;
 import android.util.Log;
 import android.widget.Toast;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-import de.tudarmstadt.informatik.hostage.logging.DatabaseHandler;
-import de.tudarmstadt.informatik.hostage.logging.Logger;
 import de.tudarmstadt.informatik.hostage.logging.MyLocationManager;
-import de.tudarmstadt.informatik.hostage.logging.SQLLogger;
+import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
+import de.tudarmstadt.informatik.hostage.protocol.HTTP;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 import de.tudarmstadt.informatik.hostage.ui.MainActivity;
+
 /**
  * Background service running as long as at least one protocol is active.
- * Service controls start and stop of protocol listener.
- * Notifies GUI about events happening in the background.
- * Creates Notifications to inform the user what it happening.
- * @author Mihai Plasoianu 
+ * Service controls start and stop of protocol listener. Notifies GUI about
+ * events happening in the background. Creates Notifications to inform the user
+ * what it happening.
+ * 
+ * @author Mihai Plasoianu
  * @author Lars Pandikow
+ * @author Wulf Pfeiffer
  */
 public class HoneyService extends Service {
 
+	private static Context context;
+
+	/**
+	 * Returns the application context.
+	 * 
+	 * @return context.
+	 */
+	public static Context getContext() {
+		return HoneyService.context;
+	}
+
+	private LinkedList<Protocol> implementedProtocols;
 	private ArrayList<HoneyListener> listeners = new ArrayList<HoneyListener>();
 	private NotificationCompat.Builder builder;
-	private SharedPreferences sessionPref;
-	private Editor editor;
+	private SharedPreferences connectionInfo;
+	private Editor connectionInfoEditor;
 
 	public List<HoneyListener> getListeners() {
 		return listeners;
 	}
 
-	private Logger log;
-
-	public Logger getLog() {
-		return log;
-	}
-
 	private final IBinder mBinder = new LocalBinder();
 
 	public class LocalBinder extends Binder {
@@ -70,58 +92,65 @@ public class HoneyService extends Service {
 	@Override
 	public void onCreate() {
 		super.onCreate();
-		log = new SQLLogger(getApplicationContext());
-		sessionPref = getSharedPreferences(MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
-		editor = sessionPref.edit();
+		HoneyService.context = getApplicationContext();
+		implementedProtocols = getImplementedProtocols();
+		connectionInfo = getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
+		connectionInfoEditor = connectionInfo.edit();
 		createNotification();
-		for (Protocol<?> protocol : getProtocolArray()) {
-			listeners.add(new HoneyListener(this, protocol));
-		}
 		registerNetReceiver();
+		updateConnectionInfo();
 		getLocationData();
+		
+		String sharedPreferencePath = getString(R.string.shared_preference_path);
+		boolean useQotd = getSharedPreferences(sharedPreferencePath , MODE_PRIVATE).getBoolean("useQotd", true);
+		if(useQotd) {
+			new QotdTask().execute(new String[] {});
+		}
+	}
+
+	@Override
+	public int onStartCommand(Intent intent, int flags, int startId) {
+		// We want this service to continue running until it is explicitly
+		// stopped, so return sticky.
+		return START_STICKY;
 	}
-	
-    @Override
-    public int onStartCommand(Intent intent, int flags, int startId) {
-        // We want this service to continue running until it is explicitly
-        // stopped, so return sticky.
-        return START_STICKY;
-    }	
 
 	@Override
 	public void onDestroy() {
 		cancelNotification();
-		super.onDestroy();
 		unregisterNetReceiver();
+		super.onDestroy();
 	}
-	
-	/** Starts an Instance of MyLocationManager to set the location within this class.
+
+	/**
+	 * Starts an Instance of MyLocationManager to set the location within this
+	 * class.
 	 */
-	private void getLocationData(){
+	private void getLocationData() {
 		MyLocationManager locationManager = new MyLocationManager(this);
-		locationManager.getUpdates(60 * 1000);
+		locationManager.getUpdates(60 * 1000, 3);
 	}
-	
+
 	/**
 	 * Deletes all session related data.
 	 */
-	private void deleteSessionData(){
-    	editor.clear();
-    	editor.commit();
+	private void deleteConnectionData() {
+		connectionInfoEditor.clear();
+		connectionInfoEditor.commit();
 	}
-	
+
 	/**
 	 * Register broadcast receiver for connectivity changes
 	 */
 	private void registerNetReceiver() {
-	    // register BroadcastReceiver on network state changes	    
+		// register BroadcastReceiver on network state changes
 		IntentFilter intent = new IntentFilter();
-	    intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); //"android.net.conn.CONNECTIVITY_CHANGE"
-	    registerReceiver(netReceiver, intent);
+		intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // "android.net.conn.CONNECTIVITY_CHANGE"
+		registerReceiver(netReceiver, intent);
 	}
 
 	/**
-	 *  Unregister broadcast receiver for connectivity changes
+	 * Unregister broadcast receiver for connectivity changes
 	 */
 	private void unregisterNetReceiver() {
 		unregisterReceiver(netReceiver);
@@ -129,167 +158,178 @@ public class HoneyService extends Service {
 
 	/**
 	 * Receiver for connectivity change broadcast.
+	 * 
 	 * @see MainActivity#BROADCAST
 	 */
 	private BroadcastReceiver netReceiver = new BroadcastReceiver() {
 		@Override
 		public void onReceive(Context context, Intent intent) {
-				String bssid_old = sessionPref.getString(MainActivity.BSSID, "");
-				String bssid_new = HelperUtils.getBSSID(context);
-				//TODO INFORM UI
-				//TODO CHECK IF OTHER NETWORKS WORK TOO
-				if(bssid_new == null || !bssid_new.equals(bssid_old)){
-					getLocationData();
-					String[] protocols = getResources().getStringArray(R.array.protocols);
-					for (String protocol : protocols) {
-						editor.remove(protocol + MainActivity.HANDLER_COUNT);
-					}						
-					notifyUI("SERVICE", "CONNECTIVITY_CHANGE");
-				}
-		}
-	};	
-
-
-	/**
-	 * Creates a Notification in the notification bar.
-	 */
-	private void createNotification() {
-		DatabaseHandler dbh = new DatabaseHandler(this);
-		boolean activeHandlers = false;
-		boolean bssidSeen = false;
-		
-		for(String protocol : getResources().getStringArray(R.array.protocols)){
-			int handlerCount = sessionPref.getInt(protocol + MainActivity.HANDLER_COUNT, 0);
-			if(handlerCount > 0){
-				activeHandlers = true;
-			}
-			if(dbh.bssidSeen(protocol, HelperUtils.getBSSID(getApplicationContext()))){
-				bssidSeen = true;
+			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)});
 			}
 		}
-		builder = new NotificationCompat.Builder(this)
-										.setContentTitle(getString(R.string.app_name))
-										.setWhen(System.currentTimeMillis());	
-		if(activeHandlers){
-			builder.setSmallIcon(R.drawable.ic_service_red);
-			builder.setContentText("Network is infected!");
-		} else if(bssidSeen){
-			builder.setSmallIcon(R.drawable.ic_service_yellow);
-			builder.setContentText("Network has been infected in previous session!");
-		} else{
-			builder.setSmallIcon(R.drawable.ic_service_green);
-			builder.setContentText("Everything looks fine!");
-		}				
-		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
-		stackBuilder.addParentStack(MainActivity.class);
-		stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
-		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
-				PendingIntent.FLAG_UPDATE_CURRENT);
-		builder.setContentIntent(resultPendingIntent);
-		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
-		mNotificationManager.notify(1, builder.build());
-	}
+	};
 	
-	/**
-	 * Updates the notification when a attack is registered.
-	 */
-	private void updateNotification() {
-		SharedPreferences defaultPref = PreferenceManager.getDefaultSharedPreferences(this);
-		String strRingtonePreference = defaultPref.getString("pref_notification_sound", "content://settings/system/notification_sound");  
-		builder = new NotificationCompat.Builder(this)
-				.setContentTitle(getString(R.string.app_name))
-				.setTicker("Honeypot under attack!")
-				.setContentText("Network is infected!")
-				.setSmallIcon(R.drawable.ic_service_red)
-				.setAutoCancel(true)
-				.setWhen(System.currentTimeMillis())
-				.setSound(Uri.parse(strRingtonePreference)); 
-		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
-		stackBuilder.addParentStack(MainActivity.class);
-		stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
-		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
-				PendingIntent.FLAG_UPDATE_CURRENT);
-		builder.setContentIntent(resultPendingIntent);
-		if(defaultPref.getBoolean("pref_vibration", false)){
-			builder.setVibrate(new long[]{100, 200, 100, 200});
-		} 
-
-		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
-		mNotificationManager.notify(1, builder.build());
-	}
 
 	/**
-	 * Cancels the Notification
+	 * Notifies the GUI about a event.
+	 * 
+	 * @param sender
+	 *            Source where the event took place.
+	 * @param key
+	 *            Detailed information about the event.
 	 */
-	private void cancelNotification() {
-		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
-		mNotificationManager.cancel(1);
+	public void notifyUI(String sender, String[] values) {
+		createNotification();
+		// Send Notification
+		if (sender.equals(HoneyHandler.class.getName()) && values[0].equals(R.string.broadcast_started)) {
+			attackNotification();
+		}
+		// Inform UI of Preference Change
+		Intent intent = new Intent(getString(R.string.broadcast));
+		intent.putExtra("SENDER", sender);
+		intent.putExtra("VALUES", values);
+		Log.i("Sender" ,sender);
+		LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
 	}
+	
 
 
 	/**
-	 * Creates a instance of each protocol defined in /res/values/protocols.xml and puts it in a List
-	 * @return ArrayList of {@link de.tudarmstadt.informatik.hostage.protocol.Protocol Protocol}
+	 * Returns an LinkedList<String> with the names of all implemented protocols.
+	 * 
+	 * @return ArrayList of
+	 *         {@link de.tudarmstadt.informatik.hostage.protocol.Protocol
+	 *         Protocol}
 	 */
-	private ArrayList<Protocol<?>> getProtocolArray() {
+	private LinkedList<Protocol> getImplementedProtocols() {
 		String[] protocols = getResources().getStringArray(R.array.protocols);
 		String packageName = Protocol.class.getPackage().getName();
-		ArrayList<Protocol<?>> protocolArray = new ArrayList<Protocol<?>>();
+		LinkedList<Protocol> implementedProtocols = new LinkedList<Protocol>();
 
 		for (String protocol : protocols) {
 			try {
-				protocolArray.add((Protocol<?>) Class.forName(
-						String.format("%s.%s", packageName, protocol))
-						.newInstance());
+				implementedProtocols.add((Protocol) Class.forName(String.format("%s.%s", packageName, protocol)).newInstance());
 			} catch (Exception e) {
 				e.printStackTrace();
 			}
 		}
-		return protocolArray;
+		return implementedProtocols;
 	}
 	
 	/**
-	 * Determines if there are running listeners.
+	 * Returns the default port number, if the protocol is implemented.
+	 * @param protocolName The name of the protocol
+	 * @return Returns the default port number, if the protocol is implemented. Else returns -1.
+	 */
+	private int getDefaultPort(String protocolName){
+		for (Protocol protocol : implementedProtocols) {
+			if(protocolName.equals(protocol.toString())){
+				return protocol.getDefaultPort();
+			}
+		}
+		return -1;
+	}
+
+	/**
+	 * Determines if there any listener is currently running.
+	 * 
 	 * @return True if there is a running listener, else false.
 	 */
-	public boolean hasRunningListeners(){
+	public boolean hasRunningListeners() {
 		for (HoneyListener listener : listeners) {
-				if (listener.isRunning())
-					return true;
+			if (listener.isRunning())
+				return true;
 		}
 		return false;
 	}
+	
+	/**
+	 * Determines if a protocol with the given name is running on its default port.
+	 * @param protocolName The protocol name
+	 * @return True if protocol is running, else false.
+	 */
+	public boolean isRunning(String protocolName){
+		int port = getDefaultPort(protocolName);
+		return isRunning(protocolName, port);
+	}
+	
+	/**
+	 * Determines if a protocol with the given name is running on the given port.
+	 * @param protocolName The protocol name
+	 * @param port Specific port
+	 * @return True if protocol is running, else false.
+	 */
+	public boolean isRunning(String protocolName, int port){
+		for (HoneyListener listener : listeners) {
+			if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
+				return listener.isRunning();
+			}
+		}	
+		return false;
+	}
+	
+	/**
+	 * Determines the number of active connections for a protocol running on its default port.
+	 * @param protocolName The protocol name
+	 * @return Number of active connections
+	 */
+	public int getNumberOfActiveConnections(String protocolName){
+		int port = getDefaultPort(protocolName);
+		return getNumberOfActiveConnections(protocolName, port);
+	}
+	
+	/**
+	 * Determines the number of active connections for a protocol running on the given port.
+	 * @param protocolName The protocol name
+	 * @param port Specific port
+	 * @return Number of active connections
+	 */
+	public int getNumberOfActiveConnections(String protocolName, int port){
+		for (HoneyListener listener : listeners) {
+			if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
+				return listener.getHandlerCount();
+			}
+		}	
+		return 0;
+	}
 
 	/**
-	 * Notifies the GUI about a event.
-	 * @param protocol The protocol where the event happened.
-	 * @param key The key for the event.
+	 * Creates a Listener for a given protocol on a specific port. 
+	 * After creation the Listener is not started.
+	 * Checks if the protocol is implemented first.
+	 * 
+	 * @param protocolName Name of the protocol
+	 * @param port Port on which to start the Listener
+	 * @return Returns the created HoneyListener, if creation failed returns null.
 	 */
-	public void notifyUI(String sender, String key) {
-		// Send Notification
-		if (key.equals(MainActivity.HANDLER_COUNT)){
-			updateNotification();
-		}else if(key.equals("CONNECTIVITY_CHANGE")){
-			createNotification();
+	private HoneyListener createListener(String protocolName, int port){
+		for(Protocol protocol : implementedProtocols){
+			if(protocolName.equals(protocol.toString())){
+				HoneyListener listener = new HoneyListener(this, protocol, port);
+				listeners.add(listener);
+				return listener;
+			} 
 		}
-		Log.i("HoneyService", key);
-		// Inform UI of Preference Change
-		Intent intent = new Intent(MainActivity.BROADCAST);
-		intent.putExtra("SENDER", sender);
-		intent.putExtra("SENDER", key);
-		LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
-	}	
-	
+		return null;
+	}
+
 	/**
-	 * Starts all listeners which are not already running
+	 * Starts all listeners which are not already running.
 	 */
 	public void startListeners() {
 		for (HoneyListener listener : listeners) {
-			if(!listener.isRunning()){
+			if (!listener.isRunning()) {
 				listener.start();
 			}
 		}
-		Toast.makeText(getApplicationContext(), "SERVICES STARTED!", Toast.LENGTH_SHORT).show();
+		Toast.makeText(getApplicationContext(), "SERVICES STARTED!",
+				Toast.LENGTH_SHORT).show();
 	}
 
 	/**
@@ -297,36 +337,79 @@ public class HoneyService extends Service {
 	 */
 	public void stopListeners() {
 		for (HoneyListener listener : listeners) {
-			if(listener.isRunning()){
+			if (listener.isRunning()) {
 				listener.stop();
 			}
 		}
-		Toast.makeText(getApplicationContext(), "SERVICES STOPPED!", Toast.LENGTH_SHORT).show();
+		Toast.makeText(getApplicationContext(), "SERVICES STOPPED!",
+				Toast.LENGTH_SHORT).show();
 	}
 
 	/**
-	 * Starts the listener for the specified protocol.
-	 * @param protocolName Name of the protocol that should be started.
-	 */ 
-	public void startListener(String protocolName) {
+	 * Starts the listener for the specified protocol. 
+	 * Creates a new HoneyService if no matching HoneyListener is found.
+	 * 
+	 * @param protocolName
+	 *            Name of the protocol that should be started.
+	 */
+	public boolean startListener(String protocolName) {
+		return startListener(protocolName, getDefaultPort(protocolName));
+	}
+	
+	/**
+	 * Starts the listener for the specified protocol and port.
+	 * Creates a new HoneyService if no matching HoneyListener is found.
+	 * 
+	 * @param protocolName
+	 *            Name of the protocol that should be started.
+	 * @param port The port number in which the listener should run.
+	 */
+	public boolean startListener(String protocolName, int port) {
 		for (HoneyListener listener : listeners) {
-			if (listener.getProtocolName().equals(protocolName)) {
-				if(!listener.isRunning()){
-					listener.start();
+			if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
+				if (!listener.isRunning()) {
+					if(listener.start()){
+						Toast.makeText(getApplicationContext(),protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
+						return true;
+					}
+					Toast.makeText(getApplicationContext(),protocolName + " SERVICE COULD NOT BE STARTED!", Toast.LENGTH_SHORT).show();
+					return false;
 				}
+				
 			}
 		}
-		Toast.makeText(getApplicationContext(), protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
+		HoneyListener listener = createListener(protocolName, port);
+		if(listener != null){
+			if(listener.start()){
+				Toast.makeText(getApplicationContext(), protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
+				return true;
+			}
+		}	
+		Toast.makeText(getApplicationContext(),protocolName + " SERVICE COULD NOT BE STARTED!", Toast.LENGTH_SHORT).show();
+		return false;
 	}
 
 	/**
 	 * Stops the listener for the specified protocol.
-	 * @param protocolName Name of the protocol that should be stopped.
-	 */ 
+	 * 
+	 * @param protocolName
+	 *            Name of the protocol that should be stopped.
+	 */
 	public void stopListener(String protocolName) {
+		stopListener(protocolName, getDefaultPort(protocolName));
+	}
+	
+	/**
+	 * Stops the listener for the specified protocol.
+	 * 
+	 * @param protocolName
+	 *            Name of the protocol that should be stopped.
+	 * @param port 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)) {
-				if(listener.isRunning()){
+			if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
+				if (listener.isRunning()) {
 					listener.stop();
 				}
 			}
@@ -335,19 +418,181 @@ public class HoneyService extends Service {
 	}
 
 	/**
-	 * Toggles a listener for specified protocol.
-	 * @param protocolName Name of the protocol that should be toggled.
+	 * Task for accuiring a qotd from one of four possible servers.
+	 * 
+	 * @author Wulf Pfeiffer
 	 */
-	public void toggleListener(String protocolName) {
-		for (HoneyListener listener : listeners) {
-			if (listener.getProtocolName().equals(protocolName)) {
-				if (listener.isRunning()) {
-					stopListener(protocolName);
-				} else {
-					startListener(protocolName);
+	private class QotdTask extends AsyncTask<String, Void, String> {
+		@Override
+		protected String doInBackground(String... unused) {
+			String[] sources = new String[] { "djxmmx.net", "ota.iambic.com",
+					"alpha.mike-r.com", "electricbiscuit.org" };
+			SecureRandom rndm = new SecureRandom();
+			StringBuffer sb = new StringBuffer();
+			try {
+				Socket client = new Socket(sources[rndm.nextInt(4)], 17);
+				BufferedReader in = new BufferedReader(new InputStreamReader(
+						client.getInputStream()));
+				while (!in.ready())
+					;
+				while (in.ready()) {
+					sb.append(in.readLine());
 				}
+				in.close();
+				client.close();
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+			return sb.toString();
+		}
+
+		@Override
+		protected void onPostExecute(String result) {
+			if (result != null)
+				HTTP.setHtmlDocumentContent(result);
+		}
+	};
+	
+	/**
+	 * Updates the connection info and saves them in the the SharedPreferences
+	 * for session data.
+	 * 
+	 * @param context
+	 *            Needs a context to get system recourses.
+	 * @see MainActivity#CONNECTION_INFO
+	 */
+	private void updateConnectionInfo() {
+		SharedPreferences pref = context.getSharedPreferences(
+				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.commit();
+		SetExternalIPTask async = new SetExternalIPTask();
+		async.execute(new String[] { "http://ip2country.sourceforge.net/ip2c.php?format=JSON" });
+	}
+	
+	/**
+	 * Task to find out the external IP.
+	 * 
+	 * @author Lars Pandikow
+	 */
+	private class SetExternalIPTask extends AsyncTask<String, Void, String> {
+		@Override
+		protected String doInBackground(String... url) {
+			String ipAddress = null;
+			try {
+				HttpClient httpclient = new DefaultHttpClient();
+				HttpGet httpget = new HttpGet(url[0]);
+				HttpResponse response;
+
+				response = httpclient.execute(httpget);
+
+				HttpEntity entity = response.getEntity();
+				entity.getContentLength();
+				String str = EntityUtils.toString(entity);
+				JSONObject json_data = new JSONObject(str);
+				ipAddress = json_data.getString("ip");
+			} catch (Exception e) {
+				e.printStackTrace();
+			}
+			return ipAddress;
+		}
+
+		@Override
+		protected void onPostExecute(String result) {
+			connectionInfoEditor.putString(getString(R.string.connection_info_external_ip), result);
+			connectionInfoEditor.commit();
+			notifyUI(this.getClass().getName(), new String[]{getString(R.string.broadcast_connectivity)});
+		}
+	};
+	
+	// Notifications
+	
+	/**
+	 * Creates a Notification in the notification bar.
+	 */
+	private void createNotification() {
+		UglyDbHelper dbh = new UglyDbHelper(this);
+		boolean activeHandlers = false;
+		boolean bssidSeen = false;
+		boolean listening = false;
+
+		for (HoneyListener listener : listeners) {
+			if(listener.isRunning())
+				listening = true;
+			if (listener.getHandlerCount() > 0) {
+				activeHandlers = true;
+			}
+			if (dbh.bssidSeen(listener.getProtocolName(), HelperUtils.getBSSID(getApplicationContext()))) {
+				bssidSeen = true;
 			}
 		}
+		builder = new NotificationCompat.Builder(this).setContentTitle(
+				getString(R.string.app_name)).setWhen(
+				System.currentTimeMillis());
+		if(!listening){
+			builder.setSmallIcon(R.drawable.ic_launcher);
+			builder.setContentText("HosTaGe is not active.");
+		} else if (activeHandlers) {
+			builder.setSmallIcon(R.drawable.ic_service_red);
+			builder.setContentText("Network is infected!");
+		} else if (bssidSeen) {
+			builder.setSmallIcon(R.drawable.ic_service_yellow);
+			builder.setContentText("Network has been infected in previous session!");
+		} else{
+			builder.setSmallIcon(R.drawable.ic_service_green);
+			builder.setContentText("Everything looks fine!");
+		} 
+		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
+		stackBuilder.addParentStack(MainActivity.class);
+		stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
+		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
+				PendingIntent.FLAG_UPDATE_CURRENT);
+		builder.setContentIntent(resultPendingIntent);
+		builder.setOngoing(true);
+		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
+		mNotificationManager.notify(1, builder.build());
+	}
+
+	/**
+	 * 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())
+				.setSound(Uri.parse(strRingtonePreference));
+		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
+		stackBuilder.addParentStack(MainActivity.class);
+		stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
+		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
+				PendingIntent.FLAG_UPDATE_CURRENT);
+		builder.setContentIntent(resultPendingIntent);
+		if (defaultPref.getBoolean("pref_vibration", false)) {
+			builder.setVibrate(new long[] { 100, 200, 100, 200 });
+		}
+
+		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
+		mNotificationManager.notify(2, builder.build());
+	}
+
+	/**
+	 * Cancels the Notification
+	 */
+	private void cancelNotification() {
+		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
+		mNotificationManager.cancel(1);
 	}
 
 }

+ 160 - 47
src/de/tudarmstadt/informatik/hostage/commons/HelperUtils.java

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

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

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

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

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

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

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

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

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

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

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

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

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

+ 0 - 156
src/de/tudarmstadt/informatik/hostage/handler/AbstractHandler.java

@@ -1,156 +0,0 @@
-package de.tudarmstadt.informatik.hostage.handler;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.Socket;
-
-import android.content.Context;
-import android.content.SharedPreferences;
-import android.content.SharedPreferences.Editor;
-import android.preference.PreferenceManager;
-import de.tudarmstadt.informatik.hostage.HoneyListener;
-import de.tudarmstadt.informatik.hostage.HoneyService;
-import de.tudarmstadt.informatik.hostage.logging.Logger;
-import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.logging.Record.TYPE;
-import de.tudarmstadt.informatik.hostage.protocol.Protocol;
-import de.tudarmstadt.informatik.hostage.ui.MainActivity;
-/**
- * Abstract class for a connection handler using a given protocol.
- * @author Mihai Plasoianu 
- */
-public abstract class AbstractHandler implements Runnable {
-
-	/**
-	 * Time until the socket throws a time out. The time is in milliseconds.
-	 */
-	private int TIMEOUT;
-
-	protected Protocol protocol;
-	private Socket client;
-	protected Thread thread;
-
-	private int attack_id;
-	private String externalIP;
-	private String BSSID;
-	private String SSID;
-
-	private HoneyListener listener;
-	protected Logger log;
-
-	/**
-	 * Constructor of the class.
-	 * Initializes class variables for communication and logging.
-	 * Then starts itself in a new Thread.
-	 * @param service The background service.
-	 * @param listener The Listener that called the service.
-	 * @param protocol The protocol on which the handler is running.
-	 * @param client A Socket for the communication with a remote client.
-	 */
-	public AbstractHandler(HoneyService service, HoneyListener listener,
-			Protocol protocol, Socket client) {
-		this.listener = listener;
-		this.log = service.getLog();
-		this.protocol = protocol;
-		this.client = client;
-		this.thread = new Thread(this);
-		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(service);
-		Editor editor = pref.edit();
-		TIMEOUT = pref.getInt("timeout", 30) * 1000;
-		attack_id = pref.getInt("ATTACK_ID_COUNTER", 0);
-		editor.putInt("ATTACK_ID_COUNTER", attack_id + 1);
-		editor.commit();
-		SharedPreferences sessionPref = service.getSharedPreferences(MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
-		BSSID = sessionPref.getString(MainActivity.BSSID, null);
-		SSID = sessionPref.getString(MainActivity.SSID, null);
-		externalIP = sessionPref.getString(MainActivity.EXTERNAL_IP, null);
-		setSoTimeout(client);
-		thread.start();
-	}
-
-	/**
-	 * Set the timeout of the socket to the hard coded time out variable.
-	 * @param client The socket
-	 * @see #TIMEOUT
-	 */
-	private void setSoTimeout(Socket client) {
-		try {
-			client.setSoTimeout(TIMEOUT);
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-	}
-
-	/**
-	 * Creates InputStream and OutputStream for the socket.
-	 * Starts communication with client.
-	 * When the client closes the connection or a time out occurs the handler is finished.
-	 */
-	public void run() {
-		InputStream in;
-		OutputStream out;
-		try {
-			in = client.getInputStream();
-			out = client.getOutputStream();
-			talkToClient(in, out);
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-		kill();
-	}
-
-	/**
-	 * Sets the interrupt flag of the thread and tries to close the socket.
-	 */
-	public void kill() {
-		thread.interrupt();
-		try {
-			client.close();
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-		listener.refreshHandlers();
-	}
-