LabelManager.py 8.5 KB

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