Listener.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. System.out.println("PROTOCOL: " + protocol);
  137. ((CIFS) protocol).initialize(this);
  138. }
  139. try {
  140. server = new MyServerSocketFactory().createServerSocket(port);
  141. if (server == null)
  142. return false;
  143. if (protocol.toString().equals("SMB")) {
  144. ((SMB) protocol).setIP(HelperUtils.inetAddressToString(Hostage.getContext()
  145. .getSharedPreferences(
  146. Hostage.getContext().getString(R.string.connection_info),
  147. Hostage.MODE_PRIVATE)
  148. .getInt(Hostage.getContext()
  149. .getString(R.string.connection_info_internal_ip), 0)));
  150. }
  151. (this.thread = new Thread(this)).start();
  152. running = true;
  153. service.notifyUI(this.getClass().getName(),
  154. new String[] { service.getString(R.string.broadcast_started), protocol.toString(), Integer.toString(port) });
  155. return true;
  156. } catch (IOException e) {
  157. return false;
  158. }
  159. }
  160. /**
  161. * Stops the listener. Closes the server socket, interrupts the Thread its
  162. * running in and notifies the background service.
  163. */
  164. public void stop() {
  165. try {
  166. server.close();
  167. thread.interrupt();
  168. running = false;
  169. service.notifyUI(this.getClass().getName(),
  170. new String[] { service.getString(R.string.broadcast_stopped), protocol.toString(), Integer.toString(port) });
  171. } catch (IOException e) {
  172. }
  173. }
  174. /**
  175. * Waits for an incoming connection, accepts it and starts a {@link Handler}
  176. */
  177. private void addHandler() {
  178. if (conReg.isConnectionFree()) {
  179. try {
  180. final Socket client = server.accept();
  181. if (ConnectionGuard.portscanInProgress()) {
  182. // ignore everything for the duration of the port scan
  183. client.close();
  184. return;
  185. }
  186. new Thread( new Runnable() {
  187. @Override
  188. public void run() {
  189. try {
  190. String ip = client.getInetAddress().getHostAddress();
  191. // the mutex should prevent multiple logging of a portscan
  192. mutex.acquire();
  193. if (ConnectionGuard.portscanInProgress()) {
  194. mutex.release();
  195. client.close();
  196. return;
  197. }
  198. if (ConnectionGuard.registerConnection(port, ip)) { // returns true when a port scan is detected
  199. logPortscan(client, System.currentTimeMillis());
  200. mutex.release();
  201. client.close();
  202. return;
  203. }
  204. mutex.release();
  205. Thread.sleep(100); // wait to see if other listeners detected a portscan
  206. if (ConnectionGuard.portscanInProgress()) {
  207. client.close();
  208. return; // prevent starting a handler
  209. }
  210. if (protocol.isSecure()) {
  211. startSecureHandler(client);
  212. } else {
  213. startHandler(client);
  214. }
  215. conReg.newOpenConnection();
  216. } catch (Exception e) {
  217. e.printStackTrace();
  218. }
  219. }
  220. }).start();
  221. } catch (Exception e) {
  222. e.printStackTrace();
  223. }
  224. }
  225. }
  226. /**
  227. * Creates a new instance of an {@link Handler}.
  228. *
  229. * @param service
  230. * The background service
  231. * @param listener
  232. * The listener that created the handler
  233. * @param protocol
  234. * The Protocol the handler will run on
  235. * @param client
  236. * The Socket the handler uses
  237. * @return A Instance of a {@link Handler} with the specified parameter.
  238. */
  239. private Handler newInstance(Hostage service, Listener listener, Protocol protocol, Socket client) {
  240. return new Handler(service, listener, protocol, client);
  241. }
  242. /**
  243. * Starts a {@link Handler} with the given socket.
  244. *
  245. * @param client
  246. * The socket with the accepted connection.
  247. * @throws Exception
  248. */
  249. private void startHandler(Socket client) throws Exception {
  250. handlers.add(newInstance(service, this, protocol.toString().equals("CIFS") ? protocol : protocol.getClass().newInstance(), client));
  251. }
  252. /**
  253. * Creates a SSLSocket out of the given socket and starts a {@link Handler}.
  254. *
  255. * @param client
  256. * The socket with the accepted connection.
  257. * @throws Exception
  258. */
  259. private void startSecureHandler(Socket client) throws Exception {
  260. SSLContext sslContext = ((SSLProtocol) protocol).getSSLContext();
  261. SSLSocketFactory factory = sslContext.getSocketFactory();
  262. SSLSocket sslClient = (SSLSocket) factory.createSocket(client, null, client.getPort(), false);
  263. sslClient.setUseClientMode(false);
  264. handlers.add(newInstance(service, this, protocol.toString().equals("CIFS") ? protocol : protocol.getClass().newInstance(), sslClient));
  265. }
  266. /**
  267. * Logs a port scan attack and notifies ui about the portscan
  268. * @param client The socket on which a port scan has been detected.
  269. * @param timestamp Timestamp when the portscan has been detected.
  270. */
  271. private void logPortscan(Socket client, long timestamp){
  272. SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(service);
  273. SharedPreferences connInfo = service.getSharedPreferences(service.getString(R.string.connection_info), Context.MODE_PRIVATE);
  274. // only handler informs about attacks so its name is used here
  275. service.notifyUI(Handler.class.getName(), new String[] {service.getString(R.string.broadcast_started), "PORTSCAN", Integer.toString(
  276. client.getPort())});
  277. AttackRecord attackRecord = new AttackRecord(true);
  278. attackRecord.setProtocol("PORTSCAN");
  279. attackRecord.setExternalIP(connInfo.getString(service.getString(R.string.connection_info_external_ip), null));
  280. attackRecord.setLocalIP(client.getLocalAddress().getHostAddress());
  281. attackRecord.setLocalPort(0);
  282. attackRecord.setRemoteIP(client.getInetAddress().getHostAddress());
  283. attackRecord.setRemotePort(client.getPort());
  284. attackRecord.setBssid(connInfo.getString(service.getString(R.string.connection_info_bssid), null));
  285. NetworkRecord networkRecord = new NetworkRecord();
  286. networkRecord.setBssid(connInfo.getString(service.getString(R.string.connection_info_bssid), null));
  287. networkRecord.setSsid(connInfo.getString(service.getString(R.string.connection_info_ssid), null));
  288. if (MyLocationManager.getNewestLocation() != null) {
  289. networkRecord.setLatitude(MyLocationManager.getNewestLocation().getLatitude());
  290. networkRecord.setLongitude(MyLocationManager.getNewestLocation().getLongitude());
  291. networkRecord.setAccuracy(MyLocationManager.getNewestLocation().getAccuracy());
  292. networkRecord.setTimestampLocation(MyLocationManager.getNewestLocation().getTime());
  293. } else {
  294. networkRecord.setLatitude(0.0);
  295. networkRecord.setLongitude(0.0);
  296. networkRecord.setAccuracy(Float.MAX_VALUE);
  297. networkRecord.setTimestampLocation(0);
  298. }
  299. Logger.logPortscan(Hostage.getContext(), attackRecord, networkRecord, timestamp);
  300. }
  301. }