blob: 18af89b53e0dbf809a77c158c841e60ace91f56a [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
Brad Bishop96ff1982019-08-19 13:50:42 -040021python () {
Andrew Geisslerc9f78652020-09-18 14:11:35 -050022 if not bb.data.inherits_class("cve-check", d):
Brad Bishop96ff1982019-08-19 13:50:42 -040023 raise bb.parse.SkipRecipe("Skip recipe when cve-check class is not loaded.")
24}
25
Andrew Geisslerc9f78652020-09-18 14:11:35 -050026python do_fetch() {
Brad Bishop96ff1982019-08-19 13:50:42 -040027 """
28 Update NVD database with json data feed
29 """
Brad Bishop6dbb3162019-11-25 09:41:34 -050030 import bb.utils
Andrew Geisslerc9f78652020-09-18 14:11:35 -050031 import bb.progress
32 import sqlite3, urllib, urllib.parse, gzip
Brad Bishop96ff1982019-08-19 13:50:42 -040033 from datetime import date
34
Brad Bishop6dbb3162019-11-25 09:41:34 -050035 bb.utils.export_proxies(d)
36
Brad Bishop96ff1982019-08-19 13:50:42 -040037 YEAR_START = 2002
38
Brad Bishop6dbb3162019-11-25 09:41:34 -050039 db_file = d.getVar("CVE_CHECK_DB_FILE")
40 db_dir = os.path.dirname(db_file)
Andrew Geisslerc9f78652020-09-18 14:11:35 -050041
42 if os.path.exists("{0}-journal".format(db_file)):
43 # If a journal is present the last update might have been interrupted. In that case,
44 # just wipe any leftovers and force the DB to be recreated.
45 os.remove("{0}-journal".format(db_file))
46
47 if os.path.exists(db_file):
48 os.remove(db_file)
Brad Bishop08902b02019-08-20 09:16:51 -040049
Andrew Geisslerd5838332022-05-27 11:33:10 -050050 # The NVD database changes once a day, so no need to update more frequently
51 # Allow the user to force-update
Brad Bishop1d80a2e2019-11-15 16:35:03 -050052 try:
53 import time
Andrew Geisslerd5838332022-05-27 11:33:10 -050054 update_interval = int(d.getVar("CVE_DB_UPDATE_INTERVAL"))
Andrew Geissler78b72792022-06-14 06:47:25 -050055 if update_interval < 0:
56 bb.note("CVE database update skipped")
57 return
Andrew Geisslerd5838332022-05-27 11:33:10 -050058 if time.time() - os.path.getmtime(db_file) < update_interval:
Andrew Geisslerc9f78652020-09-18 14:11:35 -050059 bb.debug(2, "Recently updated, skipping")
Brad Bishop1d80a2e2019-11-15 16:35:03 -050060 return
Andrew Geisslerd5838332022-05-27 11:33:10 -050061
Brad Bishop1d80a2e2019-11-15 16:35:03 -050062 except OSError:
63 pass
64
Andrew Geisslerc9f78652020-09-18 14:11:35 -050065 bb.utils.mkdirhier(db_dir)
Brad Bishop96ff1982019-08-19 13:50:42 -040066
67 # Connect to database
68 conn = sqlite3.connect(db_file)
69 c = conn.cursor()
70
71 initialize_db(c)
72
Andrew Geisslerc9f78652020-09-18 14:11:35 -050073 with bb.progress.ProgressHandler(d) as ph, open(os.path.join(d.getVar("TMPDIR"), 'cve_check'), 'a') as cve_f:
74 total_years = date.today().year + 1 - YEAR_START
75 for i, year in enumerate(range(YEAR_START, date.today().year + 1)):
76 bb.debug(2, "Updating %d" % year)
77 ph.update((float(i + 1) / total_years) * 100)
Andrew Geissler95ac1b82021-03-31 14:34:31 -050078 year_url = (d.getVar('NVDCVE_URL')) + str(year)
Andrew Geisslerc9f78652020-09-18 14:11:35 -050079 meta_url = year_url + ".meta"
80 json_url = year_url + ".json.gz"
Brad Bishop96ff1982019-08-19 13:50:42 -040081
Andrew Geisslerc9f78652020-09-18 14:11:35 -050082 # Retrieve meta last modified date
Brad Bishop96ff1982019-08-19 13:50:42 -040083 try:
Andrew Geisslerc9f78652020-09-18 14:11:35 -050084 response = urllib.request.urlopen(meta_url)
Brad Bishop96ff1982019-08-19 13:50:42 -040085 except urllib.error.URLError as e:
Andrew Geisslerc9f78652020-09-18 14:11:35 -050086 cve_f.write('Warning: CVE db update error, Unable to fetch CVE data.\n\n')
87 bb.warn("Failed to fetch CVE data (%s)" % e.reason)
Brad Bishop96ff1982019-08-19 13:50:42 -040088 return
89
Andrew Geisslerc9f78652020-09-18 14:11:35 -050090 if response:
91 for l in response.read().decode("utf-8").splitlines():
92 key, value = l.split(":", 1)
93 if key == "lastModifiedDate":
94 last_modified = value
95 break
96 else:
97 bb.warn("Cannot parse CVE metadata, update failed")
98 return
Brad Bishop96ff1982019-08-19 13:50:42 -040099
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500100 # Compare with current db last modified date
101 c.execute("select DATE from META where YEAR = ?", (year,))
102 meta = c.fetchone()
103 if not meta or meta[0] != last_modified:
104 bb.debug(2, "Updating entries")
105 # Clear products table entries corresponding to current year
106 c.execute("delete from PRODUCTS where ID like ?", ('CVE-%d%%' % year,))
107
108 # Update db with current year json file
109 try:
110 response = urllib.request.urlopen(json_url)
111 if response:
112 update_db(c, gzip.decompress(response.read()).decode('utf-8'))
113 c.execute("insert or replace into META values (?, ?)", [year, last_modified])
114 except urllib.error.URLError as e:
115 cve_f.write('Warning: CVE db update error, CVE data is outdated.\n\n')
116 bb.warn("Cannot parse CVE data (%s), update failed" % e.reason)
117 return
118 else:
119 bb.debug(2, "Already up to date (last modified %s)" % last_modified)
120 # Update success, set the date to cve_check file.
121 if year == date.today().year:
122 cve_f.write('CVE database update : %s\n\n' % date.today())
123
124 conn.commit()
125 conn.close()
Brad Bishop96ff1982019-08-19 13:50:42 -0400126}
127
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500128do_fetch[lockfiles] += "${CVE_CHECK_DB_FILE_LOCK}"
129do_fetch[file-checksums] = ""
130do_fetch[vardeps] = ""
131
Brad Bishop96ff1982019-08-19 13:50:42 -0400132def initialize_db(c):
133 c.execute("CREATE TABLE IF NOT EXISTS META (YEAR INTEGER UNIQUE, DATE TEXT)")
Brad Bishop6dbb3162019-11-25 09:41:34 -0500134
Brad Bishop96ff1982019-08-19 13:50:42 -0400135 c.execute("CREATE TABLE IF NOT EXISTS NVD (ID TEXT UNIQUE, SUMMARY TEXT, \
136 SCOREV2 TEXT, SCOREV3 TEXT, MODIFIED INTEGER, VECTOR TEXT)")
Brad Bishop6dbb3162019-11-25 09:41:34 -0500137
Brad Bishop96ff1982019-08-19 13:50:42 -0400138 c.execute("CREATE TABLE IF NOT EXISTS PRODUCTS (ID TEXT, \
139 VENDOR TEXT, PRODUCT TEXT, VERSION_START TEXT, OPERATOR_START TEXT, \
140 VERSION_END TEXT, OPERATOR_END TEXT)")
Brad Bishop6dbb3162019-11-25 09:41:34 -0500141 c.execute("CREATE INDEX IF NOT EXISTS PRODUCT_ID_IDX on PRODUCTS(ID);")
Brad Bishop96ff1982019-08-19 13:50:42 -0400142
143def parse_node_and_insert(c, node, cveId):
144 # Parse children node if needed
145 for child in node.get('children', ()):
146 parse_node_and_insert(c, child, cveId)
147
148 def cpe_generator():
149 for cpe in node.get('cpe_match', ()):
150 if not cpe['vulnerable']:
151 return
Andrew Geisslerc926e172021-05-07 16:11:35 -0500152 cpe23 = cpe.get('cpe23Uri')
153 if not cpe23:
154 return
155 cpe23 = cpe23.split(':')
156 if len(cpe23) < 6:
157 return
Brad Bishop96ff1982019-08-19 13:50:42 -0400158 vendor = cpe23[3]
159 product = cpe23[4]
160 version = cpe23[5]
161
Andrew Geissler95ac1b82021-03-31 14:34:31 -0500162 if cpe23[6] == '*' or cpe23[6] == '-':
163 version_suffix = ""
164 else:
165 version_suffix = "_" + cpe23[6]
166
Andrew Geissler82c905d2020-04-13 13:39:40 -0500167 if version != '*' and version != '-':
Brad Bishop96ff1982019-08-19 13:50:42 -0400168 # Version is defined, this is a '=' match
Andrew Geissler95ac1b82021-03-31 14:34:31 -0500169 yield [cveId, vendor, product, version + version_suffix, '=', '', '']
Andrew Geissler82c905d2020-04-13 13:39:40 -0500170 elif version == '-':
171 # no version information is available
172 yield [cveId, vendor, product, version, '', '', '']
Brad Bishop96ff1982019-08-19 13:50:42 -0400173 else:
174 # Parse start version, end version and operators
175 op_start = ''
176 op_end = ''
177 v_start = ''
178 v_end = ''
179
180 if 'versionStartIncluding' in cpe:
181 op_start = '>='
182 v_start = cpe['versionStartIncluding']
183
184 if 'versionStartExcluding' in cpe:
185 op_start = '>'
186 v_start = cpe['versionStartExcluding']
187
188 if 'versionEndIncluding' in cpe:
189 op_end = '<='
190 v_end = cpe['versionEndIncluding']
191
192 if 'versionEndExcluding' in cpe:
193 op_end = '<'
194 v_end = cpe['versionEndExcluding']
195
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600196 if op_start or op_end or v_start or v_end:
197 yield [cveId, vendor, product, v_start, op_start, v_end, op_end]
198 else:
199 # This is no version information, expressed differently.
200 # Save processing by representing as -.
201 yield [cveId, vendor, product, '-', '', '', '']
Brad Bishop96ff1982019-08-19 13:50:42 -0400202
203 c.executemany("insert into PRODUCTS values (?, ?, ?, ?, ?, ?, ?)", cpe_generator())
204
205def update_db(c, jsondata):
206 import json
207 root = json.loads(jsondata)
208
209 for elt in root['CVE_Items']:
210 if not elt['impact']:
211 continue
212
Andrew Geissler635e0e42020-08-21 15:58:33 -0500213 accessVector = None
Brad Bishop96ff1982019-08-19 13:50:42 -0400214 cveId = elt['cve']['CVE_data_meta']['ID']
215 cveDesc = elt['cve']['description']['description_data'][0]['value']
216 date = elt['lastModifiedDate']
Brad Bishop96ff1982019-08-19 13:50:42 -0400217 try:
Andrew Geissler635e0e42020-08-21 15:58:33 -0500218 accessVector = elt['impact']['baseMetricV2']['cvssV2']['accessVector']
219 cvssv2 = elt['impact']['baseMetricV2']['cvssV2']['baseScore']
220 except KeyError:
221 cvssv2 = 0.0
222 try:
223 accessVector = accessVector or elt['impact']['baseMetricV3']['cvssV3']['attackVector']
Brad Bishop96ff1982019-08-19 13:50:42 -0400224 cvssv3 = elt['impact']['baseMetricV3']['cvssV3']['baseScore']
Andrew Geissler635e0e42020-08-21 15:58:33 -0500225 except KeyError:
226 accessVector = accessVector or "UNKNOWN"
Brad Bishop96ff1982019-08-19 13:50:42 -0400227 cvssv3 = 0.0
228
229 c.execute("insert or replace into NVD values (?, ?, ?, ?, ?, ?)",
230 [cveId, cveDesc, cvssv2, cvssv3, date, accessVector])
231
232 configurations = elt['configurations']['nodes']
233 for config in configurations:
234 parse_node_and_insert(c, config, cveId)
235
236
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500237do_fetch[nostamp] = "1"
Brad Bishop96ff1982019-08-19 13:50:42 -0400238
239EXCLUDE_FROM_WORLD = "1"