mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-26 06:37:07 +00:00
fix(trivy): unpack npm tarballs before scanning
Trivy does not read archives, so a bare npm tarball always scanned clean. The scanner now extracts the tarball into node_modules/<name> in a temp dir and runs trivy rootfs on it, so the node-pkg analyzer sees the package.json. Extraction rejects absolute paths, parent segments and links that leave the tree, and caps the unpacked size at 512 MiB. The temp dir is removed after the scan. PyPI wheels and Go module zips share the archive problem and need their own extractors. This commit does not change them.
This commit is contained in:
@@ -0,0 +1,164 @@
|
|||||||
|
package trivy
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/tar"
|
||||||
|
"compress/gzip"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// maxExtractBytes caps the unpacked size so a compressed bomb cannot fill the disk.
|
||||||
|
const maxExtractBytes int64 = 512 << 20
|
||||||
|
|
||||||
|
var errTooLarge = errors.New("archive exceeds the extraction size limit")
|
||||||
|
|
||||||
|
// unpackNPM extracts an npm tarball into root/node_modules/<name>, the layout trivy's node-pkg
|
||||||
|
// analyzer reads. It returns root, which the caller must remove.
|
||||||
|
func unpackNPM(archive, name string) (root string, err error) {
|
||||||
|
if !validPackageName(name) {
|
||||||
|
return "", fmt.Errorf("unsafe package name %q", name)
|
||||||
|
}
|
||||||
|
root, err = os.MkdirTemp("", "trivy-npm-*")
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
if err != nil {
|
||||||
|
_ = os.RemoveAll(root)
|
||||||
|
root = ""
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
dest := filepath.Join(root, "node_modules", filepath.FromSlash(name))
|
||||||
|
if err = os.MkdirAll(dest, 0o750); err != nil {
|
||||||
|
return root, err
|
||||||
|
}
|
||||||
|
err = extractTarball(archive, dest)
|
||||||
|
return root, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func validPackageName(name string) bool {
|
||||||
|
if name == "" || strings.Contains(name, "\\") || !filepath.IsLocal(name) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, seg := range strings.Split(name, "/") {
|
||||||
|
if seg == ".." || seg == "." || seg == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// extractTarball unpacks a .tgz into dest, dropping the top-level directory. Links are never
|
||||||
|
// created; escaping ones are rejected outright.
|
||||||
|
func extractTarball(archive, dest string) error {
|
||||||
|
f, err := os.Open(archive) // #nosec G304 -- path from the cache, not user input
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func() { _ = f.Close() }()
|
||||||
|
gz, err := gzip.NewReader(f)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("open gzip: %w", err)
|
||||||
|
}
|
||||||
|
defer func() { _ = gz.Close() }()
|
||||||
|
|
||||||
|
tr := tar.NewReader(gz)
|
||||||
|
var total int64
|
||||||
|
for {
|
||||||
|
hdr, err := tr.Next()
|
||||||
|
if errors.Is(err, io.EOF) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("read tar: %w", err)
|
||||||
|
}
|
||||||
|
rel, err := entryPath(hdr.Name)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
switch hdr.Typeflag {
|
||||||
|
case tar.TypeDir:
|
||||||
|
if rel == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(filepath.Join(dest, rel), 0o750); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
case tar.TypeReg:
|
||||||
|
if rel == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
n, err := writeEntry(filepath.Join(dest, rel), tr, maxExtractBytes-total)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
total += n
|
||||||
|
case tar.TypeSymlink, tar.TypeLink:
|
||||||
|
if err := checkLink(hdr); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// entryPath validates a tar entry name and strips its first segment.
|
||||||
|
func entryPath(name string) (string, error) {
|
||||||
|
clean := strings.ReplaceAll(name, "\\", "/")
|
||||||
|
if strings.HasPrefix(clean, "/") {
|
||||||
|
return "", fmt.Errorf("absolute path in archive: %q", name)
|
||||||
|
}
|
||||||
|
for _, seg := range strings.Split(clean, "/") {
|
||||||
|
if seg == ".." {
|
||||||
|
return "", fmt.Errorf("path traversal in archive: %q", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
segs := strings.Split(path.Clean(clean), "/")
|
||||||
|
if len(segs) < 2 {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
rel := filepath.FromSlash(strings.Join(segs[1:], "/"))
|
||||||
|
if !filepath.IsLocal(rel) {
|
||||||
|
return "", fmt.Errorf("unsafe path in archive: %q", name)
|
||||||
|
}
|
||||||
|
return rel, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkLink(hdr *tar.Header) error {
|
||||||
|
target := strings.ReplaceAll(hdr.Linkname, "\\", "/")
|
||||||
|
if strings.HasPrefix(target, "/") {
|
||||||
|
return fmt.Errorf("absolute link target in archive: %q -> %q", hdr.Name, hdr.Linkname)
|
||||||
|
}
|
||||||
|
base := path.Dir(hdr.Name)
|
||||||
|
if hdr.Typeflag == tar.TypeLink {
|
||||||
|
base = "."
|
||||||
|
}
|
||||||
|
joined := path.Join(base, target)
|
||||||
|
if joined == ".." || strings.HasPrefix(joined, "../") {
|
||||||
|
return fmt.Errorf("link escapes the archive: %q -> %q", hdr.Name, hdr.Linkname)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeEntry copies at most limit bytes and fails when the entry is larger.
|
||||||
|
func writeEntry(dst string, r io.Reader, limit int64) (int64, error) {
|
||||||
|
if err := os.MkdirAll(filepath.Dir(dst), 0o750); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) // #nosec G304 -- dst validated by entryPath
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
n, err := io.Copy(out, io.LimitReader(r, limit+1))
|
||||||
|
if cerr := out.Close(); err == nil {
|
||||||
|
err = cerr
|
||||||
|
}
|
||||||
|
if err == nil && n > limit {
|
||||||
|
err = errTooLarge
|
||||||
|
}
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
@@ -110,15 +110,23 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
|||||||
defer cancel()
|
defer cancel()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Determine scan type based on registry
|
|
||||||
scanType := s.determineScanType(registry, filePath)
|
scanType := s.determineScanType(registry, filePath)
|
||||||
|
target := filePath
|
||||||
|
if registry == "npm" {
|
||||||
|
// trivy does not unpack archives; the node-pkg analyzer needs an installed tree.
|
||||||
|
root, err := unpackNPM(filePath, packageName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("prepare npm package for trivy: %w", err)
|
||||||
|
}
|
||||||
|
defer func() { _ = os.RemoveAll(root) }()
|
||||||
|
target = root
|
||||||
|
}
|
||||||
|
|
||||||
// Build Trivy command
|
|
||||||
args := []string{
|
args := []string{
|
||||||
scanType,
|
scanType,
|
||||||
"--format", "json",
|
"--format", "json",
|
||||||
"--quiet",
|
"--quiet",
|
||||||
filePath,
|
target,
|
||||||
}
|
}
|
||||||
|
|
||||||
cmd := exec.CommandContext(ctx, "trivy", args...) // #nosec G204 -- trivy command with controlled arguments
|
cmd := exec.CommandContext(ctx, "trivy", args...) // #nosec G204 -- trivy command with controlled arguments
|
||||||
@@ -166,7 +174,7 @@ func (s *Scanner) determineScanType(registry, filePath string) string {
|
|||||||
|
|
||||||
switch registry {
|
switch registry {
|
||||||
case "npm":
|
case "npm":
|
||||||
return "fs" // Filesystem scan for npm packages
|
return "rootfs" // rootfs enables the node-pkg analyzer; fs reads lockfiles only
|
||||||
case "pypi":
|
case "pypi":
|
||||||
return "fs" // Filesystem scan for Python packages
|
return "fs" // Filesystem scan for Python packages
|
||||||
case "go":
|
case "go":
|
||||||
|
|||||||
@@ -1,7 +1,14 @@
|
|||||||
package trivy
|
package trivy
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"archive/tar"
|
||||||
|
"bytes"
|
||||||
|
"compress/gzip"
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -16,9 +23,129 @@ import (
|
|||||||
func TestScanTimeoutIsAnInfrastructureErrorResult(t *testing.T) {
|
func TestScanTimeoutIsAnInfrastructureErrorResult(t *testing.T) {
|
||||||
scannertest.Script(t, "trivy", "exec sleep 5")
|
scannertest.Script(t, "trivy", "exec sleep 5")
|
||||||
|
|
||||||
res, err := New(config.TrivyConfig{Timeout: 100 * time.Millisecond}).Scan(context.Background(), "npm", "p", "1", "/x")
|
res, err := New(config.TrivyConfig{Timeout: 100 * time.Millisecond}).Scan(context.Background(), "pypi", "p", "1", "/x")
|
||||||
|
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.Equal(t, metadata.ScanStatusError, res.Status)
|
assert.Equal(t, metadata.ScanStatusError, res.Status)
|
||||||
assert.Equal(t, true, res.Details[scanerr.DetailInfrastructure])
|
assert.Equal(t, true, res.Details[scanerr.DetailInfrastructure])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type entry struct {
|
||||||
|
name, body, link string
|
||||||
|
typeflag byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func tgz(t *testing.T, entries ...entry) string {
|
||||||
|
t.Helper()
|
||||||
|
var buf bytes.Buffer
|
||||||
|
gz := gzip.NewWriter(&buf)
|
||||||
|
tw := tar.NewWriter(gz)
|
||||||
|
for _, e := range entries {
|
||||||
|
tf := e.typeflag
|
||||||
|
if tf == 0 {
|
||||||
|
tf = tar.TypeReg
|
||||||
|
}
|
||||||
|
hdr := &tar.Header{Name: e.name, Typeflag: tf, Mode: 0o644, Linkname: e.link}
|
||||||
|
if tf == tar.TypeReg {
|
||||||
|
hdr.Size = int64(len(e.body))
|
||||||
|
}
|
||||||
|
require.NoError(t, tw.WriteHeader(hdr))
|
||||||
|
if tf == tar.TypeReg {
|
||||||
|
_, err := tw.Write([]byte(e.body))
|
||||||
|
require.NoError(t, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
require.NoError(t, tw.Close())
|
||||||
|
require.NoError(t, gz.Close())
|
||||||
|
p := filepath.Join(t.TempDir(), "p.tgz")
|
||||||
|
require.NoError(t, os.WriteFile(p, buf.Bytes(), 0o600))
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNPMScanRunsRootfsOnUnpackedTree(t *testing.T) {
|
||||||
|
rec := t.TempDir()
|
||||||
|
scannertest.Script(t, "trivy", fmt.Sprintf(`
|
||||||
|
printf '%%s\n' "$@" > %[1]q/args
|
||||||
|
for last; do :; done
|
||||||
|
cp "$last/node_modules/@scope/pkg/package.json" %[1]q/package.json
|
||||||
|
echo "$last" > %[1]q/root
|
||||||
|
echo '{"Results":[]}'`, rec))
|
||||||
|
archive := tgz(t,
|
||||||
|
entry{name: "package/", typeflag: tar.TypeDir},
|
||||||
|
entry{name: "package/package.json", body: `{"name":"@scope/pkg"}`},
|
||||||
|
entry{name: "package/lib/index.js", body: "x"},
|
||||||
|
)
|
||||||
|
|
||||||
|
res, err := New(config.TrivyConfig{}).Scan(context.Background(), "npm", "@scope/pkg", "1.0.0", archive)
|
||||||
|
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, metadata.ScanStatusClean, res.Status)
|
||||||
|
args, err := os.ReadFile(filepath.Join(rec, "args")) // #nosec G304 -- test temp dir
|
||||||
|
require.NoError(t, err)
|
||||||
|
root, err := os.ReadFile(filepath.Join(rec, "root")) // #nosec G304 -- test temp dir
|
||||||
|
require.NoError(t, err)
|
||||||
|
lines := strings.Split(strings.TrimSpace(string(args)), "\n")
|
||||||
|
assert.Equal(t, []string{"rootfs", "--format", "json", "--quiet", strings.TrimSpace(string(root))}, lines)
|
||||||
|
pkg, err := os.ReadFile(filepath.Join(rec, "package.json")) // #nosec G304 -- test temp dir
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.JSONEq(t, `{"name":"@scope/pkg"}`, string(pkg))
|
||||||
|
_, err = os.Stat(strings.TrimSpace(string(root))) // #nosec G304 G703 -- path from the test fake
|
||||||
|
assert.True(t, os.IsNotExist(err), "temp tree must be removed")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNonNPMScansTheFileWithFS(t *testing.T) {
|
||||||
|
argsFile := scannertest.Fake(t, "trivy", "", "", 0)
|
||||||
|
_, err := New(config.TrivyConfig{}).Scan(context.Background(), "pypi", "p", "1", "/x/p.whl")
|
||||||
|
require.Error(t, err) // empty output is not JSON
|
||||||
|
assert.Equal(t, []string{"fs", "--format", "json", "--quiet", "/x/p.whl"}, scannertest.Args(t, argsFile))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExtractRejectsUnsafeArchives(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
entries []entry
|
||||||
|
}{
|
||||||
|
{"parent traversal", []entry{{name: "package/../../evil", body: "x"}}},
|
||||||
|
{"leading traversal", []entry{{name: "../evil", body: "x"}}},
|
||||||
|
{"absolute path", []entry{{name: "/etc/evil", body: "x"}}},
|
||||||
|
{"symlink to absolute", []entry{{name: "package/l", typeflag: tar.TypeSymlink, link: "/etc/passwd"}}},
|
||||||
|
{"symlink out of tree", []entry{{name: "package/l", typeflag: tar.TypeSymlink, link: "../../x"}}},
|
||||||
|
{"hardlink out of tree", []entry{{name: "package/l", typeflag: tar.TypeLink, link: "../x"}}},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
root, err := unpackNPM(tgz(t, tt.entries...), "pkg")
|
||||||
|
require.Error(t, err)
|
||||||
|
assert.Empty(t, root)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExtractSkipsInTreeLinksWithoutCreatingThem(t *testing.T) {
|
||||||
|
root, err := unpackNPM(tgz(t,
|
||||||
|
entry{name: "package/real.js", body: "x"},
|
||||||
|
entry{name: "package/l", typeflag: tar.TypeSymlink, link: "real.js"},
|
||||||
|
), "pkg")
|
||||||
|
require.NoError(t, err)
|
||||||
|
defer func() { _ = os.RemoveAll(root) }()
|
||||||
|
_, err = os.Lstat(filepath.Join(root, "node_modules", "pkg", "l"))
|
||||||
|
assert.True(t, os.IsNotExist(err))
|
||||||
|
assert.FileExists(t, filepath.Join(root, "node_modules", "pkg", "real.js"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnpackRejectsUnsafePackageNames(t *testing.T) {
|
||||||
|
archive := tgz(t, entry{name: "package/package.json", body: "{}"})
|
||||||
|
for _, name := range []string{"", "..", "../x", "/abs", "a/../../b", `a\b`} {
|
||||||
|
_, err := unpackNPM(archive, name)
|
||||||
|
assert.Error(t, err, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExtractEnforcesSizeCap(t *testing.T) {
|
||||||
|
dest := t.TempDir()
|
||||||
|
_, err := writeEntry(filepath.Join(dest, "big"), strings.NewReader(strings.Repeat("a", 11)), 10)
|
||||||
|
require.ErrorIs(t, err, errTooLarge)
|
||||||
|
n, err := writeEntry(filepath.Join(dest, "ok"), strings.NewReader(strings.Repeat("a", 10)), 10)
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.EqualValues(t, 10, n)
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user