Listener.java 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. try {
  122. server = new MyServerSocketFactory().createServerSocket(port);
  123. if (server == null)
  124. return false;
  125. if (protocol.toString().equals("SMB")) {
  126. ((SMB) protocol).setIP(HelperUtils.inetAddressToString(Hostage.getContext()
  127. .getSharedPreferences(
  128. Hostage.getContext().getString(R.string.connection_info),
  129. Hostage.MODE_PRIVATE)
  130. .getInt(Hostage.getContext()
  131. .getString(R.string.connection_info_internal_ip), 0)));
  132. }
  133. (this.thread = new Thread(this)).start();
  134. running = true;
  135. service.notifyUI(this.getClass().getName(),
  136. new String[] { service.getString(R.string.broadcast_started), protocol.toString(), Integer.toString(port) });
  137. return true;
  138. } catch (IOException e) {
  139. return false;
  140. }
  141. }
  142. /**
  143. * Stops the listener. Closes the server socket, interrupts the Thread its
  144. * running in and notifies the background service.
  145. */
  146. public void stop() {
  147. try {
  148. server.close();
  149. thread.interrupt();
  150. running = false;
  151. service.notifyUI(this.getClass().getName(),
  152. new String[] { service.getString(R.string.broadcast_stopped), protocol.toString(), Integer.toString(port) });
  153. HelperUtils.deletePort(protocol.toString(),port);
  154. } catch (IOException e) {
  155. }
  156. }
  157. /**
  158. * Waits for an incoming connection, accepts it and starts a {@link Handler}
  159. */
  160. private void addHandler() {
  161. if (conReg.isConnectionFree()) {
  162. try {
  163. final Socket client = server.accept();
  164. new Thread( new Runnable() {
  165. @Override
  166. public void run() {
  167. try {
  168. String ip = client.getInetAddress().getHostAddress();
  169. if (ConnectionGuard.registerConnection(port, ip)){
  170. return;
  171. }
  172. Log.i("sda", "pause");
  173. Thread.sleep(999);
  174. if(ConnectionGuard.detectedPortscan(port, ip)){
  175. logPortscan(client, System.currentTimeMillis());
  176. }else{
  177. if (protocol.isSecure()) {
  178. startSecureHandler(client);
  179. } else {
  180. startHandler(client);
  181. }
  182. conReg.newOpenConnection();
  183. }
  184. } catch (Exception e) {
  185. e.printStackTrace();
  186. }
  187. }
  188. }).start();
  189. } catch (Exception e) {
  190. e.printStackTrace();
  191. }
  192. }
  193. }
  194. /**
  195. * Creates a new instance of an {@link Handler}.
  196. *
  197. * @param service
  198. * The background service
  199. * @param listener
  200. * The listener that created the handler
  201. * @param protocol
  202. * The Protocol the handler will run on
  203. * @param client
  204. * The Socket the handler uses
  205. * @return A Instance of a {@link Handler} with the specified parameter.
  206. */
  207. private Handler newInstance(Hostage service, Listener listener, Protocol protocol, Socket client) {
  208. return new Handler(service, listener, protocol, client);
  209. }
  210. /**
  211. * Starts a {@link Handler} with the given socket.
  212. *
  213. * @param client
  214. * The socket with the accepted connection.
  215. * @throws Exception
  216. */
  217. private void startHandler(Socket client) throws Exception {
  218. handlers.add(newInstance(service, this, protocol.getClass().newInstance(), client));
  219. }
  220. /**
  221. * Creates a SSLSocket out of the given socket and starts a {@link Handler}.
  222. *
  223. * @param client
  224. * The socket with the accepted connection.
  225. * @throws Exception
  226. */
  227. private void startSecureHandler(Socket client) throws Exception {
  228. SSLContext sslContext = ((SSLProtocol) protocol).getSSLContext();
  229. SSLSocketFactory factory = sslContext.getSocketFactory();
  230. SSLSocket sslClient = (SSLSocket) factory.createSocket(client, null, client.getPort(), false);
  231. sslClient.setUseClientMode(false);
  232. handlers.add(newInstance(service, this, protocol.getClass().newInstance(), sslClient));
  233. }
  234. /**
  235. * Logs a port scan attack
  236. * @param client The socket on which a port scan has been detected.
  237. * @param timestamp Timestamp when the portscan has been detected.
  238. */
  239. private void logPortscan(Socket client, long timestamp){
  240. SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(service);
  241. SharedPreferences connInfo = service.getSharedPreferences(service.getString(R.string.connection_info), Context.MODE_PRIVATE);
  242. AttackRecord attackRecord = new AttackRecord(true);
  243. attackRecord.setProtocol("PORTSCAN");
  244. attackRecord.setExternalIP(connInfo.getString(service.getString(R.string.connection_info_external_ip), null));
  245. attackRecord.setLocalIP(client.getLocalAddress().getHostAddress());
  246. attackRecord.setLocalPort(0);
  247. attackRecord.setRemoteIP(client.getInetAddress().getHostAddress());
  248. attackRecord.setRemotePort(client.getPort());
  249. attackRecord.setBssid(connInfo.getString(service.getString(R.string.connection_info_bssid), null));
  250. NetworkRecord networkRecord = new NetworkRecord();
  251. networkRecord.setBssid(connInfo.getString(service.getString(R.string.connection_info_bssid), null));
  252. networkRecord.setSsid(connInfo.getString(service.getString(R.string.connection_info_ssid), null));
  253. if (MyLocationManager.getNewestLocation() != null) {
  254. networkRecord.setLatitude(MyLocationManager.getNewestLocation().getLatitude());
  255. networkRecord.setLongitude(MyLocationManager.getNewestLocation().getLongitude());
  256. networkRecord.setAccuracy(MyLocationManager.getNewestLocation().getAccuracy());
  257. networkRecord.setTimestampLocation(MyLocationManager.getNewestLocation().getTime());
  258. } else {
  259. networkRecord.setLatitude(0.0);
  260. networkRecord.setLongitude(0.0);
  261. networkRecord.setAccuracy(Float.MAX_VALUE);
  262. networkRecord.setTimestampLocation(0);
  263. }
  264. Logger.logPortscan(Hostage.getContext(), attackRecord, networkRecord, timestamp);
  265. }
  266. }