Skip to contentSkip to conversation

utils/generate-cyclonedx: move license download in a function

PATCH Superseded Thomas Perale via buildroot 1 participant 4 messages Feb 2

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

PATCH 1/3 utils/generate-cyclonedx: move license download in a function

Move the code that retrieve the SPDX licenses into a function instead of doing it top-level.

This allows to pass the CycloneDX version as a function argument instead of defining it as a top-level constant.
In next commit, the CycloneDX spec version might not be known when the top-level code is executed.

---
 utils/generate-cyclonedx | 44 ++++++++++++++++++++++++++++------------
 1 file changed, 31 insertions(+), 13 deletions(-)
utils/generate-cyclonedx +31 -13
index 2b6c6d63d3..1f7a26e870 100755
@@ -21,12 +21,10 @@ import re
 
 
 CYCLONEDX_VERSION = "1.6"
-SPDX_SCHEMA_URL = f"https://raw.githubusercontent.com/CycloneDX/specification/{CYCLONEDX_VERSION}/schema/spdx.schema.json"
 
 brpath = Path(__file__).parent.parent
 
 cyclonedxpath = Path(os.getenv("BR2_DL_DIR", brpath / "dl")) / "cyclonedx"
-SPDX_SCHEMA_PATH = cyclonedxpath / f"spdx-{CYCLONEDX_VERSION}.schema.json"
 
 BR2_VERSION_FULL = (
     subprocess.check_output(
@@ -41,21 +39,39 @@ BR2_VERSION_FULL = (
 # 'resolved_with_pedigree'.
 VULN_WITH_PEDIGREE = set()
 
+# List of supported SPDX license expression.
 SPDX_LICENSES = []
 
-if not SPDX_SCHEMA_PATH.exists():
-    # Download the CycloneDX SPDX schema JSON, and cache it locally
-    cyclonedxpath.mkdir(parents=True, exist_ok=True)
-    urllib.request.urlretrieve(SPDX_SCHEMA_URL, SPDX_SCHEMA_PATH)
+def br2_retrieve_spdx_licenses(version: str):
+    """Populate the list of supported SPDX licenses for a given CycloneDX
+    version. If the list is not present locally it will be downloaded
+    externally.
 
-try:
-    with SPDX_SCHEMA_PATH.open() as f:
-        SPDX_LICENSES = json.load(f).get("enum", [])
-except json.JSONDecodeError:
-    # In case of error the license will just not be matched to the SPDX names
-    # but the SBOM generation still work.
-    print(f"Failed to load the SPDX licenses file: {SPDX_SCHEMA_PATH}", file=sys.stderr)
+    Args:
+        version (str): CycloneDX version
+
+    Returns:
+        None
+    """
+    SPDX_SCHEMA_URL = "https://raw.githubusercontent.com/CycloneDX/specification/{}/schema/spdx.schema.json"
 
+    ret = []
+    path = cyclonedxpath / f"spdx-{version}.schema.json"
+
+    if not path.exists():
+        # Download the CycloneDX SPDX schema JSON, and cache it locally
+        cyclonedxpath.mkdir(parents=True, exist_ok=True)
+        urllib.request.urlretrieve(SPDX_SCHEMA_URL.format(version), path)
+
+    try:
+        with path.open() as f:
+            ret = json.load(f).get("enum", [])
+    except json.JSONDecodeError:
+        # In case of error the license will just not be matched to the SPDX names
+        # but the SBOM generation still work.
+        print(f"Failed to load the SPDX licenses file: {path}", file=sys.stderr)
+
+    return ret
 
 def split_top_level_comma(subj):
     """Split a string at comma's, but do not split at comma's in between parentheses.
@@ -404,6 +420,8 @@ def main():
         parser.print_help()
         sys.exit(1)
 
+    SPDX_LICENSES.extend(br2_retrieve_spdx_licenses(CYCLONEDX_VERSION))
+
     show_info_dict = json.load(args.in_file)
 
     # Remove rootfs and virtual packages if not explicitly included
Signature · 6 lines
2.52.0

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot
#1 lore raw

PATCH 2/3 utils/generate-cyclonedx: optional bump to v1.7

See changes:

- https://cyclonedx.org/news/cyclonedx-v1.7-released/
- https://github.com/CycloneDX/specification/releases/tag/1.7

Since some tools like DependencyTrack don't support CycloneDX SBOM v1.7 this bump is optional and default remains v1.6.

To allow generation of CycloneDX based on the current version of the spec we are using a 'Context' datastructure is created that reference the CycloneDX version spec currently in use.

This Context datastructure is then passed down to functions that generate part of the CycloneDX SBOM.

All the top level datastructure are moved into the Context datastructure that will be generated after the arguments from the command line are interpreted.

---
 utils/generate-cyclonedx | 61 +++++++++++++++++++++++-----------------
 1 file changed, 35 insertions(+), 26 deletions(-)
utils/generate-cyclonedx +35 -26
index 1f7a26e870..1ef2544e1b 100755
@@ -18,9 +18,9 @@ import urllib.request
 import subprocess
 import sys
 import re
+from dataclasses import dataclass, field
 
-
-CYCLONEDX_VERSION = "1.6"
+DEFAULT_CYCLONEDX_VERSION = "1.6"
 
 brpath = Path(__file__).parent.parent
 
@@ -34,13 +34,16 @@ BR2_VERSION_FULL = (
     .strip()
 )
 
-# Set of vulnerabilities that were addressed by a patch present in buildroot
-# tree. This set is used to set the analysis of the ignored CVEs to
-# 'resolved_with_pedigree'.
-VULN_WITH_PEDIGREE = set()
-
-# List of supported SPDX license expression.
-SPDX_LICENSES = []
+@dataclass
+class Context:
+    # CycloneDX Spec version
+    CYCLONEDX_VERSION: str = DEFAULT_CYCLONEDX_VERSION
+    # List of supported SPDX license expression.
+    SPDX_LICENSES: list = field(default_factory=list)
+    # Set of vulnerabilities that were addressed by a patch present in buildroot
+    # tree. This set is used to set the analysis of the ignored CVEs to
+    # 'resolved_with_pedigree'.
+    VULN_WITH_PEDIGREE: set = field(default_factory=set)
 
 def br2_retrieve_spdx_licenses(version: str):
     """Populate the list of supported SPDX licenses for a given CycloneDX
@@ -99,7 +102,7 @@ def split_top_level_comma(subj):
     yield substring
 
 
-def cyclonedx_license(lic):
+def cyclonedx_license(lic, ctx: Context):
     """Given the name of a license, create an individual entry in
     CycloneDX format. In CycloneDX, the 'id' keyword is used for
     names that are recognized as SPDX License abbreviations. All other
@@ -111,13 +114,13 @@ def cyclonedx_license(lic):
     Returns:
         dict: An entry for the license in CycloneDX format.
     """
-    key = "id" if lic in SPDX_LICENSES else "name"
+    key = "id" if lic in ctx.SPDX_LICENSES else "name"
     return {
         key: lic,
     }
 
 
-def cyclonedx_licenses(lic_list):
+def cyclonedx_licenses(lic_list, ctx: Context):
     """Create a licenses list formatted for a CycloneDX component
 
     Args:
@@ -129,7 +132,7 @@ def cyclonedx_licenses(lic_list):
     """
     return {
         "licenses": [
-            {"license": cyclonedx_license(lic.strip())} for lic in split_top_level_comma(lic_list)
+            {"license": cyclonedx_license(lic.strip(), ctx)} for lic in split_top_level_comma(lic_list)
         ]
     }
 
@@ -213,7 +216,7 @@ def read_patch_file(patch_path: Path) -> str:
     return content
 
 
-def cyclonedx_patches(patch_list: list[str]):
+def cyclonedx_patches(patch_list: list[str], ctx: Context):
     """Translate a list of patches from the show-info JSON to a list of
     patches in CycloneDX format.
 
@@ -240,7 +243,7 @@ def cyclonedx_patches(patch_list: list[str]):
             issue = {}
             cves = extract_cves_from_header(header)
             if cves:
-                VULN_WITH_PEDIGREE.update(cves)
+                ctx.VULN_WITH_PEDIGREE.update(cves)
                 issue = {
                     "resolves": [
                         {
@@ -277,7 +280,7 @@ def cyclonedx_patches(patch_list: list[str]):
     }
 
 
-def cyclonedx_component(name, comp):
+def cyclonedx_component(name, comp, ctx: Context):
     """Translate a component from the show-info output, to a component entry in CycloneDX format.
 
     Args:
@@ -295,12 +298,12 @@ def cyclonedx_component(name, comp):
         } if "name" in comp else {}),
         **({
             "version": comp["version"],
-            **(cyclonedx_licenses(comp["licenses"]) if "licenses" in comp else {}),
+            **(cyclonedx_licenses(comp["licenses"], ctx) if "licenses" in comp else {}),
         } if not comp["virtual"] else {}),
         **({
             "cpe": comp["cpe-id"],
         } if "cpe-id" in comp else {}),
-        **(cyclonedx_patches(comp["patches"]) if comp.get("patches") else {}),
+        **(cyclonedx_patches(comp["patches"], ctx) if comp.get("patches") else {}),
         "properties": [{
             "name": "BR_TYPE",
             "value": comp["type"],
@@ -324,7 +327,7 @@ def cyclonedx_dependency(ref, depends):
     }
 
 
-def cyclonedx_vulnerabilities(show_info_dict):
+def cyclonedx_vulnerabilities(show_info_dict, ctx: Context):
     """Create a JSON list of vulnerabilities ignored by buildroot and associate
     the component for which they are solved.
 
@@ -344,7 +347,7 @@ def cyclonedx_vulnerabilities(show_info_dict):
     return [{
         "id": cve,
         "analysis": {
-            "state": "resolved_with_pedigree" if cve in VULN_WITH_PEDIGREE else "in_triage",
+            "state": "resolved_with_pedigree" if cve in ctx.VULN_WITH_PEDIGREE else "in_triage",
             "detail": f"The CVE '{cve}' has been marked as ignored by Buildroot"
         },
         "affects": [
@@ -411,8 +414,11 @@ def main():
                         help="This option includes virtual packages to the CycloneDX output")
     parser.add_argument("--project-name", type=str, default="buildroot",
                         help="Specify the project name to use in the SBOM metadata (default:'buildroot')")
-    parser.add_argument("--project-version", type=str, default=f"{BR2_VERSION_FULL}",
+    parser.add_argument("--project-version", type=str,
                         help="Specify the project version to use in the SBOM metadata (default: builroot version)")
+    parser.add_argument("--v17", dest='cdx_version', action='store_const',
+                        const='1.7', default=DEFAULT_CYCLONEDX_VERSION,
+                        help=f"Use CycloneDX version 1.7 (default: {DEFAULT_CYCLONEDX_VERSION})")
 
     args = parser.parse_args()
 
@@ -420,7 +426,10 @@ def main():
         parser.print_help()
         sys.exit(1)
 
-    SPDX_LICENSES.extend(br2_retrieve_spdx_licenses(CYCLONEDX_VERSION))
+    ctx = Context(
+        CYCLONEDX_VERSION=args.cdx_version,
+        SPDX_LICENSES=br2_retrieve_spdx_licenses(args.cdx_version)
+    )
 
     show_info_dict = json.load(args.in_file)
 
@@ -431,8 +440,8 @@ def main():
 
     cyclonedx_dict = {
         "bomFormat": "CycloneDX",
-        "$schema": f"http://cyclonedx.org/schema/bom-{CYCLONEDX_VERSION}.schema.json",
-        "specVersion": f"{CYCLONEDX_VERSION}",
+        "$schema": f"http://cyclonedx.org/schema/bom-{ctx.CYCLONEDX_VERSION}.schema.json",
+        "specVersion": f"{ctx.CYCLONEDX_VERSION}",
         "metadata": {
             "component": {
                 "bom-ref": args.project_name,
@@ -458,14 +467,14 @@ def main():
             }
         },
         "components": [
-            cyclonedx_component(name, comp) for name, comp in filtered_show_info_dict.items()
+            cyclonedx_component(name, comp, ctx) for name, comp in filtered_show_info_dict.items()
         ],
         "dependencies": [
             cyclonedx_dependency(args.project_name, list(filtered_show_info_dict)),
             *[cyclonedx_dependency(ref, br2_parse_deps(ref, show_info_dict, args.virtual))
               for ref in filtered_show_info_dict],
         ],
-        "vulnerabilities": cyclonedx_vulnerabilities(show_info_dict),
+        "vulnerabilities": cyclonedx_vulnerabilities(show_info_dict, ctx),
     }
 
     args.out_file.write(json.dumps(cyclonedx_dict, indent=2))
Signature · 6 lines
2.52.0

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot
#2 lore raw

PATCH 3/3 utils/generate-cyclonedx: mark host packages as external

In reply to Thomas Perale via buildroot

Mark Buildroot's host packages as 'external' with the 'isExternal' property. Starting CycloneDX v1.7 [1][2] the CycloneDX spec defines this property like the following [3].

Quoted 5 lines

An external component is one that is not part of an assembly, but is expected to be provided by the environment, regardless of the component's .scope. This setting can be useful for distinguishing which components are bundled with the product and which can be relied upon to be present in the deployment environment.

This fits the usage of 'host' packages : a package provided by the environment and not bundled with the target.

[1] https://github.com/CycloneDX/specification/releases/tag/1.7
[2] https://cyclonedx.org/docs/1.7/json/#components_items_isExternal
[3] https://github.com/CycloneDX/specification/issues/321

---
 utils/generate-cyclonedx | 3 +++
 1 file changed, 3 insertions(+)
utils/generate-cyclonedx +3 -0
index 1ef2544e1b..097d9707de 100755
@@ -293,6 +293,9 @@ def cyclonedx_component(name, comp, ctx: Context):
     return {
         "bom-ref": name,
         "type": "library",
+        **({
+            "isExternal": True
+        } if ctx.CYCLONEDX_VERSION == "1.7" and comp["type"] == "host" else {}),
         **({
             "name": comp["name"],
         } if "name" in comp else {}),
Signature · 6 lines
2.52.0

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot
#3 lore raw

Re: [Buildroot] [PATCH 3/3] utils/generate-cyclonedx: mark host packages as external

Quoted 26 lines · Thomas Perale

Mark Buildroot's host packages as 'external' with the 'isExternal' property. Starting CycloneDX v1.7 [1][2] the CycloneDX spec defines this property like the following [3].

Quoted 5 lines

An external component is one that is not part of an assembly, but is expected to be provided by the environment, regardless of the component's .scope. This setting can be useful for distinguishing which components are bundled with the product and which can be relied upon to be present in the deployment environment.

This fits the usage of 'host' packages : a package provided by the environment and not bundled with the target.

[1] https://github.com/CycloneDX/specification/releases/tag/1.7
[2] https://cyclonedx.org/docs/1.7/json/#components_items_isExternal
[3] https://github.com/CycloneDX/specification/issues/321

---
  utils/generate-cyclonedx | 3 +++
  1 file changed, 3 insertions(+)
utils/generate-cyclonedx +0 -0
index 1ef2544e1b..097d9707de 100755

utils/generate-cyclonedx def cyclonedx_component(name, comp, ctx: Context): · line 298

Quoted 6 lines
utils/generate-cyclonedx +3 -0
@@ -293,6 +293,9 @@ def cyclonedx_component(name, comp, ctx: Context):
      return {
          "bom-ref": name,
          "type": "library",
+        **({
+            "isExternal": True
+        } if ctx.CYCLONEDX_VERSION == "1.7" and comp["type"] == "host" else {}),

Nit: maybe check if cylone-dx version is greater or equal for future proofness ?

utils/generate-cyclonedx def cyclonedx_component(name, comp, ctx: Context): · line 301

Quoted 3 lines
utils/generate-cyclonedx +0 -0
          **({
              "name": comp["name"],
          } if "name" in comp else {}),

_______________________________________________
buildroot mailing list
[email protected]
https://lists.buildroot.org/mailman/listinfo/buildroot