BasicPacketClassifierWitLabels.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. package de.tu_darmstadt.tk.SmartHomeNetworkSim.evaluation;
  2. import java.io.BufferedWriter;
  3. import java.io.File;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6. import java.util.ArrayList;
  7. import java.util.HashMap;
  8. import java.util.HashSet;
  9. import java.util.Iterator;
  10. import java.util.LinkedList;
  11. import java.util.Map.Entry;
  12. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Link;
  13. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Packet;
  14. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.PacketSniffer;
  15. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.protocols.packets.MQTTpublishPacket;
  16. import weka.core.Attribute;
  17. import weka.core.DenseInstance;
  18. import weka.core.Instance;
  19. import weka.core.Instances;
  20. /**
  21. * Unsupervised Classifier Basis, which contains methods for transforming {@link Packet}s into {@link Instance}s.
  22. *
  23. * @author Andreas T. Meyer-Berg
  24. */
  25. public abstract class BasicPacketClassifierWitLabels implements PacketSniffer {
  26. /**
  27. * True, if instances should be used for training
  28. */
  29. protected boolean training = true;
  30. /**
  31. * Attributes which should be taken into account
  32. */
  33. protected ArrayList<Attribute> atts = new ArrayList<Attribute>();
  34. /**
  35. * Collected Packets
  36. */
  37. protected Instances dataset;
  38. /**
  39. * CollectedPackets
  40. */
  41. protected HashMap<Link, LinkedList<Packet>> collectedPackets = new HashMap<Link, LinkedList<Packet>>();
  42. /**
  43. * HashMap for calculating transmission delay
  44. */
  45. protected HashMap<Link, LinkedList<Packet>> lastPackets = new HashMap<Link, LinkedList<Packet>>();
  46. /**
  47. * Map for the different Link names
  48. */
  49. protected HashSet<String> link_mappings = new HashSet<String>();
  50. /**
  51. * Map for the difference source device names
  52. */
  53. protected HashSet<String> source_mappings = new HashSet<String>();
  54. /**
  55. * Map for the different destination device names
  56. */
  57. protected HashSet<String> destination_mappings = new HashSet<String>();
  58. /**
  59. * Map for the protocol names
  60. */
  61. protected HashSet<String> protocol_mappings = new HashSet<String>();
  62. /**
  63. * Number of packets which are used to calculate the current transmission speed
  64. */
  65. protected int NUMBER_OF_PACKETS = 200;
  66. private String currentScenario = "";
  67. private int scenarioRun = 0;
  68. /**
  69. * Initializes the different maps
  70. */
  71. public BasicPacketClassifierWitLabels() {
  72. // Initialize Attribute list
  73. source_mappings.add("unknown");
  74. link_mappings.add("unknown");
  75. destination_mappings.add("unknown");
  76. protocol_mappings.add("unknown");
  77. }
  78. @Override
  79. public void processPackets(HashMap<Link, LinkedList<Packet>> packets) {
  80. if(training)
  81. try {
  82. training(packets);
  83. } catch (Exception e) {
  84. e.printStackTrace();
  85. }
  86. else
  87. classify(packets);
  88. }
  89. /**
  90. * Estimates the current Packets per second (depending on the last 100 packets of the link)
  91. * @param link Link which should be checked
  92. * @param packet Packet which should investigated
  93. * @return estimated number of packets per second
  94. */
  95. protected double getEstimatedPacketsPerSecond(Link link, Packet packet) {
  96. /**
  97. * Packets used to calculated the packets per second
  98. */
  99. LinkedList<Packet> list = lastPackets.get(link);
  100. if(list == null) {
  101. /**
  102. * Add list if not present
  103. */
  104. list = new LinkedList<Packet>();
  105. lastPackets.put(link, list);
  106. }
  107. if(list.isEmpty()) {
  108. list.addLast(packet);
  109. // Default 1 packet per second
  110. return 1.0;
  111. }
  112. if(list.size() == NUMBER_OF_PACKETS){
  113. list.removeFirst();
  114. }
  115. list.addLast(packet);
  116. /**
  117. * elapsed time in milliseconds since last packet
  118. */
  119. long elapsed_time = packet.getTimestamp()-list.getFirst().getTimestamp()/list.size();
  120. if(elapsed_time<=0)
  121. return Double.POSITIVE_INFINITY;
  122. /**
  123. * Return number of packets per second
  124. */
  125. return 1000.0/elapsed_time;
  126. }
  127. /**
  128. * Returns the instance representation of the given packet and link
  129. * @param link link the packet was sent on
  130. * @param packet packet which should be transformed
  131. * @param dataset distribution the packet is part of
  132. * @return instance representation
  133. */
  134. protected Instance packet2Instance(Link link, Packet packet, Instances dataset) {
  135. /**
  136. * Instance for the given Packet
  137. */
  138. DenseInstance instance = new DenseInstance(dataset.numAttributes());
  139. instance.setDataset(dataset);
  140. // link
  141. instance.setValue(0, stringToNominal(link_mappings, link.getName()));
  142. // source
  143. if(packet.getSource()==null) {
  144. instance.setValue(1, "unknown");
  145. instance.setValue(2, Double.NEGATIVE_INFINITY);
  146. }else if(packet.getSource().getOwner()==null){
  147. instance.setValue(1, "unknown");
  148. instance.setValue(2, packet.getSource().getPortNumber());
  149. }else {
  150. instance.setValue(1, stringToNominal(source_mappings, packet.getSource().getOwner().getName()));
  151. instance.setValue(2, packet.getSource().getPortNumber());
  152. }
  153. // Destination
  154. if(packet.getDestination()==null) {
  155. instance.setValue(3, "unknown");
  156. instance.setValue(4, Double.NEGATIVE_INFINITY);
  157. }else if(packet.getDestination().getOwner()==null){
  158. instance.setValue(3, "unknown");
  159. instance.setValue(4, packet.getDestination().getPortNumber());
  160. }else {
  161. instance.setValue(3, stringToNominal(destination_mappings, packet.getDestination().getOwner().getName()));
  162. instance.setValue(4, packet.getDestination().getPortNumber());
  163. }
  164. // Protocol name
  165. instance.setValue(5, stringToNominal(protocol_mappings, packet.getProtocolName()));
  166. // Packets per second
  167. instance.setValue(6, getEstimatedPacketsPerSecond(link, packet));
  168. // MQTT Value
  169. if(packet instanceof MQTTpublishPacket) {
  170. instance.setValue(7, ((MQTTpublishPacket)packet).getValue());
  171. instance.setValue(8, ((MQTTpublishPacket)packet).getSensorValue());
  172. } else {
  173. instance.setValue(7, -1);
  174. instance.setValue(8, -1);
  175. }
  176. return instance;
  177. }
  178. /**
  179. * Inserts the
  180. * @param map
  181. * @param nominal
  182. */
  183. protected void insertNominalIntoMap(HashSet<String> map, String nominal) {
  184. if(map == null || nominal == null)
  185. return;
  186. map.add(nominal);
  187. }
  188. /**
  189. * Transforms the String into an Number
  190. * @param map
  191. * @param s
  192. * @return
  193. */
  194. protected String stringToNominal(HashSet<String> map, String s) {
  195. return map.contains(s)?s:"unknown";
  196. }
  197. /**
  198. * Train the clusterer by collecting the packets
  199. *
  200. * @param packets packets to be learned
  201. */
  202. protected void training(HashMap<Link, LinkedList<Packet>> packets) {
  203. for(Entry<Link, LinkedList<Packet>> e:packets.entrySet()) {
  204. Link l = e.getKey();
  205. // TODO: ERROR ????????
  206. LinkedList<Packet> p = collectedPackets.get(l);
  207. if(p == null) {
  208. collectedPackets.put(l, new LinkedList<Packet>(e.getValue()));
  209. } else
  210. p.addAll(e.getValue());
  211. insertNominalIntoMap(link_mappings, l.getName());
  212. for(Packet pac: e.getValue()) {
  213. if(pac == null || pac.getSource()==null ||pac.getDestination() == null || pac.getSource().getOwner() == null || pac.getDestination().getOwner() == null)
  214. continue;
  215. insertNominalIntoMap(destination_mappings, pac.getSource().getOwner().getName());
  216. insertNominalIntoMap(destination_mappings, pac.getDestination().getOwner().getName());
  217. insertNominalIntoMap(source_mappings, pac.getSource().getOwner().getName());
  218. insertNominalIntoMap(source_mappings, pac.getDestination().getOwner().getName());
  219. insertNominalIntoMap(protocol_mappings, pac.getProtocolName());
  220. }
  221. //TODO: Add packet/Link/Names etc. to mappings
  222. }
  223. }
  224. /**
  225. * Finishes the collection and trains the clusterer on the collected packets
  226. *
  227. * @throws Exception
  228. */
  229. protected void finishDataCollection() throws Exception{
  230. /**
  231. printHashSet("Link-Name", link_mappings);
  232. printHashSet("Source-Device", source_mappings);
  233. printHashSet("Destination-Port", destination_mappings);
  234. printHashSet("Protocol-name", protocol_mappings);
  235. */
  236. atts.add(new Attribute("Link-Name", new LinkedList<String>(link_mappings)));//TODO:??
  237. atts.add(new Attribute("Source-Device", new LinkedList<String>(source_mappings)));
  238. atts.add(new Attribute("Source-Port-number", false));
  239. atts.add(new Attribute("Destination-Device", new LinkedList<String>(destination_mappings)));
  240. atts.add(new Attribute("Destination-Port-number", false));
  241. Attribute pn = new Attribute("Protocol-name", new LinkedList<String>(protocol_mappings));
  242. //pn.setWeight(10);
  243. atts.add(pn);
  244. Attribute pps = new Attribute("Packets-per-second", false);
  245. //pps.setWeight(20);
  246. atts.add(pps);
  247. atts.add(new Attribute("PacketValue", false));
  248. //atts.add(new Attribute("Anomaly", false));
  249. // TODO: Sensor Attribute, given as side channel information
  250. atts.add(new Attribute("SensorValue", false));
  251. /*
  252. atts = new ArrayList<Attribute>();
  253. atts.add(new Attribute("LN", new LinkedList<String>(link_mappings)));//TODO:??
  254. atts.add(new Attribute("SD", new LinkedList<String>(source_mappings)));
  255. atts.add(new Attribute("SPN", false));
  256. atts.add(new Attribute("DD", new LinkedList<String>(destination_mappings)));
  257. atts.add(new Attribute("DPN", false));
  258. atts.add(new Attribute("PN", new LinkedList<String>(protocol_mappings)));
  259. atts.add(new Attribute("PPS", false));
  260. atts.add(new Attribute("A", false));*/
  261. dataset = new Instances("Packets", atts, 100000);
  262. //dataset.setClassIndex(7);
  263. /**
  264. * Add Instances to dataset
  265. */
  266. for (Iterator<Entry<Link, LinkedList<Packet>>> it = collectedPackets.entrySet().iterator(); it.hasNext();) {
  267. Entry<Link, LinkedList<Packet>> entry = it.next();
  268. /**
  269. * Link the packet was captured on
  270. */
  271. Link l = entry.getKey();
  272. for (Iterator<Packet> itPacket = entry.getValue().iterator(); itPacket.hasNext();) {
  273. /**
  274. * Packets to be added to the dataset
  275. */
  276. Packet packet = (Packet) itPacket.next();
  277. dataset.add(packet2Instance(l, packet, dataset));
  278. }
  279. }
  280. trainModel(dataset);
  281. }
  282. private void printHashSet(String name, HashSet<String> toPrint) {
  283. System.out.println(name+":");
  284. for (Iterator<String> iterator = toPrint.iterator(); iterator.hasNext();) {
  285. String string = (String) iterator.next();
  286. System.out.print(string);
  287. if(iterator.hasNext())
  288. System.out.print(", ");
  289. }
  290. System.out.println();
  291. }
  292. /**
  293. * Try to classify the given packets and detect anomalies
  294. * @param packets packets to be classified
  295. */
  296. protected void classify(HashMap<Link, LinkedList<Packet>> packets) {
  297. File anomalyResults = new File("results/"+getCurrentScenario() + scenarioRun + ".csv");
  298. anomalyResults.getParentFile().mkdir();
  299. BufferedWriter writer = null;
  300. try {
  301. writer = new BufferedWriter(new FileWriter(anomalyResults));
  302. writer.write("PacketRepresentation,anomalyFPorTP,sensorInfo\n");
  303. } catch (IOException e1) {
  304. // TODO Auto-generated catch block
  305. e1.printStackTrace();
  306. }
  307. int tp = 0;
  308. int fp = 0;
  309. int tn = 0;
  310. int fn = 0;
  311. long start = Long.MAX_VALUE;
  312. long end = Long.MIN_VALUE;
  313. for (Iterator<Entry<Link, LinkedList<Packet>>> it = packets.entrySet().iterator(); it.hasNext();) {
  314. /**
  315. * Link & its packets
  316. */
  317. Entry<Link, LinkedList<Packet>> entry = it.next();
  318. /**
  319. * Link the packets were captured on
  320. */
  321. Link l = entry.getKey();
  322. for (Iterator<Packet> itPacket = entry.getValue().iterator(); itPacket.hasNext();) {
  323. /**
  324. * Packet which should be checked
  325. */
  326. Packet packet = (Packet) itPacket.next();
  327. start = Math.min(start, packet.getTimestamp());
  328. end = Math.max(end, packet.getTimestamp());
  329. /**
  330. * Instance Representation
  331. */
  332. Instance packet_instance = packet2Instance(l, packet, dataset);
  333. if(packet_instance == null)continue;
  334. String sensorLabel = "";
  335. if(packet instanceof MQTTpublishPacket) {
  336. MQTTpublishPacket mqttPac = (MQTTpublishPacket)packet;
  337. sensorLabel = ""+mqttPac.getSensorValue();
  338. if(mqttPac.isBoolean()) {
  339. sensorLabel = "" + Boolean.parseBoolean(sensorLabel);
  340. }
  341. sensorLabel = ","+sensorLabel;
  342. }
  343. try {
  344. double dist = classifyInstance(packet_instance, packet);
  345. if(dist<=1.0) {
  346. if(packet.getLabel()==0)
  347. tn++;
  348. else {
  349. fn++;
  350. writer.write(packet.getTextualRepresentation()+",FN"+sensorLabel+"\n");
  351. //System.out.println(packet.getTextualRepresentation()+",AnomalyNotFound"+sensorLabel);
  352. }
  353. }else {
  354. if(packet.getLabel()==0) {
  355. fp++;
  356. writer.write(packet.getTextualRepresentation()+",FP"+sensorLabel+"\n");
  357. } else {
  358. tp++;
  359. writer.write(packet.getTextualRepresentation()+",TP"+sensorLabel+"\n");
  360. }
  361. }
  362. } catch (Exception e) {
  363. if(packet.getLabel()==0) {
  364. fp++;
  365. try {
  366. writer.write(packet.getTextualRepresentation()+",FP"+sensorLabel+"\n");
  367. } catch (IOException e1) {
  368. // TODO Auto-generated catch block
  369. e1.printStackTrace();
  370. }
  371. } else {
  372. tp++;
  373. try {
  374. writer.write(packet.getTextualRepresentation()+",TP"+sensorLabel+"\n");
  375. } catch (IOException e1) {
  376. // TODO Auto-generated catch block
  377. e1.printStackTrace();
  378. }
  379. }
  380. }
  381. }
  382. }
  383. int n = tp+tn+fp+fn;
  384. if(n!=0) {
  385. System.out.println(getAlgoName()+" Performance: ["+start+"ms, "+end+"ms] Scenario: " + getCurrentScenario() + scenarioRun);
  386. scenarioRun++;
  387. System.out.println("n: "+n);
  388. System.out.println("TP: "+tp);
  389. System.out.println("FP: "+fp);
  390. System.out.println("TN: "+tn);
  391. System.out.println("FN: "+fn);
  392. System.out.println("TPR: "+(tp/(tp+fn+0.0)));
  393. System.out.println("FPR: "+(fp/(fp+tn+0.0)));
  394. System.out.println("");
  395. }
  396. try {
  397. writer.close();
  398. } catch (IOException e) {
  399. // TODO Auto-generated catch block
  400. e.printStackTrace();
  401. }
  402. }
  403. /**
  404. * Train the model using the given instances
  405. * @param instances training set, which should be learned
  406. */
  407. public abstract void trainModel(Instances instances);
  408. /**
  409. * classifies the given instance
  410. * @param instance instance which should be classified
  411. * @param origin original packet, which was transformed into the instance
  412. * @return distance to next centroid
  413. * @throws Exception if anomaly was detected
  414. */
  415. public abstract double classifyInstance(Instance instance, Packet origin) throws Exception;
  416. /**
  417. * Returns the timestep, after which the classifier should start classifying instead of training.
  418. * @return timestep of the testing begin.
  419. */
  420. public abstract long getClassificationStart();
  421. @Override
  422. public void setMode(boolean testing) {
  423. training = !testing;
  424. if(testing) {
  425. try {
  426. finishDataCollection();
  427. } catch (Exception e) {
  428. System.out.println("Clustering failed");
  429. e.printStackTrace();
  430. }
  431. }
  432. }
  433. @Override
  434. public boolean getMode() {
  435. return !training;
  436. }
  437. /**
  438. * Short String representation of the classifier
  439. * @return
  440. */
  441. public abstract String getAlgoName();
  442. /**
  443. * @return the currentScenario
  444. */
  445. public String getCurrentScenario() {
  446. return currentScenario;
  447. }
  448. /**
  449. * @param currentScenario the currentScenario to set
  450. */
  451. public void setCurrentScenario(String currentScenario) {
  452. this.currentScenario = currentScenario;
  453. this.scenarioRun = 0;
  454. }
  455. }