Passed
Branch master (e83018)
by Jan
03:07
created

graph.client.client.prepare_graphs()   A

Complexity

Conditions 4

Size

Total Lines 14
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 14
nop 2
dl 0
loc 14
ccs 10
cts 10
cp 1
crap 4
rs 9.7
c 0
b 0
f 0
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.source_filename = self.arg.source_filename
14 1
        self.rule_name = self.arg.rule_id
15 1
        self.xml_parser = graph.xml_parser.xml_parser(self.source_filename)
16
17 1
    def run_gui_and_return_answers(self):
18
        try:
19
            from PyInquirer import style_from_dict, Token, prompt, Separator
20
            return prompt(self.get_questions(Separator('= The Rule IDs =')))
21
        except ImportError:
22
            print('== The Rule IDs ==')
23
            for rule in self.search_rules_id():
24
                print(rule['id_rule'] + r'\b')
25
            return None
26
27 1
    def get_questions(self, separator):
28 1
        rules = self.search_rules_id()
29 1
        questions = [{
30
            'type': 'checkbox',
31
            'message': 'Select rule(s)',
32
            'name': 'rules',
33
            'choices': [separator]
34
        }]
35 1
        for rule in rules:
36 1
            questions[0]['choices'].append(dict(name=rule['id_rule']))
37 1
        return questions
38
39 1
    def _get_wanted_rules(self):
40 1
        return [
41
            x for x in self.xml_parser.get_used_rules() if re.search(
42
                self.rule_name, x['id_rule'])]
43
44 1
    def _get_wanted_not_selected_rules(self):
45 1
        return [
46
            x for x in self.xml_parser.get_notselected_rules() if re.search(
47
                self.rule_name, x['id_rule'])]
48
49 1
    def search_rules_id(self):
50 1
        rules = self._get_wanted_rules()
51 1
        notselected_rules = self._get_wanted_not_selected_rules()
52 1
        if len(notselected_rules) and not rules:
53 1
            raise ValueError(
54
                ('err- rule(s) "{}" was not selected, '
55
                 'so there are no results. The rule is'
56
                 ' "notselected" because it'
57
                 " wasn't a part of the executed profile"
58
                 " and therefore it wasn't evaluated "
59
                 "during the scan.")
60
                .format(notselected_rules[0]['id_rule']))
61 1
        elif not notselected_rules and not rules:
62 1
            raise ValueError('err- 404 rule not found!')
63
        else:
64 1
            return rules
65
66 1
    def prepare_graphs(self, rules):
67 1
        try:
68 1
            for rule in rules['rules']:
69 1
                oval_tree = graph.oval_graph.build_nodes_form_xml(
70
                    self.source_filename, rule).to_sigma_dict(0, 0)
71 1
                with open('html_interpreter/data.js', "w+") as graph_data_file:
72 1
                    graph_data_file.write("var data_json =" + str(json.dumps(
73
                        oval_tree,
74
                        sort_keys=False,
75
                        indent=4) + ";"))
76 1
                self.open_web_browser()
77 1
                print('Rule "{}" done!'.format(rule))
78 1
        except Exception as error:
79 1
            raise ValueError('Rule: "{}" Error: "{}"'.format(rule, error))
80
81 1
    def open_web_browser(self):
82 1
        try:
83 1
            webbrowser.get('firefox').open_new_tab(
84
                'html_interpreter/index.html')
85
        except BaseException:
86
            webbrowser.open_new_tab('html_interpreter/index.html')
87
88 1
    def parse_arguments(self, args):
89 1
        parser = argparse.ArgumentParser(
90
            description='Client for visualization of SCAP rule evaluation results')
91
92 1
        parser.add_argument("source_filename", help='ARF scan file')
93 1
        parser.add_argument(
94
            "rule_id", help=(
95
                'Rule ID to be visualized. A part from the full rule ID'
96
                ' a part of the ID or a regular expression can be used.'
97
                ' If brackets are used in the regular expression '
98
                'the regular expression must be quoted.'))
99 1
        args = parser.parse_args(args)
100
101
        return args
102