diff options
Diffstat (limited to 'meta/classes/cve-check.bbclass')
-rw-r--r-- | meta/classes/cve-check.bbclass | 271 |
1 files changed, 165 insertions, 106 deletions
diff --git a/meta/classes/cve-check.bbclass b/meta/classes/cve-check.bbclass index 8251ca7c97..01b3637469 100644 --- a/meta/classes/cve-check.bbclass +++ b/meta/classes/cve-check.bbclass @@ -20,11 +20,15 @@ # the only method to check against CVEs. Running this tool # doesn't guarantee your packages are free of CVEs. +# The product name that the CVE database uses. Defaults to BPN, but may need to +# be overriden per recipe (for example tiff.bb sets CVE_PRODUCT=libtiff). +CVE_PRODUCT ??= "${BPN}" +CVE_VERSION ??= "${PV}" + CVE_CHECK_DB_DIR ?= "${DL_DIR}/CVE_CHECK" -CVE_CHECK_DB_FILE ?= "${CVE_CHECK_DB_DIR}/nvd.db" +CVE_CHECK_DB_FILE ?= "${CVE_CHECK_DB_DIR}/nvdcve_1.1.db" -CVE_CHECK_LOCAL_DIR ?= "${WORKDIR}/cve" -CVE_CHECK_LOCAL_FILE ?= "${CVE_CHECK_LOCAL_DIR}/cve.log" +CVE_CHECK_LOG ?= "${T}/cve.log" CVE_CHECK_TMP_FILE ?= "${TMPDIR}/cve_check" CVE_CHECK_DIR ??= "${DEPLOY_DIR}/cve" @@ -33,40 +37,40 @@ CVE_CHECK_COPY_FILES ??= "1" CVE_CHECK_CREATE_MANIFEST ??= "1" # Whitelist for packages (PN) -CVE_CHECK_PN_WHITELIST = "\ - glibc-locale \ -" +CVE_CHECK_PN_WHITELIST ?= "" -# Whitelist for CVE and version of package -CVE_CHECK_CVE_WHITELIST = "{\ - 'CVE-2014-2524': ('6.3',), \ -}" +# Whitelist for CVE. If a CVE is found, then it is considered patched. +# The value is a string containing space separated CVE values: +# +# CVE_CHECK_WHITELIST = 'CVE-2014-2524 CVE-2018-1234' +# +CVE_CHECK_WHITELIST ?= "" python do_cve_check () { """ Check recipe for patched and unpatched CVEs """ - if os.path.exists(d.getVar("CVE_CHECK_TMP_FILE", True)): + if os.path.exists(d.getVar("CVE_CHECK_DB_FILE")): patched_cves = get_patches_cves(d) patched, unpatched = check_cves(d, patched_cves) if patched or unpatched: cve_data = get_cve_info(d, patched + unpatched) cve_write_data(d, patched, unpatched, cve_data) else: - bb.note("Failed to update CVE database, skipping CVE check") + bb.note("No CVE database found, skipping CVE check") + } -addtask cve_check after do_unpack before do_build -do_cve_check[depends] = "cve-check-tool-native:do_populate_cve_db" +addtask cve_check before do_build +do_cve_check[depends] = "cve-update-db-native:do_populate_cve_db" do_cve_check[nostamp] = "1" python cve_check_cleanup () { """ Delete the file used to gather all the CVE information. """ - - bb.utils.remove(e.data.getVar("CVE_CHECK_TMP_FILE", True)) + bb.utils.remove(e.data.getVar("CVE_CHECK_TMP_FILE")) } addhandler cve_check_cleanup @@ -79,12 +83,17 @@ python cve_check_write_rootfs_manifest () { import shutil - if os.path.exists(d.getVar("CVE_CHECK_TMP_FILE", True)): + if d.getVar("CVE_CHECK_COPY_FILES") == "1": + deploy_file = os.path.join(d.getVar("CVE_CHECK_DIR"), d.getVar("PN")) + if os.path.exists(deploy_file): + bb.utils.remove(deploy_file) + + if os.path.exists(d.getVar("CVE_CHECK_TMP_FILE")): bb.note("Writing rootfs CVE manifest") - deploy_dir = d.getVar("DEPLOY_DIR_IMAGE", True) - link_name = d.getVar("IMAGE_LINK_NAME", True) - manifest_name = d.getVar("CVE_CHECK_MANIFEST", True) - cve_tmp_file = d.getVar("CVE_CHECK_TMP_FILE", True) + deploy_dir = d.getVar("DEPLOY_DIR_IMAGE") + link_name = d.getVar("IMAGE_LINK_NAME") + manifest_name = d.getVar("CVE_CHECK_MANIFEST") + cve_tmp_file = d.getVar("CVE_CHECK_TMP_FILE") shutil.copyfile(cve_tmp_file, manifest_name) @@ -92,14 +101,13 @@ python cve_check_write_rootfs_manifest () { manifest_link = os.path.join(deploy_dir, "%s.cve" % link_name) # If we already have another manifest, update symlinks if os.path.exists(os.path.realpath(manifest_link)): - if d.getVar('RM_OLD_IMAGE', True) == "1": - os.remove(os.path.realpath(manifest_link)) os.remove(manifest_link) os.symlink(os.path.basename(manifest_name), manifest_link) bb.plain("Image CVE report stored in: %s" % manifest_name) } -ROOTFS_POSTPROCESS_COMMAND_prepend = "${@'cve_check_write_rootfs_manifest; ' if d.getVar('CVE_CHECK_CREATE_MANIFEST', True) == '1' else ''}" +ROOTFS_POSTPROCESS_COMMAND_prepend = "${@'cve_check_write_rootfs_manifest; ' if d.getVar('CVE_CHECK_CREATE_MANIFEST') == '1' else ''}" +do_rootfs[recrdeptask] += "${@'do_cve_check' if d.getVar('CVE_CHECK_CREATE_MANIFEST') == '1' else ''}" def get_patches_cves(d): """ @@ -108,12 +116,26 @@ def get_patches_cves(d): import re - pn = d.getVar("PN", True) + pn = d.getVar("PN") cve_match = re.compile("CVE:( CVE\-\d{4}\-\d+)+") + + # Matches last CVE-1234-211432 in the file name, also if written + # with small letters. Not supporting multiple CVE id's in a single + # file name. + cve_file_name_match = re.compile(".*([Cc][Vv][Ee]\-\d{4}\-\d+)") + patched_cves = set() bb.debug(2, "Looking for patches that solves CVEs for %s" % pn) for url in src_patches(d): patch_file = bb.fetch.decodeurl(url)[2] + + # Check patch file name for CVE ID + fname_match = cve_file_name_match.search(patch_file) + if fname_match: + cve = fname_match.group(1).upper() + patched_cves.add(cve) + bb.debug(2, "Found CVE %s from patch file name %s" % (cve, patch_file)) + with open(patch_file, "r", encoding="utf-8") as f: try: patch_text = f.read() @@ -124,103 +146,138 @@ def get_patches_cves(d): with open(patch_file, "r", encoding="iso8859-1") as f: patch_text = f.read() - # Search for the "CVE: " line - match = cve_match.search(patch_text) - if match: + # Search for one or more "CVE: " lines + text_match = False + for match in cve_match.finditer(patch_text): # Get only the CVEs without the "CVE: " tag cves = patch_text[match.start()+5:match.end()] for cve in cves.split(): bb.debug(2, "Patch %s solves %s" % (patch_file, cve)) patched_cves.add(cve) - else: + text_match = True + + if not fname_match and not text_match: bb.debug(2, "Patch %s doesn't solve CVEs" % patch_file) return patched_cves def check_cves(d, patched_cves): """ - Run cve-check-tool looking for patched and unpatched CVEs. + Connect to the NVD database and find unpatched cves. """ + from distutils.version import LooseVersion - import ast, csv, tempfile, subprocess, io - - cves_patched = [] cves_unpatched = [] - bpn = d.getVar("BPN", True) - pv = d.getVar("PV", True).split("git+")[0] - cves = " ".join(patched_cves) - cve_db_dir = d.getVar("CVE_CHECK_DB_DIR", True) - cve_whitelist = ast.literal_eval(d.getVar("CVE_CHECK_CVE_WHITELIST", True)) - cve_cmd = "cve-check-tool" - cmd = [cve_cmd, "--no-html", "--csv", "--not-affected", "-t", "faux", "-d", cve_db_dir] + # CVE_PRODUCT can contain more than one product (eg. curl/libcurl) + products = d.getVar("CVE_PRODUCT").split() + # If this has been unset then we're not scanning for CVEs here (for example, image recipes) + if not products: + return ([], []) + pv = d.getVar("CVE_VERSION").split("+git")[0] # If the recipe has been whitlisted we return empty lists - if d.getVar("PN", True) in d.getVar("CVE_CHECK_PN_WHITELIST", True).split(): + if d.getVar("PN") in d.getVar("CVE_CHECK_PN_WHITELIST").split(): bb.note("Recipe has been whitelisted, skipping check") return ([], []) - # It is needed to export the proxies to download the database using HTTP - bb.utils.export_proxies(d) - - try: - # Write the faux CSV file to be used with cve-check-tool - fd, faux = tempfile.mkstemp(prefix="cve-faux-") - with os.fdopen(fd, "w") as f: - f.write("%s,%s,%s," % (bpn, pv, cves)) - cmd.append(faux) - - output = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode("utf-8") - bb.debug(2, "Output of command %s:\n%s" % ("\n".join(cmd), output)) - except subprocess.CalledProcessError as e: - bb.warn("Couldn't check for CVEs: %s (output %s)" % (e, e.output)) - finally: - os.remove(faux) - - for row in csv.reader(io.StringIO(output)): - # Third row has the unpatched CVEs - if row[2]: - for cve in row[2].split(): - # Skip if the CVE has been whitlisted for the current version - if pv in cve_whitelist.get(cve,[]): - bb.note("%s-%s has been whitelisted for %s" % (bpn, pv, cve)) + old_cve_whitelist = d.getVar("CVE_CHECK_CVE_WHITELIST") + if old_cve_whitelist: + bb.warn("CVE_CHECK_CVE_WHITELIST is deprecated, please use CVE_CHECK_WHITELIST.") + cve_whitelist = d.getVar("CVE_CHECK_WHITELIST").split() + + import sqlite3 + db_file = d.expand("file:${CVE_CHECK_DB_FILE}?mode=ro") + conn = sqlite3.connect(db_file, uri=True) + + # For each of the known product names (e.g. curl has CPEs using curl and libcurl)... + for product in products: + if ":" in product: + vendor, product = product.split(":", 1) + else: + vendor = "%" + + # Find all relevant CVE IDs. + for cverow in conn.execute("SELECT DISTINCT ID FROM PRODUCTS WHERE PRODUCT IS ? AND VENDOR LIKE ?", (product, vendor)): + cve = cverow[0] + + if cve in cve_whitelist: + bb.note("%s-%s has been whitelisted for %s" % (product, pv, cve)) + # TODO: this should be in the report as 'whitelisted' + patched_cves.add(cve) + continue + elif cve in patched_cves: + bb.note("%s has been patched" % (cve)) + continue + + vulnerable = False + for row in conn.execute("SELECT * FROM PRODUCTS WHERE ID IS ? AND PRODUCT IS ? AND VENDOR LIKE ?", (cve, product, vendor)): + (_, _, _, version_start, operator_start, version_end, operator_end) = row + #bb.debug(2, "Evaluating row " + str(row)) + + if (operator_start == '=' and pv == version_start): + vulnerable = True else: + if operator_start: + try: + vulnerable_start = (operator_start == '>=' and LooseVersion(pv) >= LooseVersion(version_start)) + vulnerable_start |= (operator_start == '>' and LooseVersion(pv) > LooseVersion(version_start)) + except: + bb.warn("%s: Failed to compare %s %s %s for %s" % + (product, pv, operator_start, version_start, cve)) + vulnerable_start = False + else: + vulnerable_start = False + + if operator_end: + try: + vulnerable_end = (operator_end == '<=' and LooseVersion(pv) <= LooseVersion(version_end)) + vulnerable_end |= (operator_end == '<' and LooseVersion(pv) < LooseVersion(version_end)) + except: + bb.warn("%s: Failed to compare %s %s %s for %s" % + (product, pv, operator_end, version_end, cve)) + vulnerable_end = False + else: + vulnerable_end = False + + if operator_start and operator_end: + vulnerable = vulnerable_start and vulnerable_end + else: + vulnerable = vulnerable_start or vulnerable_end + + if vulnerable: + bb.note("%s-%s is vulnerable to %s" % (product, pv, cve)) cves_unpatched.append(cve) - bb.debug(2, "%s-%s is not patched for %s" % (bpn, pv, cve)) - # Fourth row has patched CVEs - if row[3]: - for cve in row[3].split(): - cves_patched.append(cve) - bb.debug(2, "%s-%s is patched for %s" % (bpn, pv, cve)) + break - return (cves_patched, cves_unpatched) + if not vulnerable: + bb.note("%s-%s is not vulnerable to %s" % (product, pv, cve)) + # TODO: not patched but not vulnerable + patched_cves.add(cve) + + conn.close() + + return (list(patched_cves), cves_unpatched) def get_cve_info(d, cves): """ - Get CVE information from the database used by cve-check-tool. - - Unfortunately the only way to get CVE info is set the output to - html (hard to parse) or query directly the database. + Get CVE information from the database. """ - try: - import sqlite3 - except ImportError: - from pysqlite2 import dbapi2 as sqlite3 + import sqlite3 cve_data = {} - db_file = d.getVar("CVE_CHECK_DB_FILE", True) - placeholder = ",".join("?" * len(cves)) - query = "SELECT * FROM NVD WHERE id IN (%s)" % placeholder - conn = sqlite3.connect(db_file) - cur = conn.cursor() - for row in cur.execute(query, tuple(cves)): - cve_data[row[0]] = {} - cve_data[row[0]]["summary"] = row[1] - cve_data[row[0]]["score"] = row[2] - cve_data[row[0]]["modified"] = row[3] - cve_data[row[0]]["vector"] = row[4] - conn.close() + conn = sqlite3.connect(d.getVar("CVE_CHECK_DB_FILE")) + for cve in cves: + for row in conn.execute("SELECT * FROM NVD WHERE ID IS ?", (cve,)): + cve_data[row[0]] = {} + cve_data[row[0]]["summary"] = row[1] + cve_data[row[0]]["scorev2"] = row[2] + cve_data[row[0]]["scorev3"] = row[3] + cve_data[row[0]]["modified"] = row[4] + cve_data[row[0]]["vector"] = row[5] + + conn.close() return cve_data def cve_write_data(d, patched, unpatched, cve_data): @@ -229,39 +286,41 @@ def cve_write_data(d, patched, unpatched, cve_data): CVE manifest if enabled. """ - cve_file = d.getVar("CVE_CHECK_LOCAL_FILE", True) + cve_file = d.getVar("CVE_CHECK_LOG") nvd_link = "https://web.nvd.nist.gov/view/vuln/detail?vulnId=" write_string = "" - first_alert = True - bb.utils.mkdirhier(d.getVar("CVE_CHECK_LOCAL_DIR", True)) + unpatched_cves = [] + bb.utils.mkdirhier(os.path.dirname(cve_file)) for cve in sorted(cve_data): - write_string += "PACKAGE NAME: %s\n" % d.getVar("PN", True) - write_string += "PACKAGE VERSION: %s\n" % d.getVar("PV", True) + write_string += "PACKAGE NAME: %s\n" % d.getVar("PN") + write_string += "PACKAGE VERSION: %s\n" % d.getVar("PV") write_string += "CVE: %s\n" % cve if cve in patched: write_string += "CVE STATUS: Patched\n" else: + unpatched_cves.append(cve) write_string += "CVE STATUS: Unpatched\n" - if first_alert: - bb.warn("Found unpatched CVE, for more information check %s" % cve_file) - first_alert = False write_string += "CVE SUMMARY: %s\n" % cve_data[cve]["summary"] - write_string += "CVSS v2 BASE SCORE: %s\n" % cve_data[cve]["score"] + write_string += "CVSS v2 BASE SCORE: %s\n" % cve_data[cve]["scorev2"] + write_string += "CVSS v3 BASE SCORE: %s\n" % cve_data[cve]["scorev3"] write_string += "VECTOR: %s\n" % cve_data[cve]["vector"] write_string += "MORE INFORMATION: %s%s\n\n" % (nvd_link, cve) + if unpatched_cves: + bb.warn("Found unpatched CVE (%s), for more information check %s" % (" ".join(unpatched_cves),cve_file)) + with open(cve_file, "w") as f: bb.note("Writing file %s with CVE information" % cve_file) f.write(write_string) - if d.getVar("CVE_CHECK_COPY_FILES", True) == "1": - cve_dir = d.getVar("CVE_CHECK_DIR", True) + if d.getVar("CVE_CHECK_COPY_FILES") == "1": + cve_dir = d.getVar("CVE_CHECK_DIR") bb.utils.mkdirhier(cve_dir) - deploy_file = os.path.join(cve_dir, d.getVar("PN", True)) + deploy_file = os.path.join(cve_dir, d.getVar("PN")) with open(deploy_file, "w") as f: f.write(write_string) - if d.getVar("CVE_CHECK_CREATE_MANIFEST", True) == "1": - with open(d.getVar("CVE_CHECK_TMP_FILE", True), "a") as f: + if d.getVar("CVE_CHECK_CREATE_MANIFEST") == "1": + with open(d.getVar("CVE_CHECK_TMP_FILE"), "a") as f: f.write("%s" % write_string) |