Skip to contentSkip to conversation

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

PATCH In review Thomas Perale via buildroot 1 participant 6 messages Feb 3

lore
Share & tools
lore
#0 lore raw

PATCH v2 1/5 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 | 46 ++++++++++++++++++++++++++++------------
 1 file changed, 33 insertions(+), 13 deletions(-)
utils/generate-cyclonedx +33 -13
index 2b6c6d63d3..93b648e481 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,20 +39,40 @@ 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)
 
-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)
+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.
+
+    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):
@@ -404,6 +422,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 v2 2/5 utils/generate-cyclonedx: move utility function

Move all the utility functions that are not generating CycloneDX structure to the top of the script and group the CycloneDX generation function together.

---
 utils/generate-cyclonedx | 178 +++++++++++++++++++--------------------
 1 file changed, 89 insertions(+), 89 deletions(-)
utils/generate-cyclonedx +89 -89
index 93b648e481..f5faec09b4 100755
@@ -75,65 +75,48 @@ def br2_retrieve_spdx_licenses(version: str):
     return ret
 
 
-def split_top_level_comma(subj):
-    """Split a string at comma's, but do not split at comma's in between parentheses.
+def br2_virtual_is_provided_by(ref, show_info_dict) -> list:
+    """Retrieve the list of packages that provide a virtual package.
 
     Args:
-        subj (str): String to be split.
+        ref (str): The identifier of the virtual package.
+        show_info_dict (dict): The JSON output of the show-info
+            command, parsed into a Python dictionary.
 
     Returns:
-        list: A list of substrings
+        list: package list that provides the virtual package.
     """
-    counter = 0
-    substring = ""
-
-    for char in subj:
-        if char == "," and counter == 0:
-            yield substring
-            substring = ""
-        else:
-            if char == "(":
-                counter += 1
-            elif char == ")":
-                counter -= 1
-            substring += char
+    return [
+        name
+        for name, comp in show_info_dict.items()
+        if "provides" in comp and ref in comp["provides"]
+    ]
 
-    yield substring
 
+def br2_parse_deps(ref, show_info_dict, virtual=False) -> list:
+    """This function will collect all dependencies from the show-info output.
 
-def cyclonedx_license(lic):
-    """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
-    license names are placed under the 'name' keyword.
+    The dependency on virtual package will collect the final dependency without
+    including the virtual one.
 
     Args:
-        lic (str): Name of the license
+        ref (str): The identifier of the package for which the dependencies have
+            to be looked up.
+        show_info_dict (dict): The JSON output of the show-info
+            command, parsed into a Python dictionary.
 
     Returns:
-        dict: An entry for the license in CycloneDX format.
+        list: A list of dependencies of the 'ref' package.
     """
-    key = "id" if lic in SPDX_LICENSES else "name"
-    return {
-        key: lic,
-    }
-
-
-def cyclonedx_licenses(lic_list):
-    """Create a licenses list formatted for a CycloneDX component
+    deps = set()
 
-    Args:
-        lic_list (str): A comma separated list of license names.
+    for dep in show_info_dict.get(ref, {}).get("dependencies", []):
+        if not virtual and show_info_dict.get(dep, {}).get("virtual"):
+            deps.update(br2_virtual_is_provided_by(dep, show_info_dict))
+        else:
+            deps.add(dep)
 
-    Returns:
-        dict: A dictionary with license information for the component,
-        in CycloneDX format.
-    """
-    return {
-        "licenses": [
-            {"license": cyclonedx_license(lic.strip())} for lic in split_top_level_comma(lic_list)
-        ]
-    }
+    return list(deps)
 
 
 def extract_cves_from_header(header: str) -> list[str]:
@@ -166,7 +149,7 @@ def patch_retrieve_header(content: str) -> str:
     DIFF_LINE_REGEX = re.compile(r"^diff\s+(?:--git|-[-\w]+)\s+(\S+)\s+(\S+)$")
     INDEX_LINE_REGEX = re.compile(r"^Index:\s+(\S+)$")
 
-    lines = content.split('\n')
+    lines = content.split("\n")
 
     header = []
     for i, line in enumerate(lines):
