Handler.java 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. package de.tudarmstadt.informatik.hostage;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.OutputStream;
  5. import java.net.Socket;
  6. import java.util.List;
  7. import android.content.Context;
  8. import android.content.Intent;
  9. import android.content.SharedPreferences;
  10. import android.content.SharedPreferences.Editor;
  11. import android.preference.PreferenceManager;
  12. import android.util.Log;
  13. import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
  14. import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
  15. import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
  16. import de.tudarmstadt.informatik.hostage.logging.Logger;
  17. import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
  18. import de.tudarmstadt.informatik.hostage.logging.MessageRecord.TYPE;
  19. import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
  20. import de.tudarmstadt.informatik.hostage.logging.SyncDevice;
  21. import de.tudarmstadt.informatik.hostage.nio.Reader;
  22. import de.tudarmstadt.informatik.hostage.nio.Writer;
  23. import de.tudarmstadt.informatik.hostage.protocol.GHOST;
  24. import de.tudarmstadt.informatik.hostage.protocol.Protocol;
  25. import de.tudarmstadt.informatik.hostage.protocol.Protocol.TALK_FIRST;
  26. import de.tudarmstadt.informatik.hostage.sync.tracing.TracingSyncService;
  27. import de.tudarmstadt.informatik.hostage.wrapper.Packet;
  28. /**
  29. * Abstract class for a connection handler using a given protocol.
  30. *
  31. * @author Mihai Plasoianu
  32. * @author Wulf Pfeiffer
  33. * @author Lars Pandikow
  34. */
  35. public class Handler implements Runnable {
  36. /** Time until the socket throws a time out. The time is in milliseconds. */
  37. private int TIMEOUT;
  38. private Hostage service;
  39. protected Protocol protocol;
  40. private Socket client;
  41. protected Thread thread;
  42. SharedPreferences pref;
  43. private int attack_id;
  44. private int message_id = 0;
  45. private String externalIP;
  46. private String BSSID;
  47. private String SSID;
  48. private int subnetMask;
  49. private int internalIPAddress;
  50. private boolean logged;
  51. private Listener listener;
  52. /**
  53. * Constructor of the class. Initializes class variables for communication
  54. * and logging. Then starts itself in a new Thread.
  55. *
  56. * @param service
  57. * The background service.
  58. * @param listener
  59. * The Listener that called the service.
  60. * @param protocol
  61. * The protocol on which the handler is running.
  62. * @param client
  63. * A Socket for the communication with a remote client.
  64. */
  65. public Handler(Hostage service, Listener listener, Protocol protocol, Socket client) {
  66. this.service = service;
  67. this.listener = listener;
  68. this.protocol = protocol;
  69. if (protocol.toString().equals("GHOST")) {
  70. ((GHOST) protocol).setAttackerIP(client.getInetAddress());
  71. ((GHOST) protocol).setCurrentPort(listener.getPort());
  72. }
  73. this.client = client;
  74. this.thread = new Thread(this);
  75. pref = PreferenceManager.getDefaultSharedPreferences(service);
  76. TIMEOUT = pref.getInt("timeout", 30) * 1000;
  77. getAndIncrementAttackID(pref);
  78. SharedPreferences connInfo = service.getSharedPreferences(service.getString(R.string.connection_info), Context.MODE_PRIVATE);
  79. BSSID = connInfo.getString(service.getString(R.string.connection_info_bssid), null);
  80. SSID = connInfo.getString(service.getString(R.string.connection_info_ssid), null);
  81. externalIP = connInfo.getString(service.getString(R.string.connection_info_external_ip), null);
  82. // we need this info to find out whether the attack was internal
  83. subnetMask = connInfo.getInt(service.getString(R.string.connection_info_subnet_mask), 0);
  84. internalIPAddress = connInfo.getInt(service.getString(R.string.connection_info_internal_ip), 0);
  85. setSoTimeout(client);
  86. logged = false;
  87. thread.start();
  88. }
  89. /**
  90. * Determines if the interrupt flag of the thread is set.
  91. *
  92. * @return True when the flag is set, else false.
  93. */
  94. public boolean isTerminated() {
  95. return thread.isInterrupted();
  96. }
  97. /**
  98. * Sets the interrupt flag of the thread and tries to close the socket.
  99. */
  100. public void kill() {
  101. service.notifyUI(this.getClass().getName(),
  102. new String[] { service.getString(R.string.broadcast_started), protocol.toString(), Integer.toString(listener.getPort()) });
  103. thread.interrupt();
  104. try {
  105. client.close();
  106. } catch (Exception e) {
  107. }
  108. boolean upload = pref.getBoolean("pref_auto_synchronize", false);
  109. if(upload){
  110. Intent intent = new Intent(service, TracingSyncService.class);
  111. intent.setAction(TracingSyncService.ACTION_START_SYNC);
  112. service.startService(intent);
  113. }
  114. //TODO kann ConcurrentModificationException auslösen, da über collection iteriert wird während elemente entfernt werden
  115. listener.refreshHandlers();
  116. }
  117. /**
  118. * Creates InputStream and OutputStream for the socket. Starts communication
  119. * with client. When the client closes the connection or a time out occurs
  120. * the handler is finished.
  121. */
  122. @Override
  123. public void run() {
  124. service.notifyUI(this.getClass().getName(),
  125. new String[] { service.getString(R.string.broadcast_started), protocol.toString(), Integer.toString(listener.getPort()) });
  126. InputStream in;
  127. OutputStream out;
  128. try {
  129. in = client.getInputStream();
  130. out = client.getOutputStream();
  131. talkToClient(in, out);
  132. } catch (Exception e) {
  133. e.printStackTrace();
  134. }
  135. kill();
  136. }
  137. /**
  138. * Gets attack ID for the attack. Also increases the attack ID counter by
  139. * one. Method is synchronized for thread safety.
  140. *
  141. * @param pref
  142. * The default SharedPreference of the application
  143. * @return Unique integer attack ID
  144. */
  145. private synchronized void getAndIncrementAttackID(SharedPreferences pref) {
  146. Editor editor = pref.edit();
  147. attack_id = pref.getInt("ATTACK_ID_COUNTER", 0);
  148. editor.putInt("ATTACK_ID_COUNTER", attack_id + 1);
  149. editor.commit();
  150. }
  151. /**
  152. * Set the timeout of the socket to the hard coded time out variable.
  153. *
  154. * @param client
  155. * The socket
  156. * @see #TIMEOUT
  157. */
  158. private void setSoTimeout(Socket client) {
  159. try {
  160. client.setSoTimeout(TIMEOUT);
  161. } catch (Exception e) {
  162. e.printStackTrace();
  163. }
  164. }
  165. /**
  166. * Creates a MessageRecord for a message exchanged with a client.
  167. *
  168. * @param type
  169. * The type of the message.
  170. * @param packet
  171. * The content of the message.
  172. * @return The Record representing the communication message.
  173. */
  174. protected MessageRecord createMessageRecord(TYPE type, String packet) {
  175. MessageRecord record = new MessageRecord();
  176. record.setId(message_id++);
  177. record.setAttack_id(attack_id);
  178. record.setType(type);
  179. record.setTimestamp(System.currentTimeMillis());
  180. record.setPacket(packet);
  181. return record;
  182. }
  183. /**
  184. * Creates a AttackRecord for a specific attack from a client.
  185. *
  186. * @return The AttackRecord representing the attack.
  187. */
  188. protected AttackRecord createAttackRecord() {
  189. AttackRecord record = new AttackRecord();
  190. record.setAttack_id(attack_id);
  191. record.setSync_id(attack_id);
  192. record.setDevice(SyncDevice.currentDevice().getDeviceID());
  193. record.setProtocol(protocol.toString());
  194. record.setExternalIP(externalIP);
  195. record.setLocalIP(client.getLocalAddress().getHostAddress());
  196. record.setLocalPort(client.getLocalPort());
  197. int remoteIPAddress = HelperUtils.packInetAddress(client.getInetAddress().getAddress());
  198. record.setWasInternalAttack((remoteIPAddress & subnetMask) == (internalIPAddress & subnetMask));
  199. record.setRemoteIP(client.getInetAddress().getHostAddress());
  200. record.setRemotePort(client.getPort());
  201. record.setBssid(BSSID);
  202. return record;
  203. }
  204. /**
  205. * Creates a NetworkRecord containing information about the current network.
  206. *
  207. * @return The NetworkRecord representing the current network.
  208. */
  209. protected NetworkRecord createNetworkRecord() {
  210. NetworkRecord record = new NetworkRecord();
  211. record.setBssid(BSSID);
  212. record.setSsid(SSID);
  213. if (MyLocationManager.getNewestLocation() != null) {
  214. record.setLatitude(MyLocationManager.getNewestLocation().getLatitude());
  215. record.setLongitude(MyLocationManager.getNewestLocation().getLongitude());
  216. record.setAccuracy(MyLocationManager.getNewestLocation().getAccuracy());
  217. record.setTimestampLocation(MyLocationManager.getNewestLocation().getTime());
  218. } else {
  219. record.setLatitude(0.0);
  220. record.setLongitude(0.0);
  221. record.setAccuracy(Float.MAX_VALUE);
  222. record.setTimestampLocation(0);
  223. }
  224. return record;
  225. }
  226. private void log(TYPE type, String packet){
  227. if(!logged){
  228. Logger.log(Hostage.getContext(), createNetworkRecord());
  229. Logger.log(Hostage.getContext(), createAttackRecord());
  230. logged = true;
  231. }
  232. Logger.log(Hostage.getContext(), createMessageRecord(type, packet));
  233. }
  234. /**
  235. * Communicates with a client using the corresponding protocol
  236. * implementation.
  237. *
  238. * @param in
  239. * InputStream of the socket.
  240. * @param out
  241. * OutputStream of the socket.
  242. * @throws IOException
  243. */
  244. protected void talkToClient(InputStream in, OutputStream out) throws IOException {
  245. Reader reader = new Reader(in, protocol.toString());
  246. Writer writer = new Writer(out);
  247. Packet inputLine;
  248. List<Packet> outputLine;
  249. if (protocol.whoTalksFirst() == TALK_FIRST.SERVER) {
  250. outputLine = protocol.processMessage(null);
  251. writer.write(outputLine);
  252. for (Packet o : outputLine) {
  253. log(TYPE.SEND, o.toString());
  254. }
  255. }
  256. while (!thread.isInterrupted() && (inputLine = reader.read()) != null) {
  257. outputLine = protocol.processMessage(inputLine);
  258. log(TYPE.RECEIVE, inputLine.toString());
  259. if (outputLine != null) {
  260. writer.write(outputLine);
  261. for (Packet o : outputLine) {
  262. log(TYPE.SEND, o.toString());
  263. }
  264. }
  265. if (protocol.isClosed()) {
  266. break;
  267. }
  268. }
  269. }
  270. }