Skip to content

Commit

Permalink
feat(flag): add exit-on-eosl option (#3423)
Browse files Browse the repository at this point in the history
Co-authored-by: knqyf263 <knqyf263@gmail.com>
  • Loading branch information
blueskyson and knqyf263 committed Feb 15, 2023
1 parent aa8e185 commit 32acd29
Show file tree
Hide file tree
Showing 8 changed files with 92 additions and 1 deletion.
1 change: 1 addition & 0 deletions docs/docs/references/cli/client.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Scan Flags
Report Flags
--dependency-tree show dependency origin tree (EXPERIMENTAL)
--exit-code int specify exit code when any security issues are found
--exit-on-eosl exit with the specified code when the os of image ends of service/life
-f, --format string format (table, json, sarif, template, cyclonedx, spdx, spdx-json, github, cosign-vuln) (default "table")
--ignore-policy string specify the Rego file path to evaluate each vulnerability
--ignorefile string specify .trivyignore file (default ".trivyignore")
Expand Down
1 change: 1 addition & 0 deletions docs/docs/references/cli/image.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ Scan Flags

Report Flags
--exit-code int specify exit code when any security issues are found
--exit-on-eosl exit with the specified code when the os of image ends of service/life
-f, --format string format (table, json, sarif, template, cyclonedx, spdx, spdx-json, github, cosign-vuln) (default "table")
--ignore-policy string specify the Rego file path to evaluate each vulnerability
--ignorefile string specify .trivyignore file (default ".trivyignore")
Expand Down
4 changes: 4 additions & 0 deletions docs/docs/references/customization/config-file.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ ignore-policy:
# Default is 0
exit-code: 0

# Same as '--exit-on-eosl'
# Default is false
exit-on-eosl: false

# Same as '--output'
# Default is empty (stdout)
output:
Expand Down
39 changes: 39 additions & 0 deletions docs/docs/vulnerability/examples/others.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,45 @@ $ trivy image --exit-code 0 --severity MEDIUM,HIGH ruby:2.4.0
$ trivy image --exit-code 1 --severity CRITICAL ruby:2.4.0
```

## Exit on EOSL
Sometimes you may surprisingly get 0 vulnerabilities in an old image:

- Enabling `--ignore-unfixed` option while all packages have no fixed versions.
- Scanning a rather outdated OS (e.g. Ubuntu 10.04).

An OS at the end of service/life (EOSL) usually gets into this situation, which is definitely full of vulnerabilities.
Use the `exit-on-eosl` option accompanied by `exit-code` option to exit with a non-zero code.
This flag is available with the following targets.

- Container images (`trivy image`)
- Virtual machine images (`trivy vm`)
- SBOM (`trivy sbom`)
- Root filesystem (`trivy rootfs`)

```
$ trivy image --exit-code 1 --exit-on-eosl testbeds/ubuntu:10.04
```

<details>
<summary>Result</summary>

```
2023-01-19T22:05:54.358+0800 WARN This OS version is no longer supported by the distribution: ubuntu 10.04
2023-01-19T22:05:54.358+0800 WARN The vulnerability detection may be insufficient because security updates are not provided
testbeds/ubuntu:10.04 (ubuntu 10.04)
====================================
Total: 0 (UNKNOWN: 0, LOW: 0, MEDIUM: 0, HIGH: 0, CRITICAL: 0)
```

</details>

This option is useful for CI/CD. The following example will fail when a critical vulnerability is found or the OS is EOSL:

```
$ ./trivy image --exit-code 1 --exit-on-eosl --severity CRITICAL alpine:3.16.3
```

## Reset
The `--reset` option removes all caches and database.
After this, it takes a long time as the vulnerability database needs to be rebuilt locally.
Expand Down
5 changes: 5 additions & 0 deletions pkg/commands/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@ func NewFilesystemCommand(globalFlags *flag.GlobalFlagGroup) *cobra.Command {
reportFlagGroup := flag.NewReportFlagGroup()
reportFlagGroup.ReportFormat = nil // TODO: support --report summary
reportFlagGroup.Compliance = nil // disable '--compliance'
reportFlagGroup.ExitOnEOSL = nil // disable '--exit-on-eosl'

fsFlags := &flag.Flags{
CacheFlagGroup: flag.NewCacheFlagGroup(),
Expand Down Expand Up @@ -402,6 +403,7 @@ func NewRepositoryCommand(globalFlags *flag.GlobalFlagGroup) *cobra.Command {
reportFlagGroup := flag.NewReportFlagGroup()
reportFlagGroup.ReportFormat = nil // TODO: support --report summary
reportFlagGroup.Compliance = nil // disable '--compliance'
reportFlagGroup.ExitOnEOSL = nil // disable '--exit-on-eosl'

repoFlags := &flag.Flags{
CacheFlagGroup: flag.NewCacheFlagGroup(),
Expand Down Expand Up @@ -549,6 +551,7 @@ func NewConfigCommand(globalFlags *flag.GlobalFlagGroup) *cobra.Command {
reportFlagGroup.ListAllPkgs = nil // disable '--list-all-pkgs'
reportFlagGroup.ReportFormat = nil // TODO: support --report summary
reportFlagGroup.Compliance = nil // disable '--compliance'
reportFlagGroup.ExitOnEOSL = nil // disable '--exit-on-eosl'

scanFlags := &flag.ScanFlagGroup{
// Enable only '--skip-dirs' and '--skip-files' and disable other flags
Expand Down Expand Up @@ -764,6 +767,7 @@ func NewKubernetesCommand(globalFlags *flag.GlobalFlagGroup) *cobra.Command {
compliance := flag.ComplianceFlag
compliance.Usage += fmt.Sprintf(" (%s,%s)", types.ComplianceK8sNsa, types.ComplianceK8sCIS)
reportFlagGroup.Compliance = &compliance // override usage as the accepted values differ for each subcommand.
reportFlagGroup.ExitOnEOSL = nil // disable '--exit-on-eosl'

k8sFlags := &flag.Flags{
CacheFlagGroup: flag.NewCacheFlagGroup(),
Expand Down Expand Up @@ -826,6 +830,7 @@ func NewAWSCommand(globalFlags *flag.GlobalFlagGroup) *cobra.Command {
compliance := flag.ComplianceFlag
compliance.Usage += fmt.Sprintf(" (%s, %s)", types.ComplianceAWSCIS12, types.ComplianceAWSCIS14)
reportFlagGroup.Compliance = &compliance // override usage as the accepted values differ for each subcommand.
reportFlagGroup.ExitOnEOSL = nil // disable '--exit-on-eosl'

awsFlags := &flag.Flags{
AWSFlagGroup: flag.NewAWSFlagGroup(),
Expand Down
7 changes: 7 additions & 0 deletions pkg/commands/artifact/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,7 @@ func Run(ctx context.Context, opts flag.Options, targetKind TargetKind) (err err
return xerrors.Errorf("report error: %w", err)
}

exitOnEosl(opts, report.Metadata)
Exit(opts, report.Results.Failed())

return nil
Expand Down Expand Up @@ -663,6 +664,12 @@ func Exit(opts flag.Options, failedResults bool) {
}
}

func exitOnEosl(opts flag.Options, m types.Metadata) {
if opts.ReportOptions.ExitOnEOSL && m.OS != nil && m.OS.Eosl {
Exit(opts, true)
}
}

func canonicalVersion(ver string) string {
if ver == devVersion {
return ver
Expand Down
19 changes: 18 additions & 1 deletion pkg/flag/report_flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ var (
Value: 0,
Usage: "specify exit code when any security issues are found",
}
ExitOnEOSLFlag = Flag{
Name: "exit-on-eosl",
ConfigName: "exit-on-eosl",
Value: false,
Usage: "exit with the specified code when the os of image ends of service/life",
}
OutputFlag = Flag{
Name: "output",
ConfigName: "output",
Expand Down Expand Up @@ -105,6 +111,7 @@ type ReportFlagGroup struct {
IgnoreFile *Flag
IgnorePolicy *Flag
ExitCode *Flag
ExitOnEOSL *Flag
Output *Flag
Severity *Flag
Compliance *Flag
Expand All @@ -118,6 +125,7 @@ type ReportOptions struct {
ListAllPkgs bool
IgnoreFile string
ExitCode int
ExitOnEOSL bool
IgnorePolicy string
Output io.Writer
Severities []dbTypes.Severity
Expand All @@ -134,6 +142,7 @@ func NewReportFlagGroup() *ReportFlagGroup {
IgnoreFile: &IgnoreFileFlag,
IgnorePolicy: &IgnorePolicyFlag,
ExitCode: &ExitCodeFlag,
ExitOnEOSL: &ExitOnEOSLFlag,
Output: &OutputFlag,
Severity: &SeverityFlag,
Compliance: &ComplianceFlag,
Expand All @@ -154,19 +163,26 @@ func (f *ReportFlagGroup) Flags() []*Flag {
f.IgnoreFile,
f.IgnorePolicy,
f.ExitCode,
f.ExitOnEOSL,
f.Output,
f.Severity,
f.Compliance,
}
}

func (f *ReportFlagGroup) ToOptions(out io.Writer) (ReportOptions, error) {
exitCode := getInt(f.ExitCode)
exitOnEOSL := getBool(f.ExitOnEOSL)
format := getString(f.Format)
template := getString(f.Template)
dependencyTree := getBool(f.DependencyTree)
listAllPkgs := getBool(f.ListAllPkgs)
output := getString(f.Output)

if exitOnEOSL && exitCode == 0 {
log.Logger.Warn("'--exit-on-eosl' is ignored because '--exit-code' is 0 or not specified. Use '--exit-on-eosl' option with non-zero '--exit-code' option.")
}

if format != "" && !slices.Contains(report.SupportedFormats, format) {
return ReportOptions{}, xerrors.Errorf("unknown format: %v", format)
}
Expand Down Expand Up @@ -223,7 +239,8 @@ func (f *ReportFlagGroup) ToOptions(out io.Writer) (ReportOptions, error) {
DependencyTree: dependencyTree,
ListAllPkgs: listAllPkgs,
IgnoreFile: getString(f.IgnoreFile),
ExitCode: getInt(f.ExitCode),
ExitCode: exitCode,
ExitOnEOSL: exitOnEOSL,
IgnorePolicy: getString(f.IgnorePolicy),
Output: out,
Severities: splitSeverity(getStringSlice(f.Severity)),
Expand Down
17 changes: 17 additions & 0 deletions pkg/flag/report_flags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ func TestReportFlagGroup_ToOptions(t *testing.T) {
ignoreUnfixed bool
ignoreFile string
exitCode int
exitOnEOSL bool
ignorePolicy string
output string
severities string
Expand Down Expand Up @@ -202,6 +203,20 @@ func TestReportFlagGroup_ToOptions(t *testing.T) {
Severities: []dbTypes.Severity{dbTypes.SeverityLow},
},
},
{
name: "invalid option combination: --exit-code 0 with --exit-on-eosl",
fields: fields{
exitCode: 0,
exitOnEOSL: true,
},
wantLogs: []string{
"'--exit-on-eosl' is ignored because '--exit-code' is 0 or not specified. Use '--exit-on-eosl' option with non-zero '--exit-code' option.",
},
want: flag.ReportOptions{
Output: os.Stdout,
ExitOnEOSL: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand All @@ -220,6 +235,7 @@ func TestReportFlagGroup_ToOptions(t *testing.T) {
viper.Set(flag.IgnoreUnfixedFlag.ConfigName, tt.fields.ignoreUnfixed)
viper.Set(flag.IgnorePolicyFlag.ConfigName, tt.fields.ignorePolicy)
viper.Set(flag.ExitCodeFlag.ConfigName, tt.fields.exitCode)
viper.Set(flag.ExitOnEOSLFlag.ConfigName, tt.fields.exitOnEOSL)
viper.Set(flag.OutputFlag.ConfigName, tt.fields.output)
viper.Set(flag.SeverityFlag.ConfigName, tt.fields.severities)
viper.Set(flag.ComplianceFlag.ConfigName, tt.fields.compliane)
Expand All @@ -233,6 +249,7 @@ func TestReportFlagGroup_ToOptions(t *testing.T) {
IgnoreFile: &flag.IgnoreFileFlag,
IgnorePolicy: &flag.IgnorePolicyFlag,
ExitCode: &flag.ExitCodeFlag,
ExitOnEOSL: &flag.ExitOnEOSLFlag,
Output: &flag.OutputFlag,
Severity: &flag.SeverityFlag,
Compliance: &flag.ComplianceFlag,
Expand Down

0 comments on commit 32acd29

Please sign in to comment.