2
1

generate-cyclonedx 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0-or-later
  3. # This script converts the output of the show-info make target
  4. # to CycloneDX format.
  5. #
  6. # Example usage:
  7. # $ make show-info | utils/generate-cyclonedx > sbom.json
  8. import argparse
  9. import bz2
  10. import gzip
  11. import json
  12. import os
  13. from pathlib import Path
  14. import urllib.request
  15. import subprocess
  16. import sys
  17. CYCLONEDX_VERSION = "1.6"
  18. SPDX_SCHEMA_URL = f"https://raw.githubusercontent.com/CycloneDX/specification/{CYCLONEDX_VERSION}/schema/spdx.schema.json"
  19. brpath = Path(__file__).parent.parent
  20. cyclonedxpath = Path(os.getenv("BR2_DL_DIR", brpath / "dl")) / "cyclonedx"
  21. SPDX_SCHEMA_PATH = cyclonedxpath / f"spdx-{CYCLONEDX_VERSION}.schema.json"
  22. BR2_VERSION_FULL = (
  23. subprocess.check_output(
  24. ["make", "--no-print-directory", "-C", brpath, "print-version"]
  25. )
  26. .decode()
  27. .strip()
  28. )
  29. SPDX_LICENSES = []
  30. if not SPDX_SCHEMA_PATH.exists():
  31. # Download the CycloneDX SPDX schema JSON, and cache it locally
  32. cyclonedxpath.mkdir(parents=True, exist_ok=True)
  33. urllib.request.urlretrieve(SPDX_SCHEMA_URL, SPDX_SCHEMA_PATH)
  34. try:
  35. with SPDX_SCHEMA_PATH.open() as f:
  36. SPDX_LICENSES = json.load(f).get("enum", [])
  37. except json.JSONDecodeError:
  38. # In case of error the license will just not be matched to the SPDX names
  39. # but the SBOM generation still work.
  40. print(f"Failed to load the SPDX licenses file: {SPDX_SCHEMA_PATH}", file=sys.stderr)
  41. def split_top_level_comma(subj):
  42. """Split a string at comma's, but do not split at comma's in between parentheses.
  43. Args:
  44. subj (str): String to be split.
  45. Returns:
  46. list: A list of substrings
  47. """
  48. counter = 0
  49. substring = ""
  50. for char in subj:
  51. if char == "," and counter == 0:
  52. yield substring
  53. substring = ""
  54. else:
  55. if char == "(":
  56. counter += 1
  57. elif char == ")":
  58. counter -= 1
  59. substring += char
  60. yield substring
  61. def cyclonedx_license(lic):
  62. """Given the name of a license, create an individual entry in
  63. CycloneDX format. In CycloneDX, the 'id' keyword is used for
  64. names that are recognized as SPDX License abbreviations. All other
  65. license names are placed under the 'name' keyword.
  66. Args:
  67. lic (str): Name of the license
  68. Returns:
  69. dict: An entry for the license in CycloneDX format.
  70. """
  71. key = "id" if lic in SPDX_LICENSES else "name"
  72. return {
  73. key: lic,
  74. }
  75. def cyclonedx_licenses(lic_list):
  76. """Create a licenses list formatted for a CycloneDX component
  77. Args:
  78. lic_list (str): A comma separated list of license names.
  79. Returns:
  80. dict: A dictionary with license information for the component,
  81. in CycloneDX format.
  82. """
  83. return {
  84. "licenses": [
  85. {"license": cyclonedx_license(lic.strip())} for lic in split_top_level_comma(lic_list)
  86. ]
  87. }
  88. def cyclonedx_patches(patch_list):
  89. """Translate a list of patches from the show-info JSON to a list of
  90. patches in CycloneDX format.
  91. Args:
  92. patch_list (dict): Information about the patches as a Python dictionary.
  93. Returns:
  94. dict: Patch information in CycloneDX format.
  95. """
  96. patch_contents = []
  97. for patch in patch_list:
  98. patch_path = brpath / patch
  99. if patch_path.exists():
  100. f = None
  101. if patch.endswith('.gz'):
  102. f = gzip.open(patch_path, mode="rt")
  103. elif patch.endswith('.bz'):
  104. f = bz2.open(patch_path, mode="rt")
  105. else:
  106. f = open(patch_path)
  107. try:
  108. patch_contents.append({
  109. "text": {
  110. "content": f.read()
  111. }
  112. })
  113. except Exception:
  114. # If the patch can't be read it won't be added to
  115. # the resulting SBOM.
  116. print(f"Failed to handle patch: {patch}", file=sys.stderr)
  117. f.close()
  118. else:
  119. # If the patch is not a file it's a tarball or diff url passed
  120. # through the `<pkg-name>_PATCH` variable.
  121. patch_contents.append({
  122. "url": patch
  123. })
  124. return {
  125. "pedigree": {
  126. "patches": [{
  127. "type": "unofficial",
  128. "diff": content
  129. } for content in patch_contents]
  130. },
  131. }
  132. def cyclonedx_component(name, comp):
  133. """Translate a component from the show-info output, to a component entry in CycloneDX format.
  134. Args:
  135. name (str): Key used for the package in the show-info output.
  136. comp (dict): Data about the package as a Python dictionary.
  137. Returns:
  138. dict: Component information in CycloneDX format.
  139. """
  140. return {
  141. "bom-ref": name,
  142. "type": "library",
  143. **({
  144. "name": comp["name"],
  145. } if "name" in comp else {}),
  146. **({
  147. "version": comp["version"],
  148. **(cyclonedx_licenses(comp["licenses"]) if "licenses" in comp else {}),
  149. } if not comp["virtual"] else {}),
  150. **({
  151. "cpe": comp["cpe-id"],
  152. } if "cpe-id" in comp else {}),
  153. **(cyclonedx_patches(comp["patches"]) if comp.get("patches") else {}),
  154. "properties": [{
  155. "name": "BR_TYPE",
  156. "value": comp["type"],
  157. }],
  158. }
  159. def cyclonedx_dependency(ref, depends):
  160. """Create JSON for dependency relationships between components.
  161. Args:
  162. ref (str): reference to a component bom-ref.
  163. depends (list): array of component bom-ref identifier to create the dependencies.
  164. Returns:
  165. dict: Dependency information in CycloneDX format.
  166. """
  167. return {
  168. "ref": ref,
  169. "dependsOn": depends,
  170. }
  171. def cyclonedx_vulnerabilities(show_info_dict):
  172. """Create a JSON list of vulnerabilities ignored by buildroot and associate
  173. the component for which they are solved.
  174. Args:
  175. show_info_dict (dict): The JSON output of the show-info
  176. command, parsed into a Python dictionary.
  177. Returns:
  178. list: Solved vulnerabilities list in CycloneDX format.
  179. """
  180. cves = {}
  181. for name, comp in show_info_dict.items():
  182. for cve in comp.get('ignore_cves', []):
  183. cves.setdefault(cve, []).append(name)
  184. return [{
  185. "id": cve,
  186. "analysis": {
  187. "state": "in_triage",
  188. "detail": f"The CVE '{cve}' has been marked as ignored by Buildroot"
  189. },
  190. "affects": [
  191. {"ref": bomref} for bomref in components
  192. ]
  193. } for cve, components in cves.items()]
  194. def br2_parse_deps_recursively(ref, show_info_dict, virtual=False, deps=[]):
  195. """Parse dependencies from the show-info output. This function will
  196. recursively collect all dependencies, and return a list where each dependency
  197. is stated at most once.
  198. The dependency on virtual package will collect the final dependency without
  199. including the virtual one.
  200. Args:
  201. ref (str): The identifier of the package for which the dependencies have
  202. to be looked up.
  203. show_info_dict (dict): The JSON output of the show-info
  204. command, parsed into a Python dictionary.
  205. Kwargs:
  206. deps (list): A list, to which dependencies will be appended. If set to None,
  207. a new empty list will be created. Defaults to None.
  208. Returns:
  209. list: A list of dependencies of the 'ref' package.
  210. """
  211. for dep in show_info_dict.get(ref, {}).get("dependencies", []):
  212. if dep not in deps:
  213. if virtual or show_info_dict.get(dep, {}).get("virtual") is False:
  214. deps.append(dep)
  215. br2_parse_deps_recursively(dep, show_info_dict, virtual, deps)
  216. return deps
  217. def main():
  218. parser = argparse.ArgumentParser(
  219. description='''Create a CycloneDX SBoM for the Buildroot configuration.
  220. Example usage: make show-info | utils/generate-cyclonedx > sbom.json
  221. '''
  222. )
  223. parser.add_argument("-i", "--in-file", nargs="?", type=argparse.FileType("r"),
  224. default=(None if sys.stdin.isatty() else sys.stdin))
  225. parser.add_argument("-o", "--out-file", nargs="?", type=argparse.FileType("w"),
  226. default=sys.stdout)
  227. parser.add_argument("--virtual", default=False, action='store_true',
  228. help="This option includes virtual packages to the CycloneDX output")
  229. args = parser.parse_args()
  230. if args.in_file is None:
  231. parser.print_help()
  232. sys.exit(1)
  233. show_info_dict = json.load(args.in_file)
  234. # Remove rootfs and virtual packages if not explicitly included
  235. # from the cli arguments
  236. filtered_show_info_dict = {k: v for k, v in show_info_dict.items()
  237. if ("rootfs" not in v["type"]) and (args.virtual or v["virtual"] is False)}
  238. cyclonedx_dict = {
  239. "bomFormat": "CycloneDX",
  240. "$schema": f"http://cyclonedx.org/schema/bom-{CYCLONEDX_VERSION}.schema.json",
  241. "specVersion": f"{CYCLONEDX_VERSION}",
  242. "components": [
  243. cyclonedx_component(name, comp) for name, comp in filtered_show_info_dict.items()
  244. ],
  245. "dependencies": [
  246. cyclonedx_dependency("buildroot", list(filtered_show_info_dict)),
  247. *[cyclonedx_dependency(ref, br2_parse_deps_recursively(ref, show_info_dict, args.virtual))
  248. for ref in filtered_show_info_dict],
  249. ],
  250. "vulnerabilities": cyclonedx_vulnerabilities(show_info_dict),
  251. "metadata": {
  252. "component": {
  253. "bom-ref": "buildroot",
  254. "name": "buildroot",
  255. "type": "firmware",
  256. "version": f"{BR2_VERSION_FULL}",
  257. },
  258. },
  259. }
  260. args.out_file.write(json.dumps(cyclonedx_dict, indent=2))
  261. args.out_file.write('\n')
  262. if __name__ == "__main__":
  263. main()