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