Browse Source

added comments, changed CIFS to SMB, added a delete function for cache dir

- added some comments in the CIFS part, for the most important methods and
  classes
- changed CIFS to SMB: deleted old SMB, so that we can now rename the CIFS
  part to SMB and make use of it through the profiles
- added a recursive delete function for the shares part of CIFS where the
  apps cache folder gets deleted recursivly before creating the filesystem
  structure
Daniel Lazar 10 năm trước cách đây
mục cha
commit
a2159e15d7

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

@@ -9,7 +9,7 @@
         <item>HTTPS</item>
         <item>MySQL</item>
         <item>SIP</item>
-        <item>CIFS</item>
+        <item>SMB</item>
         <item>SSH</item>
         <item>TELNET</item>
     </string-array>

+ 1 - 1
res/values/protocols.xml

@@ -9,7 +9,7 @@
         <item>HTTPS</item>
         <item>MySQL</item>
         <item>SIP</item>
-        <item>CIFS</item>
+        <item>SMB</item>
         <item>SSH</item>
         <item>TELNET</item>
     </string-array>

+ 0 - 2
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;
@@ -23,7 +22,6 @@ import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
 import de.tudarmstadt.informatik.hostage.logging.SyncDevice;
 import de.tudarmstadt.informatik.hostage.nio.Reader;
 import de.tudarmstadt.informatik.hostage.nio.Writer;
-import de.tudarmstadt.informatik.hostage.protocol.CIFS;
 import de.tudarmstadt.informatik.hostage.protocol.GHOST;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol.TALK_FIRST;

+ 8 - 24
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,9 +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.CIFS;
-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;
 
 /**
@@ -134,7 +130,7 @@ public class Listener implements Runnable {
 
 	@Override
 	public void run() {
-        if(protocol.toString().equals("CIFS")) return;
+        if(protocol.toString().equals("SMB")) return;
 
 		while (!thread.isInterrupted()) {
 			addHandler();
@@ -150,26 +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("CIFS")){
-            ((CIFS) protocol).initialize(this);
+        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(),
@@ -186,8 +170,8 @@ public class Listener implements Runnable {
 	 */
 	public void stop() {
 		try {
-            if(protocol.toString().equals("CIFS")){
-                ((CIFS) protocol).stop();
+            if(protocol.toString().equals("SMB")){
+                ((SMB) protocol).stop();
             }
 
 			server.close();
@@ -335,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())});
 	}
 }

+ 0 - 195
src/de/tudarmstadt/informatik/hostage/protocol/CIFS.java

@@ -1,195 +0,0 @@
-package de.tudarmstadt.informatik.hostage.protocol;
-
-
-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.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;
-
-public class CIFS implements Protocol {
-    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 record;
-    }
-
-    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;
-        }
-        if (packet != null && packet.length() > 0) { // prevent logging empty packets
-            Logger.log(Hostage.getContext(), createMessageRecord(type, packet));
-        }
-    }
-    @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 "CIFS";
-    }
-}

+ 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";
+    }
+}

+ 48 - 19
src/de/tudarmstadt/informatik/hostage/protocol/cifs/CifsServer.java

