lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame^] | 1 | # This class is used to check recipes against public CVEs. |
| 2 | # |
| 3 | # In order to use this class just inherit the class in the |
| 4 | # local.conf file and it will add the cve_check task for |
| 5 | # every recipe. The task can be used per recipe, per image, |
| 6 | # or using the special cases "world" and "universe". The |
| 7 | # cve_check task will print a warning for every unpatched |
| 8 | # CVE found and generate a file in the recipe WORKDIR/cve |
| 9 | # directory. If an image is build it will generate a report |
| 10 | # in DEPLOY_DIR_IMAGE for all the packages used. |
| 11 | # |
| 12 | # Example: |
| 13 | # bitbake -c cve_check openssl |
| 14 | # bitbake core-image-sato |
| 15 | # bitbake -k -c cve_check universe |
| 16 | # |
| 17 | # DISCLAIMER |
| 18 | # |
| 19 | # This class/tool is meant to be used as support and not |
| 20 | # the only method to check against CVEs. Running this tool |
| 21 | # doesn't guarantee your packages are free of CVEs. |
| 22 | |
| 23 | # The product name that the CVE database uses defaults to BPN, but may need to |
| 24 | # be overriden per recipe (for example tiff.bb sets CVE_PRODUCT=libtiff). |
| 25 | CVE_PRODUCT ??= "${BPN}" |
| 26 | CVE_VERSION ??= "${PV}" |
| 27 | |
| 28 | CVE_CHECK_DB_DIR ?= "${DL_DIR}/CVE_CHECK" |
| 29 | CVE_CHECK_DB_FILE ?= "${CVE_CHECK_DB_DIR}/nvdcve_1.1.db" |
| 30 | CVE_CHECK_DB_FILE_LOCK ?= "${CVE_CHECK_DB_FILE}.lock" |
| 31 | |
| 32 | CVE_CHECK_LOG ?= "${T}/cve.log" |
| 33 | CVE_CHECK_TMP_FILE ?= "${TMPDIR}/cve_check" |
| 34 | CVE_CHECK_SUMMARY_DIR ?= "${LOG_DIR}/cve" |
| 35 | CVE_CHECK_SUMMARY_FILE_NAME ?= "cve-summary" |
| 36 | CVE_CHECK_SUMMARY_FILE ?= "${CVE_CHECK_SUMMARY_DIR}/${CVE_CHECK_SUMMARY_FILE_NAME}" |
| 37 | |
| 38 | CVE_CHECK_DIR ??= "${DEPLOY_DIR}/cve" |
| 39 | CVE_CHECK_RECIPE_FILE ?= "${CVE_CHECK_DIR}/${PN}" |
| 40 | CVE_CHECK_MANIFEST ?= "${DEPLOY_DIR_IMAGE}/${IMAGE_NAME}${IMAGE_NAME_SUFFIX}.cve" |
| 41 | CVE_CHECK_COPY_FILES ??= "1" |
| 42 | CVE_CHECK_CREATE_MANIFEST ??= "1" |
| 43 | |
| 44 | CVE_CHECK_REPORT_PATCHED ??= "1" |
| 45 | |
| 46 | # Whitelist for packages (PN) |
| 47 | CVE_CHECK_PN_WHITELIST ?= "" |
| 48 | |
| 49 | # Whitelist for CVE. If a CVE is found, then it is considered patched. |
| 50 | # The value is a string containing space separated CVE values: |
| 51 | # |
| 52 | # CVE_CHECK_WHITELIST = 'CVE-2014-2524 CVE-2018-1234' |
| 53 | # |
| 54 | CVE_CHECK_WHITELIST ?= "" |
| 55 | |
| 56 | # Layers to be excluded |
| 57 | CVE_CHECK_LAYER_EXCLUDELIST ??= "" |
| 58 | |
| 59 | # Layers to be included |
| 60 | CVE_CHECK_LAYER_INCLUDELIST ??= "" |
| 61 | |
| 62 | |
| 63 | # set to "alphabetical" for version using single alphabetical character as increment release |
| 64 | CVE_VERSION_SUFFIX ??= "" |
| 65 | |
| 66 | python cve_save_summary_handler () { |
| 67 | import shutil |
| 68 | import datetime |
| 69 | |
| 70 | cve_tmp_file = d.getVar("CVE_CHECK_TMP_FILE") |
| 71 | |
| 72 | cve_summary_name = d.getVar("CVE_CHECK_SUMMARY_FILE_NAME") |
| 73 | cvelogpath = d.getVar("CVE_CHECK_SUMMARY_DIR") |
| 74 | bb.utils.mkdirhier(cvelogpath) |
| 75 | |
| 76 | timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S') |
| 77 | cve_summary_file = os.path.join(cvelogpath, "%s-%s.txt" % (cve_summary_name, timestamp)) |
| 78 | |
| 79 | if os.path.exists(cve_tmp_file): |
| 80 | shutil.copyfile(cve_tmp_file, cve_summary_file) |
| 81 | |
| 82 | if cve_summary_file and os.path.exists(cve_summary_file): |
| 83 | cvefile_link = os.path.join(cvelogpath, cve_summary_name) |
| 84 | |
| 85 | if os.path.exists(os.path.realpath(cvefile_link)): |
| 86 | os.remove(cvefile_link) |
| 87 | os.symlink(os.path.basename(cve_summary_file), cvefile_link) |
| 88 | } |
| 89 | |
| 90 | addhandler cve_save_summary_handler |
| 91 | cve_save_summary_handler[eventmask] = "bb.event.BuildCompleted" |
| 92 | |
| 93 | python do_cve_check () { |
| 94 | """ |
| 95 | Check recipe for patched and unpatched CVEs |
| 96 | """ |
| 97 | |
| 98 | if os.path.exists(d.getVar("CVE_CHECK_DB_FILE")): |
| 99 | try: |
| 100 | patched_cves = get_patches_cves(d) |
| 101 | except FileNotFoundError: |
| 102 | bb.fatal("Failure in searching patches") |
| 103 | whitelisted, patched, unpatched = check_cves(d, patched_cves) |
| 104 | if patched or unpatched: |
| 105 | cve_data = get_cve_info(d, patched + unpatched) |
| 106 | cve_write_data(d, patched, unpatched, whitelisted, cve_data) |
| 107 | else: |
| 108 | bb.note("No CVE database found, skipping CVE check") |
| 109 | |
| 110 | } |
| 111 | |
| 112 | addtask cve_check before do_build after do_fetch |
| 113 | do_cve_check[depends] = "cve-update-db-native:do_populate_cve_db" |
| 114 | do_cve_check[nostamp] = "1" |
| 115 | |
| 116 | python cve_check_cleanup () { |
| 117 | """ |
| 118 | Delete the file used to gather all the CVE information. |
| 119 | """ |
| 120 | bb.utils.remove(e.data.getVar("CVE_CHECK_TMP_FILE")) |
| 121 | } |
| 122 | |
| 123 | addhandler cve_check_cleanup |
| 124 | cve_check_cleanup[eventmask] = "bb.cooker.CookerExit" |
| 125 | |
| 126 | python cve_check_write_rootfs_manifest () { |
| 127 | """ |
| 128 | Create CVE manifest when building an image |
| 129 | """ |
| 130 | |
| 131 | import shutil |
| 132 | |
| 133 | if d.getVar("CVE_CHECK_COPY_FILES") == "1": |
| 134 | deploy_file = d.getVar("CVE_CHECK_RECIPE_FILE") |
| 135 | if os.path.exists(deploy_file): |
| 136 | bb.utils.remove(deploy_file) |
| 137 | |
| 138 | if os.path.exists(d.getVar("CVE_CHECK_TMP_FILE")): |
| 139 | bb.note("Writing rootfs CVE manifest") |
| 140 | deploy_dir = d.getVar("DEPLOY_DIR_IMAGE") |
| 141 | link_name = d.getVar("IMAGE_LINK_NAME") |
| 142 | manifest_name = d.getVar("CVE_CHECK_MANIFEST") |
| 143 | cve_tmp_file = d.getVar("CVE_CHECK_TMP_FILE") |
| 144 | |
| 145 | shutil.copyfile(cve_tmp_file, manifest_name) |
| 146 | |
| 147 | if manifest_name and os.path.exists(manifest_name): |
| 148 | manifest_link = os.path.join(deploy_dir, "%s.cve" % link_name) |
| 149 | # If we already have another manifest, update symlinks |
| 150 | if os.path.exists(os.path.realpath(manifest_link)): |
| 151 | os.remove(manifest_link) |
| 152 | os.symlink(os.path.basename(manifest_name), manifest_link) |
| 153 | bb.plain("Image CVE report stored in: %s" % manifest_name) |
| 154 | } |
| 155 | |
| 156 | ROOTFS_POSTPROCESS_COMMAND_prepend = "${@'cve_check_write_rootfs_manifest; ' if d.getVar('CVE_CHECK_CREATE_MANIFEST') == '1' else ''}" |
| 157 | do_rootfs[recrdeptask] += "${@'do_cve_check' if d.getVar('CVE_CHECK_CREATE_MANIFEST') == '1' else ''}" |
| 158 | |
| 159 | def get_patches_cves(d): |
| 160 | """ |
| 161 | Get patches that solve CVEs using the "CVE: " tag. |
| 162 | """ |
| 163 | |
| 164 | import re |
| 165 | |
| 166 | pn = d.getVar("PN") |
| 167 | cve_match = re.compile("CVE:( CVE\-\d{4}\-\d+)+") |
| 168 | |
| 169 | # Matches the last "CVE-YYYY-ID" in the file name, also if written |
| 170 | # in lowercase. Possible to have multiple CVE IDs in a single |
| 171 | # file name, but only the last one will be detected from the file name. |
| 172 | # However, patch files contents addressing multiple CVE IDs are supported |
| 173 | # (cve_match regular expression) |
| 174 | |
| 175 | cve_file_name_match = re.compile(".*([Cc][Vv][Ee]\-\d{4}\-\d+)") |
| 176 | |
| 177 | patched_cves = set() |
| 178 | bb.debug(2, "Looking for patches that solves CVEs for %s" % pn) |
| 179 | for url in src_patches(d): |
| 180 | patch_file = bb.fetch.decodeurl(url)[2] |
| 181 | |
| 182 | if not os.path.isfile(patch_file): |
| 183 | bb.error("File Not found: %s" % patch_file) |
| 184 | raise FileNotFoundError |
| 185 | |
| 186 | # Check patch file name for CVE ID |
| 187 | fname_match = cve_file_name_match.search(patch_file) |
| 188 | if fname_match: |
| 189 | cve = fname_match.group(1).upper() |
| 190 | patched_cves.add(cve) |
| 191 | bb.debug(2, "Found CVE %s from patch file name %s" % (cve, patch_file)) |
| 192 | |
| 193 | with open(patch_file, "r", encoding="utf-8") as f: |
| 194 | try: |
| 195 | patch_text = f.read() |
| 196 | except UnicodeDecodeError: |
| 197 | bb.debug(1, "Failed to read patch %s using UTF-8 encoding" |
| 198 | " trying with iso8859-1" % patch_file) |
| 199 | f.close() |
| 200 | with open(patch_file, "r", encoding="iso8859-1") as f: |
| 201 | patch_text = f.read() |
| 202 | |
| 203 | # Search for one or more "CVE: " lines |
| 204 | text_match = False |
| 205 | for match in cve_match.finditer(patch_text): |
| 206 | # Get only the CVEs without the "CVE: " tag |
| 207 | cves = patch_text[match.start()+5:match.end()] |
| 208 | for cve in cves.split(): |
| 209 | bb.debug(2, "Patch %s solves %s" % (patch_file, cve)) |
| 210 | patched_cves.add(cve) |
| 211 | text_match = True |
| 212 | |
| 213 | if not fname_match and not text_match: |
| 214 | bb.debug(2, "Patch %s doesn't solve CVEs" % patch_file) |
| 215 | |
| 216 | return patched_cves |
| 217 | |
| 218 | def check_cves(d, patched_cves): |
| 219 | """ |
| 220 | Connect to the NVD database and find unpatched cves. |
| 221 | """ |
| 222 | from oe.cve_check import Version |
| 223 | |
| 224 | pn = d.getVar("PN") |
| 225 | real_pv = d.getVar("PV") |
| 226 | suffix = d.getVar("CVE_VERSION_SUFFIX") |
| 227 | |
| 228 | cves_unpatched = [] |
| 229 | # CVE_PRODUCT can contain more than one product (eg. curl/libcurl) |
| 230 | products = d.getVar("CVE_PRODUCT").split() |
| 231 | # If this has been unset then we're not scanning for CVEs here (for example, image recipes) |
| 232 | if not products: |
| 233 | return ([], [], []) |
| 234 | pv = d.getVar("CVE_VERSION").split("+git")[0] |
| 235 | |
| 236 | # If the recipe has been whitelisted we return empty lists |
| 237 | if pn in d.getVar("CVE_CHECK_PN_WHITELIST").split(): |
| 238 | bb.note("Recipe has been whitelisted, skipping check") |
| 239 | return ([], [], []) |
| 240 | |
| 241 | cve_whitelist = d.getVar("CVE_CHECK_WHITELIST").split() |
| 242 | |
| 243 | import sqlite3 |
| 244 | db_file = d.expand("file:${CVE_CHECK_DB_FILE}?mode=ro") |
| 245 | conn = sqlite3.connect(db_file, uri=True) |
| 246 | |
| 247 | # For each of the known product names (e.g. curl has CPEs using curl and libcurl)... |
| 248 | for product in products: |
| 249 | if ":" in product: |
| 250 | vendor, product = product.split(":", 1) |
| 251 | else: |
| 252 | vendor = "%" |
| 253 | |
| 254 | # Find all relevant CVE IDs. |
| 255 | for cverow in conn.execute("SELECT DISTINCT ID FROM PRODUCTS WHERE PRODUCT IS ? AND VENDOR LIKE ?", (product, vendor)): |
| 256 | cve = cverow[0] |
| 257 | |
| 258 | if cve in cve_whitelist: |
| 259 | bb.note("%s-%s has been whitelisted for %s" % (product, pv, cve)) |
| 260 | # TODO: this should be in the report as 'whitelisted' |
| 261 | patched_cves.add(cve) |
| 262 | continue |
| 263 | elif cve in patched_cves: |
| 264 | bb.note("%s has been patched" % (cve)) |
| 265 | continue |
| 266 | |
| 267 | vulnerable = False |
| 268 | for row in conn.execute("SELECT * FROM PRODUCTS WHERE ID IS ? AND PRODUCT IS ? AND VENDOR LIKE ?", (cve, product, vendor)): |
| 269 | (_, _, _, version_start, operator_start, version_end, operator_end) = row |
| 270 | #bb.debug(2, "Evaluating row " + str(row)) |
| 271 | |
| 272 | if (operator_start == '=' and pv == version_start) or version_start == '-': |
| 273 | vulnerable = True |
| 274 | else: |
| 275 | if operator_start: |
| 276 | try: |
| 277 | vulnerable_start = (operator_start == '>=' and Version(pv,suffix) >= Version(version_start,suffix)) |
| 278 | vulnerable_start |= (operator_start == '>' and Version(pv,suffix) > Version(version_start,suffix)) |
| 279 | except: |
| 280 | bb.warn("%s: Failed to compare %s %s %s for %s" % |
| 281 | (product, pv, operator_start, version_start, cve)) |
| 282 | vulnerable_start = False |
| 283 | else: |
| 284 | vulnerable_start = False |
| 285 | |
| 286 | if operator_end: |
| 287 | try: |
| 288 | vulnerable_end = (operator_end == '<=' and Version(pv,suffix) <= Version(version_end,suffix) ) |
| 289 | vulnerable_end |= (operator_end == '<' and Version(pv,suffix) < Version(version_end,suffix) ) |
| 290 | except: |
| 291 | bb.warn("%s: Failed to compare %s %s %s for %s" % |
| 292 | (product, pv, operator_end, version_end, cve)) |
| 293 | vulnerable_end = False |
| 294 | else: |
| 295 | vulnerable_end = False |
| 296 | |
| 297 | if operator_start and operator_end: |
| 298 | vulnerable = vulnerable_start and vulnerable_end |
| 299 | else: |
| 300 | vulnerable = vulnerable_start or vulnerable_end |
| 301 | |
| 302 | if vulnerable: |
| 303 | bb.note("%s-%s is vulnerable to %s" % (pn, real_pv, cve)) |
| 304 | cves_unpatched.append(cve) |
| 305 | break |
| 306 | |
| 307 | if not vulnerable: |
| 308 | bb.note("%s-%s is not vulnerable to %s" % (pn, real_pv, cve)) |
| 309 | # TODO: not patched but not vulnerable |
| 310 | patched_cves.add(cve) |
| 311 | |
| 312 | conn.close() |
| 313 | |
| 314 | return (list(cve_whitelist), list(patched_cves), cves_unpatched) |
| 315 | |
| 316 | def get_cve_info(d, cves): |
| 317 | """ |
| 318 | Get CVE information from the database. |
| 319 | """ |
| 320 | |
| 321 | import sqlite3 |
| 322 | |
| 323 | cve_data = {} |
| 324 | conn = sqlite3.connect(d.getVar("CVE_CHECK_DB_FILE")) |
| 325 | |
| 326 | for cve in cves: |
| 327 | for row in conn.execute("SELECT * FROM NVD WHERE ID IS ?", (cve,)): |
| 328 | cve_data[row[0]] = {} |
| 329 | cve_data[row[0]]["summary"] = row[1] |
| 330 | cve_data[row[0]]["scorev2"] = row[2] |
| 331 | cve_data[row[0]]["scorev3"] = row[3] |
| 332 | cve_data[row[0]]["modified"] = row[4] |
| 333 | cve_data[row[0]]["vector"] = row[5] |
| 334 | |
| 335 | conn.close() |
| 336 | return cve_data |
| 337 | |
| 338 | def cve_write_data(d, patched, unpatched, whitelisted, cve_data): |
| 339 | """ |
| 340 | Write CVE information in WORKDIR; and to CVE_CHECK_DIR, and |
| 341 | CVE manifest if enabled. |
| 342 | """ |
| 343 | |
| 344 | |
| 345 | cve_file = d.getVar("CVE_CHECK_LOG") |
| 346 | fdir_name = d.getVar("FILE_DIRNAME") |
| 347 | layer = fdir_name.split("/")[-3] |
| 348 | |
| 349 | include_layers = d.getVar("CVE_CHECK_LAYER_INCLUDELIST").split() |
| 350 | exclude_layers = d.getVar("CVE_CHECK_LAYER_EXCLUDELIST").split() |
| 351 | |
| 352 | if exclude_layers and layer in exclude_layers: |
| 353 | return |
| 354 | |
| 355 | if include_layers and layer not in include_layers: |
| 356 | return |
| 357 | |
| 358 | nvd_link = "https://nvd.nist.gov/vuln/detail/" |
| 359 | write_string = "" |
| 360 | unpatched_cves = [] |
| 361 | bb.utils.mkdirhier(os.path.dirname(cve_file)) |
| 362 | |
| 363 | for cve in sorted(cve_data): |
| 364 | is_patched = cve in patched |
| 365 | if is_patched and (d.getVar("CVE_CHECK_REPORT_PATCHED") != "1"): |
| 366 | continue |
| 367 | write_string += "LAYER: %s\n" % layer |
| 368 | write_string += "PACKAGE NAME: %s\n" % d.getVar("PN") |
| 369 | write_string += "PACKAGE VERSION: %s%s\n" % (d.getVar("EXTENDPE"), d.getVar("PV")) |
| 370 | write_string += "CVE: %s\n" % cve |
| 371 | if cve in whitelisted: |
| 372 | write_string += "CVE STATUS: Whitelisted\n" |
| 373 | elif is_patched: |
| 374 | write_string += "CVE STATUS: Patched\n" |
| 375 | else: |
| 376 | unpatched_cves.append(cve) |
| 377 | write_string += "CVE STATUS: Unpatched\n" |
| 378 | write_string += "CVE SUMMARY: %s\n" % cve_data[cve]["summary"] |
| 379 | write_string += "CVSS v2 BASE SCORE: %s\n" % cve_data[cve]["scorev2"] |
| 380 | write_string += "CVSS v3 BASE SCORE: %s\n" % cve_data[cve]["scorev3"] |
| 381 | write_string += "VECTOR: %s\n" % cve_data[cve]["vector"] |
| 382 | write_string += "MORE INFORMATION: %s%s\n\n" % (nvd_link, cve) |
| 383 | |
| 384 | if unpatched_cves: |
| 385 | bb.warn("Found unpatched CVE (%s), for more information check %s" % (" ".join(unpatched_cves),cve_file)) |
| 386 | |
| 387 | if write_string: |
| 388 | with open(cve_file, "w") as f: |
| 389 | bb.note("Writing file %s with CVE information" % cve_file) |
| 390 | f.write(write_string) |
| 391 | |
| 392 | if d.getVar("CVE_CHECK_COPY_FILES") == "1": |
| 393 | deploy_file = d.getVar("CVE_CHECK_RECIPE_FILE") |
| 394 | bb.utils.mkdirhier(os.path.dirname(deploy_file)) |
| 395 | with open(deploy_file, "w") as f: |
| 396 | f.write(write_string) |
| 397 | |
| 398 | if d.getVar("CVE_CHECK_CREATE_MANIFEST") == "1": |
| 399 | cvelogpath = d.getVar("CVE_CHECK_SUMMARY_DIR") |
| 400 | bb.utils.mkdirhier(cvelogpath) |
| 401 | |
| 402 | with open(d.getVar("CVE_CHECK_TMP_FILE"), "a") as f: |
| 403 | f.write("%s" % write_string) |