BasicPacketClassifier.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. package classifier;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.HashSet;
  5. import java.util.Iterator;
  6. import java.util.LinkedList;
  7. import java.util.Map.Entry;
  8. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Link;
  9. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Packet;
  10. import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.PacketSniffer;
  11. import weka.core.Attribute;
  12. import weka.core.DenseInstance;
  13. import weka.core.Instance;
  14. import weka.core.Instances;
  15. /**
  16. * Unsupervised Classifier Basis, which contains methods for transforming {@link Packet}s into {@link Instance}s.
  17. *
  18. * @author Andreas T. Meyer-Berg
  19. */
  20. public abstract class BasicPacketClassifier implements PacketSniffer {
  21. /**
  22. * True, if instances should be used for training
  23. */
  24. protected boolean training = true;
  25. /**
  26. * Attributes which should be taken into account
  27. */
  28. protected ArrayList<Attribute> atts = new ArrayList<Attribute>();
  29. /**
  30. * Collected Packets
  31. */
  32. protected Instances dataset;
  33. /**
  34. * CollectedPackets
  35. */
  36. protected HashMap<Link, LinkedList<Packet>> collectedPackets = new HashMap<Link, LinkedList<Packet>>();
  37. /**
  38. * HashMap for calculating transmission delay
  39. */
  40. protected HashMap<Link, LinkedList<Packet>> lastPackets = new HashMap<Link, LinkedList<Packet>>();
  41. /**
  42. * Map for the different Link names
  43. */
  44. protected HashSet<String> link_mappings = new HashSet<String>();
  45. /**
  46. * Map for the difference source device names
  47. */
  48. protected HashSet<String> source_mappings = new HashSet<String>();
  49. /**
  50. * Map for the different destination device names
  51. */
  52. protected HashSet<String> destination_mappings = new HashSet<String>();
  53. /**
  54. * Map for the protocol names
  55. */
  56. protected HashSet<String> protocol_mappings = new HashSet<String>();
  57. /**
  58. * Number of packets which are used to calculate the current transmission speed
  59. */
  60. protected int NUMBER_OF_PACKETS = 200;
  61. /**
  62. * Initializes the different maps
  63. */
  64. public BasicPacketClassifier() {
  65. // Initialize Attribute list
  66. source_mappings.add("unknown");
  67. link_mappings.add("unknown");
  68. destination_mappings.add("unknown");
  69. protocol_mappings.add("unknown");
  70. }
  71. @Override
  72. public void processPackets(HashMap<Link, LinkedList<Packet>> packets) {
  73. if(training)
  74. try {
  75. training(packets);
  76. } catch (Exception e) {
  77. e.printStackTrace();
  78. }
  79. else
  80. classify(packets);
  81. }
  82. /**
  83. * Estimates the current Packets per second (depending on the last 100 packets of the link)
  84. * @param link Link which should be checked
  85. * @param packet Packet which should investigated
  86. * @return estimated number of packets per second
  87. */
  88. protected double getEstimatedPacketsPerSecond(Link link, Packet packet) {
  89. /**
  90. * Packets used to calculated the packets per second
  91. */
  92. LinkedList<Packet> list = lastPackets.get(link);
  93. if(list == null) {
  94. /**
  95. * Add list if not present
  96. */
  97. list = new LinkedList<Packet>();
  98. lastPackets.put(link, list);
  99. }
  100. if(list.isEmpty()) {
  101. list.addLast(packet);
  102. // Default 1 packet per second
  103. return 1.0;
  104. }
  105. if(list.size() == NUMBER_OF_PACKETS){
  106. list.removeFirst();
  107. }
  108. list.addLast(packet);
  109. /**
  110. * elapsed time in milliseconds since last packet
  111. */
  112. long elapsed_time = packet.getTimestamp()-list.getFirst().getTimestamp()/list.size();
  113. if(elapsed_time<=0)
  114. return Double.POSITIVE_INFINITY;
  115. /**
  116. * Return number of packets per second
  117. */
  118. return 1000.0/elapsed_time;
  119. }
  120. /**
  121. * Returns the instance representation of the given packet and link
  122. * @param link link the packet was sent on
  123. * @param packet packet which should be transformed
  124. * @param dataset distribution the packet is part of
  125. * @return instance representation
  126. */
  127. protected Instance packet2Instance(Link link, Packet packet, Instances dataset) {
  128. /**
  129. * Instance for the given Packet
  130. */
  131. DenseInstance instance = new DenseInstance(dataset.numAttributes());
  132. instance.setDataset(dataset);
  133. // link
  134. instance.setValue(0, stringToNominal(link_mappings, link.getName()));
  135. // source
  136. if(packet.getSource()==null) {
  137. instance.setValue(1, "unknown");
  138. instance.setValue(2, Double.NEGATIVE_INFINITY);
  139. }else if(packet.getSource().getOwner()==null){
  140. instance.setValue(1, "unknown");
  141. instance.setValue(2, packet.getSource().getPortNumber());
  142. }else {
  143. instance.setValue(1, stringToNominal(source_mappings, packet.getSource().getOwner().getName()));
  144. instance.setValue(2, packet.getSource().getPortNumber());
  145. }
  146. // Destination
  147. if(packet.getDestination()==null) {
  148. instance.setValue(3, "unknown");
  149. instance.setValue(4, Double.NEGATIVE_INFINITY);
  150. }else if(packet.getDestination().getOwner()==null){
  151. instance.setValue(3, "unknown");
  152. instance.setValue(4, packet.getDestination().getPortNumber());
  153. }else {
  154. instance.setValue(3, stringToNominal(destination_mappings, packet.getDestination().getOwner().getName()));
  155. instance.setValue(4, packet.getDestination().getPortNumber());
  156. }
  157. // Protocol name
  158. instance.setValue(5, stringToNominal(protocol_mappings, packet.getProtocolName()));
  159. // Packets per second
  160. instance.setValue(6, getEstimatedPacketsPerSecond(link, packet));
  161. return instance;
  162. }
  163. /**
  164. * Transforms the String into an Number
  165. * @param map
  166. * @param s
  167. * @return
  168. */
  169. protected String stringToNominal(HashSet<String> map, String s) {
  170. return map.contains(s)?s:"unknown";
  171. }
  172. /**
  173. * Train the clusterer by collecting the packets
  174. *
  175. * @param packets packets to be learned
  176. */
  177. protected void training(HashMap<Link, LinkedList<Packet>> packets) {
  178. for(Entry<Link, LinkedList<Packet>> e:packets.entrySet()) {
  179. Link l = e.getKey();
  180. LinkedList<Packet> p = collectedPackets.get(l);
  181. if(p == null)
  182. collectedPackets.put(l, new LinkedList<Packet>(e.getValue()));
  183. else
  184. p.addAll(e.getValue());
  185. }
  186. }
  187. /**
  188. * Finishes the collection and trains the clusterer on the collected packets
  189. *
  190. * @throws Exception
  191. */
  192. protected void finishDataCollection() throws Exception{
  193. atts.add(new Attribute("Link-Name", new LinkedList<String>(link_mappings)));//TODO:??
  194. atts.add(new Attribute("Source-Device", new LinkedList<String>(source_mappings)));
  195. atts.add(new Attribute("Source-Port-number", false));
  196. atts.add(new Attribute("Destination-Device", new LinkedList<String>(destination_mappings)));
  197. atts.add(new Attribute("Destination-Port-number", false));
  198. Attribute pn = new Attribute("Protocol-name", new LinkedList<String>(protocol_mappings));
  199. //pn.setWeight(10);
  200. atts.add(pn);
  201. Attribute pps = new Attribute("Packets-per-second", false);
  202. //pps.setWeight(20);
  203. atts.add(pps);
  204. //atts.add(new Attribute("Anomaly", false));
  205. /*
  206. atts = new ArrayList<Attribute>();
  207. atts.add(new Attribute("LN", new LinkedList<String>(link_mappings)));//TODO:??
  208. atts.add(new Attribute("SD", new LinkedList<String>(source_mappings)));
  209. atts.add(new Attribute("SPN", false));
  210. atts.add(new Attribute("DD", new LinkedList<String>(destination_mappings)));
  211. atts.add(new Attribute("DPN", false));
  212. atts.add(new Attribute("PN", new LinkedList<String>(protocol_mappings)));
  213. atts.add(new Attribute("PPS", false));
  214. atts.add(new Attribute("A", false));*/
  215. dataset = new Instances("Packets", atts, 100000);
  216. //dataset.setClassIndex(7);
  217. /**
  218. * Add Instances to dataset
  219. */
  220. for (Iterator<Entry<Link, LinkedList<Packet>>> it = collectedPackets.entrySet().iterator(); it.hasNext();) {
  221. Entry<Link, LinkedList<Packet>> entry = it.next();
  222. /**
  223. * Link the packet was captured on
  224. */
  225. Link l = entry.getKey();
  226. for (Iterator<Packet> itPacket = entry.getValue().iterator(); itPacket.hasNext();) {
  227. /**
  228. * Packets to be added to the dataset
  229. */
  230. Packet packet = (Packet) itPacket.next();
  231. dataset.add(packet2Instance(l, packet, dataset));
  232. }
  233. }
  234. trainModel(dataset);
  235. }
  236. /**
  237. * Try to classify the given packets and detect anomalies
  238. * @param packets packets to be classified
  239. */
  240. protected void classify(HashMap<Link, LinkedList<Packet>> packets) {
  241. int tp = 0;
  242. int fp = 0;
  243. int tn = 0;
  244. int fn = 0;
  245. long start = Long.MAX_VALUE;
  246. long end = Long.MIN_VALUE;
  247. for (Iterator<Entry<Link, LinkedList<Packet>>> it = packets.entrySet().iterator(); it.hasNext();) {
  248. /**
  249. * Link & its packets
  250. */
  251. Entry<Link, LinkedList<Packet>> entry = it.next();
  252. /**
  253. * Link the packets were captured on
  254. */
  255. Link l = entry.getKey();
  256. for (Iterator<Packet> itPacket = entry.getValue().iterator(); itPacket.hasNext();) {
  257. /**
  258. * Packet which should be checked
  259. */
  260. Packet packet = (Packet) itPacket.next();
  261. start = Math.min(start, packet.getTimestamp());
  262. end = Math.max(end, packet.getTimestamp());
  263. /**
  264. * Instance Representation
  265. */
  266. Instance packet_instance = packet2Instance(l, packet, dataset);
  267. if(packet_instance == null)continue;
  268. try {
  269. classifyInstance(packet_instance, packet);
  270. if(packet.getLabel()==0)
  271. tn++;
  272. else
  273. fn++;
  274. } catch (Exception e) {
  275. if(packet.getLabel()==0)
  276. fp++;
  277. else
  278. tp++;
  279. }
  280. }
  281. }
  282. int n = tp+tn+fp+fn;
  283. if(n!=0) {
  284. System.out.println(getAlgoName()+" Performance: ["+start+"ms, "+end+"ms]");
  285. System.out.println("n: ");
  286. System.out.println("TP: "+tp);
  287. System.out.println("FP: "+fp);
  288. System.out.println("TN: "+tn);
  289. System.out.println("FN: "+fn);
  290. System.out.println("TPR: "+(tp/(tp+fn+0.0)));
  291. System.out.println("FPR: "+(fp/(fp+tn+0.0)));
  292. System.out.println("");
  293. }
  294. }
  295. /**
  296. * Train the model using the given instances
  297. * @param instances training set, which should be learned
  298. */
  299. public abstract void trainModel(Instances instances);
  300. /**
  301. * classifies the given instance
  302. * @param instance instance which should be classified
  303. * @param origin original packet, which was transformed into the instance
  304. * @throws Exception if anomaly was detected
  305. */
  306. public abstract void classifyInstance(Instance instance, Packet origin) throws Exception;
  307. /**
  308. * Returns the timestep, after which the classifier should start classifying instead of training.
  309. * @return timestep of the testing begin.
  310. */
  311. public abstract long getClassificationStart();
  312. @Override
  313. public void setMode(boolean testing) {
  314. training = !testing;
  315. if(testing) {
  316. try {
  317. finishDataCollection();
  318. } catch (Exception e) {
  319. System.out.println("Clustering failed");
  320. e.printStackTrace();
  321. }
  322. }
  323. }
  324. @Override
  325. public boolean getMode() {
  326. return !training;
  327. }
  328. /**
  329. * Short String representation of the classifier
  330. * @return
  331. */
  332. public abstract String getAlgoName();
  333. }