Passed
Push — master ( 66a3d2...eb090f )
by Jan
04:12 queued 11s
created

graph.xml_parser.xml_parser.get_rule_dict()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1.125

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 2
ccs 1
cts 2
cp 0.5
rs 10
c 0
b 0
f 0
cc 1
nop 2
crap 1.125
1
'''
2
    Modules for create node IDs and parsing xml
3
'''
4
5 1
from lxml import etree as ET
6 1
import uuid
7 1
import graph.oval_graph
8
9
10 1
class xml_parser():
11 1
    def __init__(self, src):
12 1
        self.src = src
13 1
        self.tree = ET.parse(self.src)
14 1
        self.root = self.tree.getroot()
15 1
        if not self.validate(
16
                './schemas/arf/1.1/asset-reporting-format_1.1.0.xsd'):
17
            raise ValueError("err- This is not arf report file.")
18
19 1
    def validate(self, xsd_path):
20 1
        xmlschema_doc = ET.parse(xsd_path)
21 1
        xmlschema = ET.XMLSchema(xmlschema_doc)
22
23 1
        xml_doc = self.tree
24 1
        result = xmlschema.validate(xml_doc)
25
26 1
        return result
27
28 1
    def get_data(self, href):
29 1
        ns = {
30
            'ns0': 'http://oval.mitre.org/XMLSchema/oval-results-5',
31
            'ns1': 'http://scap.nist.gov/schema/asset-reporting-format/1.1'
32
        }
33
34 1
        report_data = None
35 1
        reports = self.root.find('.//ns1:reports', ns)
36 1
        if reports is None:
37
            raise ValueError("err- In file is missing arf reports")
38 1
        for report in reports:
39 1
            if "#" + str(report.get("id")) == href:
40 1
                report_data = report
41
42 1
        trees_data = report_data.find(
43
            './/ns0:oval_results/ns0:results/ns0:system/ns0:definitions', ns)
44 1
        return trees_data
45
46 1
    def get_used_rules(self):
47 1
        ns = {
48
            'ns0': 'http://checklists.nist.gov/xccdf/1.2',
49
        }
50 1
        rulesResults = self.root.findall(
51
            './/ns0:TestResult/ns0:rule-result', ns)
52 1
        rules = []
53 1
        for ruleResult in rulesResults:
54 1
            result = ruleResult.find('.//ns0:result', ns)
55 1
            if result.text != "notselected":
56 1
                check_content_ref = ruleResult.find(
57
                    './/ns0:check/ns0:check-content-ref', ns)
58 1
                if check_content_ref is not None:
59 1
                    rules.append(dict(
60
                        id_rule=ruleResult.get('idref'),
61
                        id_def=check_content_ref.attrib.get('name'),
62
                        href=check_content_ref.attrib.get('href'),
63
                        result=result.text))
64 1
        return rules
65
66 1
    def parse_data_to_dict(self, rule_id):
67 1
        scan = dict(definitions=[])
68 1
        used_rules = self.get_used_rules()
69 1
        for i in self.get_data(used_rules[0]['href']):
70 1
            scan['definitions'].append(self.build_graph(i))
71 1
        definitions = self._fill_extend_definition(scan)
72 1
        for definition in definitions['definitions']:
73 1
            if self.get_def_id_by_rule_id(rule_id) == definition['id']:
74 1
                return dict(rule_id=rule_id, definition=definition)
75
76 1
    def _xml_dict_to_node(self, dict_of_definition):
77 1
        children = []
78 1
        for child in dict_of_definition['node']:
79 1
            if 'operator' in child and 'id':
80 1
                children.append(self._xml_dict_to_node(child))
81
            else:
82 1
                children.append(
83
                    graph.oval_graph.OvalNode(
84
                        child['value_id'],
85
                        'value',
86
                        child['value']))
87
88 1
        if 'id' in dict_of_definition:
89 1
            children[0].node_id = dict_of_definition['id']
90 1
            return children[0]
91
        else:
