ConnectionGuard.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 ONE_SECOND_IN_NANOSECONDS = 1000000000;
  16. private static long lastTimestamp = 0;
  17. private static String lastIP = "";
  18. private static int lastPort = 0;
  19. /**
  20. * Register a connection for port scan detection. Stores information about the last connection.
  21. * @param port The local port used for communication.
  22. * @param ip The IP address of the remote device.
  23. * @return True if a port scan has been detected.
  24. */
  25. public synchronized static boolean registerConnection(int port, String ip) {
  26. long timestamp = System.nanoTime();
  27. boolean result = detectedPortscan(port, ip, timestamp);
  28. lastTimestamp = timestamp;
  29. lastIP = ip;
  30. lastPort = port;
  31. return result;
  32. }
  33. /**
  34. * Check if the new connection is part of a port scan attack.
  35. * @param port The local port used for communication.
  36. * @param ip The IP address of the remote device.
  37. * @return True if a port scan has been detected.
  38. */
  39. public synchronized static boolean detectedPortscan(int port, String ip){
  40. return detectedPortscan(port, ip, System.nanoTime());
  41. }
  42. /**
  43. * Check if the new connection is part of a port scan attack.
  44. * @param port The local port used for communication.
  45. * @param ip The IP address of the remote device.
  46. * @param timestamp Time stamp of connection
  47. * @return True if a port scan has been detected.
  48. */
  49. private synchronized static boolean detectedPortscan(int port, String ip, long timestamp) {
  50. Log.i("Alte Werte:", "LastTime: " + lastTimestamp + " ,LastIP: " + lastIP + ", lastPort:" + port);
  51. Log.i("Alte Werte:", "Time: " + timestamp + " ,IP: " + ip + ", Port:" + port);
  52. boolean result = false;
  53. boolean firstConnection = (lastTimestamp == 0);
  54. boolean belowThreshold = ((timestamp - lastTimestamp) < ONE_SECOND_IN_NANOSECONDS);
  55. boolean sameIP = (lastIP.equals(ip));
  56. boolean samePort = (lastPort == port);
  57. if (!firstConnection && sameIP && belowThreshold && !samePort) {
  58. result = true;
  59. }
  60. return result;
  61. }
  62. }