Esempio n. 1
0
    def setUp(self):
        self.db = DatabaseLayer(_db="cvedb_test")
        self.capec1 = CAPEC(id="10000",
                            name="test_capec",
                            summary="no summary",
                            prerequisites="No prerequisites",
                            solutions="There's no solution",
                            weaknesses=["10000"])
        self.cwe1 = CWE(id="10000",
                        name="test_cwe",
                        description="test cwe",
                        status="testing",
                        weakness='Testing')
        self.cpe1 = CPE(id="cpe:/a:test:test1",
                        title="Test CPE 1",
                        references=[])
        self.cpe2 = CPE(id="cpe:2.3:a:test:test2",
                        title="Test CPE 2",
                        references=[])
        self.cve1 = CVE(id="CVE-0001-0001",
                        cvss=0.1,
                        summary="Test Vulnerability",
                        vulnerable_configuration=[self.cpe1, self.cpe2],
                        published=datetime.datetime(2017, 1, 1),
                        impact=Impact("None", "None", "None"),
                        access=Access("Low", "None", "Local"),
                        cwe=self.cwe1)

        self.db.CAPEC.upsert(self.capec1)
        self.db.CWE.upsert(self.cwe1)
        self.db.CPE.upsert([self.cpe1, self.cpe2])
        self.db.CVE.upsert(self.cve1)
Esempio n. 2
0
def listranking(format='json'):
    ranks = []
    for x in DatabaseLayer().Ranking.get():
        if format == "json":
            ranks.append(x)
        else:
            ranks.append(x['cpe'] + " " + str(x['rank']))
    return ranks
Esempio n. 3
0
def index(limit=5, cpe_lookup=False, verbose=False):
    if limit == 0: limit = -1
    data = DatabaseLayer().CVE.last(limit=limit)
    for cve in progressbar(data, prefix="Processing"):
        writer = get_schema_writer()
        title = cve.summary[:70]
        data = cve.summary
        if cpe_lookup:
            for cpe in cve.vulnerable_configuration:
                data += " " + cpe.title
        if verbose:
            print('Indexing CVE-ID ' + str(cve.id) + ' ' + title)
        writer.update_document(title=title, path=cve.id, content=data)
        writer.commit()
Esempio n. 4
0
 def authErrors():
     db = DatabaseLayer(
     )  # Required to circumvent the use of self, because of this being a wrapper (This is one reason to use a singleton ;) )
     # Check auth
     if not request.headers.get('Authorization'):
         return ({
             'status': 'error',
             'reason': 'Authentication needed'
         }, 401)
     method, name, token = Advanced_API.getAuth()
     data = None
     if method.lower() not in ['basic', 'token', 'session']:
         data = ({
             'status': 'error',
             'reason': 'Authorization method not allowed'
         }, 400)
     else:
         try:
             authenticated = False
             if method.lower() == 'basic':
                 authenticator = AuthenticationHandler()
                 if authenticator.validateUser(name, token):
                     authenticated = True
             elif method.lower() == 'token':
                 if db.Users.getToken(name) == token: authenticated = True
             elif method.lower() == 'session':
                 authenticator = AuthenticationHandler()
                 if authenticator.api_sessions.get(name) == token:
                     authenticated = True
             if not authenticated:
                 data = ({
                     'status': 'error',
                     'reason': 'Authentication failed'
                 }, 401)
         except Exception as e:
             print(e)
             data = ({
                 'status': 'error',
                 'reason': 'Malformed Authentication String'
             }, 400)
     if data:
         return data
     else:
         return None
Esempio n. 5
0
 def setUp(self):
     self.db = DatabaseLayer(_db="cvedb_test")
     self.capec1 = CAPEC(id="10000",
                         name="test_capec",
                         summary="no summary",
                         prerequisites="No prerequisites",
                         solutions="There's no solution",
                         weaknesses=[])
     self.cwe1 = CWE(id="10000",
                     name="test_cwe",
                     description="test cwe",
                     status="testing",
                     weakness='Testing')
     self.cpe1 = CPE(id="cpe:/a:test:test1",
                     title="Test CPE 1",
                     references=[])
     self.cpe2 = CPE(id="cpe:2.3:a:test:test2",
                     title="Test CPE 2",
                     references=[])
Esempio n. 6
0
    _ap.add_argument('-a',
                     default=False,
                     action='store_true',
                     help='Lookup CAPEC for related CWE weaknesses')
    _ap.add_argument('-v',
                     type=str,
                     help='vendor name to lookup in reference URLs')
    _ap.add_argument(
        '--api',
        type=str,
        help=
        'When used, the script will query the specified API rather than the local instance'
    )
    args = _ap.parse_args()

    db = DatabaseLayer()
    query = Query(api=args.api)
    items = []
    kwargs = {
        'namelookup': args.n,
        'ranking': args.r,
        'capec': args.a,
        'product': args.p,  # only used by html, otherwise ignored
        'cveids': args.c
    }  # only used by html, otherwise ignored

    # Fetch cves
    if args.p:
        items.extend(query.cveforcpe(args.p))
    if args.f:
        items.extend(query.search(args.f))
Esempio n. 7
0
)
argParser.add_argument('-c',
                       default=False,
                       action='store_true',
                       help='Display CAPEC values')

args = argParser.parse_args()

if args.l:
    last = args.l