92 1
            return graph.oval_graph.OvalNode(
93
                str(uuid.uuid4()),
94
                'operator',
95
                dict_of_definition['operator'],
96
                children
97
            )
98
99 1
    def get_def_id_by_rule_id(self, rule_id):
100 1
        used_rules = self.get_used_rules()
101 1
        for rule in used_rules:
102 1
            if rule['id_rule'] == rule_id:
103 1
                return rule['id_def']
104 1
        raise ValueError('err- 404 rule not found!')
105
106 1
    def get_rule_dict(self, rule_id):
107
        return self.parse_data_to_dict(rule_id)
108
109 1
    def xml_dict_of_rule_to_node(self, rule):
110 1
        print(rule)
111 1
        dict_of_definition = rule['definition']
112 1
        return graph.oval_graph.OvalNode(
113
            rule['rule_id'],
114
            'operator',
115
            'and',
116
            [self._xml_dict_to_node(dict_of_definition)]
117
        )
118
119 1
    def get_oval_graph(self, rule_id=None):
120 1
        return self.xml_dict_of_rule_to_node(self.parse_data_to_dict(rule_id))
121
122 1
    def build_graph(self, tree_data):
123 1
        negate_status = False
124 1
        if tree_data.get('negate') is not None:
125
            negate_status = True
126 1
        graph = dict(
127
            id=tree_data.get('definition_id'),
128
            negate=negate_status,
129
            node=[])
130 1
        for tree in tree_data:
131 1
            negate_status = False
132 1
            if tree.get('negate') is not None:
133 1
                negate_status = True
134 1
            graph['negate'] = negate_status
135 1
            graph['node'].append(self._build_node(tree))
136 1
        return graph
137
138 1
    def _build_node(self, tree):
139 1
        negate_status = False
140 1
        if tree.get('negate') is not None:
141 1
            negate_status = True
142
143 1
        node = dict(
144
            operator=tree.get('operator'),
145
            negate=negate_status,
146
            result=tree.get('result'),
147
            node=[])
148 1
        for child in tree:
149 1
            if child.get('operator') is not None:
150 1
                node['node'].append(self._build_node(child))
151
            else:
152 1
                negate_status = False
153 1
                if child.get('negate') is not None:
154 1
                    negate_status = True
155
156 1
                if child.get('definition_ref') is not None:
157 1
                    node['node'].append(
158
                        dict(
159
                            extend_definition=child.get('definition_ref'),
160
                            result=child.get('result'),
161
                            negate=negate_status))
162
                else:
163 1
                    node['node'].append(
164
                        dict(
165
                            value_id=child.get('test_ref'),
166
                            value=child.get('result'),
167
                            negate=negate_status))
168 1
        return node
169
170 1
    def _fill_extend_definition(self, scan):
171 1
        out = dict(definitions=[])
172 1
        for definition in scan['definitions']:
173 1
            nodes = []
174 1
            for value in definition['node']:
175 1
                nodes.append(self._operator_as_child(value, scan))
176 1
            out['definitions'].append(dict(id=definition['id'], node=nodes))
177 1
        return out
178
179 1
    def _operator_as_child(self, value, scan):
180 1
        out = dict(
181
            operator=value['operator'],
182
            negate=value['negate'],
183
            result=value['negate'],
184
            node=[])
185 1
        for child in value['node']:
186 1
            if 'operator' in child:
187 1
                out['node'].append(self._operator_as_child(child, scan))
188 1
            elif 'extend_definition' in child:
189 1
                out['node'].append(
190
                    self._find_definition_by_id(
191
                        scan, child['extend_definition'], child['negate']))
192 1
            elif 'value_id' in child:
193 1
                out['node'].append(child)
194
            else:
195
                raise ValueError('error - unknown child')
196 1
        return out
197
198 1
    def _find_definition_by_id(self, scan, id, negate_status):
199 1
        for definition in scan['definitions']:
200 1
            if definition['id'] == id:
201 1
                definition['node'][0]['negate'] = negate_status
202
                return self._operator_as_child(definition['node'][0], scan)
203