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..586da47 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" @@ -41,14 +42,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 +58,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 +71,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 +82,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 +103,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 +128,50 @@ 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 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 { 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 +179,16 @@ func scanOne(ctx context.Context, root, file string, opts Options, data []byte) out = append(out, f) } } - return out, nil + skips := res.Skips + if res.Truncated { + skips = append(skips, Skip{Reason: "the source tree has too many files to walk"}) + } + return out, skips, 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,27 +295,54 @@ 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. +// 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. +// +// 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) { - fs, err := scanOne(ctx, root, file, opts, nil) + 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) { - 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, 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 + 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) } } - 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) } } @@ -309,12 +350,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) } } @@ -325,15 +366,143 @@ 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. + if 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) + } + 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) + } + } + 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 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 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. + 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.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+\)`) + // 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 +// 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 + rest string // the message after its verb, which starts with the whole spec + 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, k.spec = m[1], m[0] + k.rest = strings.TrimSpace(strings.TrimPrefix(msg, w[0])) + } + } + // 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 { + 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 +} + +// 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 { + 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 + } + 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"} } // 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..e303560 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 { @@ -461,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 } @@ -469,21 +470,19 @@ 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) - } 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,20 +513,104 @@ 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 { + 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 v, ok := args[name]; ok && v != "" { + } + 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 sm[2] + 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) { + 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, '/') { + // 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] + } + for _, c := range strings.Split(name, "/") { + if c == "" || strings.Trim(c, "._-") != c { + return false + } + } + return true +} + var alpineTagRE = regexp.MustCompile(`(?:^|[-_.])alpine(\d+\.\d+)`) // base decides from an image's name whether it is Alpine and which branch. @@ -601,9 +685,17 @@ func baseFromName(img string) baseInfo { name, tag = name[:i], name[i+1:] } repo := path.Base(name) + // 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, "$") 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"): @@ -614,11 +706,14 @@ 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} } + 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} @@ -956,10 +1051,16 @@ func (s *scanner) judgeSpec(rel string, at specAt, pkg, op, ver string, b baseIn if image != "" { props["image"] = image } + via, judged := b.via, b.img 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, judged) + } f := Finding{File: rel, Line: l, Props: props} if !b.known { f.Rule, f.Level = RuleNotChecked, "note" @@ -976,7 +1077,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. @@ -1010,8 +1111,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 @@ -1372,7 +1474,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 69fa67c..c2910ea 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. @@ -226,12 +226,14 @@ 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) { 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/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) +} 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) + } + } +} diff --git a/detectors/sshole/internal/repo/review_test.go b/detectors/sshole/internal/repo/review_test.go new file mode 100644 index 0000000..076dc08 --- /dev/null +++ b/detectors/sshole/internal/repo/review_test.go @@ -0,0 +1,268 @@ +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, 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{}, RuleUnpinned); f.Fixable { + t.Errorf("%+v", f) + } +} 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