blob: e042e67b09af733d7ebd68b49814d95427668bd0 [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
Andrew Geissler95ac1b82021-03-31 14:34:31 -050015NVDCVE_URL ?= "https://nvd.nist.gov/feeds/json/cve/1.1/nvdcve-1.1-"
Andrew Geisslerd5838332022-05-27 11:33:10 -050016# CVE database update interval, in seconds. By default: once a day (24*60*60).
17# Use 0 to force the update
Andrew Geissler78b72792022-06-14 06:47:25 -050018# Use a negative value to skip the update
Andrew Geisslerd5838332022-05-27 11:33:10 -050019CVE_DB_UPDATE_INTERVAL ?= "86400"
Andrew Geissler95ac1b82021-03-31 14:34:31 -050020
Patrick Williams2390b1b2022-11-03 13:47:49 -050021# Timeout for blocking socket operations, such as the connection attempt.
22CVE_SOCKET_TIMEOUT ?= "60"
23
Andrew Geissler517393d2023-01-13 08:55:19 -060024CVE_DB_TEMP_FILE ?= "${CVE_CHECK_DB_DIR}/temp_nvdcve_1.1.db"
25
Brad Bishop96ff1982019-08-19 13:50:42 -040026python () {
Andrew Geisslerc9f78652020-09-18 14:11:35 -050027 if not bb.data.inherits_class("cve-check", d):
Brad Bishop96ff1982019-08-19 13:50:42 -040028 raise bb.parse.SkipRecipe("Skip recipe when cve-check class is not loaded.")
29}
30
Andrew Geisslerc9f78652020-09-18 14:11:35 -050031python do_fetch() {
Brad Bishop96ff1982019-08-19 13:50:42 -040032 """
33 Update NVD database with json data feed
34 """
Brad Bishop6dbb3162019-11-25 09:41:34 -050035 import bb.utils
Andrew Geisslerc9f78652020-09-18 14:11:35 -050036 import bb.progress
Andrew Geissler517393d2023-01-13 08:55:19 -060037 import shutil
Brad Bishop96ff1982019-08-19 13:50:42 -040038
Brad Bishop6dbb3162019-11-25 09:41:34 -050039 bb.utils.export_proxies(d)
40
Brad Bishop6dbb3162019-11-25 09:41:34 -050041 db_file = d.getVar("CVE_CHECK_DB_FILE")
42 db_dir = os.path.dirname(db_file)
Andrew Geissler517393d2023-01-13 08:55:19 -060043 db_tmp_file = d.getVar("CVE_DB_TEMP_FILE")
Andrew Geisslerc9f78652020-09-18 14:11:35 -050044
Andrew Geissler517393d2023-01-13 08:55:19 -060045 cleanup_db_download(db_file, db_tmp_file)
Brad Bishop08902b02019-08-20 09:16:51 -040046
Andrew Geisslerd5838332022-05-27 11:33:10 -050047 # The NVD database changes once a day, so no need to update more frequently
48 # Allow the user to force-update
Brad Bishop1d80a2e2019-11-15 16:35:03 -050049 try:
50 import time
Andrew Geisslerd5838332022-05-27 11:33:10 -050051 update_interval = int(d.getVar("CVE_DB_UPDATE_INTERVAL"))
Andrew Geissler78b72792022-06-14 06:47:25 -050052 if update_interval < 0:
53 bb.note("CVE database update skipped")
54 return
Andrew Geisslerd5838332022-05-27 11:33:10 -050055 if time.time() - os.path.getmtime(db_file) < update_interval:
Andrew Geisslerc9f78652020-09-18 14:11:35 -050056 bb.debug(2, "Recently updated, skipping")
Brad Bishop1d80a2e2019-11-15 16:35:03 -050057 return
Andrew Geisslerd5838332022-05-27 11:33:10 -050058
Brad Bishop1d80a2e2019-11-15 16:35:03 -050059 except OSError:
60 pass
61
Andrew Geisslerc9f78652020-09-18 14:11:35 -050062 bb.utils.mkdirhier(db_dir)
Andrew Geissler517393d2023-01-13 08:55:19 -060063 if os.path.exists(db_file):
64 shutil.copy2(db_file, db_tmp_file)
65
66 if update_db_file(db_tmp_file, d) == True:
67 # Update downloaded correctly, can swap files
68 shutil.move(db_tmp_file, db_file)
69 else:
70 # Update failed, do not modify the database
71 bb.note("CVE database update failed")
72 os.remove(db_tmp_file)
73}
74
75do_fetch[lockfiles] += "${CVE_CHECK_DB_FILE_LOCK}"
76do_fetch[file-checksums] = ""
77do_fetch[vardeps] = ""
78
79def cleanup_db_download(db_file, db_tmp_file):
80 """
81 Cleanup the download space from possible failed downloads
82 """
83
84 # Clean up the updates done on the main file
85 # Remove it only if a journal file exists - it means a complete re-download
86 if os.path.exists("{0}-journal".format(db_file)):
87 # If a journal is present the last update might have been interrupted. In that case,
88 # just wipe any leftovers and force the DB to be recreated.
89 os.remove("{0}-journal".format(db_file))
90
91 if os.path.exists(db_file):
92 os.remove(db_file)
93
94 # Clean-up the temporary file downloads, we can remove both journal
95 # and the temporary database
96 if os.path.exists("{0}-journal".format(db_tmp_file)):
97 # If a journal is present the last update might have been interrupted. In that case,
98 # just wipe any leftovers and force the DB to be recreated.
99 os.remove("{0}-journal".format(db_tmp_file))
100
101 if os.path.exists(db_tmp_file):
102 os.remove(db_tmp_file)
103
104def update_db_file(db_tmp_file, d):
105 """
106 Update the given database file
107 """
108 import bb.utils, bb.progress
109 from datetime import date
110 import urllib, gzip, sqlite3
111
112 YEAR_START = 2002
113 cve_socket_timeout = int(d.getVar("CVE_SOCKET_TIMEOUT"))
Brad Bishop96ff1982019-08-19 13:50:42 -0400114
115 # Connect to database
Andrew Geissler517393d2023-01-13 08:55:19 -0600116 conn = sqlite3.connect(db_tmp_file)
Patrick Williams92b42cb2022-09-03 06:53:57 -0500117 initialize_db(conn)
Brad Bishop96ff1982019-08-19 13:50:42 -0400118
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500119 with bb.progress.ProgressHandler(d) as ph, open(os.path.join(d.getVar("TMPDIR"), 'cve_check'), 'a') as cve_f:
120 total_years = date.today().year + 1 - YEAR_START
121 for i, year in enumerate(range(YEAR_START, date.today().year + 1)):
122 bb.debug(2, "Updating %d" % year)
123 ph.update((float(i + 1) / total_years) * 100)
Andrew Geissler95ac1b82021-03-31 14:34:31 -0500124 year_url = (d.getVar('NVDCVE_URL')) + str(year)
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500125 meta_url = year_url + ".meta"
126 json_url = year_url + ".json.gz"
Brad Bishop96ff1982019-08-19 13:50:42 -0400127
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500128 # Retrieve meta last modified date
Brad Bishop96ff1982019-08-19 13:50:42 -0400129 try:
Patrick Williams2390b1b2022-11-03 13:47:49 -0500130 response = urllib.request.urlopen(meta_url, timeout=cve_socket_timeout)
Brad Bishop96ff1982019-08-19 13:50:42 -0400131 except urllib.error.URLError as e:
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500132 cve_f.write('Warning: CVE db update error, Unable to fetch CVE data.\n\n')
Andrew Geisslerc5535c92023-01-27 16:10:19 -0600133 bb.warn("Failed to fetch CVE data (%s)" % e)
134 import socket
135 result = socket.getaddrinfo("nvd.nist.gov", 443, proto=socket.IPPROTO_TCP)
136 bb.warn("Host IPs are %s" % (", ".join(t[4][0] for t in result)))
Andrew Geissler517393d2023-01-13 08:55:19 -0600137 return False
Brad Bishop96ff1982019-08-19 13:50:42 -0400138
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500139 if response:
140 for l in response.read().decode("utf-8").splitlines():
141 key, value = l.split(":", 1)
142 if key == "lastModifiedDate":
143 last_modified = value
144 break
145 else:
146 bb.warn("Cannot parse CVE metadata, update failed")
Andrew Geissler517393d2023-01-13 08:55:19 -0600147 return False
Brad Bishop96ff1982019-08-19 13:50:42 -0400148
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500149 # Compare with current db last modified date
Patrick Williams92b42cb2022-09-03 06:53:57 -0500150 cursor = conn.execute("select DATE from META where YEAR = ?", (year,))
151 meta = cursor.fetchone()
152 cursor.close()
153
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500154 if not meta or meta[0] != last_modified:
155 bb.debug(2, "Updating entries")
156 # Clear products table entries corresponding to current year
Patrick Williams92b42cb2022-09-03 06:53:57 -0500157 conn.execute("delete from PRODUCTS where ID like ?", ('CVE-%d%%' % year,)).close()
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500158
159 # Update db with current year json file
160 try:
Patrick Williams2390b1b2022-11-03 13:47:49 -0500161 response = urllib.request.urlopen(json_url, timeout=cve_socket_timeout)
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500162 if response:
Patrick Williams92b42cb2022-09-03 06:53:57 -0500163 update_db(conn, gzip.decompress(response.read()).decode('utf-8'))
164 conn.execute("insert or replace into META values (?, ?)", [year, last_modified]).close()
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500165 except urllib.error.URLError as e:
166 cve_f.write('Warning: CVE db update error, CVE data is outdated.\n\n')
167 bb.warn("Cannot parse CVE data (%s), update failed" % e.reason)
Andrew Geissler517393d2023-01-13 08:55:19 -0600168 return False
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500169 else:
170 bb.debug(2, "Already up to date (last modified %s)" % last_modified)
171 # Update success, set the date to cve_check file.
172 if year == date.today().year:
173 cve_f.write('CVE database update : %s\n\n' % date.today())
174
175 conn.commit()
176 conn.close()
Andrew Geissler517393d2023-01-13 08:55:19 -0600177 return True
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500178
Patrick Williams92b42cb2022-09-03 06:53:57 -0500179def initialize_db(conn):
180 with conn:
181 c = conn.cursor()
Brad Bishop6dbb3162019-11-25 09:41:34 -0500182
Patrick Williams92b42cb2022-09-03 06:53:57 -0500183 c.execute("CREATE TABLE IF NOT EXISTS META (YEAR INTEGER UNIQUE, DATE TEXT)")
Brad Bishop6dbb3162019-11-25 09:41:34 -0500184
Patrick Williams92b42cb2022-09-03 06:53:57 -0500185 c.execute("CREATE TABLE IF NOT EXISTS NVD (ID TEXT UNIQUE, SUMMARY TEXT, \
186 SCOREV2 TEXT, SCOREV3 TEXT, MODIFIED INTEGER, VECTOR TEXT)")
Brad Bishop96ff1982019-08-19 13:50:42 -0400187
Patrick Williams92b42cb2022-09-03 06:53:57 -0500188 c.execute("CREATE TABLE IF NOT EXISTS PRODUCTS (ID TEXT, \
189 VENDOR TEXT, PRODUCT TEXT, VERSION_START TEXT, OPERATOR_START TEXT, \
190 VERSION_END TEXT, OPERATOR_END TEXT)")
191 c.execute("CREATE INDEX IF NOT EXISTS PRODUCT_ID_IDX on PRODUCTS(ID);")
192
193 c.close()
194
195def parse_node_and_insert(conn, node, cveId):
Brad Bishop96ff1982019-08-19 13:50:42 -0400196 # Parse children node if needed
197 for child in node.get('children', ()):
Patrick Williams92b42cb2022-09-03 06:53:57 -0500198 parse_node_and_insert(conn, child, cveId)
Brad Bishop96ff1982019-08-19 13:50:42 -0400199
200 def cpe_generator():
201 for cpe in node.get('cpe_match', ()):
202 if not cpe['vulnerable']:
203 return
Andrew Geisslerc926e172021-05-07 16:11:35 -0500204 cpe23 = cpe.get('cpe23Uri')
205 if not cpe23:
206 return
207 cpe23 = cpe23.split(':')
208 if len(cpe23) < 6:
209 return
Brad Bishop96ff1982019-08-19 13:50:42 -0400210 vendor = cpe23[3]
211 product = cpe23[4]
212 version = cpe23[5]
213
Andrew Geissler95ac1b82021-03-31 14:34:31 -0500214 if cpe23[6] == '*' or cpe23[6] == '-':
215 version_suffix = ""
216 else:
217 version_suffix = "_" + cpe23[6]
218
Andrew Geissler82c905d2020-04-13 13:39:40 -0500219 if version != '*' and version != '-':
Brad Bishop96ff1982019-08-19 13:50:42 -0400220 # Version is defined, this is a '=' match
Andrew Geissler95ac1b82021-03-31 14:34:31 -0500221 yield [cveId, vendor, product, version + version_suffix, '=', '', '']
Andrew Geissler82c905d2020-04-13 13:39:40 -0500222 elif version == '-':
223 # no version information is available
224 yield [cveId, vendor, product, version, '', '', '']
Brad Bishop96ff1982019-08-19 13:50:42 -0400225 else:
226 # Parse start version, end version and operators
227 op_start = ''
228 op_end = ''
229 v_start = ''
230 v_end = ''
231
232 if 'versionStartIncluding' in cpe:
233 op_start = '>='
234 v_start = cpe['versionStartIncluding']
235
236 if 'versionStartExcluding' in cpe:
237 op_start = '>'
238 v_start = cpe['versionStartExcluding']
239
240 if 'versionEndIncluding' in cpe:
241 op_end = '<='
242 v_end = cpe['versionEndIncluding']
243
244 if 'versionEndExcluding' in cpe:
245 op_end = '<'
246 v_end = cpe['versionEndExcluding']
247
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600248 if op_start or op_end or v_start or v_end:
249 yield [cveId, vendor, product, v_start, op_start, v_end, op_end]
250 else:
251 # This is no version information, expressed differently.
252 # Save processing by representing as -.
253 yield [cveId, vendor, product, '-', '', '', '']
Brad Bishop96ff1982019-08-19 13:50:42 -0400254
Patrick Williams92b42cb2022-09-03 06:53:57 -0500255 conn.executemany("insert into PRODUCTS values (?, ?, ?, ?, ?, ?, ?)", cpe_generator()).close()
Brad Bishop96ff1982019-08-19 13:50:42 -0400256
Patrick Williams92b42cb2022-09-03 06:53:57 -0500257def update_db(conn, jsondata):
Brad Bishop96ff1982019-08-19 13:50:42 -0400258 import json
259 root = json.loads(jsondata)
260
261 for elt in root['CVE_Items']:
262 if not elt['impact']:
263 continue
264
Andrew Geissler635e0e42020-08-21 15:58:33 -0500265 accessVector = None
Brad Bishop96ff1982019-08-19 13:50:42 -0400266 cveId = elt['cve']['CVE_data_meta']['ID']
267 cveDesc = elt['cve']['description']['description_data'][0]['value']
268 date = elt['lastModifiedDate']
Brad Bishop96ff1982019-08-19 13:50:42 -0400269 try:
Andrew Geissler635e0e42020-08-21 15:58:33 -0500270 accessVector = elt['impact']['baseMetricV2']['cvssV2']['accessVector']
271 cvssv2 = elt['impact']['baseMetricV2']['cvssV2']['baseScore']
272 except KeyError:
273 cvssv2 = 0.0
274 try:
275 accessVector = accessVector or elt['impact']['baseMetricV3']['cvssV3']['attackVector']
Brad Bishop96ff1982019-08-19 13:50:42 -0400276 cvssv3 = elt['impact']['baseMetricV3']['cvssV3']['baseScore']
Andrew Geissler635e0e42020-08-21 15:58:33 -0500277 except KeyError:
278 accessVector = accessVector or "UNKNOWN"
Brad Bishop96ff1982019-08-19 13:50:42 -0400279 cvssv3 = 0.0
280
Patrick Williams92b42cb2022-09-03 06:53:57 -0500281 conn.execute("insert or replace into NVD values (?, ?, ?, ?, ?, ?)",
282 [cveId, cveDesc, cvssv2, cvssv3, date, accessVector]).close()
Brad Bishop96ff1982019-08-19 13:50:42 -0400283
284 configurations = elt['configurations']['nodes']
285 for config in configurations:
Patrick Williams92b42cb2022-09-03 06:53:57 -0500286 parse_node_and_insert(conn, config, cveId)
Brad Bishop96ff1982019-08-19 13:50:42 -0400287
288
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500289do_fetch[nostamp] = "1"
Brad Bishop96ff1982019-08-19 13:50:42 -0400290
291EXCLUDE_FROM_WORLD = "1"