BasicPacketClassifier.java 16 KB

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