Fabio Arnold 9 years ago
parent
commit
8d9b420be4

+ 4 - 3
assets/payload/redirect-ports.sh

@@ -4,14 +4,15 @@
 # MySQL SIP (3306 and 5060) are left out because they are >= 1024 anyways
 
 #             ECHO  FTP   HTTP  HTTPS SMB (NETBIOS UDP & TCP) SSH   TELNET
-protocol=(    "tcp" "tcp" "tcp" "tcp" "udp" "udp" "tcp" "tcp" "tcp" "tcp" )
-origin=(       7     21    80    443   137   138   137   139   22    23   )
-destination=( 28144 28169 28217 28580 28274 28275 28274 28276 28159 28160 ) # simply offset by 1024 + 27113
+protocol=(    "tcp" "tcp" "tcp" "tcp" "udp" "udp"  "tcp" "tcp" "tcp" "tcp")
+origin=(       7     21    80    443   137   138    139   22    23    445)
+destination=( 28144 28169 28217 28580 28274 28275 28276 28159 28160 28582) # simply offset by 1024 + 27113
 length=${#protocol[@]} # count protocol elements
 
 # for (( i=0; i<$length; i++ ))
 #for i in `seq 0 9` # fix for android's annoyingly limited bash
 for i in 0 1 2 3 4 5 6 7 8 9 # another fix for devices missing the seq command
+
 do
 	# echo ${protocol[$i]} ${origin[$i]} ${destination[$i]} # debug
 

+ 3 - 0
build.gradle

@@ -24,6 +24,9 @@ dependencies {
     compile files('libs/swipelistview-1.0.jar')
     compile files('libs/sshlib-v1.1.jar')
     compile files('libs/chart-library2.2.jar')
+    //compile files('libs/jlan-5.jar')
+    compile files('libs/alfresco-jlan.jar')
+    compile files('libs/cryptix-jce-provider.jar')
 }
 
 android {

BIN
libs/alfresco-jlan.jar


BIN
libs/cryptix-jce-provider.jar


BIN
libs/hazelcast/hazelcast-2.4.jar


+ 192 - 0
libs/hazelcast/hazelcastConfig.xml

@@ -0,0 +1,192 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<hazelcast xsi:schemaLocation="http://www.hazelcast.com/schema/config hazelcast-basic.xsd"
+           xmlns="http://www.hazelcast.com/schema/config"
+           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+    <group>
+        <name>dev</name>
+        <password>dev-pass</password>
+    </group>
+    <network>
+        <port auto-increment="true">5701</port>
+        <join>
+            <multicast enabled="true">
+                <multicast-group>224.2.2.3</multicast-group>
+                <multicast-port>54327</multicast-port>
+            </multicast>
+            <tcp-ip enabled="false">
+                <interface>127.0.0.1</interface>
+            </tcp-ip>
+        </join>
+        <interfaces enabled="true">
+            <interface>192.168.1.*</interface>
+        </interfaces>
+        <symmetric-encryption enabled="false">
+            <!--
+               encryption algorithm such as
+               DES/ECB/PKCS5Padding,
+               PBEWithMD5AndDES,
+               AES/CBC/PKCS5Padding,
+               Blowfish,
+               DESede
+            -->
+            <algorithm>PBEWithMD5AndDES</algorithm>
+            <!-- salt value to use when generating the secret key -->
+            <salt>thesalt</salt>
+            <!-- pass phrase to use when generating the secret key -->
+            <password>thepass</password>
+            <!-- iteration count to use when generating the secret key -->
+            <iteration-count>19</iteration-count>
+        </symmetric-encryption>
+        <asymmetric-encryption enabled="false">
+            <!-- encryption algorithm -->
+            <algorithm>RSA/NONE/PKCS1PADDING</algorithm>
+            <!-- private key password -->
+            <keyPassword>thekeypass</keyPassword>
+            <!-- private key alias -->
+            <keyAlias>local</keyAlias>
+            <!-- key store type -->
+            <storeType>JKS</storeType>
+            <!-- key store password -->
+            <storePassword>thestorepass</storePassword>
+            <!-- path to the key store -->
+            <storePath>keystore</storePath>
+        </asymmetric-encryption>
+    </network>
+    <executor-service>
+        <core-pool-size>16</core-pool-size>
+        <max-pool-size>64</max-pool-size>
+        <keep-alive-seconds>60</keep-alive-seconds>
+    </executor-service>
+    <queue name="default">
+        <!--
+            Maximum size of the queue. When a JVM's local queue size reaches the maximum,
+            all put/offer operations will get blocked until the queue size
+            of the JVM goes down below the maximum.
+            Any integer between 0 and Integer.MAX_VALUE. 0 means
+            Integer.MAX_VALUE. Default is 0.
+        -->
+        <max-size-per-jvm>0</max-size-per-jvm>
+        <!--
+            Maximum number of seconds for each item to stay in the queue. Items that are
+            not consumed in <time-to-live-seconds> will automatically
+            get evicted from the queue.
+            Any integer between 0 and Integer.MAX_VALUE. 0 means
+            infinite. Default is 0.
+        -->
+        <time-to-live-seconds>0</time-to-live-seconds>
+    </queue>
+    <map name="default">
+        <!--
+            Number of backups. If 1 is set as the backup-count for example,
+            then all entries of the map will be copied to another JVM for
+            fail-safety. Valid numbers are 0 (no backup), 1, 2, 3.
+        -->
+        <backup-count>1</backup-count>
+        <!--
+            Valid values are:
+            NONE (no eviction),
+            LRU (Least Recently Used),
+            LFU (Least Frequently Used).
+            NONE is the default.
+        -->
+        <eviction-policy>NONE</eviction-policy>
+        <!--
+            Maximum size of the map. When max size is reached,
+            map is evicted based on the policy defined.
+            Any integer between 0 and Integer.MAX_VALUE. 0 means
+            Integer.MAX_VALUE. Default is 0.
+        -->
+        <max-size>0</max-size>
+        <!--
+            When max. size is reached, specified percentage of
+            the map will be evicted. Any integer between 0 and 100.
+            If 25 is set for example, 25% of the entries will
+            get evicted.
+        -->
+        <eviction-percentage>25</eviction-percentage>
+
+        <!--
+            While recovering from split-brain (network partitioning),
+            map entries in the small cluster will merge into the bigger cluster
+            based on the policy set here. When an entry merge into the
+            cluster, there might an existing entry with the same key already.
+            Values of these entries might be different for that same key.
+            Which value should be set for the key? Conflict is resolved by
+            the policy set here. Default policy is hz.ADD_NEW_ENTRY
+
+            There are built-in merge policies such as
+            hz.NO_MERGE      ; no entry will merge.
+            hz.ADD_NEW_ENTRY ; entry will be added if the merging entry's key
+                               doesn't exist in the cluster.
+            hz.HIGHER_HITS   ; entry with the higher hits wins.
+            hz.LATEST_UPDATE ; entry with the latest update wins.
+        -->
+        <merge-policy>hz.ADD_NEW_ENTRY</merge-policy>
+    </map>
+    <!-- Add your own map merge policy implementations here:     
+    	<merge-policies>
+           	<map-merge-policy name="MY_MERGE_POLICY">
+            	<class-name>com.acme.MyOwnMergePolicy</class-name>
+        	</map-merge-policy>
+    	</merge-policies>
+    -->
+
+    <map name="AlfrescoFilesysCache">
+        <!--
+            Number of backups. If 1 is set as the backup-count for example,
+            then all entries of the map will be copied to another JVM for
+            fail-safety. Valid numbers are 0 (no backup), 1, 2, 3.
+        -->
+        <backup-count>1</backup-count>
+        <!--
+            Valid values are:
+            NONE (no eviction),
+            LRU (Least Recently Used),
+            LFU (Least Frequently Used).
+            NONE is the default.
+        -->
+        <eviction-policy>NONE</eviction-policy>
+        <!--
+            Maximum size of the map. When max size is reached,
+            map is evicted based on the policy defined.
+            Any integer between 0 and Integer.MAX_VALUE. 0 means
+            Integer.MAX_VALUE. Default is 0.
+        -->
+        <max-size>0</max-size>
+        <!--
+            When max. size is reached, specified percentage of
+            the map will be evicted. Any integer between 0 and 100.
+            If 25 is set for example, 25% of the entries will
+            get evicted.
+        -->
+        <eviction-percentage>25</eviction-percentage>
+
+        <!--
+            While recovering from split-brain (network partitioning),
+            map entries in the small cluster will merge into the bigger cluster
+            based on the policy set here. When an entry merge into the
+            cluster, there might an existing entry with the same key already.
+            Values of these entries might be different for that same key.
+            Which value should be set for the key? Conflict is resolved by
+            the policy set here. Default policy is hz.ADD_NEW_ENTRY
+
+            There are built-in merge policies such as
+            hz.NO_MERGE      ; no entry will merge.
+            hz.ADD_NEW_ENTRY ; entry will be added if the merging entry's key
+                               doesn't exist in the cluster.
+            hz.HIGHER_HITS   ; entry with the higher hits wins.
+            hz.LATEST_UPDATE ; entry with the latest update wins.
+        -->
+        <merge-policy>hz.ADD_NEW_ENTRY</merge-policy>
+<!--		
+		<near-cache>
+			<time-to-live-seconds>5</time-to-live-seconds>
+			<max-idle-seconds>60</max-idle-seconds>
+			<eviction-policy>LRU</eviction-policy>
+			<max-size>1000</max-size>
+			<invalidate-on-change>true</invalidate-on-change>
+		</near-cache>
+-->
+    </map>
+	
+</hazelcast>

BIN
libs/jlan-5.jar


+ 97 - 0
libs/service/jlansrv.conf

@@ -0,0 +1,97 @@
+#********************************************************************
+# Wrapper Properties
+#********************************************************************
+# Java Application
+wrapper.java.command=java
+
+# Java Main class
+wrapper.java.mainclass=org.alfresco.jlan.app.JLANServerService
+
+# Java Classpath (include wrapper.jar)  Add class path elements as
+#  needed starting from 1
+wrapper.java.classpath.1=../wrapper.jar
+wrapper.java.classpath.2=../../jars/alfresco-jlan.jar
+wrapper.java.classpath.3=../../libs/cryptix-jce-provider.jar
+
+# Java Library Path (location of Wrapper.DLL or libwrapper.so)
+wrapper.java.library.path.1=./
+wrapper.java.library.path.2=../../jni
+
+# Java Additional Parameters
+#wrapper.java.additional.1=-DPATH="%PATH%"
+
+# Initial Java Heap Size (in MB)
+wrapper.java.initmemory=64
+
+# Maximum Java Heap Size (in MB)
+wrapper.java.maxmemory=256
+
+# Application parameters.  Add parameters as needed starting from 1
+#wrapper.app.parameter.1=
+
+# JLAN Server service startup timeout
+wrapper.startup.timeout=30
+
+#********************************************************************
+# Wrapper Logging Properties
+#********************************************************************
+# Format of output for the console.  (See docs for formats)
+wrapper.console.format=LPM
+
+# Log Level for console output.  (See docs for log levels)
+wrapper.console.loglevel=INFO
+
+# Log file to use for wrapper output logging.
+wrapper.logfile=jlanserver.log
+
+# Format of output for the log file.  (See docs for formats)
+wrapper.logfile.format=LPTM
+
+# Log Level for log file output.  (See docs for log levels)
+wrapper.logfile.loglevel=INFO
+
+# Maximum size that the log file will be allowed to grow to before
+#  the log is rolled. Size is specified in bytes.  The default value
+#  of 0, disables log rolling.  May abbreviate with the 'k' (kb) or
+#  'm' (mb) suffix.  For example: 10m = 10 megabytes.
+wrapper.logfile.maxsize=0
+
+# Maximum number of rolled log files which will be allowed before old
+#  files are deleted.  The default value of 0 implies no limit.
+wrapper.logfile.maxfiles=0
+
+# Log Level for sys/event log output.  (See docs for log levels)
+wrapper.syslog.loglevel=NONE
+
+#********************************************************************
+# Wrapper NT Service Properties
+#********************************************************************
+# WARNING - Do not modify any of these properties when an application
+#  using this configuration file has been installed as a service.
+#  Please uninstall the service before modifying this section.  The
+#  service can then be reinstalled.
+
+# Name of the service
+wrapper.ntservice.name=JLANServer
+
+# Display name of the service
+wrapper.ntservice.displayname=Alfresco JLAN Server
+
+# Description of the service
+wrapper.ntservice.description=SMB/CIFS, NFS and FTP virtual filesystem server
+
+# Service dependencies.  Add dependencies as needed starting from 1
+wrapper.ntservice.dependency.1=
+
+# Mode in which the service is installed.  AUTO_START or DEMAND_START
+wrapper.ntservice.starttype=DEMAND_START
+
+# Allow the service to interact with the desktop.
+wrapper.ntservice.interactive=false
+
+# Account to run the service under
+#
+# Do not use .\LocalSystem as the server needs access to the network
+
+wrapper.ntservice.account=
+wrapper.ntservice.password=

+ 54 - 0
libs/service/license.txt

@@ -0,0 +1,54 @@
+Copyright (c) 1999, 2006 Tanuki Software, Inc.
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of the Java Service Wrapper and associated
+documentation files (the "Software"), to deal in the Software
+without  restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sub-license,
+and/or sell copies of the Software, and to permit persons to
+whom the Software is furnished to do so, subject to the
+following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
+NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+
+Portions of the Software have been derived from source code
+developed by Silver Egg Technology under the following license:
+
+BEGIN Silver Egg Techology License -----------------------------------
+    
+    Copyright (c) 2001 Silver Egg Technology
+    
+    Permission is hereby granted, free of charge, to any person
+    obtaining a copy of this software and associated documentation
+    files (the "Software"), to deal in the Software without 
+    restriction, including without limitation the rights to use, 
+    copy, modify, merge, publish, distribute, sub-license, and/or 
+    sell copies of the Software, and to permit persons to whom the
+    Software is furnished to do so, subject to the following 
+    conditions:
+    
+    The above copyright notice and this permission notice shall be
+    included in all copies or substantial portions of the Software.
+    
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
+    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
+    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
+    NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
+    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
+    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
+    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+    OTHER DEALINGS IN THE SOFTWARE.
+    
+END Silver Egg Techology License -------------------------------------
+

BIN
libs/service/linux/jlanserver


+ 212 - 0
libs/service/linux/jlanserver.sh

@@ -0,0 +1,212 @@
+#! /bin/bash
+
+#
+# JLAN Server Startup Script
+#
+
+#-----------------------------------------------------------------------------
+# These settings can be modified to fit the needs of your application
+
+# Application
+APP_NAME="JLANServer"
+APP_LONG_NAME="JLANServer Virtual Filesystem Server"
+
+# Wrapper
+WRAPPER_CMD="./wrapper"
+WRAPPER_CONF="./jlansrv.conf"
+
+# Priority (see the start() method if you want to use this)
+PRIORITY=
+
+# Do not modify anything beyond this point
+#-----------------------------------------------------------------------------
+
+# Get the fully qualified path to the script
+case $0 in
+    /*)
+        SCRIPT="$0"
+        ;;
+    *)
+        PWD=`pwd`
+        SCRIPT="$PWD/$0"
+        ;;
+esac
+
+# Change spaces to ":" so the tokens can be parsed.
+SCRIPT=`echo $SCRIPT | sed -e 's; ;:;g'`
+# Get the real path to this script, resolving any symbolic links
+TOKENS=`echo $SCRIPT | sed -e 's;/; ;g'`
+REALPATH=
+for C in $TOKENS; do
+    REALPATH="$REALPATH/$C"
+    while [ -h "$REALPATH" ] ; do
+        LS="`ls -ld "$REALPATH"`"
+        LINK="`expr "$LS" : '.*-> \(.*\)$'`"
+        if expr "$LINK" : '/.*' > /dev/null; then
+            REALPATH="$LINK"
+        else
+            REALPATH="`dirname "$REALPATH"`""/$LINK"
+        fi
+    done
+done
+# Change ":" chars back to spaces.
+REALPATH=`echo $REALPATH | sed -e 's;:; ;g'`
+
+# Change the current directory to the location of the script
+cd "`dirname "$REALPATH"`"
+
+# Find pidof.
+PIDOF="/bin/pidof"
+if [ ! -x $PIDOF ]
+then
+    PIDOF="/sbin/pidof"
+    if [ ! -x $PIDOF ]
+    then
+        echo "Cannot find 'pidof' in /bin or /sbin."
+        echo "This script requires 'pidof' to run."
+        exit 1
+    fi
+fi
+
+console() {
+    echo "Running $APP_LONG_NAME..."
+    pid=`$PIDOF $APP_NAME`
+    if [ -z $pid ]
+    then
+        # If you wanted to specify the priority with which
+        # your app runs, you could use nice here:
+        # exec -a $APP_NAME nice -$PRIORITY $WRAPPER_CMD $WRAPPER_CONF
+        # See "man nice" for more details.
+        exec -a $APP_NAME $WRAPPER_CMD $WRAPPER_CONF
+    else
+        echo "$APP_LONG_NAME is already running."
+        exit 1
+    fi
+}
+
+start() {
+    echo "Starting $APP_LONG_NAME..."
+    pid=`$PIDOF $APP_NAME`
+    if [ -z $pid ]
+    then
+        # If you wanted to specify the priority with which
+        # your app runs, you could use nice here:
+        # exec -a $APP_NAME nice -$PRIORITY $WRAPPER_CMD $WRAPPER_CONF wrapper.daemonize=TRUE wrapper.console.loglevel=NONE
+        # See "man nice" for more details.
+        exec -a $APP_NAME $WRAPPER_CMD $WRAPPER_CONF wrapper.daemonize=TRUE wrapper.console.loglevel=NONE
+    else
+        echo "$APP_LONG_NAME is already running."
+        exit 1
+    fi
+}
+
+stopit() {
+    echo "Stopping $APP_LONG_NAME..."
+    pid=`$PIDOF $APP_NAME`
+    if [ -z $pid ]
+    then
+        echo "$APP_LONG_NAME was not running."
+    else
+        # Running so try to stop it.
+        kill $pid
+        if [ $? -ne 0 ]
+        then
+            # An explanation for the failure should have been given
+            echo "Unable to stop $APP_LONG_NAME."
+            exit 1
+        fi
+
+        # We can not predict how long it will take for the wrapper to
+        #  actually stop as it depends on settings in wrapper.conf.
+        #  Loop until it does.
+        CNT=0
+        TOTCNT=0
+        while [ ! -z $pid ]
+        do
+            # Loop for up to 5 minutes
+            if [ "$TOTCNT" -lt "300" ]
+            then
+                if [ "$CNT" -lt "5" ]
+                then
+                    CNT=`expr $CNT + 1`
+                else
+                    echo "Waiting for $APP_LONG_NAME to exit..."
+                    CNT=0
+                fi
+                TOTCNT=`expr $TOTCNT + 1`
+
+                sleep 1
+
+                pid=`$PIDOF $APP_NAME`
+            else
+                pid=
+            fi
+        done
+
+        pid=`$PIDOF $APP_NAME`
+        if [ ! -z $pid ]
+        then
+            echo "Timed out waiting for $APP_LONG_NAME to exit."
+            echo "  Attempting a forced exit..."
+            kill -9 $pid
+        fi
+
+        pid=`$PIDOF $APP_NAME`
+        if [ ! -z $pid ]
+        then
+            echo "Failed to stop $APP_LONG_NAME."
+            exit 1
+        else
+            echo "Stopped $APP_LONG_NAME."
+        fi
+    fi
+}
+
+dump() {
+    echo "Dumping $APP_LONG_NAME..."
+    pid=`$PIDOF $APP_NAME`
+    if [ -z $pid ]
+    then
+        echo "$APP_LONG_NAME was not running."
+    else
+        kill -3 $pid
+
+        if [ $? -ne 0 ]
+        then
+            echo "Failed to dump $APP_LONG_NAME."
+        else
+            echo "Dumped $APP_LONG_NAME."
+        fi
+    fi
+}
+
+case "$1" in
+
+    'console')
+        console
+        ;;
+
+    'start')
+        start
+        ;;
+
+    'stop')
+        stopit
+        ;;
+
+    'restart')
+        stopit
+        start
+        ;;
+
+    'dump')
+        dump
+        ;;
+
+    *)
+        echo "Usage: $0 { console | start | stop | restart | dump }"
+        exit 1
+        ;;
+esac
+
+exit 0

BIN
libs/service/linux/libwrapper.so


BIN
libs/service/macosx/jlanserver


BIN
libs/service/macosx/libwrapper.jnilib


+ 5 - 0
libs/service/readme.txt

@@ -0,0 +1,5 @@
+Java Service Wrapper
+
+Complete documentation can be found by viewing doc/english/index.html
+or by going to http://wrapper.tanukisoftware.org
+

BIN
libs/service/solaris/jlanserver


BIN
libs/service/solaris/libwrapper.so


BIN
libs/service/windows/jlanserver.exe


BIN
libs/service/windows/wrapper.dll


BIN
libs/service/wrapper.jar


+ 63 - 0
res/raw/jlan_config.xml

@@ -0,0 +1,63 @@
+<?xml version="1.0" standalone="no"?>
+<!-- <!DOCTYPE jlanserver SYSTEM "jlanserver.dtd"> -->
+
+<jlanserver>
+    <servers>
+        <SMB/>
+        <noFTP/>
+        <noNFS/>
+    </servers>
+
+    <SMB>
+        <host name="HOME-PC" domain="WORKGROUP">
+            <broadcast>255.255.255.255</broadcast>
+            <smbdialects>LanMan,NT</smbdialects>
+            <comment>Alfresco JLAN Server</comment>
+            <!-- To run the server using a non-root account on linux, Mac OS X, Solaris -->
+            <netBIOSSMB sessionPort="28276" namingPort="28274" datagramPort="28275"/>
+            <tcpipSMB port="28582" ipv6="disabled"/>
+            <HostAnouncerPort>28275</HostAnouncerPort>
+            <hostAnounce interval='1'/>
+        </host>
+        <authenticator type="local">
+            <mode>SHARE</mode>
+            <allowGuest/>
+            <Debug/>
+        </authenticator>
+    </SMB>
+
+    <debug>
+        <output>
+            <class>org.alfresco.jlan.debug.ConsoleDebug</class>
+            <append/>
+        </output>
+    </debug>
+
+    <shares>
+        <diskshare name="JLAN" comment="Test share">
+            <driver>
+                <class>org.alfresco.jlan.smb.server.disk.JavaFileDiskDriver</class>
+                <LocalPath>/Bla</LocalPath>
+            </driver>
+        </diskshare>
+    </shares>
+
+    <security>
+        <JCEProvider>cryptix.jce.provider.CryptixCrypto</JCEProvider>
+        <authenticator>
+            <class>org.alfresco.jlan.server.auth.LocalAuthenticator</class>
+            <mode>USER</mode>
+            <allowGuest/>
+        </authenticator>
+        <users>
+            <user name="jlansrv">
+                <password>jlan</password>
+                <comment>System administrator</comment>
+                <administrator/>
+            </user>
+            <user name="normal">
+                <password>normal</password>
+            </user>
+        </users>
+    </security>
+</jlanserver>

+ 0 - 1
res/values-de/protocols.xml

@@ -12,7 +12,6 @@
         <item>SMB</item>
         <item>SSH</item>
         <item>TELNET</item>
-
     </string-array>
 
     <string-array name="protocols_description">

+ 31 - 6
src/de/tudarmstadt/informatik/hostage/Handler.java

@@ -11,7 +11,6 @@ import android.content.Intent;
 import android.content.SharedPreferences;
 import android.content.SharedPreferences.Editor;
 import android.preference.PreferenceManager;
-import android.util.Log;
 
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
@@ -82,6 +81,7 @@ public class Handler implements Runnable {
 			((GHOST) protocol).setAttackerIP(client.getInetAddress());
 			((GHOST) protocol).setCurrentPort(listener.getPort());
 		}
+
 		this.client = client;
 		this.thread = new Thread(this);
 		pref = PreferenceManager.getDefaultSharedPreferences(service);
@@ -101,6 +101,31 @@ public class Handler implements Runnable {
 		thread.start();		
 	}
 
+    public Handler(Hostage service, Listener listener, Protocol protocol){
+        this.service = service;
+        this.listener = listener;
+        this.protocol = protocol;
+        if (protocol.toString().equals("GHOST")) {
+            ((GHOST) protocol).setAttackerIP(client.getInetAddress());
+            ((GHOST) protocol).setCurrentPort(listener.getPort());
+        }
+
+        this.thread = new Thread(this);
+        pref = PreferenceManager.getDefaultSharedPreferences(service);
+        TIMEOUT = pref.getInt("timeout", 30) * 1000;
+        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);
+
+        // we need this info to find out whether the attack was internal
+        subnetMask = connInfo.getInt(service.getString(R.string.connection_info_subnet_mask), 0);
+        internalIPAddress = connInfo.getInt(service.getString(R.string.connection_info_internal_ip), 0);
+
+        logged = false;
+    }
+
 	/**
 	 * Determines if the interrupt flag of the thread is set.
 	 * 
@@ -192,7 +217,7 @@ public class Handler implements Runnable {
 	 *            The content of the message.
 	 * @return The Record representing the communication message.
 	 */
-	protected MessageRecord createMessageRecord(TYPE type, String packet) {
+	public MessageRecord createMessageRecord(TYPE type, String packet) {
 		MessageRecord record = new MessageRecord(true);
 		//record.setId(message_id++); // autoincrement
 		record.setAttack_id(attack_id);		
@@ -207,7 +232,7 @@ public class Handler implements Runnable {
 	 * 
 	 * @return The AttackRecord representing the attack.
 	 */
-	protected AttackRecord createAttackRecord() {
+    public AttackRecord createAttackRecord() {
 		AttackRecord record = new AttackRecord();
 		record.setAttack_id(attack_id);
         record.setSync_id(attack_id);
@@ -231,7 +256,7 @@ public class Handler implements Runnable {
 	 * 
 	 * @return The NetworkRecord representing the current network.
 	 */
-	protected NetworkRecord createNetworkRecord() {
+    public NetworkRecord createNetworkRecord() {
 		NetworkRecord record = new NetworkRecord();
 		record.setBssid(BSSID);		
 		record.setSsid(SSID);		
@@ -248,8 +273,8 @@ public class Handler implements Runnable {
 		}
 		return record;
 	}
-	
-	private void log(TYPE type, String packet) {
+
+    public void log(TYPE type, String packet){
 		if(!logged){
 			Logger.log(Hostage.getContext(), createNetworkRecord());
 			Logger.log(Hostage.getContext(), createAttackRecord());

+ 23 - 20
src/de/tudarmstadt/informatik/hostage/Listener.java

@@ -6,7 +6,6 @@ import java.net.Socket;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.concurrent.Semaphore;
-import java.util.concurrent.locks.Lock;
 
 import javax.net.ssl.SSLContext;
 import javax.net.ssl.SSLSocket;
@@ -14,9 +13,7 @@ import javax.net.ssl.SSLSocketFactory;
 
 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.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
@@ -24,8 +21,8 @@ import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
 import de.tudarmstadt.informatik.hostage.logging.Logger;
 import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
 import de.tudarmstadt.informatik.hostage.net.MyServerSocketFactory;
-import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 import de.tudarmstadt.informatik.hostage.protocol.SMB;
+import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 import de.tudarmstadt.informatik.hostage.protocol.SSLProtocol;
 
 /**
@@ -46,7 +43,7 @@ public class Listener implements Runnable {
 	private ServerSocket server;
 	private Thread thread;
 	private int port;
-	private Hostage service;
+    private Hostage service;
 
 	private ConnectionRegister conReg;
 	private boolean running = false;
@@ -102,6 +99,13 @@ public class Listener implements Runnable {
 		return protocol.toString();
 	}
 
+    public Protocol getProtocol() {
+        return protocol;
+    }
+    public Hostage getService() {
+        return service;
+    }
+
 	/**
 	 * Determines if the service is running.
 	 * 
@@ -126,6 +130,8 @@ public class Listener implements Runnable {
 
 	@Override
 	public void run() {
+        if(protocol.toString().equals("SMB")) return;
+
 		while (!thread.isInterrupted()) {
 			addHandler();
 		}
@@ -140,21 +146,14 @@ public class Listener implements Runnable {
 	 * and notifies the background service.
 	 */
 	public boolean start() {
-		if (protocol.toString().equals("SMB")) {
-			return false; // disable smb for the moment to prevent crashes
-		}
+        if(protocol.toString().equals("SMB")){
+            ((SMB) protocol).initialize(this);
+        }
+
 		try {
 			server = new MyServerSocketFactory().createServerSocket(port);
 			if (server == null)
 				return false;
-			if (protocol.toString().equals("SMB")) {
-				((SMB) protocol).setIP(HelperUtils.inetAddressToString(Hostage.getContext()
-						.getSharedPreferences(
-								Hostage.getContext().getString(R.string.connection_info),
-								Hostage.MODE_PRIVATE)
-						.getInt(Hostage.getContext()
-								.getString(R.string.connection_info_internal_ip), 0)));
-			}
 			(this.thread = new Thread(this)).start();
 			running = true;
 			service.notifyUI(this.getClass().getName(),
@@ -171,6 +170,10 @@ public class Listener implements Runnable {
 	 */
 	public void stop() {
 		try {
+            if(protocol.toString().equals("SMB")){
+                ((SMB) protocol).stop();
+            }
+
 			server.close();
 			thread.interrupt();
 			running = false;
@@ -260,7 +263,7 @@ public class Listener implements Runnable {
 	 * @throws Exception
 	 */
 	private void startHandler(Socket client) throws Exception {
-		handlers.add(newInstance(service, this, protocol.getClass().newInstance(), client));
+		handlers.add(newInstance(service, this, protocol.toString().equals("CIFS") ? protocol : protocol.getClass().newInstance(), client));
 	}
 
 	/**
@@ -275,7 +278,7 @@ public class Listener implements Runnable {
 		SSLSocketFactory factory = sslContext.getSocketFactory();
 		SSLSocket sslClient = (SSLSocket) factory.createSocket(client, null, client.getPort(), false);
 		sslClient.setUseClientMode(false);
-		handlers.add(newInstance(service, this, protocol.getClass().newInstance(), sslClient));
+		handlers.add(newInstance(service, this, protocol.toString().equals("CIFS") ? protocol : protocol.getClass().newInstance(), sslClient));
 	}	
 	
 	/**
@@ -316,7 +319,7 @@ public class Listener implements Runnable {
 		// now that the record exists we can inform the ui
 		// only handler informs about attacks so its name is used here
 		service.notifyUI(Handler.class.getName(),
-				new String[]{service.getString(R.string.broadcast_started), "PORTSCAN",
-						Integer.toString(client.getPort())});
+                new String[]{service.getString(R.string.broadcast_started), "PORTSCAN",
+                        Integer.toString(client.getPort())});
 	}
 }

+ 182 - 231
src/de/tudarmstadt/informatik/hostage/protocol/SMB.java

@@ -1,250 +1,201 @@
 package de.tudarmstadt.informatik.hostage.protocol;
 
-import java.security.SecureRandom;
-import java.util.ArrayList;
-import java.util.List;
 
+import android.content.Context;
 import android.content.SharedPreferences;
+import android.net.DhcpInfo;
+import android.net.wifi.WifiManager;
 import android.preference.PreferenceManager;
 
+import org.alfresco.jlan.app.XMLServerConfiguration;
+import org.alfresco.jlan.netbios.server.NetBIOSNameServer;
+import org.alfresco.jlan.server.SessionListener;
+import org.alfresco.jlan.server.SrvSession;
+import org.alfresco.jlan.server.config.InvalidConfigurationException;
+import org.alfresco.jlan.server.filesys.FileListener;
+import org.alfresco.jlan.server.filesys.NetworkFile;
+import org.alfresco.jlan.smb.server.CIFSConfigSection;
+import org.alfresco.jlan.smb.server.SMBServer;
+
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.InetAddress;
+import java.util.List;
+
+import de.tudarmstadt.informatik.hostage.Handler;
 import de.tudarmstadt.informatik.hostage.Hostage;
+import de.tudarmstadt.informatik.hostage.Listener;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-import de.tudarmstadt.informatik.hostage.protocol.smbutils.NBDSType;
-import de.tudarmstadt.informatik.hostage.protocol.smbutils.NBNS;
-import de.tudarmstadt.informatik.hostage.protocol.smbutils.NBNSType;
-import de.tudarmstadt.informatik.hostage.protocol.smbutils.NMB;
-import de.tudarmstadt.informatik.hostage.protocol.smbutils.SMBPacket;
+import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
+import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
+import de.tudarmstadt.informatik.hostage.logging.Logger;
+import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
+import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
+import de.tudarmstadt.informatik.hostage.logging.SyncDevice;
+import de.tudarmstadt.informatik.hostage.protocol.cifs.CifsServer;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
 import de.tudarmstadt.informatik.hostage.wrapper.Packet;
 
 /**
- * SMB protocol. It can handle the following requests: Negotiate Protocol
- * Request, Session Setup AndX Request, Tree Connect AndX Request, NT Create
- * AndX Request, Bind, NetShareEnumAll, Close Request, Tree Disconnect Request,
- * Echo Request, Trans2 Request.
- *
- * @author Wulf Pfeiffer
+ * HostageV3
+ * ================
+ * @author Alexander Brakowski
+ * @author Daniel Lazar
  */
 public class SMB implements Protocol {
-	// message constants
-	private static final byte SMB_COM_CLOSE = 0x04;
-	private static final byte SMB_COM_TRANSACTION = 0x25;
-	private static final byte SMB_COM_ECHO = 0x2B;
-	private static final byte SMB_COM_TRANSACTION2 = 0x32;
-	private static final byte SMB_COM_TREE_DISCONNECT = 0x71;
-	private static final byte SMB_COM_NEGOTIATE = 0x72;
-	private static final byte SMB_COM_SESSION_SETUP_ANDX = 0x73;
-	private static final byte SMB_COM_TREE_CONNECT_ANDX = 0x75;
-	private static final byte SMB_COM_NT_CREATE_ANDX = (byte) 0xA2;
-
-	/**
-	 * Denotes in which state the protocol is right now
-	 */
-	private STATE state = STATE.NONE;
-	private byte[] lastMessage;
-	private NMB nmb;
-
-	// version stuff
-	private String[][] possibleSmbVersions = {
-			{ "Windows 7 Professional 7600", "Windows 7 Professional 6.1" },
-			{ "Windows 8 Enterprise 9200", "Windows 8 Enterprise 9200" },
-			{ "Windows Server 2008 R2 Enterprise 7600", "Windows Server 2008 R2 Enterprise 6.1" },
-			{ "Windows Server 2012 Standard 6.2", "Windows Server 2012 Standard 6.2" },
-			{ "Unix", "Samba" },
-			{ "Windows 2002 Service Pack 2", "Windows 2002 5.1" }
-	};
-
-	/**
-	 * Represents the states of the protocol
-	 */
-	private static enum STATE {
-		NONE, CONNECTED, AUTHENTICATED, LISTING, DISCONNECTED, CLOSED
-	}
-
-	public void setIP(String ip) {
-//		TODO if porthack is working for UDP uncomment
-        nmb = new NMB(ip, "BLIBLABLUB", "Workgroup");
-        nmb.start();
-
-//		nmb = new NMB(ip, new String(serverName), workgroup);
-//		nmb.start();
-	}
-
-	private String[] initServerVersion() {
-		String sharedPreferencePath = Hostage.getContext().getString(
-				R.string.shared_preference_path);
-		String profile = Hostage
-				.getContext()
-				.getSharedPreferences(sharedPreferencePath,
-						Hostage.MODE_PRIVATE).getString("os", "");
-		if(profile.equals("Windows XP")) {
-			workgroup = "MSHOME";
-		} else {
-			workgroup = "WORKGROUP";
-		}
-
-		if (profile.equals("Windows 7")) {
-			return possibleSmbVersions[0];
-		} else if (profile.equals("Windows 8")) {
-			return possibleSmbVersions[1];
-		} else if (profile.equals("Windows Server 2008")) {
-			return possibleSmbVersions[2];
-		} else if (profile.equals("Windows Server 2012")) {
-			return possibleSmbVersions[3];
-		} else if (profile.equals("Linux")) {
-			return possibleSmbVersions[4];
-		} else if (profile.equals("Windows XP")) {
-			return possibleSmbVersions[5];
-		} else {
-			return possibleSmbVersions[new SecureRandom().nextInt(possibleSmbVersions.length)];
-		}
-	}
-
-	//required to be declared down here, do not change position over initServerVersion() and possibleServerVersions!!
-	private String[] serverVersion = initServerVersion();
-	private static byte[] serverName = HelperUtils.fillWithZero(HelperUtils
-			.getRandomString(16, true).getBytes());
-	private static String workgroup;
-	private SMBPacket smbPacket = new SMBPacket(serverVersion, new String(serverName), workgroup);
-	private int maxEchoPackets = initMaxPackets();
-	private int receivedEchoPackets = 0;
-	
-	private int initMaxPackets() {
-		int maxPackets;
-		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Hostage.getContext());
-		maxPackets = Integer.parseInt(prefs.getString("pref_timeout", "30")) / 5;
-		return maxPackets;
-	}
-
-	@Override
-	public int getPort() {
-		return 445;
-	}
-
-	@Override
-	public boolean isClosed() {
-		return (state == STATE.CLOSED);
-	}
-
-	@Override
-	public boolean isSecure() {
-		return false;
-	}
-
-    //just for debugging purpose
-    final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
-    public static String bytesToHex(byte[] bytes) {
-        char[] hexChars = new char[bytes.length * 2];
-        for ( int j = 0; j < bytes.length; j++ ) {
-            int v = bytes[j] & 0xFF;
-            hexChars[j * 2] = hexArray[v >>> 4];
-            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
+    private Listener mListener;
+    private Handler mHandler;
+    private SMBServer mSmbServer;
+    private NetBIOSNameServer mNbNameServer;
+    private CifsServer mCifsServer;
+
+    SharedPreferences pref;
+
+    private int attack_id;
+    private String externalIP;
+    private String BSSID;
+    private String SSID;
+
+    private int subnetMask;
+    private int internalIPAddress;
+
+    private boolean logged;
+
+    public Listener getListener(){
+        return mListener;
+    }
+
+    public void initialize(Listener mListener) {
+        this.mListener = mListener;
+
+        Hostage service = mListener.getService();
+        pref = PreferenceManager.getDefaultSharedPreferences(service);
+        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);
+
+        // we need this info to find out whether the attack was internal
+        subnetMask = connInfo.getInt(service.getString(R.string.connection_info_subnet_mask), 0);
+        internalIPAddress = connInfo.getInt(service.getString(R.string.connection_info_internal_ip), 0);
+        logged = false;
+
+        XMLServerConfiguration smbConfig = new XMLServerConfiguration();
+
+        try {
+            smbConfig.loadConfiguration(new InputStreamReader(MainActivity.context.getResources().openRawResource(R.raw.jlan_config)));
+            mCifsServer = new CifsServer(smbConfig, this);
+            mCifsServer.run();
+        } catch (IOException e) {
+            e.printStackTrace();
+        } catch (InvalidConfigurationException e) {
+            e.printStackTrace();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    public void stop(){
+        mCifsServer.stop();
+    }
+
+    public int getLocalIp(){
+        WifiManager wifi = (WifiManager) MainActivity.context.getSystemService(Context.WIFI_SERVICE);
+        DhcpInfo dhcp = wifi.getDhcpInfo();
+
+        return dhcp.ipAddress;
+    }
+
+    private synchronized void getAndIncrementAttackID(SharedPreferences pref) {
+        SharedPreferences.Editor editor = pref.edit();
+        attack_id = pref.getInt("ATTACK_ID_COUNTER", 0);
+        editor.putInt("ATTACK_ID_COUNTER", attack_id + 1);
+        editor.commit();
+    }
+
+    public MessageRecord createMessageRecord(MessageRecord.TYPE type, String packet) {
+        MessageRecord record = new MessageRecord(true);
+        //record.setId(message_id++); // autoincrement
+        record.setAttack_id(attack_id);
+        record.setType(type);
+        record.setTimestamp(System.currentTimeMillis());
+        record.setPacket(packet);
+        return record;
+    }
+
+    public AttackRecord createAttackRecord(int localPort, InetAddress remoteIP, int remotePort) {
+        AttackRecord record = new AttackRecord();
+        record.setAttack_id(attack_id);
+        record.setSync_id(attack_id);
+        record.setDevice(SyncDevice.currentDevice().getDeviceID());
+
+        record.setProtocol(this.toString());
+        record.setExternalIP(externalIP);
+        record.setLocalIP(CifsServer.intToInetAddress(getLocalIp()).getHostAddress());
+        record.setLocalPort(localPort);
+        record.setWasInternalAttack((HelperUtils.packInetAddress(remoteIP.getAddress()) & subnetMask) == (internalIPAddress & subnetMask));
+        record.setRemoteIP(remoteIP.getHostAddress());
+        record.setRemotePort(remotePort);
+        record.setBssid(BSSID);
+        return record;
+    }
+
+    public NetworkRecord createNetworkRecord() {
+        NetworkRecord record = new NetworkRecord();
+        record.setBssid(BSSID);
+        record.setSsid(SSID);
+        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 new String(hexChars);
+        return record;
     }
 
-	@Override
-	public List<Packet> processMessage(Packet requestPacket) {
-        if (requestPacket != null && requestPacket.getBytes().length != 0){
-            lastMessage = requestPacket.getBytes();
-            System.out.println("request packet " + bytesToHex(lastMessage));
-            smbPacket.prepareNextResponse(lastMessage);
+    public void log(MessageRecord.TYPE type, String packet, int localPort, InetAddress remoteIP, int remotePort){
+        if(!logged){
+            Logger.log(Hostage.getContext(), createNetworkRecord());
+            Logger.log(Hostage.getContext(), createAttackRecord(localPort, remoteIP, remotePort));
+            logged = true;
         }
-        else{
-            //something needs to be done, if there is no message
-            smbPacket.prepareNextResponse(0);
+        if (packet != null && packet.length() > 0) { // prevent logging empty packets
+            Logger.log(Hostage.getContext(), createMessageRecord(type, packet));
         }
-		byte smbCommand = smbPacket.getSmbCommand();
-		byte[] response;
-		List<Packet> responsePackets = new ArrayList<Packet>();
-
-		if (smbCommand == SMB_COM_ECHO) {
-			receivedEchoPackets++;
-		} else {
-			receivedEchoPackets = 0;
-		}
-		
-		if (receivedEchoPackets == maxEchoPackets) {
-			state = STATE.CLOSED;
-			response = smbPacket.getTreeDisc();
-			responsePackets.add(new Packet(response, toString()));
-			return responsePackets;
-		}
-		
-		switch (state) {
-			case NONE:
-				if (smbCommand == SMB_COM_NEGOTIATE) {
-					state = STATE.CONNECTED;
-					response = smbPacket.getNego();
-				} else {
-					state = STATE.DISCONNECTED;
-					response = smbPacket.getTreeDisc();
-				}
-				break;
-			case CONNECTED:
-				if (smbCommand == SMB_COM_SESSION_SETUP_ANDX) {
-					response = smbPacket.getSessSetup();
-				} else if (smbCommand == SMB_COM_TREE_CONNECT_ANDX) {
-					state = STATE.AUTHENTICATED;
-					response = smbPacket.getTreeCon();
-				} else {
-					state = STATE.DISCONNECTED;
-					response = smbPacket.getTreeDisc();
-				}
-				break;
-			case AUTHENTICATED:
-				if (smbCommand == SMB_COM_NT_CREATE_ANDX) {
-					state = STATE.LISTING;
-					response = smbPacket.getNTCreate();
-				} else if (smbCommand == SMB_COM_ECHO) {
-					response = smbPacket.getEcho();
-				} else if (smbCommand == SMB_COM_TRANSACTION2) {
-					response = smbPacket.getTrans2();
-				} else if (smbCommand == SMB_COM_CLOSE) {
-					response = smbPacket.getClose();
-				} else if (smbCommand == SMB_COM_TREE_DISCONNECT) {
-					state = STATE.CLOSED;
-					response = smbPacket.getTreeDisc();
-				} else {
-					state = STATE.DISCONNECTED;
-					response = smbPacket.getTreeDisc();
-				}
-				break;
-			case LISTING:
-				if (smbCommand == SMB_COM_TRANSACTION) {
-					response = smbPacket.getTrans();
-				} else if (smbCommand == SMB_COM_CLOSE) {
-					response = smbPacket.getClose();
-				} else if (smbCommand == SMB_COM_TREE_DISCONNECT) {
-					state = STATE.CLOSED;
-					response = smbPacket.getTreeDisc();
-				} else if (smbCommand == SMB_COM_NEGOTIATE) {
-					state = STATE.CONNECTED;
-					response = smbPacket.getNego();
-				} else {
-					state = STATE.DISCONNECTED;
-					response = smbPacket.getTreeDisc();
-				}
-				break;
-			case DISCONNECTED:
-				state = STATE.CLOSED;
-				response = smbPacket.getTreeDisc();
-				break;
-			default:
-				state = STATE.CLOSED;
-				response = smbPacket.getTreeDisc();
-		}
-		responsePackets.add(new Packet(response, toString()));
-		return responsePackets;
-	}
-
-	@Override
-	public String toString() {
-		return "SMB";
-	}
-
-	@Override
-	public TALK_FIRST whoTalksFirst() {
-		return TALK_FIRST.CLIENT;
-	}
-}
+    }
+    @Override
+    public int getPort() {
+        return 1025;
+    }
+
+    @Override
+    public boolean isClosed() {
+        return false;
+    }
+
+    @Override
+    public boolean isSecure() {
+        return false;
+    }
+
+    @Override
+    public List<Packet> processMessage(Packet message) {
+        return null;
+    }
+
+    @Override
+    public TALK_FIRST whoTalksFirst() {
+        return TALK_FIRST.CLIENT;
+    }
+
+    public String toString(){
+        return "SMB";
+    }
+}

+ 219 - 0
src/de/tudarmstadt/informatik/hostage/protocol/cifs/CifsServer.java

@@ -0,0 +1,219 @@
+package de.tudarmstadt.informatik.hostage.protocol.cifs;
+
+import android.content.Context;
+import android.net.DhcpInfo;
+import android.net.wifi.WifiManager;
+
+import org.alfresco.jlan.app.JLANCifsServer;
+import org.alfresco.jlan.app.XMLServerConfiguration;
+import org.alfresco.jlan.netbios.NetworkSettings;
+import org.alfresco.jlan.server.NetworkServer;
+import org.alfresco.jlan.server.ServerListener;
+import org.alfresco.jlan.server.SessionListener;
+import org.alfresco.jlan.server.SrvSession;
+import org.alfresco.jlan.server.filesys.DiskDeviceContext;
+import org.alfresco.jlan.server.filesys.DiskInterface;
+import org.alfresco.jlan.server.filesys.DiskSharedDevice;
+import org.alfresco.jlan.server.filesys.FileListener;
+import org.alfresco.jlan.server.filesys.FilesystemsConfigSection;
+import org.alfresco.jlan.server.filesys.NetworkFile;
+import org.alfresco.jlan.server.filesys.NetworkFileServer;
+import org.alfresco.jlan.server.filesys.SrvDiskInfo;
+import org.alfresco.jlan.smb.server.CIFSConfigSection;
+import org.springframework.extensions.config.element.GenericConfigElement;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+
+import de.tudarmstadt.informatik.hostage.Handler;
+import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
+import de.tudarmstadt.informatik.hostage.protocol.SMB;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
+
+/**
+ * HostageV3
+ * ================
+ * @author Alexander Brakowski
+ * @author Daniel Lazar
+ * on 19.03.15.
+ */
+public class CifsServer extends JLANCifsServer {
+
+    private final XMLServerConfiguration serverConfiguration;
+    protected final SMB SMB;
+
+    public CifsServer(XMLServerConfiguration serverConfiguration, SMB SMB){
+        super();
+
+        this.SMB = SMB;
+        this.serverConfiguration = serverConfiguration;
+    }
+
+    public void run() throws Exception {
+        CIFSConfigSection cifsConfigSection = (CIFSConfigSection) serverConfiguration.getConfigSection(CIFSConfigSection.SectionName);
+        cifsConfigSection.setBroadcastMask(getBroadcastAddress());
+        //enables the host announcer, so that it should appear in network neighborhood
+        cifsConfigSection.setHostAnnouncer(true);
+        cifsConfigSection.setDisableNIOCode(true);
+
+        int ip = SMB.getLocalIp();
+
+        //binding to one address on both SMB and NB
+        cifsConfigSection.setSMBBindAddress(intToInetAddress(ip));
+        cifsConfigSection.setNetBIOSBindAddress(intToInetAddress(ip));
+        //setting the broadcast mask for the network
+        NetworkSettings.setBroadcastMask(getBroadcastAddress());
+
+
+        if(cifsConfigSection.hasNetBIOSSMB()){
+            //adding a Netbios Server for the nameservice
+            serverConfiguration.addServer(createNetBIOSServer(serverConfiguration));
+        }
+
+        //adding a SMB server
+        serverConfiguration.addServer(createSMBServer(serverConfiguration));
+
+        FilesystemsConfigSection filesysConfig = (FilesystemsConfigSection) serverConfiguration.getConfigSection(FilesystemsConfigSection.SectionName);
+
+        //creating a file which references to the apps cache folder
+        File cacheFolder = MainActivity.context.getExternalCacheDir();
+        File jlanFolder = new File(cacheFolder.getAbsolutePath() + "/jlan");
+        deleteRecursive(jlanFolder);
+
+        //creating folders which appear if an attacker opens a session
+        File anotherFolder = new File(jlanFolder.getAbsolutePath() + "/Windows");
+        File progData = new File(jlanFolder.getAbsolutePath() + "/ProgramData");
+        File users = new File(jlanFolder.getAbsolutePath() + "/Users");
+        File temp= new File(jlanFolder.getAbsolutePath() + "/temp");
+        jlanFolder.mkdir();
+        anotherFolder.mkdir();
+        progData.mkdir();
+        users.mkdir();
+        temp.mkdir();
+
+        // SHARES
+        DiskInterface diskInterface = new PseudoJavaFileDiskDriver(SMB);
+        final GenericConfigElement driverConfig = new GenericConfigElement("driver");
+        final GenericConfigElement localPathConfig = new GenericConfigElement("LocalPath");
+        localPathConfig.setValue(jlanFolder.getAbsolutePath());
+        driverConfig.addChild(localPathConfig);
+        DiskDeviceContext diskDeviceContext = (DiskDeviceContext) diskInterface.createContext("SHARE", driverConfig);
+        diskDeviceContext.setShareName("SHARE");
+        diskDeviceContext.setConfigurationParameters(driverConfig);
+        diskDeviceContext.enableChangeHandler(false);
+        diskDeviceContext.setDiskInformation(new SrvDiskInfo(2560000, 64, 512, 2304000));// Default to a 80Gb sized disk with 90% free space
+        DiskSharedDevice diskDev = new DiskSharedDevice("SHARE", diskInterface, diskDeviceContext);
+        diskDev.setConfiguration(serverConfiguration);
+        diskDeviceContext.startFilesystem(diskDev);
+        filesysConfig.addShare(diskDev);
+
+        for(int i=0; i<serverConfiguration.numberOfServers(); i++){
+            NetworkServer server = serverConfiguration.getServer(i);
+
+            if(server instanceof NetworkFileServer){
+                NetworkFileServer fileServer = (NetworkFileServer) server;
+                fileServer.addFileListener(new FileListener() {
+                    @Override
+                    public void fileClosed(SrvSession sess, NetworkFile file) {
+                    }
+
+                    @Override
+                    public void fileOpened(SrvSession sess, NetworkFile file) {
+                    }
+                });
+            }
+
+            server.addServerListener(new ServerListener() {
+                @Override
+                public void serverStatusEvent(NetworkServer server, int event) {
+                }
+            });
+
+            server.addSessionListener(new SessionListener() {
+                @Override
+                public void sessionClosed(SrvSession sess) {
+
+
+                    SMB.log(MessageRecord.TYPE.RECEIVE, "SESSION CLOSED", 139, sess.getRemoteAddress(), 139);
+                }
+
+                @Override
+                public void sessionCreated(SrvSession sess) {
+                    SMB.getListener().getService().notifyUI(Handler.class.getName(),
+                            new String[] {
+                                    SMB.getListener().getService().getString(R.string.broadcast_started),
+                                    SMB.getListener().getProtocol().toString(),
+                                    Integer.toString(SMB.getListener().getPort())
+                            }
+                    );
+
+                    SMB.log(MessageRecord.TYPE.RECEIVE, "SESSION CREATED", 139, sess.getRemoteAddress(), 139);
+
+                }
+
+                @Override
+                public void sessionLoggedOn(SrvSession sess) {
+
+                    SMB.log(MessageRecord.TYPE.RECEIVE, "SESSION LOGGED ON", 139, sess.getRemoteAddress(), 139);
+
+                }
+            });
+            server.getShareMapper();
+            server.startServer();
+        }
+    }
+
+    /**
+     * stops the server
+     */
+    public void stop(){
+        for(int i=0; i<serverConfiguration.numberOfServers(); i++){
+            NetworkServer server = serverConfiguration.getServer(i);
+            server.shutdownServer(true);
+        }
+    }
+
+    /**
+     * helper method to obtain the broadcast address
+     */
+    private String getBroadcastAddress() throws IOException {
+        WifiManager wifi = (WifiManager) MainActivity.context.getSystemService(Context.WIFI_SERVICE);
+        DhcpInfo dhcp = wifi.getDhcpInfo();
+        // handle null somehow
+        int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
+        byte[] quads = new byte[4];
+        for (int k = 0; k < 4; k++)
+            quads[k] = (byte) (broadcast >> (k * 8));
+        return InetAddress.getByAddress(quads).toString().substring(1);
+    }
+
+    /**
+     * helper method to convert the ip from int to InetAddress
+     */
+    public static InetAddress intToInetAddress(int hostAddress) {
+        byte[] addressBytes = { (byte)(0xff & hostAddress),
+                (byte)(0xff & (hostAddress >> 8)),
+                (byte)(0xff & (hostAddress >> 16)),
+                (byte)(0xff & (hostAddress >> 24)) };
+
+        try {
+            return InetAddress.getByAddress(addressBytes);
+        } catch (UnknownHostException e) {
+            throw new AssertionError();
+        }
+    }
+/**
+ * helper method to delete the contents of the
+ * apps cache folder
+ */
+    private void deleteRecursive(File fileOrDirectory) {
+        if (fileOrDirectory.isDirectory())
+            for (File child : fileOrDirectory.listFiles())
+                deleteRecursive(child);
+
+        fileOrDirectory.delete();
+    }
+}

+ 123 - 0
src/de/tudarmstadt/informatik/hostage/protocol/cifs/PseudoJavaFileDiskDriver.java

@@ -0,0 +1,123 @@
+package de.tudarmstadt.informatik.hostage.protocol.cifs;
+
+import org.alfresco.jlan.server.SrvSession;
+import org.alfresco.jlan.server.core.DeviceContext;
+import org.alfresco.jlan.server.filesys.FileExistsException;
+import org.alfresco.jlan.server.filesys.FileName;
+import org.alfresco.jlan.server.filesys.FileOpenParams;
+import org.alfresco.jlan.server.filesys.NetworkFile;
+import org.alfresco.jlan.server.filesys.TreeConnection;
+import org.alfresco.jlan.smb.server.disk.JavaFileDiskDriver;
+import org.alfresco.jlan.smb.server.disk.JavaNetworkFile;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileWriter;
+import java.math.BigInteger;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
+import de.tudarmstadt.informatik.hostage.protocol.SMB;
+
+/**
+ * HostageV3
+ * ================
+ * @author Alexander Brakowski
+ * @author Daniel Lazar
+ *
+ * This is a pseudo file disk driver, which overwrites the libs JavaFileDiskDriver,
+ * so that we can get more information about the attack
+ */
+public class PseudoJavaFileDiskDriver extends JavaFileDiskDriver {
+    private static class PseudoJavaNetworkFile extends JavaNetworkFile {
+        protected final SMB SMB;
+        private final SrvSession sess;
+        boolean wasWrittenTo = false;
+
+        public PseudoJavaNetworkFile(File file, String netPath, SMB SMB, SrvSession sess) {
+            super(file, netPath);
+            this.SMB = SMB;
+            this.sess = sess;
+        }
+
+        /**
+         * method that checks if the file was just written, then gets the MD5 checksum of the
+         * file and logs it. Afterwards the file gets deleted.
+         * @throws java.io.IOException
+         */
+        public void closeFile() throws java.io.IOException {
+            super.closeFile();
+            if(wasWrittenTo){
+                try {
+                    MessageDigest digest = MessageDigest.getInstance("MD5");
+                    FileInputStream fis = new FileInputStream(m_file);
+
+                    byte[] buffer = new byte[8192];
+                    int numOfBytesRead;
+                    while( (numOfBytesRead = fis.read(buffer)) > 0){
+                        digest.update(buffer, 0, numOfBytesRead);
+                    }
+
+                    byte[] hash = digest.digest();
+                    String checksum = new BigInteger(1, hash).toString(16);
+
+                    String message = "File received: " + m_file.getName() + "\n\nCHECKSUM:\n" + checksum;
+
+                    SMB.log(MessageRecord.TYPE.RECEIVE, message, 445, sess.getRemoteAddress(), 445);
+                } catch (NoSuchAlgorithmException e) {
+                    e.printStackTrace();
+                }
+
+                m_file.delete();
+                wasWrittenTo = false;
+            }
+        }
+
+        public void writeFile(byte[] buf, int len, int pos)
+                throws java.io.IOException {
+            super.writeFile(buf, len, pos);
+            wasWrittenTo = true;
+        }
+
+        public void writeFile(byte[] buf, int len, int pos, long offset)
+                throws java.io.IOException {
+            super.writeFile(buf, len, pos, offset);
+            wasWrittenTo = true;
+        }
+    }
+
+    private final SMB SMB;
+
+    public PseudoJavaFileDiskDriver(SMB SMB) {
+        this.SMB = SMB;
+    }
+
+    public NetworkFile createFile(SrvSession sess, TreeConnection tree, FileOpenParams params)
+            throws java.io.IOException {
+        DeviceContext ctx = tree.getContext();
+        String fname = FileName.buildPath(ctx.getDeviceName(), params.getPath(), null, java.io.File.separatorChar);
+
+        //  Check if the file already exists
+
+        File file = new File(fname);
+        if (file.exists())
+            throw new FileExistsException();
+
+        //  Create the new file
+
+        FileWriter newFile = new FileWriter(fname, false);
+        newFile.close();
+
+        //  Create a Java network file
+
+        file = new File(fname);
+        PseudoJavaNetworkFile netFile = new PseudoJavaNetworkFile(file, params.getPath(), SMB, sess);
+        netFile.setGrantedAccess(NetworkFile.READWRITE);
+        netFile.setFullName(params.getPath());
+
+        //  Return the network file
+
+        return netFile;
+    }
+}

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/sync/android/SyncUtils.java

@@ -266,12 +266,12 @@ public class SyncUtils {
 
             JSONObject condition = new JSONObject();
 
-            if(fromTime > 0){
+            /*if(fromTime > 0){
                 Calendar calendar = GregorianCalendar.getInstance();
                 calendar.setTimeInMillis(fromTime);
 
                 condition.put("date", fromCalendar(calendar));
-            }
+            }*/
 
             String country = null;