blob: db1d69a28e5b62a895a8fdefcef2189820dae438 [file] [log] [blame]
Brad Bishop96ff1982019-08-19 13:50:42 -04001SUMMARY = "Updates the NVD CVE database"
2LICENSE = "MIT"
3
4INHIBIT_DEFAULT_DEPS = "1"
5
6inherit native
7
8deltask do_unpack
9deltask do_patch
10deltask do_configure
11deltask do_compile
12deltask do_install
13deltask do_populate_sysroot
14
15python () {
16 if not d.getVar("CVE_CHECK_DB_FILE"):
17 raise bb.parse.SkipRecipe("Skip recipe when cve-check class is not loaded.")
18}
19
20python do_populate_cve_db() {
21 """
22 Update NVD database with json data feed
23 """
Brad Bishop6dbb3162019-11-25 09:41:34 -050024 import bb.utils
Brad Bishop08902b02019-08-20 09:16:51 -040025 import sqlite3, urllib, urllib.parse, shutil, gzip
Brad Bishop96ff1982019-08-19 13:50:42 -040026 from datetime import date
27
Brad Bishop6dbb3162019-11-25 09:41:34 -050028 bb.utils.export_proxies(d)
29
Brad Bishop96ff1982019-08-19 13:50:42 -040030 BASE_URL = "https://nvd.nist.gov/feeds/json/cve/1.0/nvdcve-1.0-"
31 YEAR_START = 2002
32
Brad Bishop6dbb3162019-11-25 09:41:34 -050033 db_file = d.getVar("CVE_CHECK_DB_FILE")
34 db_dir = os.path.dirname(db_file)
Brad Bishop96ff1982019-08-19 13:50:42 -040035 json_tmpfile = os.path.join(db_dir, 'nvd.json.gz')
Brad Bishop08902b02019-08-20 09:16:51 -040036
Brad Bishop1d80a2e2019-11-15 16:35:03 -050037 # Don't refresh the database more than once an hour
38 try:
39 import time
40 if time.time() - os.path.getmtime(db_file) < (60*60):
41 return
42 except OSError:
43 pass
44
Brad Bishop96ff1982019-08-19 13:50:42 -040045 cve_f = open(os.path.join(d.getVar("TMPDIR"), 'cve_check'), 'a')
46
47 if not os.path.isdir(db_dir):
48 os.mkdir(db_dir)
49
50 # Connect to database
51 conn = sqlite3.connect(db_file)
52 c = conn.cursor()
53
54 initialize_db(c)
55
56 for year in range(YEAR_START, date.today().year + 1):
57 year_url = BASE_URL + str(year)
58 meta_url = year_url + ".meta"
59 json_url = year_url + ".json.gz"
60
61 # Retrieve meta last modified date
Brad Bishop6dbb3162019-11-25 09:41:34 -050062 response = urllib.request.urlopen(meta_url)
Brad Bishop08902b02019-08-20 09:16:51 -040063 if response:
64 for l in response.read().decode("utf-8").splitlines():
Brad Bishop96ff1982019-08-19 13:50:42 -040065 key, value = l.split(":", 1)
66 if key == "lastModifiedDate":
67 last_modified = value
68 break
69 else:
70 bb.warn("Cannot parse CVE metadata, update failed")
71 return
72
73 # Compare with current db last modified date
74 c.execute("select DATE from META where YEAR = ?", (year,))
75 meta = c.fetchone()
76 if not meta or meta[0] != last_modified:
77 # Clear products table entries corresponding to current year
78 c.execute("delete from PRODUCTS where ID like ?", ('CVE-%d%%' % year,))
79
80 # Update db with current year json file
81 try:
Brad Bishop6dbb3162019-11-25 09:41:34 -050082 response = urllib.request.urlopen(json_url)
Brad Bishop08902b02019-08-20 09:16:51 -040083 if response:
84 update_db(c, gzip.decompress(response.read()).decode('utf-8'))
Brad Bishop96ff1982019-08-19 13:50:42 -040085 c.execute("insert or replace into META values (?, ?)", [year, last_modified])
86 except urllib.error.URLError as e:
87 cve_f.write('Warning: CVE db update error, CVE data is outdated.\n\n')
88 bb.warn("Cannot parse CVE data (%s), update failed" % e.reason)
89 return
90
91 # Update success, set the date to cve_check file.
92 if year == date.today().year:
93 cve_f.write('CVE database update : %s\n\n' % date.today())
94
95 cve_f.close()
96 conn.commit()
97 conn.close()
98}
99
100def initialize_db(c):
101 c.execute("CREATE TABLE IF NOT EXISTS META (YEAR INTEGER UNIQUE, DATE TEXT)")
Brad Bishop6dbb3162019-11-25 09:41:34 -0500102
Brad Bishop96ff1982019-08-19 13:50:42 -0400103 c.execute("CREATE TABLE IF NOT EXISTS NVD (ID TEXT UNIQUE, SUMMARY TEXT, \
104 SCOREV2 TEXT, SCOREV3 TEXT, MODIFIED INTEGER, VECTOR TEXT)")
Brad Bishop6dbb3162019-11-25 09:41:34 -0500105
Brad Bishop96ff1982019-08-19 13:50:42 -0400106 c.execute("CREATE TABLE IF NOT EXISTS PRODUCTS (ID TEXT, \
107 VENDOR TEXT, PRODUCT TEXT, VERSION_START TEXT, OPERATOR_START TEXT, \
108 VERSION_END TEXT, OPERATOR_END TEXT)")
Brad Bishop6dbb3162019-11-25 09:41:34 -0500109 c.execute("CREATE INDEX IF NOT EXISTS PRODUCT_ID_IDX on PRODUCTS(ID);")
Brad Bishop96ff1982019-08-19 13:50:42 -0400110
111def parse_node_and_insert(c, node, cveId):
112 # Parse children node if needed
113 for child in node.get('children', ()):
114 parse_node_and_insert(c, child, cveId)
115
116 def cpe_generator():
117 for cpe in node.get('cpe_match', ()):
118 if not cpe['vulnerable']:
119 return
120 cpe23 = cpe['cpe23Uri'].split(':')
121 vendor = cpe23[3]
122 product = cpe23[4]
123 version = cpe23[5]
124
125 if version != '*':
126 # Version is defined, this is a '=' match
127 yield [cveId, vendor, product, version, '=', '', '']
128 else:
129 # Parse start version, end version and operators
130 op_start = ''
131 op_end = ''
132 v_start = ''
133 v_end = ''
134
135 if 'versionStartIncluding' in cpe:
136 op_start = '>='
137 v_start = cpe['versionStartIncluding']
138
139 if 'versionStartExcluding' in cpe:
140 op_start = '>'
141 v_start = cpe['versionStartExcluding']
142
143 if 'versionEndIncluding' in cpe:
144 op_end = '<='
145 v_end = cpe['versionEndIncluding']
146
147 if 'versionEndExcluding' in cpe:
148 op_end = '<'
149 v_end = cpe['versionEndExcluding']
150
151 yield [cveId, vendor, product, v_start, op_start, v_end, op_end]
152
153 c.executemany("insert into PRODUCTS values (?, ?, ?, ?, ?, ?, ?)", cpe_generator())
154
155def update_db(c, jsondata):
156 import json
157 root = json.loads(jsondata)
158
159 for elt in root['CVE_Items']:
160 if not elt['impact']:
161 continue
162
163 cveId = elt['cve']['CVE_data_meta']['ID']
164 cveDesc = elt['cve']['description']['description_data'][0]['value']
165 date = elt['lastModifiedDate']
166 accessVector = elt['impact']['baseMetricV2']['cvssV2']['accessVector']
167 cvssv2 = elt['impact']['baseMetricV2']['cvssV2']['baseScore']
168
169 try:
170 cvssv3 = elt['impact']['baseMetricV3']['cvssV3']['baseScore']
171 except:
172 cvssv3 = 0.0
173
174 c.execute("insert or replace into NVD values (?, ?, ?, ?, ?, ?)",
175 [cveId, cveDesc, cvssv2, cvssv3, date, accessVector])
176
177 configurations = elt['configurations']['nodes']
178 for config in configurations:
179 parse_node_and_insert(c, config, cveId)
180
181
182addtask do_populate_cve_db before do_fetch
183do_populate_cve_db[nostamp] = "1"
184
185EXCLUDE_FROM_WORLD = "1"