cve-check.bbclass 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. CVE_CHECK_DB_DIR ?= "${DL_DIR}/CVE_CHECK"
  23. CVE_CHECK_DB_FILE ?= "${CVE_CHECK_DB_DIR}/nvd.db"
  24. CVE_CHECK_LOCAL_DIR ?= "${WORKDIR}/cve"
  25. CVE_CHECK_LOCAL_FILE ?= "${CVE_CHECK_LOCAL_DIR}/cve.log"
  26. CVE_CHECK_TMP_FILE ?= "${TMPDIR}/cve_check"
  27. CVE_CHECK_DIR ??= "${DEPLOY_DIR}/cve"
  28. CVE_CHECK_MANIFEST ?= "${DEPLOY_DIR_IMAGE}/${IMAGE_NAME}${IMAGE_NAME_SUFFIX}.cve"
  29. CVE_CHECK_COPY_FILES ??= "1"
  30. CVE_CHECK_CREATE_MANIFEST ??= "1"
  31. # Whitelist for packages (PN)
  32. CVE_CHECK_PN_WHITELIST = "\
  33. glibc-locale \
  34. "
  35. # Whitelist for CVE and version of package
  36. CVE_CHECK_CVE_WHITELIST = "{\
  37. 'CVE-2014-2524': ('6.3',), \
  38. }"
  39. python do_cve_check () {
  40. """
  41. Check recipe for patched and unpatched CVEs
  42. """
  43. if os.path.exists(d.getVar("CVE_CHECK_TMP_FILE", True)):
  44. patched_cves = get_patches_cves(d)
  45. patched, unpatched = check_cves(d, patched_cves)
  46. if patched or unpatched:
  47. cve_data = get_cve_info(d, patched + unpatched)
  48. cve_write_data(d, patched, unpatched, cve_data)
  49. else:
  50. bb.note("Failed to update CVE database, skipping CVE check")
  51. }
  52. addtask cve_check after do_unpack before do_build
  53. do_cve_check[depends] = "cve-check-tool-native:do_populate_cve_db"
  54. do_cve_check[nostamp] = "1"
  55. python cve_check_cleanup () {
  56. """
  57. Delete the file used to gather all the CVE information.
  58. """
  59. bb.utils.remove(e.data.getVar("CVE_CHECK_TMP_FILE", True))
  60. }
  61. addhandler cve_check_cleanup
  62. cve_check_cleanup[eventmask] = "bb.cooker.CookerExit"
  63. python cve_check_write_rootfs_manifest () {
  64. """
  65. Create CVE manifest when building an image
  66. """
  67. import shutil
  68. if os.path.exists(d.getVar("CVE_CHECK_TMP_FILE", True)):
  69. bb.note("Writing rootfs CVE manifest")
  70. deploy_dir = d.getVar("DEPLOY_DIR_IMAGE", True)
  71. link_name = d.getVar("IMAGE_LINK_NAME", True)
  72. manifest_name = d.getVar("CVE_CHECK_MANIFEST", True)
  73. cve_tmp_file = d.getVar("CVE_CHECK_TMP_FILE", True)
  74. shutil.copyfile(cve_tmp_file, manifest_name)
  75. if manifest_name and os.path.exists(manifest_name):
  76. manifest_link = os.path.join(deploy_dir, "%s.cve" % link_name)
  77. # If we already have another manifest, update symlinks
  78. if os.path.exists(os.path.realpath(manifest_link)):
  79. os.remove(manifest_link)
  80. os.symlink(os.path.basename(manifest_name), manifest_link)
  81. bb.plain("Image CVE report stored in: %s" % manifest_name)
  82. }
  83. ROOTFS_POSTPROCESS_COMMAND_prepend = "${@'cve_check_write_rootfs_manifest; ' if d.getVar('CVE_CHECK_CREATE_MANIFEST', True) == '1' else ''}"
  84. def get_patches_cves(d):
  85. """
  86. Get patches that solve CVEs using the "CVE: " tag.
  87. """
  88. import re
  89. pn = d.getVar("PN", True)
  90. cve_match = re.compile("CVE:( CVE\-\d{4}\-\d+)+")
  91. patched_cves = set()
  92. bb.debug(2, "Looking for patches that solves CVEs for %s" % pn)
  93. for url in src_patches(d):
  94. patch_file = bb.fetch.decodeurl(url)[2]
  95. with open(patch_file, "r", encoding="utf-8") as f:
  96. try:
  97. patch_text = f.read()
  98. except UnicodeDecodeError:
  99. bb.debug(1, "Failed to read patch %s using UTF-8 encoding"
  100. " trying with iso8859-1" % patch_file)
  101. f.close()
  102. with open(patch_file, "r", encoding="iso8859-1") as f:
  103. patch_text = f.read()
  104. # Search for the "CVE: " line
  105. match = cve_match.search(patch_text)
  106. if match:
  107. # Get only the CVEs without the "CVE: " tag
  108. cves = patch_text[match.start()+5:match.end()]
  109. for cve in cves.split():
  110. bb.debug(2, "Patch %s solves %s" % (patch_file, cve))
  111. patched_cves.add(cve)
  112. else:
  113. bb.debug(2, "Patch %s doesn't solve CVEs" % patch_file)
  114. return patched_cves
  115. def check_cves(d, patched_cves):
  116. """
  117. Run cve-check-tool looking for patched and unpatched CVEs.
  118. """
  119. import ast, csv, tempfile, subprocess, io
  120. cves_patched = []
  121. cves_unpatched = []
  122. bpn = d.getVar("BPN", True)
  123. pv = d.getVar("PV", True).split("git+")[0]
  124. cves = " ".join(patched_cves)
  125. cve_db_dir = d.getVar("CVE_CHECK_DB_DIR", True)
  126. cve_whitelist = ast.literal_eval(d.getVar("CVE_CHECK_CVE_WHITELIST", True))
  127. cve_cmd = "cve-check-tool"
  128. cmd = [cve_cmd, "--no-html", "--csv", "--not-affected", "-t", "faux", "-d", cve_db_dir]
  129. # If the recipe has been whitlisted we return empty lists
  130. if d.getVar("PN", True) in d.getVar("CVE_CHECK_PN_WHITELIST", True).split():
  131. bb.note("Recipe has been whitelisted, skipping check")
  132. return ([], [])
  133. # It is needed to export the proxies to download the database using HTTP
  134. bb.utils.export_proxies(d)
  135. try:
  136. # Write the faux CSV file to be used with cve-check-tool
  137. fd, faux = tempfile.mkstemp(prefix="cve-faux-")
  138. with os.fdopen(fd, "w") as f:
  139. f.write("%s,%s,%s," % (bpn, pv, cves))
  140. cmd.append(faux)
  141. output = subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode("utf-8")
  142. bb.debug(2, "Output of command %s:\n%s" % ("\n".join(cmd), output))
  143. except subprocess.CalledProcessError as e:
  144. bb.warn("Couldn't check for CVEs: %s (output %s)" % (e, e.output))
  145. finally:
  146. os.remove(faux)
  147. for row in csv.reader(io.StringIO(output)):
  148. # Third row has the unpatched CVEs
  149. if row[2]:
  150. for cve in row[2].split():
  151. # Skip if the CVE has been whitlisted for the current version
  152. if pv in cve_whitelist.get(cve,[]):
  153. bb.note("%s-%s has been whitelisted for %s" % (bpn, pv, cve))
  154. else:
  155. cves_unpatched.append(cve)
  156. bb.debug(2, "%s-%s is not patched for %s" % (bpn, pv, cve))
  157. # Fourth row has patched CVEs
  158. if row[3]:
  159. for cve in row[3].split():
  160. cves_patched.append(cve)
  161. bb.debug(2, "%s-%s is patched for %s" % (bpn, pv, cve))
  162. return (cves_patched, cves_unpatched)
  163. def get_cve_info(d, cves):
  164. """
  165. Get CVE information from the database used by cve-check-tool.
  166. Unfortunately the only way to get CVE info is set the output to
  167. html (hard to parse) or query directly the database.
  168. """
  169. try:
  170. import sqlite3
  171. except ImportError:
  172. from pysqlite2 import dbapi2 as sqlite3
  173. cve_data = {}
  174. db_file = d.getVar("CVE_CHECK_DB_FILE", True)
  175. placeholder = ",".join("?" * len(cves))
  176. query = "SELECT * FROM NVD WHERE id IN (%s)" % placeholder
  177. conn = sqlite3.connect(db_file)
  178. cur = conn.cursor()
  179. for row in cur.execute(query, tuple(cves)):
  180. cve_data[row[0]] = {}
  181. cve_data[row[0]]["summary"] = row[1]
  182. cve_data[row[0]]["score"] = row[2]
  183. cve_data[row[0]]["modified"] = row[3]
  184. cve_data[row[0]]["vector"] = row[4]
  185. conn.close()
  186. return cve_data
  187. def cve_write_data(d, patched, unpatched, cve_data):
  188. """
  189. Write CVE information in WORKDIR; and to CVE_CHECK_DIR, and
  190. CVE manifest if enabled.
  191. """
  192. cve_file = d.getVar("CVE_CHECK_LOCAL_FILE", True)
  193. nvd_link = "https://web.nvd.nist.gov/view/vuln/detail?vulnId="
  194. write_string = ""
  195. first_alert = True
  196. bb.utils.mkdirhier(d.getVar("CVE_CHECK_LOCAL_DIR", True))
  197. for cve in sorted(cve_data):
  198. write_string += "PACKAGE NAME: %s\n" % d.getVar("PN", True)
  199. write_string += "PACKAGE VERSION: %s\n" % d.getVar("PV", True)
  200. write_string += "CVE: %s\n" % cve
  201. if cve in patched:
  202. write_string += "CVE STATUS: Patched\n"
  203. else:
  204. write_string += "CVE STATUS: Unpatched\n"
  205. if first_alert:
  206. bb.warn("Found unpatched CVE, for more information check %s" % cve_file)
  207. first_alert = False
  208. write_string += "CVE SUMMARY: %s\n" % cve_data[cve]["summary"]
  209. write_string += "CVSS v2 BASE SCORE: %s\n" % cve_data[cve]["score"]
  210. write_string += "VECTOR: %s\n" % cve_data[cve]["vector"]
  211. write_string += "MORE INFORMATION: %s%s\n\n" % (nvd_link, cve)
  212. with open(cve_file, "w") as f:
  213. bb.note("Writing file %s with CVE information" % cve_file)
  214. f.write(write_string)
  215. if d.getVar("CVE_CHECK_COPY_FILES", True) == "1":
  216. cve_dir = d.getVar("CVE_CHECK_DIR", True)
  217. bb.utils.mkdirhier(cve_dir)
  218. deploy_file = os.path.join(cve_dir, d.getVar("PN", True))
  219. with open(deploy_file, "w") as f:
  220. f.write(write_string)
  221. if d.getVar("CVE_CHECK_CREATE_MANIFEST", True) == "1":
  222. with open(d.getVar("CVE_CHECK_TMP_FILE", True), "a") as f:
  223. f.write("%s" % write_string)