BasicPacketClassifier.java 16 KB

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