Completed
Push — master ( 638968...b26d9e )
by -
01:31
created

explain_nxlog()   D

Complexity

Conditions 8

Size

Total Lines 49

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 8
dl 0
loc 49
rs 4.7619
1
try:
2
    from urlparse import urlparse, parse_qs
0 ignored issues
show
Unused Code introduced by
Unused urlparse imported from urlparse
Loading history...
3
except ImportError:  # python3
4
    from urllib.parse import urlparse, parse_qs
5
6
from flask import Blueprint, render_template, request, redirect, flash
7
8
from spike.model.naxsi_rules import NaxsiRules
9
10
sandbox = Blueprint('sandbox', __name__)
11
12
13
@sandbox.route("/", methods=["GET"])
14
def index():
15
    return render_template("misc/sandbox.html")
16
17
18
@sandbox.route("/rule", methods=["GET", "POST"])
19
def rule():
20
    if request.method == 'GET' or not request.form.get("rule", ''):
21
        return render_template("misc/sandbox.html")
22
23
    _textual_rule = request.form["rule"]
24
    _rule = NaxsiRules()
25
    _rule.parse_rule(_textual_rule)
26
27
    if 'visualise_rule' in request.form:
28
        if _rule.detection.startswith('rx:'):
29
            return redirect('https://regexper.com/#' + _rule.detection[3:])
30
    elif 'explain_rule' in request.form:
31
        return render_template("misc/sandbox.html", rule_explaination=_rule.explain(), rule=_rule)
32
33
    if _rule.error:
34
        flash("ERROR: {0}".format(",".join(_rule.error)))
35
    if _rule.warnings:
36
        flash("WARNINGS: {0}".format(",".join(_rule.warnings)), 'warning')
37
    return render_template("misc/sandbox.html")
38
39
40
@sandbox.route("/explain_rule/", methods=["GET", "POST"])
41
def explain_rule():
42
    rule = request.args.get('rule', '')
0 ignored issues
show
Comprehensibility Bug introduced by
rule is re-defining a name which is already available in the outer-scope (previously defined on line 19).

It is generally a bad practice to shadow variables from the outer-scope. In most cases, this is done unintentionally and might lead to unexpected behavior:

param = 5

class Foo:
    def __init__(self, param):   # "param" would be flagged here
        self.param = param
Loading history...
43
    if not rule:
44
        return redirect("/rules/")
45
    elif rule.isdigit():  # explain a rule by id
46
        _rule = NaxsiRules.query.filter(NaxsiRules.sid == rule).first()
0 ignored issues
show
Bug introduced by
The Class NaxsiRules does not seem to have a member named query.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
47
        if _rule is None:
48
            flash('Not rule with id %s' % rule)
49
            return redirect("/sandbox/")
50
    else:
51
        _textual_rule = request.form["rule"]
52
        _rule = NaxsiRules()
53
        _rule.parse_rule(_textual_rule)
54
55
    return render_template("misc/sandbox.html", rule_explaination=_rule.explain(), rule=_rule)
56
57
58
@sandbox.route('/explain_nxlog/', methods=["POST"])
59
def explain_nxlog():
60
    nxlog = request.form.get("nxlog", '')
61
    if not nxlog:
62
        return redirect("/sandbox/")
63
64
    start = nxlog.find("ip=")
65
    if start < 0:
66
        flash('{} is an invalid extlog, string "ip=" not found.'.format(nxlog))
67
        return redirect("/sandbox/")
68
69
    end = nxlog.find(", ")
70
    if end < 0:
71
        flash('{} is an invalid extlog, string "," not found.'.format(nxlog))
72
        return redirect("/sandbox/")
73
74
    # Flatten the dict, since parse_qs is a bit annoying
75
    nxdic = parse_qs(nxlog[start:end])
76
    for key, value in nxdic.items():
77
        nxdic[key] = value[0]
78
79
    explain = "Peer <strong>{}</strong> performed a request to <strong>{}</strong> on URI <strong>{}</strong> ".format(
80
        nxdic['ip'], nxdic['server'], nxdic['uri'])
81
82
    scores = list()
83
    cpt = 0
84
    while "cscore{}".format(cpt) in nxdic:
85
        cscore = "cscore{}".format(cpt)
86
        score = "score{}".format(cpt)
87
        scores.append("that reached a <strong>{}</strong> score of <strong>{}</strong> ".format(
88
            nxdic[cscore], nxdic[score]))
89
        cpt += 1
90
    explain += ' and '.join(scores)
91
92
    cpt = 0
93
    named = list()
94
    while "id{}".format(cpt) in nxdic:
95
        _id = "id{}".format(cpt)
96
        _var_name = "var_name{}".format(cpt)
97
        _zone = "zone{}".format(cpt)
98
        if "var_name{}".format(cpt) in nxdic:
99
            named.append("id <strong>{}</strong> in var named <strong>{}</strong> of zone <strong>{}</strong>".format(
100
                nxdic[_id], nxdic[_var_name], nxdic[_zone]))
101
        else:
102
            named.append("id <strong>{}</strong> in zone <strong>{}</strong>".format(nxdic[_id], nxdic[_zone]))
103
        cpt += 1
104
    explain += ' and '.join(named)
105
106
    return render_template("misc/sandbox.html", nxlog_explaination=explain, nxlog=nxlog)
107