vex.bbclass 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. #
  2. # Copyright OpenEmbedded Contributors
  3. #
  4. # SPDX-License-Identifier: MIT
  5. #
  6. # This class is used to generate metadata needed by external
  7. # tools to check for vulnerabilities, for example CVEs.
  8. #
  9. # In order to use this class just inherit the class in the
  10. # local.conf file and it will add the generate_vex task for
  11. # every recipe. If an image is build it will generate a report
  12. # in DEPLOY_DIR_IMAGE for all the packages used, it will also
  13. # generate a file for all recipes used in the build.
  14. #
  15. # Variables use CVE_CHECK prefix to keep compatibility with
  16. # the cve-check class
  17. #
  18. # Example:
  19. # bitbake -c generate_vex openssl
  20. # bitbake core-image-sato
  21. # bitbake -k -c generate_vex universe
  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. CVE_CHECK_SUMMARY_DIR ?= "${LOG_DIR}/cve"
  28. CVE_CHECK_SUMMARY_FILE_NAME_JSON = "cve-summary.json"
  29. CVE_CHECK_SUMMARY_INDEX_PATH = "${CVE_CHECK_SUMMARY_DIR}/cve-summary-index.txt"
  30. CVE_CHECK_DIR ??= "${DEPLOY_DIR}/cve"
  31. CVE_CHECK_RECIPE_FILE_JSON ?= "${CVE_CHECK_DIR}/${PN}_cve.json"
  32. CVE_CHECK_MANIFEST_JSON ?= "${IMGDEPLOYDIR}/${IMAGE_NAME}.json"
  33. # Skip CVE Check for packages (PN)
  34. CVE_CHECK_SKIP_RECIPE ?= ""
  35. # Replace NVD DB check status for a given CVE. Each of CVE has to be mentioned
  36. # separately with optional detail and description for this status.
  37. #
  38. # CVE_STATUS[CVE-1234-0001] = "not-applicable-platform: Issue only applies on Windows"
  39. # CVE_STATUS[CVE-1234-0002] = "fixed-version: Fixed externally"
  40. #
  41. # Settings the same status and reason for multiple CVEs is possible
  42. # via CVE_STATUS_GROUPS variable.
  43. #
  44. # CVE_STATUS_GROUPS = "CVE_STATUS_WIN CVE_STATUS_PATCHED"
  45. #
  46. # CVE_STATUS_WIN = "CVE-1234-0001 CVE-1234-0003"
  47. # CVE_STATUS_WIN[status] = "not-applicable-platform: Issue only applies on Windows"
  48. # CVE_STATUS_PATCHED = "CVE-1234-0002 CVE-1234-0004"
  49. # CVE_STATUS_PATCHED[status] = "fixed-version: Fixed externally"
  50. #
  51. # All possible CVE statuses could be found in cve-check-map.conf
  52. # CVE_CHECK_STATUSMAP[not-applicable-platform] = "Ignored"
  53. # CVE_CHECK_STATUSMAP[fixed-version] = "Patched"
  54. #
  55. # CVE_CHECK_IGNORE is deprecated and CVE_STATUS has to be used instead.
  56. # Keep CVE_CHECK_IGNORE until other layers migrate to new variables
  57. CVE_CHECK_IGNORE ?= ""
  58. # Layers to be excluded
  59. CVE_CHECK_LAYER_EXCLUDELIST ??= ""
  60. # Layers to be included
  61. CVE_CHECK_LAYER_INCLUDELIST ??= ""
  62. # set to "alphabetical" for version using single alphabetical character as increment release
  63. CVE_VERSION_SUFFIX ??= ""
  64. python () {
  65. if bb.data.inherits_class("cve-check", d):
  66. raise bb.parse.SkipRecipe("Skipping recipe: found incompatible combination of cve-check and vex enabled at the same time.")
  67. from oe.cve_check import extend_cve_status
  68. extend_cve_status(d)
  69. }
  70. def generate_json_report(d, out_path, link_path):
  71. if os.path.exists(d.getVar("CVE_CHECK_SUMMARY_INDEX_PATH")):
  72. import json
  73. from oe.cve_check import cve_check_merge_jsons, update_symlinks
  74. bb.note("Generating JSON CVE summary")
  75. index_file = d.getVar("CVE_CHECK_SUMMARY_INDEX_PATH")
  76. summary = {"version":"1", "package": []}
  77. with open(index_file) as f:
  78. filename = f.readline()
  79. while filename:
  80. with open(filename.rstrip()) as j:
  81. data = json.load(j)
  82. cve_check_merge_jsons(summary, data)
  83. filename = f.readline()
  84. summary["package"].sort(key=lambda d: d['name'])
  85. with open(out_path, "w") as f:
  86. json.dump(summary, f, indent=2)
  87. update_symlinks(out_path, link_path)
  88. python vex_save_summary_handler () {
  89. import shutil
  90. import datetime
  91. from oe.cve_check import update_symlinks
  92. cvelogpath = d.getVar("CVE_CHECK_SUMMARY_DIR")
  93. bb.utils.mkdirhier(cvelogpath)
  94. timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
  95. json_summary_link_name = os.path.join(cvelogpath, d.getVar("CVE_CHECK_SUMMARY_FILE_NAME_JSON"))
  96. json_summary_name = os.path.join(cvelogpath, "cve-summary-%s.json" % (timestamp))
  97. generate_json_report(d, json_summary_name, json_summary_link_name)
  98. bb.plain("Complete CVE JSON report summary created at: %s" % json_summary_link_name)
  99. }
  100. addhandler vex_save_summary_handler
  101. vex_save_summary_handler[eventmask] = "bb.event.BuildCompleted"
  102. python do_generate_vex () {
  103. """
  104. Generate metadata needed for vulnerability checking for
  105. the current recipe
  106. """
  107. from oe.cve_check import get_patched_cves
  108. try:
  109. patched_cves = get_patched_cves(d)
  110. cves_status = []
  111. products = d.getVar("CVE_PRODUCT").split()
  112. for product in products:
  113. if ":" in product:
  114. _, product = product.split(":", 1)
  115. cves_status.append([product, False])
  116. except FileNotFoundError:
  117. bb.fatal("Failure in searching patches")
  118. cve_write_data_json(d, patched_cves, cves_status)
  119. }
  120. addtask generate_vex before do_build
  121. python vex_cleanup () {
  122. """
  123. Delete the file used to gather all the CVE information.
  124. """
  125. bb.utils.remove(e.data.getVar("CVE_CHECK_SUMMARY_INDEX_PATH"))
  126. }
  127. addhandler vex_cleanup
  128. vex_cleanup[eventmask] = "bb.event.BuildCompleted"
  129. python vex_write_rootfs_manifest () {
  130. """
  131. Create VEX/CVE manifest when building an image
  132. """
  133. import json
  134. from oe.rootfs import image_list_installed_packages
  135. from oe.cve_check import cve_check_merge_jsons, update_symlinks
  136. deploy_file_json = d.getVar("CVE_CHECK_RECIPE_FILE_JSON")
  137. if os.path.exists(deploy_file_json):
  138. bb.utils.remove(deploy_file_json)
  139. # Create a list of relevant recipies
  140. recipies = set()
  141. for pkg in list(image_list_installed_packages(d)):
  142. pkg_info = os.path.join(d.getVar('PKGDATA_DIR'),
  143. 'runtime-reverse', pkg)
  144. pkg_data = oe.packagedata.read_pkgdatafile(pkg_info)
  145. recipies.add(pkg_data["PN"])
  146. bb.note("Writing rootfs VEX manifest")
  147. deploy_dir = d.getVar("IMGDEPLOYDIR")
  148. link_name = d.getVar("IMAGE_LINK_NAME")
  149. json_data = {"version":"1", "package": []}
  150. text_data = ""
  151. save_pn = d.getVar("PN")
  152. for pkg in recipies:
  153. # To be able to use the CVE_CHECK_RECIPE_FILE_JSON variable we have to evaluate
  154. # it with the different PN names set each time.
  155. d.setVar("PN", pkg)
  156. pkgfilepath = d.getVar("CVE_CHECK_RECIPE_FILE_JSON")
  157. if os.path.exists(pkgfilepath):
  158. with open(pkgfilepath) as j:
  159. data = json.load(j)
  160. cve_check_merge_jsons(json_data, data)
  161. else:
  162. bb.warn("Missing cve file for %s" % pkg)
  163. d.setVar("PN", save_pn)
  164. link_path = os.path.join(deploy_dir, "%s.json" % link_name)
  165. manifest_name = d.getVar("CVE_CHECK_MANIFEST_JSON")
  166. with open(manifest_name, "w") as f:
  167. json.dump(json_data, f, indent=2)
  168. update_symlinks(manifest_name, link_path)
  169. bb.plain("Image VEX JSON report stored in: %s" % manifest_name)
  170. }
  171. ROOTFS_POSTPROCESS_COMMAND:prepend = "vex_write_rootfs_manifest; "
  172. do_rootfs[recrdeptask] += "do_generate_vex "
  173. do_populate_sdk[recrdeptask] += "do_generate_vex "
  174. def cve_write_data_json(d, cve_data, cve_status):
  175. """
  176. Prepare CVE data for the JSON format, then write it.
  177. Done for each recipe.
  178. """
  179. from oe.cve_check import get_cpe_ids
  180. import json
  181. output = {"version":"1", "package": []}
  182. nvd_link = "https://nvd.nist.gov/vuln/detail/"
  183. fdir_name = d.getVar("FILE_DIRNAME")
  184. layer = fdir_name.split("/")[-3]
  185. include_layers = d.getVar("CVE_CHECK_LAYER_INCLUDELIST").split()
  186. exclude_layers = d.getVar("CVE_CHECK_LAYER_EXCLUDELIST").split()
  187. if exclude_layers and layer in exclude_layers:
  188. return
  189. if include_layers and layer not in include_layers:
  190. return
  191. product_data = []
  192. for s in cve_status:
  193. p = {"product": s[0], "cvesInRecord": "Yes"}
  194. if s[1] == False:
  195. p["cvesInRecord"] = "No"
  196. product_data.append(p)
  197. product_data = list({p['product']:p for p in product_data}.values())
  198. package_version = "%s%s" % (d.getVar("EXTENDPE"), d.getVar("PV"))
  199. cpes = get_cpe_ids(d.getVar("CVE_PRODUCT"), d.getVar("CVE_VERSION"))
  200. package_data = {
  201. "name" : d.getVar("PN"),
  202. "layer" : layer,
  203. "version" : package_version,
  204. "products": product_data,
  205. "cpes": cpes
  206. }
  207. cve_list = []
  208. for cve in sorted(cve_data):
  209. issue_link = "%s%s" % (nvd_link, cve)
  210. cve_item = {
  211. "id" : cve,
  212. "status" : cve_data[cve]["abbrev-status"],
  213. "link": issue_link,
  214. }
  215. if 'NVD-summary' in cve_data[cve]:
  216. cve_item["summary"] = cve_data[cve]["NVD-summary"]
  217. cve_item["scorev2"] = cve_data[cve]["NVD-scorev2"]
  218. cve_item["scorev3"] = cve_data[cve]["NVD-scorev3"]
  219. cve_item["scorev4"] = cve_data[cve]["NVD-scorev4"]
  220. cve_item["vector"] = cve_data[cve]["NVD-vector"]
  221. cve_item["vectorString"] = cve_data[cve]["NVD-vectorString"]
  222. if 'status' in cve_data[cve]:
  223. cve_item["detail"] = cve_data[cve]["status"]
  224. if 'justification' in cve_data[cve]:
  225. cve_item["description"] = cve_data[cve]["justification"]
  226. if 'resource' in cve_data[cve]:
  227. cve_item["patch-file"] = cve_data[cve]["resource"]
  228. cve_list.append(cve_item)
  229. package_data["issue"] = cve_list
  230. output["package"].append(package_data)
  231. deploy_file = d.getVar("CVE_CHECK_RECIPE_FILE_JSON")
  232. write_string = json.dumps(output, indent=2)
  233. cvelogpath = d.getVar("CVE_CHECK_SUMMARY_DIR")
  234. index_path = d.getVar("CVE_CHECK_SUMMARY_INDEX_PATH")
  235. bb.utils.mkdirhier(cvelogpath)
  236. bb.utils.mkdirhier(os.path.dirname(deploy_file))
  237. fragment_file = os.path.basename(deploy_file)
  238. fragment_path = os.path.join(cvelogpath, fragment_file)
  239. with open(fragment_path, "w") as f:
  240. f.write(write_string)
  241. with open(deploy_file, "w") as f:
  242. f.write(write_string)
  243. with open(index_path, "a+") as f:
  244. f.write("%s\n" % fragment_path)