LabelManager.py 6.6 KB

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