BasicPacketClassifier.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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. * 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 BasicPacketClassifier() {
  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. MQTTpublishPacket mqttPack = (MQTTpublishPacket)packet;
  171. if(mqttPack.isBoolean()) {
  172. if(mqttPack.getValue() == 0) {
  173. instance.setValue(6,0);
  174. } else {
  175. instance.setValue(6, 1);
  176. }
  177. }else {
  178. instance.setValue(6, ((MQTTpublishPacket)packet).getValue());
  179. }
  180. } else {
  181. instance.setValue(6, -100);
  182. }
  183. return instance;
  184. }
  185. /**
  186. * Inserts the
  187. * @param map
  188. * @param nominal
  189. */
  190. protected void insertNominalIntoMap(HashSet<String> map, String nominal) {
  191. if(map == null || nominal == null)
  192. return;
  193. map.add(nominal);
  194. }
  195. /**
  196. * Transforms the String into an Number
  197. * @param map
  198. * @param s
  199. * @return
  200. */
  201. protected String stringToNominal(HashSet<String> map, String s) {
  202. return map.contains(s)?s:"unknown";
  203. }
  204. /**
  205. * Train the clusterer by collecting the packets
  206. *
  207. * @param packets packets to be learned
  208. */
  209. protected void training(HashMap<Link, LinkedList<Packet>> packets) {
  210. for(Entry<Link, LinkedList<Packet>> e:packets.entrySet()) {
  211. Link l = e.getKey();
  212. // TODO: ERROR ????????
  213. LinkedList<Packet> p = collectedPackets.get(l);
  214. if(p == null) {
  215. collectedPackets.put(l, new LinkedList<Packet>(e.getValue()));
  216. } else
  217. p.addAll(e.getValue());
  218. insertNominalIntoMap(link_mappings, l.getName());
  219. for(Packet pac: e.getValue()) {
  220. if(pac == null || pac.getSource()==null ||pac.getDestination() == null || pac.getSource().getOwner() == null || pac.getDestination().getOwner() == null)
  221. continue;
  222. insertNominalIntoMap(destination_mappings, pac.getSource().getOwner().getName());
  223. insertNominalIntoMap(destination_mappings, pac.getDestination().getOwner().getName());
  224. insertNominalIntoMap(source_mappings, pac.getSource().getOwner().getName());
  225. insertNominalIntoMap(source_mappings, pac.getDestination().getOwner().getName());
  226. insertNominalIntoMap(protocol_mappings, pac.getProtocolName());
  227. }
  228. //TODO: Add packet/Link/Names etc. to mappings
  229. }
  230. }
  231. /**
  232. * Finishes the collection and trains the clusterer on the collected packets
  233. *
  234. * @throws Exception
  235. */
  236. protected void finishDataCollection() throws Exception{
  237. /**
  238. printHashSet("Link-Name", link_mappings);
  239. printHashSet("Source-Device", source_mappings);
  240. printHashSet("Destination-Port", destination_mappings);
  241. printHashSet("Protocol-name", protocol_mappings);
  242. */
  243. atts.add(new Attribute("Link-Name", new LinkedList<String>(link_mappings)));//TODO:??
  244. atts.add(new Attribute("Source-Device", new LinkedList<String>(source_mappings)));
  245. atts.add(new Attribute("Source-Port-number", false));
  246. atts.add(new Attribute("Destination-Device", new LinkedList<String>(destination_mappings)));
  247. atts.add(new Attribute("Destination-Port-number", false));
  248. Attribute pn = new Attribute("Protocol-name", new LinkedList<String>(protocol_mappings));
  249. //pn.setWeight(10);
  250. atts.add(pn);
  251. //Attribute pps = new Attribute("Packets-per-second", false);
  252. //pps.setWeight(20);
  253. //atts.add(pps);
  254. atts.add(new Attribute("PacketValue", false));
  255. //atts.add(new Attribute("Anomaly", false));
  256. // TODO: Sensor Attribute, given as side channel information
  257. //atts.add(new Attribute("SensorValue", false));
  258. /*
  259. atts = new ArrayList<Attribute>();
  260. atts.add(new Attribute("LN", new LinkedList<String>(link_mappings)));//TODO:??
  261. atts.add(new Attribute("SD", new LinkedList<String>(source_mappings)));
  262. atts.add(new Attribute("SPN", false));
  263. atts.add(new Attribute("DD", new LinkedList<String>(destination_mappings)));
  264. atts.add(new Attribute("DPN", false));
  265. atts.add(new Attribute("PN", new LinkedList<String>(protocol_mappings)));
  266. atts.add(new Attribute("PPS", false));
  267. atts.add(new Attribute("A", false));*/
  268. dataset = new Instances("Packets", atts, 100000);
  269. //dataset.setClassIndex(7);
  270. /**
  271. * Add Instances to dataset
  272. */
  273. for (Iterator<Entry<Link, LinkedList<Packet>>> it = collectedPackets.entrySet().iterator(); it.hasNext();) {
  274. Entry<Link, LinkedList<Packet>> entry = it.next();
  275. /**
  276. * Link the packet was captured on
  277. */
  278. Link l = entry.getKey();
  279. for (Iterator<Packet> itPacket = entry.getValue().iterator(); itPacket.hasNext();) {
  280. /**
  281. * Packets to be added to the dataset
  282. */
  283. Packet packet = (Packet) itPacket.next();
  284. dataset.add(packet2Instance(l, packet, dataset));
  285. }
  286. }
  287. trainModel(dataset);
  288. }
  289. private void printHashSet(String name, HashSet<String> toPrint) {
  290. System.out.println(name+":");
  291. for (Iterator<String> iterator = toPrint.iterator(); iterator.hasNext();) {
  292. String string = (String) iterator.next();
  293. System.out.print(string);
  294. if(iterator.hasNext())
  295. System.out.print(", ");
  296. }
  297. System.out.println();
  298. }
  299. /**
  300. * Try to classify the given packets and detect anomalies
  301. * @param packets packets to be classified
  302. */
  303. protected void classify(HashMap<Link, LinkedList<Packet>> packets) {
  304. File anomalyResults = new File("results/"+getCurrentScenario() + scenarioRun + "nolabels.csv");
  305. anomalyResults.getParentFile().mkdir();
  306. BufferedWriter writer = null;
  307. try {
  308. writer = new BufferedWriter(new FileWriter(anomalyResults));
  309. writer.write("PacketRepresentation,anomalyFPorTP,sensorInfo\n");
  310. } catch (IOException e1) {
  311. // TODO Auto-generated catch block
  312. e1.printStackTrace();
  313. }
  314. int tp = 0;
  315. int fp = 0;
  316. int tn = 0;
  317. int fn = 0;
  318. long start = Long.MAX_VALUE;
  319. long end = Long.MIN_VALUE;
  320. for (Iterator<Entry<Link, LinkedList<Packet>>> it = packets.entrySet().iterator(); it.hasNext();) {
  321. /**
  322. * Link & its packets
  323. */
  324. Entry<Link, LinkedList<Packet>> entry = it.next();
  325. /**
  326. * Link the packets were captured on
  327. */
  328. Link l = entry.getKey();
  329. for (Iterator<Packet> itPacket = entry.getValue().iterator(); itPacket.hasNext();) {
  330. /**
  331. * Packet which should be checked
  332. */
  333. Packet packet = (Packet) itPacket.next();
  334. start = Math.min(start, packet.getTimestamp());
  335. end = Math.max(end, packet.getTimestamp());
  336. /**
  337. * Instance Representation
  338. */
  339. Instance packet_instance = packet2Instance(l, packet, dataset);
  340. if(packet_instance == null)continue;
  341. String sensorLabel = "";
  342. if(packet instanceof MQTTpublishPacket) {
  343. MQTTpublishPacket mqttPac = (MQTTpublishPacket)packet;
  344. sensorLabel = ""+mqttPac.getSensorValue();
  345. if(mqttPac.isBoolean()) {
  346. sensorLabel = "" + Boolean.parseBoolean(sensorLabel);
  347. }
  348. sensorLabel = ","+sensorLabel;
  349. }
  350. try {
  351. double dist = classifyInstance(packet_instance, packet);
  352. if(dist<=Settings.DECISION_THRESHOLD) {
  353. if(packet.getLabel()==0)
  354. tn++;
  355. else {
  356. fn++;
  357. writer.write(packet.getTextualRepresentation()+",FN"+sensorLabel+"\n");
  358. //System.out.println(packet.getTextualRepresentation()+",AnomalyNotFound"+sensorLabel);
  359. }
  360. }else {
  361. if(packet.getLabel()==0) {
  362. fp++;
  363. writer.write(packet.getTextualRepresentation()+",FP"+sensorLabel+"\n");
  364. } else {
  365. tp++;
  366. writer.write(packet.getTextualRepresentation()+",TP"+sensorLabel+"\n");
  367. }
  368. }
  369. } catch (Exception e) {
  370. if(packet.getLabel()==0) {
  371. fp++;
  372. try {
  373. writer.write(packet.getTextualRepresentation()+",FP"+sensorLabel+"\n");
  374. } catch (IOException e1) {
  375. // TODO Auto-generated catch block
  376. e1.printStackTrace();
  377. }
  378. } else {
  379. tp++;
  380. try {
  381. writer.write(packet.getTextualRepresentation()+",TP"+sensorLabel+"\n");
  382. } catch (IOException e1) {
  383. // TODO Auto-generated catch block
  384. e1.printStackTrace();
  385. }
  386. }
  387. }
  388. }
  389. }
  390. int n = tp+tn+fp+fn;
  391. if(n!=0) {
  392. System.out.println(getAlgoName()+" Performance: ["+start+"ms, "+end+"ms] Scenario: " + getCurrentScenario() + scenarioRun);
  393. scenarioRun++;
  394. System.out.println("n: "+n);
  395. System.out.println("TP: "+tp);
  396. System.out.println("FP: "+fp);
  397. System.out.println("TN: "+tn);
  398. System.out.println("FN: "+fn);
  399. System.out.println("TPR: "+(tp/(tp+fn+0.0)));
  400. System.out.println("FPR: "+(fp/(fp+tn+0.0)));
  401. System.out.println("");
  402. }
  403. try {
  404. writer.close();
  405. } catch (IOException e) {
  406. // TODO Auto-generated catch block
  407. e.printStackTrace();
  408. }
  409. }
  410. /**
  411. * Train the model using the given instances
  412. * @param instances training set, which should be learned
  413. */
  414. public abstract void trainModel(Instances instances);
  415. /**
  416. * classifies the given instance
  417. * @param instance instance which should be classified
  418. * @param origin original packet, which was transformed into the instance
  419. * @return distance to next centroid
  420. * @throws Exception if anomaly was detected
  421. */
  422. public abstract double classifyInstance(Instance instance, Packet origin) throws Exception;
  423. /**
  424. * Returns the timestep, after which the classifier should start classifying instead of training.
  425. * @return timestep of the testing begin.
  426. */
  427. public abstract long getClassificationStart();
  428. @Override
  429. public void setMode(boolean testing) {
  430. training = !testing;
  431. if(testing) {
  432. try {
  433. finishDataCollection();
  434. } catch (Exception e) {
  435. System.out.println("Clustering failed");
  436. e.printStackTrace();
  437. }
  438. }
  439. }
  440. @Override
  441. public boolean getMode() {
  442. return !training;
  443. }
  444. /**
  445. * Short String representation of the classifier
  446. * @return
  447. */
  448. public abstract String getAlgoName();
  449. /**
  450. * @return the currentScenario
  451. */
  452. public String getCurrentScenario() {
  453. return currentScenario;
  454. }
  455. /**
  456. * @param currentScenario the currentScenario to set
  457. */
  458. public void setCurrentScenario(String currentScenario) {
  459. this.currentScenario = currentScenario;
  460. this.scenarioRun = 0;
  461. }
  462. }