Handler.java 11 KB

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