blob: c8c1cbf115f3e5c7532ac3bd95b4196b627fbee3 [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
18CVE_DB_UPDATE_INTERVAL ?= "86400"
Andrew Geissler95ac1b82021-03-31 14:34:31 -050019
Brad Bishop96ff1982019-08-19 13:50:42 -040020python () {
Andrew Geisslerc9f78652020-09-18 14:11:35 -050021 if not bb.data.inherits_class("cve-check", d):
Brad Bishop96ff1982019-08-19 13:50:42 -040022 raise bb.parse.SkipRecipe("Skip recipe when cve-check class is not loaded.")
23}
24
Andrew Geisslerc9f78652020-09-18 14:11:35 -050025python do_fetch() {
Brad Bishop96ff1982019-08-19 13:50:42 -040026 """
27 Update NVD database with json data feed
28 """
Brad Bishop6dbb3162019-11-25 09:41:34 -050029 import bb.utils
Andrew Geisslerc9f78652020-09-18 14:11:35 -050030 import bb.progress
31 import sqlite3, urllib, urllib.parse, gzip
Brad Bishop96ff1982019-08-19 13:50:42 -040032 from datetime import date
33
Brad Bishop6dbb3162019-11-25 09:41:34 -050034 bb.utils.export_proxies(d)
35
Brad Bishop96ff1982019-08-19 13:50:42 -040036 YEAR_START = 2002
37
Brad Bishop6dbb3162019-11-25 09:41:34 -050038 db_file = d.getVar("CVE_CHECK_DB_FILE")
39 db_dir = os.path.dirname(db_file)
Andrew Geisslerc9f78652020-09-18 14:11:35 -050040
41 if os.path.exists("{0}-journal".format(db_file)):
42 # If a journal is present the last update might have been interrupted. In that case,
43 # just wipe any leftovers and force the DB to be recreated.
44 os.remove("{0}-journal".format(db_file))
45
46 if os.path.exists(db_file):
47 os.remove(db_file)
Brad Bishop08902b02019-08-20 09:16:51 -040048
Andrew Geisslerd5838332022-05-27 11:33:10 -050049 # The NVD database changes once a day, so no need to update more frequently
50 # Allow the user to force-update
Brad Bishop1d80a2e2019-11-15 16:35:03 -050051 try:
52 import time
Andrew Geisslerd5838332022-05-27 11:33:10 -050053 update_interval = int(d.getVar("CVE_DB_UPDATE_INTERVAL"))
54 if (update_interval < 0):
55 update_interval = 0
56 if time.time() - os.path.getmtime(db_file) < update_interval:
Andrew Geisslerc9f78652020-09-18 14:11:35 -050057 bb.debug(2, "Recently updated, skipping")
Brad Bishop1d80a2e2019-11-15 16:35:03 -050058 return
Andrew Geisslerd5838332022-05-27 11:33:10 -050059
Brad Bishop1d80a2e2019-11-15 16:35:03 -050060 except OSError:
61 pass
62
Andrew Geisslerc9f78652020-09-18 14:11:35 -050063 bb.utils.mkdirhier(db_dir)
Brad Bishop96ff1982019-08-19 13:50:42 -040064
65 # Connect to database
66 conn = sqlite3.connect(db_file)
67 c = conn.cursor()
68
69 initialize_db(c)
70
Andrew Geisslerc9f78652020-09-18 14:11:35 -050071 with bb.progress.ProgressHandler(d) as ph, open(os.path.join(d.getVar("TMPDIR"), 'cve_check'), 'a') as cve_f:
72 total_years = date.today().year + 1 - YEAR_START
73 for i, year in enumerate(range(YEAR_START, date.today().year + 1)):
74 bb.debug(2, "Updating %d" % year)
75 ph.update((float(i + 1) / total_years) * 100)
Andrew Geissler95ac1b82021-03-31 14:34:31 -050076 year_url = (d.getVar('NVDCVE_URL')) + str(year)
Andrew Geisslerc9f78652020-09-18 14:11:35 -050077 meta_url = year_url + ".meta"
78 json_url = year_url + ".json.gz"
Brad Bishop96ff1982019-08-19 13:50:42 -040079
Andrew Geisslerc9f78652020-09-18 14:11:35 -050080 # Retrieve meta last modified date
Brad Bishop96ff1982019-08-19 13:50:42 -040081 try:
Andrew Geisslerc9f78652020-09-18 14:11:35 -050082 response = urllib.request.urlopen(meta_url)
Brad Bishop96ff1982019-08-19 13:50:42 -040083 except urllib.error.URLError as e:
Andrew Geisslerc9f78652020-09-18 14:11:35 -050084 cve_f.write('Warning: CVE db update error, Unable to fetch CVE data.\n\n')
85 bb.warn("Failed to fetch CVE data (%s)" % e.reason)
Brad Bishop96ff1982019-08-19 13:50:42 -040086 return
87
Andrew Geisslerc9f78652020-09-18 14:11:35 -050088 if response:
89 for l in response.read().decode("utf-8").splitlines():
90 key, value = l.split(":", 1)
91 if key == "lastModifiedDate":
92 last_modified = value
93 break
94 else:
95 bb.warn("Cannot parse CVE metadata, update failed")
96 return
Brad Bishop96ff1982019-08-19 13:50:42 -040097
Andrew Geisslerc9f78652020-09-18 14:11:35 -050098 # Compare with current db last modified date
99 c.execute("select DATE from META where YEAR = ?", (year,))
100 meta = c.fetchone()
101 if not meta or meta[0] != last_modified:
102 bb.debug(2, "Updating entries")
103 # Clear products table entries corresponding to current year
104 c.execute("delete from PRODUCTS where ID like ?", ('CVE-%d%%' % year,))
105
106 # Update db with current year json file
107 try:
108 response = urllib.request.urlopen(json_url)
109 if response:
110 update_db(c, gzip.decompress(response.read()).decode('utf-8'))
111 c.execute("insert or replace into META values (?, ?)", [year, last_modified])
112 except urllib.error.URLError as e:
113 cve_f.write('Warning: CVE db update error, CVE data is outdated.\n\n')
114 bb.warn("Cannot parse CVE data (%s), update failed" % e.reason)
115 return
116 else:
117 bb.debug(2, "Already up to date (last modified %s)" % last_modified)
118 # Update success, set the date to cve_check file.
119 if year == date.today().year:
120 cve_f.write('CVE database update : %s\n\n' % date.today())
121
122 conn.commit()
123 conn.close()
Brad Bishop96ff1982019-08-19 13:50:42 -0400124}
125
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500126do_fetch[lockfiles] += "${CVE_CHECK_DB_FILE_LOCK}"
127do_fetch[file-checksums] = ""
128do_fetch[vardeps] = ""
129
Brad Bishop96ff1982019-08-19 13:50:42 -0400130def initialize_db(c):
131 c.execute("CREATE TABLE IF NOT EXISTS META (YEAR INTEGER UNIQUE, DATE TEXT)")
Brad Bishop6dbb3162019-11-25 09:41:34 -0500132
Brad Bishop96ff1982019-08-19 13:50:42 -0400133 c.execute("CREATE TABLE IF NOT EXISTS NVD (ID TEXT UNIQUE, SUMMARY TEXT, \
134 SCOREV2 TEXT, SCOREV3 TEXT, MODIFIED INTEGER, VECTOR TEXT)")
Brad Bishop6dbb3162019-11-25 09:41:34 -0500135
Brad Bishop96ff1982019-08-19 13:50:42 -0400136 c.execute("CREATE TABLE IF NOT EXISTS PRODUCTS (ID TEXT, \
137 VENDOR TEXT, PRODUCT TEXT, VERSION_START TEXT, OPERATOR_START TEXT, \
138 VERSION_END TEXT, OPERATOR_END TEXT)")
Brad Bishop6dbb3162019-11-25 09:41:34 -0500139 c.execute("CREATE INDEX IF NOT EXISTS PRODUCT_ID_IDX on PRODUCTS(ID);")
Brad Bishop96ff1982019-08-19 13:50:42 -0400140
141def parse_node_and_insert(c, node, cveId):
142 # Parse children node if needed
143 for child in node.get('children', ()):
144 parse_node_and_insert(c, child, cveId)
145
146 def cpe_generator():
147 for cpe in node.get('cpe_match', ()):
148 if not cpe['vulnerable']:
149 return
Andrew Geisslerc926e172021-05-07 16:11:35 -0500150 cpe23 = cpe.get('cpe23Uri')
151 if not cpe23:
152 return
153 cpe23 = cpe23.split(':')
154 if len(cpe23) < 6:
155 return
Brad Bishop96ff1982019-08-19 13:50:42 -0400156 vendor = cpe23[3]
157 product = cpe23[4]
158 version = cpe23[5]
159
Andrew Geissler95ac1b82021-03-31 14:34:31 -0500160 if cpe23[6] == '*' or cpe23[6] == '-':
161 version_suffix = ""
162 else:
163 version_suffix = "_" + cpe23[6]
164
Andrew Geissler82c905d2020-04-13 13:39:40 -0500165 if version != '*' and version != '-':
Brad Bishop96ff1982019-08-19 13:50:42 -0400166 # Version is defined, this is a '=' match
Andrew Geissler95ac1b82021-03-31 14:34:31 -0500167 yield [cveId, vendor, product, version + version_suffix, '=', '', '']
Andrew Geissler82c905d2020-04-13 13:39:40 -0500168 elif version == '-':
169 # no version information is available
170 yield [cveId, vendor, product, version, '', '', '']
Brad Bishop96ff1982019-08-19 13:50:42 -0400171 else:
172 # Parse start version, end version and operators
173 op_start = ''
174 op_end = ''
175 v_start = ''
176 v_end = ''
177
178 if 'versionStartIncluding' in cpe:
179 op_start = '>='
180 v_start = cpe['versionStartIncluding']
181
182 if 'versionStartExcluding' in cpe:
183 op_start = '>'
184 v_start = cpe['versionStartExcluding']
185
186 if 'versionEndIncluding' in cpe:
187 op_end = '<='
188 v_end = cpe['versionEndIncluding']
189
190 if 'versionEndExcluding' in cpe:
191 op_end = '<'
192 v_end = cpe['versionEndExcluding']
193
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600194 if op_start or op_end or v_start or v_end:
195 yield [cveId, vendor, product, v_start, op_start, v_end, op_end]
196 else:
197 # This is no version information, expressed differently.
198 # Save processing by representing as -.
199 yield [cveId, vendor, product, '-', '', '', '']
Brad Bishop96ff1982019-08-19 13:50:42 -0400200
201 c.executemany("insert into PRODUCTS values (?, ?, ?, ?, ?, ?, ?)", cpe_generator())
202
203def update_db(c, jsondata):
204 import json
205 root = json.loads(jsondata)
206
207 for elt in root['CVE_Items']:
208 if not elt['impact']:
209 continue
210
Andrew Geissler635e0e42020-08-21 15:58:33 -0500211 accessVector = None
Brad Bishop96ff1982019-08-19 13:50:42 -0400212 cveId = elt['cve']['CVE_data_meta']['ID']
213 cveDesc = elt['cve']['description']['description_data'][0]['value']
214 date = elt['lastModifiedDate']
Brad Bishop96ff1982019-08-19 13:50:42 -0400215 try:
Andrew Geissler635e0e42020-08-21 15:58:33 -0500216 accessVector = elt['impact']['baseMetricV2']['cvssV2']['accessVector']
217 cvssv2 = elt['impact']['baseMetricV2']['cvssV2']['baseScore']
218 except KeyError:
219 cvssv2 = 0.0
220 try:
221 accessVector = accessVector or elt['impact']['baseMetricV3']['cvssV3']['attackVector']
Brad Bishop96ff1982019-08-19 13:50:42 -0400222 cvssv3 = elt['impact']['baseMetricV3']['cvssV3']['baseScore']
Andrew Geissler635e0e42020-08-21 15:58:33 -0500223 except KeyError:
224 accessVector = accessVector or "UNKNOWN"
Brad Bishop96ff1982019-08-19 13:50:42 -0400225 cvssv3 = 0.0
226
227 c.execute("insert or replace into NVD values (?, ?, ?, ?, ?, ?)",
228 [cveId, cveDesc, cvssv2, cvssv3, date, accessVector])
229
230 configurations = elt['configurations']['nodes']
231 for config in configurations:
232 parse_node_and_insert(c, config, cveId)
233
234
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500235do_fetch[nostamp] = "1"
Brad Bishop96ff1982019-08-19 13:50:42 -0400236
237EXCLUDE_FROM_WORLD = "1"