|
1
|
2 |
|
from __future__ import absolute_import |
|
2
|
2 |
|
from __future__ import print_function |
|
3
|
|
|
|
|
4
|
2 |
|
import platform |
|
5
|
|
|
|
|
6
|
2 |
|
from .constants import xml_version, oval_header, timestamp, PREFIX_TO_NS |
|
7
|
|
|
|
|
8
|
|
|
|
|
9
|
2 |
|
try: |
|
10
|
2 |
|
from xml.etree import cElementTree as ElementTree |
|
11
|
|
|
except ImportError: |
|
12
|
|
|
import cElementTree as ElementTree |
|
13
|
|
|
|
|
14
|
|
|
|
|
15
|
2 |
|
def oval_generated_header(product_name, schema_version, ssg_version): |
|
16
|
2 |
|
return xml_version + oval_header + \ |
|
17
|
|
|
""" |
|
18
|
|
|
<generator> |
|
19
|
|
|
<oval:product_name>%s from SCAP Security Guide</oval:product_name> |
|
20
|
|
|
<oval:product_version>ssg: %s, python: %s</oval:product_version> |
|
21
|
|
|
<oval:schema_version>%s</oval:schema_version> |
|
22
|
|
|
<oval:timestamp>%s</oval:timestamp> |
|
23
|
|
|
</generator>""" % (product_name, ssg_version, platform.python_version(), |
|
24
|
|
|
schema_version, timestamp) |
|
25
|
|
|
|
|
26
|
|
|
|
|
27
|
2 |
|
def open_xml(filename): |
|
28
|
|
|
""" |
|
29
|
|
|
Given a filename, register all possible namespaces, and return the XML tree. |
|
30
|
|
|
""" |
|
31
|
|
|
try: |
|
32
|
|
|
for prefix, uri in PREFIX_TO_NS.items(): |
|
33
|
|
|
ElementTree.register_namespace(prefix, uri) |
|
34
|
|
|
except Exception: |
|
35
|
|
|
# Probably an old version of Python |
|
36
|
|
|
# Doesn't matter, as this is non-essential. |
|
37
|
|
|
pass |
|
38
|
|
|
return ElementTree.parse(filename) |
|
39
|
|
|
|
|
40
|
|
|
|
|
41
|
2 |
|
def parse_file(filename): |
|
42
|
|
|
""" |
|
43
|
|
|
Given a filename, return the root of the ElementTree |
|
44
|
|
|
""" |
|
45
|
|
|
tree = open_xml(filename) |
|
46
|
|
|
return tree.getroot() |
|
47
|
|
|
|
|
48
|
|
|
|
|
49
|
2 |
|
def map_elements_to_their_ids(tree, xpath_expr): |
|
50
|
|
|
""" |
|
51
|
|
|
Given an ElementTree and an XPath expression, |
|
52
|
|
|
iterate through matching elements and create 1:1 id->element mapping. |
|
53
|
|
|
|
|
54
|
|
|
Raises AssertionError if a matching element doesn't have the ``id`` |
|
55
|
|
|
attribute. |
|
56
|
|
|
|
|
57
|
|
|
Returns mapping as a dictionary |
|
58
|
|
|
""" |
|
59
|
|
|
aggregated = {} |
|
60
|
|
|
for element in tree.findall(xpath_expr): |
|
61
|
|
|
element_id = element.get("id") |
|
62
|
|
|
assert element_id is not None |
|
63
|
|
|
aggregated[element_id] = element |
|
64
|
|
|
return aggregated |
|
65
|
|
|
|