ConnectionGuard.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package de.tudarmstadt.informatik.hostage;
  2. import android.util.Log;
  3. /**
  4. * Class used to detect port scans.
  5. * We assume a port scan if at least 2 different ports get a connection in a small amount of time.
  6. *
  7. */
  8. public class ConnectionGuard {
  9. private final static ConnectionGuard INSTANCE = new ConnectionGuard();
  10. private ConnectionGuard() {
  11. }
  12. /**
  13. * Intervall between 2 connection in wich we assume a port scan
  14. */
  15. public final static long TIMESTAMP_THRESHOLD_MS = 60000;
  16. private static long lastConnectionTimestamp = 0;
  17. private static long lastPortscanTimestamp = 0;
  18. private static String lastIP = "";
  19. private static int lastPort = 0;
  20. /**
  21. * Register a connection for port scan detection. Stores information about the last connection.
  22. * @param port The local port used for communication.
  23. * @param ip The IP address of the remote device.
  24. * @return True if a port scan has been detected.
  25. */
  26. public synchronized static boolean registerConnection(int port, String ip) {
  27. long timestamp = System.currentTimeMillis();
  28. boolean result = detectedPortscan(port, ip, timestamp);
  29. lastConnectionTimestamp = timestamp;
  30. if (result) {
  31. lastPortscanTimestamp = timestamp;
  32. }
  33. lastIP = ip;
  34. lastPort = port;
  35. return result;
  36. }
  37. public synchronized static boolean portscanInProgress() {
  38. return (System.currentTimeMillis() - lastPortscanTimestamp) < TIMESTAMP_THRESHOLD_MS;
  39. }
  40. /**
  41. * Check if the new connection is part of a port scan attack.
  42. * @param port The local port used for communication.
  43. * @param ip The IP address of the remote device.
  44. * @param timestamp Time stamp of connection
  45. * @return True if a port scan has been detected.
  46. */
  47. private synchronized static boolean detectedPortscan(int port, String ip, long timestamp) {
  48. Log.i("Alte Werte:", "LastTime: " + lastConnectionTimestamp + " ,LastIP: " + lastIP + ", lastPort:" + port);
  49. Log.i("Alte Werte:", "Time: " + timestamp + " ,IP: " + ip + ", Port:" + port);
  50. boolean result = false;
  51. boolean belowThreshold = ((timestamp - lastConnectionTimestamp) < TIMESTAMP_THRESHOLD_MS);
  52. boolean sameIP = (lastIP.equals(ip));
  53. boolean samePort = (lastPort == port);
  54. if (sameIP && belowThreshold && !samePort) {
  55. result = true;
  56. }
  57. return result;
  58. }
  59. }