-
Notifications
You must be signed in to change notification settings - Fork 602
/
Copy pathroot.go
344 lines (291 loc) · 10.5 KB
/
root.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
package cmd
import (
"fmt"
"os"
"sync"
"github.com/anchore/grype/grype"
"github.com/anchore/grype/grype/db"
"github.com/anchore/grype/grype/event"
"github.com/anchore/grype/grype/grypeerr"
"github.com/anchore/grype/grype/match"
"github.com/anchore/grype/grype/pkg"
"github.com/anchore/grype/grype/presenter"
"github.com/anchore/grype/grype/vulnerability"
"github.com/anchore/grype/internal"
"github.com/anchore/grype/internal/bus"
"github.com/anchore/grype/internal/config"
"github.com/anchore/grype/internal/format"
"github.com/anchore/grype/internal/log"
"github.com/anchore/grype/internal/ui"
"github.com/anchore/grype/internal/version"
"github.com/anchore/stereoscope"
"github.com/anchore/syft/syft/source"
"github.com/pkg/profile"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/wagoodman/go-partybus"
grypeDb "github.com/anchore/grype-db/pkg/db/v3"
)
var persistentOpts = config.CliOnlyOptions{}
var ignoreNonFixedMatches = []match.IgnoreRule{
{FixState: string(grypeDb.NotFixedState)},
{FixState: string(grypeDb.WontFixState)},
{FixState: string(grypeDb.UnknownFixState)},
}
var (
rootCmd = &cobra.Command{
Use: fmt.Sprintf("%s [IMAGE]", internal.ApplicationName),
Short: "A vulnerability scanner for container images, filesystems, and SBOMs",
Long: format.Tprintf(`A vulnerability scanner for container images, filesystems, and SBOMs.
Supports the following image sources:
{{.appName}} yourrepo/yourimage:tag defaults to using images from a Docker daemon
{{.appName}} path/to/yourproject a Docker tar, OCI tar, OCI directory, or generic filesystem directory
You can also explicitly specify the scheme to use:
{{.appName}} docker:yourrepo/yourimage:tag explicitly use the Docker daemon
{{.appName}} docker-archive:path/to/yourimage.tar use a tarball from disk for archives created from "docker save"
{{.appName}} oci-archive:path/to/yourimage.tar use a tarball from disk for OCI archives (from Podman or otherwise)
{{.appName}} oci-dir:path/to/yourimage read directly from a path on disk for OCI layout directories (from Skopeo or otherwise)
{{.appName}} dir:path/to/yourproject read directly from a path on disk (any directory)
{{.appName}} sbom:path/to/syft.json read Syft JSON from path on disk
{{.appName}} registry:yourrepo/yourimage:tag pull image directly from a registry (no container runtime required)
You can also pipe in Syft JSON directly:
syft yourimage:tag -o json | {{.appName}}
`, map[string]interface{}{
"appName": internal.ApplicationName,
}),
Args: validateRootArgs,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
if appConfig.Dev.ProfileCPU {
defer profile.Start(profile.CPUProfile).Stop()
} else if appConfig.Dev.ProfileMem {
defer profile.Start(profile.MemProfile).Stop()
}
return rootExec(cmd, args)
},
ValidArgsFunction: dockerImageValidArgsFunction,
}
)
func init() {
setGlobalCliOptions()
setRootFlags(rootCmd.Flags())
}
func setGlobalCliOptions() {
// setup global CLI options (available on all CLI commands)
rootCmd.PersistentFlags().StringVarP(&persistentOpts.ConfigPath, "config", "c", "", "application config file")
flag := "quiet"
rootCmd.PersistentFlags().BoolP(
flag, "q", false,
"suppress all logging output",
)
if err := viper.BindPFlag(flag, rootCmd.PersistentFlags().Lookup(flag)); err != nil {
fmt.Printf("unable to bind flag '%s': %+v", flag, err)
os.Exit(1)
}
rootCmd.PersistentFlags().CountVarP(&persistentOpts.Verbosity, "verbose", "v", "increase verbosity (-v = info, -vv = debug)")
}
func setRootFlags(flags *pflag.FlagSet) {
flags.StringP(
"scope", "s", source.SquashedScope.String(),
fmt.Sprintf("selection of layers to analyze, options=%v", source.AllScopes),
)
flags.StringP(
"output", "o", "",
fmt.Sprintf("report output formatter, formats=%v", presenter.AvailableFormats),
)
flags.StringP(
"file", "", "",
"file to write the report output to (default is STDOUT)",
)
flags.StringP("template", "t", "", "specify the path to a Go template file ("+
"requires 'template' output to be selected)")
flags.StringP(
"fail-on", "f", "",
fmt.Sprintf("set the return code to 1 if a vulnerability is found with a severity >= the given severity, options=%v", vulnerability.AllSeverities),
)
flags.BoolP(
"only-fixed", "", false,
"ignore matches for vulnerabilities that are not fixed",
)
}
func bindRootConfigOptions(flags *pflag.FlagSet) error {
if err := viper.BindPFlag("scope", flags.Lookup("scope")); err != nil {
return err
}
if err := viper.BindPFlag("output", flags.Lookup("output")); err != nil {
return err
}
if err := viper.BindPFlag("file", flags.Lookup("file")); err != nil {
return err
}
if err := viper.BindPFlag("output-template-file", flags.Lookup("template")); err != nil {
return err
}
if err := viper.BindPFlag("fail-on-severity", flags.Lookup("fail-on")); err != nil {
return err
}
if err := viper.BindPFlag("only-fixed", flags.Lookup("only-fixed")); err != nil {
return err
}
return nil
}
func rootExec(_ *cobra.Command, args []string) error {
// we may not be provided an image if the user is piping in SBOM input
var userInput string
if len(args) > 0 {
userInput = args[0]
}
reporter, closer, err := reportWriter()
defer func() {
if err := closer(); err != nil {
log.Warnf("unable to write to report destination: %+v", err)
}
}()
if err != nil {
return err
}
return eventLoop(
startWorker(userInput, appConfig.FailOnSeverity),
setupSignals(),
eventSubscription,
stereoscope.Cleanup,
ui.Select(isVerbose(), appConfig.Quiet, reporter)...,
)
}
func isVerbose() (result bool) {
isPipedInput, err := internal.IsPipedInput()
if err != nil {
// since we can't tell if there was piped input we assume that there could be to disable the ETUI
log.Warnf("unable to determine if there is piped input: %+v", err)
return true
}
// verbosity should consider if there is piped input (in which case we should not show the ETUI)
return appConfig.CliOptions.Verbosity > 0 || isPipedInput
}
// nolint:funlen
func startWorker(userInput string, failOnSeverity *vulnerability.Severity) <-chan error {
errs := make(chan error)
go func() {
defer close(errs)
presenterConfig, err := presenter.ValidatedConfig(appConfig.Output, appConfig.OutputTemplateFile)
if err != nil {
errs <- err
return
}
if appConfig.CheckForAppUpdate {
isAvailable, newVersion, err := version.IsUpdateAvailable()
if err != nil {
log.Errorf(err.Error())
}
if isAvailable {
log.Infof("New version of %s is available: %s", internal.ApplicationName, newVersion)
bus.Publish(partybus.Event{
Type: event.AppUpdateAvailable,
Value: newVersion,
})
} else {
log.Debugf("No new %s update available", internal.ApplicationName)
}
}
var provider vulnerability.Provider
var metadataProvider vulnerability.MetadataProvider
var dbStatus *db.Status
var packages []pkg.Package
var context pkg.Context
var wg = &sync.WaitGroup{}
var loadedDB, gatheredPackages bool
wg.Add(2)
go func() {
defer wg.Done()
log.Debug("loading DB")
provider, metadataProvider, dbStatus, err = grype.LoadVulnerabilityDB(appConfig.DB.ToCuratorConfig(), appConfig.DB.AutoUpdate)
if err = validateDBLoad(err, dbStatus); err != nil {
errs <- err
return
}
loadedDB = true
}()
go func() {
defer wg.Done()
log.Debugf("gathering packages")
packages, context, err = pkg.Provide(userInput, appConfig.ScopeOpt, appConfig.Registry.ToOptions())
if err != nil {
errs <- fmt.Errorf("failed to catalog: %w", err)
return
}
gatheredPackages = true
}()
wg.Wait()
if !loadedDB || !gatheredPackages {
return
}
if appConfig.OnlyFixed {
appConfig.Ignore = append(appConfig.Ignore, ignoreNonFixedMatches...)
}
allMatches := grype.FindVulnerabilitiesForPackage(provider, context.Distro, packages...)
remainingMatches, ignoredMatches := match.ApplyIgnoreRules(allMatches, appConfig.Ignore)
if count := len(ignoredMatches); count > 0 {
log.Infof("ignoring %d matches due to user-provided ignore rules", count)
}
// determine if there are any severities >= to the max allowable severity (which is optional).
// note: until the shared file lock in sqlittle is fixed the sqlite DB cannot be access concurrently,
// implying that the fail-on-severity check must be done before sending the presenter object.
if hitSeverityThreshold(failOnSeverity, remainingMatches, metadataProvider) {
errs <- grypeerr.ErrAboveSeverityThreshold
}
bus.Publish(partybus.Event{
Type: event.VulnerabilityScanningFinished,
Value: presenter.GetPresenter(presenterConfig, remainingMatches, ignoredMatches, packages, context, metadataProvider, appConfig, dbStatus),
})
}()
return errs
}
func validateDBLoad(loadErr error, status *db.Status) error {
if loadErr != nil {
return fmt.Errorf("failed to load vulnerability db: %w", loadErr)
}
if status == nil {
return fmt.Errorf("unable to determine DB status")
}
if status.Err != nil {
return fmt.Errorf("db could not be loaded: %w", status.Err)
}
return nil
}
func validateRootArgs(cmd *cobra.Command, args []string) error {
isPipedInput, err := internal.IsPipedInput()
if err != nil {
log.Warnf("unable to determine if there is piped input: %+v", err)
isPipedInput = false
}
if len(args) == 0 && !isPipedInput {
// in the case that no arguments are given and there is no piped input we want to show the help text and return with a non-0 return code.
if err := cmd.Help(); err != nil {
return fmt.Errorf("unable to display help: %w", err)
}
return fmt.Errorf("an image/directory argument is required")
}
return cobra.MaximumNArgs(1)(cmd, args)
}
// hitSeverityThreshold indicates if there are any severities >= to the max allowable severity (which is optional)
func hitSeverityThreshold(thresholdSeverity *vulnerability.Severity, matches match.Matches, metadataProvider vulnerability.MetadataProvider) bool {
if thresholdSeverity != nil {
var maxDiscoveredSeverity vulnerability.Severity
for m := range matches.Enumerate() {
metadata, err := metadataProvider.GetMetadata(m.Vulnerability.ID, m.Vulnerability.Namespace)
if err != nil {
continue
}
severity := vulnerability.ParseSeverity(metadata.Severity)
if severity > maxDiscoveredSeverity {
maxDiscoveredSeverity = severity
}
}
if maxDiscoveredSeverity >= *thresholdSeverity {
return true
}
}
return false
}