Passed
Pull Request — master (#187)
by Jan
06:49
created

oval_graph.arf_xml_parser.arf_xml_parser   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 126
Duplicated Lines 0 %

Test Coverage

Coverage 98.73%

Importance

Changes 0
Metric Value
eloc 104
dl 0
loc 126
ccs 78
cts 79
cp 0.9873
rs 10
c 0
b 0
f 0
wmc 20

10 Methods

Rating   Name   Duplication   Size   Complexity  
A ARFXMLParser.get_src() 0 4 1
A ARFXMLParser.__init__() 0 23 3
A ARFXMLParser._get_definition_of_rule() 0 12 3
A ARFXMLParser._get_rules_in_profile() 0 18 4
A ARFXMLParser._get_definitions() 0 4 1
A ARFXMLParser._get_rule_dict() 0 10 2
A ARFXMLParser._get_oval_definitions() 0 6 1
A ARFXMLParser.get_oval_tree() 0 3 1
A ARFXMLParser.validate() 0 5 1
A ARFXMLParser._get_report_data() 0 7 3
1
"""
2
    This file contains a class for creating OVAL graph from ARF XML source
3
"""
4
5 1
import os
6 1
import sys
7
8 1
from lxml import etree as ET
9
10 1
from ..exceptions import NotTestedRule
11 1
from ..oval_tree.builder import Builder
12 1
from ._oval_scan_definitions import _OVALScanDefinitions
13
14 1
ns = {
15
    'XMLSchema': 'http://oval.mitre.org/XMLSchema/oval-results-5',
16
    'xccdf': 'http://checklists.nist.gov/xccdf/1.2',
17
    'arf': 'http://scap.nist.gov/schema/asset-reporting-format/1.1',
18
    'oval-definitions': 'http://oval.mitre.org/XMLSchema/oval-definitions-5',
19
    'scap': 'http://scap.nist.gov/schema/scap/source/1.2',
20
    'oval-characteristics': 'http://oval.mitre.org/XMLSchema/oval-system-characteristics-5',
21
}
22
23
24 1
class ARFXMLParser:
25 1
    def __init__(self, src):
26 1
        self.src = src
27 1
        self.tree = ET.parse(self.src)
28 1
        self.root = self.tree.getroot()
29 1
        self.arf_schemas_src = '../schemas/arf/1.1/asset-reporting-format_1.1.0.xsd'
30 1
        if not self.validate(self.arf_schemas_src):
31 1
            start_red_color = '\033[91m'
32 1
            end_red_color = '\033[0m'
33 1
            message = "{}Warning: This file is not valid arf report.{}".format(
34
                start_red_color, end_red_color)
35 1
            print(message, file=sys.stderr)
36 1
        try:
37 1
            self.used_rules, self.not_tested_rules = self._get_rules_in_profile()
38 1
            self.report_data_href = list(self.used_rules.values())[0]['href']
39 1
            self.report_data = self._get_report_data(self.report_data_href)
40 1
            self.definitions = self._get_definitions()
41 1
            self.oval_definitions = self._get_oval_definitions()
42 1
            self.scan_definitions = _OVALScanDefinitions(
43
                self.definitions, self.oval_definitions, self.report_data).get_scan()
44 1
        except BaseException as error:
45 1
            raise ValueError(
46
                'This file "{}" is not arf report file or there are no results'.format(
47
                    self.src)) from error
48
49 1
    @staticmethod
50
    def get_src(src):
51 1
        dir_path = os.path.dirname(os.path.realpath(__file__))
52 1
        return str(os.path.join(dir_path, src))
53
54 1
    def validate(self, xsd_path):
55 1
        xsd_path = self.get_src(xsd_path)
56 1
        xmlschema_doc = ET.parse(xsd_path)
57 1
        xmlschema = ET.XMLSchema(xmlschema_doc)
58 1
        return xmlschema.validate(self.tree)
59
60 1
    @staticmethod
61
    def _get_rule_dict(rule_result, result, id_def, check_content_ref):
62 1
        message = rule_result.find('.//xccdf:message', ns)
63 1
        rule_dict = {}
64 1
        rule_dict['id_def'] = id_def
65 1
        rule_dict['href'] = check_content_ref.attrib.get('href')
66 1
        rule_dict['result'] = result.text
67 1
        if message is not None:
68
            rule_dict['message'] = message.text
69 1
        return rule_dict
70
71 1
    def _get_rules_in_profile(self):
72 1
        rules_results = self.root.findall(
73
            './/xccdf:TestResult/xccdf:rule-result', ns)
74 1
        rules = {}
75 1
        not_tested_rules = {}
76 1
        for rule_result in rules_results:
77 1
            result = rule_result.find('.//xccdf:result', ns)
78 1
            check_content_ref = rule_result.find(
79
                './/xccdf:check/xccdf:check-content-ref', ns)
80 1
            if check_content_ref is not None:
81 1
                id_ = rule_result.get('idref')
82 1
                id_def = check_content_ref.attrib.get('name')
83 1
                if id_def is not None:
84 1
                    rules[id_] = self._get_rule_dict(
85
                        rule_result, result, id_def, check_content_ref)
86 1
                    continue
87 1
            not_tested_rules[rule_result.get('idref')] = result.text
88 1
        return (rules, not_tested_rules)
89
90 1
    def _get_report_data(self, href):
91 1
        report_data = None
92 1
        reports = self.root.find('.//arf:reports', ns)
93 1
        for report in reports:
94 1
            if "#" + str(report.get("id")) == href:
95 1
                report_data = report
96 1
        return report_data
97
98 1
    def _get_definitions(self):
99 1
        return self.report_data.find(
100
            ('.//XMLSchema:oval_results/XMLSchema:results/'
101
             'XMLSchema:system/XMLSchema:definitions'), ns)
102
103 1
    def _get_oval_definitions(self):
104 1
        return self.root.find(
105
            './/arf:report-requests/arf:report-request/'
106
            'arf:content/scap:data-stream-collection/'
107
            'scap:component/oval-definitions:oval_definitions/'
108
            'oval-definitions:definitions', ns)
109
110 1
    def _get_definition_of_rule(self, rule_id):
111 1
        if rule_id in self.used_rules:
112 1
            rule_info = self.used_rules[rule_id]
113 1
            return dict(rule_id=rule_id,
114
                        definition_id=rule_info['id_def'],
115
                        definition=self.scan_definitions[rule_info['id_def']])
116
117 1
        if rule_id in self.not_tested_rules:
118 1
            raise NotTestedRule(
119
                'Rule "{}" is {}, so there are no results.'
120
                .format(rule_id, self.not_tested_rules[rule_id]))
121 1
        raise ValueError('404 rule "{}" not found!'.format(rule_id))
122
123 1
    def get_oval_tree(self, rule_id):
124 1
        return Builder.dict_of_rule_to_oval_tree(
125
            self._get_definition_of_rule(rule_id))
126