Listener.java 10 KB

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