BasicPacketClassifier.java 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 && !packets.entrySet().isEmpty() && !packets.entrySet().iterator().next().getValue().isEmpty() && packets.entrySet().iterator().next().getValue().getFirst().getTimestamp()>getClassificationStart()) {
  74. training = false;
  75. // Build Clusterer
  76. try {
  77. finishDataCollection();
  78. } catch (Exception e) {
  79. System.out.println("Clustering failed");
  80. e.printStackTrace();
  81. }
  82. }
  83. if(training)
  84. try {
  85. training(packets);
  86. } catch (Exception e) {
  87. e.printStackTrace();
  88. }
  89. else
  90. classify(packets);
  91. }
  92. /**
  93. * Estimates the current Packets per second (depending on the last 100 packets of the link)
  94. * @param link Link which should be checked
  95. * @param packet Packet which should investigated
  96. * @return estimated number of packets per second
  97. */
  98. protected double getEstimatedPacketsPerSecond(Link link, Packet packet) {
  99. /**
  100. * Packets used to calculated the packets per second
  101. */
  102. LinkedList<Packet> list = lastPackets.get(link);
  103. if(list == null) {
  104. /**
  105. * Add list if not present
  106. */
  107. list = new LinkedList<Packet>();
  108. lastPackets.put(link, list);
  109. }
  110. if(list.isEmpty()) {
  111. list.addLast(packet);
  112. // Default 1 packet per second
  113. return 1.0;
  114. }
  115. if(list.size() == NUMBER_OF_PACKETS){
  116. list.removeFirst();
  117. }
  118. list.addLast(packet);
  119. /**
  120. * elapsed time in milliseconds since last packet
  121. */
  122. long elapsed_time = packet.getTimestamp()-list.getFirst().getTimestamp()/list.size();
  123. if(elapsed_time<=0)
  124. return Double.POSITIVE_INFINITY;
  125. /**
  126. * Return number of packets per second
  127. */
  128. return 1000.0/elapsed_time;
  129. }
  130. /**
  131. * Returns the instance representation of the given packet and link
  132. * @param link link the packet was sent on
  133. * @param packet packet which should be transformed
  134. * @param dataset distribution the packet is part of
  135. * @return instance representation
  136. */
  137. protected Instance packet2Instance(Link link, Packet packet, Instances dataset) {
  138. /**
  139. * Instance for the given Packet
  140. */
  141. DenseInstance instance = new DenseInstance(dataset.numAttributes());
  142. instance.setDataset(dataset);
  143. // link
  144. instance.setValue(0, stringToNominal(link_mappings, link.getName()));
  145. // source
  146. if(packet.getSource()==null) {
  147. instance.setValue(1, "unknown");
  148. instance.setValue(2, Double.NEGATIVE_INFINITY);
  149. }else if(packet.getSource().getOwner()==null){
  150. instance.setValue(1, "unknown");
  151. instance.setValue(2, packet.getSource().getPortNumber());
  152. }else {
  153. instance.setValue(1, stringToNominal(source_mappings, packet.getSource().getOwner().getName()));
  154. instance.setValue(2, packet.getSource().getPortNumber());
  155. }
  156. // Destination
  157. if(packet.getDestination()==null) {
  158. instance.setValue(3, "unknown");
  159. instance.setValue(4, Double.NEGATIVE_INFINITY);
  160. }else if(packet.getDestination().getOwner()==null){
  161. instance.setValue(3, "unknown");
  162. instance.setValue(4, packet.getDestination().getPortNumber());
  163. }else {
  164. instance.setValue(3, stringToNominal(destination_mappings, packet.getDestination().getOwner().getName()));
  165. instance.setValue(4, packet.getDestination().getPortNumber());
  166. }
  167. // Protocol name
  168. instance.setValue(5, stringToNominal(protocol_mappings, packet.getProtocolName()));
  169. // Packets per second
  170. instance.setValue(6, getEstimatedPacketsPerSecond(link, packet));
  171. return instance;
  172. }
  173. /**
  174. * Transforms the String into an Number
  175. * @param map
  176. * @param s
  177. * @return
  178. */
  179. protected String stringToNominal(HashSet<String> map, String s) {
  180. return map.contains(s)?s:"unknown";
  181. }
  182. /**
  183. * Train the clusterer by collecting the packets
  184. *
  185. * @param packets packets to be learned
  186. */
  187. protected void training(HashMap<Link, LinkedList<Packet>> packets) {
  188. for(Entry<Link, LinkedList<Packet>> e:packets.entrySet()) {
  189. Link l = e.getKey();
  190. LinkedList<Packet> p = collectedPackets.get(l);
  191. if(p == null)
  192. collectedPackets.put(l, new LinkedList<Packet>(e.getValue()));
  193. else
  194. p.addAll(e.getValue());
  195. }
  196. }
  197. /**
  198. * Finishes the collection and trains the clusterer on the collected packets
  199. *
  200. * @throws Exception
  201. */
  202. protected void finishDataCollection() throws Exception{
  203. atts.add(new Attribute("Link-Name", new LinkedList<String>(link_mappings)));//TODO:??
  204. atts.add(new Attribute("Source-Device", new LinkedList<String>(source_mappings)));
  205. atts.add(new Attribute("Source-Port-number", false));
  206. atts.add(new Attribute("Destination-Device", new LinkedList<String>(destination_mappings)));
  207. atts.add(new Attribute("Destination-Port-number", false));
  208. Attribute pn = new Attribute("Protocol-name", new LinkedList<String>(protocol_mappings));
  209. //pn.setWeight(10);
  210. atts.add(pn);
  211. Attribute pps = new Attribute("Packets-per-second", false);
  212. //pps.setWeight(20);
  213. atts.add(pps);
  214. //atts.add(new Attribute("Anomaly", false));
  215. /*
  216. atts = new ArrayList<Attribute>();
  217. atts.add(new Attribute("LN", new LinkedList<String>(link_mappings)));//TODO:??
  218. atts.add(new Attribute("SD", new LinkedList<String>(source_mappings)));
  219. atts.add(new Attribute("SPN", false));
  220. atts.add(new Attribute("DD", new LinkedList<String>(destination_mappings)));
  221. atts.add(new Attribute("DPN", false));
  222. atts.add(new Attribute("PN", new LinkedList<String>(protocol_mappings)));
  223. atts.add(new Attribute("PPS", false));
  224. atts.add(new Attribute("A", false));*/
  225. dataset = new Instances("Packets", atts, 100000);
  226. //dataset.setClassIndex(7);
  227. /**
  228. * Add Instances to dataset
  229. */
  230. for (Iterator<Entry<Link, LinkedList<Packet>>> it = collectedPackets.entrySet().iterator(); it.hasNext();) {
  231. Entry<Link, LinkedList<Packet>> entry = it.next();
  232. /**
  233. * Link the packet was captured on
  234. */
  235. Link l = entry.getKey();
  236. for (Iterator<Packet> itPacket = entry.getValue().iterator(); itPacket.hasNext();) {
  237. /**
  238. * Packets to be added to the dataset
  239. */
  240. Packet packet = (Packet) itPacket.next();
  241. dataset.add(packet2Instance(l, packet, dataset));
  242. }
  243. }
  244. trainModel(dataset);
  245. }
  246. /**
  247. * Try to classify the given packets and detect anomalies
  248. * @param packets packets to be classified
  249. */
  250. protected void classify(HashMap<Link, LinkedList<Packet>> packets) {
  251. for (Iterator<Entry<Link, LinkedList<Packet>>> it = packets.entrySet().iterator(); it.hasNext();) {
  252. /**
  253. * Link & its packets
  254. */
  255. Entry<Link, LinkedList<Packet>> entry = it.next();
  256. /**
  257. * Link the packets were captured on
  258. */
  259. Link l = entry.getKey();
  260. for (Iterator<Packet> itPacket = entry.getValue().iterator(); itPacket.hasNext();) {
  261. /**
  262. * Packet which should be checked
  263. */
  264. Packet packet = (Packet) itPacket.next();
  265. /**
  266. * Instance Representation
  267. */
  268. Instance packet_instance = packet2Instance(l, packet, dataset);
  269. if(packet_instance == null)continue;
  270. classifyInstance(null, packet);
  271. }
  272. }
  273. }
  274. /**
  275. * Train the model using the given instances
  276. * @param instances training set, which should be learned
  277. */
  278. public abstract void trainModel(Instances instances);
  279. /**
  280. * classifies the given instance
  281. * @param instance instance which should be classified
  282. * @param origin original packet, which was transformed into the instance
  283. */
  284. public abstract void classifyInstance(Instance instance, Packet origin);
  285. /**
  286. * Returns the timestep, after which the classifier should start classifying instead of training.
  287. * @return timestep of the testing begin.
  288. */
  289. public abstract long getClassificationStart();
  290. }