summaryrefslogtreecommitdiffstats
path: root/meta/recipes-core/meta/cve-update-db-native.bb
diff options
context:
space:
mode:
Diffstat (limited to 'meta/recipes-core/meta/cve-update-db-native.bb')
-rw-r--r--meta/recipes-core/meta/cve-update-db-native.bb195
1 files changed, 195 insertions, 0 deletions
diff --git a/meta/recipes-core/meta/cve-update-db-native.bb b/meta/recipes-core/meta/cve-update-db-native.bb
new file mode 100644
index 0000000000..2c427a5884
--- /dev/null
+++ b/meta/recipes-core/meta/cve-update-db-native.bb
@@ -0,0 +1,195 @@
1SUMMARY = "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
25 import sqlite3, urllib, urllib.parse, shutil, gzip
26 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')
34 proxy = d.getVar("https_proxy")
35
36 if proxy:
37 # instantiate an opener but do not install it as the global
38 # opener unless if we're really sure it's applicable for all
39 # urllib requests
40 proxy_handler = urllib.request.ProxyHandler({'https': proxy})
41 proxy_opener = urllib.request.build_opener(proxy_handler)
42 else:
43 proxy_opener = None
44
45 cve_f = open(os.path.join(d.getVar("TMPDIR"), 'cve_check'), 'a')
46
47 if not os.path.isdir(db_dir):
48 os.mkdir(db_dir)
49
50 # Connect to database
51 conn = sqlite3.connect(db_file)
52 c = conn.cursor()
53
54 initialize_db(c)
55
56 for year in range(YEAR_START, date.today().year + 1):
57 year_url = BASE_URL + str(year)
58 meta_url = year_url + ".meta"
59 json_url = year_url + ".json.gz"
60
61 # Retrieve meta last modified date
62
63 response = None
64
65 if proxy_opener:
66 response = proxy_opener.open(meta_url)
67 else:
68 req = urllib.request.Request(meta_url)
69 response = urllib.request.urlopen(req)
70
71 if response:
72 for l in response.read().decode("utf-8").splitlines():
73 key, value = l.split(":", 1)
74 if key == "lastModifiedDate":
75 last_modified = value
76 break
77 else:
78 bb.warn("Cannot parse CVE metadata, update failed")
79 return
80
81 # Compare with current db last modified date
82 c.execute("select DATE from META where YEAR = ?", (year,))
83 meta = c.fetchone()
84 if not meta or meta[0] != last_modified:
85 # Clear products table entries corresponding to current year
86 c.execute("delete from PRODUCTS where ID like ?", ('CVE-%d%%' % year,))
87
88 # Update db with current year json file
89 try:
90 if proxy_opener:
91 response = proxy_opener.open(json_url)
92 else:
93 req = urllib.request.Request(json_url)
94 response = urllib.request.urlopen(req)
95
96 if response:
97 update_db(c, gzip.decompress(response.read()).decode('utf-8'))
98 c.execute("insert or replace into META values (?, ?)", [year, last_modified])
99 except urllib.error.URLError as e:
100 cve_f.write('Warning: CVE db update error, CVE data is outdated.\n\n')
101 bb.warn("Cannot parse CVE data (%s), update failed" % e.reason)
102 return
103
104 # Update success, set the date to cve_check file.
105 if year == date.today().year:
106 cve_f.write('CVE database update : %s\n\n' % date.today())
107
108 cve_f.close()
109 conn.commit()
110 conn.close()
111}
112
113def initialize_db(c):
114 c.execute("CREATE TABLE IF NOT EXISTS META (YEAR INTEGER UNIQUE, DATE TEXT)")
115 c.execute("CREATE TABLE IF NOT EXISTS NVD (ID TEXT UNIQUE, SUMMARY TEXT, \
116 SCOREV2 TEXT, SCOREV3 TEXT, MODIFIED INTEGER, VECTOR TEXT)")
117 c.execute("CREATE TABLE IF NOT EXISTS PRODUCTS (ID TEXT, \
118 VENDOR TEXT, PRODUCT TEXT, VERSION_START TEXT, OPERATOR_START TEXT, \
119 VERSION_END TEXT, OPERATOR_END TEXT)")
120
121def parse_node_and_insert(c, node, cveId):
122 # Parse children node if needed
123 for child in node.get('children', ()):
124 parse_node_and_insert(c, child, cveId)
125
126 def cpe_generator():
127 for cpe in node.get('cpe_match', ()):
128 if not cpe['vulnerable']:
129 return
130 cpe23 = cpe['cpe23Uri'].split(':')
131 vendor = cpe23[3]
132 product = cpe23[4]
133 version = cpe23[5]
134
135 if version != '*':
136 # Version is defined, this is a '=' match
137 yield [cveId, vendor, product, version, '=', '', '']
138 else:
139 # Parse start version, end version and operators
140 op_start = ''
141 op_end = ''
142 v_start = ''
143 v_end = ''
144
145 if 'versionStartIncluding' in cpe:
146 op_start = '>='
147 v_start = cpe['versionStartIncluding']
148
149 if 'versionStartExcluding' in cpe:
150 op_start = '>'
151 v_start = cpe['versionStartExcluding']
152
153 if 'versionEndIncluding' in cpe:
154 op_end = '<='
155 v_end = cpe['versionEndIncluding']
156
157 if 'versionEndExcluding' in cpe:
158 op_end = '<'
159 v_end = cpe['versionEndExcluding']
160
161 yield [cveId, vendor, product, v_start, op_start, v_end, op_end]
162
163 c.executemany("insert into PRODUCTS values (?, ?, ?, ?, ?, ?, ?)", cpe_generator())
164
165def update_db(c, jsondata):
166 import json
167 root = json.loads(jsondata)
168
169 for elt in root['CVE_Items']:
170 if not elt['impact']:
171 continue
172
173 cveId = elt['cve']['CVE_data_meta']['ID']
174 cveDesc = elt['cve']['description']['description_data'][0]['value']
175 date = elt['lastModifiedDate']
176 accessVector = elt['impact']['baseMetricV2']['cvssV2']['accessVector']
177 cvssv2 = elt['impact']['baseMetricV2']['cvssV2']['baseScore']
178
179 try:
180 cvssv3 = elt['impact']['baseMetricV3']['cvssV3']['baseScore']
181 except:
182 cvssv3 = 0.0
183
184 c.execute("insert or replace into NVD values (?, ?, ?, ?, ?, ?)",
185 [cveId, cveDesc, cvssv2, cvssv3, date, accessVector])
186
187 configurations = elt['configurations']['nodes']
188 for config in configurations:
189 parse_node_and_insert(c, config, cveId)
190
191
192addtask do_populate_cve_db before do_fetch
193do_populate_cve_db[nostamp] = "1"
194
195EXCLUDE_FROM_WORLD = "1"