Listener.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. public Protocol getProtocol() {
  91. return protocol;
  92. }
  93. public Hostage getService() {
  94. return service;
  95. }
  96. /**
  97. * Determines if the service is running.
  98. *
  99. * @return True if the service is running, else false.
  100. */
  101. public boolean isRunning() {
  102. return running;
  103. }
  104. /**
  105. * Remove all terminated handlers from its internal ArrayList.
  106. */
  107. public void refreshHandlers() {
  108. for (Iterator<Handler> iterator = handlers.iterator(); iterator.hasNext();) {
  109. Handler handler = iterator.next();
  110. if (handler.isTerminated()) {
  111. conReg.closeConnection();
  112. iterator.remove();
  113. }
  114. }
  115. }
  116. @Override
  117. public void run() {
  118. if(protocol.toString().equals("CIFS")) return;
  119. while (!thread.isInterrupted()) {
  120. addHandler();
  121. }
  122. for (Handler handler : handlers) {
  123. //TODO kann ConcurrentModificationException auslösen, da über collection iteriert wird während elemente entfernt werden
  124. handler.kill();
  125. }
  126. }
  127. /**
  128. * Starts the listener. Creates a server socket runs itself in a new Thread
  129. * and notifies the background service.
  130. */
  131. public boolean start() {
  132. if (protocol.toString().equals("SMB")) {
  133. return false; // disable smb for the moment to prevent crashes
  134. }
  135. if(protocol.toString().equals("CIFS")){
  136. ((CIFS) protocol).initialize(this);
  137. }
  138. try {
  139. server = new MyServerSocketFactory().createServerSocket(port);
  140. if (server == null)
  141. return false;
  142. if (protocol.toString().equals("SMB")) {
  143. ((SMB) protocol).setIP(HelperUtils.inetAddressToString(Hostage.getContext()
  144. .getSharedPreferences(
  145. Hostage.getContext().getString(R.string.connection_info),
  146. Hostage.MODE_PRIVATE)
  147. .getInt(Hostage.getContext()
  148. .getString(R.string.connection_info_internal_ip), 0)));
  149. }
  150. (this.thread = new Thread(this)).start();
  151. running = true;
  152. service.notifyUI(this.getClass().getName(),
  153. new String[] { service.getString(R.string.broadcast_started), protocol.toString(), Integer.toString(port) });
  154. return true;
  155. } catch (IOException e) {
  156. return false;
  157. }
  158. }
  159. /**
  160. * Stops the listener. Closes the server socket, interrupts the Thread its
  161. * running in and notifies the background service.
  162. */
  163. public void stop() {
  164. try {
  165. if(protocol.toString().equals("CIFS")){
  166. ((CIFS) protocol).stop();
  167. }
  168. server.close();
  169. thread.interrupt();
  170. running = false;
  171. service.notifyUI(this.getClass().getName(),
  172. new String[] { service.getString(R.string.broadcast_stopped), protocol.toString(), Integer.toString(port) });
  173. } catch (IOException e) {
  174. }
  175. }
  176. /**
  177. * Waits for an incoming connection, accepts it and starts a {@link Handler}
  178. */
  179. private void addHandler() {
  180. if (conReg.isConnectionFree()) {
  181. try {
  182. final Socket client = server.accept();
  183. if (ConnectionGuard.portscanInProgress()) {
  184. // ignore everything for the duration of the port scan
  185. client.close();
  186. return;
  187. }
  188. new Thread( new Runnable() {
  189. @Override
  190. public void run() {
  191. try {
  192. String ip = client.getInetAddress().getHostAddress();
  193. // the mutex should prevent multiple logging of a portscan
  194. mutex.acquire();
  195. if (ConnectionGuard.portscanInProgress()) {
  196. mutex.release();
  197. client.close();
  198. return;
  199. }
  200. if (ConnectionGuard.registerConnection(port, ip)) { // returns true when a port scan is detected
  201. logPortscan(client, System.currentTimeMillis());
  202. mutex.release();
  203. client.close();
  204. return;
  205. }
  206. mutex.release();
  207. Thread.sleep(100); // wait to see if other listeners detected a portscan
  208. if (ConnectionGuard.portscanInProgress()) {
  209. client.close();
  210. return; // prevent starting a handler
  211. }
  212. if (protocol.isSecure()) {
  213. startSecureHandler(client);
  214. } else {
  215. startHandler(client);
  216. }
  217. conReg.newOpenConnection();
  218. } catch (Exception e) {
  219. e.printStackTrace();
  220. }
  221. }
  222. }).start();
  223. } catch (Exception e) {
  224. e.printStackTrace();
  225. }
  226. }
  227. }
  228. /**
  229. * Creates a new instance of an {@link Handler}.
  230. *
  231. * @param service
  232. * The background service
  233. * @param listener
  234. * The listener that created the handler
  235. * @param protocol
  236. * The Protocol the handler will run on
  237. * @param client
  238. * The Socket the handler uses
  239. * @return A Instance of a {@link Handler} with the specified parameter.
  240. */
  241. private Handler newInstance(Hostage service, Listener listener, Protocol protocol, Socket client) {
  242. return new Handler(service, listener, protocol, client);
  243. }
  244. /**
  245. * Starts a {@link Handler} with the given socket.
  246. *
  247. * @param client
  248. * The socket with the accepted connection.
  249. * @throws Exception
  250. */
  251. private void startHandler(Socket client) throws Exception {
  252. handlers.add(newInstance(service, this, protocol.toString().equals("CIFS") ? protocol : protocol.getClass().newInstance(), client));
  253. }
  254. /**
  255. * Creates a SSLSocket out of the given socket and starts a {@link Handler}.
  256. *
  257. * @param client
  258. * The socket with the accepted connection.
  259. * @throws Exception
  260. */
  261. private void startSecureHandler(Socket client) throws Exception {
  262. SSLContext sslContext = ((SSLProtocol) protocol).getSSLContext();
  263. SSLSocketFactory factory = sslContext.getSocketFactory();
  264. SSLSocket sslClient = (SSLSocket) factory.createSocket(client, null, client.getPort(), false);
  265. sslClient.setUseClientMode(false);
  266. handlers.add(newInstance(service, this, protocol.toString().equals("CIFS") ? protocol : protocol.getClass().newInstance(), sslClient));
  267. }
  268. /**
  269. * Logs a port scan attack and notifies ui about the portscan
  270. * @param client The socket on which a port scan has been detected.
  271. * @param timestamp Timestamp when the portscan has been detected.
  272. */
  273. private void logPortscan(Socket client, long timestamp){
  274. SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(service);
  275. SharedPreferences connInfo = service.getSharedPreferences(service.getString(R.string.connection_info), Context.MODE_PRIVATE);
  276. AttackRecord attackRecord = new AttackRecord(true);
  277. attackRecord.setProtocol("PORTSCAN");
  278. attackRecord.setExternalIP(connInfo.getString(service.getString(R.string.connection_info_external_ip), null));
  279. attackRecord.setLocalIP(client.getLocalAddress().getHostAddress());
  280. attackRecord.setLocalPort(0);
  281. attackRecord.setRemoteIP(client.getInetAddress().getHostAddress());
  282. attackRecord.setRemotePort(client.getPort());
  283. attackRecord.setBssid(connInfo.getString(service.getString(R.string.connection_info_bssid), null));
  284. NetworkRecord networkRecord = new NetworkRecord();
  285. networkRecord.setBssid(connInfo.getString(service.getString(R.string.connection_info_bssid), null));
  286. networkRecord.setSsid(connInfo.getString(service.getString(R.string.connection_info_ssid), null));
  287. if (MyLocationManager.getNewestLocation() != null) {
  288. networkRecord.setLatitude(MyLocationManager.getNewestLocation().getLatitude());
  289. networkRecord.setLongitude(MyLocationManager.getNewestLocation().getLongitude());
  290. networkRecord.setAccuracy(MyLocationManager.getNewestLocation().getAccuracy());
  291. networkRecord.setTimestampLocation(MyLocationManager.getNewestLocation().getTime());
  292. } else {
  293. networkRecord.setLatitude(0.0);
  294. networkRecord.setLongitude(0.0);
  295. networkRecord.setAccuracy(Float.MAX_VALUE);
  296. networkRecord.setTimestampLocation(0);
  297. }
  298. Logger.logPortscan(Hostage.getContext(), attackRecord, networkRecord, timestamp);
  299. // now that the record exists we can inform the ui
  300. // only handler informs about attacks so its name is used here
  301. service.notifyUI(Handler.class.getName(),
  302. new String[]{service.getString(R.string.broadcast_started), "PORTSCAN",
  303. Integer.toString(client.getPort())});
  304. }
  305. }