LabelManager.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. import importlib
  2. import datetime as dt
  3. import os.path
  4. import xml.dom.minidom as minidom
  5. import ID2TLib.Label as Label
  6. class LabelManager:
  7. TAG_ROOT = 'labels'
  8. TAG_ATTACK = 'attack'
  9. TAG_ATTACK_NAME = 'name'
  10. TAG_ATTACK_NOTE = 'note'
  11. TAG_TIMESTAMP_START = 'timestamp_start'
  12. TAG_TIMESTAMP_END = 'timestamp_end'
  13. TAG_TIMESTAMP = 'timestamp'
  14. TAG_TIMESTAMP_HR = 'timestamp_hr'
  15. TAG_PARAMETERS = 'parameters'
  16. ATTR_VERSION = 'version_parser'
  17. # update this attribute if XML scheme was modified
  18. ATTR_VERSION_VALUE = '0.3'
  19. def __init__(self, filepath_pcap=None):
  20. """
  21. Creates a new LabelManager for managing the attack's labels.
  22. :param filepath_pcap: The path to the PCAP file associated to the labels.
  23. """
  24. self.labels = list()
  25. if filepath_pcap is not None:
  26. self.label_file_path = os.path.splitext(filepath_pcap)[0] + '_labels.xml'
  27. # only load labels if label file is existing
  28. if os.path.exists(self.label_file_path):
  29. self.load_labels()
  30. def add_labels(self, labels):
  31. """
  32. Adds a label to the internal list of labels.
  33. :param labels: The labels to be added
  34. """
  35. if isinstance(labels, list):
  36. self.labels = self.labels + [labels]
  37. elif isinstance(labels, tuple):
  38. for l in labels:
  39. self.labels.append(l)
  40. else:
  41. self.labels.append(labels)
  42. # sorts the labels ascending by their timestamp
  43. self.labels.sort()
  44. def write_label_file(self, filepath=None):
  45. """
  46. Writes previously added/loaded labels to a XML file. Uses the given filepath as destination path, if no path is
  47. given, uses the path in label_file_path.
  48. :param filepath: The path where the label file should be written to.
  49. """
  50. def get_subtree_timestamp(xml_tag_root, timestamp_entry):
  51. """
  52. Creates the subtree for a given timestamp, consisting of the unix time format (seconds) and a human-readable
  53. output.
  54. :param xml_tag_root: The tag name for the root of the subtree
  55. :param timestamp_entry: The timestamp as unix time
  56. :return: The root node of the XML subtree
  57. """
  58. timestamp_root = doc.createElement(xml_tag_root)
  59. # add timestamp in unix format
  60. timestamp = doc.createElement(self.TAG_TIMESTAMP)
  61. timestamp.appendChild(doc.createTextNode(str(timestamp_entry)))
  62. timestamp_root.appendChild(timestamp)
  63. # add timestamp in human-readable format
  64. timestamp_hr = doc.createElement(self.TAG_TIMESTAMP_HR)
  65. timestamp_hr_text = dt.datetime.fromtimestamp(timestamp_entry).strftime('%Y-%m-%d %H:%M:%S.%f')
  66. timestamp_hr.appendChild(doc.createTextNode(timestamp_hr_text))
  67. timestamp_root.appendChild(timestamp_hr)
  68. return timestamp_root
  69. def get_subtree_parameters(parameters):
  70. """
  71. Creates a subtree containing all parameters used to construct the attack
  72. :param parameters: The list of parameters used to run the attack
  73. :return: The root node of the XML subtree
  74. """
  75. parameters_root = doc.createElement(self.TAG_PARAMETERS)
  76. for param_key, param_value in parameters.items():
  77. param = doc.createElement(param_key.value)
  78. param.appendChild(doc.createTextNode(str(param_value)))
  79. parameters_root.appendChild(param)
  80. return parameters_root
  81. if filepath is not None:
  82. self.label_file_path = os.path.splitext(filepath)[0] + '_labels.xml'
  83. # Generate XML
  84. doc = minidom.Document()
  85. node = doc.createElement(self.TAG_ROOT)
  86. node.setAttribute(self.ATTR_VERSION, self.ATTR_VERSION_VALUE)
  87. for label in self.labels:
  88. xml_tree = doc.createElement(self.TAG_ATTACK)
  89. # add attack to XML tree
  90. attack_name = doc.createElement(self.TAG_ATTACK_NAME)
  91. attack_name.appendChild(doc.createTextNode(str(label.attack_name)))
  92. xml_tree.appendChild(attack_name)
  93. attack_note = doc.createElement(self.TAG_ATTACK_NOTE)
  94. attack_note.appendChild(doc.createTextNode(str(label.attack_note)))
  95. xml_tree.appendChild(attack_note)
  96. # add timestamp_start to XML tree
  97. xml_tree.appendChild(get_subtree_timestamp(self.TAG_TIMESTAMP_START, label.timestamp_start))
  98. # add timestamp_end to XML tree
  99. xml_tree.appendChild(get_subtree_timestamp(self.TAG_TIMESTAMP_END, label.timestamp_end))
  100. # add parameters to XML tree
  101. xml_tree.appendChild(get_subtree_parameters(label.parameters))
  102. node.appendChild(xml_tree)
  103. doc.appendChild(node)
  104. # Write XML to file
  105. file = open(self.label_file_path, 'w')
  106. file.write(doc.toprettyxml())
  107. file.close()
  108. def load_labels(self):
  109. """
  110. Loads the labels from an already existing label XML file located at label_file_path (set by constructor).
  111. """
  112. def get_value_from_node(node, tag_name, *child_number):
  113. """
  114. Returns the value located in the tag specified by tag_name from a given node. Walks therefor the
  115. node's children along as indicated by child_number, e.g., childNumber = (1,2,) first goes to the 1st child,
  116. and then to the 2nd child of the first child -> elem.childNodes[1].childNodes[2].
  117. """
  118. elem = node.getElementsByTagName(tag_name)
  119. if len(elem) == 1:
  120. elem = elem[0]
  121. for c in child_number:
  122. if len(elem.childNodes) > 0:
  123. elem = elem.childNodes[c]
  124. else:
  125. return ""
  126. return elem.data
  127. else:
  128. return ""
  129. print("Label file found. Loading labels...")
  130. try:
  131. dom = minidom.parse(self.label_file_path)
  132. except Exception:
  133. # TODO: more specific exception
  134. print('ERROR: Provided label file could not be parsed. Ignoring label file')
  135. return
  136. # Check if version of parser and version of file match
  137. version = dom.getElementsByTagName(self.TAG_ROOT)
  138. if len(version) > 0:
  139. version = version[0].getAttribute(self.ATTR_VERSION)
  140. if version == [] or not version == self.ATTR_VERSION_VALUE:
  141. print(
  142. "The file " + self.label_file_path + " was created by another version of ID2TLib.LabelManager. "
  143. "Ignoring label file.")
  144. # Parse attacks from XML file
  145. attacks = dom.getElementsByTagName(self.TAG_ATTACK)
  146. count_labels = 0
  147. for a in attacks:
  148. attack_name = get_value_from_node(a, self.TAG_ATTACK_NAME, 0)
  149. attack_note = get_value_from_node(a, self.TAG_ATTACK_NOTE, 0)
  150. timestamp_start = get_value_from_node(a, self.TAG_TIMESTAMP_START, 1, 0)
  151. timestamp_end = get_value_from_node(a, self.TAG_TIMESTAMP_END, 1, 0)
  152. # Instantiate this attack to create a parameter list with the correct types
  153. attack_module = importlib.import_module("Attack." + attack_name)
  154. attack_class = getattr(attack_module, attack_name)
  155. attack = attack_class()
  156. # Loop through all parameters listed in the XML file
  157. param = a.getElementsByTagName(self.TAG_PARAMETERS)[0]
  158. for param in param.childNodes:
  159. # Skip empty text nodes returned by minidom
  160. if not isinstance(param, minidom.Text):
  161. param_name = param.tagName
  162. param_value = param.childNodes[0].nodeValue
  163. attack.add_param_value(param_name, param_value)
  164. # Create the label from the data read
  165. label = Label.Label(attack_name, float(timestamp_start), float(timestamp_end), attack.params, attack_note)
  166. self.labels.append(label)
  167. count_labels += 1
  168. print("Read " + str(count_labels) + " label(s) successfully.")