Ejemplo n.º 1
0
class Index(Minimal, Advanced_API):
    #############
    # Variables #
    #############

    def __init__(self):
        Advanced_API.__init__(self)
        Minimal.__init__(self)
        self.minimal = False
        self.auth_handler = AuthenticationHandler()
        self.plugManager = PluginManager()
        self.login_manager = LoginManager()
        self.plugManager.loadPlugins()
        self.login_manager.init_app(self.app)
        self.login_manager.user_loader(self.load_user)
        self.redisdb = Configuration.getRedisVendorConnection()

        self.args.update({'minimal': False})
        self.pluginArgs = {
            "current_user": current_user,
            "plugin_manager": self.plugManager
        }

    #############
    # Functions #
    #############
    def generate_full_query(self, f):
        query = self.generate_minimal_query(f)
        query.extend(self.plugManager.doFilter(f, **self.pluginArgs))
        return query

    def filter_logic(self, filters, skip, limit=None):
        query = self.generate_full_query(filters)
        limit = limit if limit else self.args['pageLength']
        cve = self.db.CVE.query(limit=limit, skip=skip, query=query)
        cve = [CVEPresentation(c) for c in cve]
        # marking relevant records
        self.plugManager.mark(cve, **self.pluginArgs)
        cve = list(cve)
        return cve

    def filterUpdateField(self, data):
        if not data: return data
        returnvalue = []
        for line in data.split("\n"):
            if (not line.startswith("[+]Success to create index")
                    and not line == "Not modified"
                    and not line.startswith("Starting")):
                returnvalue.append(line)
        return "\n".join(returnvalue)

    def adminInfo(self, output=None):
        return {
            'stats': self.db.db_info(True),
            'plugins': self.plugManager.getPlugins(),
            'updateOutput': self.filterUpdateField(output),
            'token': self.db.Users.getToken(current_user.id)
        }

    # user management
    def load_user(self, id):
        return User.get(id, self.auth_handler)

    ##########
    # ROUTES #
    ##########
    def index(self):
        cve = self.filter_logic(self.defaultFilters, 0)
        filters = self.plugManager.getFilters(**self.pluginArgs)
        return render_template('index.html',
                               cve=cve,
                               r=0,
                               filters=filters,
                               **self.args)

    # /
    def index_post(self):
        args = dict(self.getFilterSettingsFromPost(0), **self.args)
        filters = self.plugManager.getFilters(**self.pluginArgs)
        return render_template('index.html', r=0, filters=filters, **args)

    # /r/<r>
    def index_filter_get(self, r):
        if not r or r < 0: r = 0
        cve = self.filter_logic(self.defaultFilters, r)
        filters = self.plugManager.getFilters(**self.pluginArgs)
        return render_template('index.html',
                               cve=cve,
                               r=r,
                               filters=filters,
                               **self.args)

    # /r/<r>
    def index_filter_post(self, r):
        if not r or r < 0: r = 0
        args = dict(self.getFilterSettingsFromPost(r), **self.args)
        filters = self.plugManager.getFilters(**self.pluginArgs)
        return render_template('index.html', r=r, filters=filters, **args)

    # /cve/<cveid>
    def cve(self, cveid):
        cve = self.api_cve(cveid)
        if cve is None:
            return render_template('error.html',
                                   status={
                                       'except': 'cve-not-found',
                                       'info': {
                                           'cve': cveid
                                       }
                                   })

        self.plugManager.markCPE(cve)
        self.plugManager.onCVEOpen(cveid, **self.pluginArgs)
        pluginData = self.plugManager.cvePluginInfo(cveid, **self.pluginArgs)
        return render_template('cve.html', cve=cve, plugins=pluginData)

    # /_get_plugins
    def _get_plugins(self):
        if not current_user.is_authenticated(
        ):  # Don't show plugins requiring auth if not authenticated
            plugins = [{
                "name": x.getName(),
                "link": x.getUID()
            } for x in self.plugManager.getWebPluginsWithPage(
                **self.pluginArgs) if not x.requiresAuth]
        else:
            plugins = [{
                "name": x.getName(),
                "link": x.getUID()
            } for x in self.plugManager.getWebPluginsWithPage(
                **self.pluginArgs)]
        return jsonify({"plugins": plugins})

    # /plugin/_get_cve_actions
    def _get_cve_actions(self):
        cve = request.args.get('cve', type=str)
        if not current_user.is_authenticated(
        ):  # Don't show actions requiring auth if not authenticated
            actions = [
                x for x in self.plugManager.getCVEActions(
                    cve, **self.pluginArgs) if not x['auth']
            ]
        else:
            actions = self.plugManager.getCVEActions(cve, **self.pluginArgs)
        return jsonify({"actions": actions})

    # /plugin/<plugin>
    def openPlugin(self, plugin):
        if self.plugManager.requiresAuth(
                plugin) and not current_user.is_authenticated():
            return render_template("requiresAuth.html")
        else:
            data = self.plugManager.openPage(plugin, **self.pluginArgs)
            if data:
                page, data, mimetype = data
                if page:
                    try:
                        return render_template(page, **data)
                    except jinja2.exceptions.TemplateSyntaxError:
                        return render_template(
                            "error.html",
                            status={'except': 'plugin-page-corrupt'})
                    except jinja2.exceptions.TemplateNotFound:
                        return render_template("error.html",
                                               status={
                                                   'except':
                                                   'plugin-page-not-found',
                                                   'page': page
                                               })
                elif data:
                    return Response(data, mimetype=mimetype)
            abort(404)

    # /plugin/<plugin>/subpage/<page>
    def openPluginSubpage(self, plugin, page):
        if self.plugManager.requiresAuth(
                plugin) and not current_user.is_authenticated():
            return render_template("requiresAuth.html")
        else:
            data = self.plugManager.openSubpage(plugin, page,
                                                **self.pluginArgs)
            if data:
                page, data, mimetype = data
                if page:
                    try:
                        return render_template(page, **data)
                    except jinja2.exceptions.TemplateSyntaxError:
                        return render_template(
                            "error.html",
                            status={'except': 'plugin-page-corrupt'})
                    except jinja2.exceptions.TemplateNotFound:
                        return render_template("error.html",
                                               status={
                                                   'except':
                                                   'plugin-page-not-found',
                                                   'page': page
                                               })
                elif data:
                    return Response(data, mimetype=mimetype)
            abort(404)

    # /plugin/<plugin>/_cve_action/<action>
    def _jsonCVEAction(self, plugin, action):
        cve = request.args.get('cve', type=str)
        response = self.plugManager.onCVEAction(cve,
                                                plugin,
                                                action,
                                                fields=dict(request.args),
                                                **self.pluginArgs)
        if type(response) is bool and response is True:
            return jsonify({'status': 'plugin_action_complete'})
        elif type(response) is bool and response is False or response is None:
            return jsonify({'status': 'plugin_action_failed'})
        elif type(response) is dict:
            return jsonify(response)
        else:
            return jsonify({'status': 'no_plugin_output'})

    # /admin
    # /admin/
    def admin(self):
        if Configuration.loginRequired():
            if not current_user.is_authenticated():
                return render_template('login.html')
        else:
            person = User.get("_dummy_", self.auth_handler)
            login_user(person)
        output = None
        if os.path.isfile(Configuration.getUpdateLogFile()):
            with open(Configuration.getUpdateLogFile()) as updateFile:
                separator = "==========================\n"
                output = updateFile.read().split(separator)[-2:]
                output = separator + separator.join(output)
        return render_template('admin.html',
                               status="default",
                               **self.adminInfo(output))

    # /admin/change_pass
    @login_required
    def change_pass(self):
        current_pass = request.args.get('current_pass')
        new_pass = request.args.get('new_pass')
        if current_user.authenticate(current_pass):
            if new_pass:
                self.db.Users.changePassword(current_user.id, new_pass)
                return jsonify({"status": "password_changed"})
            return jsonify({"status": "no_password"})
        else:
            return jsonify({"status": "wrong_user_pass"})

    # /admin/request_token
    @login_required
    def request_token(self):
        return jsonify({"token": self.db.Users.generateToken(current_user.id)})

    # /admin/updatedb
    @login_required
    def updatedb(self):
        process = subprocess.Popen([
            sys.executable,
            os.path.join(_runPath, "../sbin/db_updater.py"), "-civ"
        ],
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        out, err = process.communicate()
        output = "%s\n\nErrors:\n%s" % (str(out, 'utf-8'), str(
            err, 'utf-8')) if err else str(out, 'utf-8')
        return jsonify({"updateOutput": output, "status": "db_updated"})

    # /login
    def login_check(self):
        # validate username and password
        username = request.form.get('username')
        password = request.form.get('password')
        person = User.get(username, self.auth_handler)
        try:
            if person and person.authenticate(password):
                login_user(person)
                return render_template('admin.html',
                                       status="logged_in",
                                       **self.adminInfo())
            else:
                return render_template('login.html', status="wrong_user_pass")
        except Exception as e:
            print(e)
            return render_template('login.html', status="outdated_database")

    # /logout
    @login_required
    def logout(self):
        logout_user()
        return redirect("/")