@@ -215,6 +198,67 @@ def read_patch_file(patch_path: Path) -> str:
     return content
 
 
+def split_top_level_comma(subj):
+    """Split a string at comma's, but do not split at comma's in between parentheses.
+
+    Args:
+        subj (str): String to be split.
+
+    Returns:
+        list: A list of substrings
+    """
+    counter = 0
+    substring = ""
+
+    for char in subj:
+        if char == "," and counter == 0:
+            yield substring
+            substring = ""
+        else:
+            if char == "(":
+                counter += 1
+            elif char == ")":
+                counter -= 1
+            substring += char
+
+    yield substring
+
+
+def cyclonedx_license(lic):
+    """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
+    license names are placed under the 'name' keyword.
+
+    Args:
+        lic (str): Name of the license
+
+    Returns:
+        dict: An entry for the license in CycloneDX format.
+    """
+    key = "id" if lic in SPDX_LICENSES else "name"
+    return {
+        key: lic,
+    }
+
+
+def cyclonedx_licenses(lic_list):
+    """Create a licenses list formatted for a CycloneDX component
+
+    Args:
+        lic_list (str): A comma separated list of license names.
+
+    Returns:
+        dict: A dictionary with license information for the component,
+        in CycloneDX format.
+    """
+    return {
+        "licenses": [
+            {"license": cyclonedx_license(lic.strip())} for lic in split_top_level_comma(lic_list)
+        ]
+    }
+
+
 def cyclonedx_patches(patch_list: list[str]):
     """Translate a list of patches from the show-info JSON to a list of
     patches in CycloneDX format.
@@ -355,50 +399,6 @@ def cyclonedx_vulnerabilities(show_info_dict):
     } for cve, components in cves.items()]
 
 
-def br2_virtual_is_provided_by(ref, show_info_dict) -> list:
-    """Retrieve the list of packages that provide a virtual package.
-
-    Args:
-        ref (str): The identifier of the virtual package.
-        show_info_dict (dict): The JSON output of the show-info
-            command, parsed into a Python dictionary.
-
-    Returns:
-        list: package list that provides the virtual package.
-    """
-    return [
-        name
-        for name, comp in show_info_dict.items()
-        if "provides" in comp and ref in comp["provides"]
-    ]
-
-
-def br2_parse_deps(ref, show_info_dict, virtual=False) -> list:
-    """This function will collect all dependencies from the show-info output.
-
-    The dependency on virtual package will collect the final dependency without
-    including the virtual one.
-
-    Args:
-        ref (str): The identifier of the package for which the dependencies have
-            to be looked up.
-        show_info_dict (dict): The JSON output of the show-info
-            command, parsed into a Python dictionary.
-
-    Returns:
-        list: A list of dependencies of the 'ref' package.
-    """
-    deps = set()
-
-    for dep in show_info_dict.get(ref, {}).get("dependencies", []):
-        if not virtual and show_info_dict.get(dep, {}).get("virtual"):
-            deps.update(br2_virtual_is_provided_by(dep, show_info_dict))
-        else:
-            deps.add(dep)
-
-    return list(deps)
-
-
 def main():
     parser = argparse.ArgumentParser(
             description='''Create a CycloneDX SBoM for the Buildroot configuration.
Signature · 6 lines
2.52.0

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

PATCH v2 3/5 utils/generate-cyclonedx: encapsulate CycloneDX generation functions

In reply to Thomas Perale via buildroot

Since the script is starting to get bigger, it's also starting to get more difficult to keep track of all the different functions. This commit move all the functions that generate a part of the CycloneDX SBOM spec under the same CycloneDX dataclass.

It also allows to avoid to have to deal with a top-level shared context for the SBOM generation.

Additionnaly, two structure are created: the Context and Filter one. They hold arguments passed from the CLI.

---
 utils/generate-cyclonedx | 487 +++++++++++++++++++++------------------
 1 file changed, 265 insertions(+), 222 deletions(-)
utils/generate-cyclonedx +265 -222
index f5faec09b4..805c69c92c 100755
@@ -18,6 +18,9 @@ import urllib.request
 import subprocess
 import sys
 import re
+from typing import Mapping
+from dataclasses import dataclass, field
+from packaging.version import Version
 
 
 CYCLONEDX_VERSION = "1.6"
@@ -34,16 +37,24 @@ 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(frozen=True)
+class Options:
+    cyclonedx_version: Version
+    """CycloneDX Spec version"""
+    project_name: str
+    """Specify the project name to use in the SBOM metadata"""
+    project_version: str
+    """Specify the project version to use in the SBOM metadata"""
 
 
-def br2_retrieve_spdx_licenses(version: str):
+@dataclass(frozen=True)
+class Filters:
+    virtual: bool
+    """Includes virtual packages to the output"""
+
+
+def br2_retrieve_spdx_licenses(version: Version):
     """Populate the list of supported SPDX licenses for a given CycloneDX
     version. If the list is not present locally it will be downloaded
     externally.
