Passed
Pull Request — master (#187)
by Jan
04:47 queued 43s
created

XmlParser.__init__()   A

Complexity

Conditions 3

Size

Total Lines 23
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 23
nop 2
dl 0
loc 23
ccs 20
cts 20
cp 1
crap 3
rs 9.328
c 0
b 0
f 0
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 .._builder_oval_tree import _BuilderOvalTree
11 1
from ..exceptions import NotChecked
12 1
from ._xml_parser_oval_scan_definitions import _XmlParserScanDefinitions
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 XmlParser:
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
best-practice introduced by
Too many instance attributes (11/7)
Loading history...
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
            CRED = '\033[91m'
0 ignored issues
show
Coding Style Naming introduced by
Variable name "CRED" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
32 1
            CEND = '\033[0m'
0 ignored issues
show
Coding Style Naming introduced by
Variable name "CEND" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
33 1
            message = CRED + "Warning: This file is not valid arf report." + CEND
34 1
            print(message, file=sys.stderr)
35 1
        try:
36 1
            self.used_rules = self._get_used_rules()  # !
37 1
            self.report_data_href = list(self.used_rules.values())[0]['href']
38 1
            self.report_data = self._get_report_data(self.report_data_href)
39 1
            self.notselected_rules = self._get_notselected_rules()  # put together !
40 1
            self.definitions = self._get_definitions()
41 1
            self.oval_definitions = self._get_oval_definitions()
42 1
            self.scan_definitions = _XmlParserScanDefinitions(
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
    def get_src(self, src):
0 ignored issues
show
Coding Style introduced by
This method could be written as a function/class method.

If a method does not access any attributes of the class, it could also be implemented as a function or static method. This can help improve readability. For example

class Foo:
    def some_method(self, x, y):
        return x + y;

could be written as

class Foo:
    @classmethod
    def some_method(cls, x, y):
        return x + y;
Loading history...
introduced by
Missing function or method docstring
Loading history...
50 1
        _dir = os.path.dirname(os.path.realpath(__file__))
51 1
        FIXTURE_DIR = os.path.join(_dir, src)
0 ignored issues
show
Coding Style Naming introduced by
Variable name "FIXTURE_DIR" doesn't conform to snake_case naming style ('([^\\W\\dA-Z][^\\WA-Z]2,|_[^\\WA-Z]*|__[^\\WA-Z\\d_][^\\WA-Z]+__)$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
52 1
        return str(FIXTURE_DIR)
53
54 1
    def validate(self, xsd_path):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
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
59 1
        xml_doc = self.tree
60 1
        result = xmlschema.validate(xml_doc)
61
62 1
        return result
63
64 1
    def _get_used_rules(self):
65 1
        rules_results = self.root.findall(
66
            './/xccdf:TestResult/xccdf:rule-result', ns)
67 1
        rules = {}
68 1
        for rule_result in rules_results:
69 1
            result = rule_result.find('.//xccdf:result', ns)
70 1
            if result.text != "notselected":
71 1
                check_content_ref = rule_result.find(
72
                    './/xccdf:check/xccdf:check-content-ref', ns)
73 1
                message = rule_result.find(
74
                    './/xccdf:message', ns)
75 1
                rule_dict = {}
76 1
                if check_content_ref is not None:
77 1
                    rule_dict['id_def'] = check_content_ref.attrib.get('name')
78 1
                    rule_dict['href'] = check_content_ref.attrib.get('href')
79 1
                    rule_dict['result'] = result.text
80 1
                    if message is not None:
81 1
                        rule_dict['message'] = message.text
82 1
                    rules[rule_result.get('idref')] = rule_dict
83 1
        return rules
84
85 1
    def _get_report_data(self, href):
86 1
        report_data = None
87 1
        reports = self.root.find('.//arf:reports', ns)
88 1
        for report in reports:
89 1
            if "#" + str(report.get("id")) == href:
90 1
                report_data = report
91 1
        return report_data
92
93 1
    def _get_notselected_rules(self):
94 1
        rules_results = self.root.findall(
95
            './/xccdf:TestResult/xccdf:rule-result', ns)
96 1
        rules = []
97 1
        for rule_result in rules_results:
98 1
            result = rule_result.find('.//xccdf:result', ns)
99 1
            if result.text == "notselected":
100 1
                rules.append(rule_result.get('idref'))
101 1
        return rules
102
103 1
    def _get_definitions(self):
104 1
        data = self.report_data.find(
105
            ('.//XMLSchema:oval_results/XMLSchema:results/'
106
             'XMLSchema:system/XMLSchema:definitions'), ns)
107 1
        return data
108
109 1
    def _get_oval_definitions(self):
110 1
        return self.root.find(
111
            './/arf:report-requests/arf:report-request/'
112
            'arf:content/scap:data-stream-collection/'
113
            'scap:component/oval-definitions:oval_definitions/'
114
            'oval-definitions:definitions', ns)
115
116 1
    def _get_definition_of_rule(self, rule_id):
117 1
        if rule_id in self.used_rules:
0 ignored issues
show
unused-code introduced by
Unnecessary "elif" after "return"
Loading history...
118 1
            rule_info = self.used_rules[rule_id]
119 1
            if rule_info['id_def'] is None:
120 1
                raise NotChecked(
121
                    '"{}" is {}: {}'.format(
122
                        rule_id,
123
                        rule_info['result'],
124
                        rule_info['message']))
125 1
            return dict(rule_id=rule_id,
126
                        definition_id=rule_info['id_def'],
127
                        definition=self.scan_definitions[rule_info['id_def']])
128 1
        elif rule_id in self.notselected_rules:
129 1
            raise ValueError(
130
                'Rule "{}" was not selected, so there are no results.'
131
                .format(rule_id))
132
        else:
133 1
            raise ValueError('404 rule "{}" not found!'.format(rule_id))
134
135 1
    def get_oval_tree(self, rule_id):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
136 1
        return _BuilderOvalTree.get_oval_tree_from_dict_of_rule(
137
            self._get_definition_of_rule(rule_id))
138