Listener.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. package de.tudarmstadt.informatik.hostage;
  2. import java.io.IOException;
  3. import java.net.ServerSocket;
  4. import java.net.Socket;
  5. import java.util.ArrayList;
  6. import java.util.Iterator;
  7. import java.util.concurrent.Semaphore;
  8. import java.util.concurrent.locks.Lock;
  9. import javax.net.ssl.SSLContext;
  10. import javax.net.ssl.SSLSocket;
  11. import javax.net.ssl.SSLSocketFactory;
  12. import android.content.Context;
  13. import android.content.SharedPreferences;
  14. import android.content.SharedPreferences.Editor;
  15. import android.preference.PreferenceManager;
  16. import android.util.Log;
  17. import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
  18. import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
  19. import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
  20. import de.tudarmstadt.informatik.hostage.logging.Logger;
  21. import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
  22. import de.tudarmstadt.informatik.hostage.net.MyServerSocketFactory;
  23. import de.tudarmstadt.informatik.hostage.protocol.Protocol;
  24. import de.tudarmstadt.informatik.hostage.protocol.SMB;
  25. import de.tudarmstadt.informatik.hostage.protocol.SSLProtocol;
  26. /**
  27. * Protocol listener class:<br>
  28. * Creates a Socket on the port of a given protocol and listens for incoming
  29. * connections.<br>
  30. * For each connection creates a Socket and instantiate an {@link Handler}.
  31. *
  32. * @author Mihai Plasoianu
  33. * @author Wulf Pfeiffer
  34. */
  35. public class Listener implements Runnable {
  36. private ArrayList<Handler> handlers = new ArrayList<Handler>();
  37. private Protocol protocol;
  38. private ServerSocket server;
  39. private Thread thread;
  40. private int port;
  41. private Hostage service;
  42. private ConnectionRegister conReg;
  43. private boolean running = false;
  44. private static Semaphore mutex = new Semaphore(1); // to enable atomic section in portscan detection
  45. /**
  46. * Constructor for the class. Instantiate class variables.
  47. *
  48. * @param service
  49. * The Background service that started the listener.
  50. * @param protocol
  51. * The Protocol on which the listener is running.
  52. */
  53. public Listener(Hostage service, Protocol protocol) {
  54. this.service = service;
  55. this.protocol = protocol;
  56. port = protocol.getPort();
  57. conReg = new ConnectionRegister(service);
  58. }
  59. public Listener(Hostage service, Protocol protocol, int port) {
  60. this.service = service;
  61. this.protocol = protocol;
  62. this.port = port;
  63. conReg = new ConnectionRegister(service);
  64. }
  65. /**
  66. * Determines the amount of active handlers.
  67. *
  68. * @return The number of active handlers.
  69. */
  70. public int getHandlerCount() {
  71. return handlers.size();
  72. }
  73. /**
  74. * Return the port number on which the listener listening.
  75. *
  76. * @return Used port number.
  77. */
  78. public int getPort() {
  79. return port;
  80. }
  81. /**
  82. * Determine the name of the protocol the listener is running on.
  83. *
  84. * @return Name of the protocol
  85. */
  86. public String getProtocolName() {
  87. return protocol.toString();
  88. }
  89. /**
  90. * Determines if the service is running.
  91. *
  92. * @return True if the service is running, else false.
  93. */
  94. public boolean isRunning() {
  95. return running;
  96. }
  97. /**
  98. * Remove all terminated handlers from its internal ArrayList.
  99. */
  100. public void refreshHandlers() {
  101. for (Iterator<Handler> iterator = handlers.iterator(); iterator.hasNext();) {
  102. Handler handler = iterator.next();
  103. if (handler.isTerminated()) {
  104. conReg.closeConnection();
  105. iterator.remove();
  106. }
  107. }
  108. }
  109. @Override
  110. public void run() {
  111. while (!thread.isInterrupted()) {
  112. addHandler();
  113. }
  114. for (Handler handler : handlers) {
  115. //TODO kann ConcurrentModificationException auslösen, da über collection iteriert wird während elemente entfernt werden
  116. handler.kill();
  117. }
  118. }
  119. /**
  120. * Starts the listener. Creates a server socket runs itself in a new Thread
  121. * and notifies the background service.
  122. */
  123. public boolean start() {
  124. if (protocol.toString().equals("SMB")) {
  125. return false; // disable smb for the moment to prevent crashes
  126. }
  127. try {
  128. server = new MyServerSocketFactory().createServerSocket(port);
  129. if (server == null)
  130. return false;
  131. if (protocol.toString().equals("SMB")) {
  132. ((SMB) protocol).setIP(HelperUtils.inetAddressToString(Hostage.getContext()
  133. .getSharedPreferences(
  134. Hostage.getContext().getString(R.string.connection_info),
  135. Hostage.MODE_PRIVATE)
  136. .getInt(Hostage.getContext()
  137. .getString(R.string.connection_info_internal_ip), 0)));
  138. }
  139. (this.thread = new Thread(this)).start();
  140. running = true;
  141. service.notifyUI(this.getClass().getName(),
  142. new String[] { service.getString(R.string.broadcast_started), protocol.toString(), Integer.toString(port) });
  143. return true;
  144. } catch (IOException e) {
  145. return false;
  146. }
  147. }
  148. /**
  149. * Stops the listener. Closes the server socket, interrupts the Thread its
  150. * running in and notifies the background service.
  151. */
  152. public void stop() {
  153. try {
  154. server.close();
  155. thread.interrupt();
  156. running = false;
  157. service.notifyUI(this.getClass().getName(),
  158. new String[] { service.getString(R.string.broadcast_stopped), protocol.toString(), Integer.toString(port) });
  159. } catch (IOException e) {
  160. }
  161. }
  162. /**
  163. * Waits for an incoming connection, accepts it and starts a {@link Handler}
  164. */
  165. private void addHandler() {
  166. if (conReg.isConnectionFree()) {
  167. try {
  168. final Socket client = server.accept();
  169. if (ConnectionGuard.portscanInProgress()) {
  170. // ignore everything for the duration of the port scan
  171. client.close();
  172. return;
  173. }
  174. new Thread( new Runnable() {
  175. @Override
  176. public void run() {
  177. try {
  178. String ip = client.getInetAddress().getHostAddress();
  179. // the mutex should prevent multiple logging of a portscan
  180. mutex.acquire();
  181. if (ConnectionGuard.portscanInProgress()) {
  182. mutex.release();
  183. client.close();
  184. return;
  185. }
  186. if (ConnectionGuard.registerConnection(port, ip)) { // returns true when a port scan is detected
  187. logPortscan(client, System.currentTimeMillis());
  188. mutex.release();
  189. client.close();
  190. return;
  191. }
  192. mutex.release();
  193. Thread.sleep(100); // wait to see if other listeners detected a portscan
  194. if (ConnectionGuard.portscanInProgress()) {
  195. client.close();
  196. return; // prevent starting a handler
  197. }
  198. if (protocol.isSecure()) {
  199. startSecureHandler(client);
  200. } else {
  201. startHandler(client);
  202. }
  203. conReg.newOpenConnection();
  204. } catch (Exception e) {
  205. e.printStackTrace();
  206. }
  207. }
  208. }).start();
  209. } catch (Exception e) {
  210. e.printStackTrace();
  211. }
  212. }
  213. }
  214. /**
  215. * Creates a new instance of an {@link Handler}.
  216. *
  217. * @param service
  218. * The background service
  219. * @param listener
  220. * The listener that created the handler
  221. * @param protocol
  222. * The Protocol the handler will run on
  223. * @param client
  224. * The Socket the handler uses
  225. * @return A Instance of a {@link Handler} with the specified parameter.
  226. */
  227. private Handler newInstance(Hostage service, Listener listener, Protocol protocol, Socket client) {
  228. return new Handler(service, listener, protocol, client);
  229. }
  230. /**
  231. * Starts a {@link Handler} with the given socket.
  232. *
  233. * @param client
  234. * The socket with the accepted connection.
  235. * @throws Exception
  236. */
  237. private void startHandler(Socket client) throws Exception {
  238. handlers.add(newInstance(service, this, protocol.getClass().newInstance(), client));
  239. }
  240. /**
  241. * Creates a SSLSocket out of the given socket and starts a {@link Handler}.
  242. *
  243. * @param client
  244. * The socket with the accepted connection.
  245. * @throws Exception
  246. */
  247. private void startSecureHandler(Socket client) throws Exception {
  248. SSLContext sslContext = ((SSLProtocol) protocol).getSSLContext();
  249. SSLSocketFactory factory = sslContext.getSocketFactory();
  250. SSLSocket sslClient = (SSLSocket) factory.createSocket(client, null, client.getPort(), false);
  251. sslClient.setUseClientMode(false);
  252. handlers.add(newInstance(service, this, protocol.getClass().newInstance(), sslClient));
  253. }
  254. /**
  255. * Logs a port scan attack and notifies ui about the portscan
  256. * @param client The socket on which a port scan has been detected.
  257. * @param timestamp Timestamp when the portscan has been detected.
  258. */
  259. private void logPortscan(Socket client, long timestamp){
  260. SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(service);
  261. SharedPreferences connInfo = service.getSharedPreferences(service.getString(R.string.connection_info), Context.MODE_PRIVATE);
  262. AttackRecord attackRecord = new AttackRecord(true);
  263. attackRecord.setProtocol("PORTSCAN");
  264. attackRecord.setExternalIP(connInfo.getString(service.getString(R.string.connection_info_external_ip), null));
  265. attackRecord.setLocalIP(client.getLocalAddress().getHostAddress());
  266. attackRecord.setLocalPort(0);
  267. attackRecord.setRemoteIP(client.getInetAddress().getHostAddress());
  268. attackRecord.setRemotePort(client.getPort());
  269. attackRecord.setBssid(connInfo.getString(service.getString(R.string.connection_info_bssid), null));
  270. NetworkRecord networkRecord = new NetworkRecord();
  271. networkRecord.setBssid(connInfo.getString(service.getString(R.string.connection_info_bssid), null));
  272. networkRecord.setSsid(connInfo.getString(service.getString(R.string.connection_info_ssid), null));
  273. if (MyLocationManager.getNewestLocation() != null) {
  274. networkRecord.setLatitude(MyLocationManager.getNewestLocation().getLatitude());
  275. networkRecord.setLongitude(MyLocationManager.getNewestLocation().getLongitude());
  276. networkRecord.setAccuracy(MyLocationManager.getNewestLocation().getAccuracy());
  277. networkRecord.setTimestampLocation(MyLocationManager.getNewestLocation().getTime());
  278. } else {
  279. networkRecord.setLatitude(0.0);
  280. networkRecord.setLongitude(0.0);
  281. networkRecord.setAccuracy(Float.MAX_VALUE);
  282. networkRecord.setTimestampLocation(0);
  283. }
  284. Logger.logPortscan(Hostage.getContext(), attackRecord, networkRecord, timestamp);
  285. // now that the record exists we can inform the ui
  286. // only handler informs about attacks so its name is used here
  287. service.notifyUI(Handler.class.getName(),
  288. new String[]{service.getString(R.string.broadcast_started), "PORTSCAN",
  289. Integer.toString(client.getPort())});
  290. }
  291. }