#!/usr/bin/python3

###############################################################################
##
## Functions for downloading and parsing Common Vulnerability DB data
##
###############################################################################

import logging, sys
import re
import urllib.request
import datetime

logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)

## Get details of given CVE entry from NIST DB
def fetchCVE(cve_id, cve_base_url, cvss_base_url):
    url = ''

    logging.info('Fetching CVE: ' + cve_id + '\n')

    #Make this subtitution for some reason
    cve_id = re.sub('^CAN','CVE',cve_id)

    ##
    ## get CVE Scores from NVD
    ##

    url = cvss_base_url + cve_id
    try:
        req = urllib.request.urlopen(url)
        charset = req.info().get_content_charset()
        if charset is None:
            charset = 'utf-8'
        cvss = req.read().decode(charset)
    except urllib.error.HTTPError as err:
        print('Failed to download CVE: ' + url + '\n')
        cvss = ''

    # Check for error pages: referenced but unpublished CVEs :-/
    if re.compile('.*is valid CVE format, but CVE was not found.*').match(cvss):
        print(cve_id + ' does not exist in NIST DB\n')

	##
	## get CVE from MITRE
	##
        
    logging.info('Fetching CVE: ' + cve_id + ' from MITRE\n')

    url = cve_base_url + cve_id
    try:
        req = urllib.request.urlopen(url)
        charset = req.info().get_content_charset()
        if charset is None:
            charset = 'utf-8'
        cve = req.read().decode(charset)
    except urllib.error.HTTPError as err:
        print('Failed to download CVE: ' + url + ' from MITRE\n')
        cve = ''
        return cve

    # Check for error pages: referenced but unpublished CVEs :-/
    if re.compile('.*Could not find a CVE entry or candidate named.*').match(cve):
        print(cve_id + 'does not exist in MITRE DB\n')
        return ''

    s = ''
    ret = s.join((cvss,cve))
    return ret
###############################################################################

## Get CVE severity rating and report date, and return
## (date base-score impact-score exploit-score)
def parseCVE(cve_id, cve):
    #use worst case info as defaults
    cve_date = datetime.datetime.now()
    print(cve_date)
    cve_base = 10
    cve_impact = 10
    cve_exploit = 10

    if cve == '':
        # No details means we assume worst-case (highest score, recent bug)
        if re.compile('LOCAL-(.*)').match(cve_id):
            




#test1 = fetchCVE('CVE-2015-2750', 'http://cve.mitre.org/cgi-bin/cvename.cgi?name=', 'http://web.nvd.nist.gov/view/vuln/detail?vulnId=')
#print(test1)
parseCVE('a','b')
