Listener.java 10 KB

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