From 947eadd61258e2430fa1504ff1bda16cf6e1f4bc Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 03:23:57 +0000 Subject: [PATCH 1/5] sshole: a never-checked finding no longer reads as already fixed repo.Find took any finding missing on rescan as gone, so fix (and Sensei's /fix, which copies this package) reported it as already fixed even when it was never checked or could not be checked this time. It now returns gone only when the rescan checked what the scan reported, and otherwise declines with "rescan to confirm": - a not-checked finding (a skipped file, an unresolved image, a Buildroot file with no C library) that is no longer on its line, naming the finding there now when the reference resolves to a vulnerable pin; - a file that cannot be read this time (oversized, not a regular file), and a missing file for a not-checked finding; - a line past the end of the file; - an apk, end-of-life or build finding whose line is not checked this time (the base image lookup failed, the FROM is now an unset variable); - a Yocto finding when a build file the rescan needs cannot be read. A checked finding that is gone from its line, or whose file is deleted, still reads as gone. Plan returned already=true for a line past the end of the file, and fix skipped it silently; it declines now, and the always-false result is gone. An unset variable in FROM (ARG BASE / FROM ${BASE}) expanded to an empty image name, which reads as scratch, so an apk install of OpenSSH on it was not reported at all. It is kept as written now and reported as not checked. Co-Authored-By: Claude Opus 5.5 --- detectors/sshole/internal/repo/more_test.go | 11 +- .../sshole/internal/repo/notchecked_test.go | 196 ++++++++++++++++++ detectors/sshole/internal/repo/plan.go | 131 ++++++++---- detectors/sshole/internal/repo/repo.go | 5 + detectors/sshole/internal/repo/repo_test.go | 12 +- detectors/sshole/repo.go | 7 +- 6 files changed, 304 insertions(+), 58 deletions(-) create mode 100644 detectors/sshole/internal/repo/notchecked_test.go diff --git a/detectors/sshole/internal/repo/more_test.go b/detectors/sshole/internal/repo/more_test.go index 35c05f1..25d6de6 100644 --- a/detectors/sshole/internal/repo/more_test.go +++ b/detectors/sshole/internal/repo/more_test.go @@ -22,10 +22,7 @@ func fixAll(t *testing.T, root string) []Finding { if !f.Fixable { continue } - ch, already, err := Plan(ctx, root, f, Options{}) - if already { - continue - } + ch, err := Plan(ctx, root, f, Options{}) if err != nil { t.Fatalf("%s:%d %s: %v", f.File, f.Line, f.Rule, err) } @@ -212,7 +209,7 @@ func TestYoctoPatchFix(t *testing.T) { if acme == nil || !acme.Fixable || two == nil || two.Fixable || !strings.Contains(two.Fix, "different openssh versions") { t.Fatalf("%+v\n%+v", acme, two) } - ch, _, err := Plan(context.Background(), root, *acme, Options{}) + ch, err := Plan(context.Background(), root, *acme, Options{}) if err != nil { t.Fatal(err) } @@ -274,7 +271,7 @@ func TestAlpineRetag(t *testing.T) { if len(fs) != 1 || !fs[0].Fixable || fs[0].Props["upgrade"] != "python:3.9-alpine3.16" { t.Fatalf("%+v", fs) } - ch, _, err := Plan(context.Background(), root, fs[0], opts) + ch, err := Plan(context.Background(), root, fs[0], opts) if err != nil || ch.Edits[0].New != "FROM python:3.9-alpine3.16" { t.Fatalf("%v %+v", err, ch) } @@ -353,7 +350,7 @@ func TestBuildrootGitPatchDir(t *testing.T) { if len(fs) != 1 { t.Fatalf("%+v", fs) } - if _, _, err := Plan(context.Background(), root, fs[0], Options{}); err == nil || !strings.Contains(err.Error(), ".git") { + if _, err := Plan(context.Background(), root, fs[0], Options{}); err == nil || !strings.Contains(err.Error(), ".git") { t.Fatalf("%v", err) } } diff --git a/detectors/sshole/internal/repo/notchecked_test.go b/detectors/sshole/internal/repo/notchecked_test.go new file mode 100644 index 0000000..e47d3ca --- /dev/null +++ b/detectors/sshole/internal/repo/notchecked_test.go @@ -0,0 +1,196 @@ +package repo + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +// A finding that was not checked, or that cannot be checked again now, is +// never "gone": Find declines with "rescan to confirm" instead, so a fix +// does not report it as already fixed. + +var ( + alpine321 = Options{Base: func(context.Context, string) (bool, string, error) { return true, "3.21", nil }} + baseDown = Options{Base: func(context.Context, string) (bool, string, error) { return false, "", errors.New("denied") }} +) + +// mustDecline fails unless Find declined, naming what was not checked. +func mustDecline(t *testing.T, what string, f *Finding, gone bool, err error) { + t.Helper() + d, ok := IsDeclined(err) + if gone || f != nil || !ok { + t.Fatalf("%s: want a decline, got finding %+v, gone %v, err %v", what, f, gone, err) + } + if !strings.Contains(d.Reason, "rescan to confirm") { + t.Errorf("%s: reason %q does not say rescan to confirm", what, d.Reason) + } +} + +func findOne(t *testing.T, root string, opts Options, rule string) Finding { + t.Helper() + fs := scan(t, root, opts) + if len(fs) != 1 || fs[0].Rule != rule { + t.Fatalf("want one %s finding, got %+v", rule, fs) + } + return fs[0] +} + +func TestFindSkippedFile(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + big := "FROM alpine:3.22\nRUN apk add openssh-server\n" + strings.Repeat("#\n", maxFileSize/2) + write(t, root, "Dockerfile", big) + res, err := Scan(ctx, root, Options{}) + if err != nil || len(res.Skips) != 1 || len(res.Findings) != 0 { + t.Fatalf("%v %+v", err, res) + } + // A skip reaches a report as a not-checked finding on its file. The + // file is still too large, then gone, then readable with nothing in + // it: none of these checked what the skip left out. + sk := res.Skips[0] + f, gone, err := Find(ctx, root, sk.File, 0, RuleNotChecked, sk.Reason, Options{}) + mustDecline(t, "still oversized", f, gone, err) + os.Remove(filepath.Join(root, "Dockerfile")) + f, gone, err = Find(ctx, root, sk.File, 0, RuleNotChecked, sk.Reason, Options{}) + mustDecline(t, "removed", f, gone, err) + write(t, root, "Dockerfile", "FROM alpine:3.22\n") + f, gone, err = Find(ctx, root, sk.File, 0, RuleNotChecked, sk.Reason, Options{}) + mustDecline(t, "readable now", f, gone, err) +} + +func TestFindFileUnreadableNow(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + write(t, root, "Dockerfile", "FROM alpine:3.22\nRUN usermod -p '*' bob\n") + star := findOne(t, root, Options{}, RuleStar) + // Oversized this time. + write(t, root, "Dockerfile", "FROM alpine:3.22\nRUN usermod -p '*' bob\n"+strings.Repeat("#\n", maxFileSize/2)) + f, gone, err := Find(ctx, root, "Dockerfile", star.Line, RuleStar, star.Message, Options{}) + mustDecline(t, "oversized", f, gone, err) + // Not a regular file this time. + os.Remove(filepath.Join(root, "Dockerfile")) + write(t, root, "real", "FROM alpine:3.22\n") + if err := os.Symlink("real", filepath.Join(root, "Dockerfile")); err != nil { + t.Fatal(err) + } + f, gone, err = Find(ctx, root, "Dockerfile", star.Line, RuleStar, star.Message, Options{}) + mustDecline(t, "symlink", f, gone, err) +} + +func TestFindUnresolvedImage(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + write(t, root, "Dockerfile", "FROM acme/base:1\nRUN apk add openssh-server=9.9_p1-r2\n") + pin := findOne(t, root, alpine321, RulePin) + // The base image cannot be read this time. + f, gone, err := Find(ctx, root, "Dockerfile", pin.Line, RulePin, pin.Message, baseDown) + mustDecline(t, "lookup failed", f, gone, err) + // The image is now an unresolved build argument. + write(t, root, "Dockerfile", "FROM ${BASE}\nRUN apk add openssh-server=9.9_p1-r2\n") + f, gone, err = Find(ctx, root, "Dockerfile", pin.Line, RulePin, pin.Message, alpine321) + mustDecline(t, "${BASE}", f, gone, err) +} + +func TestFindNotCheckedNowVulnerable(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + write(t, root, "Dockerfile", "FROM acme/base:1\nRUN apk add openssh-server=9.9_p1-r2\n") + nc := findOne(t, root, baseDown, RuleNotChecked) + // Still not checked: the same finding, not gone. + f, gone, err := Find(ctx, root, "Dockerfile", nc.Line, RuleNotChecked, nc.Message, baseDown) + if err != nil || gone || f == nil || f.Rule != RuleNotChecked { + t.Fatalf("still not checked: %+v %v %v", f, gone, err) + } + // The base resolves now, to Alpine with a vulnerable pin. + f, gone, err = Find(ctx, root, "Dockerfile", nc.Line, RuleNotChecked, nc.Message, alpine321) + mustDecline(t, "resolves to a pin", f, gone, err) + if d, _ := IsDeclined(err); !strings.Contains(d.Reason, RulePin) { + t.Errorf("decline does not name the finding there now: %q", d.Reason) + } +} + +func TestFindStaleLine(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + write(t, root, "Dockerfile", "FROM alpine:3.22\nRUN true\nRUN true\nRUN usermod -p '*' bob\n") + star := findOne(t, root, Options{}, RuleStar) + // The file was cut short: line 4 is past its end. + write(t, root, "Dockerfile", "FROM alpine:3.22\nRUN usermod -p '*' alice\n") + for _, msg := range []string{"", "a message that matches nothing"} { + f, gone, err := Find(ctx, root, "Dockerfile", star.Line, RuleStar, msg, Options{}) + mustDecline(t, "past the end, message "+msg, f, gone, err) + } + // Plan, between the scan and the fix, does not take it as fixed. + if ch, err := Plan(ctx, root, star, Options{}); ch != nil || err == nil { + t.Fatalf("plan of a stale line: %+v %v", ch, err) + } else if d, ok := IsDeclined(err); !ok || !strings.Contains(d.Reason, "rescan to confirm") { + t.Errorf("plan of a stale line: %v", err) + } +} + +func TestFindYoctoTreeUnreadable(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + write(t, root, "meta-a/conf/layer.conf", "LAYERSERIES_COMPAT_a = \"scarthgap\"\n") + write(t, root, "meta-a/conf/distro/a.conf", "TCLIBC = \"musl\"\n") + write(t, root, "meta-a/recipes-core/images/a.bb", "IMAGE_INSTALL:append = \" openssh\"\n") + b := findOne(t, root, Options{}, RuleBuild) + // The distro configuration that sets musl cannot be read this time. + write(t, root, "meta-a/conf/distro/a.conf", "TCLIBC = \"musl\"\n"+strings.Repeat("#\n", maxFileSize/2)) + f, gone, err := Find(ctx, root, b.File, b.Line, RuleBuild, b.Message, Options{}) + mustDecline(t, "distro conf oversized", f, gone, err) +} + +// What was checked and is really gone still reads as gone. +func TestFindCheckedAndGone(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + write(t, root, "Dockerfile", "FROM acme/base:1\nRUN apk add openssh-server=9.9_p1-r2 && usermod -p '*' bob\n") + fs := scan(t, root, alpine321) + if len(fs) != 2 || fs[0].Rule == fs[1].Rule { + t.Fatalf("%+v", fs) + } + star := fs[0] + if star.Rule != RuleStar { + star = fs[1] + } + write(t, root, "Dockerfile", "FROM acme/base:1\nRUN apk add 'openssh-server>=9.9_p2-r1' && usermod -p '*NP*' bob\n") + for _, g := range fs { + f, gone, err := Find(ctx, root, g.File, g.Line, g.Rule, g.Message, alpine321) + if err != nil || !gone || f != nil { + t.Errorf("%s: %+v %v %v", g.Rule, f, gone, err) + } + } + // The star field is checked without the base image: a failed lookup + // does not hold it back. + f, gone, err := Find(ctx, root, "Dockerfile", star.Line, RuleStar, star.Message, baseDown) + if err != nil || !gone || f != nil { + t.Errorf("star with the lookup down: %+v %v %v", f, gone, err) + } + // A deleted file has no findings left. + os.Remove(filepath.Join(root, "Dockerfile")) + if f, gone, err := Find(ctx, root, "Dockerfile", star.Line, RuleStar, star.Message, Options{}); err != nil || !gone || f != nil { + t.Errorf("deleted: %+v %v %v", f, gone, err) + } +} + +// An image the scan cannot resolve is not checked, not scratch. +func TestUnresolvedImageIsNotChecked(t *testing.T) { + for _, from := range []string{"ARG BASE\nFROM ${BASE}", "FROM $BASE", "FROM ${BASE:-}", "FROM {{ .Base }}"} { + root := t.TempDir() + write(t, root, "Dockerfile", from+"\nRUN apk add openssh-server\n") + if fs := scan(t, root, Options{}); len(fs) != 1 || fs[0].Rule != RuleNotChecked { + t.Errorf("%q: %+v", from, fs) + } + } + // A default still decides. + root := t.TempDir() + write(t, root, "Dockerfile", "FROM ${BASE:-debian:12}\nRUN apk add openssh-server\n") + if fs := scan(t, root, Options{}); len(fs) != 0 { + t.Errorf("default: %+v", fs) + } +} diff --git a/detectors/sshole/internal/repo/plan.go b/detectors/sshole/internal/repo/plan.go index b0a7ed5..19161f3 100644 --- a/detectors/sshole/internal/repo/plan.go +++ b/detectors/sshole/internal/repo/plan.go @@ -41,14 +41,15 @@ func IsDeclined(err error) (*Declined, bool) { // Plan builds the edit for a finding the scan reported at file:line with // rule and, for apk findings, props["package"]. It rescans the edited file // in memory and accepts the edit only when that finding is gone and nothing -// new appeared. already is true when the finding is no longer there. -func Plan(ctx context.Context, root string, f Finding, opts Options) (*Change, bool, error) { +// new appeared. A line that is no longer there declines: the file changed +// since the scan, and the finding is not checked again here. +func Plan(ctx context.Context, root string, f Finding, opts Options) (*Change, error) { if !f.Fixable || f.edit == nil && len(f.newFiles) == 0 { - return nil, false, &Declined{Reason: f.Fix} + return nil, &Declined{Reason: f.Fix} } for p, data := range f.newFiles { if err := checkNewPath(root, p, data); err != nil { - return nil, false, &Declined{Reason: err.Error() + "; add the fix by hand"} + return nil, &Declined{Reason: err.Error() + "; add the fix by hand"} } } if f.edit == nil { @@ -56,12 +57,12 @@ func Plan(ctx context.Context, root string, f Finding, opts Options) (*Change, b } b, err := readFile(root, f.File) if err != nil { - return nil, false, err + return nil, err } lines := strings.Split(string(b), "\n") e := *f.edit if e.Line < 1 || e.Line > len(lines) { - return nil, true, nil + return nil, notChecked("line %d is past the end of %s, which changed since the scan", e.Line, f.File) } line := strings.TrimSuffix(lines[e.Line-1], "\r") if e.Col < 0 || e.Col+len(e.Old) > len(line) || line[e.Col:e.Col+len(e.Old)] != e.Old { @@ -69,7 +70,7 @@ func Plan(ctx context.Context, root string, f Finding, opts Options) (*Change, b // the one finding that is still the same word, or decline. now, err := scanOne(ctx, root, f.File, opts, b) if err != nil { - return nil, false, err + return nil, err } var match *Edit n := 0 @@ -80,7 +81,7 @@ func Plan(ctx context.Context, root string, f Finding, opts Options) (*Change, b } } if n != 1 { - return nil, false, &Declined{Reason: fmt.Sprintf("%s:%d no longer reads as scanned", f.File, e.Line)} + return nil, &Declined{Reason: fmt.Sprintf("%s:%d no longer reads as scanned", f.File, e.Line)} } e = *match } @@ -101,24 +102,24 @@ func Plan(ctx context.Context, root string, f Finding, opts Options) (*Change, b } before, err := scanOne(ctx, root, f.File, opts, nil) if err != nil { - return nil, false, err + return nil, err } after, err := scanOne(ctx, root, f.File, o, o.Overlay[f.File]) if err != nil { - return nil, false, err + return nil, err } if count(after, f.Rule, f.Line) >= count(before, f.Rule, f.Line) { - return nil, false, &Declined{Reason: "the edit did not clear the finding; change it by hand"} + return nil, &Declined{Reason: "the edit did not clear the finding; change it by hand"} } if len(after) > len(before) { - return nil, false, &Declined{Reason: "the edit raised a new finding; change it by hand"} + return nil, &Declined{Reason: "the edit raised a new finding; change it by hand"} } - return ch, false, nil + return ch, nil } // planNewFiles plans a fix that only adds files, checked by rescanning the // finding's file with the files in place. -func planNewFiles(ctx context.Context, root string, f Finding, opts Options) (*Change, bool, error) { +func planNewFiles(ctx context.Context, root string, f Finding, opts Options) (*Change, error) { o := opts o.Overlay = map[string][]byte{} for p, data := range f.newFiles { @@ -126,42 +127,49 @@ func planNewFiles(ctx context.Context, root string, f Finding, opts Options) (*C } before, err := scanOne(ctx, root, f.File, opts, nil) if err != nil { - return nil, false, err + return nil, err } after, err := scanOne(ctx, root, f.File, o, nil) if err != nil { - return nil, false, err + return nil, err } if count(after, f.Rule, f.Line) >= count(before, f.Rule, f.Line) { - return nil, false, &Declined{Reason: "the added files did not clear the finding; add the fix by hand"} + return nil, &Declined{Reason: "the added files did not clear the finding; add the fix by hand"} } - return &Change{File: f.File, Summary: summary(f), NewFiles: f.newFiles}, false, nil + return &Change{File: f.File, Summary: summary(f), NewFiles: f.newFiles}, nil } func scanOne(ctx context.Context, root, file string, opts Options, data []byte) ([]Finding, error) { + fs, _, err := scanFile(ctx, root, file, opts, data) + return fs, err +} + +// scanFile is scanOne that also returns the other files the rescan needed +// and could not read: a Yocto finding joins files across the tree. +func scanFile(ctx context.Context, root, file string, opts Options, data []byte) ([]Finding, []Skip, error) { s := &scanner{ctx: ctx, root: root, opts: opts, bases: map[string]baseInfo{}} if data == nil { var err error if data, err = readFile(root, file); err != nil { - return nil, err + return nil, nil, err } } switch kindOf(file) { case "dockerfile": - return s.dockerfile(file, string(data)), nil + return s.dockerfile(file, string(data)), nil, nil case "shell": - return s.script(file, string(data)), nil + return s.script(file, string(data)), nil, nil case "yaml": - return s.yaml(file, string(data)), nil + return s.yaml(file, string(data)), nil, nil case "sshd_config": - return s.sshdConfig(file, string(data)), nil + return s.sshdConfig(file, string(data)), nil, nil case "build": // A Yocto finding needs the whole tree (TCLIBC and bbappends live // in other files): rescan it, keeping this file's findings. if s.yoctoNeedsTree(file) { res, err := Scan(ctx, root, opts) if err != nil { - return nil, err + return nil, nil, err } var out []Finding for _, f := range res.Findings { @@ -169,12 +177,21 @@ func scanOne(ctx context.Context, root, file string, opts Options, data []byte) out = append(out, f) } } - return out, nil + var unread []Skip + for _, sk := range res.Skips { + if kindOf(sk.File) == "build" { + unread = append(unread, sk) + } + } + if res.Truncated { + unread = append(unread, Skip{File: "the source tree", Reason: "too many files to walk"}) + } + return out, unread, nil } s.build(file, string(data)) - return s.finishBuild(), nil + return s.finishBuild(), nil, nil } - return nil, nil + return nil, nil, nil } func count(fs []Finding, rule string, line int) int { @@ -281,15 +298,22 @@ func Printable(s string) string { } // Find rescans one file and returns the finding with this rule at this -// line. spec, when not empty, picks between several on the line: the apk -// spec or the text the finding's message quotes. gone is true when the file -// has no such finding any more. +// line. message, when not empty, picks between several on the line: the apk +// spec or the text the finding's message quotes. gone is true only when +// this rescan checked what the scan reported and the finding is not there: +// a not-checked finding, a file or base image that cannot be read this +// time, or a line past the end of the file declines with "rescan to +// confirm" instead. func Find(ctx context.Context, root, file string, line int, rule, message string, opts Options) (f *Finding, gone bool, err error) { - fs, err := scanOne(ctx, root, file, opts, nil) + data, err := readFile(root, file) if err != nil { - if errors.Is(err, os.ErrNotExist) { - return nil, true, nil + if errors.Is(err, os.ErrNotExist) && rule != RuleNotChecked { + return nil, true, nil // the file is deleted, and its findings with it } + return nil, false, notChecked("%s could not be read (%v), so it is not checked", file, err) + } + fs, unread, err := scanFile(ctx, root, file, opts, data) + if err != nil { return nil, false, err } var at []Finding @@ -325,15 +349,42 @@ func Find(ctx context.Context, root, file string, line int, rule, message string return nil, false, &Declined{Reason: fmt.Sprintf("line %d of %s no longer has this finding and the file has %d like it; rescan and fix the new findings", line, file, len(moved))} } } - switch len(at) { - case 0: - return nil, true, nil - case 1: + if len(at) > 0 { + // Several identical findings on one line: the first; the rest + // come back on the next scan. return &at[0], false, nil } - // Several identical findings on one line: the first; the rest come - // back on the next scan. - return &at[0], false, nil + // Not there. That is "gone" only when the scan checked it and this + // rescan checked the same again. + switch { + case rule == RuleNotChecked: + now := "" + for _, g := range fs { + if g.Line == line && g.Level != "note" { + now = fmt.Sprintf(", and line %d now has %s (%s)", line, g.Rule, g.Message) + break + } + } + return nil, false, notChecked("%s:%d was not checked when it was scanned%s", file, line, now) + case len(unread) > 0: + return nil, false, notChecked("%s could not be read this time (%s), so %s is not checked", unread[0].File, unread[0].Reason, file) + case line > len(strings.Split(string(data), "\n")): + return nil, false, notChecked("line %d is past the end of %s, which changed since the scan", line, file) + case rule == RulePin || rule == RuleUnpinned || rule == RuleEOL || rule == RuleBuild: + // These depend on the base image or the C library: a not-checked + // finding on the line means this rescan could not judge it. + for _, g := range fs { + if g.Line == line && g.Rule == RuleNotChecked { + return nil, false, notChecked("line %d of %s is not checked this time (%s)", line, file, g.Message) + } + } + } + return nil, true, nil +} + +// notChecked declines a finding Find cannot confirm as gone. +func notChecked(format string, args ...any) error { + return &Declined{Reason: fmt.Sprintf(format, args...) + "; rescan to confirm"} } // WriteNewFiles writes files a change adds, refusing symbolic links on diff --git a/detectors/sshole/internal/repo/repo.go b/detectors/sshole/internal/repo/repo.go index a535b21..41d72db 100644 --- a/detectors/sshole/internal/repo/repo.go +++ b/detectors/sshole/internal/repo/repo.go @@ -523,6 +523,11 @@ func expand(s string, args map[string]string) string { if v, ok := args[name]; ok && v != "" { return v } + if sm[2] == "" { + // Unresolved: kept as written, so the image is not known + // (an empty name would read as scratch, nothing to check). + return m + } return sm[2] }) } diff --git a/detectors/sshole/internal/repo/repo_test.go b/detectors/sshole/internal/repo/repo_test.go index 69fa67c..481e383 100644 --- a/detectors/sshole/internal/repo/repo_test.go +++ b/detectors/sshole/internal/repo/repo_test.go @@ -119,9 +119,9 @@ func TestFixRoundTrip(t *testing.T) { if f.Level == "note" { continue } - ch, already, err := Plan(ctx, root, f, Options{}) - if already || err != nil { - t.Fatalf("%s:%d %s: %v %v", f.File, f.Line, f.Rule, already, err) + ch, err := Plan(ctx, root, f, Options{}) + if err != nil { + t.Fatalf("%s:%d %s: %v", f.File, f.Line, f.Rule, err) } if err := Apply(root, ch); err != nil { t.Fatal(err) @@ -153,7 +153,7 @@ func TestPlanDeclines(t *testing.T) { if len(fs) != 1 || fs[0].Fixable { t.Fatalf("alpine:latest offline should be reported but not fixable: %+v", fs) } - if _, _, err := Plan(context.Background(), root, fs[0], Options{}); err == nil { + if _, err := Plan(context.Background(), root, fs[0], Options{}); err == nil { t.Fatal("planned an edit with no branch") } else if _, ok := IsDeclined(err); !ok { t.Fatalf("not a decline: %v", err) @@ -166,12 +166,12 @@ func TestPlanDeclines(t *testing.T) { } // A file changed after the scan is not edited. write(t, root, "Dockerfile", "FROM alpine\nRUN apk add openssh-server-pam\n") - if _, _, err := Plan(context.Background(), root, fs[0], opts); err == nil { + if _, err := Plan(context.Background(), root, fs[0], opts); err == nil { t.Fatal("edited a changed line") } // A word that only moved is found again. write(t, root, "Dockerfile", "FROM alpine\nRUN apk add openssh-server\n") - if ch, _, err := Plan(context.Background(), root, fs[0], opts); err != nil || !strings.Contains(ch.Edits[0].New, "apk add 'openssh-server>=10.3_p1-r2'") { + if ch, err := Plan(context.Background(), root, fs[0], opts); err != nil || !strings.Contains(ch.Edits[0].New, "apk add 'openssh-server>=10.3_p1-r2'") { t.Fatalf("moved word: %v %+v", err, ch) } // A failed resolution leaves it unchecked. diff --git a/detectors/sshole/repo.go b/detectors/sshole/repo.go index 0c5f64a..5dbbab8 100644 --- a/detectors/sshole/repo.go +++ b/detectors/sshole/repo.go @@ -329,11 +329,8 @@ func (d *Detector) Fix(ctx context.Context, dirs []string, o engine.Options, std code = max(code, 1) continue } - ch, already, err := repo.Plan(ctx, dir, f, opts) - switch { - case already: - continue - case err != nil: + ch, err := repo.Plan(ctx, dir, f, opts) + if err != nil { fmt.Fprintf(stdout, "not fixed %s %s\n", where, repo.Printable(err.Error())) code = max(code, 1) continue From a83864a08adb31d7923aa0c4d3652b3a570fb74d Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 03:46:21 +0000 Subject: [PATCH 2/5] sshole: fixes from the review of the not-checked change Find: - Declines rules and files it never rescans (image, unknown rules, files the scanner does not read) instead of calling them gone. - Takes the package, the variable and the build system from the finding's message. A not-checked finding about any of them, anywhere in the file, holds the finding back; one about something else (an unset $EXTRA beside a fixed pin) no longer does. - Declines when the line still has a finding for the same package under another rule (eol-base and apk-unpinned when the lookup fails, a pin loosened to no floor), and when a build file still has its build finding, moved and reworded. - A Yocto finding is held back only by its own TCLIBC file, or a directory holding it, being unreadable (or the walk's limit), not by any oversized build file in the tree; an unreadable directory now counts. - Past the end of the file declines only while the file still has findings of that rule; otherwise the whole-file rescan settles it. - Messages stored with "set on line N" still match. Scanner: - A pin through a variable no longer puts a line number in its message. - FROM variables: an empty value or default expands to empty again (ARG REGISTRY= / ${REGISTRY:-}); an unset prefix before a complete image (${REGISTRY}alpine:3.21) is judged on the rest, with a note naming it; an unset optional suffix (python:${PY}${FLAVOR}) still resolves online; anything else, such as alpine:${MAJOR}.${MINOR}, is not known (it was a false end-of-life finding, and the last commit made it fixable). - ARG with no value is unset, not empty. Co-Authored-By: Claude Opus 5.5 --- detectors/sshole/internal/repo/plan.go | 144 ++++++++-- detectors/sshole/internal/repo/repo.go | 106 +++++-- detectors/sshole/internal/repo/review_test.go | 267 ++++++++++++++++++ 3 files changed, 467 insertions(+), 50 deletions(-) create mode 100644 detectors/sshole/internal/repo/review_test.go diff --git a/detectors/sshole/internal/repo/plan.go b/detectors/sshole/internal/repo/plan.go index 19161f3..cfb32e0 100644 --- a/detectors/sshole/internal/repo/plan.go +++ b/detectors/sshole/internal/repo/plan.go @@ -7,6 +7,7 @@ import ( "os" "path" "path/filepath" + "regexp" "sort" "strings" "unicode" @@ -144,8 +145,9 @@ func scanOne(ctx context.Context, root, file string, opts Options, data []byte) return fs, err } -// scanFile is scanOne that also returns the other files the rescan needed -// and could not read: a Yocto finding joins files across the tree. +// scanFile is scanOne that also returns what the rescan could not read +// when it walked the tree: a Yocto finding joins files across it. A Skip +// with no file is the walk's limit. func scanFile(ctx context.Context, root, file string, opts Options, data []byte) ([]Finding, []Skip, error) { s := &scanner{ctx: ctx, root: root, opts: opts, bases: map[string]baseInfo{}} if data == nil { @@ -177,16 +179,11 @@ func scanFile(ctx context.Context, root, file string, opts Options, data []byte) out = append(out, f) } } - var unread []Skip - for _, sk := range res.Skips { - if kindOf(sk.File) == "build" { - unread = append(unread, sk) - } - } + skips := res.Skips if res.Truncated { - unread = append(unread, Skip{File: "the source tree", Reason: "too many files to walk"}) + skips = append(skips, Skip{Reason: "the source tree has too many files to walk"}) } - return out, unread, nil + return out, skips, nil } s.build(file, string(data)) return s.finishBuild(), nil, nil @@ -300,11 +297,16 @@ func Printable(s string) string { // Find rescans one file and returns the finding with this rule at this // line. message, when not empty, picks between several on the line: the apk // spec or the text the finding's message quotes. gone is true only when -// this rescan checked what the scan reported and the finding is not there: -// a not-checked finding, a file or base image that cannot be read this -// time, or a line past the end of the file declines with "rescan to -// confirm" instead. +// this rescan checked what the scan reported and the finding is not there. +// Otherwise it declines with "rescan to confirm": a not-checked finding; a +// rule or file this package does not rescan; a file, TCLIBC setting or base +// image that cannot be read this time; another finding for the same package +// on the line; and a line past the end of a file that still has findings +// like it. func Find(ctx context.Context, root, file string, line int, rule, message string, opts Options) (f *Finding, gone bool, err error) { + if !findRules[rule] || kindOf(file) == "" { + return nil, false, notChecked("%s findings in %s are not rescanned here, so it is not checked", rule, file) + } data, err := readFile(root, file) if err != nil { if errors.Is(err, os.ErrNotExist) && rule != RuleNotChecked { @@ -312,20 +314,21 @@ func Find(ctx context.Context, root, file string, line int, rule, message string } return nil, false, notChecked("%s could not be read (%v), so it is not checked", file, err) } - fs, unread, err := scanFile(ctx, root, file, opts, data) + fs, skips, err := scanFile(ctx, root, file, opts, data) if err != nil { return nil, false, err } + msg := lineRefRE.ReplaceAllString(message, ")") // stored before messages lost their line numbers var at []Finding for _, g := range fs { if g.Rule == rule && g.Line == line { at = append(at, g) } } - if len(at) > 1 && message != "" { + if len(at) > 1 && msg != "" { var picked []Finding for _, g := range at { - if strings.Contains(message, g.Message) || g.Props["spec"] != "" && strings.Contains(message, g.Props["spec"]) { + if strings.Contains(msg, g.Message) || g.Props["spec"] != "" && strings.Contains(msg, g.Props["spec"]) { picked = append(picked, g) } } @@ -333,12 +336,12 @@ func Find(ctx context.Context, root, file string, line int, rule, message string at = picked } } - if len(at) == 0 && message != "" { + if len(at) == 0 && msg != "" { // The line moved (an edit above it): the same finding elsewhere in // the file, when there is exactly one, is still this finding. var moved []Finding for _, g := range fs { - if g.Rule == rule && strings.Contains(message, g.Message) { + if g.Rule == rule && strings.Contains(msg, g.Message) { moved = append(moved, g) } } @@ -356,8 +359,7 @@ func Find(ctx context.Context, root, file string, line int, rule, message string } // Not there. That is "gone" only when the scan checked it and this // rescan checked the same again. - switch { - case rule == RuleNotChecked: + if rule == RuleNotChecked { now := "" for _, g := range fs { if g.Line == line && g.Level != "note" { @@ -366,22 +368,104 @@ func Find(ctx context.Context, root, file string, line int, rule, message string } } return nil, false, notChecked("%s:%d was not checked when it was scanned%s", file, line, now) - case len(unread) > 0: - return nil, false, notChecked("%s could not be read this time (%s), so %s is not checked", unread[0].File, unread[0].Reason, file) - case line > len(strings.Split(string(data), "\n")): - return nil, false, notChecked("line %d is past the end of %s, which changed since the scan", line, file) - case rule == RulePin || rule == RuleUnpinned || rule == RuleEOL || rule == RuleBuild: - // These depend on the base image or the C library: a not-checked - // finding on the line means this rescan could not judge it. + } + for _, sk := range skips { + if blocksYocto(sk, msg) { + what := sk.Reason + if sk.File != "" { + what = fmt.Sprintf("%s could not be read this time (%s)", sk.File, sk.Reason) + } + return nil, false, notChecked("%s, so %s is not checked", what, file) + } + } + k := keyOf(msg) + for _, g := range fs { + switch { + case g.Rule == RuleNotChecked && k.holds(g): + // The same package, variable or build system, anywhere in + // the file: this rescan could not judge it. + return nil, false, notChecked("%s:%d is not checked this time (%s)", file, g.Line, g.Message) + case g.Level != "note" && k.pkg != "" && g.Props["package"] == k.pkg && g.Line == line: + // The same package under another rule (a pin loosened, an + // end-of-life base no longer known as one). + return nil, false, notChecked("line %d of %s now has %s (%s)", line, file, g.Rule, g.Message) + case rule == RuleBuild && g.Rule == RuleBuild && k.system != "" && g.Props["system"] == k.system && g.Props["package"] == k.pkg: + // One build finding per file and system: moved and reworded. + return nil, false, notChecked("%s:%d still has %s (%s)", file, g.Line, g.Rule, g.Message) + } + } + if line > len(strings.Split(string(data), "\n")) { for _, g := range fs { - if g.Line == line && g.Rule == RuleNotChecked { - return nil, false, notChecked("line %d of %s is not checked this time (%s)", line, file, g.Message) + if g.Rule == rule { + return nil, false, notChecked("line %d is past the end of %s, which changed since the scan and still has %s findings", line, file, rule) } } } return nil, true, nil } +// findRules are the rules a rescan of one file produces. +var findRules = map[string]bool{RulePin: true, RuleUnpinned: true, RuleEOL: true, RuleStar: true, RulePassword: true, + RuleNotChecked: true, RuleAnsible: true, RuleBuild: true} + +var ( + lineRefRE = regexp.MustCompile(`, set on line \d+\)`) + viaRE = regexp.MustCompile(`\(through \$([A-Za-z_][A-Za-z0-9_]*)`) + tclibcRE = regexp.MustCompile(` and (\S+):\d+ sets TCLIBC`) +) + +// findKey is what a finding's message names: the OpenSSH package, the +// variable it came through, the build system. +type findKey struct{ pkg, via, system string } + +func keyOf(msg string) findKey { + var k findKey + w := strings.Fields(msg) + if len(w) >= 2 && (w[0] == "installs" || w[0] == "pins") { + if m := specRE.FindStringSubmatch(strings.Trim(w[1], `'"`)); m != nil && sshPackages[m[1]] { + k.pkg = m[1] + } + } + if m := viaRE.FindStringSubmatch(msg); m != nil { + k.via = m[1] + } + switch { + case strings.HasPrefix(msg, "Buildroot "): + k.system = "buildroot" + case strings.HasPrefix(msg, "Yocto "): + k.system = "yocto" + case strings.HasPrefix(msg, "OpenWrt configuration builds ") && len(w) >= 4: + k.system, k.pkg = "openwrt", w[3] + } + return k +} + +// holds reports whether a not-checked finding is about what k names. +func (k findKey) holds(g Finding) bool { + if k.pkg != "" && g.Props["package"] == k.pkg || k.system != "" && g.Props["system"] == k.system { + return true + } + if k.via == "" { + return false + } + m := varRE.FindStringSubmatch(g.Props["spec"]) + return m != nil && (m[1] == k.via || m[3] == k.via) +} + +// blocksYocto reports whether a file the Yocto rescan could not read may +// hide the finding: the TCLIBC setting its message names, or a directory +// holding it. Without that reference, any build file or directory. +func blocksYocto(sk Skip, msg string) bool { + if sk.File == "" { + return true // the tree past the walk's limit + } + if m := tclibcRE.FindStringSubmatch(msg); m != nil { + return sk.File == m[1] || strings.HasPrefix(m[1], sk.File+"/") + } + k := kindOf(sk.File) + return k == "build" || k == "" +} + // notChecked declines a finding Find cannot confirm as gone. func notChecked(format string, args ...any) error { return &Declined{Reason: fmt.Sprintf(format, args...) + "; rescan to confirm"} diff --git a/detectors/sshole/internal/repo/repo.go b/detectors/sshole/internal/repo/repo.go index 41d72db..5d9e78f 100644 --- a/detectors/sshole/internal/repo/repo.go +++ b/detectors/sshole/internal/repo/repo.go @@ -300,6 +300,7 @@ type baseInfo struct { alpine, known bool branch string why string + via string // an unset variable before the image name (a registry) } type scanner struct { @@ -471,19 +472,17 @@ func (s *scanner) dockerfile(rel, text string) []Finding { v = strings.Trim(v, `"'`) args[k] = v s.defineVar(k, v, in) - } else if _, set := args[k]; !set && in.cmd == "ARG" { - args[k] = "" } } case "FROM": f := strings.Fields(in.args.text) - var img, as string + var img, as, via string for i := 0; i < len(f); i++ { if strings.HasPrefix(f[i], "--") { continue } if img == "" { - img = expand(f[i], args) + img, via = expandImage(f[i], args) } else if strings.EqualFold(f[i], "as") && i+1 < len(f) { as = f[i+1] break @@ -493,6 +492,7 @@ func (s *scanner) dockerfile(rel, text string) []Finding { cur = b } else { cur = s.base(img) + cur.via = via } curImage = img s.from = fromInfo{image: img} @@ -513,23 +513,79 @@ func (s *scanner) dockerfile(rel, text string) []Finding { var varRE = regexp.MustCompile(`\$\{([A-Za-z_][A-Za-z0-9_]*)(?::?-([^}]*))?\}|\$([A-Za-z_][A-Za-z0-9_]*)`) -func expand(s string, args map[string]string) string { - return varRE.ReplaceAllStringFunc(s, func(m string) string { - sm := varRE.FindStringSubmatch(m) - name := sm[1] - if name == "" { - name = sm[3] +// expandImage expands the variables in a FROM image. One that is not set +// and has no default leaves the image unknown, kept as written, except a +// prefix before a complete image (a registry: via names it and the rest is +// judged) and an optional suffix the image is complete without. An empty +// value or default expands to empty. +func expandImage(w string, args map[string]string) (img, via string) { + if !strings.Contains(w, "$") { + return w, "" + } + unset := false + loose := varRE.ReplaceAllStringFunc(w, func(m string) string { + v, ok := lookupVar(m, args) + unset = unset || !ok + return v + }) + loose = strings.TrimLeft(loose, "/") // an empty registry before "/" + if !unset && validImage(loose) { + return loose, "" + } + if loc := varRE.FindStringIndex(w); loc != nil && loc[0] == 0 { + if _, ok := lookupVar(w[:loc[1]], args); !ok { + if rest, _ := expandImage(strings.TrimLeft(w[loc[1]:], "/"), args); validImage(rest) { + return rest, w[:loc[1]] + } } - if v, ok := args[name]; ok && v != "" { - return v + } + if unset && validImage(loose) { + return loose, "" + } + return w, "" +} + +// lookupVar resolves one variable reference; ok is false when it is not +// set and has no default. +func lookupVar(m string, args map[string]string) (string, bool) { + sm := varRE.FindStringSubmatch(m) + name := sm[1] + if name == "" { + name = sm[3] + } + v, set := args[name] + switch { + case set && (v != "" || !strings.Contains(m, ":-")): + return v, true + case strings.Contains(m, "-"): // ${X:-d} or ${X-d}; a name has no "-" + return sm[2], true + } + return "", false +} + +var tagRE = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9_.-]*$`) + +// validImage reports whether s reads as a whole image reference. +func validImage(s string) bool { + if s == "" || strings.ContainsAny(s, "${} \t") { + return false + } + name := s + if i := strings.IndexByte(name, '@'); i >= 0 { + name = name[:i] + } + if i := strings.LastIndexByte(name, ':'); i > strings.LastIndexByte(name, '/') { + if !tagRE.MatchString(name[i+1:]) { + return false } - if sm[2] == "" { - // Unresolved: kept as written, so the image is not known - // (an empty name would read as scratch, nothing to check). - return m + name = name[:i] + } + for _, c := range strings.Split(name, "/") { + if c == "" || strings.Trim(c, "._-") != c { + return false } - return sm[2] - }) + } + return true } var alpineTagRE = regexp.MustCompile(`(?:^|[-_.])alpine(\d+\.\d+)`) @@ -595,6 +651,9 @@ func (s *scanner) need(b baseInfo) baseInfo { } func baseFromName(img string) baseInfo { + if strings.Contains(img, "$") { + return baseInfo{} // not known: a variable the file does not set + } if img == "" || img == "scratch" { return baseInfo{known: true} } @@ -961,10 +1020,16 @@ func (s *scanner) judgeSpec(rel string, at specAt, pkg, op, ver string, b baseIn if image != "" { props["image"] = image } + via := b.via b = s.need(b) if b.branch != "" { props["branch"] = b.branch } + note := "" + if via != "" { + props["image_variable"] = via + note = fmt.Sprintf(" (the image starts with %s, which this file does not set; judged as %s)", via, image) + } f := Finding{File: rel, Line: l, Props: props} if !b.known { f.Rule, f.Level = RuleNotChecked, "note" @@ -981,7 +1046,7 @@ func (s *scanner) judgeSpec(rel string, at specAt, pkg, op, ver string, b baseIn fixed, haveFixed := assess.AlpineFixedFor(b.branch) if b.branch != "" && !haveFixed { f.Rule, f.Level = RuleEOL, "error" - f.Message = fmt.Sprintf("installs %s on Alpine %s (%s), which has no OpenSSH package with the *sshole fix", at.val, b.branch, image) + f.Message = fmt.Sprintf("installs %s on Alpine %s (%s), which has no OpenSSH package with the *sshole fix", at.val, b.branch, image) + note f.Fix = "Move the base image to an Alpine release with a fixed package (" + fixedTable() + "), or set PasswordAuthentication no and change every \"*\" password field to \"*NP*\"" // The official alpine image, tagged on its FROM line, moves to the // nearest release with a fixed package, as a labelled upgrade. @@ -1015,8 +1080,9 @@ func (s *scanner) judgeSpec(rel string, at specAt, pkg, op, ver string, b baseIn f.Message = fmt.Sprintf("pins %s to a release without the *sshole fix", at.val) } if at.via != "" { - f.Message += fmt.Sprintf(" (through $%s, set on line %d)", at.via, at.editLine) + f.Message += fmt.Sprintf(" (through $%s)", at.via) } + f.Message += note if !haveFixed { f.Fix = "Require " + pkg + " at the fixed release for this image's Alpine branch (" + fixedTable() + ")" return f, true diff --git a/detectors/sshole/internal/repo/review_test.go b/detectors/sshole/internal/repo/review_test.go new file mode 100644 index 0000000..3b95d9c --- /dev/null +++ b/detectors/sshole/internal/repo/review_test.go @@ -0,0 +1,267 @@ +package repo + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" +) + +// Cases from the independent review of the not-checked change (numbers +// are the review's findings). + +func alpineAt(branch string) Options { + return Options{Base: func(context.Context, string) (bool, string, error) { return true, branch, nil }} +} + +func mustBeGone(t *testing.T, what string, f *Finding, gone bool, err error) { + t.Helper() + if err != nil || !gone || f != nil { + t.Fatalf("%s: want gone, got finding %+v, gone %v, err %v", what, f, gone, err) + } +} + +// 1: an end-of-life finding rescans as apk-unpinned when the lookup fails, +// and the reverse. +func TestReviewEOLAndUnpinnedSwap(t *testing.T) { + ctx := context.Background() + for _, from := range []string{"FROM acme/app:alpine", "FROM alpine"} { + root := t.TempDir() + write(t, root, "Dockerfile", from+"\nRUN apk add openssh-server\n") + eol := findOne(t, root, alpineAt("3.14"), RuleEOL) + for name, o := range map[string]Options{"lookup down": baseDown, "no lookup": {}} { + f, gone, err := Find(ctx, root, "Dockerfile", eol.Line, RuleEOL, eol.Message, o) + mustDecline(t, from+", "+name, f, gone, err) + } + } + root := t.TempDir() + write(t, root, "Dockerfile", "FROM acme/app:alpine\nRUN apk add openssh-server\n") + un := findOne(t, root, baseDown, RuleUnpinned) + f, gone, err := Find(ctx, root, "Dockerfile", un.Line, RuleUnpinned, un.Message, alpineAt("3.14")) + mustDecline(t, "unpinned now end-of-life", f, gone, err) +} + +// 5: a pin loosened to no floor is not fixed. +func TestReviewPinLoosened(t *testing.T) { + root := t.TempDir() + write(t, root, "Dockerfile", "FROM alpine:3.21\nRUN apk add openssh-server=9.9_p1-r2\n") + pin := findOne(t, root, Options{}, RulePin) + write(t, root, "Dockerfile", "FROM alpine:3.21\nRUN apk add openssh-server\n") + f, gone, err := Find(context.Background(), root, "Dockerfile", pin.Line, RulePin, pin.Message, Options{}) + mustDecline(t, "loosened", f, gone, err) +} + +// 2a: lookup down and the line shifted. +func TestReviewNotCheckedElsewhere(t *testing.T) { + root := t.TempDir() + write(t, root, "Dockerfile", "FROM acme/base:1\nRUN apk add openssh-server=9.9_p1-r2\n") + pin := findOne(t, root, alpine321, RulePin) + write(t, root, "Dockerfile", "# a comment\nFROM acme/base:1\nRUN apk add openssh-server=9.9_p1-r2\n") + f, gone, err := Find(context.Background(), root, "Dockerfile", pin.Line, RulePin, pin.Message, baseDown) + mustDecline(t, "shifted, lookup down", f, gone, err) +} + +// 2b: Buildroot whose C library is no longer set. +func TestReviewBuildrootLibcRemoved(t *testing.T) { + root := t.TempDir() + write(t, root, "configs/a_defconfig", "BR2_TOOLCHAIN_BUILDROOT_MUSL=y\nBR2_PACKAGE_OPENSSH=y\n") + b := findOne(t, root, Options{}, RuleBuild) + write(t, root, "configs/a_defconfig", "BR2_PACKAGE_OPENSSH=y\n") + f, gone, err := Find(context.Background(), root, b.File, b.Line, RuleBuild, b.Message, Options{}) + mustDecline(t, "libc removed", f, gone, err) +} + +// 2c: a pin through a variable keeps no line number in its message, and +// a message stored with one still matches. +func TestReviewVariableMoved(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + write(t, root, "Dockerfile", "FROM alpine:3.21\nARG PKGS=\"openssh-server=9.9_p1-r2\"\nRUN apk add $PKGS\n") + pin := findOne(t, root, Options{}, RulePin) + if strings.Contains(pin.Message, "line") { + t.Errorf("line number in the message: %q", pin.Message) + } + write(t, root, "Dockerfile", "FROM alpine:3.21\n# a comment\nARG PKGS=\"openssh-server=9.9_p1-r2\"\nRUN apk add $PKGS\n") + for _, msg := range []string{pin.Message, strings.TrimSuffix(pin.Message, ")") + ", set on line 2)"} { + f, gone, err := Find(ctx, root, "Dockerfile", pin.Line, RulePin, msg, Options{}) + if err != nil || gone || f == nil || f.Line != pin.Line+1 { + t.Errorf("%q: %+v %v %v", msg, f, gone, err) + } + } + // The variable is no longer set: not checked, not gone. + write(t, root, "Dockerfile", "FROM alpine:3.21\n# a comment\n\nRUN apk add $PKGS\n") + f, gone, err := Find(ctx, root, "Dockerfile", pin.Line, RulePin, pin.Message, Options{}) + mustDecline(t, "variable unset", f, gone, err) +} + +// 3: rules and files Find never produces. +func TestReviewForeignRules(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + write(t, root, "docker-compose.yml", "services:\n ssh:\n image: acme/sshd:1\n") + write(t, root, "Dockerfile", "FROM alpine:3.22\n") + write(t, root, "k8s/deploy.json", "{}\n") + for _, c := range []struct{ file, rule string }{ + {"docker-compose.yml", "image"}, + {"Dockerfile", "bogus"}, + {"k8s/deploy.json", RuleStar}, + {"k8s/missing.json", RuleStar}, + } { + f, gone, err := Find(ctx, root, c.file, 3, c.rule, "", Options{}) + mustDecline(t, c.file+" "+c.rule, f, gone, err) + } +} + +func yoctoTree(t *testing.T) string { + root := t.TempDir() + write(t, root, "meta-a/conf/layer.conf", "LAYERSERIES_COMPAT_a = \"scarthgap\"\n") + write(t, root, "meta-a/conf/distro/a.conf", "TCLIBC = \"musl\"\n") + write(t, root, "meta-a/recipes-core/images/a.bb", "IMAGE_INSTALL:append = \" openssh\"\n") + return root +} + +// 4: an unreadable directory holding the TCLIBC setting. +func TestReviewYoctoDirUnreadable(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root reads a mode 000 directory") + } + root := yoctoTree(t) + b := findOne(t, root, Options{}, RuleBuild) + dir := filepath.Join(root, "meta-a/conf/distro") + if err := os.Chmod(dir, 0); err != nil { + t.Fatal(err) + } + defer os.Chmod(dir, 0o755) + f, gone, err := Find(context.Background(), root, b.File, b.Line, RuleBuild, b.Message, Options{}) + mustDecline(t, "distro dir unreadable", f, gone, err) +} + +func TestReviewYoctoSkipRelevance(t *testing.T) { + msg := "Yocto image installs the OpenSSH server and meta-a/conf/distro/a.conf:1 sets TCLIBC to musl; x" + for _, c := range []struct { + skip string + want bool + }{ + {"meta-a/conf/distro/a.conf", true}, + {"meta-a/conf/distro", true}, + {"meta-a", true}, + {"meta-a/conf/distro/b.conf", false}, + {"third_party/tables/data.inc", false}, + {"meta-a/conf/distro/a.conf.bak", false}, + } { + if got := blocksYocto(Skip{File: c.skip}, msg); got != c.want { + t.Errorf("%s: %v", c.skip, got) + } + } + // Without the reference, any build file or directory counts. + if !blocksYocto(Skip{File: "x/local.conf"}, "Yocto image") { + t.Error("no reference: build file does not count") + } +} + +// 6: a fixed pin next to a variable install is gone. +func TestReviewFixedPinBesideVariable(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + write(t, root, "Dockerfile", "FROM alpine:3.21\nRUN apk add openssh-server=9.9_p1-r2 $EXTRA\n") + var pin Finding + for _, f := range scan(t, root, Options{}) { + if f.Rule == RulePin { + pin = f + } + } + ch, err := Plan(ctx, root, pin, Options{}) + if err != nil { + t.Fatal(err) + } + if err := Apply(root, ch); err != nil { + t.Fatal(err) + } + f, gone, err := Find(ctx, root, "Dockerfile", pin.Line, RulePin, pin.Message, Options{}) + mustBeGone(t, "fixed pin", f, gone, err) +} + +// 7: an unrelated oversized build file, skipped at scan time too. +func TestReviewYoctoUnrelatedSkip(t *testing.T) { + ctx := context.Background() + root := yoctoTree(t) + write(t, root, "third_party/tables/data.inc", strings.Repeat("#\n", maxFileSize/2+1)) + b := findOne(t, root, Options{}, RuleBuild) + if !b.Fixable { + t.Fatalf("not fixable: %+v", b) + } + ch, err := Plan(ctx, root, b, Options{}) + if err != nil { + t.Fatal(err) + } + if err := Apply(root, ch); err != nil { + t.Fatal(err) + } + f, gone, err := Find(ctx, root, b.File, b.Line, RuleBuild, b.Message, Options{}) + mustBeGone(t, "bbappend added", f, gone, err) +} + +// 8: past the end, but the whole-file rescan has nothing like it left. +func TestReviewPastEndSettled(t *testing.T) { + root := t.TempDir() + write(t, root, "Dockerfile", "FROM alpine:3.22\nRUN true\nRUN true\nRUN usermod -p '*' bob\nRUN true\nRUN true\n") + star := findOne(t, root, Options{}, RuleStar) + write(t, root, "Dockerfile", "FROM alpine:3.22\nRUN true\n") + for _, msg := range []string{star.Message, ""} { + f, gone, err := Find(context.Background(), root, "Dockerfile", star.Line, RuleStar, msg, Options{}) + mustBeGone(t, "past the end, message "+msg, f, gone, err) + } +} + +// 11: empty and prefix variables in FROM are still judged. +func TestReviewFromVariables(t *testing.T) { + for _, from := range []string{ + "ARG REGISTRY=\nFROM ${REGISTRY}alpine:3.21", + "ARG REGISTRY=\"\"\nFROM ${REGISTRY}alpine:3.21", + "FROM ${REGISTRY:-}alpine:3.21", + } { + root := t.TempDir() + write(t, root, "Dockerfile", from+"\nRUN apk add openssh-server\n") + if f := findOne(t, root, Options{}, RuleUnpinned); !f.Fixable || strings.Contains(f.Message, "REGISTRY") { + t.Errorf("%q: %+v", from, f) + } + } + // Unset: the image after it is judged, with a note. + for _, from := range []string{"FROM ${REGISTRY}alpine:3.21", "ARG REGISTRY\nFROM ${REGISTRY}/alpine:3.21", "FROM $REGISTRY/alpine:3.21"} { + root := t.TempDir() + write(t, root, "Dockerfile", from+"\nRUN apk add openssh-server\n") + if f := findOne(t, root, Options{}, RuleUnpinned); !f.Fixable || !strings.Contains(f.Message, "REGISTRY") { + t.Errorf("%q: %+v", from, f) + } + } + // An end-of-life base behind the prefix is still fixed in place. + root := t.TempDir() + write(t, root, "Dockerfile", "FROM ${REGISTRY}alpine:3.14\nRUN apk add openssh-server\n") + eol := findOne(t, root, Options{}, RuleEOL) + ch, err := Plan(context.Background(), root, eol, Options{}) + if err != nil || ch.Edits[0].New != "FROM ${REGISTRY}alpine:3.16" { + t.Fatalf("%+v %v", ch, err) + } + // An optional suffix: resolved online as before. + root = t.TempDir() + write(t, root, "Dockerfile", "ARG PY=3.12\nFROM python:${PY}${FLAVOR}\nRUN apk add openssh-server\n") + var asked []string + o := Options{Base: func(_ context.Context, img string) (bool, string, error) { + asked = append(asked, img) + return true, "3.21", nil + }} + findOne(t, root, o, RuleUnpinned) + if strings.Join(asked, ",") != "python:3.12" { + t.Errorf("looked up %v", asked) + } +} + +// 12: a tag made only of unset variables is not known, and not fixed. +func TestReviewTagOfVariables(t *testing.T) { + root := t.TempDir() + write(t, root, "Dockerfile", "FROM alpine:${MAJOR}.${MINOR}\nRUN apk add openssh-server\n") + if f := findOne(t, root, Options{}, RuleNotChecked); f.Fixable { + t.Errorf("%+v", f) + } +} From 965f139f974489069bfee007575d5a03fb745ad5 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 04:00:47 +0000 Subject: [PATCH 3/5] sshole: fixes from the second review of the not-checked change Find: - Fails closed when the message gives no key (empty, prefixed or reworded): any not-checked finding with a package, system or variable holds the finding back, as does any other apk finding on the line, and any build finding in a build file. - On a line with findings for several packages, only the message's own package is this finding (a fixed openssh-server pin no longer returns the openssh pin beside it). - A finding for the same package with the same spec elsewhere in the file also holds it back (end-of-life, lookup down, line shifted). - FuzzScanText checks that every finding's message gives back its own package, variable and system, or none; a test checks it exactly for every message kind. Scanner: - A variable in the tag keeps what the name says: alpine:${V}, python:${PY}-alpine and node:${NODE}-alpine3.14 are judged as Alpine (with the branch when the name gives it whole), as on main, and never looked up. Only an image whose name is a variable is not known. - ARG and ENV values expand the variables already set (ARG TAG=3.21 / ARG BASE=alpine:${TAG}). - A tag that ends in ".", "_" or "-" is not a whole tag, so alpine:3.${MINOR} is no longer end-of-life on "Alpine 3." nor rewritten. - The prefix note names every unset variable before the image and the image judged, not the stage name. Co-Authored-By: Claude Opus 5.5 --- detectors/sshole/internal/repo/plan.go | 34 ++-- detectors/sshole/internal/repo/repo.go | 54 ++++-- detectors/sshole/internal/repo/repo_test.go | 1 + .../sshole/internal/repo/review2_test.go | 164 ++++++++++++++++++ detectors/sshole/internal/repo/review_test.go | 5 +- 5 files changed, 233 insertions(+), 25 deletions(-) create mode 100644 detectors/sshole/internal/repo/review2_test.go diff --git a/detectors/sshole/internal/repo/plan.go b/detectors/sshole/internal/repo/plan.go index cfb32e0..75a5b6f 100644 --- a/detectors/sshole/internal/repo/plan.go +++ b/detectors/sshole/internal/repo/plan.go @@ -319,9 +319,15 @@ func Find(ctx context.Context, root, file string, line int, rule, message string return nil, false, err } msg := lineRefRE.ReplaceAllString(message, ")") // stored before messages lost their line numbers + k := keyOf(msg) + apkRule := rule == RulePin || rule == RuleUnpinned || rule == RuleEOL + // A key the message should give and does not (empty, reworded): any + // package or system holds the finding back, so it never reads as gone + // only because the message did not parse. + k.any = apkRule && k.pkg == "" || rule == RuleBuild && k.system == "" var at []Finding for _, g := range fs { - if g.Rule == rule && g.Line == line { + if g.Rule == rule && g.Line == line && (k.pkg == "" || g.Props["package"] == k.pkg) { at = append(at, g) } } @@ -378,18 +384,19 @@ func Find(ctx context.Context, root, file string, line int, rule, message string return nil, false, notChecked("%s, so %s is not checked", what, file) } } - k := keyOf(msg) for _, g := range fs { + apk := g.Rule == RulePin || g.Rule == RuleUnpinned || g.Rule == RuleEOL switch { case g.Rule == RuleNotChecked && k.holds(g): // The same package, variable or build system, anywhere in // the file: this rescan could not judge it. return nil, false, notChecked("%s:%d is not checked this time (%s)", file, g.Line, g.Message) - case g.Level != "note" && k.pkg != "" && g.Props["package"] == k.pkg && g.Line == line: + case apk && (k.pkg != "" && g.Props["package"] == k.pkg && (g.Line == line || g.Props["spec"] == k.spec) || k.any && apkRule && g.Line == line): // The same package under another rule (a pin loosened, an - // end-of-life base no longer known as one). - return nil, false, notChecked("line %d of %s now has %s (%s)", line, file, g.Rule, g.Message) - case rule == RuleBuild && g.Rule == RuleBuild && k.system != "" && g.Props["system"] == k.system && g.Props["package"] == k.pkg: + // end-of-life base no longer known as one), on the line or + // with the same spec elsewhere (the line moved). + return nil, false, notChecked("%s:%d now has %s (%s)", file, g.Line, g.Rule, g.Message) + case rule == RuleBuild && g.Rule == RuleBuild && (k.any || k.system != "" && g.Props["system"] == k.system && g.Props["package"] == k.pkg): // One build finding per file and system: moved and reworded. return nil, false, notChecked("%s:%d still has %s (%s)", file, g.Line, g.Rule, g.Message) } @@ -414,16 +421,20 @@ var ( tclibcRE = regexp.MustCompile(` and (\S+):\d+ sets TCLIBC`) ) -// findKey is what a finding's message names: the OpenSSH package, the -// variable it came through, the build system. -type findKey struct{ pkg, via, system string } +// findKey is what a finding's message names: the OpenSSH package and the +// spec that installs it, the variable it came through, the build system. +// any: the message should name one and does not, so anything matches. +type findKey struct { + pkg, spec, via, system string + any bool +} func keyOf(msg string) findKey { var k findKey w := strings.Fields(msg) if len(w) >= 2 && (w[0] == "installs" || w[0] == "pins") { if m := specRE.FindStringSubmatch(strings.Trim(w[1], `'"`)); m != nil && sshPackages[m[1]] { - k.pkg = m[1] + k.pkg, k.spec = m[1], m[0] } } if m := viaRE.FindStringSubmatch(msg); m != nil { @@ -442,6 +453,9 @@ func keyOf(msg string) findKey { // holds reports whether a not-checked finding is about what k names. func (k findKey) holds(g Finding) bool { + if k.any { + return g.Props["package"] != "" || g.Props["system"] != "" || varRE.MatchString(g.Props["spec"]) + } if k.pkg != "" && g.Props["package"] == k.pkg || k.system != "" && g.Props["system"] == k.system { return true } diff --git a/detectors/sshole/internal/repo/repo.go b/detectors/sshole/internal/repo/repo.go index 5d9e78f..1ac7b6c 100644 --- a/detectors/sshole/internal/repo/repo.go +++ b/detectors/sshole/internal/repo/repo.go @@ -462,7 +462,7 @@ func (s *scanner) dockerfile(rel, text string) []Finding { // ENV KEY value with spaces k, v, _ := strings.Cut(strings.TrimSpace(in.args.text), " ") v = strings.TrimSpace(v) - args[k] = v + args[k] = expandSet(v, args) s.defineVar(k, v, in) continue } @@ -470,7 +470,7 @@ func (s *scanner) dockerfile(rel, text string) []Finding { k, v, ok := strings.Cut(a, "=") if ok { v = strings.Trim(v, `"'`) - args[k] = v + args[k] = expandSet(v, args) s.defineVar(k, v, in) } } @@ -534,17 +534,39 @@ func expandImage(w string, args map[string]string) (img, via string) { } if loc := varRE.FindStringIndex(w); loc != nil && loc[0] == 0 { if _, ok := lookupVar(w[:loc[1]], args); !ok { - if rest, _ := expandImage(strings.TrimLeft(w[loc[1]:], "/"), args); validImage(rest) { - return rest, w[:loc[1]] + tail := w[loc[1]:] + trimmed := strings.TrimLeft(tail, "/") + if rest, restVia := expandImage(trimmed, args); validImage(rest) { + via = w[:loc[1]] + if restVia != "" { + via += tail[:len(tail)-len(trimmed)] + restVia + } + return rest, via } } } if unset && validImage(loose) { return loose, "" } + // What the file does not set stays as written: the name may still + // say Alpine (alpine:${V}, python:${PY}-alpine3.21). + if strict := expandSet(w, args); strings.Contains(strict, "$") { + return strict, "" + } return w, "" } +// expandSet expands the variables that are set or have a default, and +// keeps the others as written. +func expandSet(w string, args map[string]string) string { + return varRE.ReplaceAllStringFunc(w, func(m string) string { + if v, ok := lookupVar(m, args); ok { + return v + } + return m + }) +} + // lookupVar resolves one variable reference; ok is false when it is not // set and has no default. func lookupVar(m string, args map[string]string) (string, bool) { @@ -575,7 +597,8 @@ func validImage(s string) bool { name = name[:i] } if i := strings.LastIndexByte(name, ':'); i > strings.LastIndexByte(name, '/') { - if !tagRE.MatchString(name[i+1:]) { + // A tag cut short by an unset variable ("3." of 3.${MINOR}) is not one. + if tag := name[i+1:]; !tagRE.MatchString(tag) || strings.ContainsAny(tag[len(tag)-1:], "._-") { return false } name = name[:i] @@ -651,9 +674,6 @@ func (s *scanner) need(b baseInfo) baseInfo { } func baseFromName(img string) baseInfo { - if strings.Contains(img, "$") { - return baseInfo{} // not known: a variable the file does not set - } if img == "" || img == "scratch" { return baseInfo{known: true} } @@ -665,9 +685,17 @@ func baseFromName(img string) baseInfo { name, tag = name[:i], name[i+1:] } repo := path.Base(name) + if strings.Contains(repo, "$") { + return baseInfo{} // the image is a variable the file does not set + } + // A variable in the tag: the name still says Alpine, but not which + // release, and the image is never looked up. + vary := strings.Contains(tag, "$") switch { case repo == "alpine": switch { + case vary: + return baseInfo{alpine: true, known: true} case tag == "" || tag == "latest": return baseInfo{alpine: true, known: true} // branch moves: resolve it case tag == "edge" || strings.HasPrefix(tag, "20"): @@ -678,8 +706,8 @@ func baseFromName(img string) baseInfo { } return baseInfo{alpine: true, known: true} case strings.Contains(tag, "alpine"): - if m := alpineTagRE.FindStringSubmatch(tag); m != nil { - return baseInfo{alpine: true, known: true, branch: m[1]} + if m := alpineTagRE.FindStringSubmatchIndex(tag); m != nil && !strings.HasPrefix(tag[m[1]:], "$") { + return baseInfo{alpine: true, known: true, branch: tag[m[2]:m[3]]} } return baseInfo{alpine: true, known: true} } @@ -1020,7 +1048,7 @@ func (s *scanner) judgeSpec(rel string, at specAt, pkg, op, ver string, b baseIn if image != "" { props["image"] = image } - via := b.via + via, judged := b.via, b.img b = s.need(b) if b.branch != "" { props["branch"] = b.branch @@ -1028,7 +1056,7 @@ func (s *scanner) judgeSpec(rel string, at specAt, pkg, op, ver string, b baseIn note := "" if via != "" { props["image_variable"] = via - note = fmt.Sprintf(" (the image starts with %s, which this file does not set; judged as %s)", via, image) + note = fmt.Sprintf(" (the image starts with %s, which this file does not set; judged as %s)", via, judged) } f := Finding{File: rel, Line: l, Props: props} if !b.known { @@ -1443,7 +1471,7 @@ var alpineSuffixRE = regexp.MustCompile(`^(.*alpine)(\d+)\.(\d+)$`) // fixed OpenSSH package: same tag with only the Alpine release changed, // confirmed by reading the candidate's /etc/alpine-release. func (s *scanner) alpineRetag(image string) string { - if s.opts.Tags == nil || s.opts.Base == nil || strings.Contains(image, "@") { + if s.opts.Tags == nil || s.opts.Base == nil || strings.ContainsAny(image, "@$") { return "" } i := strings.LastIndexByte(image, ':') diff --git a/detectors/sshole/internal/repo/repo_test.go b/detectors/sshole/internal/repo/repo_test.go index 481e383..6c5ff3a 100644 --- a/detectors/sshole/internal/repo/repo_test.go +++ b/detectors/sshole/internal/repo/repo_test.go @@ -232,6 +232,7 @@ func FuzzScanText(f *testing.F) { if x.edit != nil && x.edit.Line < 1 { t.Fatal("edit before line 1") } + checkKey(t, x) } sc.script("a.sh", s) sc.yaml("a.yml", s) diff --git a/detectors/sshole/internal/repo/review2_test.go b/detectors/sshole/internal/repo/review2_test.go new file mode 100644 index 0000000..57f7fe9 --- /dev/null +++ b/detectors/sshole/internal/repo/review2_test.go @@ -0,0 +1,164 @@ +package repo + +import ( + "context" + "strings" + "testing" +) + +// Cases from the second review of the not-checked change. + +// checkKey asserts that what Find reads from a message is the finding's +// own package, variable and build system; an empty key is allowed (Find +// then fails closed), a wrong one is not. +func checkKey(t *testing.T, f Finding) { + t.Helper() + k := keyOf(f.Message) + if k.pkg != "" && k.pkg != f.Props["package"] || k.via != "" && k.via != f.Props["variable"] || k.system != "" && k.system != f.Props["system"] { + t.Fatalf("key %+v from %q, props %v", k, f.Message, f.Props) + } +} + +// Every message the scanner writes gives back its own key, exactly. +func TestKeyRoundTrip(t *testing.T) { + root := t.TempDir() + write(t, root, "a/Dockerfile", "FROM alpine:3.21\nARG PKGS=\"openssh-server=9.9_p1-r2\"\nRUN apk add $PKGS openssh@edge 'openssh-server-pam~9.9'\n") + write(t, root, "b/Dockerfile", "FROM alpine:3.14\nRUN apk add openssh-server\n") + write(t, root, "c/Dockerfile", "FROM ${REGISTRY}alpine:3.21\nRUN apk add openssh-server=9.9_p1-r2\n") + write(t, root, "d/Dockerfile", "FROM acme/base:1\nRUN apk add openssh-server\n") + write(t, root, "configs/a_defconfig", "BR2_PACKAGE_OPENSSH=y\n") + write(t, root, "configs/b_defconfig", "BR2_TOOLCHAIN_BUILDROOT_MUSL=y\nBR2_PACKAGE_OPENSSH=y\n") + write(t, root, "openwrt/.config", "CONFIG_TARGET_x86=y\nCONFIG_PACKAGE_openssh-server=y\n") + write(t, root, "meta-a/conf/layer.conf", "LAYERSERIES_COMPAT_a = \"scarthgap\"\n") + write(t, root, "meta-a/conf/distro/a.conf", "TCLIBC = \"musl\"\n") + write(t, root, "meta-a/recipes-core/images/a.bb", "IMAGE_INSTALL:append = \" openssh\"\n") + seen := map[string]bool{} + for _, f := range scan(t, root, Options{}) { + if f.Rule == RuleStar || f.Rule == RulePassword || f.Rule == RuleAnsible { + continue + } + k := keyOf(f.Message) + if k.pkg != f.Props["package"] || k.via != f.Props["variable"] || k.system != f.Props["system"] { + if !(f.Rule == RuleNotChecked && f.Props["package"] == "" && f.Props["system"] == "") { // a variable install names no package + t.Errorf("%s %s:%d key %+v from %q, props %v", f.Rule, f.File, f.Line, k, f.Message, f.Props) + } + } + seen[f.Rule+"/"+f.Props["system"]] = true + } + for _, want := range []string{RulePin + "/", RuleUnpinned + "/", RuleEOL + "/", RuleNotChecked + "/", RuleNotChecked + "/buildroot", RuleBuild + "/buildroot", RuleBuild + "/openwrt", RuleBuild + "/yocto"} { + if !seen[want] { + t.Errorf("no %s finding in the round trip", want) + } + } +} + +// 1: a message Find cannot read a key from fails closed. +func TestReview2KeyFailsClosed(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + write(t, root, "Dockerfile", "FROM acme/base:1\nRUN apk add openssh-server=9.9_p1-r2\n") + pin := findOne(t, root, alpine321, RulePin) + m := pin.Message + for _, msg := range []string{"", "Dockerfile:2: " + m, "apk-pin: " + m, strings.ToUpper(m[:1]) + m[1:], "**" + m + "**", + strings.Replace(m, "openssh-server=9.9_p1-r2", "`openssh-server=9.9_p1-r2`", 1)} { + f, gone, err := Find(ctx, root, "Dockerfile", pin.Line, RulePin, msg, baseDown) + mustDecline(t, "pin, message "+msg, f, gone, err) + } + // End-of-life swapped to unpinned, no message. + root = t.TempDir() + write(t, root, "Dockerfile", "FROM acme/app:alpine\nRUN apk add openssh-server\n") + eol := findOne(t, root, alpineAt("3.14"), RuleEOL) + f, gone, err := Find(ctx, root, "Dockerfile", eol.Line, RuleEOL, "", baseDown) + mustDecline(t, "end-of-life, no message", f, gone, err) + // Buildroot with the C library commented out, no message. + root = t.TempDir() + write(t, root, "configs/a_defconfig", "BR2_TOOLCHAIN_BUILDROOT_MUSL=y\nBR2_PACKAGE_OPENSSH=y\n") + b := findOne(t, root, Options{}, RuleBuild) + write(t, root, "configs/a_defconfig", "# BR2_TOOLCHAIN_BUILDROOT_MUSL=y\nBR2_PACKAGE_OPENSSH=y\n") + f, gone, err = Find(ctx, root, b.File, b.Line, RuleBuild, "", Options{}) + mustDecline(t, "buildroot, no message", f, gone, err) +} + +// 2: a variable in the image keeps what the name says; ARG values expand. +func TestReview2NameWithVariable(t *testing.T) { + for _, c := range []struct { + from, apk, rule string + fixable bool + }{ + {"ARG V\nFROM alpine:${V}", "openssh-server", RuleUnpinned, false}, + {"FROM alpine:${ALPINE_VERSION}", "openssh-server=9.9_p1-r2", RulePin, false}, + {"FROM python:${PY}-alpine", "openssh-server", RuleUnpinned, false}, + {"FROM python:${PY}-alpine3.21", "openssh-server", RuleUnpinned, true}, + {"FROM node:${NODE}-alpine3.14", "openssh-server", RuleEOL, false}, + {"ARG TAG=3.21\nARG BASE=alpine:${TAG}\nFROM ${BASE}", "openssh-server", RuleUnpinned, true}, + {"FROM python:${PY}-alpine3.1${X}", "openssh-server", RuleUnpinned, false}, + } { + root := t.TempDir() + write(t, root, "Dockerfile", c.from+"\nRUN apk add "+c.apk+"\n") + f := findOne(t, root, Options{}, c.rule) + if f.Fixable != c.fixable { + t.Errorf("%q: fixable %v: %+v", c.from, f.Fixable, f) + } + if strings.Contains(f.Message, "is not known") { + t.Errorf("%q: %q", c.from, f.Message) + } + } + // The registry is never asked about an image it cannot name. + root := t.TempDir() + write(t, root, "Dockerfile", "FROM alpine:${V}\nRUN apk add openssh-server\n") + o := Options{Base: func(_ context.Context, img string) (bool, string, error) { + t.Errorf("looked up %q", img) + return true, "3.21", nil + }} + findOne(t, root, o, RuleUnpinned) +} + +// 3: a tag cut short by an unset variable is not a release. +func TestReview2TagCutShort(t *testing.T) { + for _, tag := range []string{"3.${MINOR}", "3_${X}", "3-${X}"} { + if validImage("alpine:" + strings.Split(tag, "$")[0]) { + t.Errorf("%s: valid", tag) + } + root := t.TempDir() + write(t, root, "Dockerfile", "FROM alpine:"+tag+"\nRUN apk add openssh-server\n") + if f := findOne(t, root, Options{}, RuleUnpinned); f.Fixable { + t.Errorf("%s: %+v", tag, f) + } + } +} + +// Nit 4: end-of-life, lookup down and the line shifted. +func TestReview2EOLShifted(t *testing.T) { + root := t.TempDir() + write(t, root, "Dockerfile", "FROM acme/app:alpine\nRUN apk add openssh-server\n") + eol := findOne(t, root, alpineAt("3.14"), RuleEOL) + write(t, root, "Dockerfile", "# a comment\nFROM acme/app:alpine\nRUN apk add openssh-server\n") + f, gone, err := Find(context.Background(), root, "Dockerfile", eol.Line, RuleEOL, eol.Message, baseDown) + mustDecline(t, "shifted, lookup down", f, gone, err) +} + +// Nit 7: two pins on one line, the first fixed. +func TestReview2OtherPackageOnLine(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + write(t, root, "Dockerfile", "FROM alpine:3.21\nRUN apk add openssh-server=9.9_p1-r2 openssh=9.9_p1-r2\n") + var first Finding + for _, f := range scan(t, root, Options{}) { + if f.Props["package"] == "openssh-server" { + first = f + } + } + write(t, root, "Dockerfile", "FROM alpine:3.21\nRUN apk add 'openssh-server=9.9_p2-r1' openssh=9.9_p1-r2\n") + f, gone, err := Find(ctx, root, "Dockerfile", first.Line, RulePin, first.Message, Options{}) + mustBeGone(t, "first pin fixed", f, gone, err) +} + +// Nit 8: the note names the image and every variable before it. +func TestReview2PrefixNote(t *testing.T) { + root := t.TempDir() + write(t, root, "Dockerfile", "FROM ${A}/${B}/alpine:3.21 AS b\nFROM b\nRUN apk add openssh-server\n") + f := findOne(t, root, Options{}, RuleUnpinned) + if !strings.Contains(f.Message, "${A}/${B}") || !strings.Contains(f.Message, "judged as alpine:3.21") { + t.Errorf("%q", f.Message) + } +} diff --git a/detectors/sshole/internal/repo/review_test.go b/detectors/sshole/internal/repo/review_test.go index 3b95d9c..076dc08 100644 --- a/detectors/sshole/internal/repo/review_test.go +++ b/detectors/sshole/internal/repo/review_test.go @@ -257,11 +257,12 @@ func TestReviewFromVariables(t *testing.T) { } } -// 12: a tag made only of unset variables is not known, and not fixed. +// 12, round 2 #2: a tag made of unset variables keeps what the name says +// (Alpine), without a branch, so nothing is end-of-life or rewritten. func TestReviewTagOfVariables(t *testing.T) { root := t.TempDir() write(t, root, "Dockerfile", "FROM alpine:${MAJOR}.${MINOR}\nRUN apk add openssh-server\n") - if f := findOne(t, root, Options{}, RuleNotChecked); f.Fixable { + if f := findOne(t, root, Options{}, RuleUnpinned); f.Fixable { t.Errorf("%+v", f) } } From fb38b1177b801c506efe51d07ec588abd06dabbe Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 06:28:52 +0000 Subject: [PATCH 4/5] sshole: nits from the third review of the not-checked change - The variable a finding came through is read only from the end of its message (before the prefix note), so a spec quoting "(through $Y" is not taken for variable Y; it is a FuzzScanText seed now. - A spec with a space matches itself elsewhere in the file: the key keeps the message after its verb, which starts with the whole spec. - Find documents that callers must pass the message: with none, only the exact line is looked at. - An image whose name is a variable says nothing about glibc, but its tag can still say Alpine (${IMG}:alpine), as on main. - Tests for a moved build finding found with no message or a reworded one, a variable image name, and a legacy ENV value that expands an earlier one. Co-Authored-By: Claude Opus 5.5 --- detectors/sshole/internal/repo/plan.go | 20 +++++- detectors/sshole/internal/repo/repo.go | 9 ++- detectors/sshole/internal/repo/repo_test.go | 1 + .../sshole/internal/repo/review3_test.go | 66 +++++++++++++++++++ 4 files changed, 90 insertions(+), 6 deletions(-) create mode 100644 detectors/sshole/internal/repo/review3_test.go diff --git a/detectors/sshole/internal/repo/plan.go b/detectors/sshole/internal/repo/plan.go index 75a5b6f..c89760b 100644 --- a/detectors/sshole/internal/repo/plan.go +++ b/detectors/sshole/internal/repo/plan.go @@ -303,6 +303,10 @@ func Printable(s string) string { // image that cannot be read this time; another finding for the same package // on the line; and a line past the end of a file that still has findings // like it. +// +// Callers (Sensei's /fix) must pass the finding's message: with none, only +// the exact line is looked at, so a finding that moved is not followed and +// declines, and a line with several findings of the rule returns the first. func Find(ctx context.Context, root, file string, line int, rule, message string, opts Options) (f *Finding, gone bool, err error) { if !findRules[rule] || kindOf(file) == "" { return nil, false, notChecked("%s findings in %s are not rescanned here, so it is not checked", rule, file) @@ -391,7 +395,7 @@ func Find(ctx context.Context, root, file string, line int, rule, message string // The same package, variable or build system, anywhere in // the file: this rescan could not judge it. return nil, false, notChecked("%s:%d is not checked this time (%s)", file, g.Line, g.Message) - case apk && (k.pkg != "" && g.Props["package"] == k.pkg && (g.Line == line || g.Props["spec"] == k.spec) || k.any && apkRule && g.Line == line): + case apk && (k.pkg != "" && g.Props["package"] == k.pkg && (g.Line == line || k.sameSpec(g.Props["spec"])) || k.any && apkRule && g.Line == line): // The same package under another rule (a pin loosened, an // end-of-life base no longer known as one), on the line or // with the same spec elsewhere (the line moved). @@ -417,8 +421,10 @@ var findRules = map[string]bool{RulePin: true, RuleUnpinned: true, RuleEOL: true var ( lineRefRE = regexp.MustCompile(`, set on line \d+\)`) - viaRE = regexp.MustCompile(`\(through \$([A-Za-z_][A-Za-z0-9_]*)`) - tclibcRE = regexp.MustCompile(` and (\S+):\d+ sets TCLIBC`) + // The variable suffix ends the message, before only the prefix note + // (whose parts hold no spaces), so a spec cannot fake one. + viaRE = regexp.MustCompile(`\(through \$([A-Za-z_][A-Za-z0-9_]*)\)(?: \(the image starts with \S+, which this file does not set; judged as \S+\))?$`) + tclibcRE = regexp.MustCompile(` and (\S+):\d+ sets TCLIBC`) ) // findKey is what a finding's message names: the OpenSSH package and the @@ -426,6 +432,7 @@ var ( // any: the message should name one and does not, so anything matches. type findKey struct { pkg, spec, via, system string + rest string // the message after its verb, which starts with the whole spec any bool } @@ -435,6 +442,7 @@ func keyOf(msg string) findKey { if len(w) >= 2 && (w[0] == "installs" || w[0] == "pins") { if m := specRE.FindStringSubmatch(strings.Trim(w[1], `'"`)); m != nil && sshPackages[m[1]] { k.pkg, k.spec = m[1], m[0] + k.rest = strings.TrimSpace(strings.TrimPrefix(msg, w[0])) } } if m := viaRE.FindStringSubmatch(msg); m != nil { @@ -451,6 +459,12 @@ func keyOf(msg string) findKey { return k } +// sameSpec reports whether spec is the one the message quotes; one with +// a space is cut short in k.spec. +func (k findKey) sameSpec(spec string) bool { + return spec != "" && (spec == k.spec || strings.HasPrefix(k.rest, spec+" ")) +} + // holds reports whether a not-checked finding is about what k names. func (k findKey) holds(g Finding) bool { if k.any { diff --git a/detectors/sshole/internal/repo/repo.go b/detectors/sshole/internal/repo/repo.go index 1ac7b6c..e303560 100644 --- a/detectors/sshole/internal/repo/repo.go +++ b/detectors/sshole/internal/repo/repo.go @@ -685,9 +685,9 @@ func baseFromName(img string) baseInfo { name, tag = name[:i], name[i+1:] } repo := path.Base(name) - if strings.Contains(repo, "$") { - return baseInfo{} // the image is a variable the file does not set - } + // The name is a variable the file does not set: only a tag can say + // Alpine (${IMG}:alpine), and the name says nothing about glibc. + unnamed := strings.Contains(repo, "$") // A variable in the tag: the name still says Alpine, but not which // release, and the image is never looked up. vary := strings.Contains(tag, "$") @@ -711,6 +711,9 @@ func baseFromName(img string) baseInfo { } return baseInfo{alpine: true, known: true} } + if unnamed { + return baseInfo{} + } for _, glibc := range []string{"wolfi", "chainguard", "debian", "ubuntu", "fedora", "centos", "rockylinux", "almalinux", "amazonlinux", "ubi", "distroless"} { if strings.Contains(name, glibc) { return baseInfo{known: true} diff --git a/detectors/sshole/internal/repo/repo_test.go b/detectors/sshole/internal/repo/repo_test.go index 6c5ff3a..c2910ea 100644 --- a/detectors/sshole/internal/repo/repo_test.go +++ b/detectors/sshole/internal/repo/repo_test.go @@ -226,6 +226,7 @@ func TestSplitShell(t *testing.T) { func FuzzScanText(f *testing.F) { f.Add(svc) f.Add("RUN apk add 'x\nFROM\n\\") + f.Add("FROM alpine:3.21\nRUN apk add 'openssh-server=1 (through $Y'\n") f.Fuzz(func(t *testing.T, s string) { sc := &scanner{ctx: context.Background(), bases: map[string]baseInfo{}} for _, x := range sc.dockerfile("Dockerfile", s) { diff --git a/detectors/sshole/internal/repo/review3_test.go b/detectors/sshole/internal/repo/review3_test.go new file mode 100644 index 0000000..3fe0fd3 --- /dev/null +++ b/detectors/sshole/internal/repo/review3_test.go @@ -0,0 +1,66 @@ +package repo + +import ( + "context" + "testing" +) + +// Cases from the third review of the not-checked change. + +// Nit 4: a spec that quotes "(through $Y" is not a variable install. +func TestReview3CraftedVia(t *testing.T) { + root := t.TempDir() + write(t, root, "Dockerfile", "FROM alpine:3.21\nRUN apk add 'openssh-server=1 (through $Y'\n") + pin := findOne(t, root, Options{}, RulePin) + if k := keyOf(pin.Message); k.via != "" { + t.Errorf("via %q from %q", k.via, pin.Message) + } + // A real one, with the prefix note after it, still reads. + write(t, root, "Dockerfile", "FROM ${R}alpine:3.21\nARG PKGS=\"openssh-server=9.9_p1-r2\"\nRUN apk add $PKGS\n") + pin = findOne(t, root, Options{}, RulePin) + if k := keyOf(pin.Message); k.via != "PKGS" { + t.Errorf("via %q from %q", k.via, pin.Message) + } +} + +// Nit 5: a spec with a space, the line shifted and the lookup down. +func TestReview3SpecWithSpace(t *testing.T) { + root := t.TempDir() + write(t, root, "Dockerfile", "FROM acme/app:alpine\nRUN apk add 'openssh-server>=9.0 x'\n") + eol := findOne(t, root, alpineAt("3.14"), RuleEOL) + write(t, root, "Dockerfile", "# a comment\nFROM acme/app:alpine\nRUN apk add 'openssh-server>=9.0 x'\n") + f, gone, err := Find(context.Background(), root, "Dockerfile", eol.Line, RuleEOL, eol.Message, baseDown) + mustDecline(t, "spaced spec", f, gone, err) +} + +// Nit 7: a build finding that moved, found with no message or a reworded one. +func TestReview3BuildMoved(t *testing.T) { + root := t.TempDir() + write(t, root, "configs/a_defconfig", "BR2_TOOLCHAIN_BUILDROOT_MUSL=y\nBR2_PACKAGE_OPENSSH=y\n") + b := findOne(t, root, Options{}, RuleBuild) + write(t, root, "configs/a_defconfig", "# moved\nBR2_TOOLCHAIN_BUILDROOT_MUSL=y\nBR2_PACKAGE_OPENSSH=y\n") + for _, msg := range []string{"", "Buildroot configuration builds the OpenSSH server against musl; worded as it was before"} { + f, gone, err := Find(context.Background(), root, b.File, b.Line, RuleBuild, msg, Options{}) + mustDecline(t, "moved, message "+msg, f, gone, err) + } +} + +// Nit 7: an image whose name is a variable says nothing about glibc; its +// tag can still say Alpine, as on main. +func TestReview3VariableRepository(t *testing.T) { + for _, c := range []struct{ from, rule string }{ + {"FROM ${debian_base}", RuleNotChecked}, + {"FROM ${IMG}:alpine", RuleUnpinned}, + } { + root := t.TempDir() + write(t, root, "Dockerfile", c.from+"\nRUN apk add openssh-server\n") + findOne(t, root, Options{}, c.rule) + } +} + +// Nit 7: a legacy ENV value expands the variables already set. +func TestReview3LegacyEnv(t *testing.T) { + root := t.TempDir() + write(t, root, "Dockerfile", "FROM alpine:3.21 AS a\nENV TAG 3.14\nENV BASE alpine:${TAG}\nFROM ${BASE}\nRUN apk add openssh-server\n") + findOne(t, root, Options{}, RuleEOL) +} From a82cef221f9dde4bce6408bcf1d029157d94bcd7 Mon Sep 17 00:00:00 2001 From: Greg Anderson Date: Wed, 18 Nov 2026 21:37:16 +0000 Subject: [PATCH 5/5] sshole: follow-ups from the final review of the not-checked change - The variable a finding came through is read after trimming a trailing full stop, spaces and newlines from the message, so a stored message that ends in one still names it and a removed ARG is not gone. - With no message, an apk finding no longer on its line declines while the file still has any apk finding (it may be this one, moved); before, only its own line was looked at and it read as gone. - Find's doc says which rules follow a moved finding: all of them with the message; with none, the apk rules and build-config decline, and star-account, password-config and ansible-apk read as gone. Co-Authored-By: Claude Opus 5.5 --- detectors/sshole/internal/repo/plan.go | 18 +++++--- .../sshole/internal/repo/review4_test.go | 46 +++++++++++++++++++ 2 files changed, 58 insertions(+), 6 deletions(-) create mode 100644 detectors/sshole/internal/repo/review4_test.go diff --git a/detectors/sshole/internal/repo/plan.go b/detectors/sshole/internal/repo/plan.go index c89760b..586da47 100644 --- a/detectors/sshole/internal/repo/plan.go +++ b/detectors/sshole/internal/repo/plan.go @@ -304,9 +304,13 @@ func Printable(s string) string { // on the line; and a line past the end of a file that still has findings // like it. // -// Callers (Sensei's /fix) must pass the finding's message: with none, only -// the exact line is looked at, so a finding that moved is not followed and -// declines, and a line with several findings of the rule returns the first. +// Callers (Sensei's /fix) must pass the finding's message. Only with it does +// Find follow a finding that moved to another line, for every rule. With +// none, only the exact line is looked at and a line with several findings +// of the rule returns the first; one not on its line declines for the apk +// rules (apk-pin, apk-unpinned, eol-base) and build-config, whose key is +// then unknown, while star-account, password-config and ansible-apk read +// as gone. func Find(ctx context.Context, root, file string, line int, rule, message string, opts Options) (f *Finding, gone bool, err error) { if !findRules[rule] || kindOf(file) == "" { return nil, false, notChecked("%s findings in %s are not rescanned here, so it is not checked", rule, file) @@ -395,10 +399,11 @@ func Find(ctx context.Context, root, file string, line int, rule, message string // The same package, variable or build system, anywhere in // the file: this rescan could not judge it. return nil, false, notChecked("%s:%d is not checked this time (%s)", file, g.Line, g.Message) - case apk && (k.pkg != "" && g.Props["package"] == k.pkg && (g.Line == line || k.sameSpec(g.Props["spec"])) || k.any && apkRule && g.Line == line): + case apk && (k.pkg != "" && g.Props["package"] == k.pkg && (g.Line == line || k.sameSpec(g.Props["spec"])) || k.any && apkRule): // The same package under another rule (a pin loosened, an // end-of-life base no longer known as one), on the line or - // with the same spec elsewhere (the line moved). + // with the same spec elsewhere (the line moved). With no key, + // any apk finding in the file: it may be this one, moved. return nil, false, notChecked("%s:%d now has %s (%s)", file, g.Line, g.Rule, g.Message) case rule == RuleBuild && g.Rule == RuleBuild && (k.any || k.system != "" && g.Props["system"] == k.system && g.Props["package"] == k.pkg): // One build finding per file and system: moved and reworded. @@ -445,7 +450,8 @@ func keyOf(msg string) findKey { k.rest = strings.TrimSpace(strings.TrimPrefix(msg, w[0])) } } - if m := viaRE.FindStringSubmatch(msg); m != nil { + // A stored message may end in a full stop or a newline. + if m := viaRE.FindStringSubmatch(strings.TrimRight(msg, ". \t\r\n")); m != nil { k.via = m[1] } switch { diff --git a/detectors/sshole/internal/repo/review4_test.go b/detectors/sshole/internal/repo/review4_test.go new file mode 100644 index 0000000..cc0136c --- /dev/null +++ b/detectors/sshole/internal/repo/review4_test.go @@ -0,0 +1,46 @@ +package repo + +import ( + "context" + "testing" +) + +// Cases from the final review of the not-checked change. + +// A message stored with a trailing full stop or newline still names its +// variable, so a removed ARG is not checked, not gone. +func TestReview4ViaTrailing(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + write(t, root, "Dockerfile", "FROM alpine:3.21\nARG PKGS=\"openssh-server=9.9_p1-r2\"\nRUN apk add $PKGS\n") + pin := findOne(t, root, Options{}, RulePin) + write(t, root, "Dockerfile", "FROM alpine:3.21\n\nRUN apk add $PKGS\n") + for _, tail := range []string{".", "\n", " ", ".\n", " .\r\n"} { + if k := keyOf(pin.Message + tail); k.via != "PKGS" { + t.Errorf("%q: via %q", tail, k.via) + } + f, gone, err := Find(ctx, root, "Dockerfile", pin.Line, RulePin, pin.Message+tail, Options{}) + mustDecline(t, "ARG removed, tail "+tail, f, gone, err) + } +} + +// With no message, Find follows no finding to another line: apk and build +// findings decline (their key is unknown), the others read as gone. +func TestReview4MovedNoMessage(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + write(t, root, "Dockerfile", "FROM alpine:3.21\nRUN apk add openssh-server=9.9_p1-r2 && usermod -p '*' bob\n") + fs := scan(t, root, Options{}) + write(t, root, "Dockerfile", "# moved\nFROM alpine:3.21\nRUN apk add openssh-server=9.9_p1-r2 && usermod -p '*' bob\n") + for _, g := range fs { + f, gone, err := Find(ctx, root, "Dockerfile", g.Line, g.Rule, "", Options{}) + switch g.Rule { + case RulePin: + mustDecline(t, "pin moved, no message", f, gone, err) + case RuleStar: + mustBeGone(t, "star moved, no message", f, gone, err) + default: + t.Fatalf("unexpected %+v", g) + } + } +}