Listener.java 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. } catch (IOException e) {
  154. }
  155. }
  156. /**
  157. * Waits for an incoming connection, accepts it and starts a {@link Handler}
  158. */
  159. private void addHandler() {
  160. if (conReg.isConnectionFree()) {
  161. try {
  162. final Socket client = server.accept();
  163. new Thread( new Runnable() {
  164. @Override
  165. public void run() {
  166. try {
  167. String ip = client.getInetAddress().getHostAddress();
  168. if (ConnectionGuard.registerConnection(port, ip)){
  169. return;
  170. }
  171. Log.i("sda", "pause");
  172. Thread.sleep(999);
  173. if(ConnectionGuard.detectedPortscan(port, ip)){
  174. logPortscan(client, System.currentTimeMillis());
  175. }else{
  176. if (protocol.isSecure()) {
  177. startSecureHandler(client);
  178. } else {
  179. startHandler(client);
  180. }
  181. conReg.newOpenConnection();
  182. }
  183. } catch (Exception e) {
  184. e.printStackTrace();
  185. }
  186. }
  187. }).start();
  188. } catch (Exception e) {
  189. e.printStackTrace();
  190. }
  191. }
  192. }
  193. /**
  194. * Creates a new instance of an {@link Handler}.
  195. *
  196. * @param service
  197. * The background service
  198. * @param listener
  199. * The listener that created the handler
  200. * @param protocol
  201. * The Protocol the handler will run on
  202. * @param client
  203. * The Socket the handler uses
  204. * @return A Instance of a {@link Handler} with the specified parameter.
  205. */
  206. private Handler newInstance(Hostage service, Listener listener, Protocol protocol, Socket client) {
  207. return new Handler(service, listener, protocol, client);
  208. }
  209. /**
  210. * Starts a {@link Handler} with the given socket.
  211. *
  212. * @param client
  213. * The socket with the accepted connection.
  214. * @throws Exception
  215. */
  216. private void startHandler(Socket client) throws Exception {
  217. handlers.add(newInstance(service, this, protocol.getClass().newInstance(), client));
  218. }
  219. /**
  220. * Creates a SSLSocket out of the given socket and starts a {@link Handler}.
  221. *
  222. * @param client
  223. * The socket with the accepted connection.
  224. * @throws Exception
  225. */
  226. private void startSecureHandler(Socket client) throws Exception {
  227. SSLContext sslContext = ((SSLProtocol) protocol).getSSLContext();
  228. SSLSocketFactory factory = sslContext.getSocketFactory();
  229. SSLSocket sslClient = (SSLSocket) factory.createSocket(client, null, client.getPort(), false);
  230. sslClient.setUseClientMode(false);
  231. handlers.add(newInstance(service, this, protocol.getClass().newInstance(), sslClient));
  232. }
  233. /**
  234. * Logs a port scan attack
  235. * @param client The socket on which a port scan has been detected.
  236. * @param timestamp Timestamp when the portscan has been detected.
  237. */
  238. private void logPortscan(Socket client, long timestamp){
  239. SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(service);
  240. SharedPreferences connInfo = service.getSharedPreferences(service.getString(R.string.connection_info), Context.MODE_PRIVATE);
  241. Editor editor = pref.edit();
  242. int attack_id = pref.getInt("ATTACK_ID_COUNTER", 0);
  243. editor.putInt("ATTACK_ID_COUNTER", attack_id + 1);
  244. editor.commit();
  245. AttackRecord attackRecord = new AttackRecord();
  246. attackRecord.setAttack_id(attack_id);
  247. attackRecord.setProtocol("PORTSCAN");
  248. attackRecord.setExternalIP(connInfo.getString(service.getString(R.string.connection_info_external_ip), null));
  249. attackRecord.setLocalIP(client.getLocalAddress().getHostAddress());
  250. attackRecord.setLocalPort(0);
  251. attackRecord.setRemoteIP(client.getInetAddress().getHostAddress());
  252. attackRecord.setRemotePort(client.getPort());
  253. attackRecord.setBssid(connInfo.getString(service.getString(R.string.connection_info_bssid), null));
  254. NetworkRecord networkRecord = new NetworkRecord();
  255. networkRecord.setBssid(connInfo.getString(service.getString(R.string.connection_info_bssid), null));
  256. networkRecord.setSsid(connInfo.getString(service.getString(R.string.connection_info_ssid), null));
  257. if (MyLocationManager.getNewestLocation() != null) {
  258. networkRecord.setLatitude(MyLocationManager.getNewestLocation().getLatitude());
  259. networkRecord.setLongitude(MyLocationManager.getNewestLocation().getLongitude());
  260. networkRecord.setAccuracy(MyLocationManager.getNewestLocation().getAccuracy());
  261. networkRecord.setTimestampLocation(MyLocationManager.getNewestLocation().getTime());
  262. } else {
  263. networkRecord.setLatitude(0.0);
  264. networkRecord.setLongitude(0.0);
  265. networkRecord.setAccuracy(Float.MAX_VALUE);
  266. networkRecord.setTimestampLocation(0);
  267. }
  268. Logger.logPortscan(Hostage.getContext(), attackRecord, networkRecord, timestamp);
  269. }
  270. }