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.bb190
1 files changed, 190 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..e9a023e9bd
--- /dev/null
+++ b/meta/recipes-core/meta/cve-update-db-native.bb
@@ -0,0 +1,190 @@
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 import bb.utils
25 import sqlite3, urllib, urllib.parse, shutil, gzip
26 from datetime import date
27
28 bb.utils.export_proxies(d)
29
30 BASE_URL = "https://nvd.nist.gov/feeds/json/cve/1.0/nvdcve-1.0-"
31 YEAR_START = 2002
32
33 db_file = d.getVar("CVE_CHECK_DB_FILE")
34 db_dir = os.path.dirname(db_file)
35 json_tmpfile = os.path.join(db_dir, 'nvd.json.gz')
36
37 # Don't refresh the database more than once an hour
38 try:
39 import time
40 if time.time() - os.path.getmtime(db_file) < (60*60):
41 return
42 except OSError:
43 pass
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 response = urllib.request.urlopen(meta_url)
63 if response:
64 for l in response.read().decode("utf-8").splitlines():
65 key, value = l.split(":", 1)
66 if key == "lastModifiedDate":
67 last_modified = value
68 break
69 else:
70 bb.warn("Cannot parse CVE metadata, update failed")
71 return
72
73 # Compare with current db last modified date
74 c.execute("select DATE from META where YEAR = ?", (year,))
75 meta = c.fetchone()
76 if not meta or meta[0] != last_modified:
77 # Clear products table entries corresponding to current year
78 c.execute("delete from PRODUCTS where ID like ?", ('CVE-%d%%' % year,))
79
80 # Update db with current year json file
81 try:
82 response = urllib.request.urlopen(json_url)
83 if response:
84 update_db(c, gzip.decompress(response.read()).decode('utf-8'))
85 c.execute("insert or replace into META values (?, ?)", [year, last_modified])
86 except urllib.error.URLError as e:
87 cve_f.write('Warning: CVE db update error, CVE data is outdated.\n\n')
88 bb.warn("Cannot parse CVE data (%s), update failed" % e.reason)
89 return
90
91 # Update success, set the date to cve_check file.
92 if year == date.today().year:
93 cve_f.write('CVE database update : %s\n\n' % date.today())
94
95 cve_f.close()
96 conn.commit()
97 conn.close()
98}
99
100def initialize_db(c):
101 c.execute("CREATE TABLE IF NOT EXISTS META (YEAR INTEGER UNIQUE, DATE TEXT)")
102
103 c.execute("CREATE TABLE IF NOT EXISTS NVD (ID TEXT UNIQUE, SUMMARY TEXT, \
104 SCOREV2 TEXT, SCOREV3 TEXT, MODIFIED INTEGER, VECTOR TEXT)")
105
106 c.execute("CREATE TABLE IF NOT EXISTS PRODUCTS (ID TEXT, \
107 VENDOR TEXT, PRODUCT TEXT, VERSION_START TEXT, OPERATOR_START TEXT, \
108 VERSION_END TEXT, OPERATOR_END TEXT)")
109 c.execute("CREATE INDEX IF NOT EXISTS PRODUCT_ID_IDX on PRODUCTS(ID);")
110
111def parse_node_and_insert(c, node, cveId):
112 # Parse children node if needed
113 for child in node.get('children', ()):
114 parse_node_and_insert(c, child, cveId)
115
116 def cpe_generator():
117 for cpe in node.get('cpe_match', ()):
118 if not cpe['vulnerable']:
119 return
120 cpe23 = cpe['cpe23Uri'].split(':')
121 vendor = cpe23[3]
122 product = cpe23[4]
123 version = cpe23[5]
124
125 if version != '*':
126 # Version is defined, this is a '=' match
127 yield [cveId, vendor, product, version, '=', '', '']
128 else:
129 # Parse start version, end version and operators
130 op_start = ''
131 op_end = ''
132 v_start = ''
133 v_end = ''
134
135 if 'versionStartIncluding' in cpe:
136 op_start = '>='
137 v_start = cpe['versionStartIncluding']
138
139 if 'versionStartExcluding' in cpe:
140 op_start = '>'
141 v_start = cpe['versionStartExcluding']
142
143 if 'versionEndIncluding' in cpe:
144 op_end = '<='
145 v_end = cpe['versionEndIncluding']
146
147 if 'versionEndExcluding' in cpe:
148 op_end = '<'
149 v_end = cpe['versionEndExcluding']
150
151 yield [cveId, vendor, product, v_start, op_start, v_end, op_end]
152
153 c.executemany("insert into PRODUCTS values (?, ?, ?, ?, ?, ?, ?)", cpe_generator())
154
155def update_db(c, jsondata):
156 import json
157 root = json.loads(jsondata)
158
159 for elt in root['CVE_Items']:
160 if not elt['impact']:
161 continue
162
163 accessVector = None
164 cveId = elt['cve']['CVE_data_meta']['ID']
165 cveDesc = elt['cve']['description']['description_data'][0]['value']
166 date = elt['lastModifiedDate']
167 try:
168 accessVector = elt['impact']['baseMetricV2']['cvssV2']['accessVector']
169 cvssv2 = elt['impact']['baseMetricV2']['cvssV2']['baseScore']
170 except KeyError:
171 cvssv2 = 0.0
172 try:
173 accessVector = accessVector or elt['impact']['baseMetricV3']['cvssV3']['attackVector']
174 cvssv3 = elt['impact']['baseMetricV3']['cvssV3']['baseScore']
175 except KeyError:
176 accessVector = accessVector or "UNKNOWN"
177 cvssv3 = 0.0
178
179 c.execute("insert or replace into NVD values (?, ?, ?, ?, ?, ?)",
180 [cveId, cveDesc, cvssv2, cvssv3, date, accessVector])
181
182 configurations = elt['configurations']['nodes']
183 for config in configurations:
184 parse_node_and_insert(c, config, cveId)
185
186
187addtask do_populate_cve_db before do_fetch
188do_populate_cve_db[nostamp] = "1"
189
190EXCLUDE_FROM_WORLD = "1"