diff --git a/Tools/ci/generate_sbom.py b/Tools/ci/generate_sbom.py index cbca30db397..7d2cb3c189e 100755 --- a/Tools/ci/generate_sbom.py +++ b/Tools/ci/generate_sbom.py @@ -1,16 +1,24 @@ #!/usr/bin/env python3 -"""Generate SPDX 2.3 JSON SBOM for a PX4 firmware build. +"""Generate an SPDX 3.0.1 JSON-LD SBOM for a PX4 firmware build. Produces one SBOM per board target containing: -- PX4 firmware as the primary package -- Git submodules as CONTAINS dependencies -- Python build requirements as BUILD_DEPENDENCY_OF packages -- Board-specific modules as CONTAINS packages +- PX4 firmware as the primary package (the document's root element) +- Git submodules and board-specific modules, which the firmware contains +- Python build requirements, which the firmware depends on at build time +- The compiler, which the firmware uses as a build tool -Requires PyYAML (pyyaml) for loading license overrides. +Licenses are expressed as LicenseExpression elements linked to each package +by hasDeclaredLicense and hasConcludedLicense relationships. A package whose +license is unknown is linked to the NoAssertionLicense individual, so the +SBOM states explicitly that the license is unknown. Unknown copyright text is +recorded as NOASSERTION for the same reason. + +The output uses only the standard library plus PyYAML (for the overrides +file), so it runs unchanged in every build container. """ import argparse import configparser +import hashlib import json import re import subprocess @@ -44,27 +52,73 @@ COPYLEFT_LICENSES = { "AGPL-3.0-only", } -def load_license_overrides(source_dir): - """Load license overrides and comments from YAML config file. +SPDX_SPEC_VERSION = "3.0.1" +SPDX_CONTEXT = "https://spdx.org/rdf/3.0.1/spdx-context.jsonld" +SPDX_LICENSE_LIST_VERSION = "3.22.0" +CREATION_INFO_ID = "_:creationinfo" +NOASSERTION = "NOASSERTION" +NOASSERTION_LICENSE = "expandedlicensing_NoAssertionLicense" - Returns (overrides, comments) dicts mapping submodule path to values. - Falls back to empty dicts if the file is missing. +PX4_REPO_URL = "https://github.com/PX4/PX4-Autopilot" +PX4_COPYRIGHT = "Copyright (c) PX4 Development Team" +PX4_ORGANIZATION = "Dronecode Foundation" +PYPI_ORGANIZATION = "Python Package Index" + +# Compiler vendors recognized from the first line of ` --version`. +# Unrecognized compilers get no supplier rather than a guessed one. +COMPILER_VENDORS = [ + ("Arm GNU Toolchain", "Arm Limited"), + ("GNU Arm Embedded Toolchain", "Arm Limited"), + ("Apple clang", "Apple Inc."), + ("Ubuntu", "Canonical Ltd."), +] + + +def load_overrides(source_dir): + """Load per-submodule SBOM metadata from Tools/ci/license-overrides.yaml. + + Returns (overrides, organizations): overrides maps a submodule path to its + entry (license, comment, copyright, originator, requires, scope), and + organizations maps a git host organization to a display name. Both are + empty if the file is missing. """ yaml_path = source_dir / "Tools" / "ci" / "license-overrides.yaml" if not yaml_path.exists(): return {}, {} with open(yaml_path) as f: - data = yaml.safe_load(f) + data = yaml.safe_load(f) or {} - overrides = {} - comments = {} - for path, entry in (data.get("overrides") or {}).items(): - overrides[path] = entry["license"] - if "comment" in entry: - comments[path] = entry["comment"] + organizations = {k.lower(): v for k, v in (data.get("organizations") or {}).items()} + return data.get("overrides") or {}, organizations - return overrides, comments + +def license_overrides(overrides): + """Map submodule path to overridden license, for entries that set one.""" + return {path: entry["license"] for path, entry in overrides.items() if "license" in entry} + + +def load_board_config(board_config): + """Read a Kconfig boardconfig file into a dict of enabled symbols.""" + if not board_config or not board_config.exists(): + return None + config = {} + for line in board_config.read_text().splitlines(): + match = re.match(r"^(CONFIG_[A-Za-z0-9_]+)=(.*)$", line.strip()) + if match and match.group(2) != "n": + config[match.group(1)] = match.group(2) + return config + + +def requirement_met(requires, board_config): + """Evaluate a `requires` entry ("CONFIG_X" or "!CONFIG_X") against the board config. + + Without a board config the requirement cannot be checked and is treated as met. + """ + if not requires or board_config is None: + return True + negate = requires.startswith("!") + return (requires.lstrip("!") in board_config) != negate LICENSE_FILENAMES = ["LICENSE", "LICENSE.md", "LICENSE.txt", "LICENCE", "LICENCE.md", "COPYING", "COPYING.md"] @@ -95,10 +149,10 @@ def detect_license(submodule_dir): return "NOASSERTION" -def get_submodule_license(source_dir, sub_path, license_overrides): +def get_submodule_license(source_dir, sub_path, overridden): """Return the SPDX license for a submodule: override > auto-detect.""" - if sub_path in license_overrides: - return license_overrides[sub_path] + if sub_path in overridden: + return overridden[sub_path] return detect_license(source_dir / sub_path) @@ -127,57 +181,100 @@ def parse_gitmodules(source_dir): return submodules -def get_submodule_commits(source_dir): - """Get commit hashes for all submodules via git ls-tree -r (works without init).""" +def run_command(args, cwd=None): + """Run a command and return its stdout, or None if it fails or is missing.""" try: result = subprocess.run( - ["git", "ls-tree", "-r", "HEAD"], - cwd=str(source_dir), + args, + cwd=str(cwd) if cwd else None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - text=True, + universal_newlines=True, check=True, ) - except (subprocess.CalledProcessError, FileNotFoundError): - return {} + except (subprocess.CalledProcessError, OSError): + return None + return result.stdout - commits = {} - for line in result.stdout.splitlines(): - parts = line.split() - if len(parts) >= 4 and parts[1] == "commit": - commits[parts[3]] = parts[2] - return commits +def get_git_objects(source_dir): + """Map paths in HEAD to (object type, hash) via git ls-tree (works without init). + + Covers submodule commits and directory trees, which give the submodule + versions and the content identifiers of PX4 modules. + """ + output = run_command(["git", "ls-tree", "-r", "-t", "HEAD"], source_dir) or "" + objects = {} + for line in output.splitlines(): + meta, _, path = line.partition("\t") + parts = meta.split() + if len(parts) == 3 and parts[1] in ("commit", "tree"): + objects[path] = (parts[1], parts[2]) + return objects + + +def get_dirty_paths(source_dir): + """Return the paths that differ from HEAD (modified, staged or untracked).""" + output = run_command(["git", "status", "--porcelain", "--ignore-submodules=all"], source_dir) or "" + return [line[3:].split(" -> ")[-1].strip('"') for line in output.splitlines()] def get_git_info(source_dir: Path) -> dict: - """Get PX4 git version and hash.""" - info = {"version": "unknown", "hash": "unknown"} + """Get the PX4 version (git describe), commit hash and exact tag, if any.""" + describe = run_command(["git", "describe", "--always", "--tags", "--dirty"], source_dir) + commit = run_command(["git", "rev-parse", "HEAD"], source_dir) + tag = run_command(["git", "describe", "--exact-match", "--tags", "HEAD"], source_dir) + commit = commit.strip() if commit else "unknown" + return { + "version": describe.strip() if describe else "unknown", + "hash": commit, + # purl versions must be a tag or a commit, never a describe string + "purl_version": tag.strip() if tag else commit, + } + + +def get_python_package_version(name): + """Return the installed version of a Python distribution, or None. + + Uses the interpreter running the generator, which is the one the build + uses for its Python tooling. + """ try: - result = subprocess.run( - ["git", "describe", "--always", "--tags", "--dirty"], - cwd=str(source_dir), - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, - check=True, - ) - info["version"] = result.stdout.strip() - except (subprocess.CalledProcessError, FileNotFoundError): - pass + from importlib import metadata + except ImportError: + return None try: - result = subprocess.run( - ["git", "rev-parse", "HEAD"], - cwd=str(source_dir), - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, - check=True, - ) - info["hash"] = result.stdout.strip() - except (subprocess.CalledProcessError, FileNotFoundError): - pass - return info + return metadata.version(name) + except metadata.PackageNotFoundError: + return None + + +def get_compiler_info(compiler): + """Return (name, version, vendor) for a compiler path; unknown parts are None.""" + name = Path(compiler).name + version = run_command([compiler, "-dumpfullversion"]) or run_command([compiler, "-dumpversion"]) + banner = (run_command([compiler, "--version"]) or "").splitlines() + first_line = banner[0] if banner else "" + vendor = next((v for marker, v in COMPILER_VENDORS if marker in first_line), None) + return name, version.strip() if version else None, vendor + + +def sha256_file(path): + digest = hashlib.sha256() + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def swhid(object_type, object_hash): + """Software Heritage ID for a git object: commits are revisions, trees are directories.""" + kind = {"commit": "rev", "tree": "dir"}[object_type] + return { + "type": "software_ContentIdentifier", + "software_contentIdentifierType": "swhid", + "software_contentIdentifierValue": f"swh:1:{kind}:{object_hash}", + } def parse_requirements(requirements_path): @@ -227,11 +324,13 @@ def read_module_list(modules_file, source_dir): return modules -def make_purl(pkg_type: str, namespace: str, name: str, version: str = "") -> str: +def make_purl(pkg_type: str, namespace: str, name: str, version: str = "", subpath: str = "") -> str: """Construct a Package URL (purl).""" - purl = f"pkg:{pkg_type}/{namespace}/{name}" + purl = f"pkg:{pkg_type}/{namespace}/{name}" if namespace else f"pkg:{pkg_type}/{name}" if version: purl += f"@{version}" + if subpath: + purl += f"#{subpath}" return purl @@ -249,72 +348,157 @@ def extract_git_host_org_repo(url): return "", "", "" -def generate_sbom(source_dir, board, modules_file, compiler, platform=""): - """Generate a complete SPDX 2.3 JSON document.""" - license_overrides, license_comments = load_license_overrides(source_dir) +class SpdxGraph: + """Collects the elements of an SPDX 3 JSON-LD document. + + Every element gets an IRI under the document namespace and refers to one + shared CreationInfo blank node. Organizations and license expressions are + created once and reused by every element that refers to them. + """ + + def __init__(self, namespace, created): + self.namespace = namespace + self.creation_info = { + "type": "CreationInfo", + "@id": CREATION_INFO_ID, + "specVersion": SPDX_SPEC_VERSION, + "created": created, + "createdBy": [], + "createdUsing": [], + } + self.elements = [] + self._organizations = {} + self._licenses = {} + self._relationship_count = 0 + + def iri(self, local_id): + return f"{self.namespace}#{spdx_id(local_id)}" + + def add(self, element_type, local_id, props): + """Add an element, dropping properties whose value is None.""" + element = { + "type": element_type, + "spdxId": self.iri(local_id), + "creationInfo": CREATION_INFO_ID, + } + element.update({k: v for k, v in props.items() if v is not None}) + self.elements.append(element) + return element["spdxId"] + + def organization(self, name): + if name not in self._organizations: + self._organizations[name] = self.add( + "Organization", f"Organization-{name}", {"name": name}) + return self._organizations[name] + + def license(self, expression): + if expression not in self._licenses: + self._licenses[expression] = self.add( + "simplelicensing_LicenseExpression", f"License-{expression}", { + "simplelicensing_licenseExpression": expression, + "simplelicensing_licenseListVersion": SPDX_LICENSE_LIST_VERSION, + }) + return self._licenses[expression] + + def relate(self, from_id, relationship_type, to_ids, scope=None, comment=None): + """Add a Relationship, or a LifecycleScopedRelationship when scoped.""" + self._relationship_count += 1 + return self.add( + "LifecycleScopedRelationship" if scope else "Relationship", + f"Relationship-{self._relationship_count}", { + "from": from_id, + "relationshipType": relationship_type, + "to": list(to_ids), + "scope": scope, + "comment": comment, + }) + + def set_license(self, package_id, license_id, comment=None): + """Declare and conclude a license; NOASSERTION links to NoAssertionLicense.""" + if license_id == NOASSERTION: + license_ref = NOASSERTION_LICENSE + else: + license_ref = self.license(license_id) + self.relate(package_id, "hasDeclaredLicense", [license_ref]) + self.relate(package_id, "hasConcludedLicense", [license_ref], comment=comment) + + +def generate_sbom(source_dir, board, modules_file, compiler, platform="", + board_config=None, firmware_file=None): + """Generate a complete SPDX 3.0.1 JSON-LD document.""" + overrides, org_names = load_overrides(source_dir) + overridden = license_overrides(overrides) + config = load_board_config(board_config) git_info = get_git_info(source_dir) + git_objects = get_git_objects(source_dir) + dirty_paths = get_dirty_paths(source_dir) timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") # Deterministic namespace using UUID5 from git hash + board ns_seed = f"{git_info['hash']}:{board}" doc_namespace = f"https://spdx.org/spdxdocs/{board}-{uuid.uuid5(uuid.NAMESPACE_URL, ns_seed)}" - doc = { - "spdxVersion": "SPDX-2.3", - "dataLicense": "CC0-1.0", - "SPDXID": "SPDXRef-DOCUMENT", - "name": f"PX4 Firmware SBOM for {board}", - "documentNamespace": doc_namespace, - "creationInfo": { - "created": timestamp, - "creators": [ - "Tool: px4-generate-sbom", - "Organization: Dronecode Foundation", - ], - "licenseListVersion": "3.22", - }, - "packages": [], - "relationships": [], - } + graph = SpdxGraph(doc_namespace, timestamp) + dronecode = graph.organization(PX4_ORGANIZATION) + + def supplier(org): + """Organization element for a git host organization, by display name.""" + return graph.organization(org_names.get(org.lower(), org)) if org else None + + def px4_purl(subpath=""): + return make_purl("github", "PX4", "PX4-Autopilot", git_info["purl_version"], subpath) + + def content_id(path): + """SWHID of a path in HEAD, unless the working tree changed it.""" + if path not in git_objects or any(d == path or d.startswith(path + "/") for d in dirty_paths): + return None + return [swhid(*git_objects[path])] + + tool = graph.add("Tool", "Tool-px4-generate-sbom", { + "name": f"px4-generate-sbom {git_info['version']}", + "externalIdentifier": [{ + "type": "ExternalIdentifier", + "externalIdentifierType": "packageUrl", + "identifier": px4_purl("Tools/ci/generate_sbom.py"), + }], + }) + graph.creation_info["createdBy"].append(dronecode) + graph.creation_info["createdUsing"].append(tool) # Primary package: PX4 firmware - primary_spdx_id = f"SPDXRef-PX4-{spdx_id(board)}" - doc["packages"].append({ - "SPDXID": primary_spdx_id, + primary = graph.add("software_Package", f"PX4-{board}", { "name": board, - "versionInfo": git_info["version"], - "packageFileName": f"{board}.px4", - "supplier": "Organization: Dronecode Foundation", - "downloadLocation": "https://github.com/PX4/PX4-Autopilot", - "filesAnalyzed": False, - "primaryPackagePurpose": "FIRMWARE", - "licenseConcluded": "BSD-3-Clause", - "licenseDeclared": "BSD-3-Clause", - "copyrightText": "Copyright (c) PX4 Development Team", - "externalRefs": [ - { - "referenceCategory": "PACKAGE-MANAGER", - "referenceType": "purl", - "referenceLocator": make_purl( - "github", "PX4", "PX4-Autopilot", git_info["version"] - ), - } - ], + "software_packageVersion": git_info["version"], + "software_downloadLocation": PX4_REPO_URL, + "software_packageUrl": px4_purl(), + "software_primaryPurpose": "firmware", + "software_copyrightText": PX4_COPYRIGHT, + "suppliedBy": dronecode, }) + graph.set_license(primary, "BSD-3-Clause") - doc["relationships"].append({ - "spdxElementId": "SPDXRef-DOCUMENT", - "relationshipType": "DESCRIBES", - "relatedSpdxElement": primary_spdx_id, - }) + # The distributed firmware file, only for builds that produce one + if firmware_file and firmware_file.is_file(): + firmware = graph.add("software_File", f"File-{firmware_file.name}", { + "name": firmware_file.name, + "software_fileKind": "file", + "software_primaryPurpose": "firmware", + "verifiedUsing": [{ + "type": "Hash", + "algorithm": "sha256", + "hashValue": sha256_file(firmware_file), + }], + }) + graph.relate(primary, "hasDistributionArtifact", [firmware]) # Git submodules (filtered to those relevant to this board's modules) submodules = parse_gitmodules(source_dir) - submodule_commits = get_submodule_commits(source_dir) modules = read_module_list(modules_file, source_dir) def submodule_is_relevant(sub_path): """A submodule is relevant if any board module path overlaps with it.""" + if not requirement_met(overrides.get(sub_path, {}).get("requires"), config): + return False # NuttX platform submodules are only relevant for NuttX builds if sub_path.startswith("platforms/nuttx/"): return platform in ("nuttx", "") @@ -329,141 +513,113 @@ def generate_sbom(source_dir, board, modules_file, compiler, platform=""): return True return False + contained = [] + build_deps = [] + for sub in submodules: if not submodule_is_relevant(sub["path"]): continue sub_path = sub["path"] - sub_path_id = sub_path.replace("/", "-") - sub_spdx_id = f"SPDXRef-Submodule-{spdx_id(sub_path_id)}" - commit = submodule_commits.get(sub_path, "unknown") - license_id = get_submodule_license(source_dir, sub_path, license_overrides) + entry = overrides.get(sub_path, {}) + commit = git_objects.get(sub_path, (None, None))[1] + license_id = get_submodule_license(source_dir, sub_path, overridden) host, org, repo = extract_git_host_org_repo(sub["url"]) - download = sub["url"] if sub["url"] else "NOASSERTION" # Use repo name from URL for human-readable name, fall back to last path component display_name = repo if repo else sub_path.rsplit("/", 1)[-1] - pkg = { - "SPDXID": sub_spdx_id, + sub_id = graph.add("software_Package", f"Submodule-{sub_path.replace('/', '-')}", { "name": display_name, - "versionInfo": commit, - "supplier": f"Organization: {org}" if org else "NOASSERTION", - "downloadLocation": download, - "filesAnalyzed": False, - "licenseConcluded": license_id, - "licenseDeclared": license_id, - "copyrightText": "NOASSERTION", - } - - comment = license_comments.get(sub_path) - if comment: - pkg["licenseComments"] = comment - - if host and org and repo: - pkg["externalRefs"] = [ - { - "referenceCategory": "PACKAGE-MANAGER", - "referenceType": "purl", - "referenceLocator": make_purl(host, org, repo, commit), - } - ] - - doc["packages"].append(pkg) - doc["relationships"].append({ - "spdxElementId": primary_spdx_id, - "relationshipType": "CONTAINS", - "relatedSpdxElement": sub_spdx_id, - }) - - # Python build dependencies - requirements_path = source_dir / "Tools" / "setup" / "requirements.txt" - py_deps = parse_requirements(requirements_path) - - for dep in py_deps: - dep_name = dep["name"] - dep_spdx_id = f"SPDXRef-PyDep-{spdx_id(dep_name)}" - version_str = dep["version_spec"] if dep["version_spec"] else "NOASSERTION" - - doc["packages"].append({ - "SPDXID": dep_spdx_id, - "name": dep_name, - "versionInfo": version_str, - "supplier": "NOASSERTION", - "downloadLocation": f"https://pypi.org/project/{dep_name}/", - "filesAnalyzed": False, - "primaryPackagePurpose": "APPLICATION", - "licenseConcluded": "NOASSERTION", - "licenseDeclared": "NOASSERTION", - "copyrightText": "NOASSERTION", - "externalRefs": [ - { - "referenceCategory": "PACKAGE-MANAGER", - "referenceType": "purl", - "referenceLocator": f"pkg:pypi/{dep_name}", - } - ], - }) - doc["relationships"].append({ - "spdxElementId": dep_spdx_id, - "relationshipType": "BUILD_DEPENDENCY_OF", - "relatedSpdxElement": primary_spdx_id, + "software_packageVersion": commit, + "software_downloadLocation": sub["url"] or None, + "software_packageUrl": make_purl(host, org, repo, commit) if host and org and repo else None, + "software_copyrightText": entry.get("copyright", NOASSERTION), + "software_contentIdentifier": [swhid("commit", commit)] if commit else None, + "suppliedBy": supplier(org), + "originatedBy": [graph.organization(entry["originator"])] if "originator" in entry else None, }) + graph.set_license(sub_id, license_id, comment=entry.get("comment")) + (build_deps if entry.get("scope") == "build" else contained).append(sub_id) # Board-specific modules (already read above for submodule filtering) for mod in modules: - mod_path_id = mod.replace("/", "-") - mod_spdx_id = f"SPDXRef-Module-{spdx_id(mod_path_id)}" - # Derive short name: strip leading src/ for readability display_name = mod if display_name.startswith("src/"): display_name = display_name[4:] - doc["packages"].append({ - "SPDXID": mod_spdx_id, + mod_id = graph.add("software_Package", f"Module-{mod.replace('/', '-')}", { "name": display_name, - "versionInfo": git_info["version"], - "supplier": "Organization: Dronecode Foundation", - "downloadLocation": "https://github.com/PX4/PX4-Autopilot", - "filesAnalyzed": False, - "licenseConcluded": "BSD-3-Clause", - "licenseDeclared": "BSD-3-Clause", - "copyrightText": "NOASSERTION", + "software_packageVersion": git_info["version"], + "software_downloadLocation": PX4_REPO_URL, + "software_packageUrl": px4_purl(mod), + "software_copyrightText": PX4_COPYRIGHT, + "software_contentIdentifier": content_id(mod), + "suppliedBy": dronecode, }) - doc["relationships"].append({ - "spdxElementId": primary_spdx_id, - "relationshipType": "CONTAINS", - "relatedSpdxElement": mod_spdx_id, + graph.set_license(mod_id, "BSD-3-Clause") + contained.append(mod_id) + + if contained: + graph.relate(primary, "contains", contained) + + # Python build dependencies, at the version installed in the build environment + requirements_path = source_dir / "Tools" / "setup" / "requirements.txt" + pypi = graph.organization(PYPI_ORGANIZATION) + + for dep in parse_requirements(requirements_path): + dep_name = dep["name"] + version = get_python_package_version(dep_name) + dep_id = graph.add("software_Package", f"PyDep-{dep_name}", { + "name": dep_name, + "software_packageVersion": version, + "software_downloadLocation": f"https://pypi.org/project/{dep_name}/", + "software_packageUrl": make_purl("pypi", "", dep_name.lower().replace("_", "-"), version), + "software_primaryPurpose": "application", + "software_copyrightText": NOASSERTION, + "suppliedBy": pypi, }) + graph.set_license(dep_id, NOASSERTION) + build_deps.append(dep_id) + + if build_deps: + graph.relate(primary, "dependsOn", build_deps, scope="build") # Compiler as a build tool if compiler: - compiler_spdx_id = f"SPDXRef-Compiler-{spdx_id(compiler)}" - doc["packages"].append({ - "SPDXID": compiler_spdx_id, - "name": compiler, - "versionInfo": "NOASSERTION", - "supplier": "NOASSERTION", - "downloadLocation": "NOASSERTION", - "filesAnalyzed": False, - "primaryPackagePurpose": "APPLICATION", - "licenseConcluded": "NOASSERTION", - "licenseDeclared": "NOASSERTION", - "copyrightText": "NOASSERTION", - }) - doc["relationships"].append({ - "spdxElementId": compiler_spdx_id, - "relationshipType": "BUILD_TOOL_OF", - "relatedSpdxElement": primary_spdx_id, + name, version, vendor = get_compiler_info(compiler) + compiler_id = graph.add("software_Package", f"Compiler-{name}", { + "name": name, + "software_packageVersion": version, + "software_packageUrl": make_purl("generic", "", name, version), + "software_primaryPurpose": "application", + "software_copyrightText": NOASSERTION, + "suppliedBy": graph.organization(vendor) if vendor else None, }) + graph.set_license(compiler_id, NOASSERTION) + graph.relate(primary, "usesTool", [compiler_id], scope="build") - return doc + document = { + "type": "SpdxDocument", + "spdxId": graph.iri("SpdxDocument"), + "creationInfo": CREATION_INFO_ID, + "name": f"PX4 Firmware SBOM for {board}", + "dataLicense": graph.license("CC0-1.0"), + "profileConformance": ["core", "software", "simpleLicensing"], + "rootElement": [primary], + "element": [e["spdxId"] for e in graph.elements], + } + + return { + "@context": SPDX_CONTEXT, + "@graph": [graph.creation_info, document] + graph.elements, + } def verify_licenses(source_dir): """Verify license detection for all submodules. Returns exit code.""" - license_overrides, _ = load_license_overrides(source_dir) + overridden = license_overrides(load_overrides(source_dir)[0]) submodules = parse_gitmodules(source_dir) if not submodules: print("No submodules found in .gitmodules") @@ -478,14 +634,14 @@ def verify_licenses(source_dir): sub_dir = source_dir / sub_path checked_out = sub_dir.is_dir() and any(sub_dir.iterdir()) - has_explicit_override = sub_path in license_overrides + has_explicit_override = sub_path in overridden if not checked_out: detected = "(not checked out)" - override = license_overrides.get(sub_path, "") + override = overridden.get(sub_path, "") final = override if override else "NOASSERTION" else: detected = detect_license(sub_dir) - override = license_overrides.get(sub_path, "") + override = overridden.get(sub_path, "") final = override if override else detected if final == "NOASSERTION" and has_explicit_override: @@ -507,7 +663,7 @@ def verify_licenses(source_dir): sub_path = sub["path"] sub_dir = source_dir / sub_path checked_out = sub_dir.is_dir() and any(sub_dir.iterdir()) - override = license_overrides.get(sub_path, "") + override = overridden.get(sub_path, "") if checked_out: final_lic = override if override else detect_license(sub_dir) else: @@ -535,7 +691,7 @@ def verify_licenses(source_dir): def main(): parser = argparse.ArgumentParser( - description="Generate SPDX 2.3 JSON SBOM for PX4 firmware" + description="Generate SPDX 3.0.1 JSON-LD SBOM for PX4 firmware" ) parser.add_argument( "--source-dir", @@ -569,6 +725,18 @@ def main(): default="", help="PX4 platform (nuttx, posix, qurt). Filters platform-specific submodules.", ) + parser.add_argument( + "--board-config", + type=Path, + default=None, + help="Kconfig boardconfig file, used to evaluate `requires` entries in the overrides file", + ) + parser.add_argument( + "--firmware-file", + type=Path, + default=None, + help="Firmware file the build distributes (e.g. the .px4), recorded with its SHA-256", + ) parser.add_argument( "--output", type=Path, @@ -592,6 +760,8 @@ def main(): modules_file=args.modules_file, compiler=args.compiler, platform=args.platform, + board_config=args.board_config, + firmware_file=args.firmware_file, ) args.output.parent.mkdir(parents=True, exist_ok=True) @@ -599,7 +769,7 @@ def main(): json.dump(sbom, f, indent=2) f.write("\n") - pkg_count = len(sbom["packages"]) + pkg_count = sum(1 for e in sbom["@graph"] if e["type"] == "software_Package") print(f"SBOM generated: {args.output} ({pkg_count} packages)") diff --git a/Tools/ci/inspect_sbom.py b/Tools/ci/inspect_sbom.py index ac31660c806..4be3b28a81b 100755 --- a/Tools/ci/inspect_sbom.py +++ b/Tools/ci/inspect_sbom.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Inspect a PX4 SPDX SBOM file. +"""Inspect a PX4 SPDX 3 SBOM file. Usage: inspect_sbom.py # full summary @@ -14,103 +14,170 @@ import sys from collections import Counter from pathlib import Path +RELATIONSHIP_TYPES = ("Relationship", "LifecycleScopedRelationship") +NOASSERTION = "NOASSERTION" +# SPDX individuals that license relationships may point to instead of an element +LICENSE_INDIVIDUALS = { + "expandedlicensing_NoAssertionLicense": NOASSERTION, + "expandedlicensing_NoneLicense": "NONE", +} -def load(path): - return json.loads(Path(path).read_text()) + +class Sbom: + """Index over the @graph of a PX4 SPDX 3 JSON-LD document.""" + + def __init__(self, doc): + graph = doc["@graph"] + self.by_id = {e["spdxId"]: e for e in graph if "spdxId" in e} + self.creation_info = next(e for e in graph if e["type"] == "CreationInfo") + self.document = next(e for e in graph if e["type"] == "SpdxDocument") + self.packages = [e for e in graph if e["type"] == "software_Package"] + self.relationships = [e for e in graph if e["type"] in RELATIONSHIP_TYPES] + self.root = self.by_id[self.document["rootElement"][0]] + + self.declared = {} + self.contained = set() + for r in self.relationships: + if r["relationshipType"] == "hasDeclaredLicense": + to = r["to"][0] + self.declared[r["from"]] = ( + LICENSE_INDIVIDUALS[to] if to in LICENSE_INDIVIDUALS + else self.by_id[to]["simplelicensing_licenseExpression"]) + elif r["relationshipType"] == "contains" and r["from"] == self.root["spdxId"]: + self.contained.update(r["to"]) + + def license(self, pkg): + return self.declared.get(pkg["spdxId"], NOASSERTION) + + def supplier(self, pkg): + return self.by_id[pkg["suppliedBy"]]["name"] if "suppliedBy" in pkg else None + + def originator(self, pkg): + return self.names(pkg["originatedBy"]) if "originatedBy" in pkg else None + + def names(self, ids): + return ", ".join(self.by_id[i]["name"] for i in ids) def pkg_type(pkg): - spdx_id = pkg["SPDXID"] + local_id = pkg["spdxId"].split("#", 1)[-1] for prefix in ("Submodule", "PyDep", "Module", "Compiler", "PX4"): - if f"-{prefix}-" in spdx_id or spdx_id.startswith(f"SPDXRef-{prefix}"): + if local_id.startswith(f"{prefix}-"): return prefix return "Other" -def summary(doc): - print(f"spdxVersion: {doc['spdxVersion']}") - print(f"name: {doc['name']}") - print(f"namespace: {doc['documentNamespace']}") - print(f"created: {doc['creationInfo']['created']}") - print(f"creators: {', '.join(doc['creationInfo']['creators'])}") +def summary(sbom): + print(f"specVersion: {sbom.creation_info['specVersion']}") + print(f"name: {sbom.document['name']}") + print(f"spdxId: {sbom.document['spdxId']}") + print(f"created: {sbom.creation_info['created']}") + print(f"createdBy: {sbom.names(sbom.creation_info['createdBy'])}") + print(f"createdUsing: {sbom.names(sbom.creation_info.get('createdUsing', []))}") print() - types = Counter(pkg_type(p) for p in doc["packages"]) - print(f"Packages: {len(doc['packages'])}") + types = Counter(pkg_type(p) for p in sbom.packages) + print(f"Packages: {len(sbom.packages)}") for t, c in types.most_common(): print(f" {t}: {c}") print() - rc = Counter(r["relationshipType"] for r in doc["relationships"]) - print(f"Relationships: {len(doc['relationships'])}") + rc = Counter() + for r in sbom.relationships: + rc[r["relationshipType"]] += len(r["to"]) + print(f"Relationship edges: {sum(rc.values())} ({len(sbom.relationships)} relationship elements)") for t, n in rc.most_common(): print(f" {t}: {n}") print() - primary = doc["packages"][0] - print(f"Primary package:") + primary = sbom.root + print("Primary package:") print(f" name: {primary['name']}") - print(f" version: {primary['versionInfo']}") - print(f" purpose: {primary.get('primaryPackagePurpose', 'N/A')}") - print(f" license: {primary['licenseDeclared']}") + print(f" version: {primary.get('software_packageVersion', 'N/A')}") + print(f" purpose: {primary.get('software_primaryPurpose', 'N/A')}") + print(f" license: {sbom.license(primary)}") print() + for f in (e for e in sbom.by_id.values() if e["type"] == "software_File"): + hashes = ", ".join(f"{h['algorithm']}:{h['hashValue']}" for h in f.get("verifiedUsing", [])) + print(f"Firmware file: {f['name']} ({hashes or 'no hash'})") + print() + noassert = [ p["name"] - for p in doc["packages"] - if pkg_type(p) == "Submodule" and p["licenseDeclared"] == "NOASSERTION" + for p in sbom.packages + if p["spdxId"] in sbom.contained and sbom.license(p) == NOASSERTION ] if noassert: - print(f"WARNING: {len(noassert)} submodules with NOASSERTION license:") + print(f"WARNING: {len(noassert)} firmware components with no license assertion:") for n in noassert: print(f" - {n}") else: - print("All submodule licenses mapped") + print("All firmware component licenses mapped") print(f"\nFile size: {Path(sys.argv[1]).stat().st_size // 1024}KB") -def search(doc, term): +def search(sbom, term): term = term.lower() - found = [p for p in doc["packages"] if term in p["name"].lower()] + found = [p for p in sbom.packages if term in p["name"].lower()] if not found: print(f"No packages matching '{term}'") return print(f"Found {len(found)} packages matching '{term}':\n") for p in found: print(json.dumps(p, indent=2)) + print(f"license: {sbom.license(p)}") + print(f"supplier: {sbom.supplier(p)}") + if sbom.originator(p): + print(f"upstream: {sbom.originator(p)}") print() -def ntia_check(doc): - required = ["SPDXID", "name", "versionInfo", "supplier", "downloadLocation"] - missing = [] - for p in doc["packages"]: - for f in required: - if f not in p or p[f] in ("", None): - missing.append((p["name"], f)) +def ntia_check(sbom): + """Check the NTIA minimum elements for every component in the firmware. + + Components are the root package and everything it contains. Build-time + dependencies and tools are listed for information only: they are not + part of the shipped binary. + """ + components = [sbom.root] + [sbom.by_id[i] for i in sorted(sbom.contained)] + required = { + "name": lambda p: p.get("name"), + "version": lambda p: p.get("software_packageVersion"), + "supplier": sbom.supplier, + } + + missing = [ + (p["name"], field) + for p in components + for field, get in required.items() + if not get(p) + ] if missing: print(f"FAIL: {len(missing)} missing fields:") for name, field in missing: print(f" {name}: missing {field}") else: - print(f"PASS: All {len(doc['packages'])} packages have required fields") + print(f"PASS: All {len(components)} firmware components have name, version and supplier") - print(f"\nCreators: {doc['creationInfo']['creators']}") - print(f"Timestamp: {doc['creationInfo']['created']}") + build_only = [p for p in sbom.packages if p is not sbom.root and p["spdxId"] not in sbom.contained] + incomplete = [p["name"] for p in build_only if not all(get(p) for get in required.values())] + if incomplete: + print(f"INFO: {len(incomplete)} of {len(build_only)} build-time packages lack a version or supplier") - rels = [r for r in doc["relationships"] if r["relationshipType"] == "DESCRIBES"] - print(f"DESCRIBES relationships: {len(rels)}") + print(f"\nAuthor: {sbom.names(sbom.creation_info['createdBy'])}") + print(f"Timestamp: {sbom.creation_info['created']}") + print(f"Root element: {sbom.root['name']}, contains {len(sbom.contained)} components") - return len(missing) == 0 + return not missing -def licenses(doc): +def licenses(sbom): by_license = {} - for p in doc["packages"]: - lic = p.get("licenseDeclared", "NOASSERTION") - by_license.setdefault(lic, []).append(p["name"]) + for p in sbom.packages: + by_license.setdefault(sbom.license(p), []).append(p["name"]) for lic in sorted(by_license.keys()): names = by_license[lic] @@ -119,15 +186,14 @@ def licenses(doc): print(f" {n}") -def list_packages(doc, filter_type): +def list_packages(sbom, filter_type): filter_type = filter_type.lower() - for p in sorted(doc["packages"], key=lambda x: x["name"]): + for p in sorted(sbom.packages, key=lambda x: x["name"]): t = pkg_type(p) if filter_type != "all" and t.lower() != filter_type: continue - lic = p.get("licenseDeclared", "?") - ver = p["versionInfo"][:20] if len(p["versionInfo"]) > 20 else p["versionInfo"] - print(f" {t:10s} {p['name']:50s} {ver:20s} {lic}") + ver = p.get("software_packageVersion", NOASSERTION)[:20] + print(f" {t:10s} {p['name']:50s} {ver:20s} {sbom.license(p)}") def main(): @@ -135,24 +201,29 @@ def main(): print(__doc__) sys.exit(1) - doc = load(sys.argv[1]) + doc = json.loads(Path(sys.argv[1]).read_text()) + if "@graph" not in doc: + print(f"Not an SPDX 3 JSON-LD document (spdxVersion: {doc.get('spdxVersion', 'unknown')}).") + print("SPDX 2.3 SBOMs from older PX4 releases need inspect_sbom.py from that release.") + sys.exit(1) + sbom = Sbom(doc) cmd = sys.argv[2] if len(sys.argv) > 2 else "summary" if cmd == "summary": - summary(doc) + summary(sbom) elif cmd == "search": if len(sys.argv) < 4: print("Usage: inspect_sbom.py search ") sys.exit(1) - search(doc, sys.argv[3]) + search(sbom, sys.argv[3]) elif cmd == "ntia": - if not ntia_check(doc): + if not ntia_check(sbom): sys.exit(1) elif cmd == "licenses": - licenses(doc) + licenses(sbom) elif cmd == "list": filter_type = sys.argv[3] if len(sys.argv) > 3 else "all" - list_packages(doc, filter_type) + list_packages(sbom, filter_type) else: print(f"Unknown command: {cmd}") print(__doc__) diff --git a/Tools/ci/license-overrides.yaml b/Tools/ci/license-overrides.yaml index 54457c7fadd..1e9fa3102dc 100644 --- a/Tools/ci/license-overrides.yaml +++ b/Tools/ci/license-overrides.yaml @@ -1,9 +1,30 @@ -# SPDX license overrides for submodules where auto-detection fails or is wrong. -# Each entry maps a submodule path to its SPDX license identifier and an -# optional comment explaining why the override exists. +# Per-submodule SBOM metadata, for cases auto-detection cannot cover. +# Each entry is keyed by submodule path. All keys are optional: +# +# license: SPDX license expression, overriding auto-detection. +# comment: Why the license override exists; emitted on hasConcludedLicense. +# copyright: Copyright text. Without it the SBOM records NOASSERTION. +# originator: Upstream organization of a PX4-hosted fork (originatedBy). +# requires: Kconfig symbol the board must enable ("CONFIG_X"), or must +# not enable ("!CONFIG_X"), for the submodule to be included. +# scope: "build" for submodules used only to build the firmware +# (code generators); they become build dependencies instead +# of firmware contents. +# +# `organizations` maps a git host organization to the supplier name shown in +# the SBOM. Organizations not listed appear under their git host name. # # Run `python3 Tools/ci/generate_sbom.py --verify-licenses` to validate. +organizations: + PX4: "Dronecode Foundation" + mavlink: "MAVLink" + dronecan: "DroneCAN" + opencyphal: "OpenCyphal" + google: "Google" + rl-tools: "RLtools" + voxl-public/voxl-sdk/core-libs: "ModalAI" + overrides: src/modules/mavlink/mavlink: license: "LGPL-3.0-only AND MIT" @@ -20,9 +41,11 @@ overrides: comment: >- Dual-licensed. PX4 elects BSD-3-Clause. No board currently enables CONFIG_LIB_CDRSTREAM. + originator: "Eclipse Foundation" src/lib/cdrstream/rosidl: license: "Apache-2.0" + originator: "Open Robotics" src/lib/crypto/monocypher: license: "BSD-2-Clause OR CC0-1.0" @@ -33,19 +56,23 @@ overrides: src/lib/crypto/libtomcrypt: license: "Unlicense" comment: "Public domain dedication. Functionally equivalent to Unlicense." + originator: "LibTom Projects" src/lib/crypto/libtommath: license: "Unlicense" comment: "Public domain dedication. Functionally equivalent to Unlicense." + originator: "LibTom Projects" platforms/nuttx/NuttX/nuttx: license: "Apache-2.0" comment: >- Composite LICENSE (6652 lines) includes BSD/MIT/ISC sub-components. Primary license is Apache-2.0. NOTICE file contains FAT LFN patent warnings. + originator: "Apache Software Foundation" platforms/nuttx/NuttX/apps: license: "Apache-2.0" + originator: "Apache Software Foundation" boards/modalai/voxl2/libfc-sensor-api: license: "NOASSERTION" @@ -60,3 +87,39 @@ overrides: boards/modalai/voxl2/src/lib/mpa/libmodal-pipe: license: "LGPL-3.0-only" comment: "LGPL-3.0 weak copyleft. Used via header includes in VOXL2 mpa library." + + src/modules/uxrce_dds_client/Micro-XRCE-DDS-Client: + originator: "eProsima" + requires: "!CONFIG_UXRCE_DDS_CLIENT_USE_DDS_V3" + + src/modules/uxrce_dds_client/Micro-XRCE-DDS-Client-v3: + originator: "eProsima" + requires: "CONFIG_UXRCE_DDS_CLIENT_USE_DDS_V3" + + src/modules/zenoh/zenoh-pico: + originator: "Eclipse Foundation" + + src/lib/heatshrink/heatshrink: + originator: "Atomic Object" + + src/drivers/uavcan/libdronecan/dsdl: + originator: "DroneCAN" + + # DSDL code generator: runs at build time, none of it is in the firmware. + src/drivers/uavcan/libdronecan/libuavcan/dsdl_compiler/pydronecan: + scope: "build" + + src/drivers/cyphal/legacy_data_types: + originator: "OpenCyphal" + + src/lib/tensorflow_lite_micro/tflite_micro: + originator: "Google" + + src/drivers/ins/microstrain/mip_sdk: + originator: "MicroStrain" + + src/drivers/ins/sbgecom/sbgECom: + originator: "SBG Systems" + + src/drivers/actuators/vertiq_io/iq-module-communication-cpp: + originator: "Vertiq" diff --git a/cmake/sbom.cmake b/cmake/sbom.cmake index c259748db0f..4488915f1f0 100644 --- a/cmake/sbom.cmake +++ b/cmake/sbom.cmake @@ -31,9 +31,9 @@ # ############################################################################ -# SBOM - SPDX 2.3 JSON Software Bill of Materials generation +# SBOM - SPDX 3.0.1 JSON-LD Software Bill of Materials generation -option(GENERATE_SBOM "Generate SPDX 2.3 SBOM" ON) +option(GENERATE_SBOM "Generate SPDX 3.0.1 SBOM" ON) if(DEFINED ENV{PX4_SBOM_DISABLE}) set(GENERATE_SBOM OFF) @@ -49,14 +49,24 @@ if(GENERATE_SBOM) set(sbom_output "${PX4_BINARY_DIR}/${PX4_CONFIG}.sbom.spdx.json") + # Builds that produce a .px4 (NuttX) record it with its SHA-256, so the + # SBOM is regenerated whenever the firmware changes. + get_property(sbom_firmware_file GLOBAL PROPERTY PX4_FIRMWARE_PACKAGE) + set(sbom_firmware_args) + if(sbom_firmware_file) + set(sbom_firmware_args --firmware-file ${sbom_firmware_file}) + endif() + add_custom_command( OUTPUT ${sbom_output} COMMAND ${PYTHON_EXECUTABLE} ${PX4_SOURCE_DIR}/Tools/ci/generate_sbom.py --source-dir ${PX4_SOURCE_DIR} --board ${PX4_CONFIG} --modules-file ${sbom_module_list_file} + --board-config ${BOARD_CONFIG} --compiler ${CMAKE_C_COMPILER} --platform ${PX4_PLATFORM} + ${sbom_firmware_args} --output ${sbom_output} DEPENDS ${PX4_SOURCE_DIR}/Tools/ci/generate_sbom.py @@ -64,9 +74,16 @@ if(GENERATE_SBOM) ${PX4_SOURCE_DIR}/.gitmodules ${PX4_SOURCE_DIR}/Tools/setup/requirements.txt ${sbom_module_list_file} + # Regenerated from BOARD_CONFIG at configure time. Depending on + # BOARD_CONFIG itself would collide with the `boardconfig` target. + ${PX4_BINARY_DIR}/px4_boardconfig.h + ${sbom_firmware_file} COMMENT "Generating SPDX SBOM for ${PX4_CONFIG}" ) add_custom_target(sbom ALL DEPENDS ${sbom_output}) + if(TARGET px4_package) + add_dependencies(sbom px4_package) + endif() endif() diff --git a/docs/en/contribute/sbom.md b/docs/en/contribute/sbom.md index e9e12995a89..aa07b4abad5 100644 --- a/docs/en/contribute/sbom.md +++ b/docs/en/contribute/sbom.md @@ -1,6 +1,6 @@ # Software Bill of Materials (SBOM) -PX4 generates a [Software Bill of Materials](https://www.ntia.gov/SBOM) for every firmware build in [SPDX 2.3](https://spdx.github.io/spdx-spec/v2.3/) JSON format. +PX4 generates a [Software Bill of Materials](https://www.ntia.gov/SBOM) for every firmware build in [SPDX 3.0.1](https://spdx.github.io/spdx-spec/v3.0.1/) JSON-LD format. ## Why SBOM? @@ -10,19 +10,23 @@ PX4 generates a [Software Bill of Materials](https://www.ntia.gov/SBOM) for ever ## Format -PX4 uses SPDX 2.3 JSON. +PX4 uses SPDX 3.0.1, serialized as JSON-LD. SPDX is the Linux Foundation's own standard (ISO/IEC 5962), aligning with PX4's position as a Dronecode/LF project. Zephyr RTOS also uses SPDX. +Earlier PX4 releases produced SPDX 2.3 JSON, with the same file name. + Each SBOM contains: -- **Primary package**: The PX4 firmware for a specific board target, marked with `primaryPackagePurpose: FIRMWARE`. -- **Git submodules**: All third-party libraries included via git submodules (~33 packages), with SPDX license identifiers and commit hashes. -- **Python build dependencies**: Packages from `Tools/setup/requirements.txt` marked as `BUILD_DEPENDENCY_OF` the firmware. +- **Primary package**: The PX4 firmware for a specific board target, with `software_primaryPurpose: firmware`. It is the document's root element. +- **Firmware file**: The `.px4` file the build distributes, with its SHA-256 hash. Only builds that produce a `.px4` (NuttX boards) include it. +- **Git submodules**: The third-party libraries included via git submodules that the board actually builds, with SPDX license expressions, commit hashes and, for PX4-hosted forks, the upstream project. - **Board-specific modules**: Internal PX4 modules compiled for the target board. -- **Compiler**: The C compiler used for the build. +- **Python build dependencies**: Packages from `Tools/setup/requirements.txt`, at the version installed in the build environment, which the firmware depends on at build time. +- **Build-only submodules**: Submodules used only to generate code during the build (such as the DroneCAN DSDL compiler), recorded as build dependencies rather than firmware contents. +- **Compiler**: The C compiler used for the build, with its version, recorded as a build tool. -Typical SBOM size: 70-100 packages, ~500 lines, ~20 KB JSON. +A typical NuttX board SBOM has around 280 packages and is about 700 KB. ## Generation @@ -71,10 +75,17 @@ python3 Tools/ci/generate_sbom.py \ --source-dir . \ --board px4_fmu-v6x_default \ --modules-file build/px4_fmu-v6x_default/config_module_list.txt \ + --board-config build/px4_fmu-v6x_default/boardconfig \ --compiler arm-none-eabi-gcc \ + --platform nuttx \ + --firmware-file build/px4_fmu-v6x_default/px4_fmu-v6x_default.px4 \ --output build/px4_fmu-v6x_default/px4_fmu-v6x_default.sbom.spdx.json ``` +`--board-config` and `--firmware-file` are optional. +Without `--board-config`, submodules that depend on a Kconfig option (see `requires` below) are always included. +Without `--firmware-file`, the SBOM has no firmware file element. + ## Artifacts SBOMs are available in: @@ -87,20 +98,21 @@ SBOMs are available in: ## Validation -Validate an SBOM against the SPDX JSON schema: +Validate an SBOM against the SPDX 3.0.1 JSON schema and SHACL model with [spdx3-validate](https://pypi.org/project/spdx3-validate/): ```sh -python3 -c " -import json -doc = json.load(open('build/px4_sitl_default/px4_sitl_default.sbom.spdx.json')) -assert doc['spdxVersion'] == 'SPDX-2.3' -assert doc['dataLicense'] == 'CC0-1.0' -assert len(doc['packages']) > 0 -print(f'Valid: {len(doc[\"packages\"])} packages') -" +pip install spdx3-validate +spdx3-validate --json build/px4_sitl_default/px4_sitl_default.sbom.spdx.json ``` -For full schema validation, use the [SPDX online validator](https://tools.spdx.org/app/validate/) or the `spdx-tools` CLI. +The validator downloads the schema and model from spdx.org, so it needs network access. + +To summarize an SBOM or check the NTIA minimum elements, use `Tools/ci/inspect_sbom.py`: + +```sh +python3 Tools/ci/inspect_sbom.py build/px4_sitl_default/px4_sitl_default.sbom.spdx.json +python3 Tools/ci/inspect_sbom.py build/px4_sitl_default/px4_sitl_default.sbom.spdx.json ntia +``` ## License Detection @@ -130,7 +142,7 @@ Supported patterns include: | EPL-2.0 | "Eclipse Public License", "2.0" | | Unlicense | "The Unlicense", "unlicense.org" | -If no pattern matches, the license is set to `NOASSERTION`. +If no pattern matches, the license is `NOASSERTION`: the submodule's license relationships point to the SPDX `NoAssertionLicense` value, which states explicitly that the license is unknown. ### Override File @@ -145,10 +157,41 @@ overrides: ``` Each entry maps a submodule path to its correct SPDX license identifier. -The optional `comment` field is emitted as `licenseComments` in the SBOM, +The optional `comment` field is emitted as the `comment` of the package's `hasConcludedLicense` relationship, providing context for auditors reviewing complex licensing situations (dual licenses, composite LICENSE files, public domain dedications). +Despite its name, the file holds all per-submodule SBOM metadata. +Every key is optional: + +| Key | Effect | +| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | +| `license` | SPDX license expression, overriding auto-detection. | +| `comment` | Why the license override exists. | +| `copyright` | Copyright text for the package. Without it the SBOM records `NOASSERTION`. | +| `originator` | Upstream organization of a fork hosted under the PX4 GitHub organization, recorded as `originatedBy`. | +| `requires` | Kconfig symbol the board must enable (`CONFIG_X`), or must not enable (`!CONFIG_X`), for the submodule to be listed. | +| `scope` | `build` for submodules used only to build the firmware (code generators). They are recorded as build dependencies, not firmware contents. | + +For example, the two Micro XRCE-DDS Client versions are listed only when the board selects them: + +```yaml +overrides: + src/modules/uxrce_dds_client/Micro-XRCE-DDS-Client-v3: + originator: "eProsima" + requires: "CONFIG_UXRCE_DDS_CLIENT_USE_DDS_V3" +``` + +The top-level `organizations` map gives the supplier name for a git host organization: + +```yaml +organizations: + PX4: "Dronecode Foundation" + mavlink: "MAVLink" +``` + +Organizations not listed appear under their git host name. + ### Copyleft Guardrail The `--verify-licenses` command flags submodules with copyleft licenses @@ -163,6 +206,9 @@ The `--platform` argument (set automatically by CMake via `${PX4_PLATFORM}`) controls which platform-specific submodules are included. This ensures SITL builds do not list NuttX RTOS packages. +Other submodules are included when a module the board builds lives inside them or contains them, +and when the board configuration (passed by CMake via `--board-config`) satisfies their `requires` entry. + ### Verification Run the verify command to check detection for all submodules: @@ -203,24 +249,51 @@ This section is for integrators, compliance teams, and anyone reviewing SBOM art ### Reading the JSON -Each SBOM is a single JSON document following SPDX 2.3. -Key fields: +Each SBOM is a single SPDX 3.0.1 JSON-LD document. +Everything in it is an element in the top-level `@graph` array, identified by its `spdxId` and distinguished by its `type`: -- **`packages`**: Array of all components. Each has `name`, `versionInfo`, `licenseConcluded`, and `SPDXID`. -- **`relationships`**: How packages relate. `CONTAINS` means a submodule is compiled into firmware. `BUILD_DEPENDENCY_OF` means a tool used only during build. -- **`licenseConcluded`**: The SPDX license identifier determined for that package. -- **`licenseComments`**: Free-text explanation for complex cases (dual licenses, composite files, public domain). -- **`externalRefs`**: Package URLs (purls) linking to GitHub repos or PyPI. +- **`SpdxDocument`**: The document itself. `rootElement` points to the firmware package. +- **`software_Package`**: One per component, with `name`, `software_packageVersion`, `software_downloadLocation`, `software_packageUrl` (a purl linking to the GitHub repo, PyPI or the PX4 source path), `software_copyrightText` and, where known, `suppliedBy`. Forks hosted by PX4 also have `originatedBy`, the upstream project. +- **`software_contentIdentifier`**: A [Software Heritage ID](https://www.softwareheritage.org/software-hash-identifiers/) of the exact source: `swh:1:rev:` (the commit) for submodules, `swh:1:dir:` (the git tree) for PX4 modules. Modules with uncommitted changes have none. +- **`software_File`**: The `.px4` firmware file, with a SHA-256 hash in `verifiedUsing`. +- **`Relationship`**: How elements relate. The firmware `contains` its submodules and modules, and `hasDistributionArtifact` the firmware file. +- **`LifecycleScopedRelationship`**: A relationship limited to a lifecycle stage. With `scope: build`, the firmware `dependsOn` the Python packages and build-only submodules, and `usesTool` the compiler, only while it is being built. +- **`simplelicensing_LicenseExpression`**: An SPDX license expression. Each package links to one through a `hasDeclaredLicense` and a `hasConcludedLicense` relationship. The `comment` on `hasConcludedLicense` explains complex cases (dual licenses, composite files, public domain). -### Understanding NOASSERTION +### Understanding Unknown Values -`NOASSERTION` means no license could be determined. -For submodules, this happens when: +The SBOM marks unknown information explicitly instead of leaving it out: + +- A license that could not be determined links to `expandedlicensing_NoAssertionLicense`. `inspect_sbom.py` reports these packages as `NOASSERTION`. +- Unknown copyright text is `NOASSERTION`. + +Python packages and the compiler always have an unknown license. +For submodules, the license is unknown when: - The submodule is not checked out (common in CI shallow clones). - No LICENSE/COPYING file exists. - The LICENSE file does not match any known pattern and no override is configured. For shipped firmware, `NOASSERTION` should be resolved by adding an override. -For build-only dependencies (Python packages), `NOASSERTION` is acceptable +For build-only dependencies (Python packages, the compiler), `NOASSERTION` is acceptable since these are not compiled into the firmware binary. + +### Verifying Release Artifacts + +Release builds (version tags) publish signed [build provenance attestations](https://docs.github.com/en/actions/security-for-github-actions/using-artifact-attestations/using-artifact-attestations-to-establish-provenance-for-builds) for every firmware file and SBOM. +The attestations are stored by GitHub and recorded in the public [Sigstore](https://www.sigstore.dev/) transparency log; the files themselves are unchanged. + +To check that a file was built by the PX4 release workflow, use the GitHub CLI: + +```sh +gh attestation verify px4_fmu-v6x_default.px4 --repo PX4/PX4-Autopilot +gh attestation verify px4_fmu-v6x_default.sbom.spdx.json --repo PX4/PX4-Autopilot +``` + +The SBOM records the SHA-256 of its `.px4`, so a verified SBOM whose hash matches the firmware file describes that exact firmware: + +```sh +sha256sum px4_fmu-v6x_default.px4 +``` + +Builds from branches (including `main`) are not attested. diff --git a/platforms/nuttx/CMakeLists.txt b/platforms/nuttx/CMakeLists.txt index a861bf255af..d7fa9c5c6d5 100644 --- a/platforms/nuttx/CMakeLists.txt +++ b/platforms/nuttx/CMakeLists.txt @@ -555,6 +555,7 @@ if (TARGET parameters_xml AND TARGET airframes_xml AND EXISTS ${PX4_SOURCE_DIR}/ ) add_custom_target(px4_package ALL DEPENDS ${fw_package}) + set_property(GLOBAL PROPERTY PX4_FIRMWARE_PACKAGE ${fw_package}) # upload helper # create upload target helper if NuttX USB CDCACM is present