@@ -224,179 +235,245 @@ def split_top_level_comma(subj):
     yield substring
 
 
-def cyclonedx_license(lic):
-    """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
-    license names are placed under the 'name' keyword.
-
-    Args:
-        lic (str): Name of the license
-
-    Returns:
-        dict: An entry for the license in CycloneDX format.
-    """
-    key = "id" if lic in SPDX_LICENSES else "name"
-    return {
-        key: lic,
-    }
-
-
-def cyclonedx_licenses(lic_list):
-    """Create a licenses list formatted for a CycloneDX component
-
-    Args:
-        lic_list (str): A comma separated list of license names.
-
-    Returns:
-        dict: A dictionary with license information for the component,
-        in CycloneDX format.
-    """
-    return {
-        "licenses": [
-            {"license": cyclonedx_license(lic.strip())} for lic in split_top_level_comma(lic_list)
-        ]
-    }
-
-
-def cyclonedx_patches(patch_list: list[str]):
-    """Translate a list of patches from the show-info JSON to a list of
-    patches in CycloneDX format.
-
-    Args:
-        patch_list (list): Array of patch relative paths for a given component.
-
-    Returns:
-        dict: Patch information in CycloneDX format.
-    """
-    patch_contents = []
-    for patch in patch_list:
-        patch_path = brpath / patch
-        if patch_path.exists():
-            try:
-                content = read_patch_file(patch_path)
-            except Exception:
-                # If the patch can't be read it won't be added to
-                # the resulting SBOM.
-                print(f"Failed to handle patch: {patch}", file=sys.stderr)
-                continue
-
-            header = patch_retrieve_header(content)
-
-            issue = {}
-            cves = extract_cves_from_header(header)
-            if cves:
-                VULN_WITH_PEDIGREE.update(cves)
-                issue = {
-                    "resolves": [
-                        {
-                            "type": "security",
-                            "name": cve
-                        } for cve in cves
-                    ]
-                }
+@dataclass
+class CycloneDX:
+    show_info_dict: Mapping
+    """Output of Buildroot `make show-info` converted as a dict."""
+    options: Options
+    """CycloneDX generation options passed from the CLI arguments"""
+    filters: Filters
+    """Filters that apply to the `show_info_dict` content"""
+    _filtered_show_info_dict: Mapping = field(default_factory=dict)
+    """Subset of `show_info_dict` based on the `Filters` passed in the the
+    `filters` argument."""
+    _spdx_licenses: list = field(default_factory=list)
+    """List of supported SPDX license expression. Initialized during the
+    `__post_init__` step, fetched either online or from local copy"""
+    _vuln_with_pedigree: set = field(default_factory=set)
+    """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'."""
+
+    def __post_init__(self):
+        self._spdx_licenses = br2_retrieve_spdx_licenses(self.options.cyclonedx_version)
+
+        # Remove rootfs and virtual packages if not explicitly included
+        # from the cli arguments
+        self._filtered_show_info_dict = {
+            k: v for k, v in self.show_info_dict.items()
+            if ("rootfs" not in v["type"]) and (self.filters.virtual or v["virtual"] is False)
+        }
+
+    def _component_licenses_license(self, lic: str):
+        """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
+        license names are placed under the 'name' keyword.
+
+        Args:
+            lic (str): Name of the license
+
+        Returns:
+            dict: An entry for the license in CycloneDX format.
+        """
+        key = "id" if lic in self._spdx_licenses else "name"
+        return {
+            key: lic,
+        }
+
+    def _component_licenses(self, lic_list: str):
+        """Create a licenses list formatted for a CycloneDX component
+
+        Args:
+            lic_list (str): A comma separated list of license names.
+
+        Returns:
+            dict: A dictionary with license information for the component,
+            in CycloneDX format.
+        """
+        return {
+            "licenses": [
+                {"license": self._component_licenses_license(lic.strip())} for lic in split_top_level_comma(lic_list)
+            ]
+        }
+
+    def _component_patches(self, patch_list: list[str]):
+        """Translate a list of patches from the show-info JSON to a list of
+        patches in CycloneDX format.
+
+        Args:
+            patch_list (list): Array of patch relative paths for a given component.
+
+        Returns:
+            dict: Patch information in CycloneDX format.
+        """
+        patch_contents = []
+        for patch in patch_list:
+            patch_path = brpath / patch
+            if patch_path.exists():
+                try:
+                    content = read_patch_file(patch_path)
+                except Exception:
+                    # If the patch can't be read it won't be added to
+                    # the resulting SBOM.
+                    print(f"Failed to handle patch: {patch}", file=sys.stderr)
+                    continue
+
+                header = patch_retrieve_header(content)
+
+                issue = {}
+                cves = extract_cves_from_header(header)
+                if cves:
+                    self._vuln_with_pedigree.update(cves)
+                    issue = {
+                        "resolves": [
+                            {
+                                "type": "security",
+                                "name": cve
+                            } for cve in cves
+                        ]
+                    }
 
