Commit e21492fd1a

e21492fd1a3c22ed9c49c7b54d594d6bacd97e0f

parent: b9b8a8b5b6

Verified · cmc ci/build: success ci/quality: success ci/test: success

cmc <hello@cleberg.net> · 2026-11-20 19:52 UTC

codescan: check unquoted-expansion hits against the script

A hit of bash unquoted-variable-expansion-in-command counts only where its command has an expansion the shell word-splits: not inside double quotes or arithmetic. A script that does not read to the end keeps its hits.

Closes #352

Layout: unified · split

.gitbay/wiki/Admin.org +6 −1
@@ -499,7 +499,12 @@ set aside, as are the repository's =security-ignore= paths and
499generic mode and takes a quote inside ={{ }}= for the end of the 499generic mode and takes a quote inside ={{ }}= for the end of the
500attribute, is checked against the template at the scanned commit: it 500attribute, is checked against the template at the scanned commit: it
501counts only where an expression there is an unquoted attribute value 501counts only where an expression there is an unquoted attribute value
502or stands in for attributes. The issue says how many were set aside 502or stands in for attributes. A hit of
503=bash/lang/correctness/unquoted-variable-expansion-in-command=, which
504also reports an expansion inside a =$(( ))= in double quotes, is checked against the script the same way: it
505counts only where the command has an expansion the shell word-splits.
506A file either check cannot read to the end keeps its hits. The issue
507says how many were set aside
503and why. A finding a writer dismisses (=repo security dismiss=, by the 508and why. A finding a writer dismisses (=repo security dismiss=, by the
504fingerprint the issue prints) stays out of the issue across scans until 509fingerprint the issue prints) stays out of the issue across scans until
505it is reopened; the issue closes when nothing is left open. 510it is reopened; the issue closes when nothing is left open.
internal/codescan/codescan.go +3
@@ -320,6 +320,9 @@ func Body(r Report) string {
320 if r.Aside.Quoted > 0 { 320 if r.Aside.Quoted > 0 {
321 notListed = append(notListed, fmt.Sprintf("%d unquoted-attribute hits on attributes the template quotes", r.Aside.Quoted)) 321 notListed = append(notListed, fmt.Sprintf("%d unquoted-attribute hits on attributes the template quotes", r.Aside.Quoted))
322 } 322 }
323 if r.Aside.Unsplit > 0 {
324 notListed = append(notListed, fmt.Sprintf("%d unquoted-expansion hits on expansions the shell does not split", r.Aside.Unsplit))
325 }
323 if len(notListed) > 0 { 326 if len(notListed) > 0 {
324 fmt.Fprintf(&b, "\nNot listed: %s. `repo security status %s` shows them.\n", strings.Join(notListed, "; "), r.Repo) 327 fmt.Fprintf(&b, "\nNot listed: %s. `repo security status %s` shows them.\n", strings.Join(notListed, "; "), r.Repo)
325 } 328 }
internal/codescan/scope.go +18 −13
@@ -28,16 +28,18 @@ type Scope struct {
28 28
29// Aside counts the findings a scope set aside: Ignored by path or rule, 29// Aside counts the findings a scope set aside: Ignored by path or rule,
30// Unused by the library a rule is about, Quoted by reading the template an 30// Unused by the library a rule is about, Quoted by reading the template an
31// unquoted-attribute hit is in. 31// unquoted-attribute hit is in, Unsplit by reading the script an
32// unquoted-expansion hit is in.
32type Aside struct { 33type Aside struct {
33 Ignored int `json:"ignored,omitempty"` 34 Ignored int `json:"ignored,omitempty"`
34 Unused map[string]int `json:"unused,omitempty"` 35 Unused map[string]int `json:"unused,omitempty"`
35 Quoted int `json:"quoted,omitempty"` 36 Quoted int `json:"quoted,omitempty"`
37 Unsplit int `json:"unsplit,omitempty"`
36} 38}
37 39
38// Any reports whether anything was set aside. 40// Any reports whether anything was set aside.
39func (a Aside) Any() bool { 41func (a Aside) Any() bool {
40 return a.Ignored > 0 || len(a.Unused) > 0 || a.Quoted > 0 42 return a.Ignored > 0 || len(a.Unused) > 0 || a.Quoted > 0 || a.Unsplit > 0
41} 43}
42 44
43// Apply splits findings into those reported, at most MaxFindings of them, 45// Apply splits findings into those reported, at most MaxFindings of them,
@@ -47,7 +49,7 @@ func (s Scope) Apply(findings []store.SecurityFinding) ([]store.SecurityFinding,
47 var kept []store.SecurityFinding 49 var kept []store.SecurityFinding
48 var aside Aside 50 var aside Aside
49 truncated := false 51 truncated := false
50 unquoted := map[string]map[int]bool{} 52 unquoted, unsplit := map[string]map[int]bool{}, map[string]map[int]bool{}
51 for _, f := range findings { 53 for _, f := range findings {
52 if s.ignored(f) { 54 if s.ignored(f) {
53 aside.Ignored++ 55 aside.Ignored++
@@ -60,10 +62,14 @@ func (s Scope) Apply(findings []store.SecurityFinding) ([]store.SecurityFinding,
60 aside.Unused[l.name()]++ 62 aside.Unused[l.name()]++
61 continue 63 continue
62 } 64 }
63 if ruleIn(f.Rule, unquotedAttrRule) && !s.unquoted(f, unquoted) { 65 if ruleIn(f.Rule, unquotedAttrRule) && !s.onLine(f, unquoted, unquotedLines) {
64 aside.Quoted++ 66 aside.Quoted++
65 continue 67 continue
66 } 68 }
69 if ruleIn(f.Rule, unquotedExpansionRule) && !s.onLine(f, unsplit, splitLines) {
70 aside.Unsplit++
71 continue
72 }
67 if len(kept) == MaxFindings { 73 if len(kept) == MaxFindings {
68 truncated = true 74 truncated = true
69 continue 75 continue
@@ -73,23 +79,22 @@ func (s Scope) Apply(findings []store.SecurityFinding) ([]store.SecurityFinding,
73 return kept, aside, truncated 79 return kept, aside, truncated
74} 80}
75 81
76// unquoted reports whether an unquoted-attribute hit is on a line where the 82// onLine reports whether a hit is on a line that lines, reading the file,
77// template has an unquoted attribute expression, or the file cannot be 83// marks, or the file cannot be read to say. Files are read once, into seen.
78// read to say. Files are read once, into seen. 84func (s Scope) onLine(f store.SecurityFinding, seen map[string]map[int]bool, lines func([]byte) (map[int]bool, bool)) bool {
79func (s Scope) unquoted(f store.SecurityFinding, seen map[string]map[int]bool) bool {
80 if s.Read == nil || f.Path == "" || f.Line == 0 { 85 if s.Read == nil || f.Path == "" || f.Line == 0 {
81 return true 86 return true
82 } 87 }
83 lines, read := seen[f.Path] 88 marked, read := seen[f.Path]
84 if !read { 89 if !read {
85 if src, err := s.Read(f.Path); err == nil { 90 if src, err := s.Read(f.Path); err == nil {
86 if l, ok := unquotedLines(src); ok { 91 if l, ok := lines(src); ok {
87 lines = l 92 marked = l
88 } 93 }
89 } 94 }
90 seen[f.Path] = lines 95 seen[f.Path] = marked
91 } 96 }
92 return lines == nil || lines[f.Line] 97 return marked == nil || marked[f.Line]
93} 98}
94 99
95func (s Scope) ignored(f store.SecurityFinding) bool { 100func (s Scope) ignored(f store.SecurityFinding) bool {
internal/codescan/shell.go added +272
@@ -0,0 +1,272 @@
1package codescan
2
3import "strings"
4
5// unquotedExpansionRule flags a parameter expansion in a command. It
6// reports $1 in printf "%$(($1 - 1))s", where the shell splits nothing:
7// arithmetic is never word-split, and here it is inside double quotes as
8// well.
9// splitLines reads the script to tell those apart from the real thing.
10const unquotedExpansionRule = "bash.lang.correctness.unquoted-variable-expansion-in-command"
11
12// Shell contexts. In a command, a backtick or a $( ) an expansion is
13// word-split; in double quotes and arithmetic it is not.
14const (
15 shCommand = iota
16 shSubst
17 shBacktick
18 shDouble
19 shArith
20)
21
22type shFrame struct {
23 kind int
24 depth int // ( open within the frame
25}
26
27type heredoc struct {
28 delim string
29 strip, quoted bool
30}
31
32// splitLines returns the lines of a shell script that hold an expansion
33// the shell word-splits: $name, ${…}, $1, $* or $@ outside double quotes
34// and arithmetic. A command that runs over several lines marks all of
35// them. ok is false when the script does not read to the end with every
36// quote, bracket and heredoc closed, and then nothing is known.
37func splitLines(src []byte) (lines map[int]bool, ok bool) {
38 s := string(src)
39 lines = map[int]bool{}
40 stack := []shFrame{{kind: shCommand}}
41 line, first := 1, 1
42 split := false
43 var pending []heredoc
44 push := func(kind int) { stack = append(stack, shFrame{kind: kind}) }
45 pop := func() { stack = stack[:len(stack)-1] }
46 for i := 0; i < len(s); i++ {
47 c := s[i]
48 top := &stack[len(stack)-1]
49 if c == '\n' {
50 line++
51 if top.kind == shDouble || top.kind == shArith {
52 continue
53 }
54 end, l, sp, ok := heredocs(s, i+1, pending)
55 if !ok {
56 return nil, false
57 }
58 i, line, split, pending = end-1, line+l, split || sp, nil
59 if len(stack) == 1 {
60 if split {
61 for l := first; l < line; l++ {
62 lines[l] = true
63 }
64 }
65 first, split = line, false
66 }
67 continue
68 }
69 if c == '\\' {
70 if i+1 < len(s) && s[i+1] == '\n' {
71 line++
72 }
73 i++
74 continue
75 }
76 if c == '$' {
77 n, kind, splits := dollar(s, i, top.kind)
78 if n < 0 {
79 return nil, false
80 }
81 line += strings.Count(s[i:i+n], "\n")
82 split = split || splits
83 if kind >= 0 {
84 push(kind)
85 }
86 i += n - 1
87 continue
88 }
89 switch top.kind {
90 case shDouble:
91 switch c {
92 case '"':
93 pop()
94 case '`':
95 push(shBacktick)
96 }
97 case shArith:
98 switch {
99 case c == '"':
100 push(shDouble)
101 case c == '(':
102 top.depth++
103 case c == ')' && top.depth > 0:
104 top.depth--
105 case c == ')':
106 if i+1 >= len(s) || s[i+1] != ')' {
107 return nil, false
108 }
109 pop()
110 i++
111 }
112 default: // shCommand, shSubst, shBacktick
113 switch {
114 case c == '\'':
115 end := strings.IndexByte(s[i+1:], '\'')
116 if end < 0 {
117 return nil, false
118 }
119 line += strings.Count(s[i+1:i+1+end], "\n")
120 i += 1 + end
121 case c == '"':
122 push(shDouble)
123 case c == '`' && top.kind == shBacktick:
124 pop()
125 case c == '`':
126 push(shBacktick)
127 case c == '#' && (i == 0 || strings.IndexByte(" \t\n;|&(", s[i-1]) >= 0):
128 if end := strings.IndexByte(s[i:], '\n'); end >= 0 {
129 i += end - 1
130 } else {
131 i = len(s)
132 }
133 case c == '(':
134 top.depth++
135 case c == ')' && top.depth > 0:
136 top.depth--
137 case c == ')' && top.kind == shSubst:
138 pop()
139 case strings.HasPrefix(s[i:], "<<") && !strings.HasPrefix(s[i:], "<<<"):
140 h, n := heredocOp(s, i)
141 if n < 0 {
142 return nil, false
143 }
144 pending = append(pending, h)
145 i += n - 1
146 }
147 }
148 }
149 if len(stack) != 1 || len(pending) > 0 {
150 return nil, false
151 }
152 if split {
153 for l := first; l <= line; l++ {
154 lines[l] = true
155 }
156 }
157 return lines, true
158}
159
160// dollar reads the expansion starting with the $ at i, in a context of
161// kind ctx. n is how many bytes it takes, or -1 when it is not closed;
162// kind is the frame it opens, or -1; splits is whether the shell
163// word-splits it there.
164func dollar(s string, i, ctx int) (n, kind int, splits bool) {
165 splitting := ctx != shDouble && ctx != shArith
166 rest := s[i+1:]
167 switch {
168 case strings.HasPrefix(rest, "(("):
169 return 3, shArith, false
170 case strings.HasPrefix(rest, "("):
171 return 2, shSubst, false
172 case strings.HasPrefix(rest, "{"):
173 depth := 0
174 for j := 1; j < len(s)-i; j++ {
175 switch s[i+j] {
176 case '\\':
177 j++
178 case '{':
179 depth++
180 case '}':
181 if depth--; depth == 0 {
182 return j + 1, -1, splitting
183 }
184 }
185 }
186 return -1, -1, false
187 case strings.HasPrefix(rest, "'") && ctx != shDouble:
188 for j := 2; j < len(s)-i; j++ {
189 switch s[i+j] {
190 case '\\':
191 j++
192 case '\'':
193 return j + 1, -1, false
194 }
195 }
196 return -1, -1, false
197 case strings.HasPrefix(rest, `"`) && ctx != shDouble:
198 return 2, shDouble, false
199 case rest != "" && (rest[0] == '_' || isLetter(rest[0])):
200 j := 1
201 for j < len(rest) && (rest[j] == '_' || isLetter(rest[j]) || rest[j] >= '0' && rest[j] <= '9') {
202 j++
203 }
204 return j + 1, -1, splitting
205 case rest != "" && (rest[0] >= '0' && rest[0] <= '9' || rest[0] == '*' || rest[0] == '@'):
206 return 2, -1, splitting
207 }
208 // $# $? $$ $! $- expand to text with no separators in it; a bare $ is
209 // literal.
210 if rest != "" && strings.IndexByte("#?$!-", rest[0]) >= 0 {
211 return 2, -1, false
212 }
213 return 1, -1, false
214}
215
216// heredocOp reads a << or <<- operator and its delimiter word at i. n is
217// how many bytes it takes, or -1 when there is no word.
218func heredocOp(s string, i int) (heredoc, int) {
219 j := i + 2
220 var h heredoc
221 if j < len(s) && s[j] == '-' {
222 h.strip = true
223 j++
224 }
225 for j < len(s) && (s[j] == ' ' || s[j] == '\t') {
226 j++
227 }
228 start := j
229 for j < len(s) && strings.IndexByte(" \t\n;|&<>()", s[j]) < 0 {
230 j++
231 }
232 word := s[start:j]
233 h.quoted = strings.ContainsAny(word, `'"\`)
234 h.delim = strings.NewReplacer(`'`, "", `"`, "", `\`, "").Replace(word)
235 if h.delim == "" {
236 return h, -1
237 }
238 return h, j - i
239}
240
241// heredocs reads the bodies of the pending heredocs from i, the start of
242// the line after their operators. end is just past the last delimiter
243// line, n the lines read. A body that is not quoted and runs a command
244// substitution counts as splitting, since the command inside is not
245// read here.
246func heredocs(s string, i int, pending []heredoc) (end, n int, splits, ok bool) {
247 for _, h := range pending {
248 for {
249 if i >= len(s) {
250 return 0, 0, false, false
251 }
252 nl := strings.IndexByte(s[i:], '\n')
253 text := s[i:]
254 next := len(s)
255 if nl >= 0 {
256 text, next = s[i:i+nl], i+nl+1
257 n++
258 }
259 if !h.quoted && (strings.Contains(text, "$(") || strings.Contains(text, "`")) {
260 splits = true
261 }
262 i = next
263 if h.strip {
264 text = strings.TrimLeft(text, "\t")
265 }
266 if text == h.delim {
267 break
268 }
269 }
270 }
271 return i, n, splits, true
272}
internal/codescan/shell_test.go added +97
@@ -0,0 +1,97 @@
1package codescan
2
3import (
4 "errors"
5 "testing"
6
7 "gitbay.org/gitbay/internal/store"
8)
9
10func TestSplitLines(t *testing.T) {
11 for _, tc := range []struct {
12 name, src string
13 want bool
14 }{
15 {"arithmetic in double quotes", `text() { printf '×'; printf "%$(($1 - 1))s" '' | tr ' ' x; }`, false},
16 {"bare arithmetic", `echo $(( $n + 1 ))`, false},
17 {"nested arithmetic parens", `echo "$(( ($a + $b) * 2 ))"`, false},
18 {"double quoted", `echo "$x ${y:-a b}"`, false},
19 {"single quoted", `echo '$x'`, false},
20 {"ansi-c quoted", `echo $'a\'$x'`, false},
21 {"escaped dollar", `echo \$x`, false},
22 {"special parameters", `echo $# $? $$ $! $-`, false},
23 {"comment", `echo ok # $x`, false},
24 {"comment line", "# the repo's own\necho \"$x\"", false},
25 {"quoted heredoc", "cat <<'EOF'\n$(id) $x\nEOF", false},
26 {"unquoted", `echo $x`, true},
27 {"unquoted braces", `echo ${x}`, true},
28 {"positional", `rm $1`, true},
29 {"all arguments", `f $@`, true},
30 {"command substitution in quotes", `echo "$(ls $dir)"`, true},
31 {"command substitution in arithmetic", `echo $(( $(wc -l <$f) + 1 ))`, true},
32 {"backticks in quotes", "echo \"`ls $dir`\"", true},
33 {"after quoted arithmetic", `printf "%$(($1 - 1))s" $x`, true},
34 } {
35 lines, ok := splitLines([]byte(tc.src))
36 if !ok {
37 t.Errorf("%s: not read", tc.name)
38 continue
39 }
40 if lines[1] != tc.want {
41 t.Errorf("%s: split = %v, want %v", tc.name, lines[1], tc.want)
42 }
43 }
44}
45
46func TestSplitLinesAcrossLines(t *testing.T) {
47 src := "a=\"$(($n\n+ 1))\"\necho \\\n $x\ncat <<EOF\n$(id)\nEOF\necho \"$y\"\n"
48 lines, ok := splitLines([]byte(src))
49 want := map[int]bool{3: true, 4: true, 5: true, 6: true, 7: true}
50 if !ok || len(lines) != len(want) {
51 t.Fatalf("lines = %v ok %v", lines, ok)
52 }
53 for l := range want {
54 if !lines[l] {
55 t.Errorf("line %d not marked: %v", l, lines)
56 }
57 }
58 for _, src := range []string{`echo "$x`, `echo '$x`, `echo $((1 + 2)`, `echo $(ls`, `echo ${x`, "cat <<EOF\nbody\n", `echo $'x`} {
59 if _, ok := splitLines([]byte(src)); ok {
60 t.Errorf("%q read", src)
61 }
62 }
63}
64
65func TestScopeChecksShellSplitting(t *testing.T) {
66 rule := "opt.opengrep-rules.bash.lang.correctness.unquoted-variable-expansion-in-command"
67 files := map[string]string{
68 "quoted.sh": "#!/bin/sh\nprintf \"%$(($1 - 1))s\" ''\n",
69 "unquoted.sh": "rm $1\n",
70 "broken.sh": "echo \"$x\n",
71 }
72 read := func(p string) ([]byte, error) {
73 if src, ok := files[p]; ok {
74 return []byte(src), nil
75 }
76 return nil, errors.New("missing")
77 }
78 findings := []store.SecurityFinding{
79 {Rule: rule, Path: "quoted.sh", Line: 2},
80 {Rule: rule, Path: "unquoted.sh", Line: 1},
81 {Rule: rule, Path: "broken.sh", Line: 1},
82 {Rule: rule, Path: "gone.sh", Line: 1},
83 {Rule: "other", Path: "quoted.sh", Line: 2},
84 }
85 kept, aside, _ := Scope{Read: read}.Apply(findings)
86 if aside.Unsplit != 1 || len(kept) != 4 {
87 t.Fatalf("kept %+v aside %+v", kept, aside)
88 }
89 for _, f := range kept {
90 if f.Path == "quoted.sh" && f.Rule == rule {
91 t.Errorf("unsplit hit kept")
92 }
93 }
94 if kept, aside, _ := (Scope{}).Apply(findings); aside.Unsplit != 0 || len(kept) != 5 {
95 t.Errorf("without Read: kept %d aside %+v", len(kept), aside)
96 }
97}
internal/control/security.go +3
@@ -491,6 +491,9 @@ func asideText(a codescan.Aside) string {
491 if a.Quoted > 0 { 491 if a.Quoted > 0 {
492 parts = append(parts, fmt.Sprintf("%d quoted attributes", a.Quoted)) 492 parts = append(parts, fmt.Sprintf("%d quoted attributes", a.Quoted))
493 } 493 }
494 if a.Unsplit > 0 {
495 parts = append(parts, fmt.Sprintf("%d unsplit expansions", a.Unsplit))
496 }
494 return strings.Join(parts, ", ") 497 return strings.Join(parts, ", ")
495} 498}
496 499
internal/web/templates/settings.html +1 −1
@@ -188,7 +188,7 @@
188</form>{{end}} 188</form>{{end}}
189{{if .Security.Enabled}} 189{{if .Security.Enabled}}
190<p class="meta">Next scan {{.Security.NextRun}} · last results {{if .Security.LastResults}}{{when .Security.LastResults}}{{else}}never{{end}}{{if .Security.IssueNumber}} · <a href="/{{.Repo.OwnerName}}/{{.Repo.Name}}/issues/{{.Security.IssueNumber}}">#{{.Security.IssueNumber}}</a>{{end}}</p> 190<p class="meta">Next scan {{.Security.NextRun}} · last results {{if .Security.LastResults}}{{when .Security.LastResults}}{{else}}never{{end}}{{if .Security.IssueNumber}} · <a href="/{{.Repo.OwnerName}}/{{.Repo.Name}}/issues/{{.Security.IssueNumber}}">#{{.Security.IssueNumber}}</a>{{end}}</p>
191{{with .Security.Aside}}{{if .Any}}<p class="meta">Set aside by the last scan:{{if .Ignored}} {{.Ignored}} under the paths or rules below, or marked vendored or generated in <code>.gitattributes</code>.{{end}}{{range $lib, $n := .Unused}} {{$n}} from {{$lib}} rules, which no manifest names.{{end}}{{if .Quoted}} {{.Quoted}} unquoted-attribute hits on attributes the template quotes.{{end}}</p>{{end}}{{end}} 191{{with .Security.Aside}}{{if .Any}}<p class="meta">Set aside by the last scan:{{if .Ignored}} {{.Ignored}} under the paths or rules below, or marked vendored or generated in <code>.gitattributes</code>.{{end}}{{range $lib, $n := .Unused}} {{$n}} from {{$lib}} rules, which no manifest names.{{end}}{{if .Quoted}} {{.Quoted}} unquoted-attribute hits on attributes the template quotes.{{end}}{{if .Unsplit}} {{.Unsplit}} unquoted-expansion hits on expansions the shell does not split.{{end}}</p>{{end}}{{end}}
192{{if .Security.Findings}}<div class="tablewrap"><table class="keys"> 192{{if .Security.Findings}}<div class="tablewrap"><table class="keys">
193<tr class="cols"><th scope="col">location</th><th scope="col">rule</th><th scope="col">level</th><th scope="col"><span class="vh">dismiss</span></th></tr> 193<tr class="cols"><th scope="col">location</th><th scope="col">rule</th><th scope="col">level</th><th scope="col"><span class="vh">dismiss</span></th></tr>
194{{range .Security.Findings}}<tr> 194{{range .Security.Findings}}<tr>