diff options
| -rw-r--r-- | meta/recipes-core/meta/cve-update-db-native.bb | 291 |
1 files changed, 291 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..e042e67b09 --- /dev/null +++ b/meta/recipes-core/meta/cve-update-db-native.bb | |||
| @@ -0,0 +1,291 @@ | |||
| 1 | SUMMARY = "Updates the NVD CVE database" | ||
| 2 | LICENSE = "MIT" | ||
| 3 | |||
| 4 | INHIBIT_DEFAULT_DEPS = "1" | ||
| 5 | |||
| 6 | inherit native | ||
| 7 | |||
| 8 | deltask do_unpack | ||
| 9 | deltask do_patch | ||
| 10 | deltask do_configure | ||
| 11 | deltask do_compile | ||
| 12 | deltask do_install | ||
| 13 | deltask do_populate_sysroot | ||
| 14 | |||
| 15 | NVDCVE_URL ?= "https://nvd.nist.gov/feeds/json/cve/1.1/nvdcve-1.1-" | ||
| 16 | # CVE database update interval, in seconds. By default: once a day (24*60*60). | ||
| 17 | # Use 0 to force the update | ||
| 18 | # Use a negative value to skip the update | ||
| 19 | CVE_DB_UPDATE_INTERVAL ?= "86400" | ||
| 20 | |||
| 21 | # Timeout for blocking socket operations, such as the connection attempt. | ||
| 22 | CVE_SOCKET_TIMEOUT ?= "60" | ||
| 23 | |||
| 24 | CVE_DB_TEMP_FILE ?= "${CVE_CHECK_DB_DIR}/temp_nvdcve_1.1.db" | ||
| 25 | |||
| 26 | python () { | ||
| 27 | if not bb.data.inherits_class("cve-check", d): | ||
| 28 | raise bb.parse.SkipRecipe("Skip recipe when cve-check class is not loaded.") | ||
| 29 | } | ||
| 30 | |||
| 31 | python do_fetch() { | ||
| 32 | """ | ||
| 33 | Update NVD database with json data feed | ||
| 34 | """ | ||
| 35 | import bb.utils | ||
| 36 | import bb.progress | ||
| 37 | import shutil | ||
| 38 | |||
| 39 | bb.utils.export_proxies(d) | ||
| 40 | |||
| 41 | db_file = d.getVar("CVE_CHECK_DB_FILE") | ||
| 42 | db_dir = os.path.dirname(db_file) | ||
| 43 | db_tmp_file = d.getVar("CVE_DB_TEMP_FILE") | ||
| 44 | |||
| 45 | cleanup_db_download(db_file, db_tmp_file) | ||
| 46 | |||
| 47 | # The NVD database changes once a day, so no need to update more frequently | ||
| 48 | # Allow the user to force-update | ||
| 49 | try: | ||
| 50 | import time | ||
| 51 | update_interval = int(d.getVar("CVE_DB_UPDATE_INTERVAL")) | ||
| 52 | if update_interval < 0: | ||
| 53 | bb.note("CVE database update skipped") | ||
| 54 | return | ||
| 55 | if time.time() - os.path.getmtime(db_file) < update_interval: | ||
| 56 | bb.debug(2, "Recently updated, skipping") | ||
| 57 | return | ||
| 58 | |||
| 59 | except OSError: | ||
| 60 | pass | ||
| 61 | |||
| 62 | bb.utils.mkdirhier(db_dir) | ||
| 63 | if os.path.exists(db_file): | ||
| 64 | shutil.copy2(db_file, db_tmp_file) | ||
| 65 | |||
| 66 | if update_db_file(db_tmp_file, d) == True: | ||
| 67 | # Update downloaded correctly, can swap files | ||
| 68 | shutil.move(db_tmp_file, db_file) | ||
| 69 | else: | ||
| 70 | # Update failed, do not modify the database | ||
| 71 | bb.note("CVE database update failed") | ||
| 72 | os.remove(db_tmp_file) | ||
| 73 | } | ||
| 74 | |||
| 75 | do_fetch[lockfiles] += "${CVE_CHECK_DB_FILE_LOCK}" | ||
| 76 | do_fetch[file-checksums] = "" | ||
| 77 | do_fetch[vardeps] = "" | ||
| 78 | |||
| 79 | def cleanup_db_download(db_file, db_tmp_file): | ||
| 80 | """ | ||
| 81 | Cleanup the download space from possible failed downloads | ||
| 82 | """ | ||
| 83 | |||
| 84 | # Clean up the updates done on the main file | ||
| 85 | # Remove it only if a journal file exists - it means a complete re-download | ||
| 86 | if os.path.exists("{0}-journal".format(db_file)): | ||
| 87 | # If a journal is present the last update might have been interrupted. In that case, | ||
| 88 | # just wipe any leftovers and force the DB to be recreated. | ||
| 89 | os.remove("{0}-journal".format(db_file)) | ||
| 90 | |||
| 91 | if os.path.exists(db_file): | ||
| 92 | os.remove(db_file) | ||
| 93 | |||
| 94 | # Clean-up the temporary file downloads, we can remove both journal | ||
| 95 | # and the temporary database | ||
| 96 | if os.path.exists("{0}-journal".format(db_tmp_file)): | ||
| 97 | # If a journal is present the last update might have been interrupted. In that case, | ||
| 98 | # just wipe any leftovers and force the DB to be recreated. | ||
| 99 | os.remove("{0}-journal".format(db_tmp_file)) | ||
| 100 | |||
| 101 | if os.path.exists(db_tmp_file): | ||
| 102 | os.remove(db_tmp_file) | ||
| 103 | |||
| 104 | def update_db_file(db_tmp_file, d): | ||
| 105 | """ | ||
| 106 | Update the given database file | ||
| 107 | """ | ||
| 108 | import bb.utils, bb.progress | ||
| 109 | from datetime import date | ||
| 110 | import urllib, gzip, sqlite3 | ||
| 111 | |||
| 112 | YEAR_START = 2002 | ||
| 113 | cve_socket_timeout = int(d.getVar("CVE_SOCKET_TIMEOUT")) | ||
| 114 | |||
| 115 | # Connect to database | ||
| 116 | conn = sqlite3.connect(db_tmp_file) | ||
| 117 | initialize_db(conn) | ||
| 118 | |||
| 119 | with bb.progress.ProgressHandler(d) as ph, open(os.path.join(d.getVar("TMPDIR"), 'cve_check'), 'a') as cve_f: | ||
| 120 | total_years = date.today().year + 1 - YEAR_START | ||
| 121 | for i, year in enumerate(range(YEAR_START, date.today().year + 1)): | ||
| 122 | bb.debug(2, "Updating %d" % year) | ||
| 123 | ph.update((float(i + 1) / total_years) * 100) | ||
| 124 | year_url = (d.getVar('NVDCVE_URL')) + str(year) | ||
| 125 | meta_url = year_url + ".meta" | ||
| 126 | json_url = year_url + ".json.gz" | ||
| 127 | |||
| 128 | # Retrieve meta last modified date | ||
| 129 | try: | ||
| 130 | response = urllib.request.urlopen(meta_url, timeout=cve_socket_timeout) | ||
| 131 | except urllib.error.URLError as e: | ||
| 132 | cve_f.write('Warning: CVE db update error, Unable to fetch CVE data.\n\n') | ||
| 133 | bb.warn("Failed to fetch CVE data (%s)" % e) | ||
| 134 | import socket | ||
| 135 | result = socket.getaddrinfo("nvd.nist.gov", 443, proto=socket.IPPROTO_TCP) | ||
| 136 | bb.warn("Host IPs are %s" % (", ".join(t[4][0] for t in result))) | ||
| 137 | return False | ||
| 138 | |||
| 139 | if response: | ||
| 140 | for l in response.read().decode("utf-8").splitlines(): | ||
| 141 | key, value = l.split(":", 1) | ||
| 142 | if key == "lastModifiedDate": | ||
| 143 | last_modified = value | ||
| 144 | break | ||
| 145 | else: | ||
| 146 | bb.warn("Cannot parse CVE metadata, update failed") | ||
| 147 | return False | ||
| 148 | |||
| 149 | # Compare with current db last modified date | ||
| 150 | cursor = conn.execute("select DATE from META where YEAR = ?", (year,)) | ||
| 151 | meta = cursor.fetchone() | ||
| 152 | cursor.close() | ||
| 153 | |||
| 154 | if not meta or meta[0] != last_modified: | ||
| 155 | bb.debug(2, "Updating entries") | ||
| 156 | # Clear products table entries corresponding to current year | ||
| 157 | conn.execute("delete from PRODUCTS where ID like ?", ('CVE-%d%%' % year,)).close() | ||
| 158 | |||
| 159 | # Update db with current year json file | ||
| 160 | try: | ||
| 161 | response = urllib.request.urlopen(json_url, timeout=cve_socket_timeout) | ||
| 162 | if response: | ||
| 163 | update_db(conn, gzip.decompress(response.read()).decode('utf-8')) | ||
| 164 | conn.execute("insert or replace into META values (?, ?)", [year, last_modified]).close() | ||
| 165 | except urllib.error.URLError as e: | ||
| 166 | cve_f.write('Warning: CVE db update error, CVE data is outdated.\n\n') | ||
| 167 | bb.warn("Cannot parse CVE data (%s), update failed" % e.reason) | ||
| 168 | return False | ||
| 169 | else: | ||
| 170 | bb.debug(2, "Already up to date (last modified %s)" % last_modified) | ||
| 171 | # Update success, set the date to cve_check file. | ||
| 172 | if year == date.today().year: | ||
| 173 | cve_f.write('CVE database update : %s\n\n' % date.today()) | ||
| 174 | |||
| 175 | conn.commit() | ||
| 176 | conn.close() | ||
| 177 | return True | ||
| 178 | |||
| 179 | def initialize_db(conn): | ||
| 180 | with conn: | ||
| 181 | c = conn.cursor() | ||
| 182 | |||
| 183 | c.execute("CREATE TABLE IF NOT EXISTS META (YEAR INTEGER UNIQUE, DATE TEXT)") | ||
| 184 | |||
| 185 | c.execute("CREATE TABLE IF NOT EXISTS NVD (ID TEXT UNIQUE, SUMMARY TEXT, \ | ||
| 186 | SCOREV2 TEXT, SCOREV3 TEXT, MODIFIED INTEGER, VECTOR TEXT)") | ||
| 187 | |||
| 188 | c.execute("CREATE TABLE IF NOT EXISTS PRODUCTS (ID TEXT, \ | ||
| 189 | VENDOR TEXT, PRODUCT TEXT, VERSION_START TEXT, OPERATOR_START TEXT, \ | ||
| 190 | VERSION_END TEXT, OPERATOR_END TEXT)") | ||
| 191 | c.execute("CREATE INDEX IF NOT EXISTS PRODUCT_ID_IDX on PRODUCTS(ID);") | ||
| 192 | |||
| 193 | c.close() | ||
| 194 | |||
| 195 | def parse_node_and_insert(conn, node, cveId): | ||
| 196 | # Parse children node if needed | ||
| 197 | for child in node.get('children', ()): | ||
| 198 | parse_node_and_insert(conn, child, cveId) | ||
| 199 | |||
| 200 | def cpe_generator(): | ||
| 201 | for cpe in node.get('cpe_match', ()): | ||
| 202 | if not cpe['vulnerable']: | ||
| 203 | return | ||
| 204 | cpe23 = cpe.get('cpe23Uri') | ||
| 205 | if not cpe23: | ||
| 206 | return | ||
| 207 | cpe23 = cpe23.split(':') | ||
| 208 | if len(cpe23) < 6: | ||
| 209 | return | ||
| 210 | vendor = cpe23[3] | ||
| 211 | product = cpe23[4] | ||
| 212 | version = cpe23[5] | ||
| 213 | |||
| 214 | if cpe23[6] == '*' or cpe23[6] == '-': | ||
| 215 | version_suffix = "" | ||
| 216 | else: | ||
| 217 | version_suffix = "_" + cpe23[6] | ||
| 218 | |||
| 219 | if version != '*' and version != '-': | ||
| 220 | # Version is defined, this is a '=' match | ||
| 221 | yield [cveId, vendor, product, version + version_suffix, '=', '', ''] | ||
| 222 | elif version == '-': | ||
| 223 | # no version information is available | ||
| 224 | yield [cveId, vendor, product, version, '', '', ''] | ||
| 225 | else: | ||
| 226 | # Parse start version, end version and operators | ||
| 227 | op_start = '' | ||
| 228 | op_end = '' | ||
| 229 | v_start = '' | ||
| 230 | v_end = '' | ||
| 231 | |||
| 232 | if 'versionStartIncluding' in cpe: | ||
| 233 | op_start = '>=' | ||
| 234 | v_start = cpe['versionStartIncluding'] | ||
| 235 | |||
| 236 | if 'versionStartExcluding' in cpe: | ||
| 237 | op_start = '>' | ||
| 238 | v_start = cpe['versionStartExcluding'] | ||
| 239 | |||
| 240 | if 'versionEndIncluding' in cpe: | ||
| 241 | op_end = '<=' | ||
| 242 | v_end = cpe['versionEndIncluding'] | ||
| 243 | |||
| 244 | if 'versionEndExcluding' in cpe: | ||
| 245 | op_end = '<' | ||
| 246 | v_end = cpe['versionEndExcluding'] | ||
| 247 | |||
| 248 | if op_start or op_end or v_start or v_end: | ||
| 249 | yield [cveId, vendor, product, v_start, op_start, v_end, op_end] | ||
| 250 | else: | ||
| 251 | # This is no version information, expressed differently. | ||
| 252 | # Save processing by representing as -. | ||
| 253 | yield [cveId, vendor, product, '-', '', '', ''] | ||
| 254 | |||
| 255 | conn.executemany("insert into PRODUCTS values (?, ?, ?, ?, ?, ?, ?)", cpe_generator()).close() | ||
| 256 | |||
| 257 | def update_db(conn, jsondata): | ||
| 258 | import json | ||
| 259 | root = json.loads(jsondata) | ||
| 260 | |||
| 261 | for elt in root['CVE_Items']: | ||
| 262 | if not elt['impact']: | ||
| 263 | continue | ||
| 264 | |||
| 265 | accessVector = None | ||
| 266 | cveId = elt['cve']['CVE_data_meta']['ID'] | ||
| 267 | cveDesc = elt['cve']['description']['description_data'][0]['value'] | ||
| 268 | date = elt['lastModifiedDate'] | ||
| 269 | try: | ||
| 270 | accessVector = elt['impact']['baseMetricV2']['cvssV2']['accessVector'] | ||
| 271 | cvssv2 = elt['impact']['baseMetricV2']['cvssV2']['baseScore'] | ||
| 272 | except KeyError: | ||
| 273 | cvssv2 = 0.0 | ||
| 274 | try: | ||
| 275 | accessVector = accessVector or elt['impact']['baseMetricV3']['cvssV3']['attackVector'] | ||
| 276 | cvssv3 = elt['impact']['baseMetricV3']['cvssV3']['baseScore'] | ||
| 277 | except KeyError: | ||
| 278 | accessVector = accessVector or "UNKNOWN" | ||
| 279 | cvssv3 = 0.0 | ||
| 280 | |||
| 281 | conn.execute("insert or replace into NVD values (?, ?, ?, ?, ?, ?)", | ||
| 282 | [cveId, cveDesc, cvssv2, cvssv3, date, accessVector]).close() | ||
| 283 | |||
| 284 | configurations = elt['configurations']['nodes'] | ||
| 285 | for config in configurations: | ||
| 286 | parse_node_and_insert(conn, config, cveId) | ||
| 287 | |||
| 288 | |||
| 289 | do_fetch[nostamp] = "1" | ||
| 290 | |||
| 291 | EXCLUDE_FROM_WORLD = "1" | ||
