Browse Source

added mutex to prevent race in port scan detection and multiple logging

Fabio Arnold 9 years ago
parent
commit
a223f7f237

+ 0 - 10
src/de/tudarmstadt/informatik/hostage/ConnectionGuard.java

@@ -47,16 +47,6 @@ public class ConnectionGuard {
 		return (System.currentTimeMillis() - lastPortscanTimestamp) < TIMESTAMP_THRESHOLD_MS;
 	}
 	
-	/**
-	 * Check if the new connection is part of a port scan attack.
-	 * @param port The local port used for communication.
-	 * @param ip The IP address of the remote device.
-	 * @return True if a port scan has been detected.
-	 */
-	public synchronized static boolean detectedPortscan(int port, String ip){
-		return detectedPortscan(port, ip, System.currentTimeMillis());
-	}
-	
 	/**
 	 * Check if the new connection is part of a port scan attack.
 	 * @param port The local port used for communication.

+ 24 - 2
src/de/tudarmstadt/informatik/hostage/Listener.java

@@ -5,6 +5,8 @@ import java.net.ServerSocket;
 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;
@@ -49,6 +51,8 @@ public class Listener implements Runnable {
 	private ConnectionRegister conReg;
 	private boolean running = false;
 
+	private static Semaphore mutex = new Semaphore(1); // to enable atomic section in portscan detection
+
 	/**
 	 * Constructor for the class. Instantiate class variables.
 	 * 
@@ -184,7 +188,8 @@ public class Listener implements Runnable {
 			try {
 				final Socket client = server.accept();
 				if (ConnectionGuard.portscanInProgress()) {
-					// stop logging attacks
+					// ignore everything for the duration of the port scan
+					client.close();
 					return;
 				}
 				new Thread( new Runnable() {
@@ -192,10 +197,27 @@ public class Listener implements Runnable {
 				    public void run() {
 				    	try {
 				    		String ip = client.getInetAddress().getHostAddress();
-				    		if (ConnectionGuard.registerConnection(port, ip)){ // returns true when a port scan is detected
+
+							// the mutex should prevent multiple logging of a portscan
+							mutex.acquire();
+							if (ConnectionGuard.portscanInProgress()) {
+								mutex.release();
+								client.close();
+								return;
+							}
+				    		if (ConnectionGuard.registerConnection(port, ip)) { // returns true when a port scan is detected
 								logPortscan(client, System.currentTimeMillis());
+								mutex.release();
+								client.close();
 				    			return;
 				    		}
+							mutex.release();
+							Thread.sleep(100); // wait to see if other listeners detected a portscan
+							if (ConnectionGuard.portscanInProgress()) {
+								client.close();
+								return; // prevent starting a handler
+							}
+
 							if (protocol.isSecure()) {
 								startSecureHandler(client);
 							} else {