Listener.java 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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 javax.net.ssl.SSLContext;
  8. import javax.net.ssl.SSLSocket;
  9. import javax.net.ssl.SSLSocketFactory;
  10. import android.content.Context;
  11. import android.content.SharedPreferences;
  12. import android.content.SharedPreferences.Editor;
  13. import android.preference.PreferenceManager;
  14. import android.util.Log;
  15. import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
  16. import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
  17. import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
  18. import de.tudarmstadt.informatik.hostage.logging.Logger;
  19. import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
  20. import de.tudarmstadt.informatik.hostage.net.MyServerSocketFactory;
  21. import de.tudarmstadt.informatik.hostage.protocol.Protocol;
  22. import de.tudarmstadt.informatik.hostage.protocol.SMB;
  23. import de.tudarmstadt.informatik.hostage.protocol.SSLProtocol;
  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. /**
  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. /**
  87. * Determines if the service is running.
  88. *
  89. * @return True if the service is running, else false.
  90. */
  91. public boolean isRunning() {
  92. return running;
  93. }
  94. /**
  95. * Remove all terminated handlers from its internal ArrayList.
  96. */
  97. public void refreshHandlers() {
  98. for (Iterator<Handler> iterator = handlers.iterator(); iterator.hasNext();) {
  99. Handler handler = iterator.next();
  100. if (handler.isTerminated()) {
  101. conReg.closeConnection();
  102. iterator.remove();
  103. }
  104. }
  105. }
  106. @Override
  107. public void run() {
  108. while (!thread.isInterrupted()) {
  109. addHandler();
  110. }
  111. for (Handler handler : handlers) {
  112. //TODO kann ConcurrentModificationException auslösen, da über collection iteriert wird während elemente entfernt werden
  113. handler.kill();
  114. }
  115. }
  116. /**
  117. * Starts the listener. Creates a server socket runs itself in a new Thread
  118. * and notifies the background service.
  119. */
  120. public boolean start() {
  121. if (protocol.toString().equals("SMB")) {
  122. return false; // disable smb for the moment to prevent crashes
  123. }
  124. try {
  125. server = new MyServerSocketFactory().createServerSocket(port);
  126. if (server == null)
  127. return false;
  128. if (protocol.toString().equals("SMB")) {
  129. ((SMB) protocol).setIP(HelperUtils.inetAddressToString(Hostage.getContext()
  130. .getSharedPreferences(
  131. Hostage.getContext().getString(R.string.connection_info),
  132. Hostage.MODE_PRIVATE)
  133. .getInt(Hostage.getContext()
  134. .getString(R.string.connection_info_internal_ip), 0)));
  135. }
  136. (this.thread = new Thread(this)).start();
  137. running = true;
  138. service.notifyUI(this.getClass().getName(),
  139. new String[] { service.getString(R.string.broadcast_started), protocol.toString(), Integer.toString(port) });
  140. return true;
  141. } catch (IOException e) {
  142. return false;
  143. }
  144. }
  145. /**
  146. * Stops the listener. Closes the server socket, interrupts the Thread its
  147. * running in and notifies the background service.
  148. */
  149. public void stop() {
  150. try {
  151. server.close();
  152. thread.interrupt();
  153. running = false;
  154. service.notifyUI(this.getClass().getName(),
  155. new String[] { service.getString(R.string.broadcast_stopped), protocol.toString(), Integer.toString(port) });
  156. } catch (IOException e) {
  157. }
  158. }
  159. /**
  160. * Waits for an incoming connection, accepts it and starts a {@link Handler}
  161. */
  162. private void addHandler() {
  163. if (conReg.isConnectionFree()) {
  164. try {
  165. final Socket client = server.accept();
  166. new Thread( new Runnable() {
  167. @Override
  168. public void run() {
  169. try {
  170. String ip = client.getInetAddress().getHostAddress();
  171. if (ConnectionGuard.registerConnection(port, ip)){
  172. return;
  173. }
  174. Log.i("sda", "pause");
  175. Thread.sleep(999);
  176. if(ConnectionGuard.detectedPortscan(port, ip)){
  177. logPortscan(client, System.currentTimeMillis());
  178. }else{
  179. if (protocol.isSecure()) {
  180. startSecureHandler(client);
  181. } else {
  182. startHandler(client);
  183. }
  184. conReg.newOpenConnection();
  185. }
  186. } catch (Exception e) {
  187. e.printStackTrace();
  188. }
  189. }
  190. }).start();
  191. } catch (Exception e) {
  192. e.printStackTrace();
  193. }
  194. }
  195. }
  196. /**
  197. * Creates a new instance of an {@link Handler}.
  198. *
  199. * @param service
  200. * The background service
  201. * @param listener
  202. * The listener that created the handler
  203. * @param protocol
  204. * The Protocol the handler will run on
  205. * @param client
  206. * The Socket the handler uses
  207. * @return A Instance of a {@link Handler} with the specified parameter.
  208. */
  209. private Handler newInstance(Hostage service, Listener listener, Protocol protocol, Socket client) {
  210. return new Handler(service, listener, protocol, client);
  211. }
  212. /**
  213. * Starts a {@link Handler} with the given socket.
  214. *
  215. * @param client
  216. * The socket with the accepted connection.
  217. * @throws Exception
  218. */
  219. private void startHandler(Socket client) throws Exception {
  220. handlers.add(newInstance(service, this, protocol.getClass().newInstance(), client));
  221. }
  222. /**
  223. * Creates a SSLSocket out of the given socket and starts a {@link Handler}.
  224. *
  225. * @param client
  226. * The socket with the accepted connection.
  227. * @throws Exception
  228. */
  229. private void startSecureHandler(Socket client) throws Exception {
  230. SSLContext sslContext = ((SSLProtocol) protocol).getSSLContext();
  231. SSLSocketFactory factory = sslContext.getSocketFactory();
  232. SSLSocket sslClient = (SSLSocket) factory.createSocket(client, null, client.getPort(), false);
  233. sslClient.setUseClientMode(false);
  234. handlers.add(newInstance(service, this, protocol.getClass().newInstance(), sslClient));
  235. }
  236. /**
  237. * Logs a port scan attack
  238. * @param client The socket on which a port scan has been detected.
  239. * @param timestamp Timestamp when the portscan has been detected.
  240. */
  241. private void logPortscan(Socket client, long timestamp){
  242. SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(service);
  243. SharedPreferences connInfo = service.getSharedPreferences(service.getString(R.string.connection_info), Context.MODE_PRIVATE);
  244. AttackRecord attackRecord = new AttackRecord(true);
  245. attackRecord.setProtocol("PORTSCAN");
  246. attackRecord.setExternalIP(connInfo.getString(service.getString(R.string.connection_info_external_ip), null));
  247. attackRecord.setLocalIP(client.getLocalAddress().getHostAddress());
  248. attackRecord.setLocalPort(0);
  249. attackRecord.setRemoteIP(client.getInetAddress().getHostAddress());
  250. attackRecord.setRemotePort(client.getPort());
  251. attackRecord.setBssid(connInfo.getString(service.getString(R.string.connection_info_bssid), null));
  252. NetworkRecord networkRecord = new NetworkRecord();
  253. networkRecord.setBssid(connInfo.getString(service.getString(R.string.connection_info_bssid), null));
  254. networkRecord.setSsid(connInfo.getString(service.getString(R.string.connection_info_ssid), null));
  255. if (MyLocationManager.getNewestLocation() != null) {
  256. networkRecord.setLatitude(MyLocationManager.getNewestLocation().getLatitude());
  257. networkRecord.setLongitude(MyLocationManager.getNewestLocation().getLongitude());
  258. networkRecord.setAccuracy(MyLocationManager.getNewestLocation().getAccuracy());
  259. networkRecord.setTimestampLocation(MyLocationManager.getNewestLocation().getTime());
  260. } else {
  261. networkRecord.setLatitude(0.0);
  262. networkRecord.setLongitude(0.0);
  263. networkRecord.setAccuracy(Float.MAX_VALUE);
  264. networkRecord.setTimestampLocation(0);
  265. }
  266. Logger.logPortscan(Hostage.getContext(), attackRecord, networkRecord, timestamp);
  267. }
  268. }