cve-check.bbclass 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. # The product name that the CVE database uses. Defaults to BPN, but may need to
  23. # be overriden per recipe (for example tiff.bb sets CVE_PRODUCT=libtiff).
  24. CVE_PRODUCT ??= "${BPN}"
  25. CVE_VERSION ??= "${PV}"
  26. CVE_CHECK_DB_DIR ?= "${DL_DIR}/CVE_CHECK"
  27. CVE_CHECK_DB_FILE ?= "${CVE_CHECK_DB_DIR}/nvdcve_1.1.db"
  28. CVE_CHECK_DB_FILE_LOCK ?= "${CVE_CHECK_DB_FILE}.lock"
  29. CVE_CHECK_LOG ?= "${T}/cve.log"
  30. CVE_CHECK_TMP_FILE ?= "${TMPDIR}/cve_check"
  31. CVE_CHECK_SUMMARY_DIR ?= "${LOG_DIR}/cve"
  32. CVE_CHECK_SUMMARY_FILE_NAME ?= "cve-summary"
  33. CVE_CHECK_SUMMARY_FILE ?= "${CVE_CHECK_SUMMARY_DIR}/${CVE_CHECK_SUMMARY_FILE_NAME}"
  34. CVE_CHECK_DIR ??= "${DEPLOY_DIR}/cve"
  35. CVE_CHECK_RECIPE_FILE ?= "${CVE_CHECK_DIR}/${PN}"
  36. CVE_CHECK_MANIFEST ?= "${DEPLOY_DIR_IMAGE}/${IMAGE_NAME}${IMAGE_NAME_SUFFIX}.cve"
  37. CVE_CHECK_COPY_FILES ??= "1"
  38. CVE_CHECK_CREATE_MANIFEST ??= "1"
  39. CVE_CHECK_REPORT_PATCHED ??= "1"
  40. # Whitelist for packages (PN)
  41. CVE_CHECK_PN_WHITELIST ?= ""
  42. # Whitelist for CVE. If a CVE is found, then it is considered patched.
  43. # The value is a string containing space separated CVE values:
  44. #
  45. # CVE_CHECK_WHITELIST = 'CVE-2014-2524 CVE-2018-1234'
  46. #
  47. CVE_CHECK_WHITELIST ?= ""
  48. python cve_save_summary_handler () {
  49. import shutil
  50. import datetime
  51. cve_tmp_file = d.getVar("CVE_CHECK_TMP_FILE")
  52. cve_summary_name = d.getVar("CVE_CHECK_SUMMARY_FILE_NAME")
  53. cvelogpath = d.getVar("CVE_CHECK_SUMMARY_DIR")
  54. bb.utils.mkdirhier(cvelogpath)
  55. timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
  56. cve_summary_file = os.path.join(cvelogpath, "%s-%s.txt" % (cve_summary_name, timestamp))
  57. if os.path.exists(cve_tmp_file):
  58. shutil.copyfile(cve_tmp_file, cve_summary_file)
  59. if cve_summary_file and os.path.exists(cve_summary_file):
  60. cvefile_link = os.path.join(cvelogpath, cve_summary_name)
  61. if os.path.exists(os.path.realpath(cvefile_link)):
  62. os.remove(cvefile_link)
  63. os.symlink(os.path.basename(cve_summary_file), cvefile_link)
  64. }
  65. addhandler cve_save_summary_handler
  66. cve_save_summary_handler[eventmask] = "bb.event.BuildCompleted"
  67. python do_cve_check () {
  68. """
  69. Check recipe for patched and unpatched CVEs
  70. """
  71. if os.path.exists(d.getVar("CVE_CHECK_DB_FILE")):
  72. try:
  73. patched_cves = get_patches_cves(d)
  74. except FileNotFoundError:
  75. bb.fatal("Failure in searching patches")
  76. whitelisted, patched, unpatched = check_cves(d, patched_cves)
  77. if patched or unpatched:
  78. cve_data = get_cve_info(d, patched + unpatched)
  79. cve_write_data(d, patched, unpatched, whitelisted, cve_data)
  80. else:
  81. bb.note("No CVE database found, skipping CVE check")
  82. }
  83. addtask cve_check before do_build after do_fetch
  84. do_cve_check[depends] = "cve-update-db-native:do_fetch"
  85. do_cve_check[nostamp] = "1"
  86. python cve_check_cleanup () {
  87. """
  88. Delete the file used to gather all the CVE information.
  89. """
  90. bb.utils.remove(e.data.getVar("CVE_CHECK_TMP_FILE"))
  91. }
  92. addhandler cve_check_cleanup
  93. cve_check_cleanup[eventmask] = "bb.cooker.CookerExit"
  94. python cve_check_write_rootfs_manifest () {
  95. """
  96. Create CVE manifest when building an image
  97. """
  98. import shutil
  99. if d.getVar("CVE_CHECK_COPY_FILES") == "1":
  100. deploy_file = d.getVar("CVE_CHECK_RECIPE_FILE")
  101. if os.path.exists(deploy_file):
  102. bb.utils.remove(deploy_file)
  103. if os.path.exists(d.getVar("CVE_CHECK_TMP_FILE")):
  104. bb.note("Writing rootfs CVE manifest")
  105. deploy_dir = d.getVar("DEPLOY_DIR_IMAGE")
  106. link_name = d.getVar("IMAGE_LINK_NAME")
  107. manifest_name = d.getVar("CVE_CHECK_MANIFEST")
  108. cve_tmp_file = d.getVar("CVE_CHECK_TMP_FILE")
  109. shutil.copyfile(cve_tmp_file, manifest_name)
  110. if manifest_name and os.path.exists(manifest_name):
  111. manifest_link = os.path.join(deploy_dir, "%s.cve" % link_name)
  112. # If we already have another manifest, update symlinks
  113. if os.path.exists(os.path.realpath(manifest_link)):
  114. os.remove(manifest_link)
  115. os.symlink(os.path.basename(manifest_name), manifest_link)
  116. bb.plain("Image CVE report stored in: %s" % manifest_name)
  117. }
  118. ROOTFS_POSTPROCESS_COMMAND_prepend = "${@'cve_check_write_rootfs_manifest; ' if d.getVar('CVE_CHECK_CREATE_MANIFEST') == '1' else ''}"
  119. do_rootfs[recrdeptask] += "${@'do_cve_check' if d.getVar('CVE_CHECK_CREATE_MANIFEST') == '1' else ''}"
  120. def get_patches_cves(d):
  121. """
  122. Get patches that solve CVEs using the "CVE: " tag.
  123. """
  124. import re
  125. pn = d.getVar("PN")
  126. cve_match = re.compile("CVE:( CVE\-\d{4}\-\d+)+")
  127. # Matches last CVE-1234-211432 in the file name, also if written
  128. # with small letters. Not supporting multiple CVE id's in a single
  129. # file name.
  130. cve_file_name_match = re.compile(".*([Cc][Vv][Ee]\-\d{4}\-\d+)")
  131. patched_cves = set()
  132. bb.debug(2, "Looking for patches that solves CVEs for %s" % pn)
  133. for url in src_patches(d):
  134. patch_file = bb.fetch.decodeurl(url)[2]
  135. if not os.path.isfile(patch_file):
  136. bb.error("File Not found: %s" % patch_file)
  137. raise FileNotFoundError
  138. # Check patch file name for CVE ID
  139. fname_match = cve_file_name_match.search(patch_file)
  140. if fname_match:
  141. cve = fname_match.group(1).upper()
  142. patched_cves.add(cve)
  143. bb.debug(2, "Found CVE %s from patch file name %s" % (cve, patch_file))
  144. with open(patch_file, "r", encoding="utf-8") as f:
  145. try:
  146. patch_text = f.read()
  147. except UnicodeDecodeError:
  148. bb.debug(1, "Failed to read patch %s using UTF-8 encoding"
  149. " trying with iso8859-1" % patch_file)
  150. f.close()
  151. with open(patch_file, "r", encoding="iso8859-1") as f:
  152. patch_text = f.read()
  153. # Search for one or more "CVE: " lines
  154. text_match = False
  155. for match in cve_match.finditer(patch_text):
  156. # Get only the CVEs without the "CVE: " tag
  157. cves = patch_text[match.start()+5:match.end()]
  158. for cve in cves.split():
  159. bb.debug(2, "Patch %s solves %s" % (patch_file, cve))
  160. patched_cves.add(cve)
  161. text_match = True
  162. if not fname_match and not text_match:
  163. bb.debug(2, "Patch %s doesn't solve CVEs" % patch_file)
  164. return patched_cves
  165. def check_cves(d, patched_cves):
  166. """
  167. Connect to the NVD database and find unpatched cves.
  168. """
  169. from distutils.version import LooseVersion
  170. cves_unpatched = []
  171. # CVE_PRODUCT can contain more than one product (eg. curl/libcurl)
  172. products = d.getVar("CVE_PRODUCT").split()
  173. # If this has been unset then we're not scanning for CVEs here (for example, image recipes)
  174. if not products:
  175. return ([], [], [])
  176. pv = d.getVar("CVE_VERSION").split("+git")[0]
  177. # If the recipe has been whitlisted we return empty lists
  178. if d.getVar("PN") in d.getVar("CVE_CHECK_PN_WHITELIST").split():
  179. bb.note("Recipe has been whitelisted, skipping check")
  180. return ([], [], [])
  181. old_cve_whitelist = d.getVar("CVE_CHECK_CVE_WHITELIST")
  182. if old_cve_whitelist:
  183. bb.warn("CVE_CHECK_CVE_WHITELIST is deprecated, please use CVE_CHECK_WHITELIST.")
  184. cve_whitelist = d.getVar("CVE_CHECK_WHITELIST").split()
  185. import sqlite3
  186. db_file = d.expand("file:${CVE_CHECK_DB_FILE}?mode=ro")
  187. conn = sqlite3.connect(db_file, uri=True)
  188. # For each of the known product names (e.g. curl has CPEs using curl and libcurl)...
  189. for product in products:
  190. if ":" in product:
  191. vendor, product = product.split(":", 1)
  192. else:
  193. vendor = "%"
  194. # Find all relevant CVE IDs.
  195. for cverow in conn.execute("SELECT DISTINCT ID FROM PRODUCTS WHERE PRODUCT IS ? AND VENDOR LIKE ?", (product, vendor)):
  196. cve = cverow[0]
  197. if cve in cve_whitelist:
  198. bb.note("%s-%s has been whitelisted for %s" % (product, pv, cve))
  199. # TODO: this should be in the report as 'whitelisted'
  200. patched_cves.add(cve)
  201. continue
  202. elif cve in patched_cves:
  203. bb.note("%s has been patched" % (cve))
  204. continue
  205. vulnerable = False
  206. for row in conn.execute("SELECT * FROM PRODUCTS WHERE ID IS ? AND PRODUCT IS ? AND VENDOR LIKE ?", (cve, product, vendor)):
  207. (_, _, _, version_start, operator_start, version_end, operator_end) = row
  208. #bb.debug(2, "Evaluating row " + str(row))
  209. if (operator_start == '=' and pv == version_start) or version_start == '-':
  210. vulnerable = True
  211. else:
  212. if operator_start:
  213. try:
  214. vulnerable_start = (operator_start == '>=' and LooseVersion(pv) >= LooseVersion(version_start))
  215. vulnerable_start |= (operator_start == '>' and LooseVersion(pv) > LooseVersion(version_start))
  216. except:
  217. bb.warn("%s: Failed to compare %s %s %s for %s" %
  218. (product, pv, operator_start, version_start, cve))
  219. vulnerable_start = False
  220. else:
  221. vulnerable_start = False
  222. if operator_end:
  223. try:
  224. vulnerable_end = (operator_end == '<=' and LooseVersion(pv) <= LooseVersion(version_end))
  225. vulnerable_end |= (operator_end == '<' and LooseVersion(pv) < LooseVersion(version_end))
  226. except:
  227. bb.warn("%s: Failed to compare %s %s %s for %s" %
  228. (product, pv, operator_end, version_end, cve))
  229. vulnerable_end = False
  230. else:
  231. vulnerable_end = False
  232. if operator_start and operator_end:
  233. vulnerable = vulnerable_start and vulnerable_end
  234. else:
  235. vulnerable = vulnerable_start or vulnerable_end
  236. if vulnerable:
  237. bb.note("%s-%s is vulnerable to %s" % (product, pv, cve))
  238. cves_unpatched.append(cve)
  239. break
  240. if not vulnerable:
  241. bb.note("%s-%s is not vulnerable to %s" % (product, pv, cve))
  242. # TODO: not patched but not vulnerable
  243. patched_cves.add(cve)
  244. conn.close()
  245. return (list(cve_whitelist), list(patched_cves), cves_unpatched)
  246. def get_cve_info(d, cves):
  247. """
  248. Get CVE information from the database.
  249. """
  250. import sqlite3
  251. cve_data = {}
  252. conn = sqlite3.connect(d.getVar("CVE_CHECK_DB_FILE"))
  253. for cve in cves:
  254. for row in conn.execute("SELECT * FROM NVD WHERE ID IS ?", (cve,)):
  255. cve_data[row[0]] = {}
  256. cve_data[row[0]]["summary"] = row[1]
  257. cve_data[row[0]]["scorev2"] = row[2]
  258. cve_data[row[0]]["scorev3"] = row[3]
  259. cve_data[row[0]]["modified"] = row[4]
  260. cve_data[row[0]]["vector"] = row[5]
  261. conn.close()
  262. return cve_data
  263. def cve_write_data(d, patched, unpatched, whitelisted, cve_data):
  264. """
  265. Write CVE information in WORKDIR; and to CVE_CHECK_DIR, and
  266. CVE manifest if enabled.
  267. """
  268. cve_file = d.getVar("CVE_CHECK_LOG")
  269. nvd_link = "https://web.nvd.nist.gov/view/vuln/detail?vulnId="
  270. write_string = ""
  271. unpatched_cves = []
  272. bb.utils.mkdirhier(os.path.dirname(cve_file))
  273. for cve in sorted(cve_data):
  274. is_patched = cve in patched
  275. if is_patched and (d.getVar("CVE_CHECK_REPORT_PATCHED") != "1"):
  276. continue
  277. write_string += "PACKAGE NAME: %s\n" % d.getVar("PN")
  278. write_string += "PACKAGE VERSION: %s%s\n" % (d.getVar("EXTENDPE"), d.getVar("PV"))
  279. write_string += "CVE: %s\n" % cve
  280. if cve in whitelisted:
  281. write_string += "CVE STATUS: Whitelisted\n"
  282. elif is_patched:
  283. write_string += "CVE STATUS: Patched\n"
  284. else:
  285. unpatched_cves.append(cve)
  286. write_string += "CVE STATUS: Unpatched\n"
  287. write_string += "CVE SUMMARY: %s\n" % cve_data[cve]["summary"]
  288. write_string += "CVSS v2 BASE SCORE: %s\n" % cve_data[cve]["scorev2"]
  289. write_string += "CVSS v3 BASE SCORE: %s\n" % cve_data[cve]["scorev3"]
  290. write_string += "VECTOR: %s\n" % cve_data[cve]["vector"]
  291. write_string += "MORE INFORMATION: %s%s\n\n" % (nvd_link, cve)
  292. if unpatched_cves:
  293. bb.warn("Found unpatched CVE (%s), for more information check %s" % (" ".join(unpatched_cves),cve_file))
  294. if write_string:
  295. with open(cve_file, "w") as f:
  296. bb.note("Writing file %s with CVE information" % cve_file)
  297. f.write(write_string)
  298. if d.getVar("CVE_CHECK_COPY_FILES") == "1":
  299. deploy_file = d.getVar("CVE_CHECK_RECIPE_FILE")
  300. bb.utils.mkdirhier(os.path.dirname(deploy_file))
  301. with open(deploy_file, "w") as f:
  302. f.write(write_string)
  303. if d.getVar("CVE_CHECK_CREATE_MANIFEST") == "1":
  304. cvelogpath = d.getVar("CVE_CHECK_SUMMARY_DIR")
  305. bb.utils.mkdirhier(cvelogpath)
  306. with open(d.getVar("CVE_CHECK_TMP_FILE"), "a") as f:
  307. f.write("%s" % write_string)