blob: 19875a49b1c92296c8b52054df66bc74199c9f5c [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
15python () {
16 if not d.getVar("CVE_CHECK_DB_FILE"):
17 raise bb.parse.SkipRecipe("Skip recipe when cve-check class is not loaded.")
18}
19
20python do_populate_cve_db() {
21 """
22 Update NVD database with json data feed
23 """
24
Brad Bishop08902b02019-08-20 09:16:51 -040025 import sqlite3, urllib, urllib.parse, shutil, gzip
Brad Bishop96ff1982019-08-19 13:50:42 -040026 from datetime import date
27
28 BASE_URL = "https://nvd.nist.gov/feeds/json/cve/1.0/nvdcve-1.0-"
29 YEAR_START = 2002
30
31 db_dir = os.path.join(d.getVar("DL_DIR"), 'CVE_CHECK')
32 db_file = os.path.join(db_dir, 'nvdcve_1.0.db')
33 json_tmpfile = os.path.join(db_dir, 'nvd.json.gz')
Brad Bishop08902b02019-08-20 09:16:51 -040034
Brad Bishop1d80a2e2019-11-15 16:35:03 -050035 # Don't refresh the database more than once an hour
36 try:
37 import time
38 if time.time() - os.path.getmtime(db_file) < (60*60):
39 return
40 except OSError:
41 pass
42
43 proxy = d.getVar("https_proxy")
Brad Bishop08902b02019-08-20 09:16:51 -040044 if proxy:
45 # instantiate an opener but do not install it as the global
46 # opener unless if we're really sure it's applicable for all
47 # urllib requests
48 proxy_handler = urllib.request.ProxyHandler({'https': proxy})
49 proxy_opener = urllib.request.build_opener(proxy_handler)
50 else:
51 proxy_opener = None
52
Brad Bishop96ff1982019-08-19 13:50:42 -040053 cve_f = open(os.path.join(d.getVar("TMPDIR"), 'cve_check'), 'a')
54
55 if not os.path.isdir(db_dir):
56 os.mkdir(db_dir)
57
58 # Connect to database
59 conn = sqlite3.connect(db_file)
60 c = conn.cursor()
61
62 initialize_db(c)
63
64 for year in range(YEAR_START, date.today().year + 1):
65 year_url = BASE_URL + str(year)
66 meta_url = year_url + ".meta"
67 json_url = year_url + ".json.gz"
68
69 # Retrieve meta last modified date
Brad Bishop08902b02019-08-20 09:16:51 -040070
71 response = None
72
73 if proxy_opener:
74 response = proxy_opener.open(meta_url)
75 else:
76 req = urllib.request.Request(meta_url)
77 response = urllib.request.urlopen(req)
78
79 if response:
80 for l in response.read().decode("utf-8").splitlines():
Brad Bishop96ff1982019-08-19 13:50:42 -040081 key, value = l.split(":", 1)
82 if key == "lastModifiedDate":
83 last_modified = value
84 break
85 else:
86 bb.warn("Cannot parse CVE metadata, update failed")
87 return
88
89 # Compare with current db last modified date
90 c.execute("select DATE from META where YEAR = ?", (year,))
91 meta = c.fetchone()
92 if not meta or meta[0] != last_modified:
93 # Clear products table entries corresponding to current year
94 c.execute("delete from PRODUCTS where ID like ?", ('CVE-%d%%' % year,))
95
96 # Update db with current year json file
97 try:
Brad Bishop08902b02019-08-20 09:16:51 -040098 if proxy_opener:
99 response = proxy_opener.open(json_url)
100 else:
101 req = urllib.request.Request(json_url)
102 response = urllib.request.urlopen(req)
103
104 if response:
105 update_db(c, gzip.decompress(response.read()).decode('utf-8'))
Brad Bishop96ff1982019-08-19 13:50:42 -0400106 c.execute("insert or replace into META values (?, ?)", [year, last_modified])
107 except urllib.error.URLError as e:
108 cve_f.write('Warning: CVE db update error, CVE data is outdated.\n\n')
109 bb.warn("Cannot parse CVE data (%s), update failed" % e.reason)
110 return
111
112 # Update success, set the date to cve_check file.
113 if year == date.today().year:
114 cve_f.write('CVE database update : %s\n\n' % date.today())
115
116 cve_f.close()
117 conn.commit()
118 conn.close()
119}
120
121def initialize_db(c):
122 c.execute("CREATE TABLE IF NOT EXISTS META (YEAR INTEGER UNIQUE, DATE TEXT)")
123 c.execute("CREATE TABLE IF NOT EXISTS NVD (ID TEXT UNIQUE, SUMMARY TEXT, \
124 SCOREV2 TEXT, SCOREV3 TEXT, MODIFIED INTEGER, VECTOR TEXT)")
125 c.execute("CREATE TABLE IF NOT EXISTS PRODUCTS (ID TEXT, \
126 VENDOR TEXT, PRODUCT TEXT, VERSION_START TEXT, OPERATOR_START TEXT, \
127 VERSION_END TEXT, OPERATOR_END TEXT)")
128
129def parse_node_and_insert(c, node, cveId):
130 # Parse children node if needed
131 for child in node.get('children', ()):
132 parse_node_and_insert(c, child, cveId)
133
134 def cpe_generator():
135 for cpe in node.get('cpe_match', ()):
136 if not cpe['vulnerable']:
137 return
138 cpe23 = cpe['cpe23Uri'].split(':')
139 vendor = cpe23[3]
140 product = cpe23[4]
141 version = cpe23[5]
142
143 if version != '*':
144 # Version is defined, this is a '=' match
145 yield [cveId, vendor, product, version, '=', '', '']
146 else:
147 # Parse start version, end version and operators
148 op_start = ''
149 op_end = ''
150 v_start = ''
151 v_end = ''
152
153 if 'versionStartIncluding' in cpe:
154 op_start = '>='
155 v_start = cpe['versionStartIncluding']
156
157 if 'versionStartExcluding' in cpe:
158 op_start = '>'
159 v_start = cpe['versionStartExcluding']
160
161 if 'versionEndIncluding' in cpe:
162 op_end = '<='
163 v_end = cpe['versionEndIncluding']
164
165 if 'versionEndExcluding' in cpe:
166 op_end = '<'
167 v_end = cpe['versionEndExcluding']
168
169 yield [cveId, vendor, product, v_start, op_start, v_end, op_end]
170
171 c.executemany("insert into PRODUCTS values (?, ?, ?, ?, ?, ?, ?)", cpe_generator())
172
173def update_db(c, jsondata):
174 import json
175 root = json.loads(jsondata)
176
177 for elt in root['CVE_Items']:
178 if not elt['impact']:
179 continue
180
181 cveId = elt['cve']['CVE_data_meta']['ID']
182 cveDesc = elt['cve']['description']['description_data'][0]['value']
183 date = elt['lastModifiedDate']
184 accessVector = elt['impact']['baseMetricV2']['cvssV2']['accessVector']
185 cvssv2 = elt['impact']['baseMetricV2']['cvssV2']['baseScore']
186
187 try:
188 cvssv3 = elt['impact']['baseMetricV3']['cvssV3']['baseScore']
189 except:
190 cvssv3 = 0.0
191
192 c.execute("insert or replace into NVD values (?, ?, ?, ?, ?, ?)",
193 [cveId, cveDesc, cvssv2, cvssv3, date, accessVector])
194
195 configurations = elt['configurations']['nodes']
196 for config in configurations:
197 parse_node_and_insert(c, config, cveId)
198
199
200addtask do_populate_cve_db before do_fetch
201do_populate_cve_db[nostamp] = "1"
202
203EXCLUDE_FROM_WORLD = "1"