blob: 25ec6bac71dd81a293f5baa65b2416b9fc082d89 [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-"
16
Brad Bishop96ff1982019-08-19 13:50:42 -040017python () {
Andrew Geisslerc9f78652020-09-18 14:11:35 -050018 if not bb.data.inherits_class("cve-check", d):
Brad Bishop96ff1982019-08-19 13:50:42 -040019 raise bb.parse.SkipRecipe("Skip recipe when cve-check class is not loaded.")
20}
21
Andrew Geisslerc9f78652020-09-18 14:11:35 -050022python do_fetch() {
Brad Bishop96ff1982019-08-19 13:50:42 -040023 """
24 Update NVD database with json data feed
25 """
Brad Bishop6dbb3162019-11-25 09:41:34 -050026 import bb.utils
Andrew Geisslerc9f78652020-09-18 14:11:35 -050027 import bb.progress
28 import sqlite3, urllib, urllib.parse, gzip
Brad Bishop96ff1982019-08-19 13:50:42 -040029 from datetime import date
30
Brad Bishop6dbb3162019-11-25 09:41:34 -050031 bb.utils.export_proxies(d)
32
Brad Bishop96ff1982019-08-19 13:50:42 -040033 YEAR_START = 2002
34
Brad Bishop6dbb3162019-11-25 09:41:34 -050035 db_file = d.getVar("CVE_CHECK_DB_FILE")
36 db_dir = os.path.dirname(db_file)
Andrew Geisslerc9f78652020-09-18 14:11:35 -050037
38 if os.path.exists("{0}-journal".format(db_file)):
39 # If a journal is present the last update might have been interrupted. In that case,
40 # just wipe any leftovers and force the DB to be recreated.
41 os.remove("{0}-journal".format(db_file))
42
43 if os.path.exists(db_file):
44 os.remove(db_file)
Brad Bishop08902b02019-08-20 09:16:51 -040045
Brad Bishop1d80a2e2019-11-15 16:35:03 -050046 # Don't refresh the database more than once an hour
47 try:
48 import time
49 if time.time() - os.path.getmtime(db_file) < (60*60):
Andrew Geisslerc9f78652020-09-18 14:11:35 -050050 bb.debug(2, "Recently updated, skipping")
Brad Bishop1d80a2e2019-11-15 16:35:03 -050051 return
52 except OSError:
53 pass
54
Andrew Geisslerc9f78652020-09-18 14:11:35 -050055 bb.utils.mkdirhier(db_dir)
Brad Bishop96ff1982019-08-19 13:50:42 -040056
57 # Connect to database
58 conn = sqlite3.connect(db_file)
59 c = conn.cursor()
60
61 initialize_db(c)
62
Andrew Geisslerc9f78652020-09-18 14:11:35 -050063 with bb.progress.ProgressHandler(d) as ph, open(os.path.join(d.getVar("TMPDIR"), 'cve_check'), 'a') as cve_f:
64 total_years = date.today().year + 1 - YEAR_START
65 for i, year in enumerate(range(YEAR_START, date.today().year + 1)):
66 bb.debug(2, "Updating %d" % year)
67 ph.update((float(i + 1) / total_years) * 100)
Andrew Geissler95ac1b82021-03-31 14:34:31 -050068 year_url = (d.getVar('NVDCVE_URL')) + str(year)
Andrew Geisslerc9f78652020-09-18 14:11:35 -050069 meta_url = year_url + ".meta"
70 json_url = year_url + ".json.gz"
Brad Bishop96ff1982019-08-19 13:50:42 -040071
Andrew Geisslerc9f78652020-09-18 14:11:35 -050072 # Retrieve meta last modified date
Brad Bishop96ff1982019-08-19 13:50:42 -040073 try:
Andrew Geisslerc9f78652020-09-18 14:11:35 -050074 response = urllib.request.urlopen(meta_url)
Brad Bishop96ff1982019-08-19 13:50:42 -040075 except urllib.error.URLError as e:
Andrew Geisslerc9f78652020-09-18 14:11:35 -050076 cve_f.write('Warning: CVE db update error, Unable to fetch CVE data.\n\n')
77 bb.warn("Failed to fetch CVE data (%s)" % e.reason)
Brad Bishop96ff1982019-08-19 13:50:42 -040078 return
79
Andrew Geisslerc9f78652020-09-18 14:11:35 -050080 if response:
81 for l in response.read().decode("utf-8").splitlines():
82 key, value = l.split(":", 1)
83 if key == "lastModifiedDate":
84 last_modified = value
85 break
86 else:
87 bb.warn("Cannot parse CVE metadata, update failed")
88 return
Brad Bishop96ff1982019-08-19 13:50:42 -040089
Andrew Geisslerc9f78652020-09-18 14:11:35 -050090 # Compare with current db last modified date
91 c.execute("select DATE from META where YEAR = ?", (year,))
92 meta = c.fetchone()
93 if not meta or meta[0] != last_modified:
94 bb.debug(2, "Updating entries")
95 # Clear products table entries corresponding to current year
96 c.execute("delete from PRODUCTS where ID like ?", ('CVE-%d%%' % year,))
97
98 # Update db with current year json file
99 try:
100 response = urllib.request.urlopen(json_url)
101 if response:
102 update_db(c, gzip.decompress(response.read()).decode('utf-8'))
103 c.execute("insert or replace into META values (?, ?)", [year, last_modified])
104 except urllib.error.URLError as e:
105 cve_f.write('Warning: CVE db update error, CVE data is outdated.\n\n')
106 bb.warn("Cannot parse CVE data (%s), update failed" % e.reason)
107 return
108 else:
109 bb.debug(2, "Already up to date (last modified %s)" % last_modified)
110 # Update success, set the date to cve_check file.
111 if year == date.today().year:
112 cve_f.write('CVE database update : %s\n\n' % date.today())
113
114 conn.commit()
115 conn.close()
Brad Bishop96ff1982019-08-19 13:50:42 -0400116}
117
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500118do_fetch[lockfiles] += "${CVE_CHECK_DB_FILE_LOCK}"
119do_fetch[file-checksums] = ""
120do_fetch[vardeps] = ""
121
Brad Bishop96ff1982019-08-19 13:50:42 -0400122def initialize_db(c):
123 c.execute("CREATE TABLE IF NOT EXISTS META (YEAR INTEGER UNIQUE, DATE TEXT)")
Brad Bishop6dbb3162019-11-25 09:41:34 -0500124
Brad Bishop96ff1982019-08-19 13:50:42 -0400125 c.execute("CREATE TABLE IF NOT EXISTS NVD (ID TEXT UNIQUE, SUMMARY TEXT, \
126 SCOREV2 TEXT, SCOREV3 TEXT, MODIFIED INTEGER, VECTOR TEXT)")
Brad Bishop6dbb3162019-11-25 09:41:34 -0500127
Brad Bishop96ff1982019-08-19 13:50:42 -0400128 c.execute("CREATE TABLE IF NOT EXISTS PRODUCTS (ID TEXT, \
129 VENDOR TEXT, PRODUCT TEXT, VERSION_START TEXT, OPERATOR_START TEXT, \
130 VERSION_END TEXT, OPERATOR_END TEXT)")
Brad Bishop6dbb3162019-11-25 09:41:34 -0500131 c.execute("CREATE INDEX IF NOT EXISTS PRODUCT_ID_IDX on PRODUCTS(ID);")
Brad Bishop96ff1982019-08-19 13:50:42 -0400132
133def parse_node_and_insert(c, node, cveId):
134 # Parse children node if needed
135 for child in node.get('children', ()):
136 parse_node_and_insert(c, child, cveId)
137
138 def cpe_generator():
139 for cpe in node.get('cpe_match', ()):
140 if not cpe['vulnerable']:
141 return
142 cpe23 = cpe['cpe23Uri'].split(':')
143 vendor = cpe23[3]
144 product = cpe23[4]
145 version = cpe23[5]
146
Andrew Geissler95ac1b82021-03-31 14:34:31 -0500147 if cpe23[6] == '*' or cpe23[6] == '-':
148 version_suffix = ""
149 else:
150 version_suffix = "_" + cpe23[6]
151
Andrew Geissler82c905d2020-04-13 13:39:40 -0500152 if version != '*' and version != '-':
Brad Bishop96ff1982019-08-19 13:50:42 -0400153 # Version is defined, this is a '=' match
Andrew Geissler95ac1b82021-03-31 14:34:31 -0500154 yield [cveId, vendor, product, version + version_suffix, '=', '', '']
Andrew Geissler82c905d2020-04-13 13:39:40 -0500155 elif version == '-':
156 # no version information is available
157 yield [cveId, vendor, product, version, '', '', '']
Brad Bishop96ff1982019-08-19 13:50:42 -0400158 else:
159 # Parse start version, end version and operators
160 op_start = ''
161 op_end = ''
162 v_start = ''
163 v_end = ''
164
165 if 'versionStartIncluding' in cpe:
166 op_start = '>='
167 v_start = cpe['versionStartIncluding']
168
169 if 'versionStartExcluding' in cpe:
170 op_start = '>'
171 v_start = cpe['versionStartExcluding']
172
173 if 'versionEndIncluding' in cpe:
174 op_end = '<='
175 v_end = cpe['versionEndIncluding']
176
177 if 'versionEndExcluding' in cpe:
178 op_end = '<'
179 v_end = cpe['versionEndExcluding']
180
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600181 if op_start or op_end or v_start or v_end:
182 yield [cveId, vendor, product, v_start, op_start, v_end, op_end]
183 else:
184 # This is no version information, expressed differently.
185 # Save processing by representing as -.
186 yield [cveId, vendor, product, '-', '', '', '']
Brad Bishop96ff1982019-08-19 13:50:42 -0400187
188 c.executemany("insert into PRODUCTS values (?, ?, ?, ?, ?, ?, ?)", cpe_generator())
189
190def update_db(c, jsondata):
191 import json
192 root = json.loads(jsondata)
193
194 for elt in root['CVE_Items']:
195 if not elt['impact']:
196 continue
197
Andrew Geissler635e0e42020-08-21 15:58:33 -0500198 accessVector = None
Brad Bishop96ff1982019-08-19 13:50:42 -0400199 cveId = elt['cve']['CVE_data_meta']['ID']
200 cveDesc = elt['cve']['description']['description_data'][0]['value']
201 date = elt['lastModifiedDate']
Brad Bishop96ff1982019-08-19 13:50:42 -0400202 try:
Andrew Geissler635e0e42020-08-21 15:58:33 -0500203 accessVector = elt['impact']['baseMetricV2']['cvssV2']['accessVector']
204 cvssv2 = elt['impact']['baseMetricV2']['cvssV2']['baseScore']
205 except KeyError:
206 cvssv2 = 0.0
207 try:
208 accessVector = accessVector or elt['impact']['baseMetricV3']['cvssV3']['attackVector']
Brad Bishop96ff1982019-08-19 13:50:42 -0400209 cvssv3 = elt['impact']['baseMetricV3']['cvssV3']['baseScore']
Andrew Geissler635e0e42020-08-21 15:58:33 -0500210 except KeyError:
211 accessVector = accessVector or "UNKNOWN"
Brad Bishop96ff1982019-08-19 13:50:42 -0400212 cvssv3 = 0.0
213
214 c.execute("insert or replace into NVD values (?, ?, ?, ?, ?, ?)",
215 [cveId, cveDesc, cvssv2, cvssv3, date, accessVector])
216
217 configurations = elt['configurations']['nodes']
218 for config in configurations:
219 parse_node_and_insert(c, config, cveId)
220
221
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500222do_fetch[nostamp] = "1"
Brad Bishop96ff1982019-08-19 13:50:42 -0400223
224EXCLUDE_FROM_WORLD = "1"