Passed
Push — master ( 2ef001...6551ad )
by Jan
03:14 queued 11s
created

graph.client   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 171
Duplicated Lines 0 %

Test Coverage

Coverage 93.88%

Importance

Changes 0
Metric Value
eloc 145
dl 0
loc 171
ccs 92
cts 98
cp 0.9388
rs 9.68
c 0
b 0
f 0
wmc 34

12 Methods

Rating   Name   Duplication   Size   Complexity  
A client.parse_arguments() 0 40 1
A client._get_wanted_not_selected_rules() 0 4 1
A client.open_web_browser() 0 8 3
A client.get_only_fail_rule() 0 2 2
A client.save_dict() 0 4 2
A client.__init__() 0 16 3
A client._get_wanted_rules() 0 4 1
A client.search_rules_id() 0 16 5
A client.create_dict_of_rule() 0 6 2
A client.prepare_data() 0 9 3
B client.run_gui_and_return_answers() 0 19 6
B client.get_questions() 0 21 5
1 1
from __future__ import print_function, unicode_literals
2 1
import re
3 1
import graph.xml_parser
4 1
import graph.oval_graph
5 1
import webbrowser
6 1
import json
7 1
import argparse
8
9
10 1
class client():
11 1
    def __init__(self, args):
12 1
        self.arg = self.parse_arguments(args)
13 1
        self.remove_pass_tests = self.arg.remove_pass_tests
14 1
        self.show_fail_rules = self.arg.show_fail_rules
15 1
        self.show_not_selected_rules = self.arg.show_not_selected_rules
16 1
        self.off_webbrowser = self.arg.off_web_browser
17 1
        self.source_filename = self.arg.source_filename
18 1
        self.tree = self.arg.tree
19 1
        self.rule_name = self.arg.rule_id
20 1
        self.xml_parser = graph.xml_parser.xml_parser(self.source_filename)
21 1
        if self.tree:
22 1
            self.html_interpreter = 'tree_html_interpreter'
23
        else:
24 1
            self.html_interpreter = 'graph_html_interpreter'
25 1
        if self.remove_pass_tests:
26
            raise NotImplementedError('Not implemented!')
27
28 1
    def run_gui_and_return_answers(self):
29 1
        try:
30 1
            from PyInquirer import style_from_dict, Token, prompt, Separator
31
            return prompt(
32
                self.get_questions(
33
                    Separator('= The Rules IDs ='),
34
                    Separator('= The not selected rule IDs =')))
35 1
        except ImportError:
36 1
            print('== The Rule IDs ==')
37 1
            rules = self.search_rules_id()
38 1
            if self.show_fail_rules:
39 1
                rules = self.get_only_fail_rule(rules)
40 1
            for rule in rules:
41 1
                print(rule['id_rule'] + r'\b')
42 1
            if self.show_not_selected_rules:
43 1
                print('== The not selected rule IDs ==')
44 1
                for rule in self._get_wanted_not_selected_rules():
45 1
                    print(rule['id_rule'] + '(Not selected)')
46 1
            return None
47
48 1
    def get_questions(
49
            self,
50
            separator_rule_ids,
51
            separator_not_selected_rule_ids):
52 1
        rules = self.search_rules_id()
53 1
        if self.show_fail_rules:
54 1
            rules = self.get_only_fail_rule(rules)
55 1
        questions = [{
56
            'type': 'checkbox',
57
            'message': 'Select rule(s)',
58
            'name': 'rules',
59
            'choices': [separator_rule_ids]
60
        }]
61 1
        for rule in rules:
62 1
            questions[0]['choices'].append(dict(name=rule['id_rule']))
63 1
        if self.show_not_selected_rules:
64 1
            questions[0]['choices'].append(separator_not_selected_rule_ids)
65 1
            for rule in self._get_wanted_not_selected_rules():
66 1
                questions[0]['choices'].append(
67
                    dict(name=rule['id_rule'], disabled='Not selected'))
68 1
        return questions
69
70 1
    def get_only_fail_rule(self, rules):
71 1
        return list(filter(lambda rule: rule['result'] == 'fail', rules))
