Completed
Push — master ( 7c8092...97052d )
by -
01:44
created

explain()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1.125
Metric Value
dl 0
loc 3
ccs 1
cts 2
cp 0.5
rs 10
cc 1
crap 1.125
1 1
try:
2 1
    from urlparse import parse_qs
3
except ImportError:  # python3
4
    from urllib.parse import parse_qs
5 1
import logging
6 1
from time import time
7
8 1
from flask import Blueprint, render_template, request, redirect, flash, Response, url_for
9 1
from sqlalchemy.exc import SQLAlchemyError
0 ignored issues
show
Configuration introduced by
The import sqlalchemy.exc could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
10
11 1
from spike.model import db
12 1
from spike.model.naxsi_whitelist import NaxsiWhitelist
13 1
from spike.model.naxsi_whitelistsets import NaxsiWhitelistSets
14 1
from spike.model.naxsi_rules import NaxsiRules
15 1
from spike.model import naxsi_mz
16
17 1
whitelists = Blueprint('whitelists', __name__)
18
19
20 1
@whitelists.route("/")
21
def index():
22 1
    _wlist = NaxsiWhitelist.query.order_by(NaxsiWhitelist.wid.desc()).all()
0 ignored issues
show
Bug introduced by
The Class NaxsiWhitelist 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...
23 1
    if not _wlist:
24 1
        flash("No whitelist found, please create one", "success")
25 1
        return redirect(url_for('whitelists.new'))
26
    return render_template("whitelists/index.html", whitelists=_wlist)
27
28
29 1
@whitelists.route("/plain/<string:wid>", methods=["GET"])
30
def plain(wid):
31
    _wlist = NaxsiWhitelist.query.filter(NaxsiRules.sid == wid).first()
0 ignored issues
show
Bug introduced by
The Class NaxsiWhitelist 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...
32
    if not _wlist:
33
        flash("no rules found, please create one", "error")
34
        return redirect(url_for('whitelists.index'))
35
    return Response(_wlist.fullstr(), mimetype='text/plain')
36
37
38 1
@whitelists.route("/view/<string:wid>", methods=["GET"])
39
def view(wid):
40
    _wlist = NaxsiWhitelist.query.filter(NaxsiWhitelist.id == wid).first()
0 ignored issues
show
Bug introduced by
The Class NaxsiWhitelist 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...
41
    if _wlist is None:
42
        flash("no rules found, please create one", "error")
43
        return redirect(url_for('whitelists.index'))
44
    return render_template("whitelists/view.html", whitelist=_wlist)
45
46
47 1
@whitelists.route("/edit/<string:wid>", methods=["GET"])
48
def edit(wid):
49
    return redirect(url_for('whitelists.new'))
50
51
52 1
@whitelists.route("/del/<string:wid>", methods=["GET"])
53
def del_sid(wid):
54
    _wlist = NaxsiWhitelist.query.filter(NaxsiWhitelist.sid == wid).first()
0 ignored issues
show
Bug introduced by
The Class NaxsiWhitelist 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...
Bug introduced by
The Class NaxsiWhitelist does not seem to have a member named sid.

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...
55
    if not _wlist:
56
        return redirect(url_for('whitelists.index'))
57 1
58
    db.session.delete(_wlist)
59
60
    try:
61
        db.session.commit()
62 1
        flash("OK: deleted %s : %s" % (wid, _wlist.msg), "success")
63
    except SQLAlchemyError:
64 1
        flash("ERROR while trying to update %s" % wid, "error")
65 1
66 1
    return redirect(url_for('whitelists.index'))
67
68 1
69 1
@whitelists.route("/generate", methods=["GET", "POST"])
70 1
def generate():
71
    if request.method == "GET":
72 1
        return render_template("misc/whitelist_generator.html")
73 1
    nxlogs = request.form.get('nxlogs', '')
74 1
75
    if not nxlogs:
76 1
        flash('Please input nxlogs')
77 1
        return render_template("misc/whitelist_generator.html")
78 1
79 1
    whitelist = list()
80
    for nxlog in nxlogs.split('\n'):
81 1
        if not nxlog:
82 1
            continue
83 1
        start = nxlog.find("ip=")
84 1
        if start < 0:
85
            flash('{} is an invalid extlog, string "ip=" not found.'.format(nxlog))
86
            return render_template("misc/whitelist_generator.html", nxlogs=nxlogs)
87 1
88 1
        end = nxlog.find(", ")
89 1
        if end < 0:
90
            flash('{} is an invalid extlog, string "," not found.'.format(nxlog))
91 1
            return render_template("misc/whitelist_generator.html", nxlogs=nxlogs)
92 1
93 1
        # Flatten the dict, since parse_qs is a bit annoying
94 1
        nxdic = parse_qs(nxlog[start:end])
95 1
        for key, value in nxdic.items():
96 1
            nxdic[key] = value[0]
97 1
98
        cpt = 0
99
        while "id{}".format(cpt) in nxdic:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
100 1
            _id = "id{}".format(cpt)
101 1
            _var_name = "var_name{}".format(cpt)
102
            _zone = "zone{}".format(cpt)
103
            if "var_name{}".format(cpt) in nxdic:
104 1
                whitelist.append('BasicRule wl:{} "mz:{}:{}"'.format(nxdic[_id], nxdic[_var_name], nxdic[_zone]))
105
            else:
106 1
                whitelist.append('BasicRule wl:{} "mz:{}"'.format(nxdic[_id], nxdic[_var_name]))
107 1
            cpt += 1
108 1
    return render_template("misc/whitelist_generator.html", whitelist='\n'.join(whitelist) + ';', nxlogs=nxlogs)
109
110
111
@whitelists.route('/new', methods=["GET", "POST"])
112
def new():
113
    if request.method == "GET":
114
        _whitelistesets = NaxsiWhitelistSets.query.all()
0 ignored issues
show
Bug introduced by
The Class NaxsiWhitelistSets 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...
115
        return render_template('whitelists/new.html', matchzones=naxsi_mz, whitelistsets=_whitelistesets)
116
117
    logging.debug('Posted new request: %s', request.form)
118
    mz = "|".join(filter(len, request.form.getlist("mz") + request.form.getlist("custom_mz_val")))
119
120
    score = request.form.get("score", "")
0 ignored issues
show
Unused Code introduced by
The variable score seems to be unused.
Loading history...
121
    score += ':'
122
    score += request.form.get("score_%s" % request.form.get("score", ""), "")
123
124
    wlist = NaxsiWhitelist(wid=request.form.get("id", ""), timestamp=int(time()),
125
                            whitelistset=request.form.get("whitelistset", ""), mz=mz, active=1,
126
                            negative=request.form.get("negative", "") == 'checked')
127
    wlist.validate()
128
129
    if wlist.error:
130
        flash("ERROR: {0}".format(",".join(wlist.error)))
131
        return redirect(url_for('whitelists.new'))
132
    elif wlist.warnings:
133
        flash("WARNINGS: {0}".format(",".join(wlist.warnings)))
134
135
    db.session.add(wlist)
136
137
    try:
138
        db.session.commit()
139
        flash('Created!')
140
    except SQLAlchemyError as e:
0 ignored issues
show
Coding Style Naming introduced by
The name e does not conform to the variable naming conventions ([a-z_][a-z0-9_]{1,30}$).

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...
141
        flash("Error : %s" % e, "error")
142
143
    return render_template('whitelists/index.html')
144