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