Passed
Branch master (53139b)
by Matěj
04:46 queued 02:30
created

_get_benchmark_node()   A

Complexity

Conditions 3

Size

Total Lines 10
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nop 3
dl 0
loc 10
rs 9.9
c 0
b 0
f 0
1
#!/usr/bin/env python2
2
import xml.etree.cElementTree as ET
3
4
import logging
5
6
NAMESPACES = {
7
    'xccdf': "http://checklists.nist.gov/xccdf/1.2",
8
    'ds': "http://scap.nist.gov/schema/scap/source/1.2",
9
    'xlink': "http://www.w3.org/1999/xlink",
10
}
11
12
13
logging.getLogger(__name__).addHandler(logging.NullHandler())
14
15
16
def infer_benchmark_id_from_component_ref_id(datastream, ref_id):
17
    root = ET.parse(datastream).getroot()
18
    component_ref_node = root.find("*//ds:component-ref[@id='{0}']"
19
                                   .format(ref_id), NAMESPACES)
20
    if component_ref_node is None:
21
        msg = (
22
            'Component reference of Ref-Id {} not found within datastream'
23
            .format(ref_id))
24
        raise RuntimeError(msg)
25
26
    comp_id = component_ref_node.get('{%s}href' % NAMESPACES['xlink'])
27
    comp_id = comp_id.lstrip('#')
28
29
    query = ".//ds:component[@id='{}']/xccdf:Benchmark".format(comp_id)
30
    benchmark_node = root.find(query, NAMESPACES)
31
    if benchmark_node is None:
32
        msg = (
33
            'Benchmark not found within component of Id {}'
34
            .format(comp_id)
35
        )
36
        raise RuntimeError(msg)
37
38
    return benchmark_node.get('id')
39
40
41
def _get_benchmark_node(datastream, benchmark_id, logging):
42
    root = ET.parse(datastream).getroot()
43
    benchmark_node = root.find(
44
        "*//xccdf:Benchmark[@id='{0}']".format(benchmark_id), NAMESPACES)
45
    if benchmark_node is None:
46
        if logging is not None:
47
            logging.error(
48
                "Benchmark ID '{}' not found within DataStream"
49
                .format(benchmark_id))
50
    return benchmark_node
51
52
53
def get_all_profiles_in_benchmark(datastream, benchmark_id, logging=None):
54
    benchmark_node = _get_benchmark_node(datastream, benchmark_id, logging)
55
    all_profiles = benchmark_node.findall('xccdf:Profile', NAMESPACES)
56
    return all_profiles
57
58
59
def benchmark_get_applicable_platforms(datastream, benchmark_id, logging=None):
60
    """
61
    Returns a set of CPEs the given benchmark is applicable to.
62
    """
63
    benchmark_node = _get_benchmark_node(datastream, benchmark_id, logging)
64
    platform_elements = benchmark_node.findall('xccdf:platform', NAMESPACES)
65
    cpes = {platform_el.get("idref") for platform_el in platform_elements}
66
    return cpes
67