@@ -30,50 +30,60 @@ 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.CIFS;
+import de.tudarmstadt.informatik.hostage.protocol.SMB;
 import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
 
 /**
  * HostageV3
  * ================
-
- * Created by abrakowski on 19.03.15.
+ * @author Alexander Brakowski
+ * @author Daniel Lazar
+ * on 19.03.15.
  */
 public class CifsServer extends JLANCifsServer {
 
     private final XMLServerConfiguration serverConfiguration;
-    protected final CIFS cifs;
+    protected final SMB SMB;
 
-    public CifsServer(XMLServerConfiguration serverConfiguration, CIFS cifs){
+    public CifsServer(XMLServerConfiguration serverConfiguration, SMB SMB){
         super();
 
-        this.cifs = cifs;
+        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 = cifs.getLocalIp();
+        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");
@@ -85,17 +95,17 @@ public class CifsServer extends JLANCifsServer {
         temp.mkdir();
 
         // SHARES
-        DiskInterface diskInterface = new PseudoJavaFileDiskDriver(cifs);
+        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("JLANSHARE", driverConfig);
-        diskDeviceContext.setShareName("JLANSHARE");
+        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("JLANSHARE", diskInterface, diskDeviceContext);
+        DiskSharedDevice diskDev = new DiskSharedDevice("SHARE", diskInterface, diskDeviceContext);
         diskDev.setConfiguration(serverConfiguration);
         diskDeviceContext.startFilesystem(diskDev);
         filesysConfig.addShare(diskDev);
@@ -127,27 +137,27 @@ public class CifsServer extends JLANCifsServer {
                 public void sessionClosed(SrvSession sess) {
 
 
-                    cifs.log(MessageRecord.TYPE.RECEIVE, "SESSION CLOSED", 139, sess.getRemoteAddress(), 139);
+                    SMB.log(MessageRecord.TYPE.RECEIVE, "SESSION CLOSED", 139, sess.getRemoteAddress(), 139);
                 }
 
                 @Override
                 public void sessionCreated(SrvSession sess) {
-                    cifs.getListener().getService().notifyUI(Handler.class.getName(),
+                    SMB.getListener().getService().notifyUI(Handler.class.getName(),
                             new String[] {
-                                    cifs.getListener().getService().getString(R.string.broadcast_started),
-                                    cifs.getListener().getProtocol().toString(),
-                                    Integer.toString(cifs.getListener().getPort())
+                                    SMB.getListener().getService().getString(R.string.broadcast_started),
+                                    SMB.getListener().getProtocol().toString(),
+                                    Integer.toString(SMB.getListener().getPort())
                             }
                     );
 
-                    cifs.log(MessageRecord.TYPE.RECEIVE, "SESSION CREATED", 139, sess.getRemoteAddress(), 139);
+                    SMB.log(MessageRecord.TYPE.RECEIVE, "SESSION CREATED", 139, sess.getRemoteAddress(), 139);
 
                 }
 
                 @Override
                 public void sessionLoggedOn(SrvSession sess) {
 
-                    cifs.log(MessageRecord.TYPE.RECEIVE, "SESSION LOGGED ON", 139, sess.getRemoteAddress(), 139);
+                    SMB.log(MessageRecord.TYPE.RECEIVE, "SESSION LOGGED ON", 139, sess.getRemoteAddress(), 139);
 
                 }
             });
@@ -156,6 +166,9 @@ public class CifsServer extends JLANCifsServer {
         }
     }
 
+    /**
+     * stops the server
+     */
     public void stop(){
         for(int i=0; i<serverConfiguration.numberOfServers(); i++){
             NetworkServer server = serverConfiguration.getServer(i);
@@ -163,11 +176,13 @@ public class CifsServer extends JLANCifsServer {
         }
     }
 
+    /**
+     * 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
-        System.out.println("DEBUG:::::IP::::"+dhcp.ipAddress);
         int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
         byte[] quads = new byte[4];
         for (int k = 0; k < 4; k++)
@@ -175,6 +190,9 @@ public class CifsServer extends JLANCifsServer {
         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)),
@@ -187,4 +205,15 @@ public class CifsServer extends JLANCifsServer {
             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();
+    }
 }

+ 22 - 10
src/de/tudarmstadt/informatik/hostage/protocol/cifs/PseudoJavaFileDiskDriver.java

@@ -18,23 +18,34 @@ import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 
 import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
-import de.tudarmstadt.informatik.hostage.protocol.CIFS;
+import de.tudarmstadt.informatik.hostage.protocol.SMB;
 
 /**
- * Created by Daniel on 26.03.2015.
+ * 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 CIFS cifs;
+        protected final SMB SMB;
         private final SrvSession sess;
         boolean wasWrittenTo = false;
 
-        public PseudoJavaNetworkFile(File file, String netPath, CIFS cifs, SrvSession sess) {
+        public PseudoJavaNetworkFile(File file, String netPath, SMB SMB, SrvSession sess) {
             super(file, netPath);
-            this.cifs = cifs;
+            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){
@@ -53,12 +64,13 @@ public class PseudoJavaFileDiskDriver extends JavaFileDiskDriver {
 
                     String message = "File received: " + m_file.getName() + "\n\nCHECKSUM:\n" + checksum;
 
-                    cifs.log(MessageRecord.TYPE.RECEIVE, message, 445, sess.getRemoteAddress(), 445);
+                    SMB.log(MessageRecord.TYPE.RECEIVE, message, 445, sess.getRemoteAddress(), 445);
                 } catch (NoSuchAlgorithmException e) {
                     e.printStackTrace();
                 }
 
                 m_file.delete();
+                wasWrittenTo = false;
             }
         }
 
@@ -75,10 +87,10 @@ public class PseudoJavaFileDiskDriver extends JavaFileDiskDriver {
         }
     }
 
-    private final CIFS cifs;
+    private final SMB SMB;
 
-    public PseudoJavaFileDiskDriver(CIFS cifs) {
-        this.cifs = cifs;
+    public PseudoJavaFileDiskDriver(SMB SMB) {
+        this.SMB = SMB;
     }
 
     public NetworkFile createFile(SrvSession sess, TreeConnection tree, FileOpenParams params)
@@ -100,7 +112,7 @@ public class PseudoJavaFileDiskDriver extends JavaFileDiskDriver {
         //  Create a Java network file
 
         file = new File(fname);
-        PseudoJavaNetworkFile netFile = new PseudoJavaNetworkFile(file, params.getPath(), cifs, sess);
+        PseudoJavaNetworkFile netFile = new PseudoJavaNetworkFile(file, params.getPath(), SMB, sess);
         netFile.setGrantedAccess(NetworkFile.READWRITE);
         netFile.setFullName(params.getPath());