else:
    last = 10

ref = "http://adulau.github.com/cve-search/"

cves = DatabaseLayer().CVE.last(limit=last, ranking=args.r)

if not (args.f == "html"):
    from feedformatter import Feed
    feed = Feed()

    feed.feed['title'] = "cve-search Last " + str(
        last) + " CVE entries generated on " + str(datetime.datetime.now())
    feed.feed['link'] = "http://adulau.github.com/cve-search/"
    feed.feed['author'] = "Generated with cve-search available at " + ref
    feed.feed['description'] = ""
else:
    print("<html><head>")
    print(
        "<style>.cve table { border-collapse: collapse; text-align: left; width: 100%; } .cve {font: normal 12px/150% Geneva, Arial, Helvetica, sans-serif; background: #fff; overflow: hidden; border: 1px solid #006699; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; }.cve table td, .cve table th { padding: 3px 10px; }.cve table tbody td { color: #00496B; border-left: 1px solid #E1EEF4;font-size: 12px;font-weight: normal; }.cve table tbody .alt td { background: #E1EEF4; color: #00496B; }.cve table tbody td:first-child { border-left: none; }.cve table tbody tr:last-child td { border-bottom: none; }.cve table tfoot td div { border-top: 1px solid #006699;background: #E1EEF4;} .cve table tfoot td { padding: 0; font-size: 12px } .cve table tfoot td div{ padding: 0px; }</style>"
    )
Esempio n. 8
0
 def __init__(self):
     self.plugins = {}
     self.db = DatabaseLayer()
Esempio n. 9
0
 def __init__(self):
     self.db = DatabaseLayer()
Esempio n. 10
0
runPath = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(runPath, ".."))

from redis import exceptions as redisExceptions

from lib.Config        import Configuration
from lib.DatabaseLayer import DatabaseLayer
from lib.Toolkit       import pad

argParser = argparse.ArgumentParser(description='CPE entries importer in Redis cache')
argParser.add_argument('-v', action='store_true', default=False, help='Verbose logging')
argParser.add_argument('-o', action='store_true', default=False, help='Import cpeother database in Redis cache')
args = argParser.parse_args()

if args.o:
    cpe = DatabaseLayer().CPE.getAllAlternative()
else:
    cpe = DatabaseLayer().CPE.getAll()

try:
    r = Configuration.getRedisVendorConnection()
except:
    sys.exit(1)

for e in cpe:
    try:
        if not args.o:
            if e.id.count(':') > 4:
                value = ":".join(e.id.split(':')[:6])
            (prefix, cpeversion, cpetype, vendor, product, version) = pad(value.split(':'),6)
        else:
Esempio n. 11
0
        print(json.dumps(output, sort_keys=True, indent=4))
    elif output_format == "compact":
        print("\n".join([i.id for i in data]))
    elif output_format == "expanded":
        print("\n".join(["%s  %s" % (i.id, i.title) for i in data]))


if __name__ == "__main__":
    argParser = argparse.ArgumentParser(
        description='Search for CPE with a pattern')
    argParser.add_argument('-s',
                           type=str,
                           required=True,
                           help='search in cpe list')
    argParser.add_argument(
        '-o',
        type=str,
        default='expanded',
        help='O = output format [expanded, compact, json] (default: expanded)')
    argParser.add_argument(
        '-f',
        action='store_true',
        help=
        'Enlarge the CPE search to all CPE indexed. Need the cpeother activated.',
        default=False)

    args = argParser.parse_args()
    data = DatabaseLayer().CPE.get_regex(urllib.parse.quote(args.s), args.f)

    output(data, args.o)
Esempio n. 12
0
def dump(limit, ranking=False, via4=False, capec=False):
    db = DatabaseLayer()
    for cve in db.CVE.last(limit=limit, via4=via4, ranking=ranking):
        item = cve.dict(capec, human_dates=True)
        print(json.dumps(item, sort_keys=True))
Esempio n. 13
0
def searchcve(cpe=None):
    if cpe is None:
        return False
    cve = DatabaseLayer().CVE.forCPE(cpe)
    return cve
Esempio n. 14
0
argParser.add_argument('-c',
                       type=str,
                       help='CPE name to add (e.g. google:chrome)')
argParser.add_argument('-g',
                       type=str,
                       help='Name of the organization (e.g. mycompany)')
argParser.add_argument('-r',
                       type=int,
                       default=1,
                       help='Ranking value (integer) default value is 1')
argParser.add_argument('-f',
                       type=str,
                       help='Find ranking based on a CPE name regexp')
argParser.add_argument('-l', action='store_true', help='List all ranking')
argParser.add_argument('-d',
                       type=str,
                       default=None,
                       help='Remove ranking based on a CPE name regexp')
args = argParser.parse_args()

if args.c is not None and args.g is not None:
    DatabaseLayer().Ranking.add(cpe=args.c, key=args.g, rank=args.r)
elif args.f is not None:
    print(DatabaseLayer().CPE.ranking(cpe=args.f))
elif args.l:
    print(listranking())
elif args.d:
    DatabaseLayer().Ranking.remove(cpe=args.d)
else:
    argParser.print_help()
Esempio n. 15
0
 def __init__(self, **kwargs):
     self.methods = []
     self._load_methods()
     self.api_sessions = {}
     self.db = DatabaseLayer()