Downloaded file name is `javadb.tar.gz` rather than `db.tar.gz`.
Also `--skip-update` is deprecated in favor of `--skip-db-update` and `--skip-java-db-update`.
* adding a fix for update-cache that was not applied on AWS scans.
* removing unneeded code
---------
Co-authored-by: Gio Rodriguez <giovanni.rodriguez@aquasec.com>
* Add test for filter with both duplicates and different package paths
* Add package path in key of uniqVulns map
* Add package path to the sorting logic
This commit bumps the go-dep-parser version. This revents Trivy from detecting vulnerabilities in Poetry dev-dependency, so the document is also updated.
Co-authored-by: DmitriyLewen <dmitriy.lewen@smartforce.io>
For images with single layer, the layer key was directly being used as merged cache key.
This was posing an issue of data override and any other image having the same layer could get incorrect data.
So, fixed:
1. Even for 1 layer - merged layer key hash will be calculated
2. We will not go with assumption that merged data will have only 1 pkgInfo
3. We are setting a SchemaVersion in blob being generated in ToBlobInfo
YAML files can also have the `.yml` file extension. So the helm config should take that into account.
Signed-off-by: Juan Antonio Osorio <juan.osoriorobles@eu.equinix.com>
While analyzing failure of the report schema validation i found URL looks like that: `https://ubuntu.com/security/notices/USN-5051-4 (regression only in trusty/esm)`. This causing gitlab to mark report as invalid. Patch provided just using first word of the url word.
* chore: add integration label and merge security label
* use the kind/security label for vulnerabilities
Co-authored-by: knqyf263 <knqyf263@gmail.com>
* fix: support for helm chart *.tar.gz
- add test to validate
Signed-off-by: Owen Rumney <owen.rumney@aquasec.com>
* fix: adding missing test tar
Signed-off-by: Owen Rumney <owen.rumney@aquasec.com>
* feat: adding helm support
- adding tests for helm analyzer
- add test for non helm tarball
- adding in-memory filesystem for helm
- handle multiple charts at a time
- check the size is smaller than arbitrary size of 200MB if a tarball
* fix(secrets): added '/' for file paths derived from image
* refactor(secrets): used input.Dir to find image scan
* test(secrets): added path to image-config.yaml
* fix(k8s): summary report when when only vulns exit
Signed-off-by: Jose Donizetti <jdbjunior@gmail.com>
* fix(k8s): return error for not supported report
Signed-off-by: Jose Donizetti <jdbjunior@gmail.com>
* test(k8s): add tests for report Failed()
Signed-off-by: Jose Donizetti <jdbjunior@gmail.com>
* refactor: improve error message
Signed-off-by: Jose Donizetti <jdbjunior@gmail.com>
* feat(k8s): Add report flag for summary
* chore: add headings to the severity columns
* chore: make the default output of k8s summary table
Signed-off-by: Owen Rumney <owen.rumney@aquasec.com>
This is being mitigated in defsec as well to prevent results with no
filename getting through to fanal
Signed-off-by: Owen Rumney <owen.rumney@aquasec.com>
The Label Schema Convention has been deprecated in favor of the OCI
image spec.
Update the gorelease config to use the new replacement fields.
This is not considered a breaking change, as it only touches metadata
and the Label Schema Convention is deprecated for over two years (March
2019).
Most fields only need to be renamed. `org.label-schema.schema-version`
could be removed without replacement.
`org.opencontainers.image.documentation` was added to link to the
Github page documentation in the exact version.
`org.opencontainers.image.url` was added pointing to the Aqua Security
product page of trivy.
Further labels were considered but not added (unclear purpose or value).
Find the `*.proto` files and run in a `for loop` to run `protoc`
for each file in a separated command. If fail, `|| exit` will exit
with the returned error.
The POSIX standard specifies that the return status of `find` is 0
unless an error occurred while traversing the directories;
the return status of executed commands doesn't enter into it.
To overcome this limitation, the `-exec ... +` pattern could be used
From the docs (https://man7.org/linux/man-pages/man1/find.1.html):
"If any invocation with the `+' form returns a non-zero
value as exit status, then find returns a non-zero exit
status."
But as well, "This variant of the -exec action runs the specified command
on the selected files, but the command line is built by appending each selected
file name at the end;"
Unfortunately, at the moment `protoc-gen-twirp` plugin doesn't
support multiple files from different packages when the `go_package` option
is explicitly mentioned.
https://github.com/twitchtv/twirp/blob/main/protoc-gen-twirp/generator.go#L181-L185
Signed-off-by: Yuval Goldberg <yuvigoldi@gmail.com>
- rework some of the iac tests to be more flexible to change
- update the scanner to use the moved parser
- everything is now in defsec now for CF parsing, scanning and testing
- new version of cfsec brought in with latest fanal
- fixes issue where cfsec treats files as CloudFormation when they
arent
- fixes issuee where invalid content errors are surfaced to Trivy
- Gets addition of service and provider on the IaC results - this is not
visible to others
* chore(release): add ubuntu older versions to deploy script
`ubuntu-distro-info --supported` returns only versions: `bionic`, `focal`, `hirsute`, `impish` and `jammy`.
`ubuntu-distro-info --supported-esm` returns another versions: `trusty`, `xenial`, `bionic`, `focal` and `jammy`.
for the release script we should use the union of these sets.
Fixes#1194
* change `uniq` command to `-u` parameter
* feat(iac): Adding resource and Line data
- adding line in file information to the misconfiguration result
- updating tfsec and cfsec versions to provide this additional info
* Add usage of IaC metadata
* update the fanal version
* feature(iac): Add location and resource to Results
- add the iac resource and line in file information for tfsec and cfsec
- update the version of tfsec and cfsec
The current install.sh script logs all messages to stderr via ```echoerr()``` function. Since godownloader is no longer maintained, it seems reasonable to update install.sh here.
* Add new networking API features to Ingress
This PR adds `v1` of the networking API introduced with k8s 1.19.
It also adds the new field `ingressClassName` introduced with k8s 1.18.
Fixes#1261
* Also query for the Kind in the capabilities
Signed-off-by: Christian Zunker <christian.zunker@codecentric.cloud>
The io/ioutil package has been deprecated as of Go 1.16, see
https://golang.org/doc/go1.16#ioutil. This commit replaces the existing
io/ioutil functions with their new definitions in io and os packages.
Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
* Made below changes
1. To avoid confusion, changed the layer(blobinfo) size to uncompressed size
2. Added v1.configfile as return type of inspect method
Co-authored-by: Teppei Fukuda <knqyf263@gmail.com>
* fix(oracle): handle advisories contain ksplice versions
Improve a handling of advisories contain ksplice versions:
* when one of them doesn't have ksplice, we'll also skip it
* extract kspliceX and compare it with kspliceY in advisories
* if kspliceX and kspliceY are different, we will skip the advisory.
Fixes#1205
* fix(oracle): handle advisories contain ksplice versions
simplify code and remove duplicated tests
Fixes#1205
* run go fmt
There is a closure inside a function for Action field: variable p always refers on the last plugin.
solution: redefine variable inside the for loop.
Fixes#1086
* Capture license information for apk packages
* changed order or license info in package struct
* Remove space replacement with comma for license info
SLE 15.3 is about to be released and will be maintained until
6 months after 15.4. this allows us to guess the 15 SP2 EOL date,
so updating that as well.
* Update Fanal library reference
This commit updates Fanal library version to latest which
includes support for Google artifact repository.
* chore(mod): tidy
Co-authored-by: knqyf263 <knqyf263@gmail.com>
* Added support for list all packages flag in client
This commit is to support --list-all_pkgs argument in client command
Example command: trivy -d client --list-all-pkgs --remote http://localhost:8080 ubuntu:18.04.
* Updated argument in client.md
* Fixed all format issues
* feat: Support Google artifact registry
This commit adds the capability to scan images from Google artifact
registry(GAR). GAR domains were earlier rejected by Trivy e.g.
europe-west3-docker.pkg.dev etc. With this change, we will treat domain
ending with 'docker.pkg.dev' as GAR domain and use gcloud sdk to fetch
credentials from provided file or credstore.
* refactor: rename GCR to Registry
Co-authored-by: knqyf263 <knqyf263@gmail.com>
* Add uncompressed layer size
This commit will help in getting uncompressed layer sizes. Can sum up these layer sizes to get the actual image size
* Removed unnecessary exception
* refactor
Co-authored-by: knqyf263 <knqyf263@gmail.com>
* Add gitlab codequality template
* add unit test for gitlab codequality template
* update line endings to msdos (\r\n) from unix
* update gitlab docs for codeclimate template
* fix(go): if patchedVersion is empty mark it as vulnerable
* fix(go): skip checking for vulnerable version if empty
* fix(go): refactored empty check at start of match
* fix(go): added unit test for empty patched/vulnerable version
* Add HIGH severity to Trivy command in GitLab CI example to match comment
* Change comment to accurately reflect Trivy command that fails only on CRITICAL vulnerabilities
* feat(GoBinary) support gobinary and add test
* update(modules) update go-dep-parser
* test(gobinary) update test
* fix(library): return nil with empty result
* test(library): add tests
* refactor: group imports
* chore: update .gitignore
* Update README.md
* refactor(gobinary): update an error
* chore(ci): bunp up Go to 1.16
Co-authored-by: knqyf263 <knqyf263@gmail.com>
* Update SARIF repot template
* Update test data sarif.golden
* Fix golangci-lint issue
* Add test cases
* Address review feedbacks
* Inline value in assert statement
* Fix location Uri format issue
* Update install docs to make commands consistent
Removed `$` prefixes from code blocks to make them constant across the page and make the commands copypasta-able.
* Revert change on docs which need manual changes
* Minimal WIP cross platform build with goreleaser
* Add Docker manifest, update docker image tags
* Update GH release workflow
* Comment out ECR image repo and RPM/DEB generation
* Enable and set up Docker Buildx for multi-platform builds
Also add caching of Go modules
* Add Docker Buildx support, re-enable parent repo workflows
* Add Docker Buildx support for multi-arch image builds
* Added Docker Buildx setup into `build-test` job of `test` workflow
Otherwise the `test` workflow will fail.
Also updated `setup-go` GH action to latest version, v2, per request
of @krol3
* feat(config): support HCL1 files
* feat(config): support HCL2 files
* feat(hcl): add Version()
* feat(config): support HCL files
- combine HCL2.0 and HCL1.0 parsing, checking for conformation to HCL2.0
spec first
- checks for HCL1.0 conformation if content does not comply with HCL2.0
spec
- parsing returns an error only if file content does not
comply with BOTH HCL2.0 and HCL1.0
* add Type() test
Co-authored-by: knqyf263 <knqyf263@gmail.com>
* mkdocs: add top level nav
* mkdocs: add installation nav
* mkdocs: add quick-start nav
* mkdocs: add examples nav
* mkdocs: add CI nav
* mkdocs: add vuln-detection nav
* mkdocs: add comparison nav
* mkdocs: add usage nav
* mkdocs: add migration nav
* mkdocs: add FAQ nav
* mkdocs: add mkdocs.yml
* mkdocs: add github workflow
* docs: update documents
* fix links
* chore(ci): use ORG_GITHUB_TOKEN
* chore(mkdocs): use mike
* chore(ci): support dev
* chore(ci): documentation test
Co-authored-by: knqyf263 <knqyf263@gmail.com>
* refactor(scan): rename image to artifact
* refactor(scan): trim version suffixes for debug info
* chore(mod): update fanal
* refactor: reduce complexity
* chore(mod): update fanal
* refactor(scan): early return
* feat(config): support Dockerfile
* update namings and add Type() test
* only accepts dockerfile as ext/base name
* simplify dockerfile check
* add test case
* Add sprig template function to template writer
* gofmt corrected
* includes corrected
* GoFMT corrected
* Added accidentically removed template functions
* Corrected use of template-file
* Add sprig test
* Add short example for sprig.
As suggested by the go-redis client, parse the url to get the config.
This will fix problems, when the url contains a username and/or password.
Fixes#798
Signed-off-by: Christian Zunker <christian.zunker@codecentric.cloud>
* Fix errors in SARIF format
* Fix one golden file for integration tests
* Fix golden file
* Fix golden again :>
* Update sarif.tpl
* Update alpine-310.sarif.golden
* Remove global flags from subcommands
If the global flags are added to the subcommand as well as being used
globally, their value will be overwritten when the arguments for the
subcommand are parsed. This leads to the value passed to the flag at the
global position being lost.
* Update readme
You can now specify redis as caching as backend.
The default is still the filesystem.
In case redis is added as caching backend, the cache-dir is still
used for the vulnerability database.
Fixes#781
Signed-off-by: Christian Zunker <christian.zunker@codecentric.cloud>
* Initial nuget advisory detector code.
Signed-off-by: Johannes Tegnér <johannes@jitesoft.com>
* Added nuget package to scan.go
Signed-off-by: Johannes Tegnér <johannes@jitesoft.com>
* Removed nuget advisory file and instead added csharp/nuget as a driver in driver.go.
Signed-off-by: Johannes Tegnér <johannes@jitesoft.com>
* Removed nuget package from driver. Added ghasnuget as a source in vulnerability.go
Signed-off-by: Johannes Tegnér <johannes@jitesoft.com>
* Updated nuget driver to use correct name and to initialize with the new generic scanner.
Signed-off-by: Johannes Tegnér <johannes@jitesoft.com>
* refactor: cut out to a separate method
* chore(mod): update trivy-db
* fix(driver): add a general driver
* test(ghsa): add nuget
* chore: update README
Co-authored-by: knqyf263 <knqyf263@gmail.com>
* feat(cache): support Redis
* chore(mod): update
* feat(main): support Redis
* test: update error messages according to different errors on GitHub Actions
* feat(redis): add prefix
* fix an error
Co-authored-by: Daniel Pacak <pacak.daniel@gmail.com>
* fix an error
Co-authored-by: Daniel Pacak <pacak.daniel@gmail.com>
* fix(main): defer close
* test(redis): fix error messages
* test(redis): count current connections
Co-authored-by: Daniel Pacak <pacak.daniel@gmail.com>
* test(redis): use structs instead of string literals
Co-authored-by: Daniel Pacak <pacak.daniel@gmail.com>
* (fix): Make the table output less wide.
Currently the table outupt can be as long as 200 characters wide in some
images like nginx:1.16
This PR merges the Title and the URL columns to shorten it.
With this change the longest column has reduced from 200 -> 162 (-19%).
Signed-off-by: Simarpreet Singh <simar@linux.com>
* (fix): Remove Debian TEMP-* links.
These links are quite wide. Removing them makes it 200 -> 143 (-28.5%) shorter for table output.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* Revert "(fix): Remove Debian TEMP-* links."
This reverts commit 228540f7c3.
without that you get this arning:
WARN This OS version is not on the EOL list: suse linux enterprise server 15.2
which is actually misleading because 15.2 is the most current release,
we just don't know when it ends. we can however assume that it runs
for at least another year.
Signed-off-by: Dirk Mueller <dirk@dmllr.de>
Signed-off-by: Dirk Mueller <dmueller@suse.com>
* Warn when a user attempts to use trivy without a detectable lockfile
* Update pkg/scanner/local/scan.go
Co-authored-by: Teppei Fukuda <knqyf263@gmail.com>
Co-authored-by: Teppei Fukuda <knqyf263@gmail.com>
* Skip downloading DB if a remote DB is not updated
* Apply suggestions from code review
Co-authored-by: Teppei Fukuda <knqyf263@gmail.com>
* update github.com/aquasecurity/trivy-db version
* fix lint
* Use UTC datetime
* display DownloadedAt info in debug log
* refactor(db): merge isLatestDB into isNewDB
Co-authored-by: Teppei Fukuda <knqyf263@gmail.com>
* add linter supports
* add only minor version
* use latest version
* Fix println with format issue
* Fix test
* Fix tests
* For slice with unknown length, preallocating the array
* fix code-coverage
* Removed linter rules
* Reverting linter fixes, adding TODO for later
* Ignore linter error for import
* Remove another err var.
* Ignore shadow error
* Fixes
* Fix issue
* Add back goimports local-prefixes
* Update local prefixes
* Removed extra spaces and merge the imports
* more refactoring
* Update photon.go
Co-authored-by: Teppei Fukuda <knqyf263@gmail.com>
* Add contrib/ to the release chain for Docker
Add the complete contrib/ folder to the release chain
* Include all template files to the tar.gz archives
This improves the installation step in `.gitlab-ci.yml`.
- Removes unnecessary installation and use of `curl` (replaces it with `wget`)
- Removes storing the intermediate file by using a pipe to `tar`
Before this change, only a subset of templates were included in the docker image.
Now all templates which are part of the git repo will be included when the docker image will be build, a future commit for every new template is not needed anymore
Condition:- Specify an image name and tag ":" separated.
If correct image name and tag is specified ":" separated, image with given tag will be return otherwise first one will be return
* Added test and support of ASFF template
* Improve test coverage
* Fixed/Improved tests
* Removed extra space
* Added NVD score/vectors, Added logic to trim description due to file size restriction
* Included quotations around AccountID
* sarif: Tweak format for GitHub UI
Signed-off-by: Simarpreet Singh <simar@linux.com>
* sarif: Make sarif easier to use with a default template
This will help us use Trivy in places like GitHub Actions where
we cannot specify a template as input.
$ trivy image --format=sarif alpine:3.10.1
Signed-off-by: Simarpreet Singh <simar@linux.com>
* Revert "sarif: Make sarif easier to use with a default template"
This reverts commit 5b5d1c8f7d.
* .dockerignore: Add un-needed large directories
Signed-off-by: Simarpreet Singh <simar@linux.com>
* Dockerfile: Add sarif template.
This will let users run and save the output through the docker image
Example:
```
docker run --rm -it -v $(pwd):/tmp aquasec/trivy:latest image -f template --template "@contrib/sarif.tpl" --output="/tmp/sarif.test" alpine:3.10.2
```
Signed-off-by: Simarpreet Singh <simar@linux.com>
* Fixed case when pre-release is in suffix
* moved regex to global scope
* removed not needed code
* Update error to debug
* skip constraint when empty
* Implemented ruby comparison version check.
* Added semver package to validate and check version
* Added more tests
* Replaced go-version with semver
* Removing go-version from dependency
* Added check for ruby gem version format
* Updated semver model and patch rewrite process
* Refactoring
* fix: Due read after write consistency in S3 missingLayers called the actual object that created cache 403 response
This change creating index file for each object so missingLayers will not hit object that not exist.
* fix comments error description
Co-authored-by: oranmoshai <oran.moshai@aquasec.com>
* chore(README): prepare for v0.9.0
* chore(README): replace 'artifacts' with 'containers and other artifacts'
* chore: more detail for filesystem scan
Co-authored-by: Liz Rice <liz@lizrice.com>
* chore: more detail for embedding Trivy in the Dockerfile
Co-authored-by: Liz Rice <liz@lizrice.com>
* Update README.md
Co-authored-by: Liz Rice <liz@lizrice.com>
* Update README.md
Co-authored-by: Liz Rice <liz@lizrice.com>
* chore(README): add a new line
* chore(README): revert TOC and add blog links
* chore(README): add Microscanner link
Co-authored-by: Liz Rice <liz@lizrice.com>
* test(integration): move to the test directory
* chore: update fixtures path
* test: put common test images under the test directory
* chore(Makefile): rename
* feat: support local filesystem and remote git repository [PART 1] (fanal#109)
* feat(walker): add tar/fs walker
* fs_test: Add test names
Signed-off-by: Simarpreet Singh <simar@linux.com>
* walk_test: Add Test_isIgnored
Signed-off-by: Simarpreet Singh <simar@linux.com>
* feat: support local filesystem and remote git repository [PART 2] (fanal#110)
* refactor(analyzer): merge OSAnalyzer, PkgAnalyze, LibAnalyzer into
Analyzer
* test: comment out temporarily
* fix(amazon): check the length
* fix(analyzer): make AnalysisResult a reference
* library/analyzer: Refactor library analyzer code.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* feat: support local filesystem and remote git repository [PART 3] (fanal#111)
* refactor(image): move directory
* feat(applier): add applier
* fix(apk): replace extractor with applier
* test: comment out temporarily
* feat: support local filesystem and remote git repository [PART 4] (fanal#112)
* feat(artifact): add image, local and remote artifact
* image_test: Rename test field to use new convention
Signed-off-by: Simarpreet Singh <simar@linux.com>
* image_test: Add a test for put artifact failure
Signed-off-by: Simarpreet Singh <simar@linux.com>
* refactor(remote): remove unnecessary files for unit test
* feat: support local filesystem and remote git repository [PART 5] (fanal#113)
* test(integration): fix tests
* feat: support local filesystem and remote git repository [PART 6] (fanal#114)
* feat(main): add sub commands
* refactor(types): remove unused type
* chore(mod): update
* test(artifact): add mock
* fix(analyzer): redhat must be replaced with oracle
* fix(analyzer): debian must be replaced with ubuntu
* fix(fs): display dir when hostname is empty
Co-authored-by: Simarpreet Singh <simar@linux.com>
Co-authored-by: Simarpreet Singh <simar@linux.com>
* fix: make AnalysisResult a reference
Co-authored-by: Simarpreet Singh <simar@linux.com>
* refactor(walker): fix comment
Co-authored-by: Simarpreet Singh <simar@linux.com>
Co-authored-by: Simarpreet Singh <simar@linux.com>
Co-authored-by: Simarpreet Singh <simar@linux.com>
* vulnerability: Add CVSS Vectors to JSON output.
Now Trivy will display the CVSS Vectors presented by various
vendors as part of the JSON output. This can be seen as follows:
```
{
"VulnerabilityID": "CVE-2019-9923",
"PkgName": "tar",
"InstalledVersion": "1.30+dfsg-6",
"Layer": {
"Digest": "sha256:90fe46dd819953eb995f9cc9c326130abe9dd0b3993a998e12c01d0218a0b831",
"DiffID": "sha256:e40d297cf5f89a9822af4c2f63caa2f2085d5aa188137506918e603774b083cb"
},
"SeveritySource": "debian",
"Title": "tar: null-pointer dereference in pax_decode_header in sparse.c",
"Description": "pax_decode_header in sparse.c in GNU Tar before 1.32 had a NULL pointer dereference when parsing certain archives that have malformed extended headers.",
"Severity": "LOW",
"VendorVectors": {
"nvd": {
"v2": "AV:N/AC:L/Au:N/C:N/I:N/A:P",
"v3": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H"
},
"redhat": {
"v3": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:L"
}
},
"References": [
"http://git.savannah.gnu.org/cgit/tar.git/commit/?id=cb07844454d8cc9fb21f53ace75975f91185a120",
"http://lists.opensuse.org/opensuse-security-announce/2019-04/msg00077.html",
"http://savannah.gnu.org/bugs/?55369",
"https://bugs.launchpad.net/ubuntu/+source/tar/+bug/1810241"
]
},
```
Signed-off-by: Simarpreet Singh <simar@linux.com>
* mod: Update to latest master of trivy-db
Signed-off-by: Simarpreet Singh <simar@linux.com>
* vulnerability_test: Fix tests for new struct type
Signed-off-by: Simarpreet Singh <simar@linux.com>
* Add S3 support for layer caching this will allow to save image results on managed persistent object store
* Working on PR comments
Co-authored-by: oranmoshai <oran.moshai@aquasec.com>
* fix(standalone): add defer to close databases
* test(client/server): launch a server only once
* test(docker_engine): remove the duplicated case
* test(docker_engine): copy a database only once
* test(standalone): copy a database only once
* test(server): fix tests according to updated mock
* chore(mod): update
* chore(ci): add integration tests to GitHub Actions
* chore(ci): bump up Go to 1.14
* chore(ci): remove integration tests from CircleCI
* chore(ci): add name
* chore(ci): add new lines
* contrib/gitlab.tpl: Add new id field
https://docs.gitlab.com/ee/user/application_security/container_scanning/#reports-json-format
vulnerabilities[].id Unique identifier of the vulnerability.
vulnerabilities[].cve (DEPRECATED - use vulnerabilities[].id instead) A fingerprint string value that represents a concrete occurrence of the vulnerability. It’s used to determine whether two vulnerability occurrences are same or different. May not be 100% accurate. This is NOT a CVE.
Signed-off-by: Manuel Rüger <manuel@rueg.eu>
* Update integration test for Gitlab
Co-authored-by: Teppei Fukuda <knqyf263@gmail.com>
* analyzer: Send back package and apps info for unknown OS if found.
We should send back package and apps info if found even
in the case of an unknown OS. Example Dockerfile:
```
$ cat Dockerfile
FROM hello-world
ADD https://raw.githubusercontent.com/aquasecurity/trivy-ci-test/master/Cargo.lock .
```
Should say ErrUnknownOS but still scan the Cargo vulns.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* fix(analyzer): send back package and apps info even if there is no package found
* fix(main): handle specific errors
Co-authored-by: knqyf263 <knqyf263@gmail.com>
* feat(image): support OCI Image Format
* refactor: rename NewDockerArchiveImage to NewArchiveImage
* test: rename TestNewDockerArchiveImage to TestNewArchiveImage
* fix: introduce go-multierror
* image: add more sad paths for tryOCI func
Signed-off-by: Simarpreet Singh <simar@linux.com>
* test(image): add more test case
Co-authored-by: Simarpreet Singh <simar@linux.com>
* wip: Add a failing test to demo severity override
Signed-off-by: Simarpreet Singh <simar@linux.com>
* scan.go: Return osFound for use in determining vendor.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* pkg: Fix ScanImage return in case an OSFound
Signed-off-by: Simarpreet Singh <simar@linux.com>
* scan_test: Include a package-lock.json for happy path
Signed-off-by: Simarpreet Singh <simar@linux.com>
* wip: Add a test to include various reportResult types
Signed-off-by: Simarpreet Singh <simar@linux.com>
* Makefile: Add a target to generate mocks.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* vulnerability: Pass reportType as argument for FillInfo.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* vulnerability: Add other types of vulnerabilities.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* integration: Update golden files.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* ospkg: Fix FillInfo for ospkg/server
Signed-off-by: Simarpreet Singh <simar@linux.com>
* rpc: Add os.Family type to Response.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* vulnerability_test.go: Add case where no vendor severity exists.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* vulnerability: Fallback to NVD if it exists.
Also add tests for other cases.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* rpc: Fix a few sites with reportType info and tests.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* vulnerability: Remove VendorSeverity from displayed results
Signed-off-by: Simarpreet Singh <simar@linux.com>
* vulnerability: Add vulnerability source information.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* vulnerability: Add VendorSeverity logic for lightDB as well.
This commit also makes FillInfo logic common to both light and full DBs.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* remove some crufty TODOs
Signed-off-by: Simarpreet Singh <simar@linux.com>
* vulnerability_test: Add a case for light db for documentation purposes
Signed-off-by: Simarpreet Singh <simar@linux.com>
* mod: update trivy-db to point to master
Signed-off-by: Simarpreet Singh <simar@linux.com>
* scan_test: Remove cruft and bring back test cases
Signed-off-by: Simarpreet Singh <simar@linux.com>
* scan_test: Add pkg Type to mock return
Signed-off-by: Simarpreet Singh <simar@linux.com>
* vulnerability: reorder err check after err
Signed-off-by: Simarpreet Singh <simar@linux.com>
* client_test: Fix import ordering
Signed-off-by: Simarpreet Singh <simar@linux.com>
* convert.go: Use result.Type
Signed-off-by: Simarpreet Singh <simar@linux.com>
* convert: Use result.Type and simplify ConvertFromRpcResults signature
Signed-off-by: Simarpreet Singh <simar@linux.com>
* vulnerability: Refactor calls to getVendorSeverity
Signed-off-by: Simarpreet Singh <simar@linux.com>
* integration: Remove centos-7-critical.json.golden
There's no critical vulnerability in CentOS 7 anymore.
In addition this test was not adding any value that is already
not covered by existing tests cases.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* rpc: Include severity source in tests.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* integration: Update test db to include VendorSeverity.
Test DB is now a snapshot of full database from trivy-db.
Also update golden files to include SeveritySource.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* vulnerability: Make centos7 use RHEL vendor severities
Signed-off-by: Simarpreet Singh <simar@linux.com>
* refactor: wrap errors
* feat(db): add the metadata file
* test(db): re-generate mocks
* fix(app): read metadata from the file in showVersion
* fix: open the database after downloading it
* fix(operation): use UpdateMetadata
* chore(mod): update dependency
* test(integration): fix tests
* fix(conf): rename TRIVY_NONSSL to TRIVY_NON_SSL
After trying to run trivy using CircleCI based on the sample configuration and failing, I want to suggest the following updates:
* `docker:18.09-git` no longer exists and causes workflow to fail, replaced with `stable-git` instead.
* added `setup_remote_docker` or else the docker commands fail in the rest of the execution, as per https://circleci.com/docs/2.0/building-docker-images/#overview
Co-authored-by: Teppei Fukuda <knqyf263@gmail.com>
* app: Show just version if DB is missing
Signed-off-by: Simarpreet Singh <simar@linux.com>
* app: Dont panic if cache-dir is bogus
Signed-off-by: Simarpreet Singh <simar@linux.com>
* app: DRY up logic for showVersion
Signed-off-by: Simarpreet Singh <simar@linux.com>
* app: Expose Trivy and VulnDB version through --version
Signed-off-by: Simarpreet Singh <simar@linux.com>
* pkg: Use time.Time as value not reference.
Based on: 64db180151
Signed-off-by: Simarpreet Singh <simar@linux.com>
* app: Use various formatted outputs
Signed-off-by: Simarpreet Singh <simar@linux.com>
* app: Take value of --cache-dir for cacheDir
Signed-off-by: Simarpreet Singh <simar@linux.com>
* app: Refactor and test showVersion
Signed-off-by: Simarpreet Singh <simar@linux.com>
* library: lighten names by remove version suffix
Signed-off-by: Simarpreet Singh <simar@linux.com>
* app: Show types and add parity of table and JSON
Signed-off-by: Simarpreet Singh <simar@linux.com>
* app: Switch to show using UTC time
Signed-off-by: Simarpreet Singh <simar@linux.com>
* mod: Update to latest trivy-db master.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* app: Use c.App.Writer for os.Stdout
Signed-off-by: Simarpreet Singh <simar@linux.com>
* app: Replace table output with docker version style output
Signed-off-by: Simarpreet Singh <simar@linux.com>
* app: Fix output to show as "Version" for Trivy version.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* app: Move VersionInfo struct out to app.go
Signed-off-by: Simarpreet Singh <simar@linux.com>
* feat(extractor): switch to layer ID of origin layer
* integration: update golden file for vuln-image
This file was updated during a COVID-19 crisis.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* test(docker): sort applications
* test(docker): fix order
Co-authored-by: Simarpreet Singh <simar@linux.com>
* analyzer: Include layerID as part of LayerInfo
Signed-off-by: Simarpreet Singh <simar@linux.com>
* Add LayerID to Package struct
Signed-off-by: Simarpreet Singh <simar@linux.com>
* analyzer: Remove ID from returned layerInfo
Signed-off-by: Simarpreet Singh <simar@linux.com>
* analyzer: Handle missing layer.ID from cached layer
Signed-off-by: Simarpreet Singh <simar@linux.com>
* extractor/docker: Cleanup logic to avoid extra slice usage
Signed-off-by: Simarpreet Singh <simar@linux.com>
* integration: Fix golden files to include LayerID
Signed-off-by: Simarpreet Singh <simar@linux.com>
* analyzer: Remove condition for adding layer.ID
Signed-off-by: Simarpreet Singh <simar@linux.com>
* types: Introduce types.LibraryInfo
Signed-off-by: Simarpreet Singh <simar@linux.com>
* docker: Add LayerID to each LibraryInfo
Signed-off-by: Simarpreet Singh <simar@linux.com>
* .github/bench: Bump up docker version
Signed-off-by: Simarpreet Singh <simar@linux.com>
* intergration/perf: Remove other OSes for the timebeing.
Looks like Github CI is running out of space while running
other tests. Until we find a better solution we need to comment
out bigger OSes.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* fix(image): call Close() via cleanup funcion
* refactor(type): add omitempty
* analyzer: Change to types.LibraryInfo in analzyer.go
Signed-off-by: Simarpreet Singh <simar@linux.com>
* wip: add CleanupDockerExtractorFn for cleanup
Signed-off-by: Simarpreet Singh <simar@linux.com>
* refactor(analyzer): remove un-needed function
* test(cache): comment in
* Revert "wip: add CleanupDockerExtractorFn for cleanup"
This reverts commit dabfae104bf6d63492823c6c3eb94175d26eabad.
* Revert ".github/bench: Bump up docker version"
This reverts commit b982c46861e1cc0851d53621c0e68ac40918d755.
* refactor(analyzer): sort imports
* test(cache): remove debug code
* test(cache): format
* chore(image): remove debug code
Co-authored-by: Teppei Fukuda <knqyf263@gmail.com>
* refactor(docker_conf): rename and remove unnecessary options
* feat(rpc): define new API
* fix(cli): change default timeout
* fix(import): fix package names
* refactor(vulnerability): remove old mock
* refactor(utils): remove un-needed functions
* feat(cache): implement cache communicating with a server
* refactor(scan): separate scan function as local scanner
* test(scanner): add tests for ScanImage
* refactor(scan): remove unused options
* test(vulnerability): generate mock
* refactor(server): split a file
* feat(server): implement new RPC server
* feat(client): implement new RPC client
* fix(cache): use new cache interface
* fix(standalone): use new scanner
* fix(client): use new scanner
* fix(server): pass cache
* test(integration): make sure an error is not nil before calling the method
* fix(mod): update dependencies
* test(integration): ensure the image load finishes
* feat(docker): support DOCKER_HOST and DOCKER_CERT_PATH
* chore(mod): update dependencies
* refactor(rpc): remove old client
* feat(server): support old API for backward compatibility
* fix(server): check a schema version of JSON cache
* fix(rpc): add a version to packages
* feat(rpc): add PutImage
* test: rename expectations
* refactor(cache): rename LayerCache to ImageCache
* refactor: rename ImageInfo to ImageReference
* fix(applier): pass image_id to ApplyLayer
* feat(cache): handle image cache
* chore(mod): update dependencies
* refactor(server): pass only config
* feat(cli): add -removed-pkgs option
* refactor(err): wrap errors
* test: cli: append warning when --template option is ignored
to avoid --template is silently ignored when --format <table|json>
or no --format is passed.
Signed-off-by: Takuya Noguchi <takninnovationresearch@gmail.com>
* cli: append warning when --template option is ignored
to avoid --template is silently ignored when --format <table|json>
or no --format is passed.
Signed-off-by: Takuya Noguchi <takninnovationresearch@gmail.com>
* test: cli: append warning when --format template is ignored
when --template is not specified
Signed-off-by: Takuya Noguchi <takninnovationresearch@gmail.com>
* cli: append warning when --format template is ignored
when --template is not specified
Signed-off-by: Takuya Noguchi <takninnovationresearch@gmail.com>
Co-authored-by: Teppei Fukuda <knqyf263@gmail.com>
* integration: Add a test to use fanal as a library
Signed-off-by: Simarpreet Singh <simar@linux.com>
* integration: Table driven library_tests
Signed-off-by: Simarpreet Singh <simar@linux.com>
* integration: Add even more OSes to the docker mode test
Signed-off-by: Simarpreet Singh <simar@linux.com>
* library_test: run tests in parallel
Signed-off-by: Simarpreet Singh <simar@linux.com>
* .git: Update gitignore with trivy images dir
Signed-off-by: Simarpreet Singh <simar@linux.com>
* library_test: add golden files for packages
Signed-off-by: Simarpreet Singh <simar@linux.com>
* library_test: Run all tests in parallel
Signed-off-by: Simarpreet Singh <simar@linux.com>
* library_test: Refactor check logic to run twice.
Once for no cache, once with cache.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* library_test: Fix cache invocation
Signed-off-by: Simarpreet Singh <simar@linux.com>
* integration: Add a more comprehensive image for library_test
Signed-off-by: Simarpreet Singh <simar@linux.com>
* library_test: Introduce anon struct type
Signed-off-by: Simarpreet Singh <simar@linux.com>
* travis: add make test-integration
Signed-off-by: Simarpreet Singh <simar@linux.com>
* travis: Upgrade docker version
Signed-off-by: Simarpreet Singh <simar@linux.com>
* feat(client): retry HTTP request when getting an unavailable error
* fix(integration-test): use a snapshot database for Docker mode (#352)
* fix(integration): add a binary name
The first argument is used for the program name. --skip-update was
ignored.
* fix(integration): use a snapshot database
After a new vulnerability is found, this test fails
* chore(integration): add t.Run
* refactor(client): functionalize common processes
* refactor(client): remove unused const
* fix(integration): add a binary name
The first argument is used for the program name. --skip-update was
ignored.
* fix(integration): use a snapshot database
After a new vulnerability is found, this test fails
* chore(integration): add t.Run
* chore(mod): update dependencies
* fix(scanner): make scanner take a cache client as the argument
* refactor: sort imports
* refactor(cache): create a struct to clear cache
* fix(cache): use a struct to clear cache
* fix(wire): update constructor to take cache struct
* fix(cache): use the constructor generated by wire
* docs(cli): update the option description
* fix(cache): use the cache struct
* fix(cache): split Reset into ClearDB and ClearImages
* fix(github): return db size
* fix(github_mock): add size
* feat(indicator): add progress bar
* refactor(config): remove global Quiet
* fix(db): take progress bar as an argument
* fix(progress): inject progress bar
Instead of using tomoyamachi's fork we can now use the vanilla upstream
package genuinetools/reg. This package gets better maintenance and is
the same as aquasecurity/fanal uses.
Signed-off-by: Jakub Bielecki <jakub.bielecki@codilime.com>
* change mod genuinetools/reg to vanilla
Instead of using tomoyamachi's fork we can now use the vanilla upstream
package genuinetools/reg. This package gets better maintenance.
Also introducing new checksums for reg's children/dependecies.
Signed-off-by: Jakub Bielecki <jakub.bielecki@codilime.com>
* go mod tidy
Workaround for a deficient Ping implementation of reg package.
Ping fails on docker registries that return http 401
Authentication Required when requesting general /v2 url, but
happily allow unauthenticated pull of a specific image.
Closesaquasecurity/trivyfanal#229
Signed-off-by: Jakub Bielecki <jakub.bielecki@codilime.com>
* chore(makefile): add Makefile
* chore(ci): use make
* chore(makefile): add clean
* chore(makefile): fix test commands
* chore(ci): split tests into the unit test and the integration test
I have added a mapping to a specific environment variable for every
currently available flag, I have followed the convention to simply
replace dashes within the flag name by an underscore.
There is no further configuration or change required as urfave/cli is
handling all of that for us.
Signed-off-by: Thomas Boerger <thomas@webhippie.de>
* Add flag to download vulnerability database
When the `--download-db-only` flag is supplied, we will just download
the vulnerability database and exit without performing any scans.
If a database had been downloaded before the present run, and
`--only-update` option has been specified, we will only update the
database for the selected distribution and exit.
* Add documentation for `--download-db-only` flag
Add section to README on usage limitations of the new flag.
the rubygems version includes "platform" within the version
and it gets pulled into version.Version as a pre-release
value.
this means that in the case of something like "ffi",
1.9.25-java is not counted correctly as matching
">= 1.9.25".
* Support Amazon Linux
* amazon: Add tests for Scanner Detect functionality
* amazon: Add more test cases for unhappy paths.
This commit also asserts the logged output via observer.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* amazon: Add a test case for invalid fixed pkg version
Signed-off-by: Simarpreet Singh <simar@linux.com>
* mod: go mod tidy
Signed-off-by: Simarpreet Singh <simar@linux.com>
* amazon: Inject dependency seams for exposed db interface and logger.
This commit also exposes an interface for doing db operations.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* amazon: Use injected logger for scanner.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* amazon_test: Add a sample testdata dir
Signed-off-by: Simarpreet Singh <simar@linux.com>
* amazon: Add tests for for Get() for amazon vulns.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* vulnsrc_test: Fix invocation call to SetVersion()
Signed-off-by: Simarpreet Singh <simar@linux.com>
* amazon_test: Add a test for severirtyFromPriority
Signed-off-by: Simarpreet Singh <simar@linux.com>
* amazon_test: Add tests for constructVersion()
Signed-off-by: Simarpreet Singh <simar@linux.com>
* amazon: Refactor walkFunc outside for testability purposes
Signed-off-by: Simarpreet Singh <simar@linux.com>
* amazon: Refactor walkFn and add tests for it.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* amazon: Refactor commitFunc closure and add tests
This commit also introduces an interface for the
vulnerability package to be used as a seam.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* Revert "amazon: Use injected logger for scanner."
This reverts commit 5a81e4d824a95f4de4aae2e2b903eedd0f7e241f.
* test(amazon): fix failed tests
* fix(vulnerability): trim references
* test(amazon): add integration test
* divide into NewApp function
* sort scan results for idempotency
* chore(integration): add integration tests
* tar_input_test: strengthen assertions
Signed-off-by: Simarpreet Singh <simar@linux.com>
* writer_test: Add a happy path for TestReportWriter
Signed-off-by: Simarpreet Singh <simar@linux.com>
* writer_test: switch to table test cases
Signed-off-by: Simarpreet Singh <simar@linux.com>
* writer_test: Add more scenarios for TestReportWriter_Table
Signed-off-by: Simarpreet Singh <simar@linux.com>
* writer: Change back to []Results and add happy path for JSON writer
Signed-off-by: Simarpreet Singh <simar@linux.com>
* writer_test: Switch to a table driven format
Signed-off-by: Simarpreet Singh <simar@linux.com>
* writer_test: cleanup
Signed-off-by: Simarpreet Singh <simar@linux.com>
* scan: Go back to report.Result by value
Signed-off-by: Simarpreet Singh <simar@linux.com>
* Revert "scan: Go back to report.Result by value"
This reverts commit 03b6f7abd7d0d22d87c825d0ef3759cca200b9fc.
* switch back to by value for results
Signed-off-by: Simarpreet Singh <simar@linux.com>
* writer_test: document a behavior with template inputs
Signed-off-by: Simarpreet Singh <simar@linux.com>
* vulnerability: Add a failing test to show unexpected sorting behavior.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* report: Simplify []*Result to []Result.
Signed-off-by: Simarpreet Singh <simar@linux.com>
* test(template): add happy path
* test(vulnerability): fix expected values
* tar_input_test: Move gunzipDB
Signed-off-by: Simarpreet Singh <simar@linux.com>
* Add : add option flag to specify ignorefile
* Add : reading flag and pass variable to function
* Add : reading specific ignorefile as trivyIgnore
* Remove extra ignoreFile check from vulnerability.go
Remove check if ignoreFile is empty
Co-Authored-By: Teppei Fukuda <knqyf263@gmail.com>
* Fix : remove completely ignoreFile check
* Refactor : run gofmt to main.go
In several files, the error passed from filepath.Walk to WalkFunc is
not checked. As the info argument to WalkFn is nil in case of an error,
accessing info can cause a runtime panic.
This commit adds checks for errors passed through to WalkFunc.
* extract all files in target require filedirs
* use separator to string
* change dpkg file match algorithm
* use filepath.Clean
* add test for target dir files
- Adds a new analyzer error for "no packages detected"
- Package analyzers now return the common "no packages detected" error
- Returned errors from the package analyzers are checked against the
common "no packages detected" errors and filters those out. Other
errors will now be passed back to the user for debugging.
* Added --only-update flag
* Added feature for --only-update flag
* Added README of --only-update
* Fixed README
* Use only Update function
* Added warning message
You don't need to tap a repo to install from it with Homebrew it seems. Homebrew will automatically tap it with `brew install`:
```
❯ brew install knqyf263/trivy/trivy
Updating Homebrew...
....
Cloning into '/usr/local/Homebrew/Library/Taps/knqyf263/homebrew-trivy'...
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
Tapped 1 formula (27 files, 23.5KB).
==> Installing trivy from knqyf263/trivy
```
* Added cache-dir flag
The flag cache-dir allows users to specify the cache directory the
database is stored in.
Signed-off-by: Ken Herner <kherner@navistone.com>
* Moved dbDir definition into functions
Need to move dbDir definition into the calling functions as the cache
directory may have been specified. With dbDir defined at package level,
it would always be instantiated to the default value and would never be
updated to the user specifyed value.
Signed-off-by: Ken Herner <kherner@navistone.com>
* fix genuinetools/reg module version
* merge ubuntu analyzer into debianbase analyzer
* add os analyzer tests
* add redhat base test
* add redhatbase test file
* use AnalyzeOsError
* add gitignore empty folder
* change variable name in test codes
* skip coverage check on forked project
See [Issues](https://aquasecurity.github.io/trivy/latest/community/contribute/issue/) and [Pull Requests](https://aquasecurity.github.io/trivy/latest/community/contribute/pr/)
- [Comparison with other scanners](#comparison-with-other-scanners)
- [Overview](#overview)
- [vs Clair, Quay](#vs-clair-quay)
- [vs Anchore Engine](#vs-anchore-engine)
- [vs Docker Hub, GCR](#vs-docker-hub-gcr)
- [Q&A](#qa)
- [Homebrew](#homebrew)
- [Others](#others)
## Quick Start
# Abstract
### Get Trivy
`Trivy` (`tri` pronounced like **tri**gger, `vy` pronounced like en**vy**) is a simple and comprehensive vulnerability scanner for containers.
`Trivy` detects vulnerabilities of OS packages (Alpine, RHEL, CentOS, etc.) and application dependencies (Bundler, Composer, npm, yarn etc.).
`Trivy` is easy to use. Just install the binary and you're ready to scan. All you need to do for scanning is to specify a container image name.
Trivy is available in most common distribution channels. The full list of installation options is available in the [Installation] page. Here are a few popular examples:
It is considered to be used in CI. Before pushing to a container registry, you can scan your local container image easily.
See [here](#continuous-integration-ci) for details.
-`brew install trivy`
-`docker run aquasec/trivy`
- Download binary from <https://github.com/aquasecurity/trivy/releases/latest/>
- See [Installation] for more
# Features
Trivy is integrated with many popular platforms and applications. The complete list of integrations is available in the [Ecosystem] page. Here are a few popular examples:
-Detect comprehensive vulnerabilities
-OS packages (Alpine, **Red Hat Universal Base Image**, Red Hat Enterprise Linux, CentOS, Debian and Ubuntu)
-**Application dependencies** (Bundler, Composer, Pipenv, npm, yarn and Cargo)
- Simple
- Specify only an image name
- Easy installation
- **No need for prerequirements** such as installation of DB, libraries, etc.
-`apt-get install`, `yum install` and `brew install` is possible (See [Installation](#installation))
- High accuracy
- **Especially Alpine Linux and RHEL/CentOS** (See [Comparison with other scanners](#comparison-with-other-scanners))
- Other OSes are also high
- Continuous Integration
- **Compatible with CI** such as Travis CI, CircleCI, Jenkins, etc.
There are canary builds ([Docker Hub](https://hub.docker.com/r/aquasec/trivy/tags?page=1&name=canary), [GitHub](https://github.com/aquasecurity/trivy/pkgs/container/trivy/75776514?tag=canary), [ECR](https://gallery.ecr.aws/aquasecurity/trivy#canary) images and [binaries](https://github.com/aquasecurity/trivy/actions/workflows/canary.yaml)) as generated every push to main branch.
## RHEL/CentOS
Please be aware: canary builds might have critical bugs, it's not recommended for use in production.
Go to [the releases page](https://github.com/knqyf263/trivy/releases), find the version you want, and download the zip file. Unpack the zip file, and put the binary to somewhere you want (on UNIX-y systems, /usr/local/bin or the like). Make sure it has execution bits turned on.
You need to install `rpm` command for scanning RHEL/CentOS.
## From source
```sh
$ go get -u github.com/knqyf263/trivy
```
# Quick Start
Simply specify an image name (and a tag). **The `latest` tag should be avoided as problems occur with cache.**. See [Clear image caches](#clear-image-caches)
```
$ trivy [YOUR_IMAGE_NAME]
```
For example:
```
$ trivy python:3.7-alpine
```
# Examples
### Scan an image
Simply specify an image name (and a tag).
```
$ trivy python:3.7-alpine
```bash
trivy image python:3.4-alpine
```
<details>
<summary>Result</summary>
```
2019-05-16T01:20:43.180+0900 INFO Updating vulnerability database...
2019-05-16T01:20:53.029+0900 INFO Detecting Alpine vulnerabilities...
`Trivy` updates vulnerability database every time it is run. This is usually fast as it is a difference update. But if you want to skip even that, use the `--skip-update` option.
```
$ trivy --skip-update alpine:3.9
```
### Ignore unfixed vulnerabilities
By default, `Trivy` also detects unpatched/unfixed vulnerabilities. This means you can't fix these vulnerabilities even if you update all packages.
If you would like to ignore them, use the `--ignore-unfixed` option.
```
$ trivy --exit-code 1 httpd:2.4.39
```
### Specify exit code
By default, `Trivy` exits with code 0 even when vulnerabilities are detected.
Use the `--exit-code` option if you want to exit with a non-zero exit code.
```
$ trivy --exit-code 1 httpd:2.4.39
```
This option is useful for CI/CD. In the following example, the test will fail only when a critical vulnerability is found.
The `--clear-cache` option removes image caches. This option is useful if the image which has the same tag is updated (such as when using `latest` tag).
```
$ trivy --clear-cache redis:5.0.4
```
### 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.
```
$ trivy --reset
```
# Continuous Integration (CI)
Scan your image built in Travis CI/CircleCI. The test will fail if a vulnerability is found. When you don't want to fail the test, specify `--exit-code 0` .
**Note**: The first time take a while (faster by cache after the second time)
The following bar charts show the results of scanning [composer:1.7.2](https://hub.docker.com/_/composer?tab=tags) and [crate:3.2.2](https://hub.docker.com/_/crate?tab=tags) by container scanners. These images were selected randomly.
See [spreadsheet](https://docs.google.com/spreadsheets/d/16uj9vGh2PHMcVwb_D4h0nYUSvzCAxcnUz9UgQaDCYs4/edit#gid=0) for details.
In this case, the union of vulnerabilities detected by all vulnerability scanners is used as a data set.
**NOTE**
- There may be vulnerabilities that all scanners could not detect.
- There may be a mistake because I have confirmed the correctness manually.
### Alpine Linux
The results of [composer:1.7.2](https://hub.docker.com/_/composer?tab=tags) using Alpine Linux 3.7.1 (as of 2019/05/12).
<img src="imgs/alpine.png" width="500">
`Trivy` has high accuracy and high precision, while GCR did not detect any vulnerability. Althogh Docker Hub has many True Positive, it also has many False Positive.
### RHEL/CentOS
The results of [crate:3.2.2](https://hub.docker.com/_/crate?tab=tags) using CentOS 7.6.1810. (as of 2019/05/14).
The following chart includes only fixable vulnerabilities.
However, the purpose of this database is to make it possible to know what packages has backported fixes.
As README says, it is not a complete database of all security issues in Alpine.
`Trivy` collects vulnerability information in Alpine Linux from [Alpine LInux Redmine](https://bugs.alpinelinux.org/projects/alpine/issues).
Then, those vulnerabilities will be saved on [vuln-list](https://github.com/knqyf263/vuln-list/tree/master/alpine)
`alpine-secdb` has 6959 vulnerabilities (as of 2019/05/12).
`vuln-list` has 11101 vulnerabilities related with Alpine Linux (as of 2019/05/12).
There is a difference in detection accuracy because the number of vulnerabilities is nearly doubled.
In addition, `Trivy` analyzes the middle layer as well and find out which version of the library was used for static linking.
`Clair` can not handle the following cases because it analyzes the image after applying the all layers.
```
RUN apk add --no-cache sqlite-dev \
&& wget https://xxx/yyy.tar.gz \
&& tar zxvf yyy.tar.gz && cd yyy \
&& make && make install \
&& apk del sqlite-dev
```
Finally, `Trivy` can also detect vulnerabilities in application dependent libraries such as Bundler, Composer, Pipenv, etc.
## vs Anchore Engine
Similar to Clair, there is a difference in detection accuracy on Alpine Linux.
Then, as noted above, `Anchore Engine` does not detect unfixable vulnerabilities on RHEL/CentOS, whereas `Trivy` does.
Also, `Anchore Engine` needs some steps to start scanning.
`Trivy` is much easier to use.
## vs Quay, Docker Hub, GCR
As `Quay` seems to use `Clair` internally, it has the same accuracy with `Clair`. `Docker Hub` can scan only official images. `GCR` hardly detects vulnerability on Alpine Linux. Also, it is locked to a specific registry.
`Trivy` does not depend on the registry. In addition, it is easy to be integrated with CI/CD services.
# Q&A
## Homebrew
### Error: Your macOS keychain GitHub credentials do not have sufficient scope!
```
$ brew tap knqyf263/trivy
Error: Your macOS keychain GitHub credentials do not have sufficient scope!
This directory contains media assets, such as the Trivy logo.
Assets under this directory are provided under the Creative Commons - BY 4.0 License. For more details, see here: <https://creativecommons.org/licenses/by/4.0/>
log_crit "uname_os_check '$(uname -s)' got converted to '$os' which is not a GOOS value. Please file bug at https://github.com/client9/shlib"
return1
}
uname_arch_check(){
arch=$(uname_arch)
case"$arch" in
386)return0;;
amd64)return0;;
arm64)return0;;
armv5)return0;;
armv6)return0;;
armv7)return0;;
ppc64)return0;;
ppc64le)return0;;
mips)return0;;
mipsle)return0;;
mips64)return0;;
mips64le)return0;;
s390x)return0;;
amd64p32)return0;;
esac
log_crit "uname_arch_check '$(uname -m)' got converted to '$arch' which is not a GOARCH value. Please file bug report at https://github.com/client9/shlib"
return1
}
untar(){
tarball=$1
case"${tarball}" in
*.tar.gz | *.tgz) tar --no-same-owner -xzf "${tarball}";;
*.tar) tar --no-same-owner -xf "${tarball}";;
*.zip) unzip "${tarball}";;
*)
log_err "untar unknown archive format for ${tarball}"
Thank you for taking interest in contributing to Trivy!
- Feel free to open issues for any reason. When you open a new issue, you'll have to select an issue kind: bug/feature/support and fill the required information based on the selected template.
- Please spend a small amount of time giving due diligence to the issue tracker. Your issue might be a duplicate. If it is, please add your comment to the existing issue.
- Remember that users might search for your issue in the future, so please give it a meaningful title to help others.
- The issue should clearly explain the reason for opening, the proposal if you have any, and any relevant technical information.
## Wrong detection
Trivy depends on [multiple data sources](https://aquasecurity.github.io/trivy/latest/docs/vulnerability/detection/data-source/).
Sometime these databases contain mistakes.
If Trivy can't detect any CVE-IDs or shows false positive result, at first please follow the next steps:
1. Run Trivy with `-f json` that shows data sources.
2. According to the shown data source, make sure that the security advisory in the data source is correct.
If the data source is correct and Trivy shows wrong results, please raise an issue on Trivy.
### GitHub Advisory Database
Visit [here](https://github.com/advisories) and search CVE-ID.
If you find a problem, it'll be nice to fix it: [How to contribute to a GitHub security advisory](https://github.blog/2022-02-22-github-advisory-database-now-open-to-community-contributions/)
### GitLab Advisory Database
Visit [here](https://advisories.gitlab.com/) and search CVE-ID.
If you find a problem, it'll be nice to fix it: [Create an issue to GitLab Advisory Database](https://gitlab.com/gitlab-org/security-products/gemnasium-db/-/issues/new)
### Red Hat CVE Database
Visit [here](https://access.redhat.com/security/security-updates/?cwe=476#/cve) and search CVE-ID.
Thank you for taking interest in contributing to Trivy!
1. Every Pull Request should have an associated bug or feature issue unless you are fixing a trivial documentation issue.
1. Please add the associated Issue link in the PR description.
1. Your PR is more likely to be accepted if it focuses on just one change.
1. There's no need to add or tag reviewers.
1. If a reviewer commented on your code or asked for changes, please remember to respond with comment. Do not mark discussion as resolved. It's up to reviewer to mark it resolved (in case if suggested fix addresses problem properly). PRs with unresolved issues should not be merged (even if the comment is unclear or requires no action from your side).
1. Please include a comment with the results before and after your change.
1. Your PR is more likely to be accepted if it includes tests (We have not historically been very strict about tests, but we would like to improve this!).
1. If your PR affects the user experience in some way, please update the README.md and the CLI help accordingly.
## Development
Install the necessary tools for development by following their respective installation instructions.
- [Go](https://go.dev/doc/install)
- [Mage](https://magefile.org/)
### Build
After making changes to the Go source code, build the project with the following command:
```shell
$ mage build
$ ./trivy -h
```
### Lint
You must pass the linter checks:
```shell
$ mage lint
```
Additionally, you need to have run `go mod tidy`, so execute the following command as well:
```shell
$ mage tidy
```
### Unit tests
Your PR must pass all the unit tests. You can test it as below.
```
$ mage test:unit
```
### Integration tests
Your PR must pass all the integration tests. You can test it as below.
```
$ mage test:integration
```
### Documentation
You can build the documents as below and view it at http://localhost:8000.
```
$ mage docs:serve
```
## Title
It is not that strict, but we use the title conventions in this repository.
Each commit message doesn't have to follow the conventions as long as it is clear and descriptive since it will be squashed and merged.
### Format of the title
```
<type>(<scope>): <subject>
```
The `type` and `scope` should always be lowercase as shown below.
**Allowed `<type>` values:**
- **feat** for a new feature for the user, not a new feature for build script. Such commit will trigger a release bumping a MINOR version.
- **fix** for a bug fix for the user, not a fix to a build script. Such commit will trigger a release bumping a PATCH version.
- **perf** for performance improvements. Such commit will trigger a release bumping a PATCH version.
- **docs** for changes to the documentation.
- **style** for formatting changes, missing semicolons, etc.
- **refactor** for refactoring production code, e.g. renaming a variable.
- **test** for adding missing tests, refactoring tests; no production code change.
- **build** for updating build configuration, development tools or other changes irrelevant to the user.
- **chore** for updates that do not apply to the above, such as dependency updates.
- **ci** for changes to CI configuration files and scripts
- **revert** for revert to a previous commit
**Allowed `<scope>` values:**
checks:
- vuln
- misconf
- secret
- license
mode:
- image
- fs
- repo
- sbom
- k8s
- server
- aws
- vm
os:
- alpine
- redhat
- alma
- rocky
- mariner
- oracle
- debian
- ubuntu
- amazon
- suse
- photon
- distroless
language:
- ruby
- php
- python
- nodejs
- rust
- dotnet
- java
- go
- elixir
- dart
vuln:
- os
- lang
config:
- kubernetes
- dockerfile
- terraform
- cloudformation
container
- docker
- podman
- containerd
- oci
cli:
- cli
- flag
SBOM:
- cyclonedx
- spdx
- purl
others:
- helm
- report
- db
- deps
The `<scope>` can be empty (e.g. if the change is a global or difficult to assign to a single component), in which case the parentheses are omitted.
### Example titles
```
feat(alma): add support for AlmaLinux
```
```
fix(oracle): handle advisories with ksplice versions
```
```
docs(misconf): add comparison with Conftest and TFsec
```
```
chore(deps): bump go.uber.org/zap from 1.19.1 to 1.20.0
```
**NOTE**: please do not use `chore(deps): update fanal` and something like that if you add new features or fix bugs in Trivy-related projects.
The PR title should describe what the PR adds or fixes even though it just updates the dependency in Trivy.
## Commits
## Understand where your pull request belongs
Trivy is composed of several repositories that work together:
- [Trivy](https://github.com/aquasecurity/trivy) is the client-side, user-facing, command line tool.
- [vuln-list](https://github.com/aquasecurity/vuln-list) is a vulnerability database, aggregated from different sources, and normalized for easy consumption. Think of this as the "server" side of the trivy command line tool. **There should be no pull requests to this repo**
- [vuln-list-update](https://github.com/aquasecurity/vuln-list-update) is the code that maintains the vuln-list database.
- [trivy-db](https://github.com/aquasecurity/trivy-db) maintains the vulnerability database pulled by Trivy CLI.
- [go-dep-parser](https://github.com/aquasecurity/go-dep-parser) is a library for parsing lock files such as package-lock.json and Gemfile.lock.
Triage is an important part of maintaining the health of the trivy repo.
A well organized repo allows maintainers to prioritize feature requests, fix bugs, and respond to users facing difficulty with the tool as quickly as possible.
Triage includes:
- Labeling issues
- Responding to issues
- Closing issues
# Daily Triage
Daily triage has two goals:
1. Responsiveness for new issues
1. Responsiveness when explicitly requested information was provided
It covers:
1. Issues without a `kind/` or `triage/` label
1. Issues without a `priority/` label
1.`triage/needs-information` issues which the user has followed up on, and now require a response.
## Categorization
The most important level of categorizing the issue is defining what type it is.
We typically want at least one of the following labels on every issue, and some issues may fall into multiple categories:
-`triage/support` - The default for most incoming issues
-`kind/bug` - When it’s a bug or we aren’t delivering the best user experience
Other possibilities:
-`kind/feature`- Identify new feature requests
-`kind/testing` - Update or fix unit/integration tests
-`kind/cleanup` - Cleaning up/refactoring the codebase
-`kind/documentation` - Updates or additions to trivy documentation
If the issue is specific to a driver for OS packages or libraries:
**co/[driver for OS packages]**
-`co/alpine`
-`co/amazon`
-`co/debian`
-`co/oracle`
-`co/photon`
-`co/redhat`
-`co/suse`
-`co/ubuntu`
**co/[driver for libraries of programming languages]**
-`co/bundler`
-`co/cargo`
-`co/composer`
-`co/npm`
-`co/yarn`
-`co/pipenv`
-`co/poetry`
**Help wanted?**
`Good First Issue` - bug has a proposed solution, can be implemented w/o further discussion.
`Help wanted` - if the bug could use help from a contributor
## Prioritization
If the issue is not `triage/support`, it needs a priority label.
`priority/critical-urgent` - someones top priority ASAP, such as security issue, user-visible bug, or build breakage. Rarely used.
`priority/important-soon`: in time for the next two releases. It should be attached to a milestone.
`priority/important-longterm`: 2-4 releases from now
`priority/backlog`: agreed that this would be good to have, but no one is available at the moment. Consider tagging as `help wanted`
`priority/awaiting-more-evidence`: may be useful, but there is not yet enough support.
# Weekly Triage
Weekly triage has three goals:
1. Catching up on unresponded issues
1. Reviewing and closing PR’s
1. Closing stale issues
## Post-Release Triage
Post-release triage occurs after a major release (around every 4-6 weeks).
It focuses on:
1. Closing bugs that have been resolved by the release
1. Reprioritizing bugs that have not been resolved by the release
1. Letting users know if we believe that there is still an issue
This includes reviewing:
1. Every issue that hasn’t been touched in the last 2 days
1. Re-evaluation of long-term issues
1. Re-evaluation of short-term issues
## Responding to Issues
### Needs More Information
A sample response to ask for more info:
> I don’t yet have a clear way to replicate this issue. Do you mind adding some additional details. Here is additional information that would be helpful:
>
> \* The exact `trivy` command line used
>
> \* The exact image you want to scan
>
> \* The full output of the `trivy` command, preferably with `--debug` for extra logging.
>
>
> Thank you for sharing your experience!
Then: Label with `triage/needs-information`.
### Issue might be resolved
If you think a release may have resolved an issue, ask the author to see if their issue has been resolved:
> Could you please check to see if trivy <x> addresses this issue? We've made some changes with how this is handled, and improved the trivy logs output to help us debug tricky cases like this.
Then: Label with `triage/needs-information`.
## Closing with Care
Issues typically need to be closed for the following reasons:
- The issue has been addressed
- The issue is a duplicate of an existing issue
- There has been a lack of information over a long period of time
In any of these situations, we aim to be kind when closing the issue, and offer the author action items should they need to reopen their issue or still require a solution.
Samples responses for these situations include:
### Issue has been addressed
>@author: I believe this issue is now addressed by trivy v1.0.0, as it <reason>. If you still see this issue with trivy v1.0 or higher, please reopen this issue.
>
>Thank you for reporting this issue!
Then: Close the issue
### Duplicate Issue
>This issue appears to be a duplicate of #X, do you mind if we move the conversation there?
>
>This way we can centralize the content relating to the issue. If you feel that this issue is not in fact a duplicate, please re-open it. If you have additional information to share, please add it to the new issue.
>
>Thank you for reporting this!
Then: Label with `triage/duplicate` and close the issue.
### Lack of Information
If an issue hasn't been active for more than four weeks, and the author has been pinged at least once, then the issue can be closed.
>Hey @author -- hopefully it's OK if I close this - there wasn't enough information to make it actionable, and some time has already passed. If you are able to provide additional details, you may reopen it at any point.
>
>Here is additional information that may be helpful to us:
>
>\* Whether the issue occurs with the latest trivy release
>
>\* The exact `trivy` command line used
>
>\* The exact image you want to scan
>
>\* The full output of the `trivy` command, preferably with `--debug` for extra logging.
>
>
>Thank you for sharing your experience!
Then: Close the issue.
## Help Wanted issues
We use two labels [help wanted](https://github.com/aquasecurity/trivy/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22)
and [good first issue](https://github.com/aquasecurity/trivy/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)
to identify issues that have been specially groomed for new contributors.
We have specific [guidelines](/docs/community/maintainer/help-wanted.md)
for how to use these labels. If you see an issue that satisfies these
guidelines, you can add the `help wanted` label and the `good first issue` label.
Please note that adding the `good first issue` label must also
add the `help wanted` label.
If an issue has these labels but does not satisfy the guidelines, please
ask for more details to be added to the issue or remove the labels.
You have to know where to put the DB files. The following command shows the default cache directory.
```
$ ssh user@host
$ trivy -h | grep cache
--cache-dir value cache directory (default: "/home/myuser/.cache/trivy") [$TRIVY_CACHE_DIR]
```
=== "Vulnerability db"
Put the DB file in the cache directory + `/db`.
```
$ mkdir -p /home/myuser/.cache/trivy/db
$ cd /home/myuser/.cache/trivy/db
$ tar xvf /path/to/db.tar.gz -C /home/myuser/.cache/trivy/db
x trivy.db
x metadata.json
$ rm /path/to/db.tar.gz
```
=== "Java index db[^1]"
Put the DB file in the cache directory + `/java-db`.
```
$ mkdir -p /home/myuser/.cache/trivy/java-db
$ cd /home/myuser/.cache/trivy/java-db
$ tar xvf /path/to/javadb.tar.gz -C /home/myuser/.cache/trivy/java-db
x trivy-java.db
x metadata.json
$ rm /path/to/javadb.tar.gz
```
In an air-gapped environment it is your responsibility to update the Trivy databases on a regular basis, so that the scanner can detect recently-identified vulnerabilities.
### Run Trivy with the specific flags.
In an air-gapped environment, you have to specify `--skip-db-update` and `--skip-java-db-update`[^1] so that Trivy doesn't attempt to download the latest database files.
In addition, if you want to scan `pom.xml` dependencies, you need to specify `--offline-scan` since Trivy tries to issue API requests for scanning Java applications by default.
The `plugin.yaml` field should contain the following information:
- name: The name of the plugin. This also determines how the plugin will be made available in the Trivy CLI. For example, if the plugin is named kubectl, you can call the plugin with `trivy kubectl`. (required)
- version: The version of the plugin. (required)
- usage: A short usage description. (required)
- description: A long description of the plugin. This is where you could provide a helpful documentation of your plugin. (required)
- platforms: (required)
- selector: The OS/Architecture specific variations of a execution file. (optional)
- os: OS information based on GOOS (linux, darwin, etc.) (optional)
- arch: The architecture information based on GOARCH (amd64, arm64, etc.) (optional)
- uri: Where the executable file is. Relative path from the root directory of the plugin or remote URL such as HTTP and S3. (required)
- bin: Which file to call when the plugin is executed. Relative path from the root directory of the plugin. (required)
The following rules will apply in deciding which platform to select:
- If both `os` and `arch` under `selector` match the current platform, search will stop and the platform will be used.
- If `selector` is not present, the platform will be used.
- If `os` matches and there is no more specific `arch` match, the platform will be used.
- If no `platform` match is found, Trivy will exit with an error.
After determining platform, Trivy will download the execution file from `uri` and store it in the plugin cache.
When the plugin is called via Trivy CLI, `bin` command will be executed.
The plugin is responsible for handling flags and arguments. Any arguments are passed to the plugin from the `trivy` command.
A plugin should be archived `*.tar.gz`.
```bash
$ tar -czvf myplugin.tar.gz plugin.yaml script.py
plugin.yaml
script.py
$ trivy plugin install myplugin.tar.gz
2023-03-03T19:04:42.026+0600 INFO Installing the plugin from myplugin.tar.gz...
2023-03-03T19:04:42.026+0600 INFO Loading the plugin metadata...
2022-09-16T17:37:13.258+0900 INFO Vulnerability scanning is enabled
2022-09-16T17:37:13.258+0900 INFO Secret scanning is enabled
2022-09-16T17:37:13.258+0900 INFO If your scanning is slow, please try '--scanners vuln' to disable secret scanning
2022-09-16T17:37:13.258+0900 INFO Please see also https://aquasecurity.github.io/trivy/dev/docs/secret/scanning/#recommendation for faster secret detection
2022-09-16T17:37:14.827+0900 INFO Detected SBOM format: cyclonedx-json
2022-09-16T17:37:14.901+0900 INFO Found SBOM (cyclonedx) attestation in Rekor
2022-09-16T17:37:14.903+0900 INFO Detected OS: alpine
2022-09-16T17:37:14.903+0900 INFO Detecting Alpine vulnerabilities...
2022-09-16T17:37:14.907+0900 INFO Number of language-specific files: 0
2022-09-16T17:37:14.908+0900 WARN This OS version is no longer supported by the distribution: alpine 3.7.3
2022-09-16T17:37:14.908+0900 WARN The vulnerability detection may be insufficient because security updates are not provided
[Cosign](https://github.com/sigstore/cosign) supports generating and verifying [in-toto attestations](https://github.com/in-toto/attestation). This tool enables you to sign and verify SBOM attestation.
And, Trivy can take an SBOM attestation as input and scan for vulnerabilities
!!! note
In the following examples, the `cosign` command will write an attestation to a target OCI registry, so you must have permission to write.
If you want to avoid writing an OCI registry and only want to see an attestation, add the `--no-upload` option to the `cosign` command.
## Sign with a local key pair
Cosign can generate key pairs and use them for signing and verification. After you run the following command, you will get a public and private key pair. Read more about [how to generate key pairs](https://docs.sigstore.dev/cosign/key-generation).
```bash
$ cosign generate-key-pair
```
In the following example, Trivy generates an SBOM in the CycloneDX format, and then Cosign attaches an attestation of the SBOM to a container image with a local key pair.
```bash
# The cyclonedx type is supported in Cosign v1.10.0 or later.
Trivy can take an SBOM attestation as input and scan for vulnerabilities. Currently, Trivy supports CycloneDX-type attestation.
In the following example, Cosign can get an CycloneDX-type attestation and trivy scan it.
You must create CycloneDX-type attestation before trying the example.
To learn more about how to create an CycloneDX-Type attestation and attach it to an image, see the [Sign with a local key pair](#sign-with-a-local-key-pair) section.
"Description":"libfetch before 2021-07-26, as used in apk-tools, xbps, and other products, mishandles numeric strings for the FTP and HTTP protocols. The FTP passive mode implementation allows an out-of-bounds read because strtol is used to parse the relevant numbers into address bytes. It does not check if the line ends prematurely. If it does, the for-loop condition checks for the '\\0' terminator one byte too late.",
[Cosign](https://github.com/sigstore/cosign) supports generating and verifying [in-toto attestations](https://github.com/in-toto/attestation). This tool enables you to sign and verify Cosign vulnerability attestation.
!!! note
In the following examples, the `cosign` command will write an attestation to a target OCI registry, so you must have permission to write.
If you want to avoid writing an OCI registry and only want to see an attestation, add the `--no-upload` option to the `cosign` command.
### Sign with a local key pair
Cosign can generate key pairs and use them for signing and verification. After you run the following command, you will get a public and private key pair. Read more about [how to generate key pairs](https://docs.sigstore.dev/cosign/key-generation).
```bash
$ cosign generate-key-pair
```
In the following example, Trivy generates a cosign vulnerability scan record, and then Cosign attaches an attestation of it to a container image with a local key pair.
This feature might change without preserving backwards compatibility.
Trivy’s compliance flag lets you curate a specific set of checks into a report. In a typical Trivy scan, there are hundreds of different checks for many different components and configurations, but sometimes you already know which specific checks you are interested in. Often this would be an industry accepted set of checks such as CIS, or some vendor specific guideline, or your own organization policy that you want to comply with. These are all possible using the flexible compliance infrastructure that's built into Trivy. Compliance reports are defined as simple YAML documents that select checks to include in the report.
## Usage
Compliance report is currently supported in the following targets (trivy sub-commands):
-`trivy image`
-`trivy aws`
-`trivy k8s`
Add the `--compliance` flag to the command line, and set it's value to desired report.
For example: `trivy k8s cluster --compliance k8s-nsa` (see below for built-in and custom reports)
### Options
The following flags are compatible with `--compliance` flag and allows customizing it's output:
You can create your own custom compliance report. A compliance report is a simple YAML document in the following format:
```yaml
spec:
id:"k8s-myreport"# report unique identifier. this should not container spaces.
title:"My custom Kubernetes report"# report title. Any one-line title.
description:"Describe your report"# description of the report. Any text.
relatedResources :
- https://some.url# useful references. URLs only.
version:"1.0"# spec version (string)
controls:
- name:"Non-root containers"# Name for the control (appears in the report as is). Any one-line name.
description:'Check that container is not running as root'# Description (appears in the report as is). Any text.
id:"1.0"# control identifier (string)
checks:# list of existing Trivy checks that define the control
- id:AVD-KSV-0012# check ID. Must start with `AVD-` or `CVE-`
severity:"MEDIUM"# Severity for the control (note that checks severity isn't used)
- name:"Immutable container file systems"
description:'Check that container root file system is immutable'
id:"1.1"
checks:
- id:AVD-KSV-0014
severity:"LOW"
```
The check id field (`controls[].checks[].id`) is referring to existing check by it's "AVD ID". This AVD ID is easily located in the check's source code metadata header, or by browsing [Aqua vulnerability DB](https://avd.aquasec.com/), specifically in the [Misconfigurations](https://avd.aquasec.com/misconfig/) and [Vulnerabilities](https://avd.aquasec.com/nvd) sections.
Once you have a compliance spec, you can select it by file path: `trivy --compliance @</path/to/compliance.yaml>` (note the `@` indicating file path instead of report id).
Trivy scans any container image for license files and offers an opinionated view on the risk associated with the license.
License are classified using the [Google License Classification][google-license-classification] -
- Forbidden
- Restricted
- Reciprocal
- Notice
- Permissive
- Unencumbered
- Unknown
!!! tip
Licenses that Trivy fails to recognize are classified as UNKNOWN.
As those licenses may be in violation, it is recommended to check those unknown licenses as well.
By default, Trivy scans licenses for packages installed by `apk`, `apt-get`, `dnf`, `npm`, `pip`, `gem`, etc.
To enable extended license scanning, you can use `--license-full`.
In addition to package licenses, Trivy scans source code files, Markdown documents, text files and `LICENSE` documents to identify license usage within the image or filesystem.
!!! note
The full license scanning is expensive. It takes a while.
Currently, the standard license scanning doesn't support filesystem and repository scanning.
Running containers with 'root' user can lead to a container escape situation. It is a best practice to run containers as non-root users, which can be done by adding a 'USER' statement to the Dockerfile.
| Dockerfile | `Dockerfile`, `Dockerfile.*`, and `*.Dockerfile` |
| Containerfile | `Containerfile`, `Containerfile.*`, and `*.Containerfile` |
| Terraform | `*.tf` and `*.tf.json` |
### Configuration languages
In the above general file formats, Trivy automatically identifies the following types of configuration files:
- CloudFormation (JSON/YAML)
- Kubernetes (JSON/YAML)
- Helm (YAML)
- Terraform Plan (JSON)
This is useful for filtering inputs, as described below.
## Rego format
A single package must contain only one policy.
!!!example
``` rego
# METADATA
# title: Deployment not allowed
# description: Deployments are not allowed because of some reasons.
# schemas:
# - input: schema["kubernetes"]
# custom:
# id: ID001
# severity: LOW
# input:
# selector:
# - type: kubernetes
package user.kubernetes.ID001
deny[res] {
input.kind == "Deployment"
msg := sprintf("Found deployment '%s' but deployments are not allowed", [input.metadata.name])
res := result.new(msg, input.kind)
}
```
In this example, ID001 "Deployment not allowed" is defined under `user.kubernetes.ID001`.
If you add a new custom policy, it must be defined under a new package like `user.kubernetes.ID002`.
### Policy structure
`# METADATA` (optional)
: - SHOULD be defined for clarity since these values will be displayed in the scan results
- `custom.input` SHOULD be set to indicate the input type the policy should be applied to. See [list of available types](https://github.com/aquasecurity/defsec/blob/418759b4dc97af25f30f32e0bd365be7984003a1/pkg/types/sources.go)
`package` (required)
: - MUST follow the Rego's [specification][package]
- MUST be unique per policy
- SHOULD include policy id for uniqueness
- MAY include the group name such as `kubernetes` for clarity
- Group name has no effect on policy evaluation
`deny` (required)
: - SHOULD be `deny` or start with `deny_`
- Although `warn`, `warn_*`, `violation`, `violation_` also work for compatibility, `deny` is recommended as severity can be defined in `__rego_metadata__`.
- SHOULD return ONE OF:
- The result of a call to `result.new(msg, cause)`. The `msg` is a `string` describing the issue occurrence, and the `cause` is the property/object where the issue occurred. Providing this allows Trivy to ascertain line numbers and highlight code in the output.
- A `string` denoting the detected issue
- Although `object` with `msg` field is accepted, other fields are dropped and `string` is recommended if `result.new()` is not utilised.
- e.g. `{"msg": "deny message", "details": "something"}`
### Package
A package name must be unique per policy.
!!!example
``` rego
package user.kubernetes.ID001
```
By default, only `builtin.*` packages will be evaluated.
If you define custom packages, you have to specify the package prefix via `--namespaces` option.
``` bash
trivy conf --policy /path/to/custom_policies --namespaces user /path/to/config_dir
```
In this case, `user.*` will be evaluated.
Any package prefixes such as `main` and `user` are allowed.
### Metadata
Metadata helps enrich Trivy's scan results with useful information.
The annotation format is described in the [OPA documentation](https://www.openpolicyagent.org/docs/latest/annotations/).
Trivy supports extra fields in the `custom` section as described below.
!!!example
``` rego
# METADATA
# title: Deployment not allowed
# description: Deployments are not allowed because of some reasons.
# custom:
# id: ID001
# severity: LOW
# input:
# selector:
# - type: kubernetes
```
All fields are optional. The `schemas` field should be used to enable policy validation using a built-in schema. The
schema that will be used is based on the input document type. It is recommended to use this to ensure your policies are
correct and do not reference incorrect properties/values.
| Field name | Allowed values | Default value | In table | In JSON |
For more details on how to define schemas within Rego policies, please see the [OPA guide](https://www.openpolicyagent.org/docs/latest/schemas/#schema-annotations) that describes it in more detail.
It is highly recommended to write tests for your custom policies.
## Rego testing
To help you verify the correctness of your custom policies, OPA gives you a framework that you can use to write tests for your policies.
By writing tests for your custom policies you can speed up the development process of new rules and reduce the amount of time it takes to modify rules as requirements evolve.
For more details, see [Policy Testing][opa-testing].
!!! example
```
package user.dockerfile.ID002
test_add_denied {
r := deny with input as {"stages": {"alpine:3.13": [
r[_] == "Consider using 'COPY /target/app.jar app.jar' command instead of 'ADD /target/app.jar app.jar'"
}
```
To write tests for custom policies, you can refer to existing tests under [defsec][defsec].
## Go testing
[Fanal][fanal] which is a core library of Trivy can be imported as a Go library.
You can scan config files in Go and test your custom policies using Go's testing methods, such as [table-driven tests][table].
This allows you to use the actual configuration file as input, making it easy to prepare test data and ensure that your custom policies work in practice.
In particular, Dockerfile and HCL need to be converted to structural data as input, which may be different from the expected input format.
!!! tip
We recommend writing OPA and Go tests both since they have different roles, like unit tests and integration tests.
The following example stores allowed and denied configuration files in a directory.
`Successes` contains the result of successes, and `Failures` contains the result of failures.
``` go
{
name: "disallowed ports",
input: "configs/",
fields: fields{
policyPaths: []string{"policy"},
dataPaths: []string{"data"},
namespaces: []string{"user"},
},
want: []types.Misconfiguration{
{
FileType: types.Dockerfile,
FilePath: "Dockerfile.allowed",
Successes: types.MisconfResults{
{
Namespace: "user.dockerfile.ID002",
PolicyMetadata: types.PolicyMetadata{
ID: "ID002",
Type: "Docker Custom Check",
Title: "Disallowed ports exposed",
Severity: "HIGH",
},
},
},
},
{
FileType: types.Dockerfile,
FilePath: "Dockerfile.denied",
Failures: types.MisconfResults{
{
Namespace: "user.dockerfile.ID002",
Message: "Port 23 should not be exposed",
PolicyMetadata: types.PolicyMetadata{
ID: "ID002",
Type: "Docker Custom Check",
Title: "Disallowed ports exposed",
Severity: "HIGH",
},
},
},
},
},
},
```
`Dockerfile.allowed` has one successful result in `Successes`, while `Dockerfile.denied` has one failure result in `Failures`.
Running containers with 'root' user can lead to a container escape situation. It is a best practice to run containers as non-root users, which can be done by adding a 'USER' statement to the Dockerfile.
There are a number of options for overriding values in Helm charts. When override values are passed to the Helm scanner, the values will be used during the Manifest rendering process and will become part of the scanned artifact.
For suggestions or issues regarding policy content, please open an issue under the [defsec][defsec] repository.
Helm Chart scanning will resolve the chart to Kubernetes manifests then run the [kubernetes][kubernetes] checks.
## Policy Distribution
defsec policies are distributed as an OPA bundle on [GitHub Container Registry][ghcr] (GHCR).
When misconfiguration detection is enabled, Trivy pulls the OPA bundle from GHCR as an OCI artifact and stores it in the cache.
Those policies are then loaded into Trivy OPA engine and used for detecting misconfigurations.
If Trivy is unable to pull down newer policies, it will use the embedded set of policies as a fallback. This is also the case in air-gap environments where `--skip-policy-update` might be passed.
## Update Interval
Trivy checks for updates to OPA bundle on GHCR every 24 hours and pulls it if there are any updates.
Exceptions let you specify cases where you allow policy violations.
Trivy supports two types of exceptions.
!!! info
Exceptions can be applied to built-in policies as well as custom policies.
## Namespace-based exceptions
There are some cases where you need to disable built-in policies partially or fully.
Namespace-based exceptions lets you rough choose which individual packages to exempt.
To use namespace-based exceptions, create a Rego rule with the name `exception` that returns the package names to exempt.
The `exception` rule must be defined under `namespace.exceptions`.
`data.namespaces` includes all package names.
!!! example
``` rego
package namespace.exceptions
import data.namespaces
exception[ns] {
ns := data.namespaces[_]
startswith(ns, "builtin.kubernetes")
}
```
This example exempts all built-in policies for Kubernetes.
For more details, see [an example][ns-example].
## Rule-based exceptions
There are some cases where you need more flexibility and granularity in defining which cases to exempt.
Rule-based exceptions lets you granularly choose which individual rules to exempt, while also declaring under which conditions to exempt them.
To use rule-based exceptions, create a Rego rule with the name `exception` that returns the rule name suffixes to exempt, prefixed by `deny_` (for example, returning `foo` will exempt `deny_foo`).
The rule can make any other assertion, for example, on the input or data documents.
This is useful to specify the exemption for a specific case.
Note that if you specify the empty string, the exception will match all rules named `deny`.
```
exception[rules] {
# Logic
rules = ["foo","bar"]
}
```
The above would provide an exception from `deny_foo` and `deny_bar`.
!!! example
```
package user.kubernetes.ID100
__rego_metadata := {
"id": "ID100",
"title": "Deployment not allowed",
"severity": "HIGH",
"type": "Kubernetes Custom Check",
}
deny_deployment[msg] {
input.kind == "Deployment"
msg = sprintf("Found deployment '%s' but deployments are not allowed", [name])
}
exception[rules] {
input.kind == "Deployment"
input.metadata.name == "allow-deployment"
rules := ["deployment"]
}
```
If you want to apply rule-based exceptions to built-in policies, you have to define the exception under the same package.
!!! example
``` rego
package builtin.kubernetes.KSV012
exception[rules] {
input.metadata.name == "can-run-as-root"
rules := [""]
}
```
This exception is applied to [KSV012][ksv012] in defsec.
You can get the package names in the [defsec repository][defsec] or the JSON output from Trivy.
Trivy provides built-in policies to detect configuration issues in popular Infrastructure as Code files, such as: Docker, Kubernetes, Terraform, CloudFormation, and more.
In addition to built-in policies, you can write your own custom policies, as you can see [here][custom].

## Quick start
Simply specify a directory containing IaC files such as Terraform, CloudFormation, Azure ARM templates, Helm Charts and Dockerfile.
``` bash
$ trivy config [YOUR_IaC_DIRECTORY]
```
!!! example
```
$ ls build/
Dockerfile
$ trivy config ./build
2022-05-16T13:29:29.952+0100 INFO Detected config files: 1
Running containers with 'root' user can lead to a container escape situation. It is a best practice to run containers as non-root users, which can be done by adding a 'USER' statement to the Dockerfile.
Running containers with 'root' user can lead to a container escape situation. It is a best practice to run containers as non-root users, which can be done by adding a 'USER' statement to the Dockerfile.
Sysctls can disable security mechanisms or affect all containers on a host, and should be disallowed except for an allowed 'safe' subset. A sysctl is considered safe if it is namespaced in the container or the Pod, and it is isolated from other Pods or processes on the same Node.
Scan an AWS account for misconfigurations. Trivy uses the same authentication methods as the AWS CLI. See https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html
--helm-set strings specify Helm values on the command line (can specify multiple or separate values with commas: key1=val1,key2=val2)
--helm-set-file strings specify Helm values from respective files specified via the command line (can specify multiple or separate values with commas: key1=path1,key2=path2)
--helm-set-string strings specify Helm string values on the command line (can specify multiple or separate values with commas: key1=val1,key2=val2)
--helm-values strings specify paths to override the Helm values.yaml files
-h, --help help for aws
--ignore-policy string specify the Rego file path to evaluate each vulnerability
--include-non-failures include successes and exceptions, available with '--scanners config'
--list-all-pkgs enabling the option will output all packages regardless of vulnerability
--max-cache-age duration The maximum age of the cloud cache. Cached data will be requeried from the cloud provider if it is older than this. (default 24h0m0s)
-o, --output string output file name
--policy-namespaces strings Rego namespaces
--region string AWS Region to scan
--report string specify a report format for the output. (all,summary) (default "all")
--service strings Only scan AWS Service(s) specified with this flag. Can specify multiple services using --service A --service B etc.
-s, --severity string severities of security issues to be displayed (comma separated) (default "UNKNOWN,LOW,MEDIUM,HIGH,CRITICAL")
--helm-set strings specify Helm values on the command line (can specify multiple or separate values with commas: key1=val1,key2=val2)
--helm-set-file strings specify Helm values from respective files specified via the command line (can specify multiple or separate values with commas: key1=path1,key2=path2)
--helm-set-string strings specify Helm string values on the command line (can specify multiple or separate values with commas: key1=val1,key2=val2)
--helm-values strings specify paths to override the Helm values.yaml files
--helm-set strings specify Helm values on the command line (can specify multiple or separate values with commas: key1=val1,key2=val2)
--helm-set-file strings specify Helm values from respective files specified via the command line (can specify multiple or separate values with commas: key1=path1,key2=path2)
--helm-set-string strings specify Helm string values on the command line (can specify multiple or separate values with commas: key1=val1,key2=val2)
--helm-values strings specify paths to override the Helm values.yaml files
-h, --help help for filesystem
--ignore-policy string specify the Rego file path to evaluate each vulnerability
--ignore-unfixed display only fixed vulnerabilities
--ignored-licenses strings specify a list of license to ignore
--generate-default-config write the default config to trivy-default.yaml
--insecure allow insecure server connections when using TLS
-q, --quiet suppress progress bar and log output
--timeout duration timeout (default 5m0s)
-v, --version show version
```
### SEE ALSO
* [trivy](trivy.md) - Unified security scanner
###### Auto generated by spf13/cobra on 16-Mar-2023
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.