-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
unmarshal.go
264 lines (231 loc) · 6.72 KB
/
unmarshal.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
package cyclonedx
import (
"bytes"
"errors"
"io"
"strings"
cdx "github.com/CycloneDX/cyclonedx-go"
"github.com/package-url/packageurl-go"
"github.com/samber/lo"
"go.uber.org/zap"
"golang.org/x/xerrors"
"github.com/aquasecurity/trivy/pkg/digest"
"github.com/aquasecurity/trivy/pkg/log"
"github.com/aquasecurity/trivy/pkg/sbom/core"
)
var (
ErrUnsupportedType = errors.New("unsupported type")
)
type BOM struct {
*core.BOM
}
func DecodeJSON(r io.Reader) (*cdx.BOM, error) {
bom := cdx.NewBOM()
decoder := cdx.NewBOMDecoder(r, cdx.BOMFileFormatJSON)
if err := decoder.Decode(bom); err != nil {
return nil, xerrors.Errorf("CycloneDX decode error: %w", err)
}
return bom, nil
}
func (b *BOM) UnmarshalJSON(data []byte) error {
log.Logger.Debug("Unmarshalling CycloneDX JSON...")
if b.BOM == nil {
b.BOM = core.NewBOM(core.Options{GenerateBOMRef: true})
}
cdxBOM, err := DecodeJSON(bytes.NewReader(data))
if err != nil {
return xerrors.Errorf("CycloneDX decode error: %w", err)
}
if !IsTrivySBOM(cdxBOM) {
log.Logger.Warnf("Third-party SBOM may lead to inaccurate vulnerability detection")
log.Logger.Warnf("Recommend using Trivy to generate SBOMs")
}
if err = b.parseBOM(cdxBOM); err != nil {
return xerrors.Errorf("failed to parse sbom: %w", err)
}
// Store the original metadata
b.BOM.SerialNumber = cdxBOM.SerialNumber
b.BOM.Version = cdxBOM.Version
return nil
}
func (b *BOM) parseBOM(bom *cdx.BOM) error {
// Convert all CycloneDX components into Trivy components
components := b.parseComponents(bom.Components)
// Convert the metadata component into Trivy component
mComponent, err := b.parseMetadataComponent(bom)
if err != nil {
return xerrors.Errorf("failed to parse root component: %w", err)
} else if mComponent != nil {
components[mComponent.PkgID.BOMRef] = mComponent
}
// Parse dependencies and build relationships
for _, dep := range lo.FromPtr(bom.Dependencies) {
ref, ok := components[dep.Ref]
if !ok {
continue
}
for _, depRef := range lo.FromPtr(dep.Dependencies) {
dependency, ok := components[depRef]
if !ok {
continue
}
b.BOM.AddRelationship(ref, dependency, core.RelationshipDependsOn)
}
}
return nil
}
func (b *BOM) parseMetadataComponent(bom *cdx.BOM) (*core.Component, error) {
if bom.Metadata == nil || bom.Metadata.Component == nil {
return nil, nil
}
root, err := b.parseComponent(*bom.Metadata.Component)
if err != nil {
return nil, xerrors.Errorf("failed to parse metadata component: %w", err)
}
root.Root = true
b.BOM.AddComponent(root)
return root, nil
}
func (b *BOM) parseComponents(cdxComponents *[]cdx.Component) map[string]*core.Component {
components := make(map[string]*core.Component)
for _, component := range lo.FromPtr(cdxComponents) {
c, err := b.parseComponent(component)
if errors.Is(err, ErrUnsupportedType) {
log.Logger.Infow("Skipping the component with the unsupported type",
zap.String("bom-ref", component.BOMRef), zap.String("type", string(component.Type)))
continue
} else if err != nil {
log.Logger.Warnw("Failed to parse component: %s", zap.Error(err))
continue
}
b.BOM.AddComponent(c)
components[component.BOMRef] = c
}
return components
}
func (b *BOM) parseComponent(c cdx.Component) (*core.Component, error) {
componentType, err := b.unmarshalType(c.Type)
if err != nil {
return nil, xerrors.Errorf("failed to unmarshal component type: %w", err)
}
// Parse PURL
var purl packageurl.PackageURL
if c.PackageURL != "" {
purl, err = packageurl.FromString(c.PackageURL)
if err != nil {
return nil, xerrors.Errorf("failed to parse PURL: %w", err)
}
}
component := &core.Component{
Type: componentType,
Name: c.Name,
Group: c.Group,
Version: c.Version,
Licenses: b.unmarshalLicenses(c.Licenses),
Files: []core.File{
{
Digests: b.unmarshalHashes(c.Hashes),
},
},
PkgID: core.PkgID{
PURL: &purl,
BOMRef: c.BOMRef,
},
Supplier: b.unmarshalSupplier(c.Supplier),
Properties: b.unmarshalProperties(c.Properties),
}
return component, nil
}
func (b *BOM) unmarshalType(t cdx.ComponentType) (core.ComponentType, error) {
var ctype core.ComponentType
switch t {
case cdx.ComponentTypeContainer:
ctype = core.TypeContainerImage
case cdx.ComponentTypeApplication:
ctype = core.TypeApplication
case cdx.ComponentTypeLibrary:
ctype = core.TypeLibrary
case cdx.ComponentTypeOS:
ctype = core.TypeOS
case cdx.ComponentTypePlatform:
ctype = core.TypePlatform
default:
return "", ErrUnsupportedType
}
return ctype, nil
}
// parsePackageLicenses checks all supported license fields and returns a list of licenses.
// https://cyclonedx.org/docs/1.5/json/#components_items_licenses
func (b *BOM) unmarshalLicenses(l *cdx.Licenses) []string {
var licenses []string
for _, license := range lo.FromPtr(l) {
if license.License != nil {
// Trivy uses `Name` field to marshal licenses
if license.License.Name != "" {
licenses = append(licenses, license.License.Name)
continue
}
if license.License.ID != "" {
licenses = append(licenses, license.License.ID)
continue
}
}
if license.Expression != "" {
licenses = append(licenses, license.Expression)
continue
}
}
return licenses
}
func (b *BOM) unmarshalHashes(hashes *[]cdx.Hash) []digest.Digest {
var digests []digest.Digest
for _, h := range lo.FromPtr(hashes) {
var alg digest.Algorithm
switch h.Algorithm {
case cdx.HashAlgoSHA1:
alg = digest.SHA1
case cdx.HashAlgoSHA256:
alg = digest.SHA256
case cdx.HashAlgoMD5:
alg = digest.MD5
default:
log.Logger.Warnf("Unsupported hash algorithm: %s", h.Algorithm)
}
digests = append(digests, digest.NewDigestFromString(alg, h.Value))
}
return digests
}
func (b *BOM) unmarshalSupplier(supplier *cdx.OrganizationalEntity) string {
if supplier == nil {
return ""
}
return supplier.Name
}
func (b *BOM) unmarshalProperties(properties *[]cdx.Property) []core.Property {
var props []core.Property
for _, p := range lo.FromPtr(properties) {
props = append(props, core.Property{
Name: strings.TrimPrefix(p.Name, Namespace),
Value: p.Value,
})
}
return props
}
func IsTrivySBOM(c *cdx.BOM) bool {
if c == nil || c.Metadata == nil || c.Metadata.Tools == nil {
return false
}
for _, component := range lo.FromPtr(c.Metadata.Tools.Components) {
if component.Group == ToolVendor && component.Name == ToolName {
return true
}
}
// Metadata.Tools array is deprecated (as of CycloneDX v1.5). We check this field for backward compatibility.
// cf. https://github.com/CycloneDX/cyclonedx-go/blob/b9654ae9b4705645152d20eb9872b5f3d73eac49/cyclonedx.go#L988
for _, tool := range lo.FromPtr(c.Metadata.Tools.Tools) {
if tool.Vendor == ToolVendor && tool.Name == ToolName {
return true
}
}
return false
}