Handler.java 9.3 KB

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