Listener.java 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. package de.tudarmstadt.informatik.hostage;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.net.ServerSocket;
  6. import java.net.Socket;
  7. import java.security.SecureRandom;
  8. import java.util.ArrayList;
  9. import java.util.Iterator;
  10. import javax.net.ssl.SSLContext;
  11. import javax.net.ssl.SSLSocket;
  12. import javax.net.ssl.SSLSocketFactory;
  13. import android.content.Context;
  14. import android.content.SharedPreferences;
  15. import android.content.SharedPreferences.Editor;
  16. import android.os.AsyncTask;
  17. import android.preference.PreferenceManager;
  18. import android.util.Log;
  19. import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
  20. import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
  21. import de.tudarmstadt.informatik.hostage.logging.Logger;
  22. import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
  23. import de.tudarmstadt.informatik.hostage.net.MyServerSocketFactory;
  24. import de.tudarmstadt.informatik.hostage.protocol.HTTP;
  25. import de.tudarmstadt.informatik.hostage.protocol.Protocol;
  26. import de.tudarmstadt.informatik.hostage.protocol.SMB;
  27. import de.tudarmstadt.informatik.hostage.protocol.SSLProtocol;
  28. /**
  29. * Protocol listener class:<br>
  30. * Creates a Socket on the port of a given protocol and listens for incoming
  31. * connections.<br>
  32. * For each connection creates a Socket and instantiate an {@link Handler}.
  33. *
  34. * @author Mihai Plasoianu
  35. * @author Wulf Pfeiffer
  36. */
  37. public class Listener implements Runnable {
  38. private ArrayList<Handler> handlers = new ArrayList<Handler>();
  39. private Protocol protocol;
  40. private ServerSocket server;
  41. private Thread thread;
  42. private int port;
  43. private Hostage service;
  44. private ConnectionRegister conReg;
  45. private boolean running = false;
  46. /**
  47. * Constructor for the class. Instantiate class variables.
  48. *
  49. * @param service
  50. * The Background service that started the listener.
  51. * @param protocol
  52. * The Protocol on which the listener is running.
  53. */
  54. public Listener(Hostage service, Protocol protocol) {
  55. this.service = service;
  56. this.protocol = protocol;
  57. port = protocol.getPort();
  58. conReg = new ConnectionRegister(service);
  59. }
  60. public Listener(Hostage service, Protocol protocol, int port) {
  61. this.service = service;
  62. this.protocol = protocol;
  63. this.port = port;
  64. conReg = new ConnectionRegister(service);
  65. }
  66. /**
  67. * Determines the amount of active handlers.
  68. *
  69. * @return The number of active handlers.
  70. */
  71. public int getHandlerCount() {
  72. return handlers.size();
  73. }
  74. /**
  75. * Return the port number on which the listener listening.
  76. *
  77. * @return Used port number.
  78. */
  79. public int getPort() {
  80. return port;
  81. }
  82. /**
  83. * Determine the name of the protocol the listener is running on.
  84. *
  85. * @return Name of the protocol
  86. */
  87. public String getProtocolName() {
  88. return protocol.toString();
  89. }
  90. /**
  91. * Determines if the service is running.
  92. *
  93. * @return True if the service is running, else false.
  94. */
  95. public boolean isRunning() {
  96. return running;
  97. }
  98. /**
  99. * Remove all terminated handlers from its internal ArrayList.
  100. */
  101. public void refreshHandlers() {
  102. for (Iterator<Handler> iterator = handlers.iterator(); iterator.hasNext();) {
  103. Handler handler = iterator.next();
  104. if (handler.isTerminated()) {
  105. conReg.closeConnection();
  106. iterator.remove();
  107. }
  108. }
  109. }
  110. @Override
  111. public void run() {
  112. while (!thread.isInterrupted()) {
  113. addHandler();
  114. }
  115. for (Handler handler : handlers) {
  116. //TODO kann ConcurrentModificationException auslösen, da über collection iteriert wird während elemente entfernt werden
  117. handler.kill();
  118. }
  119. }
  120. /**
  121. * Starts the listener. Creates a server socket runs itself in a new Thread
  122. * and notifies the background service.
  123. */
  124. public boolean start() {
  125. try {
  126. server = new MyServerSocketFactory().createServerSocket(port);
  127. if (server == null)
  128. return false;
  129. if (protocol.toString().equals("SMB")) {
  130. ((SMB) protocol).setIP(Hostage.getContext()
  131. .getSharedPreferences(Hostage.getContext().getString(R.string.connection_info), Hostage.MODE_PRIVATE)
  132. .getString(Hostage.getContext().getString(R.string.connection_info_internal_ip), ""));
  133. }
  134. (this.thread = new Thread(this)).start();
  135. running = true;
  136. service.notifyUI(this.getClass().getName(),
  137. new String[] { service.getString(R.string.broadcast_started), protocol.toString(), Integer.toString(port) });
  138. return true;
  139. } catch (IOException e) {
  140. return false;
  141. }
  142. }
  143. /**
  144. * Stops the listener. Closes the server socket, interrupts the Thread its
  145. * running in and notifies the background service.
  146. */
  147. public void stop() {
  148. try {
  149. server.close();
  150. thread.interrupt();
  151. running = false;
  152. service.notifyUI(this.getClass().getName(),
  153. new String[] { service.getString(R.string.broadcast_stopped), protocol.toString(), Integer.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. final String protocolName = this.getProtocolName();
  165. new Thread( new Runnable() {
  166. @Override
  167. public void run() {
  168. try {
  169. String ip = client.getInetAddress().getHostAddress();
  170. if (ConnectionGuard.registerConnection(protocolName, ip)){
  171. Log.i("Listener", "Portscan detected.");
  172. return;
  173. }
  174. Thread.sleep(ConnectionGuard.ONE_SECOND_IN_NANOSECONDS / 1000);
  175. if(ConnectionGuard.detectedPortscan(protocolName, ip)){
  176. Log.i("Listener", "Portscan detected.");
  177. logPortscan(client);
  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. * Starts a Handler with Portscan as Protocol. Afterwards kills it. For Logging purpose only!
  238. */
  239. private void logPortscan(Socket client){
  240. SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(service);
  241. SharedPreferences connInfo = service.getSharedPreferences(service.getString(R.string.connection_info), Context.MODE_PRIVATE);
  242. Editor editor = pref.edit();
  243. int attack_id = pref.getInt("ATTACK_ID_COUNTER", 0);
  244. editor.putInt("ATTACK_ID_COUNTER", attack_id + 1);
  245. editor.commit();
  246. AttackRecord attackRecord = new AttackRecord();
  247. attackRecord.setAttack_id(attack_id);
  248. attackRecord.setProtocol("PORTSCAN");
  249. attackRecord.setExternalIP(connInfo.getString(service.getString(R.string.connection_info_external_ip), null));
  250. attackRecord.setLocalIP(client.getLocalAddress().getHostAddress());
  251. attackRecord.setLocalPort(0);
  252. attackRecord.setRemoteIP(client.getInetAddress().getHostAddress());
  253. attackRecord.setRemotePort(client.getPort());
  254. attackRecord.setBssid(connInfo.getString(service.getString(R.string.connection_info_bssid), null));
  255. NetworkRecord networkRecord = new NetworkRecord();
  256. networkRecord.setBssid(connInfo.getString(service.getString(R.string.connection_info_bssid), null));
  257. networkRecord.setSsid(connInfo.getString(service.getString(R.string.connection_info_ssid), null));
  258. if (MyLocationManager.getNewestLocation() != null) {
  259. networkRecord.setLatitude(MyLocationManager.getNewestLocation().getLatitude());
  260. networkRecord.setLongitude(MyLocationManager.getNewestLocation().getLongitude());
  261. networkRecord.setAccuracy(MyLocationManager.getNewestLocation().getAccuracy());
  262. networkRecord.setTimestampLocation(MyLocationManager.getNewestLocation().getTime());
  263. } else {
  264. networkRecord.setLatitude(0.0);
  265. networkRecord.setLongitude(0.0);
  266. networkRecord.setAccuracy(Float.MAX_VALUE);
  267. networkRecord.setTimestampLocation(0);
  268. }
  269. Logger.log(Hostage.getContext(), attackRecord);
  270. Logger.log(Hostage.getContext(), networkRecord);
  271. }
  272. }