-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
docker.go
324 lines (284 loc) · 9.46 KB
/
docker.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
package applier
import (
"fmt"
"strings"
"time"
"github.com/knqyf263/nested"
"github.com/package-url/packageurl-go"
"github.com/samber/lo"
"github.com/aquasecurity/trivy/pkg/dependency"
ftypes "github.com/aquasecurity/trivy/pkg/fanal/types"
"github.com/aquasecurity/trivy/pkg/log"
"github.com/aquasecurity/trivy/pkg/purl"
"github.com/aquasecurity/trivy/pkg/types"
)
type Config struct {
ContainerConfig containerConfig `json:"container_config"`
History []History
}
type containerConfig struct {
Env []string
}
type History struct {
Created time.Time
CreatedBy string `json:"created_by"`
}
func findPackage(e ftypes.Package, s []ftypes.Package) *ftypes.Package {
for _, a := range s {
if a.Name == e.Name && a.Version == e.Version && a.Release == e.Release {
return &a
}
}
return nil
}
func lookupOriginLayerForPkg(pkg ftypes.Package, layers []ftypes.BlobInfo) (string, string, []string, *ftypes.BuildInfo) {
for i, layer := range layers {
for _, info := range layer.PackageInfos {
if p := findPackage(pkg, info.Packages); p != nil {
return layer.Digest, layer.DiffID, p.InstalledFiles, lookupBuildInfo(i, layers)
}
}
}
return "", "", nil, nil
}
// lookupBuildInfo looks up Red Hat content sets from all layers
func lookupBuildInfo(index int, layers []ftypes.BlobInfo) *ftypes.BuildInfo {
if layers[index].BuildInfo != nil {
return layers[index].BuildInfo
}
// Base layer (layers[0]) is missing content sets
// - it needs to be shared from layers[1]
if index == 0 {
if len(layers) > 1 {
return layers[1].BuildInfo
}
return nil
}
// Customer's layers build on top of Red Hat image are also missing content sets
// - it needs to be shared from the last Red Hat's layers which contains content sets
for i := index - 1; i >= 1; i-- {
if layers[i].BuildInfo != nil {
return layers[i].BuildInfo
}
}
return nil
}
func lookupOriginLayerForLib(filePath string, lib ftypes.Package, layers []ftypes.BlobInfo) (string, string) {
for _, layer := range layers {
for _, layerApp := range layer.Applications {
if filePath != layerApp.FilePath {
continue
}
if findPackage(lib, layerApp.Packages) != nil {
return layer.Digest, layer.DiffID
}
}
}
return "", ""
}
// ApplyLayers returns the merged layer
// nolint: gocyclo
func ApplyLayers(layers []ftypes.BlobInfo) ftypes.ArtifactDetail {
sep := "/"
nestedMap := nested.Nested{}
secretsMap := make(map[string]ftypes.Secret)
var mergedLayer ftypes.ArtifactDetail
for _, layer := range layers {
for _, opqDir := range layer.OpaqueDirs {
opqDir = strings.TrimSuffix(opqDir, sep) // this is necessary so that an empty element is not contribute into the array of the DeleteByString function
_ = nestedMap.DeleteByString(opqDir, sep) // nolint
}
for _, whFile := range layer.WhiteoutFiles {
_ = nestedMap.DeleteByString(whFile, sep) // nolint
}
mergedLayer.OS.Merge(layer.OS)
if layer.Repository != nil {
mergedLayer.Repository = layer.Repository
}
// Apply OS packages
for _, pkgInfo := range layer.PackageInfos {
key := fmt.Sprintf("%s/type:ospkg", pkgInfo.FilePath)
nestedMap.SetByString(key, sep, pkgInfo)
}
// Apply language-specific packages
for _, app := range layer.Applications {
key := fmt.Sprintf("%s/type:%s", app.FilePath, app.Type)
nestedMap.SetByString(key, sep, app)
}
// Apply misconfigurations
for _, config := range layer.Misconfigurations {
config.Layer = ftypes.Layer{
Digest: layer.Digest,
DiffID: layer.DiffID,
}
key := fmt.Sprintf("%s/type:config", config.FilePath)
nestedMap.SetByString(key, sep, config)
}
// Apply secrets
for _, secret := range layer.Secrets {
l := ftypes.Layer{
Digest: layer.Digest,
DiffID: layer.DiffID,
CreatedBy: layer.CreatedBy,
}
secretsMap = mergeSecrets(secretsMap, secret, l)
}
// Apply license files
for _, license := range layer.Licenses {
license.Layer = ftypes.Layer{
Digest: layer.Digest,
DiffID: layer.DiffID,
}
key := fmt.Sprintf("%s/type:license,%s", license.FilePath, license.Type)
nestedMap.SetByString(key, sep, license)
}
// Apply custom resources
for _, customResource := range layer.CustomResources {
key := fmt.Sprintf("%s/custom:%s", customResource.FilePath, customResource.Type)
customResource.Layer = ftypes.Layer{
Digest: layer.Digest,
DiffID: layer.DiffID,
}
nestedMap.SetByString(key, sep, customResource)
}
}
// nolint
_ = nestedMap.Walk(func(keys []string, value any) error {
switch v := value.(type) {
case ftypes.PackageInfo:
mergedLayer.Packages = append(mergedLayer.Packages, v.Packages...)
case ftypes.Application:
mergedLayer.Applications = append(mergedLayer.Applications, v)
case ftypes.Misconfiguration:
mergedLayer.Misconfigurations = append(mergedLayer.Misconfigurations, v)
case ftypes.LicenseFile:
mergedLayer.Licenses = append(mergedLayer.Licenses, v)
case ftypes.CustomResource:
mergedLayer.CustomResources = append(mergedLayer.CustomResources, v)
}
return nil
})
for _, s := range secretsMap {
mergedLayer.Secrets = append(mergedLayer.Secrets, s)
}
// Extract dpkg licenses
// The license information is not stored in the dpkg database and in a separate file,
// so we have to merge the license information into the package.
dpkgLicenses := make(map[string][]string)
mergedLayer.Licenses = lo.Reject(mergedLayer.Licenses, func(license ftypes.LicenseFile, _ int) bool {
if license.Type != ftypes.LicenseTypeDpkg {
return false
}
// e.g.
// "adduser" => {"GPL-2"}
// "openssl" => {"MIT", "BSD"}
dpkgLicenses[license.PkgName] = lo.Map(license.Findings, func(finding ftypes.LicenseFinding, _ int) string {
return finding.Name
})
// Remove this license in the merged result as it is merged into the package information.
return true
})
if len(mergedLayer.Licenses) == 0 {
mergedLayer.Licenses = nil
}
for i, pkg := range mergedLayer.Packages {
// Skip lookup for SBOM
if lo.IsEmpty(pkg.Layer) {
originLayerDigest, originLayerDiffID, installedFiles, buildInfo := lookupOriginLayerForPkg(pkg, layers)
mergedLayer.Packages[i].Layer = ftypes.Layer{
Digest: originLayerDigest,
DiffID: originLayerDiffID,
}
mergedLayer.Packages[i].BuildInfo = buildInfo
// Debian/Ubuntu has the installed files only in the first layer where the package is installed.
mergedLayer.Packages[i].InstalledFiles = installedFiles
}
if mergedLayer.OS.Family != "" {
mergedLayer.Packages[i].Identifier.PURL = newPURL(mergedLayer.OS.Family, types.Metadata{OS: &mergedLayer.OS}, pkg)
}
mergedLayer.Packages[i].Identifier.UID = dependency.UID("", pkg)
// Only debian packages
if licenses, ok := dpkgLicenses[pkg.Name]; ok {
mergedLayer.Packages[i].Licenses = licenses
}
}
for _, app := range mergedLayer.Applications {
for i, pkg := range app.Packages {
// Skip lookup for SBOM
if lo.IsEmpty(pkg.Layer) {
originLayerDigest, originLayerDiffID := lookupOriginLayerForLib(app.FilePath, pkg, layers)
app.Packages[i].Layer = ftypes.Layer{
Digest: originLayerDigest,
DiffID: originLayerDiffID,
}
}
if pkg.Identifier.PURL == nil {
app.Packages[i].Identifier.PURL = newPURL(app.Type, types.Metadata{}, pkg)
}
app.Packages[i].Identifier.UID = dependency.UID(app.FilePath, pkg)
}
}
// Aggregate python/ruby/node.js packages and JAR files
aggregate(&mergedLayer)
return mergedLayer
}
func newPURL(pkgType ftypes.TargetType, metadata types.Metadata, pkg ftypes.Package) *packageurl.PackageURL {
p, err := purl.New(pkgType, metadata, pkg)
if err != nil {
log.Error("Failed to create PackageURL", log.Err(err))
return nil
}
return p.Unwrap()
}
// aggregate merges all packages installed by pip/gem/npm/jar/conda into each application
func aggregate(detail *ftypes.ArtifactDetail) {
var apps []ftypes.Application
aggregatedApps := make(map[ftypes.LangType]*ftypes.Application)
for _, t := range ftypes.AggregatingTypes {
aggregatedApps[t] = &ftypes.Application{Type: t}
}
for _, app := range detail.Applications {
a, ok := aggregatedApps[app.Type]
if !ok {
apps = append(apps, app)
continue
}
a.Packages = append(a.Packages, app.Packages...)
}
for _, app := range aggregatedApps {
if len(app.Packages) > 0 {
apps = append(apps, *app)
}
}
// Overwrite Applications
detail.Applications = apps
}
// We must save secrets from all layers even though they are removed in the uppler layer.
// If the secret was changed at the top level, we need to overwrite it.
func mergeSecrets(secretsMap map[string]ftypes.Secret, newSecret ftypes.Secret, layer ftypes.Layer) map[string]ftypes.Secret {
for i := range newSecret.Findings { // add layer to the Findings from the new secret
newSecret.Findings[i].Layer = layer
}
secret, ok := secretsMap[newSecret.FilePath]
if !ok {
// Add the new finding if its file doesn't exist before
secretsMap[newSecret.FilePath] = newSecret
} else {
// If the new finding has the same `RuleID` as the finding in the previous layers - use the new finding
for _, previousFinding := range secret.Findings { // secrets from previous layers
if !secretFindingsContains(newSecret.Findings, previousFinding) {
newSecret.Findings = append(newSecret.Findings, previousFinding)
}
}
secretsMap[newSecret.FilePath] = newSecret
}
return secretsMap
}
func secretFindingsContains(findings []ftypes.SecretFinding, finding ftypes.SecretFinding) bool {
for _, f := range findings {
if f.RuleID == finding.RuleID {
return true
}
}
return false
}