Handler.java 10 KB

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