-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
marshal.go
557 lines (489 loc) · 16.2 KB
/
marshal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
package spdx
import (
"context"
"fmt"
"slices"
"sort"
"strings"
"time"
"github.com/mitchellh/hashstructure/v2"
"github.com/package-url/packageurl-go"
"github.com/samber/lo"
"github.com/spdx/tools-golang/spdx"
"github.com/spdx/tools-golang/spdx/v2/common"
spdxutils "github.com/spdx/tools-golang/utils"
"golang.org/x/xerrors"
"github.com/aquasecurity/trivy/pkg/clock"
"github.com/aquasecurity/trivy/pkg/digest"
"github.com/aquasecurity/trivy/pkg/licensing"
"github.com/aquasecurity/trivy/pkg/licensing/expression"
"github.com/aquasecurity/trivy/pkg/log"
"github.com/aquasecurity/trivy/pkg/sbom/core"
sbomio "github.com/aquasecurity/trivy/pkg/sbom/io"
"github.com/aquasecurity/trivy/pkg/types"
"github.com/aquasecurity/trivy/pkg/uuid"
)
const (
DocumentSPDXIdentifier = "DOCUMENT"
DocumentNamespace = "http://aquasecurity.github.io/trivy"
CreatorOrganization = "aquasecurity"
CreatorTool = "trivy"
noneField = "NONE"
noAssertionField = "NOASSERTION"
)
const (
CategoryPackageManager = "PACKAGE-MANAGER"
RefTypePurl = "purl"
// Package Purpose fields
PackagePurposeOS = "OPERATING-SYSTEM"
PackagePurposeContainer = "CONTAINER"
PackagePurposeSource = "SOURCE"
PackagePurposeApplication = "APPLICATION"
PackagePurposeLibrary = "LIBRARY"
PackageSupplierNoAssertion = "NOASSERTION"
PackageSupplierOrganization = "Organization"
RelationShipContains = common.TypeRelationshipContains
RelationShipDescribe = common.TypeRelationshipDescribe
RelationShipDependsOn = common.TypeRelationshipDependsOn
ElementOperatingSystem = "OperatingSystem"
ElementApplication = "Application"
ElementPackage = "Package"
ElementFile = "File"
)
var (
SourcePackagePrefix = "built package from"
SourceFilePrefix = "package found in"
)
// duplicateProperties contains a list of properties contained in other fields.
var duplicateProperties = []string{
// `SourceInfo` contains SrcName and SrcVersion (it contains PropertySrcRelease and PropertySrcEpoch)
core.PropertySrcName,
core.PropertySrcRelease,
core.PropertySrcEpoch,
core.PropertySrcVersion,
// `File` contains filePath.
core.PropertyFilePath,
}
type Marshaler struct {
format spdx.Document
hasher Hash
appVersion string // Trivy version. It needed for `creator` field
}
type Hash func(v any, format hashstructure.Format, opts *hashstructure.HashOptions) (uint64, error)
type marshalOption func(*Marshaler)
func WithHasher(hasher Hash) marshalOption {
return func(opts *Marshaler) {
opts.hasher = hasher
}
}
func NewMarshaler(version string, opts ...marshalOption) *Marshaler {
m := &Marshaler{
format: spdx.Document{},
hasher: hashstructure.Hash,
appVersion: version,
}
for _, opt := range opts {
opt(m)
}
return m
}
func (m *Marshaler) MarshalReport(ctx context.Context, report types.Report) (*spdx.Document, error) {
// Convert into an intermediate representation
bom, err := sbomio.NewEncoder(core.Options{}).Encode(report)
if err != nil {
return nil, xerrors.Errorf("failed to marshal report: %w", err)
}
return m.Marshal(ctx, bom)
}
func (m *Marshaler) Marshal(ctx context.Context, bom *core.BOM) (*spdx.Document, error) {
var (
relationShips []*spdx.Relationship
packages []*spdx.Package
)
root := bom.Root()
pkgDownloadLocation := m.packageDownloadLocation(root)
// Component ID => SPDX ID
packageIDs := make(map[uuid.UUID]spdx.ElementID)
// Root package contains OS, OS packages, language-specific packages and so on.
rootPkg, err := m.rootSPDXPackage(root, pkgDownloadLocation)
if err != nil {
return nil, xerrors.Errorf("failed to generate a root package: %w", err)
}
packages = append(packages, rootPkg)
relationShips = append(relationShips,
m.spdxRelationShip(DocumentSPDXIdentifier, rootPkg.PackageSPDXIdentifier, RelationShipDescribe),
)
packageIDs[root.ID()] = rootPkg.PackageSPDXIdentifier
var files []*spdx.File
for _, c := range bom.Components() {
if c.Root {
continue
}
spdxPackage, err := m.spdxPackage(c, pkgDownloadLocation)
if err != nil {
return nil, xerrors.Errorf("spdx package error: %w", err)
}
// Add advisories for package
// cf. https://spdx.github.io/spdx-spec/v2.3/how-to-use/#k1-including-security-information-in-a-spdx-document
if vulns, ok := bom.Vulnerabilities()[c.ID()]; ok {
for _, v := range vulns {
spdxPackage.PackageExternalReferences = append(spdxPackage.PackageExternalReferences, m.advisoryExternalReference(v.PrimaryURL))
}
}
packages = append(packages, &spdxPackage)
packageIDs[c.ID()] = spdxPackage.PackageSPDXIdentifier
spdxFiles, err := m.spdxFiles(c)
if err != nil {
return nil, xerrors.Errorf("spdx files error: %w", err)
} else if len(spdxFiles) == 0 {
continue
}
files = append(files, spdxFiles...)
for _, file := range spdxFiles {
relationShips = append(relationShips,
m.spdxRelationShip(spdxPackage.PackageSPDXIdentifier, file.FileSPDXIdentifier, RelationShipContains),
)
}
verificationCode, err := spdxutils.GetVerificationCode(spdxFiles, "")
if err != nil {
return nil, xerrors.Errorf("package verification error: %w", err)
}
spdxPackage.FilesAnalyzed = true
spdxPackage.PackageVerificationCode = &verificationCode
}
for id, rels := range bom.Relationships() {
for _, rel := range rels {
refA, ok := packageIDs[id]
if !ok {
continue
}
refB, ok := packageIDs[rel.Dependency]
if !ok {
continue
}
relationShips = append(relationShips, m.spdxRelationShip(refA, refB, m.spdxRelationshipType(rel.Type)))
}
}
sortPackages(packages)
sortRelationships(relationShips)
sortFiles(files)
return &spdx.Document{
SPDXVersion: spdx.Version,
DataLicense: spdx.DataLicense,
SPDXIdentifier: DocumentSPDXIdentifier,
DocumentName: root.Name,
DocumentNamespace: getDocumentNamespace(root),
CreationInfo: &spdx.CreationInfo{
Creators: []common.Creator{
{
Creator: CreatorOrganization,
CreatorType: "Organization",
},
{
Creator: fmt.Sprintf("%s-%s", CreatorTool, m.appVersion),
CreatorType: "Tool",
},
},
Created: clock.Now(ctx).UTC().Format(time.RFC3339),
},
Packages: packages,
Relationships: relationShips,
Files: files,
}, nil
}
func (m *Marshaler) packageDownloadLocation(root *core.Component) string {
location := noneField
// this field is used for git/mercurial/subversion/bazaar:
// https://spdx.github.io/spdx-spec/v2.2.2/package-information/#77-package-download-location-field
if root.Type == core.TypeRepository {
// Trivy currently only supports git repositories. Format examples:
// git+https://git.myproject.org/MyProject.git
// git+http://git.myproject.org/MyProject
location = fmt.Sprintf("git+%s", root.Name)
}
return location
}
func (m *Marshaler) rootSPDXPackage(root *core.Component, pkgDownloadLocation string) (*spdx.Package, error) {
var externalReferences []*spdx.PackageExternalReference
// When the target is a container image, add PURL to the external references of the root package.
if root.PkgIdentifier.PURL != nil {
externalReferences = append(externalReferences, m.purlExternalReference(root.PkgIdentifier.PURL.String()))
}
pkgID, err := calcPkgID(m.hasher, fmt.Sprintf("%s-%s", root.Name, root.Type))
if err != nil {
return nil, xerrors.Errorf("failed to get %s package ID: %w", pkgID, err)
}
pkgPurpose := PackagePurposeSource
if root.Type == core.TypeContainerImage {
pkgPurpose = PackagePurposeContainer
}
return &spdx.Package{
PackageName: root.Name,
PackageSPDXIdentifier: elementID(camelCase(string(root.Type)), pkgID),
PackageDownloadLocation: pkgDownloadLocation,
PackageAttributionTexts: m.spdxAttributionTexts(root),
PackageExternalReferences: externalReferences,
PrimaryPackagePurpose: pkgPurpose,
}, nil
}
func (m *Marshaler) appendAttributionText(attributionTexts []string, key, value string) []string {
if value == "" {
return attributionTexts
}
return append(attributionTexts, fmt.Sprintf("%s: %s", key, value))
}
func (m *Marshaler) purlExternalReference(packageURL string) *spdx.PackageExternalReference {
return &spdx.PackageExternalReference{
Category: CategoryPackageManager,
RefType: RefTypePurl,
Locator: packageURL,
}
}
func (m *Marshaler) advisoryExternalReference(primaryURL string) *spdx.PackageExternalReference {
return &spdx.PackageExternalReference{
Category: common.CategorySecurity,
RefType: common.TypeSecurityAdvisory,
Locator: primaryURL,
}
}
func (m *Marshaler) spdxPackage(c *core.Component, pkgDownloadLocation string) (spdx.Package, error) {
pkgID, err := calcPkgID(m.hasher, c)
if err != nil {
return spdx.Package{}, xerrors.Errorf("failed to get os metadata package ID: %w", err)
}
var elementType, purpose, license, sourceInfo string
var supplier *spdx.Supplier
switch c.Type {
case core.TypeOS:
elementType = ElementOperatingSystem
purpose = PackagePurposeOS
case core.TypeApplication:
elementType = ElementApplication
purpose = PackagePurposeApplication
case core.TypeLibrary:
elementType = ElementPackage
purpose = PackagePurposeLibrary
license = m.spdxLicense(c)
if c.SrcName != "" {
sourceInfo = fmt.Sprintf("%s: %s %s", SourcePackagePrefix, c.SrcName, c.SrcVersion)
} else if c.SrcFile != "" {
sourceInfo = fmt.Sprintf("%s: %s", SourceFilePrefix, c.SrcFile)
}
supplier = &spdx.Supplier{Supplier: PackageSupplierNoAssertion}
if c.Supplier != "" {
supplier = &spdx.Supplier{
SupplierType: PackageSupplierOrganization, // Always use "Organization" at the moment as it is difficult to distinguish between "Person" or "Organization".
Supplier: c.Supplier,
}
}
}
var pkgExtRefs []*spdx.PackageExternalReference
if c.PkgIdentifier.PURL != nil {
pkgExtRefs = []*spdx.PackageExternalReference{m.purlExternalReference(c.PkgIdentifier.PURL.String())}
}
var digests []digest.Digest
for _, f := range c.Files {
// The file digests are stored separately.
if f.Path != "" {
continue
}
digests = append(digests, f.Digests...)
}
return spdx.Package{
PackageSPDXIdentifier: elementID(elementType, pkgID),
PackageName: spdxPkgName(c),
PackageVersion: c.Version,
PrimaryPackagePurpose: purpose,
PackageDownloadLocation: pkgDownloadLocation,
PackageExternalReferences: pkgExtRefs,
PackageAttributionTexts: m.spdxAttributionTexts(c),
PackageSourceInfo: sourceInfo,
PackageSupplier: supplier,
PackageChecksums: m.spdxChecksums(digests),
// The Declared License is what the authors of a project believe govern the package
PackageLicenseConcluded: license,
// The Concluded License field is the license the SPDX file creator believes governs the package
PackageLicenseDeclared: license,
}, nil
}
func spdxPkgName(component *core.Component) string {
if p := component.PkgIdentifier.PURL; p != nil && component.Group != "" {
if p.Type == packageurl.TypeMaven || p.Type == packageurl.TypeGradle {
return component.Group + ":" + component.Name
}
return component.Group + "/" + component.Name
}
return component.Name
}
func (m *Marshaler) spdxAttributionTexts(c *core.Component) []string {
var texts []string
for _, p := range c.Properties {
// Add properties that are not in other fields.
if !slices.Contains(duplicateProperties, p.Name) {
texts = m.appendAttributionText(texts, p.Name, p.Value)
}
}
return texts
}
func (m *Marshaler) spdxLicense(c *core.Component) string {
if len(c.Licenses) == 0 {
return noAssertionField
}
return NormalizeLicense(c.Licenses)
}
func (m *Marshaler) spdxChecksums(digests []digest.Digest) []common.Checksum {
var checksums []common.Checksum
for _, d := range digests {
var alg spdx.ChecksumAlgorithm
switch d.Algorithm() {
case digest.SHA1:
alg = spdx.SHA1
case digest.SHA256:
alg = spdx.SHA256
case digest.MD5:
alg = spdx.MD5
default:
return nil
}
checksums = append(checksums, spdx.Checksum{
Algorithm: alg,
Value: d.Encoded(),
})
}
return checksums
}
func (m *Marshaler) spdxFiles(c *core.Component) ([]*spdx.File, error) {
var files []*spdx.File
for _, file := range c.Files {
if file.Path == "" || len(file.Digests) == 0 {
continue
}
spdxFile, err := m.spdxFile(file.Path, file.Digests)
if err != nil {
return nil, xerrors.Errorf("failed to parse file: %w", err)
}
files = append(files, spdxFile)
}
return files, nil
}
func (m *Marshaler) spdxFile(filePath string, digests []digest.Digest) (*spdx.File, error) {
pkgID, err := calcPkgID(m.hasher, filePath)
if err != nil {
return nil, xerrors.Errorf("failed to get %s package ID: %w", filePath, err)
}
return &spdx.File{
FileSPDXIdentifier: spdx.ElementID(fmt.Sprintf("File-%s", pkgID)),
FileName: filePath,
Checksums: m.spdxChecksums(digests),
}, nil
}
func (m *Marshaler) spdxRelationShip(refA, refB spdx.ElementID, operator string) *spdx.Relationship {
ref := spdx.Relationship{
RefA: common.MakeDocElementID("", string(refA)),
RefB: common.MakeDocElementID("", string(refB)),
Relationship: operator,
}
return &ref
}
func (m *Marshaler) spdxRelationshipType(relType core.RelationshipType) string {
switch relType {
case core.RelationshipDependsOn:
return RelationShipDependsOn
case core.RelationshipContains:
return RelationShipContains
case core.RelationshipDescribes:
return RelationShipDescribe
default:
return RelationShipDependsOn
}
}
func sortPackages(pkgs []*spdx.Package) {
sort.Slice(pkgs, func(i, j int) bool {
switch {
case pkgs[i].PrimaryPackagePurpose != pkgs[j].PrimaryPackagePurpose:
return pkgs[i].PrimaryPackagePurpose < pkgs[j].PrimaryPackagePurpose
case pkgs[i].PackageName != pkgs[j].PackageName:
return pkgs[i].PackageName < pkgs[j].PackageName
default:
return pkgs[i].PackageSPDXIdentifier < pkgs[j].PackageSPDXIdentifier
}
})
}
func sortRelationships(rels []*spdx.Relationship) {
sort.Slice(rels, func(i, j int) bool {
switch {
case rels[i].RefA.ElementRefID != rels[j].RefA.ElementRefID:
return rels[i].RefA.ElementRefID < rels[j].RefA.ElementRefID
case rels[i].RefB.ElementRefID != rels[j].RefB.ElementRefID:
return rels[i].RefB.ElementRefID < rels[j].RefB.ElementRefID
default:
return rels[i].Relationship < rels[j].Relationship
}
})
}
func sortFiles(files []*spdx.File) {
sort.Slice(files, func(i, j int) bool {
switch {
case files[i].FileName != files[j].FileName:
return files[i].FileName < files[j].FileName
default:
return files[i].FileSPDXIdentifier < files[j].FileSPDXIdentifier
}
})
}
func elementID(elementType, pkgID string) spdx.ElementID {
return spdx.ElementID(fmt.Sprintf("%s-%s", elementType, pkgID))
}
func getDocumentNamespace(root *core.Component) string {
return fmt.Sprintf("%s/%s/%s-%s",
DocumentNamespace,
string(root.Type),
strings.ReplaceAll(strings.ReplaceAll(root.Name, "https://", ""), "http://", ""), // remove http(s):// prefix when scanning repos
uuid.New().String(),
)
}
func calcPkgID(h Hash, v any) (string, error) {
f, err := h(v, hashstructure.FormatV2, &hashstructure.HashOptions{
ZeroNil: true,
SlicesAsSets: true,
})
if err != nil {
return "", xerrors.Errorf("could not build package ID for %+v: %w", v, err)
}
return fmt.Sprintf("%x", f), nil
}
func camelCase(inputUnderScoreStr string) (camelCase string) {
isToUpper := false
for k, v := range inputUnderScoreStr {
if k == 0 {
camelCase = strings.ToUpper(string(inputUnderScoreStr[0]))
} else {
if isToUpper {
camelCase += strings.ToUpper(string(v))
isToUpper = false
} else {
if v == '_' {
isToUpper = true
} else {
camelCase += string(v)
}
}
}
}
return
}
func NormalizeLicense(licenses []string) string {
license := strings.Join(lo.Map(licenses, func(license string, index int) string {
// e.g. GPL-3.0-with-autoconf-exception
license = strings.ReplaceAll(license, "-with-", " WITH ")
license = strings.ReplaceAll(license, "-WITH-", " WITH ")
return fmt.Sprintf("(%s)", license)
}), " AND ")
s, err := expression.Normalize(license, licensing.NormalizeLicense, expression.NormalizeForSPDX)
if err != nil {
// Not fail on the invalid license
log.Warn("Unable to marshal SPDX licenses", log.String("license", license))
return ""
}
return s
}