blob: c35dbe11849608f47b0fef0256a98539ab5795cd [file] [log] [blame]
Andrew Geissler5199d832021-09-24 16:47:35 -05001#
2# SPDX-License-Identifier: GPL-2.0-only
3#
4
5DEPLOY_DIR_SPDX ??= "${DEPLOY_DIR}/spdx/${MACHINE}"
6
7# The product name that the CVE database uses. Defaults to BPN, but may need to
8# be overriden per recipe (for example tiff.bb sets CVE_PRODUCT=libtiff).
9CVE_PRODUCT ??= "${BPN}"
10CVE_VERSION ??= "${PV}"
11
12SPDXDIR ??= "${WORKDIR}/spdx"
13SPDXDEPLOY = "${SPDXDIR}/deploy"
14SPDXWORK = "${SPDXDIR}/work"
15
Patrick Williams93c203f2021-10-06 16:15:23 -050016SPDX_TOOL_NAME ??= "oe-spdx-creator"
17SPDX_TOOL_VERSION ??= "1.0"
18
Andrew Geissler5199d832021-09-24 16:47:35 -050019SPDXRUNTIMEDEPLOY = "${SPDXDIR}/runtime-deploy"
20
21SPDX_INCLUDE_SOURCES ??= "0"
22SPDX_INCLUDE_PACKAGED ??= "0"
23SPDX_ARCHIVE_SOURCES ??= "0"
24SPDX_ARCHIVE_PACKAGED ??= "0"
25
26SPDX_UUID_NAMESPACE ??= "sbom.openembedded.org"
27SPDX_NAMESPACE_PREFIX ??= "http://spdx.org/spdxdoc"
28
29SPDX_LICENSES ??= "${COREBASE}/meta/files/spdx-licenses.json"
30
31do_image_complete[depends] = "virtual/kernel:do_create_spdx"
32
33def get_doc_namespace(d, doc):
34 import uuid
35 namespace_uuid = uuid.uuid5(uuid.NAMESPACE_DNS, d.getVar("SPDX_UUID_NAMESPACE"))
36 return "%s/%s-%s" % (d.getVar("SPDX_NAMESPACE_PREFIX"), doc.name, str(uuid.uuid5(namespace_uuid, doc.name)))
37
Andrew Geisslereff27472021-10-29 15:35:00 -050038def create_annotation(d, comment):
39 from datetime import datetime, timezone
40
41 creation_time = datetime.now(tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
42 annotation = oe.spdx.SPDXAnnotation()
43 annotation.annotationDate = creation_time
44 annotation.annotationType = "OTHER"
45 annotation.annotator = "Tool: %s - %s" % (d.getVar("SPDX_TOOL_NAME"), d.getVar("SPDX_TOOL_VERSION"))
46 annotation.comment = comment
47 return annotation
48
Patrick Williams93c203f2021-10-06 16:15:23 -050049def recipe_spdx_is_native(d, recipe):
50 return any(a.annotationType == "OTHER" and
51 a.annotator == "Tool: %s - %s" % (d.getVar("SPDX_TOOL_NAME"), d.getVar("SPDX_TOOL_VERSION")) and
52 a.comment == "isNative" for a in recipe.annotations)
Andrew Geissler5199d832021-09-24 16:47:35 -050053
54def is_work_shared(d):
55 pn = d.getVar('PN')
56 return bb.data.inherits_class('kernel', d) or pn.startswith('gcc-source')
57
58
59python() {
60 import json
61 if d.getVar("SPDX_LICENSE_DATA"):
62 return
63
64 with open(d.getVar("SPDX_LICENSES"), "r") as f:
65 data = json.load(f)
66 # Transform the license array to a dictionary
67 data["licenses"] = {l["licenseId"]: l for l in data["licenses"]}
68 d.setVar("SPDX_LICENSE_DATA", data)
69}
70
71def convert_license_to_spdx(lic, document, d, existing={}):
72 from pathlib import Path
73 import oe.spdx
74
75 available_licenses = d.getVar("AVAILABLE_LICENSES").split()
76 license_data = d.getVar("SPDX_LICENSE_DATA")
77 extracted = {}
78
79 def add_extracted_license(ident, name):
80 nonlocal document
81
82 if name in extracted:
83 return
84
85 extracted_info = oe.spdx.SPDXExtractedLicensingInfo()
86 extracted_info.name = name
87 extracted_info.licenseId = ident
88 extracted_info.extractedText = None
89
90 if name == "PD":
91 # Special-case this.
92 extracted_info.extractedText = "Software released to the public domain"
93 elif name in available_licenses:
94 # This license can be found in COMMON_LICENSE_DIR or LICENSE_PATH
95 for directory in [d.getVar('COMMON_LICENSE_DIR')] + d.getVar('LICENSE_PATH').split():
96 try:
97 with (Path(directory) / name).open(errors="replace") as f:
98 extracted_info.extractedText = f.read()
99 break
100 except FileNotFoundError:
101 pass
102 if extracted_info.extractedText is None:
103 # Error out, as the license was in available_licenses so should
104 # be on disk somewhere.
105 bb.error("Cannot find text for license %s" % name)
106 else:
107 # If it's not SPDX, or PD, or in available licenses, then NO_GENERIC_LICENSE must be set
108 filename = d.getVarFlag('NO_GENERIC_LICENSE', name)
109 if filename:
110 filename = d.expand("${S}/" + filename)
111 with open(filename, errors="replace") as f:
112 extracted_info.extractedText = f.read()
113 else:
114 bb.error("Cannot find any text for license %s" % name)
115
116 extracted[name] = extracted_info
117 document.hasExtractedLicensingInfos.append(extracted_info)
118
119 def convert(l):
120 if l == "(" or l == ")":
121 return l
122
123 if l == "&":
124 return "AND"
125
126 if l == "|":
127 return "OR"
128
129 if l == "CLOSED":
130 return "NONE"
131
132 spdx_license = d.getVarFlag("SPDXLICENSEMAP", l) or l
133 if spdx_license in license_data["licenses"]:
134 return spdx_license
135
136 try:
137 spdx_license = existing[l]
138 except KeyError:
139 spdx_license = "LicenseRef-" + l
140 add_extracted_license(spdx_license, l)
141
142 return spdx_license
143
144 lic_split = lic.replace("(", " ( ").replace(")", " ) ").split()
145
146 return ' '.join(convert(l) for l in lic_split)
147
148
149def process_sources(d):
150 pn = d.getVar('PN')
151 assume_provided = (d.getVar("ASSUME_PROVIDED") or "").split()
152 if pn in assume_provided:
153 for p in d.getVar("PROVIDES").split():
154 if p != pn:
155 pn = p
156 break
157
158 # glibc-locale: do_fetch, do_unpack and do_patch tasks have been deleted,
159 # so avoid archiving source here.
160 if pn.startswith('glibc-locale'):
161 return False
162 if d.getVar('PN') == "libtool-cross":
163 return False
164 if d.getVar('PN') == "libgcc-initial":
165 return False
166 if d.getVar('PN') == "shadow-sysroot":
167 return False
168
169 # We just archive gcc-source for all the gcc related recipes
170 if d.getVar('BPN') in ['gcc', 'libgcc']:
171 bb.debug(1, 'spdx: There is bug in scan of %s is, do nothing' % pn)
172 return False
173
174 return True
175
176
177def add_package_files(d, doc, spdx_pkg, topdir, get_spdxid, get_types, *, archive=None, ignore_dirs=[], ignore_top_level_dirs=[]):
178 from pathlib import Path
179 import oe.spdx
180 import hashlib
181
182 source_date_epoch = d.getVar("SOURCE_DATE_EPOCH")
183 if source_date_epoch:
184 source_date_epoch = int(source_date_epoch)
185
186 sha1s = []
187 spdx_files = []
188
189 file_counter = 1
190 for subdir, dirs, files in os.walk(topdir):
191 dirs[:] = [d for d in dirs if d not in ignore_dirs]
192 if subdir == str(topdir):
193 dirs[:] = [d for d in dirs if d not in ignore_top_level_dirs]
194
195 for file in files:
196 filepath = Path(subdir) / file
197 filename = str(filepath.relative_to(topdir))
198
199 if filepath.is_file() and not filepath.is_symlink():
200 spdx_file = oe.spdx.SPDXFile()
201 spdx_file.SPDXID = get_spdxid(file_counter)
202 for t in get_types(filepath):
203 spdx_file.fileTypes.append(t)
204 spdx_file.fileName = filename
205
206 if archive is not None:
207 with filepath.open("rb") as f:
208 info = archive.gettarinfo(fileobj=f)
209 info.name = filename
210 info.uid = 0
211 info.gid = 0
212 info.uname = "root"
213 info.gname = "root"
214
215 if source_date_epoch is not None and info.mtime > source_date_epoch:
216 info.mtime = source_date_epoch
217
218 archive.addfile(info, f)
219
220 sha1 = bb.utils.sha1_file(filepath)
221 sha1s.append(sha1)
222 spdx_file.checksums.append(oe.spdx.SPDXChecksum(
223 algorithm="SHA1",
224 checksumValue=sha1,
225 ))
226 spdx_file.checksums.append(oe.spdx.SPDXChecksum(
227 algorithm="SHA256",
228 checksumValue=bb.utils.sha256_file(filepath),
229 ))
230
231 doc.files.append(spdx_file)
232 doc.add_relationship(spdx_pkg, "CONTAINS", spdx_file)
233 spdx_pkg.hasFiles.append(spdx_file.SPDXID)
234
235 spdx_files.append(spdx_file)
236
237 file_counter += 1
238
239 sha1s.sort()
240 verifier = hashlib.sha1()
241 for v in sha1s:
242 verifier.update(v.encode("utf-8"))
243 spdx_pkg.packageVerificationCode.packageVerificationCodeValue = verifier.hexdigest()
244
245 return spdx_files
246
247
248def add_package_sources_from_debug(d, package_doc, spdx_package, package, package_files, sources):
249 from pathlib import Path
250 import hashlib
251 import oe.packagedata
252 import oe.spdx
253
254 debug_search_paths = [
255 Path(d.getVar('PKGD')),
256 Path(d.getVar('STAGING_DIR_TARGET')),
257 Path(d.getVar('STAGING_DIR_NATIVE')),
258 ]
259
260 pkg_data = oe.packagedata.read_subpkgdata_extended(package, d)
261
262 if pkg_data is None:
263 return
264
265 for file_path, file_data in pkg_data["files_info"].items():
266 if not "debugsrc" in file_data:
267 continue
268
269 for pkg_file in package_files:
270 if file_path.lstrip("/") == pkg_file.fileName.lstrip("/"):
271 break
272 else:
273 bb.fatal("No package file found for %s" % str(file_path))
274 continue
275
276 for debugsrc in file_data["debugsrc"]:
277 ref_id = "NOASSERTION"
278 for search in debug_search_paths:
279 debugsrc_path = search / debugsrc.lstrip("/")
280 if not debugsrc_path.exists():
281 continue
282
283 file_sha256 = bb.utils.sha256_file(debugsrc_path)
284
285 if file_sha256 in sources:
286 source_file = sources[file_sha256]
287
288 doc_ref = package_doc.find_external_document_ref(source_file.doc.documentNamespace)
289 if doc_ref is None:
290 doc_ref = oe.spdx.SPDXExternalDocumentRef()
291 doc_ref.externalDocumentId = "DocumentRef-dependency-" + source_file.doc.name
292 doc_ref.spdxDocument = source_file.doc.documentNamespace
293 doc_ref.checksum.algorithm = "SHA1"
294 doc_ref.checksum.checksumValue = source_file.doc_sha1
295 package_doc.externalDocumentRefs.append(doc_ref)
296
297 ref_id = "%s:%s" % (doc_ref.externalDocumentId, source_file.file.SPDXID)
298 else:
299 bb.debug(1, "Debug source %s with SHA256 %s not found in any dependency" % (str(debugsrc_path), file_sha256))
300 break
301 else:
302 bb.debug(1, "Debug source %s not found" % debugsrc)
303
304 package_doc.add_relationship(pkg_file, "GENERATED_FROM", ref_id, comment=debugsrc)
305
306def collect_dep_recipes(d, doc, spdx_recipe):
307 from pathlib import Path
308 import oe.sbom
309 import oe.spdx
310
311 deploy_dir_spdx = Path(d.getVar("DEPLOY_DIR_SPDX"))
312
313 dep_recipes = []
314 taskdepdata = d.getVar("BB_TASKDEPDATA", False)
315 deps = sorted(set(
316 dep[0] for dep in taskdepdata.values() if
317 dep[1] == "do_create_spdx" and dep[0] != d.getVar("PN")
318 ))
319 for dep_pn in deps:
320 dep_recipe_path = deploy_dir_spdx / "recipes" / ("recipe-%s.spdx.json" % dep_pn)
321
322 spdx_dep_doc, spdx_dep_sha1 = oe.sbom.read_doc(dep_recipe_path)
323
324 for pkg in spdx_dep_doc.packages:
325 if pkg.name == dep_pn:
326 spdx_dep_recipe = pkg
327 break
328 else:
329 continue
330
331 dep_recipes.append(oe.sbom.DepRecipe(spdx_dep_doc, spdx_dep_sha1, spdx_dep_recipe))
332
333 dep_recipe_ref = oe.spdx.SPDXExternalDocumentRef()
334 dep_recipe_ref.externalDocumentId = "DocumentRef-dependency-" + spdx_dep_doc.name
335 dep_recipe_ref.spdxDocument = spdx_dep_doc.documentNamespace
336 dep_recipe_ref.checksum.algorithm = "SHA1"
337 dep_recipe_ref.checksum.checksumValue = spdx_dep_sha1
338
339 doc.externalDocumentRefs.append(dep_recipe_ref)
340
341 doc.add_relationship(
342 "%s:%s" % (dep_recipe_ref.externalDocumentId, spdx_dep_recipe.SPDXID),
343 "BUILD_DEPENDENCY_OF",
344 spdx_recipe
345 )
346
347 return dep_recipes
348
349collect_dep_recipes[vardepsexclude] += "BB_TASKDEPDATA"
350
351
352def collect_dep_sources(d, dep_recipes):
353 import oe.sbom
354
355 sources = {}
356 for dep in dep_recipes:
Patrick Williams93c203f2021-10-06 16:15:23 -0500357 # Don't collect sources from native recipes as they
358 # match non-native sources also.
359 if recipe_spdx_is_native(d, dep.recipe):
360 continue
Andrew Geissler5199d832021-09-24 16:47:35 -0500361 recipe_files = set(dep.recipe.hasFiles)
362
363 for spdx_file in dep.doc.files:
364 if spdx_file.SPDXID not in recipe_files:
365 continue
366
367 if "SOURCE" in spdx_file.fileTypes:
368 for checksum in spdx_file.checksums:
369 if checksum.algorithm == "SHA256":
370 sources[checksum.checksumValue] = oe.sbom.DepSource(dep.doc, dep.doc_sha1, dep.recipe, spdx_file)
371 break
372
373 return sources
374
375
376python do_create_spdx() {
377 from datetime import datetime, timezone
378 import oe.sbom
379 import oe.spdx
380 import uuid
381 from pathlib import Path
382 from contextlib import contextmanager
383 import oe.cve_check
384
385 @contextmanager
386 def optional_tarfile(name, guard, mode="w"):
387 import tarfile
388 import bb.compress.zstd
389
390 num_threads = int(d.getVar("BB_NUMBER_THREADS"))
391
392 if guard:
393 name.parent.mkdir(parents=True, exist_ok=True)
394 with bb.compress.zstd.open(name, mode=mode + "b", num_threads=num_threads) as f:
395 with tarfile.open(fileobj=f, mode=mode + "|") as tf:
396 yield tf
397 else:
398 yield None
399
400
401 deploy_dir_spdx = Path(d.getVar("DEPLOY_DIR_SPDX"))
402 spdx_workdir = Path(d.getVar("SPDXWORK"))
403 include_packaged = d.getVar("SPDX_INCLUDE_PACKAGED") == "1"
404 include_sources = d.getVar("SPDX_INCLUDE_SOURCES") == "1"
405 archive_sources = d.getVar("SPDX_ARCHIVE_SOURCES") == "1"
406 archive_packaged = d.getVar("SPDX_ARCHIVE_PACKAGED") == "1"
Andrew Geissler5199d832021-09-24 16:47:35 -0500407
408 creation_time = datetime.now(tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
409
410 doc = oe.spdx.SPDXDocument()
411
412 doc.name = "recipe-" + d.getVar("PN")
413 doc.documentNamespace = get_doc_namespace(d, doc)
414 doc.creationInfo.created = creation_time
415 doc.creationInfo.comment = "This document was created by analyzing recipe files during the build."
416 doc.creationInfo.licenseListVersion = d.getVar("SPDX_LICENSE_DATA")["licenseListVersion"]
417 doc.creationInfo.creators.append("Tool: OpenEmbedded Core create-spdx.bbclass")
418 doc.creationInfo.creators.append("Organization: OpenEmbedded ()")
419 doc.creationInfo.creators.append("Person: N/A ()")
420
421 recipe = oe.spdx.SPDXPackage()
422 recipe.name = d.getVar("PN")
423 recipe.versionInfo = d.getVar("PV")
424 recipe.SPDXID = oe.sbom.get_recipe_spdxid(d)
Andrew Geisslereff27472021-10-29 15:35:00 -0500425 if bb.data.inherits_class("native", d) or bb.data.inherits_class("cross", d):
426 recipe.annotations.append(create_annotation(d, "isNative"))
Andrew Geissler5199d832021-09-24 16:47:35 -0500427
428 for s in d.getVar('SRC_URI').split():
429 if not s.startswith("file://"):
430 recipe.downloadLocation = s
431 break
432 else:
433 recipe.downloadLocation = "NOASSERTION"
434
435 homepage = d.getVar("HOMEPAGE")
436 if homepage:
437 recipe.homepage = homepage
438
439 license = d.getVar("LICENSE")
440 if license:
441 recipe.licenseDeclared = convert_license_to_spdx(license, doc, d)
442
443 summary = d.getVar("SUMMARY")
444 if summary:
445 recipe.summary = summary
446
447 description = d.getVar("DESCRIPTION")
448 if description:
449 recipe.description = description
450
451 # Some CVEs may be patched during the build process without incrementing the version number,
452 # so querying for CVEs based on the CPE id can lead to false positives. To account for this,
453 # save the CVEs fixed by patches to source information field in the SPDX.
454 patched_cves = oe.cve_check.get_patched_cves(d)
455 patched_cves = list(patched_cves)
456 patched_cves = ' '.join(patched_cves)
457 if patched_cves:
458 recipe.sourceInfo = "CVEs fixed: " + patched_cves
459
460 cpe_ids = oe.cve_check.get_cpe_ids(d.getVar("CVE_PRODUCT"), d.getVar("CVE_VERSION"))
461 if cpe_ids:
462 for cpe_id in cpe_ids:
463 cpe = oe.spdx.SPDXExternalReference()
464 cpe.referenceCategory = "SECURITY"
465 cpe.referenceType = "http://spdx.org/rdf/references/cpe23Type"
466 cpe.referenceLocator = cpe_id
467 recipe.externalRefs.append(cpe)
468
469 doc.packages.append(recipe)
470 doc.add_relationship(doc, "DESCRIBES", recipe)
471
472 if process_sources(d) and include_sources:
473 recipe_archive = deploy_dir_spdx / "recipes" / (doc.name + ".tar.zst")
474 with optional_tarfile(recipe_archive, archive_sources) as archive:
475 spdx_get_src(d)
476
477 add_package_files(
478 d,
479 doc,
480 recipe,
481 spdx_workdir,
482 lambda file_counter: "SPDXRef-SourceFile-%s-%d" % (d.getVar("PN"), file_counter),
483 lambda filepath: ["SOURCE"],
484 ignore_dirs=[".git"],
485 ignore_top_level_dirs=["temp"],
486 archive=archive,
487 )
488
489 if archive is not None:
490 recipe.packageFileName = str(recipe_archive.name)
491
492 dep_recipes = collect_dep_recipes(d, doc, recipe)
493
494 doc_sha1 = oe.sbom.write_doc(d, doc, "recipes")
495 dep_recipes.append(oe.sbom.DepRecipe(doc, doc_sha1, recipe))
496
497 recipe_ref = oe.spdx.SPDXExternalDocumentRef()
498 recipe_ref.externalDocumentId = "DocumentRef-recipe-" + recipe.name
499 recipe_ref.spdxDocument = doc.documentNamespace
500 recipe_ref.checksum.algorithm = "SHA1"
501 recipe_ref.checksum.checksumValue = doc_sha1
502
503 sources = collect_dep_sources(d, dep_recipes)
504 found_licenses = {license.name:recipe_ref.externalDocumentId + ":" + license.licenseId for license in doc.hasExtractedLicensingInfos}
505
Patrick Williams93c203f2021-10-06 16:15:23 -0500506 if not recipe_spdx_is_native(d, recipe):
Andrew Geissler5199d832021-09-24 16:47:35 -0500507 bb.build.exec_func("read_subpackage_metadata", d)
508
509 pkgdest = Path(d.getVar("PKGDEST"))
510 for package in d.getVar("PACKAGES").split():
511 if not oe.packagedata.packaged(package, d):
512 continue
513
514 package_doc = oe.spdx.SPDXDocument()
515 pkg_name = d.getVar("PKG:%s" % package) or package
516 package_doc.name = pkg_name
517 package_doc.documentNamespace = get_doc_namespace(d, package_doc)
518 package_doc.creationInfo.created = creation_time
519 package_doc.creationInfo.comment = "This document was created by analyzing packages created during the build."
520 package_doc.creationInfo.licenseListVersion = d.getVar("SPDX_LICENSE_DATA")["licenseListVersion"]
521 package_doc.creationInfo.creators.append("Tool: OpenEmbedded Core create-spdx.bbclass")
522 package_doc.creationInfo.creators.append("Organization: OpenEmbedded ()")
523 package_doc.creationInfo.creators.append("Person: N/A ()")
524 package_doc.externalDocumentRefs.append(recipe_ref)
525
526 package_license = d.getVar("LICENSE:%s" % package) or d.getVar("LICENSE")
527
528 spdx_package = oe.spdx.SPDXPackage()
529
530 spdx_package.SPDXID = oe.sbom.get_package_spdxid(pkg_name)
531 spdx_package.name = pkg_name
532 spdx_package.versionInfo = d.getVar("PV")
533 spdx_package.licenseDeclared = convert_license_to_spdx(package_license, package_doc, d, found_licenses)
534
535 package_doc.packages.append(spdx_package)
536
537 package_doc.add_relationship(spdx_package, "GENERATED_FROM", "%s:%s" % (recipe_ref.externalDocumentId, recipe.SPDXID))
538 package_doc.add_relationship(package_doc, "DESCRIBES", spdx_package)
539
540 package_archive = deploy_dir_spdx / "packages" / (package_doc.name + ".tar.zst")
541 with optional_tarfile(package_archive, archive_packaged) as archive:
542 package_files = add_package_files(
543 d,
544 package_doc,
545 spdx_package,
546 pkgdest / package,
547 lambda file_counter: oe.sbom.get_packaged_file_spdxid(pkg_name, file_counter),
548 lambda filepath: ["BINARY"],
549 archive=archive,
550 )
551
552 if archive is not None:
553 spdx_package.packageFileName = str(package_archive.name)
554
555 add_package_sources_from_debug(d, package_doc, spdx_package, package, package_files, sources)
556
557 oe.sbom.write_doc(d, package_doc, "packages")
558}
559# NOTE: depending on do_unpack is a hack that is necessary to get it's dependencies for archive the source
560addtask do_create_spdx after do_package do_packagedata do_unpack before do_build do_rm_work
561
562SSTATETASKS += "do_create_spdx"
563do_create_spdx[sstate-inputdirs] = "${SPDXDEPLOY}"
564do_create_spdx[sstate-outputdirs] = "${DEPLOY_DIR_SPDX}"
565
566python do_create_spdx_setscene () {
567 sstate_setscene(d)
568}
569addtask do_create_spdx_setscene
570
571do_create_spdx[dirs] = "${SPDXDEPLOY} ${SPDXWORK}"
572do_create_spdx[cleandirs] = "${SPDXDEPLOY} ${SPDXWORK}"
573do_create_spdx[depends] += "${PATCHDEPENDENCY}"
574do_create_spdx[deptask] = "do_create_spdx"
575
576def collect_package_providers(d):
577 from pathlib import Path
578 import oe.sbom
579 import oe.spdx
580 import json
581
582 deploy_dir_spdx = Path(d.getVar("DEPLOY_DIR_SPDX"))
583
584 providers = {}
585
586 taskdepdata = d.getVar("BB_TASKDEPDATA", False)
587 deps = sorted(set(
588 dep[0] for dep in taskdepdata.values() if dep[0] != d.getVar("PN")
589 ))
590 deps.append(d.getVar("PN"))
591
592 for dep_pn in deps:
593 recipe_data = oe.packagedata.read_pkgdata(dep_pn, d)
594
595 for pkg in recipe_data.get("PACKAGES", "").split():
596
597 pkg_data = oe.packagedata.read_subpkgdata_dict(pkg, d)
598 rprovides = set(n for n, _ in bb.utils.explode_dep_versions2(pkg_data.get("RPROVIDES", "")).items())
599 rprovides.add(pkg)
600
601 for r in rprovides:
602 providers[r] = pkg
603
604 return providers
605
606collect_package_providers[vardepsexclude] += "BB_TASKDEPDATA"
607
608python do_create_runtime_spdx() {
609 from datetime import datetime, timezone
610 import oe.sbom
611 import oe.spdx
612 import oe.packagedata
613 from pathlib import Path
614
615 deploy_dir_spdx = Path(d.getVar("DEPLOY_DIR_SPDX"))
616 spdx_deploy = Path(d.getVar("SPDXRUNTIMEDEPLOY"))
Andrew Geisslereff27472021-10-29 15:35:00 -0500617 is_native = bb.data.inherits_class("native", d) or bb.data.inherits_class("cross", d)
Andrew Geissler5199d832021-09-24 16:47:35 -0500618
619 creation_time = datetime.now(tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
620
621 providers = collect_package_providers(d)
622
623 if not is_native:
624 bb.build.exec_func("read_subpackage_metadata", d)
625
626 dep_package_cache = {}
627
628 pkgdest = Path(d.getVar("PKGDEST"))
629 for package in d.getVar("PACKAGES").split():
630 localdata = bb.data.createCopy(d)
631 pkg_name = d.getVar("PKG:%s" % package) or package
632 localdata.setVar("PKG", pkg_name)
633 localdata.setVar('OVERRIDES', d.getVar("OVERRIDES", False) + ":" + package)
634
635 if not oe.packagedata.packaged(package, localdata):
636 continue
637
638 pkg_spdx_path = deploy_dir_spdx / "packages" / (pkg_name + ".spdx.json")
639
640 package_doc, package_doc_sha1 = oe.sbom.read_doc(pkg_spdx_path)
641
642 for p in package_doc.packages:
643 if p.name == pkg_name:
644 spdx_package = p
645 break
646 else:
647 bb.fatal("Package '%s' not found in %s" % (pkg_name, pkg_spdx_path))
648
649 runtime_doc = oe.spdx.SPDXDocument()
650 runtime_doc.name = "runtime-" + pkg_name
651 runtime_doc.documentNamespace = get_doc_namespace(localdata, runtime_doc)
652 runtime_doc.creationInfo.created = creation_time
653 runtime_doc.creationInfo.comment = "This document was created by analyzing package runtime dependencies."
654 runtime_doc.creationInfo.licenseListVersion = d.getVar("SPDX_LICENSE_DATA")["licenseListVersion"]
655 runtime_doc.creationInfo.creators.append("Tool: OpenEmbedded Core create-spdx.bbclass")
656 runtime_doc.creationInfo.creators.append("Organization: OpenEmbedded ()")
657 runtime_doc.creationInfo.creators.append("Person: N/A ()")
658
659 package_ref = oe.spdx.SPDXExternalDocumentRef()
660 package_ref.externalDocumentId = "DocumentRef-package-" + package
661 package_ref.spdxDocument = package_doc.documentNamespace
662 package_ref.checksum.algorithm = "SHA1"
663 package_ref.checksum.checksumValue = package_doc_sha1
664
665 runtime_doc.externalDocumentRefs.append(package_ref)
666
667 runtime_doc.add_relationship(
668 runtime_doc.SPDXID,
669 "AMENDS",
670 "%s:%s" % (package_ref.externalDocumentId, package_doc.SPDXID)
671 )
672
673 deps = bb.utils.explode_dep_versions2(localdata.getVar("RDEPENDS") or "")
674 seen_deps = set()
675 for dep, _ in deps.items():
676 if dep in seen_deps:
677 continue
678
679 dep = providers[dep]
680
681 if not oe.packagedata.packaged(dep, localdata):
682 continue
683
684 dep_pkg_data = oe.packagedata.read_subpkgdata_dict(dep, d)
685 dep_pkg = dep_pkg_data["PKG"]
686
687 if dep in dep_package_cache:
688 (dep_spdx_package, dep_package_ref) = dep_package_cache[dep]
689 else:
690 dep_path = deploy_dir_spdx / "packages" / ("%s.spdx.json" % dep_pkg)
691
692 spdx_dep_doc, spdx_dep_sha1 = oe.sbom.read_doc(dep_path)
693
694 for pkg in spdx_dep_doc.packages:
695 if pkg.name == dep_pkg:
696 dep_spdx_package = pkg
697 break
698 else:
699 bb.fatal("Package '%s' not found in %s" % (dep_pkg, dep_path))
700
701 dep_package_ref = oe.spdx.SPDXExternalDocumentRef()
702 dep_package_ref.externalDocumentId = "DocumentRef-runtime-dependency-" + spdx_dep_doc.name
703 dep_package_ref.spdxDocument = spdx_dep_doc.documentNamespace
704 dep_package_ref.checksum.algorithm = "SHA1"
705 dep_package_ref.checksum.checksumValue = spdx_dep_sha1
706
707 dep_package_cache[dep] = (dep_spdx_package, dep_package_ref)
708
709 runtime_doc.externalDocumentRefs.append(dep_package_ref)
710
711 runtime_doc.add_relationship(
712 "%s:%s" % (dep_package_ref.externalDocumentId, dep_spdx_package.SPDXID),
713 "RUNTIME_DEPENDENCY_OF",
714 "%s:%s" % (package_ref.externalDocumentId, spdx_package.SPDXID)
715 )
716 seen_deps.add(dep)
717
718 oe.sbom.write_doc(d, runtime_doc, "runtime", spdx_deploy)
719}
720
721addtask do_create_runtime_spdx after do_create_spdx before do_build do_rm_work
722SSTATETASKS += "do_create_runtime_spdx"
723do_create_runtime_spdx[sstate-inputdirs] = "${SPDXRUNTIMEDEPLOY}"
724do_create_runtime_spdx[sstate-outputdirs] = "${DEPLOY_DIR_SPDX}"
725
726python do_create_runtime_spdx_setscene () {
727 sstate_setscene(d)
728}
729addtask do_create_runtime_spdx_setscene
730
731do_create_runtime_spdx[dirs] = "${SPDXRUNTIMEDEPLOY}"
732do_create_runtime_spdx[cleandirs] = "${SPDXRUNTIMEDEPLOY}"
733do_create_runtime_spdx[rdeptask] = "do_create_spdx"
734
735def spdx_get_src(d):
736 """
737 save patched source of the recipe in SPDX_WORKDIR.
738 """
739 import shutil
740 spdx_workdir = d.getVar('SPDXWORK')
741 spdx_sysroot_native = d.getVar('STAGING_DIR_NATIVE')
742 pn = d.getVar('PN')
743
744 workdir = d.getVar("WORKDIR")
745
746 try:
747 # The kernel class functions require it to be on work-shared, so we dont change WORKDIR
748 if not is_work_shared(d):
749 # Change the WORKDIR to make do_unpack do_patch run in another dir.
750 d.setVar('WORKDIR', spdx_workdir)
751 # Restore the original path to recipe's native sysroot (it's relative to WORKDIR).
752 d.setVar('STAGING_DIR_NATIVE', spdx_sysroot_native)
753
754 # The changed 'WORKDIR' also caused 'B' changed, create dir 'B' for the
755 # possibly requiring of the following tasks (such as some recipes's
756 # do_patch required 'B' existed).
757 bb.utils.mkdirhier(d.getVar('B'))
758
759 bb.build.exec_func('do_unpack', d)
760 # Copy source of kernel to spdx_workdir
761 if is_work_shared(d):
762 d.setVar('WORKDIR', spdx_workdir)
763 d.setVar('STAGING_DIR_NATIVE', spdx_sysroot_native)
764 src_dir = spdx_workdir + "/" + d.getVar('PN')+ "-" + d.getVar('PV') + "-" + d.getVar('PR')
765 bb.utils.mkdirhier(src_dir)
766 if bb.data.inherits_class('kernel',d):
767 share_src = d.getVar('STAGING_KERNEL_DIR')
768 cmd_copy_share = "cp -rf " + share_src + "/* " + src_dir + "/"
769 cmd_copy_kernel_result = os.popen(cmd_copy_share).read()
770 bb.note("cmd_copy_kernel_result = " + cmd_copy_kernel_result)
771
772 git_path = src_dir + "/.git"
773 if os.path.exists(git_path):
774 shutils.rmtree(git_path)
775
776 # Make sure gcc and kernel sources are patched only once
777 if not (d.getVar('SRC_URI') == "" or is_work_shared(d)):
778 bb.build.exec_func('do_patch', d)
779
780 # Some userland has no source.
781 if not os.path.exists( spdx_workdir ):
782 bb.utils.mkdirhier(spdx_workdir)
783 finally:
784 d.setVar("WORKDIR", workdir)
785
786do_rootfs[recrdeptask] += "do_create_spdx do_create_runtime_spdx"
787
788ROOTFS_POSTUNINSTALL_COMMAND =+ "image_combine_spdx ; "
789python image_combine_spdx() {
790 import os
791 import oe.spdx
792 import oe.sbom
793 import io
794 import json
795 from oe.rootfs import image_list_installed_packages
796 from datetime import timezone, datetime
797 from pathlib import Path
798 import tarfile
799 import bb.compress.zstd
800
801 creation_time = datetime.now(tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
802 image_name = d.getVar("IMAGE_NAME")
803 image_link_name = d.getVar("IMAGE_LINK_NAME")
804
805 deploy_dir_spdx = Path(d.getVar("DEPLOY_DIR_SPDX"))
806 imgdeploydir = Path(d.getVar("IMGDEPLOYDIR"))
807 source_date_epoch = d.getVar("SOURCE_DATE_EPOCH")
808
809 doc = oe.spdx.SPDXDocument()
810 doc.name = image_name
811 doc.documentNamespace = get_doc_namespace(d, doc)
812 doc.creationInfo.created = creation_time
813 doc.creationInfo.comment = "This document was created by analyzing the source of the Yocto recipe during the build."
814 doc.creationInfo.licenseListVersion = d.getVar("SPDX_LICENSE_DATA")["licenseListVersion"]
815 doc.creationInfo.creators.append("Tool: OpenEmbedded Core create-spdx.bbclass")
816 doc.creationInfo.creators.append("Organization: OpenEmbedded ()")
817 doc.creationInfo.creators.append("Person: N/A ()")
818
819 image = oe.spdx.SPDXPackage()
820 image.name = d.getVar("PN")
821 image.versionInfo = d.getVar("PV")
822 image.SPDXID = oe.sbom.get_image_spdxid(image_name)
823
824 doc.packages.append(image)
825
826 spdx_package = oe.spdx.SPDXPackage()
827
828 packages = image_list_installed_packages(d)
829
830 for name in sorted(packages.keys()):
831 pkg_spdx_path = deploy_dir_spdx / "packages" / (name + ".spdx.json")
832 pkg_doc, pkg_doc_sha1 = oe.sbom.read_doc(pkg_spdx_path)
833
834 for p in pkg_doc.packages:
835 if p.name == name:
836 pkg_ref = oe.spdx.SPDXExternalDocumentRef()
837 pkg_ref.externalDocumentId = "DocumentRef-%s" % pkg_doc.name
838 pkg_ref.spdxDocument = pkg_doc.documentNamespace
839 pkg_ref.checksum.algorithm = "SHA1"
840 pkg_ref.checksum.checksumValue = pkg_doc_sha1
841
842 doc.externalDocumentRefs.append(pkg_ref)
843 doc.add_relationship(image, "CONTAINS", "%s:%s" % (pkg_ref.externalDocumentId, p.SPDXID))
844 break
845 else:
846 bb.fatal("Unable to find package with name '%s' in SPDX file %s" % (name, pkg_spdx_path))
847
848 runtime_spdx_path = deploy_dir_spdx / "runtime" / ("runtime-" + name + ".spdx.json")
849 runtime_doc, runtime_doc_sha1 = oe.sbom.read_doc(runtime_spdx_path)
850
851 runtime_ref = oe.spdx.SPDXExternalDocumentRef()
852 runtime_ref.externalDocumentId = "DocumentRef-%s" % runtime_doc.name
853 runtime_ref.spdxDocument = runtime_doc.documentNamespace
854 runtime_ref.checksum.algorithm = "SHA1"
855 runtime_ref.checksum.checksumValue = runtime_doc_sha1
856
857 # "OTHER" isn't ideal here, but I can't find a relationship that makes sense
858 doc.externalDocumentRefs.append(runtime_ref)
859 doc.add_relationship(
860 image,
861 "OTHER",
862 "%s:%s" % (runtime_ref.externalDocumentId, runtime_doc.SPDXID),
863 comment="Runtime dependencies for %s" % name
864 )
865
866 image_spdx_path = imgdeploydir / (image_name + ".spdx.json")
867
868 with image_spdx_path.open("wb") as f:
869 doc.to_json(f, sort_keys=True)
870
871 image_spdx_link = imgdeploydir / (image_link_name + ".spdx.json")
872 image_spdx_link.symlink_to(os.path.relpath(image_spdx_path, image_spdx_link.parent))
873
874 num_threads = int(d.getVar("BB_NUMBER_THREADS"))
875
876 visited_docs = set()
877
878 index = {"documents": []}
879
880 spdx_tar_path = imgdeploydir / (image_name + ".spdx.tar.zst")
881 with bb.compress.zstd.open(spdx_tar_path, "w", num_threads=num_threads) as f:
882 with tarfile.open(fileobj=f, mode="w|") as tar:
883 def collect_spdx_document(path):
884 nonlocal tar
885 nonlocal deploy_dir_spdx
886 nonlocal source_date_epoch
887 nonlocal index
888
889 if path in visited_docs:
890 return
891
892 visited_docs.add(path)
893
894 with path.open("rb") as f:
895 doc, sha1 = oe.sbom.read_doc(f)
896 f.seek(0)
897
898 if doc.documentNamespace in visited_docs:
899 return
900
901 bb.note("Adding SPDX document %s" % path)
902 visited_docs.add(doc.documentNamespace)
903 info = tar.gettarinfo(fileobj=f)
904
905 info.name = doc.name + ".spdx.json"
906 info.uid = 0
907 info.gid = 0
908 info.uname = "root"
909 info.gname = "root"
910
911 if source_date_epoch is not None and info.mtime > int(source_date_epoch):
912 info.mtime = int(source_date_epoch)
913
914 tar.addfile(info, f)
915
916 index["documents"].append({
917 "filename": info.name,
918 "documentNamespace": doc.documentNamespace,
919 "sha1": sha1,
920 })
921
922 for ref in doc.externalDocumentRefs:
923 ref_path = deploy_dir_spdx / "by-namespace" / ref.spdxDocument.replace("/", "_")
924 collect_spdx_document(ref_path)
925
926 collect_spdx_document(image_spdx_path)
927
928 index["documents"].sort(key=lambda x: x["filename"])
929
930 index_str = io.BytesIO(json.dumps(index, sort_keys=True).encode("utf-8"))
931
932 info = tarfile.TarInfo()
933 info.name = "index.json"
934 info.size = len(index_str.getvalue())
935 info.uid = 0
936 info.gid = 0
937 info.uname = "root"
938 info.gname = "root"
939
940 tar.addfile(info, fileobj=index_str)
941
942 def make_image_link(target_path, suffix):
943 link = imgdeploydir / (image_link_name + suffix)
944 link.symlink_to(os.path.relpath(target_path, link.parent))
945
946 make_image_link(spdx_tar_path, ".spdx.tar.zst")
947
948 spdx_index_path = imgdeploydir / (image_name + ".spdx.index.json")
949 with spdx_index_path.open("w") as f:
950 json.dump(index, f, sort_keys=True)
951
952 make_image_link(spdx_index_path, ".spdx.index.json")
953}
954