blob: 9b9dbbd75f26b61540610306c27f41ea838d7073 [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
Brad Bishop96ff1982019-08-19 13:50:42 -040024python () {
Andrew Geisslerc9f78652020-09-18 14:11:35 -050025 if not bb.data.inherits_class("cve-check", d):
Brad Bishop96ff1982019-08-19 13:50:42 -040026 raise bb.parse.SkipRecipe("Skip recipe when cve-check class is not loaded.")
27}
28
Andrew Geisslerc9f78652020-09-18 14:11:35 -050029python do_fetch() {
Brad Bishop96ff1982019-08-19 13:50:42 -040030 """
31 Update NVD database with json data feed
32 """
Brad Bishop6dbb3162019-11-25 09:41:34 -050033 import bb.utils
Andrew Geisslerc9f78652020-09-18 14:11:35 -050034 import bb.progress
35 import sqlite3, urllib, urllib.parse, gzip
Brad Bishop96ff1982019-08-19 13:50:42 -040036 from datetime import date
37
Brad Bishop6dbb3162019-11-25 09:41:34 -050038 bb.utils.export_proxies(d)
39
Brad Bishop96ff1982019-08-19 13:50:42 -040040 YEAR_START = 2002
41
Brad Bishop6dbb3162019-11-25 09:41:34 -050042 db_file = d.getVar("CVE_CHECK_DB_FILE")
43 db_dir = os.path.dirname(db_file)
Andrew Geisslerc9f78652020-09-18 14:11:35 -050044
Patrick Williams2390b1b2022-11-03 13:47:49 -050045 cve_socket_timeout = int(d.getVar("CVE_SOCKET_TIMEOUT"))
46
Andrew Geisslerc9f78652020-09-18 14:11:35 -050047 if os.path.exists("{0}-journal".format(db_file)):
48 # If a journal is present the last update might have been interrupted. In that case,
49 # just wipe any leftovers and force the DB to be recreated.
50 os.remove("{0}-journal".format(db_file))
51
52 if os.path.exists(db_file):
53 os.remove(db_file)
Brad Bishop08902b02019-08-20 09:16:51 -040054
Andrew Geisslerd5838332022-05-27 11:33:10 -050055 # The NVD database changes once a day, so no need to update more frequently
56 # Allow the user to force-update
Brad Bishop1d80a2e2019-11-15 16:35:03 -050057 try:
58 import time
Andrew Geisslerd5838332022-05-27 11:33:10 -050059 update_interval = int(d.getVar("CVE_DB_UPDATE_INTERVAL"))
Andrew Geissler78b72792022-06-14 06:47:25 -050060 if update_interval < 0:
61 bb.note("CVE database update skipped")
62 return
Andrew Geisslerd5838332022-05-27 11:33:10 -050063 if time.time() - os.path.getmtime(db_file) < update_interval:
Andrew Geisslerc9f78652020-09-18 14:11:35 -050064 bb.debug(2, "Recently updated, skipping")
Brad Bishop1d80a2e2019-11-15 16:35:03 -050065 return
Andrew Geisslerd5838332022-05-27 11:33:10 -050066
Brad Bishop1d80a2e2019-11-15 16:35:03 -050067 except OSError:
68 pass
69
Andrew Geisslerc9f78652020-09-18 14:11:35 -050070 bb.utils.mkdirhier(db_dir)
Brad Bishop96ff1982019-08-19 13:50:42 -040071
72 # Connect to database
73 conn = sqlite3.connect(db_file)
Patrick Williams92b42cb2022-09-03 06:53:57 -050074 initialize_db(conn)
Brad Bishop96ff1982019-08-19 13:50:42 -040075
Andrew Geisslerc9f78652020-09-18 14:11:35 -050076 with bb.progress.ProgressHandler(d) as ph, open(os.path.join(d.getVar("TMPDIR"), 'cve_check'), 'a') as cve_f:
77 total_years = date.today().year + 1 - YEAR_START
78 for i, year in enumerate(range(YEAR_START, date.today().year + 1)):
79 bb.debug(2, "Updating %d" % year)
80 ph.update((float(i + 1) / total_years) * 100)
Andrew Geissler95ac1b82021-03-31 14:34:31 -050081 year_url = (d.getVar('NVDCVE_URL')) + str(year)
Andrew Geisslerc9f78652020-09-18 14:11:35 -050082 meta_url = year_url + ".meta"
83 json_url = year_url + ".json.gz"
Brad Bishop96ff1982019-08-19 13:50:42 -040084
Andrew Geisslerc9f78652020-09-18 14:11:35 -050085 # Retrieve meta last modified date
Brad Bishop96ff1982019-08-19 13:50:42 -040086 try:
Patrick Williams2390b1b2022-11-03 13:47:49 -050087 response = urllib.request.urlopen(meta_url, timeout=cve_socket_timeout)
Brad Bishop96ff1982019-08-19 13:50:42 -040088 except urllib.error.URLError as e:
Andrew Geisslerc9f78652020-09-18 14:11:35 -050089 cve_f.write('Warning: CVE db update error, Unable to fetch CVE data.\n\n')
90 bb.warn("Failed to fetch CVE data (%s)" % e.reason)
Brad Bishop96ff1982019-08-19 13:50:42 -040091 return
92
Andrew Geisslerc9f78652020-09-18 14:11:35 -050093 if response:
94 for l in response.read().decode("utf-8").splitlines():
95 key, value = l.split(":", 1)
96 if key == "lastModifiedDate":
97 last_modified = value
98 break
99 else:
100 bb.warn("Cannot parse CVE metadata, update failed")
101 return
Brad Bishop96ff1982019-08-19 13:50:42 -0400102
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500103 # Compare with current db last modified date
Patrick Williams92b42cb2022-09-03 06:53:57 -0500104 cursor = conn.execute("select DATE from META where YEAR = ?", (year,))
105 meta = cursor.fetchone()
106 cursor.close()
107
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500108 if not meta or meta[0] != last_modified:
109 bb.debug(2, "Updating entries")
110 # Clear products table entries corresponding to current year
Patrick Williams92b42cb2022-09-03 06:53:57 -0500111 conn.execute("delete from PRODUCTS where ID like ?", ('CVE-%d%%' % year,)).close()
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500112
113 # Update db with current year json file
114 try:
Patrick Williams2390b1b2022-11-03 13:47:49 -0500115 response = urllib.request.urlopen(json_url, timeout=cve_socket_timeout)
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500116 if response:
Patrick Williams92b42cb2022-09-03 06:53:57 -0500117 update_db(conn, gzip.decompress(response.read()).decode('utf-8'))
118 conn.execute("insert or replace into META values (?, ?)", [year, last_modified]).close()
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500119 except urllib.error.URLError as e:
120 cve_f.write('Warning: CVE db update error, CVE data is outdated.\n\n')
121 bb.warn("Cannot parse CVE data (%s), update failed" % e.reason)
122 return
123 else:
124 bb.debug(2, "Already up to date (last modified %s)" % last_modified)
125 # Update success, set the date to cve_check file.
126 if year == date.today().year:
127 cve_f.write('CVE database update : %s\n\n' % date.today())
128
129 conn.commit()
130 conn.close()
Brad Bishop96ff1982019-08-19 13:50:42 -0400131}
132
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500133do_fetch[lockfiles] += "${CVE_CHECK_DB_FILE_LOCK}"
134do_fetch[file-checksums] = ""
135do_fetch[vardeps] = ""
136
Patrick Williams92b42cb2022-09-03 06:53:57 -0500137def initialize_db(conn):
138 with conn:
139 c = conn.cursor()
Brad Bishop6dbb3162019-11-25 09:41:34 -0500140
Patrick Williams92b42cb2022-09-03 06:53:57 -0500141 c.execute("CREATE TABLE IF NOT EXISTS META (YEAR INTEGER UNIQUE, DATE TEXT)")
Brad Bishop6dbb3162019-11-25 09:41:34 -0500142
Patrick Williams92b42cb2022-09-03 06:53:57 -0500143 c.execute("CREATE TABLE IF NOT EXISTS NVD (ID TEXT UNIQUE, SUMMARY TEXT, \
144 SCOREV2 TEXT, SCOREV3 TEXT, MODIFIED INTEGER, VECTOR TEXT)")
Brad Bishop96ff1982019-08-19 13:50:42 -0400145
Patrick Williams92b42cb2022-09-03 06:53:57 -0500146 c.execute("CREATE TABLE IF NOT EXISTS PRODUCTS (ID TEXT, \
147 VENDOR TEXT, PRODUCT TEXT, VERSION_START TEXT, OPERATOR_START TEXT, \
148 VERSION_END TEXT, OPERATOR_END TEXT)")
149 c.execute("CREATE INDEX IF NOT EXISTS PRODUCT_ID_IDX on PRODUCTS(ID);")
150
151 c.close()
152
153def parse_node_and_insert(conn, node, cveId):
Brad Bishop96ff1982019-08-19 13:50:42 -0400154 # Parse children node if needed
155 for child in node.get('children', ()):
Patrick Williams92b42cb2022-09-03 06:53:57 -0500156 parse_node_and_insert(conn, child, cveId)
Brad Bishop96ff1982019-08-19 13:50:42 -0400157
158 def cpe_generator():
159 for cpe in node.get('cpe_match', ()):
160 if not cpe['vulnerable']:
161 return
Andrew Geisslerc926e172021-05-07 16:11:35 -0500162 cpe23 = cpe.get('cpe23Uri')
163 if not cpe23:
164 return
165 cpe23 = cpe23.split(':')
166 if len(cpe23) < 6:
167 return
Brad Bishop96ff1982019-08-19 13:50:42 -0400168 vendor = cpe23[3]
169 product = cpe23[4]
170 version = cpe23[5]
171
Andrew Geissler95ac1b82021-03-31 14:34:31 -0500172 if cpe23[6] == '*' or cpe23[6] == '-':
173 version_suffix = ""
174 else:
175 version_suffix = "_" + cpe23[6]
176
Andrew Geissler82c905d2020-04-13 13:39:40 -0500177 if version != '*' and version != '-':
Brad Bishop96ff1982019-08-19 13:50:42 -0400178 # Version is defined, this is a '=' match
Andrew Geissler95ac1b82021-03-31 14:34:31 -0500179 yield [cveId, vendor, product, version + version_suffix, '=', '', '']
Andrew Geissler82c905d2020-04-13 13:39:40 -0500180 elif version == '-':
181 # no version information is available
182 yield [cveId, vendor, product, version, '', '', '']
Brad Bishop96ff1982019-08-19 13:50:42 -0400183 else:
184 # Parse start version, end version and operators
185 op_start = ''
186 op_end = ''
187 v_start = ''
188 v_end = ''
189
190 if 'versionStartIncluding' in cpe:
191 op_start = '>='
192 v_start = cpe['versionStartIncluding']
193
194 if 'versionStartExcluding' in cpe:
195 op_start = '>'
196 v_start = cpe['versionStartExcluding']
197
198 if 'versionEndIncluding' in cpe:
199 op_end = '<='
200 v_end = cpe['versionEndIncluding']
201
202 if 'versionEndExcluding' in cpe:
203 op_end = '<'
204 v_end = cpe['versionEndExcluding']
205
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600206 if op_start or op_end or v_start or v_end:
207 yield [cveId, vendor, product, v_start, op_start, v_end, op_end]
208 else:
209 # This is no version information, expressed differently.
210 # Save processing by representing as -.
211 yield [cveId, vendor, product, '-', '', '', '']
Brad Bishop96ff1982019-08-19 13:50:42 -0400212
Patrick Williams92b42cb2022-09-03 06:53:57 -0500213 conn.executemany("insert into PRODUCTS values (?, ?, ?, ?, ?, ?, ?)", cpe_generator()).close()
Brad Bishop96ff1982019-08-19 13:50:42 -0400214
Patrick Williams92b42cb2022-09-03 06:53:57 -0500215def update_db(conn, jsondata):
Brad Bishop96ff1982019-08-19 13:50:42 -0400216 import json
217 root = json.loads(jsondata)
218
219 for elt in root['CVE_Items']:
220 if not elt['impact']:
221 continue
222
Andrew Geissler635e0e42020-08-21 15:58:33 -0500223 accessVector = None
Brad Bishop96ff1982019-08-19 13:50:42 -0400224 cveId = elt['cve']['CVE_data_meta']['ID']
225 cveDesc = elt['cve']['description']['description_data'][0]['value']
226 date = elt['lastModifiedDate']
Brad Bishop96ff1982019-08-19 13:50:42 -0400227 try:
Andrew Geissler635e0e42020-08-21 15:58:33 -0500228 accessVector = elt['impact']['baseMetricV2']['cvssV2']['accessVector']
229 cvssv2 = elt['impact']['baseMetricV2']['cvssV2']['baseScore']
230 except KeyError:
231 cvssv2 = 0.0
232 try:
233 accessVector = accessVector or elt['impact']['baseMetricV3']['cvssV3']['attackVector']
Brad Bishop96ff1982019-08-19 13:50:42 -0400234 cvssv3 = elt['impact']['baseMetricV3']['cvssV3']['baseScore']
Andrew Geissler635e0e42020-08-21 15:58:33 -0500235 except KeyError:
236 accessVector = accessVector or "UNKNOWN"
Brad Bishop96ff1982019-08-19 13:50:42 -0400237 cvssv3 = 0.0
238
Patrick Williams92b42cb2022-09-03 06:53:57 -0500239 conn.execute("insert or replace into NVD values (?, ?, ?, ?, ?, ?)",
240 [cveId, cveDesc, cvssv2, cvssv3, date, accessVector]).close()
Brad Bishop96ff1982019-08-19 13:50:42 -0400241
242 configurations = elt['configurations']['nodes']
243 for config in configurations:
Patrick Williams92b42cb2022-09-03 06:53:57 -0500244 parse_node_and_insert(conn, config, cveId)
Brad Bishop96ff1982019-08-19 13:50:42 -0400245
246
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500247do_fetch[nostamp] = "1"
Brad Bishop96ff1982019-08-19 13:50:42 -0400248
249EXCLUDE_FROM_WORLD = "1"