Listener.java 9.5 KB

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