From 819d8edef8ffe6b2179658674c06747fdbfe2eda Mon Sep 17 00:00:00 2001 From: kyledong-suse Date: Thu, 16 Jan 2025 14:22:31 -0500 Subject: [PATCH] NVSHAS-9584: Add package github.com/coreos/clair 1. Add upstream package github.com/coreos/clair 2. Update usage for tar functions based on neuvector repo's change --- common/db.go | 2 +- cvetools/cvesearch.go | 3 +- cvetools/image.go | 18 +- go.mod | 1 + go.sum | 2 + vendor/github.com/coreos/clair/LICENSE | 202 ++++++++++++++++++ vendor/github.com/coreos/clair/NOTICE | 5 + .../coreos/clair/pkg/tarutil/tarutil.go | 190 ++++++++++++++++ vendor/modules.txt | 3 + 9 files changed, 412 insertions(+), 14 deletions(-) create mode 100644 vendor/github.com/coreos/clair/LICENSE create mode 100644 vendor/github.com/coreos/clair/NOTICE create mode 100644 vendor/github.com/coreos/clair/pkg/tarutil/tarutil.go diff --git a/common/db.go b/common/db.go index ef74749b..f281536c 100644 --- a/common/db.go +++ b/common/db.go @@ -721,7 +721,7 @@ func unzipDb(path, desPath string, encryptKey []byte) error { } tarFile := bytes.NewReader(plainData) - err = utils.ExtractAllArchiveToFiles(desPath, tarFile, maxExtractSize, nil) + err = utils.ExtractAllArchiveToFiles(desPath, tarFile, nil) if err != nil { log.WithFields(log.Fields{"error": err}).Error("Extract db file error") return err diff --git a/cvetools/cvesearch.go b/cvetools/cvesearch.go index 4648502e..2efe6ed7 100644 --- a/cvetools/cvesearch.go +++ b/cvetools/cvesearch.go @@ -28,7 +28,6 @@ import ( ) const ( - maxFileSize = 300 * 1024 * 1024 contentManifest = "root/buildinfo/content_manifests" ) @@ -144,7 +143,7 @@ func (cv *ScanTools) ScanImageData(data *share.ScanData) (*share.ScanResult, err pkgs, err := utils.SelectivelyExtractArchive(bytes.NewReader(data.Buffer), func(filename string) bool { return true - }, maxFileSize) + }) if err != nil { log.WithFields(log.Fields{"error": err}).Error("read file error") return result, err diff --git a/cvetools/image.go b/cvetools/image.go index f00c28a6..eeade3ea 100644 --- a/cvetools/image.go +++ b/cvetools/image.go @@ -25,6 +25,7 @@ import ( "github.com/neuvector/neuvector/share/scan/registry" "github.com/neuvector/neuvector/share/scan/secrets" "github.com/neuvector/neuvector/share/utils" + "github.com/coreos/clair/pkg/tarutil" ) const ( @@ -334,13 +335,8 @@ func getImageLayers(tmpDir string, imageTar string) ([]string, map[string]string defer reader.Close() //get the manifest from the image tar - files, _ := utils.SelectivelyExtractArchive(bufio.NewReader(reader), func(filename string) bool { - if filename == manifestJson || strings.HasSuffix(filename, layerJson) || filename == ociLayout { - return true - } else { - return false - } - }, maxFileSize) + filenames := []string{manifestJson, layerJson, ociLayout} + files, _ := tarutil.ExtractFiles(bufio.NewReader(reader), filenames) // https://github.com/opencontainers/image-spec/blob/main/image-layout.md // Optional: Following the index.json to find a manifest @@ -447,7 +443,7 @@ func getImageLayerIterate( size = info.Size } - pathMap, err := selectiveFilesFromPath(layerPath, maxFileSize, func(path, fullpath string) bool { + pathMap, err := selectiveFilesFromPath(layerPath, func(path, fullpath string) bool { if scan.OSPkgFiles.Contains(path) || scan.IsAppsPkgFile(path, fullpath) { return true } @@ -621,7 +617,7 @@ func downloadLayers(ctx context.Context, layers []string, sizes map[string]int64 break } - size, err = utils.ExtractAllArchive(layerPath, rd.(io.ReadCloser), -1) + size, err = utils.ExtractAllArchive(layerPath, rd.(io.ReadCloser)) if err != nil { log.WithFields(log.Fields{"error": err, "path": layerPath}).Error("Failed to unzip image") os.RemoveAll(layerPath) @@ -648,7 +644,7 @@ func downloadLayers(ctx context.Context, layers []string, sizes map[string]int64 // selectiveFilesFromPath the specified files and folders // store them in a map indexed by file paths -func selectiveFilesFromPath(rootPath string, maxFileSize int64, selected func(string, string) bool) (map[string]string, error) { +func selectiveFilesFromPath(rootPath string, selected func(string, string) bool) (map[string]string, error) { rootLen := len(filepath.Clean(rootPath)) data := make(map[string]string) @@ -660,7 +656,7 @@ func selectiveFilesFromPath(rootPath string, maxFileSize int64, selected func(st } if !info.IsDir() { - if info.Mode().IsRegular() && (maxFileSize > 0 && info.Size() < maxFileSize) { + if info.Mode().IsRegular() && (info.Size() < tarutil.MaxExtractableFileSize) { inpath := path[(rootLen + 1):] // remove the root "/" if selected(inpath, path) { data[inpath] = path diff --git a/go.mod b/go.mod index c07df5cc..84a522cf 100644 --- a/go.mod +++ b/go.mod @@ -35,6 +35,7 @@ require ( github.com/containerd/ttrpc v1.2.4 // indirect github.com/containerd/typeurl v1.0.3-0.20220422153119-7f6e6d160d67 // indirect github.com/containerd/typeurl/v2 v2.1.1 // indirect + github.com/coreos/clair v2.1.0+incompatible // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/distribution/reference v0.5.0 // indirect github.com/docker/distribution v2.8.3+incompatible // indirect diff --git a/go.sum b/go.sum index 588cf004..04de46fc 100644 --- a/go.sum +++ b/go.sum @@ -45,6 +45,8 @@ github.com/containerd/typeurl v1.0.3-0.20220422153119-7f6e6d160d67 h1:rQvjv7gRi6 github.com/containerd/typeurl v1.0.3-0.20220422153119-7f6e6d160d67/go.mod h1:HDkcKOXRnX6yKnXv3P0QrogFi0DoiauK/LpQi961f0A= github.com/containerd/typeurl/v2 v2.1.1 h1:3Q4Pt7i8nYwy2KmQWIw2+1hTvwTE/6w9FqcttATPO/4= github.com/containerd/typeurl/v2 v2.1.1/go.mod h1:IDp2JFvbwZ31H8dQbEIY7sDl2L3o3HZj1hsSQlywkQ0= +github.com/coreos/clair v2.1.0+incompatible h1:lY0fTAGneYxXfq0j2vM+Xxip30XBzSn2tzSolAwkMnc= +github.com/coreos/clair v2.1.0+incompatible/go.mod h1:uXhHPWAoRqw0jJc2f8RrPCwRhIo9otQ8OEWUFtpCiwA= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= diff --git a/vendor/github.com/coreos/clair/LICENSE b/vendor/github.com/coreos/clair/LICENSE new file mode 100644 index 00000000..e06d2081 --- /dev/null +++ b/vendor/github.com/coreos/clair/LICENSE @@ -0,0 +1,202 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/vendor/github.com/coreos/clair/NOTICE b/vendor/github.com/coreos/clair/NOTICE new file mode 100644 index 00000000..e520005c --- /dev/null +++ b/vendor/github.com/coreos/clair/NOTICE @@ -0,0 +1,5 @@ +CoreOS Project +Copyright 2015 CoreOS, Inc + +This product includes software developed at CoreOS, Inc. +(http://www.coreos.com/). diff --git a/vendor/github.com/coreos/clair/pkg/tarutil/tarutil.go b/vendor/github.com/coreos/clair/pkg/tarutil/tarutil.go new file mode 100644 index 00000000..357f96da --- /dev/null +++ b/vendor/github.com/coreos/clair/pkg/tarutil/tarutil.go @@ -0,0 +1,190 @@ +// Copyright 2017 clair authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package tarutil implements some tar utility functions. +package tarutil + +import ( + "archive/tar" + "bufio" + "bytes" + "compress/bzip2" + "compress/gzip" + "errors" + "io" + "io/ioutil" + "os/exec" + "strings" +) + +var ( + // ErrCouldNotExtract occurs when an extraction fails. + ErrCouldNotExtract = errors.New("tarutil: could not extract the archive") + + // ErrExtractedFileTooBig occurs when a file to extract is too big. + ErrExtractedFileTooBig = errors.New("tarutil: could not extract one or more files from the archive: file too big") + + // MaxExtractableFileSize enforces the maximum size of a single file within a + // tarball that will be extracted. This protects against malicious files that + // may used in an attempt to perform a Denial of Service attack. + MaxExtractableFileSize int64 = 200 * 1024 * 1024 // 200 MiB + + readLen = 6 // max bytes to sniff + gzipHeader = []byte{0x1f, 0x8b} + bzip2Header = []byte{0x42, 0x5a, 0x68} + xzHeader = []byte{0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00} +) + +// FilesMap is a map of files' paths to their contents. +type FilesMap map[string][]byte + +// ExtractFiles decompresses and extracts only the specified files from an +// io.Reader representing an archive. +func ExtractFiles(r io.Reader, filenames []string) (FilesMap, error) { + data := make(map[string][]byte) + + // Decompress the archive. + tr, err := NewTarReadCloser(r) + if err != nil { + return data, ErrCouldNotExtract + } + defer tr.Close() + + // For each element in the archive + for { + hdr, err := tr.Next() + if err == io.EOF { + break + } + if err != nil { + return data, ErrCouldNotExtract + } + + // Get element filename + filename := hdr.Name + filename = strings.TrimPrefix(filename, "./") + + // Determine if we should extract the element + toBeExtracted := false + for _, s := range filenames { + if strings.HasPrefix(filename, s) { + toBeExtracted = true + break + } + } + + if toBeExtracted { + // File size limit + if hdr.Size > MaxExtractableFileSize { + return data, ErrExtractedFileTooBig + } + + // Extract the element + if hdr.Typeflag == tar.TypeSymlink || hdr.Typeflag == tar.TypeLink || hdr.Typeflag == tar.TypeReg { + d, _ := ioutil.ReadAll(tr) + data[filename] = d + } + } + } + + return data, nil +} + +// XzReader implements io.ReadCloser for data compressed via `xz`. +type XzReader struct { + io.ReadCloser + cmd *exec.Cmd + closech chan error +} + +// NewXzReader returns an io.ReadCloser by executing a command line `xz` +// executable to decompress the provided io.Reader. +// +// It is the caller's responsibility to call Close on the XzReader when done. +func NewXzReader(r io.Reader) (*XzReader, error) { + rpipe, wpipe := io.Pipe() + ex, err := exec.LookPath("xz") + if err != nil { + return nil, err + } + cmd := exec.Command(ex, "--decompress", "--stdout") + + closech := make(chan error) + + cmd.Stdin = r + cmd.Stdout = wpipe + + go func() { + err := cmd.Run() + wpipe.CloseWithError(err) + closech <- err + }() + + return &XzReader{rpipe, cmd, closech}, nil +} + +// Close cleans up the resources used by an XzReader. +func (r *XzReader) Close() error { + r.ReadCloser.Close() + r.cmd.Process.Kill() + return <-r.closech +} + +// TarReadCloser embeds a *tar.Reader and the related io.Closer +// It is the caller's responsibility to call Close on TarReadCloser when +// done. +type TarReadCloser struct { + *tar.Reader + io.Closer +} + +// Close cleans up the resources used by a TarReadCloser. +func (r *TarReadCloser) Close() error { + return r.Closer.Close() +} + +// NewTarReadCloser attempts to detect the compression algorithm for an +// io.Reader and returns a TarReadCloser wrapping the Reader to transparently +// decompress the contents. +// +// Gzip/Bzip2/XZ detection is done by using the magic numbers: +// Gzip: the first two bytes should be 0x1f and 0x8b. Defined in the RFC1952. +// Bzip2: the first three bytes should be 0x42, 0x5a and 0x68. No RFC. +// XZ: the first three bytes should be 0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00. No RFC. +func NewTarReadCloser(r io.Reader) (*TarReadCloser, error) { + br := bufio.NewReader(r) + header, err := br.Peek(readLen) + if err == nil { + switch { + case bytes.HasPrefix(header, gzipHeader): + gr, err := gzip.NewReader(br) + if err != nil { + return nil, err + } + return &TarReadCloser{tar.NewReader(gr), gr}, nil + case bytes.HasPrefix(header, bzip2Header): + bzip2r := ioutil.NopCloser(bzip2.NewReader(br)) + return &TarReadCloser{tar.NewReader(bzip2r), bzip2r}, nil + case bytes.HasPrefix(header, xzHeader): + xzr, err := NewXzReader(br) + if err != nil { + return nil, err + } + return &TarReadCloser{tar.NewReader(xzr), xzr}, nil + } + } + + dr := ioutil.NopCloser(br) + return &TarReadCloser{tar.NewReader(dr), dr}, nil +} diff --git a/vendor/modules.txt b/vendor/modules.txt index a2593304..1a4f97dd 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -165,6 +165,9 @@ github.com/containerd/typeurl # github.com/containerd/typeurl/v2 v2.1.1 ## explicit; go 1.13 github.com/containerd/typeurl/v2 +# github.com/coreos/clair v2.1.0+incompatible +## explicit +github.com/coreos/clair/pkg/tarutil # github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc ## explicit github.com/davecgh/go-spew/spew