-            patch_contents.append({
-                "diff": {
-                    "text": {
-                        "content": content
+                patch_contents.append({
+                    "diff": {
+                        "text": {
+                            "content": content
+                        }
+                    },
+                    **issue
+                })
+            else:
+                # If the patch is not a file it's a tarball or diff url passed
+                # through the `<pkg-name>_PATCH` variable.
+                patch_contents.append({
+                    "diff": {
+                        "url": patch
                     }
+                })
+
+        return {
+            "pedigree": {
+                "patches": [{
+                    "type": "unofficial",
+                    **content
+                } for content in patch_contents]
+            },
+        }
+
+    def _component(self, name: str, comp: dict):
+        """Translate a component from the show-info output, to a component entry in CycloneDX format.
+
+        Args:
+            name (str): Key used for the package in the show-info output.
+            comp (dict): Data about the package as a Python dictionary.
+
+        Returns:
+            dict: Component information in CycloneDX format.
+        """
+        return {
+            "bom-ref": name,
+            "type": "library",
+            **({
+                "name": comp["name"],
+            } if "name" in comp else {}),
+            **({
+                "version": comp["version"],
+                **(self._component_licenses(comp["licenses"]) if "licenses" in comp else {}),
+            } if not comp["virtual"] else {}),
+            **({
+                "cpe": comp["cpe-id"],
+            } if "cpe-id" in comp else {}),
+            **(self._component_patches(comp["patches"]) if comp.get("patches") else {}),
+            "properties": [{
+                "name": "BR_TYPE",
+                "value": comp["type"],
+            }],
+        }
+
+    def _dependency(self, ref: str, depends: list):
+        """Create JSON for dependency relationships between components.
+
+        Args:
+            ref (str): reference to a component bom-ref.
+            depends (list): array of component bom-ref identifier to create the dependencies.
+
+        Returns:
+            dict: Dependency information in CycloneDX format.
+        """
+        return {
+            "ref": ref,
+            "dependsOn": sorted(depends),
+        }
+
+    @property
+    def vulnerabilities(self):
+        """Create a JSON list of vulnerabilities ignored by buildroot and associate
+        the component for which they are solved.
+
+        Args:
+            show_info_dict (dict): The JSON output of the show-info
+                command, parsed into a Python dictionary.
+
+        Returns:
+            list: Solved vulnerabilities list in CycloneDX format.
+        """
+        cves = {}
+
+        for name, comp in self._filtered_show_info_dict.items():
+            for cve in comp.get('ignore_cves', []):
+                cves.setdefault(cve, []).append(name)
+
+        return [{
+            "id": cve,
+            "analysis": {
+                "state": "resolved_with_pedigree" if cve in self._vuln_with_pedigree else "in_triage",
+                "detail": f"The CVE '{cve}' has been marked as ignored by Buildroot"
+            },
+            "affects": [
+                {"ref": bomref} for bomref in components
+            ]
+        } for cve, components in cves.items()]
+
+    @property
+    def cyclonedx(self):
+        return {
+            "bomFormat": "CycloneDX",
+            "$schema": f"http://cyclonedx.org/schema/bom-{self.options.cyclonedx_version}.schema.json",
+            "specVersion": f"{self.options.cyclonedx_version}",
+            "metadata": {
+                "component": {
+                    "bom-ref": self.options.project_name,
+                    "name": self.options.project_name,
+                    "version": self.options.project_version,
+                    "type": "firmware",
                 },
-                **issue
-            })
-        else:
-            # If the patch is not a file it's a tarball or diff url passed
-            # through the `<pkg-name>_PATCH` variable.
-            patch_contents.append({
-                "diff": {
-                    "url": patch
+                "tools": {
+                    "components": [
+                        {
+                            "type": "application",
+                            "name": "Buildroot generate-cyclonedx",
+                            "version": f"{BR2_VERSION_FULL}",
+                            "licenses": [
+                                {
+                                    "license": {
+                                        "id": "GPL-2.0"
+                                    }
+                                }
+                            ]
+                        }
+                    ],
                 }
-            })
-
-    return {
-        "pedigree": {
-            "patches": [{
-                "type": "unofficial",
-                **content
-            } for content in patch_contents]
-        },
-    }
-
-
-def cyclonedx_component(name, comp):
-    """Translate a component from the show-info output, to a component entry in CycloneDX format.
-
-    Args:
-        name (str): Key used for the package in the show-info output.
-        comp (dict): Data about the package as a Python dictionary.
-
-    Returns:
-        dict: Component information in CycloneDX format.
-    """
-    return {
-        "bom-ref": name,
-        "type": "library",
-        **({
-            "name": comp["name"],
-        } if "name" in comp else {}),
-        **({
-            "version": comp["version"],
-            **(cyclonedx_licenses(comp["licenses"]) 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 {}),
-        "properties": [{
-            "name": "BR_TYPE",
-            "value": comp["type"],
-        }],
-    }
-
-
-def cyclonedx_dependency(ref, depends):
-    """Create JSON for dependency relationships between components.
-
-    Args:
-        ref (str): reference to a component bom-ref.
-        depends (list): array of component bom-ref identifier to create the dependencies.
-
-    Returns:
-        dict: Dependency information in CycloneDX format.
-    """
-    return {
-        "ref": ref,
-        "dependsOn": sorted(depends),
-    }
-
-
-def cyclonedx_vulnerabilities(show_info_dict):
-    """Create a JSON list of vulnerabilities ignored by buildroot and associate
-    the component for which they are solved.
-
-    Args:
-        show_info_dict (dict): The JSON output of the show-info
-            command, parsed into a Python dictionary.
-
-    Returns:
-        list: Solved vulnerabilities list in CycloneDX format.
-    """
-    cves = {}
-
-    for name, comp in show_info_dict.items():
-        for cve in comp.get('ignore_cves', []):
-            cves.setdefault(cve, []).append(name)
-
-    return [{
-        "id": cve,
-        "analysis": {
-            "state": "resolved_with_pedigree" if cve in VULN_WITH_PEDIGREE else "in_triage",
-            "detail": f"The CVE '{cve}' has been marked as ignored by Buildroot"
-        },
-        "affects": [
-            {"ref": bomref} for bomref in components
-        ]
-    } for cve, components in cves.items()]
+            },
+            "components": [
+                self._component(name, comp) for name, comp in self._filtered_show_info_dict.items()
+            ],
+            "dependencies": [
+                self._dependency(self.options.project_name, list(self._filtered_show_info_dict)),
+                *[self._dependency(ref, br2_parse_deps(ref, self.show_info_dict, self.filters.virtual))
+                  for ref in self._filtered_show_info_dict],
+            ],
+            "vulnerabilities": self.vulnerabilities,
+        }
 
 
 def main():
@@ -422,55 +499,21 @@ def main():
         parser.print_help()
         sys.exit(1)
 
-    SPDX_LICENSES.extend(br2_retrieve_spdx_licenses(CYCLONEDX_VERSION))
+    opt = Options(
+        cyclonedx_version=Version(CYCLONEDX_VERSION),
+        project_name=args.project_name,
+        project_version=args.project_version,
+    )
+
+    filters = Filters(
+        virtual=args.virtual
+    )
 
     show_info_dict = json.load(args.in_file)
 
-    # Remove rootfs and virtual packages if not explicitly included
-    # from the cli arguments
-    filtered_show_info_dict = {k: v for k, v in show_info_dict.items()
-                               if ("rootfs" not in v["type"]) and (args.virtual or v["virtual"] is False)}
-
-    cyclonedx_dict = {
-        "bomFormat": "CycloneDX",
-        "$schema": f"http://cyclonedx.org/schema/bom-{CYCLONEDX_VERSION}.schema.json",
-        "specVersion": f"{CYCLONEDX_VERSION}",
-        "metadata": {
-            "component": {
-                "bom-ref": args.project_name,
-                "name": args.project_name,
-                "version": args.project_version,
-                "type": "firmware",
-            },
-            "tools": {
-                "components": [
-                    {
-                        "type": "application",
-                        "name": "Buildroot generate-cyclonedx",
-                        "version": f"{BR2_VERSION_FULL}",
-                        "licenses": [
-                            {
-                                "license": {
-                                    "id": "GPL-2.0"
-                                }
-                            }
-                        ]
-                    }
-                ],
-            }
-        },
-        "components": [
-            cyclonedx_component(name, comp) 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),
-    }
-
-    args.out_file.write(json.dumps(cyclonedx_dict, indent=2))
+    out = CycloneDX(show_info_dict=show_info_dict, options=opt, filters=filters)
+
+    args.out_file.write(json.dumps(out.cyclonedx, indent=2))
     args.out_file.write('\n')
 
 
Signature · 6 lines
2.52.0

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

PATCH v2 4/5 utils/generate-cyclonedx: optional bump to v1.7

In reply to Thomas Perale via buildroot

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 | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
utils/generate-cyclonedx +5 -3
index 805c69c92c..66eae08c01 100755
@@ -22,8 +22,7 @@ from typing import Mapping
 from dataclasses import dataclass, field
 from packaging.version import Version
 
-
-CYCLONEDX_VERSION = "1.6"
+DEFAULT_CYCLONEDX_VERSION = "1.6"
 
 brpath = Path(__file__).parent.parent
 
@@ -492,6 +491,9 @@ def main():
                         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}",
                         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()
 
@@ -500,7 +502,7 @@ def main():
         sys.exit(1)
 
     opt = Options(
-        cyclonedx_version=Version(CYCLONEDX_VERSION),
+        cyclonedx_version=Version(args.cdx_version),
         project_name=args.project_name,
         project_version=args.project_version,
     )
Signature · 6 lines
2.52.0

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

PATCH v2 5/5 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 66eae08c01..25bf5506d2 100755
@@ -372,6 +372,9 @@ class CycloneDX:
         return {
             "bom-ref": name,
             "type": "library",
+            **({
+                "isExternal": True
+            } if self.options.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
author Acked-by Titouan Christophe on v2 1/5
#5 lore raw
In reply to Thomas Perale via buildroot

Hi Thomas,

Quoted 9 lines · Thomas Perale

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.

Quoted 74 lines
---
  utils/generate-cyclonedx | 46 ++++++++++++++++++++++++++++------------
  1 file changed, 33 insertions(+), 13 deletions(-)
utils/generate-cyclonedx +31 -13
index 2b6c6d63d3..93b648e481 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,20 +39,40 @@ 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)
 
-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)
+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.
+
+    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):

utils/generate-cyclonedx def main(): · line 429

Quoted 8 lines
utils/generate-cyclonedx +2 -0
@@ -404,6 +422,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

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