Commit 0eeb8c22 authored by Alexandre Dulaunoy's avatar Alexandre Dulaunoy
Browse files

Merge remote-tracking branch 'pj/master'

parents 2a8fa770 8e47223f
Loading
Loading
Loading
Loading
+1 −1
Original line number Diff line number Diff line
@@ -311,4 +311,4 @@ cve-search is free software released under the "Modified BSD license"

    Copyright (c) 2012 Wim Remes - https://github.com/wimremes/
    Copyright (c) 2012-2016 Alexandre Dulaunoy - https://github.com/adulau/
    Copyright (c) 2015-2016 Pieter-Jan Moreels - https://github.com/pidgeyl/
    Copyright (c) 2015-2017 Pieter-Jan Moreels - https://github.com/pidgeyl/
+16 −6
Original line number Diff line number Diff line
@@ -8,15 +8,18 @@
# Copyright (c) 2016 	Pieter-Jan Moreels - pieterjan.moreels@gmail.com

# Imports
import sys
import datetime
import importlib
import os
import sys
import uuid

runPath = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(runPath, ".."))

import importlib

import lib.DatabaseLayer as db
from lib.Config    import Configuration as conf
from lib.Singleton import Singleton

# Constants
UNREACHABLE   = -1
@@ -28,10 +31,11 @@ class AuthenticationMethod:
  def validateUser(self, user, pwd):
    return WRONG_CREDS

class AuthenticationHandler:
  def __init__(self):
class AuthenticationHandler(metaclass=Singleton):
  def __init__(self, **kwargs):
    self.methods = []
    self._load_methods()
    self.api_sessions = {}

  def _load_methods(self):
    self.methods = []
@@ -82,3 +86,9 @@ class AuthenticationHandler:
    #  so we check the user against the local database.
    return db.verifyUser(user, password)

  def new_api_session(self, user):
    self.api_sessions[user] = (uuid.uuid4().hex, datetime.datetime.now())
    return self.api_sessions[user][0]

  def get_api_session(self, user, extend=True):
    return self.api_sessions.get(user)
+28 −11
Original line number Diff line number Diff line
@@ -14,6 +14,7 @@ import ast
import sqlite3
import pymongo
import re
import uuid

from passlib.hash import pbkdf2_sha256

@@ -198,6 +199,7 @@ def getSearchResults(search):
      # Check if already in result data
      if not any(item['id']==entry['id'] for entry in result['data']):
        entry=getCVE(item['id'])
        if entry:
          entry['reason']=collection['n']
          result['data'].append(entry)
  return result
@@ -225,15 +227,19 @@ def via4Linked(key, val):
  cveList=[x['id'] for x in colVIA4.find({key: val})]
  return sanitize(getCVEs(query={'id':{'$in':cveList}}))

def getDBStats():
  cols=['cve', 'cpe', 'cpeOther', 'capec', 'd2sec', 'vendor']
  stats={x+'A': getSize(x.lower()) for x in cols}
  stats['cveA']=getSize('cves')
  stats.update({x+'U': getLastModified(x.lower()) for x in cols})
  stats.update({'blA': colBLACKLIST.count(), 'wlA':colWHITELIST.count()})
  stats.update({'dbOnDisk': db.command("dbstats")['storageSize'], 'dbSize':db.command('dbstats')['dataSize']})
  stats['dbName']=conf.getMongoDB()
  return stats
def getDBStats(include_admin=False):
  data={'cves': {}, 'cpe': {}, 'cpeOther': {}, 'capec': {}, 'cwe': {}, 'via4': {}}
  for key in data.keys():
    data[key] = {'size': getSize(key.lower()),
                 'last_update': getLastModified(key.lower())}
  if include_admin:
    data['whitelist']={'size': colWHITELIST.count()}
    data['blacklist']={'size': colBLACKLIST.count()}
    data = {'stats': {'size_on_disk': db.command("dbstats")['storageSize'],
                      'db_size':      db.command('dbstats')['dataSize'],
                      'name':         conf.getMongoDB()},
            'data':  data}
  return data

# Dynamic data
def getWhitelist():
@@ -320,6 +326,17 @@ def getUsers():
def getUser(user):
  return sanitize(colUSERS.find_one({"username": user}))

def getToken(user):
  data = sanitize(colUSERS.find_one({"username": user}))
  if not data:              return None
  if 'token' in data.keys():return data['token']
  else:                     return generateToken(user)

def generateToken(user):
  token = uuid.uuid4().hex
  colUSERS.update({'username': user}, {'$set': {'token': token}})
  return token

###########
# Plugins #
###########
+5 −4
Original line number Diff line number Diff line
@@ -18,15 +18,16 @@ import importlib
import lib.DatabaseLayer as db
from lib.Config    import Configuration as conf
from lib.Config    import ConfigReader
from lib.Singleton import Singleton

class PluginManager():
class PluginManager(metaclass=Singleton):
  def __init__(self):
    self.plugins = {}

  def loadPlugins(self):
    settingsReader = ConfigReader(conf.getPluginsettings())
    if not os.path.exists(conf.getPluginLoadSettings()):
        print("[!] Could not find plugin loader file!")
        print("[-] No plugin loader file!")
        return
    # Read and parse plugin file
    data = open(conf.getPluginLoadSettings(), "r").read()

lib/Singleton.py

0 → 100644
+6 −0
Original line number Diff line number Diff line
class Singleton(type):
  _instances = {}
  def __call__(cls, *args, **kwargs):
    if cls not in cls._instances:
      cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
    return cls._instances[cls]
Loading