72
73 1
    def _get_wanted_rules(self):
74 1
        return [
75
            x for x in self.xml_parser.get_used_rules() if re.search(
76
                self.rule_name, x['id_rule'])]
77
78 1
    def _get_wanted_not_selected_rules(self):
79 1
        return [
80
            x for x in self.xml_parser.get_notselected_rules() if re.search(
81
                self.rule_name, x['id_rule'])]
82
83 1
    def search_rules_id(self):
84 1
        rules = self._get_wanted_rules()
85 1
        notselected_rules = self._get_wanted_not_selected_rules()
86 1
        if len(notselected_rules) and not rules:
87 1
            raise ValueError(
88
                ('err- rule(s) "{}" was not selected, '
89
                 "so there are no results. The rule is"
90
                 ' "notselected" because it'
91
                 " wasn't a part of the executed profile"
92
                 " and therefore it wasn't evaluated "
93
                 "during the scan.")
94
                .format(notselected_rules[0]['id_rule']))
95 1
        elif not notselected_rules and not rules:
96 1
            raise ValueError('err- 404 rule not found!')
97
        else:
98 1
            return rules
99
100 1
    def create_dict_of_rule(self, rule_id):
101 1
        if self.tree:
102 1
            return graph.oval_graph.build_nodes_form_xml(
103
                self.source_filename, rule_id).to_JsTree_dict()
104 1
        return graph.oval_graph.build_nodes_form_xml(
105
            self.source_filename, rule_id).to_sigma_dict(0, 0)
106
107 1
    def save_dict(self, dict):
108 1
        with open(self.html_interpreter + '/data.js', "w+") as data_file:
109 1
            data_file.write("var data_json =" + str(json.dumps(
110
                dict, sort_keys=False, indent=4) + ";"))
111
112 1
    def prepare_data(self, rules):
113 1
        try:
114 1
            for rule in rules['rules']:
115 1
                oval_tree = self.create_dict_of_rule(rule)
116 1
                self.save_dict(oval_tree)
117 1
                self.open_web_browser()
118 1
                print('Rule "{}" done!'.format(rule))
119 1
        except Exception as error:
120 1
            raise ValueError('Rule: "{}" Error: "{}"'.format(rule, error))
121
122 1
    def open_web_browser(self):
123 1
        if not self.off_webbrowser:
124
            try:
125
                webbrowser.get('firefox').open_new_tab(
126
                    self.html_interpreter + '/index.html')
127
            except BaseException:
128
                webbrowser.open_new_tab(
129
                    self.src_html_interpreter + '/index.html')
130
131 1
    def parse_arguments(self, args):
132 1
        parser = argparse.ArgumentParser(
133
            description="Client for visualization of SCAP rule evaluation results")
134 1
        parser.add_argument(
135
            '--show-fail-rules',
136
            action="store_true",
137
            default=False,
138
            help="Show only FAIL rules")
139 1
        parser.add_argument(
140
            '--show-not-selected-rules',
141
            action="store_true",
142
            default=False,
143
            help="Show notselected rules. These rules will not be visualized.")
144 1
        parser.add_argument(
145
            '--off-web-browser',
146
            action="store_true",
147
            default=False,
148
            help="It does not start the web browser.")
149 1
        parser.add_argument(
150
            '--tree',
151
            action="store_true",
152
            default=False,
153
            help="Render the graph in a form of directory tree")
154 1
        parser.add_argument(
155
            '--remove-pass-tests',
156
            action="store_true",
157
            default=False,
158
            help=(
159
                "Do not display passing tests for better orientation in"
160
                " graphs that contain a large amount of nodes.(Not implemented)"))
161 1
        parser.add_argument("source_filename", help="ARF scan file")
162 1
        parser.add_argument(
163
            "rule_id", help=(
164
                "Rule ID to be visualized. A part from the full rule ID"
165
                " a part of the ID or a regular expression can be used."
166
                " If brackets are used in the regular expression "
167
                "the regular expression must be quoted."))
168 1
        args = parser.parse_args(args)
169
170
        return args
171