Handler.java 11 KB

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