diff --git a/policies/github_env_injection.rego b/policies/github_env_injection.rego index 0fb72c5b..3ecd8a4b 100644 --- a/policies/github_env_injection.rego +++ b/policies/github_env_injection.rego @@ -40,16 +40,16 @@ import data.lib.location # KEEP IN SYNC with policies/template_injection.rego::unsafe_patterns # (byte-for-byte; enforced by TestIssue209UnsafePatternsMatchTemplateInjection). unsafe_patterns := [ - `\${{[^}]*github\.event\.[^}]*\.(title|body)\b`, - `\${{[^}]*github\.head_ref\b`, - `\${{[^}]*github\.event\.[^}]*\.head\.(ref|label)\b`, - `\${{[^}]*github\.event\.[^}]*head_branch\b`, - `\${{[^}]*github\.event\.[^}]*head\.repo\.default_branch\b`, - `\${{[^}]*github\.event\.[^}]*head_repository\.default_branch\b`, - `\${{[^}]*github\.event\.[^}]*\.message\b`, - `\${{[^}]*github\.event\.[^}]*\.(description|homepage)\b`, - `\${{[^}]*github\.event\.[^}]*(author|committer)\.(name|email)\b`, - `\${{[^}]*github\.event\.[^}]*page_name\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*\.(title|body)\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.head_ref\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*\.head\.(ref|label)\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*head_branch\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*head\.repo\.default_branch\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*head_repository\.default_branch\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*\.message\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*\.(description|homepage)\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*(author|committer)\.(name|email)\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*page_name\b`, ] # NEWLINE-capable subset: fields that can contain a literal newline and thus @@ -58,8 +58,8 @@ unsafe_patterns := [ # cannot poison $GITHUB_ENV through an env-bound write. Used only by the # env-bound $GITHUB_ENV rule. (A subset of unsafe_patterns by construction.) newline_unsafe_patterns := [ - `\${{[^}]*github\.event\.[^}]*\.body\b`, - `\${{[^}]*github\.event\.[^}]*\.message\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*\.body\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*\.message\b`, ] # A redirect (`>>` / `>`) or `tee` writing into the named file, in `$VAR` or @@ -83,8 +83,7 @@ deny contains finding if { job := input.pipeline.jobs[i] line := split(job.scripts[j], "\n")[_] _matches(line, sink_patterns) - _matches(line, unsafe_patterns) - not _tojson_wrapped(line) + _untrusted(line, unsafe_patterns) finding := _finding(job.name, "", _direct_subject(job), _direct_line(job), "writes a user-controlled template expression into $GITHUB_ENV or $GITHUB_PATH; an attacker can hijack later steps") } @@ -95,8 +94,7 @@ deny contains finding if { some i job := input.pipeline.jobs[i] some varname - _matches(job.variables[varname], newline_unsafe_patterns) - not _tojson_wrapped(job.variables[varname]) + _untrusted(job.variables[varname], newline_unsafe_patterns) some j line := split(job.scripts[j], "\n")[_] _matches(line, env_sink_patterns) @@ -111,8 +109,7 @@ deny contains finding if { some i job := input.pipeline.jobs[i] some varname - _matches(job.variables[varname], unsafe_patterns) - not _tojson_wrapped(job.variables[varname]) + _untrusted(job.variables[varname], unsafe_patterns) some j line := split(job.scripts[j], "\n")[_] _matches(line, path_sink_patterns) @@ -130,8 +127,7 @@ deny contains finding if { some i job := input.pipeline.jobs[i] some varname - _matches(job.variables[varname], newline_unsafe_patterns) - not _tojson_wrapped(job.variables[varname]) + _untrusted(job.variables[varname], newline_unsafe_patterns) some j _heredoc_to_sink(job.scripts[j], varname, env_sink_patterns) finding := _finding(job.name, varname, _value_subject(job.variables[varname]), _var_line(job, varname), sprintf("writes $%s into $GITHUB_ENV through a heredoc/redirect; the multiline value still opens a second variable (base64-encode or use a randomised heredoc delimiter)", [varname])) @@ -143,8 +139,7 @@ deny contains finding if { some i job := input.pipeline.jobs[i] some varname - _matches(job.variables[varname], unsafe_patterns) - not _tojson_wrapped(job.variables[varname]) + _untrusted(job.variables[varname], unsafe_patterns) some j _heredoc_to_sink(job.scripts[j], varname, path_sink_patterns) finding := _finding(job.name, varname, _value_subject(job.variables[varname]), _var_line(job, varname), sprintf("writes $%s into $GITHUB_PATH through a heredoc/redirect; an attacker controls a directory placed on PATH", [varname])) @@ -180,7 +175,21 @@ _heredoc_to_sink(script, varname, sinkpatterns) if { regex.match(sprintf(`(?s)<<-?\s*["']?\w+["']?[^\n]*(%s).*\$\{?%s\b`, [sinkpat, varname]), script) } -_tojson_wrapped(s) if regex.match(`(?i)\$\{\{[^}]*\btojson\s*\(`, s) +# _untrusted: s holds an expression whose untrusted field reaches the +# output raw, that is outside every toJSON(...) call. toJSON escapes the +# newline, but only for the value it wraps: a toJSON elsewhere on the line +# (`A=${{ toJSON(github.sha) }} B=${{ github.event.issue.title }}`) or +# elsewhere in the expression (`format('{0} {1}', github.event.comment.body, +# toJSON(github.sha))`) leaves the field raw. +_untrusted(s, patterns) if { + some e in regex.find_n(`\$\{\{(?:'(?:''|[^'])*'|[^'}])*`, s, -1) + _matches(_without_tojson(e), patterns) +} + +# _without_tojson: the expression with each toJSON(...) call removed, so +# what is left is what reaches the output raw. A call with nested +# parentheses (toJSON(format(...))) is left in place and still flagged. +_without_tojson(e) := regex.replace(e, `(?i)\btojson\s*\((?:'(?:''|[^'])*'|[^'()}])*\)`, "") _finding(jobname, varname, subject, line, msg) := { "code": "ISSUE-209", @@ -198,8 +207,7 @@ _direct_line(job) := location.first({location.script_line(job, j, li) | some j, script in job.scripts some li, line in split(script, "\n") _matches(line, sink_patterns) - _matches(line, unsafe_patterns) - not _tojson_wrapped(line) + _untrusted(line, unsafe_patterns) }) # _var_line: the line of an env-bound finding (#572), the first write of @@ -209,11 +217,11 @@ _direct_line(job) := location.first({location.script_line(job, j, li) | _var_line(job, varname) := location.first(env | path) if { value := job.variables[varname] env := {n | - _matches(value, newline_unsafe_patterns) + _untrusted(value, newline_unsafe_patterns) some n in {_sink_line(job, varname, env_sink_patterns), _heredoc_line(job, varname, env_sink_patterns)} } path := {n | - _matches(value, unsafe_patterns) + _untrusted(value, unsafe_patterns) some n in {_sink_line(job, varname, path_sink_patterns), _heredoc_line(job, varname, path_sink_patterns)} } } else := 0 @@ -244,16 +252,15 @@ _direct_subject(job) := s if { some script in job.scripts some line in split(script, "\n") _matches(line, sink_patterns) - not _tojson_wrapped(line) - some e in regex.find_n(`\$\{\{[^}]*`, line, -1) - _matches(e, unsafe_patterns) + some e in regex.find_n(`\$\{\{(?:'(?:''|[^'])*'|[^'}])*`, line, -1) + _matches(_without_tojson(e), unsafe_patterns) }) } else := "" # _value_subject: the untrusted expression an env: binding holds. _value_subject(value) := s if { s := min({trim_space(trim_prefix(e, "${{")) | - some e in regex.find_n(`\$\{\{[^}]*`, value, -1) - _matches(e, unsafe_patterns) + some e in regex.find_n(`\$\{\{(?:'(?:''|[^'])*'|[^'}])*`, value, -1) + _matches(_without_tojson(e), unsafe_patterns) }) } else := "" diff --git a/policies/template_injection.rego b/policies/template_injection.rego index 67ca8db5..f2ec78fd 100644 --- a/policies/template_injection.rego +++ b/policies/template_injection.rego @@ -31,16 +31,19 @@ import data.lib.location # cannot carry an injection payload, and flagging them drowns the # real signal in false positives. # -# `[^}]*` keeps every match inside a single `${{ … }}` expression so -# an unrelated safe expression on the same line cannot trigger one. +# Between `${{` and the field, `(?:'(?:''|[^'])*'|[^'}])*` skips +# single-quoted strings whole and stops at the first `}` outside one, so +# a match stays inside one `${{ … }}` expression (an unrelated safe +# expression on the same line cannot trigger one) while a `}` in a +# literal such as format('{0}', …) does not end it (#631). unsafe_patterns := [ # Titles and bodies — issue, pull_request, comment, review, # discussion. - `\${{[^}]*github\.event\.[^}]*\.(title|body)\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*\.(title|body)\b`, # Branch / ref names controlled on the attacker's fork. - `\${{[^}]*github\.head_ref\b`, - `\${{[^}]*github\.event\.[^}]*\.head\.(ref|label)\b`, - `\${{[^}]*github\.event\.[^}]*head_branch\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.head_ref\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*\.head\.(ref|label)\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*head_branch\b`, # default_branch is attacker-controlled ONLY on the fork ("head") # repository: pull_request.head.repo.default_branch (an attacker can # rename their fork's default branch) and the workflow_run @@ -48,16 +51,16 @@ unsafe_patterns := [ # default_branch is admin metadata and must NOT be flagged (#230). # RE2 has no negative lookahead, so we require the fork qualifier # instead of excluding the base path. - `\${{[^}]*github\.event\.[^}]*head\.repo\.default_branch\b`, - `\${{[^}]*github\.event\.[^}]*head_repository\.default_branch\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*head\.repo\.default_branch\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*head_repository\.default_branch\b`, # Commit messages. - `\${{[^}]*github\.event\.[^}]*\.message\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*\.message\b`, # Repository metadata an attacker sets on their fork. - `\${{[^}]*github\.event\.[^}]*\.(description|homepage)\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*\.(description|homepage)\b`, # Author / committer identity free text. - `\${{[^}]*github\.event\.[^}]*(author|committer)\.(name|email)\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*(author|committer)\.(name|email)\b`, # GitHub Pages page name. - `\${{[^}]*github\.event\.[^}]*page_name\b`, + `\${{(?:'(?:''|[^'])*'|[^'}])*github\.event\.(?:'(?:''|[^'])*'|[^'}])*page_name\b`, ] deny contains finding if { @@ -66,9 +69,8 @@ deny contains finding if { script := job.scripts[j] lines := split(script, "\n") some li - line := lines[li] - _line_controlled(job, line) - not _safe_sink(lines, li, line) + some e in regex.find_n(`\$\{\{(?:'(?:''|[^'])*'|[^'}])*`, lines[li], -1) + _injected(job, lines, li, e) finding := { "code": "ISSUE-207", "severity": "critical", @@ -85,8 +87,8 @@ _job_line(job) := location.first({location.script_line(job, j, li) | some j, script in job.scripts lines := split(script, "\n") some li, line in lines - _line_controlled(job, line) - not _safe_sink(lines, li, line) + some e in regex.find_n(`\$\{\{(?:'(?:''|[^'])*'|[^'}])*`, line, -1) + _injected(job, lines, li, e) }) # _job_subject: the untrusted expression this job's finding names, "${{" @@ -97,17 +99,17 @@ _job_subject(job) := s if { some script in job.scripts lines := split(script, "\n") some li, line in lines - not _safe_sink(lines, li, line) - some e in regex.find_n(`\$\{\{[^}]*`, line, -1) - _expression_controlled(job, e) + some e in regex.find_n(`\$\{\{(?:'(?:''|[^'])*'|[^'}])*`, line, -1) + _injected(job, lines, li, e) }) } else := "" -# _line_controlled: the line holds an expression whose value someone -# controls when the job runs (_expression_controlled). -_line_controlled(job, line) if { - some e in regex.find_n(`\$\{\{[^}]*`, line, -1) +# _injected: expression e on line li of a script reaches the shell with a +# value someone controls when the job runs (_expression_controlled), and +# is not a safe sink. +_injected(job, lines, li, e) if { _expression_controlled(job, e) + not _safe_sink(lines, li, e) } # _expression_controlled: the expression reads a free-text field, and not @@ -142,9 +144,9 @@ _matches_unsafe(line) if { regex.match(unsafe_patterns[k], line) } -# A matched expression is a safe sink (#229) only when it is BOTH wrapped -# in toJSON(...) AND sits inside a quoted heredoc body. Neither condition -# alone is sufficient: +# A matched expression is a safe sink (#229) only when BOTH every untrusted +# field in it sits inside a toJSON(...) call AND the line is inside a +# quoted heredoc body. Neither condition alone is sufficient: # - toJSON inside `echo "..."` still runs $()/backticks: the shell # evaluates them inside double quotes and toJSON does not escape `$`. # - a raw expression inside a quoted heredoc is substituted by GitHub @@ -154,14 +156,20 @@ _matches_unsafe(line) if { # (<<"EOF" / <<'EOF') disables all expansion, so together they are safe. # Reading the value as data (jq, json.load) is a separate safe sink not # special-cased here; bind through env: and dereference "$VAR" instead. -_safe_sink(lines, li, line) if { - _tojson_wrapped(line) +# +# The check is per expression and on the field itself: a toJSON elsewhere +# on the line (`${{ toJSON(github.sha) }} ${{ github.event.issue.title }}`) +# or elsewhere in the expression (`format('{0} {1}', github.event.comment.body, +# toJSON(github.sha))`) leaves the field raw. +_safe_sink(lines, li, e) if { _inside_quoted_heredoc(lines, li) + not _matches_unsafe(_without_tojson(e)) } -_tojson_wrapped(line) if { - regex.match(`(?i)\$\{\{[^}]*\btojson\s*\(`, line) -} +# _without_tojson: the expression with each toJSON(...) call removed, so +# what is left is what reaches the shell raw. A call with nested +# parentheses (toJSON(format(...))) is left in place and still flagged. +_without_tojson(e) := regex.replace(e, `(?i)\btojson\s*\((?:'(?:''|[^'])*'|[^'()}])*\)`, "") # Line li is inside a quoted heredoc when an earlier line opens one # (<<"WORD" / <<'WORD', optionally <<-) and a later line closes it with diff --git a/policies/template_injection_brace_in_string_test.go b/policies/template_injection_brace_in_string_test.go new file mode 100644 index 00000000..e5245be4 --- /dev/null +++ b/policies/template_injection_brace_in_string_test.go @@ -0,0 +1,102 @@ +package policies_test + +import ( + "context" + "strings" + "testing" +) + +func TestTemplateInjectionBraceInsideStringLiteral(t *testing.T) { + const workflow = `name: format-injection +on: issue_comment +jobs: + direct: + runs-on: ubuntu-latest + steps: + - run: echo "${{ format('{0}', github.event.comment.body) }}" + escaped-quote: + runs-on: ubuntu-latest + steps: + - run: echo "${{ format('it''s {0}', github.event.issue.title) }}" + env-redirect: + runs-on: ubuntu-latest + steps: + - run: echo "BODY=${{ format('{0}', github.event.comment.body) }}" >> "$GITHUB_ENV" + safe-quoted-expression: + runs-on: ubuntu-latest + steps: + - run: echo "${{ format('github.event.issue.title') }}" + env-tojson-later-argument: + runs-on: ubuntu-latest + steps: + - run: echo "X=${{ format('{0} {1}', github.event.comment.body, toJSON(github.sha)) }}" >> "$GITHUB_ENV" + env-tojson-other-expression: + runs-on: ubuntu-latest + steps: + - run: echo "A=${{ toJSON(github.sha) }} B=${{ github.event.issue.title }}" >> "$GITHUB_ENV" + env-tojson-wrapped: + runs-on: ubuntu-latest + steps: + - run: echo "B=${{ toJSON(github.event.comment.body) }}" >> "$GITHUB_ENV" + heredoc-tojson-later-argument: + runs-on: ubuntu-latest + steps: + - run: | + cat <<'EOF' + ${{ format('{0} {1}', github.event.comment.body, toJSON(github.sha)) }} + EOF + heredoc-tojson-other-expression: + runs-on: ubuntu-latest + steps: + - run: | + cat <<'EOF' + ${{ toJSON(github.sha) }} ${{ github.event.issue.title }} + EOF + heredoc-tojson-wrapped: + runs-on: ubuntu-latest + steps: + - run: | + cat <<'EOF' + ${{ toJSON(github.event.issue.title) }} + EOF +` + findings, err := evaluateStrict(loadPolicies(t), context.Background(), scanWorkflow(t, workflow), nil) + if err != nil { + t.Fatalf("evaluate policies: %v", err) + } + + for _, tc := range []struct { + job string + code string + want int + subject string + }{ + {"direct", "ISSUE-207", 1, "format('{0}', github.event.comment.body)"}, + {"escaped-quote", "ISSUE-207", 1, "format('it''s {0}', github.event.issue.title)"}, + {"env-redirect", "ISSUE-209", 1, "format('{0}', github.event.comment.body)"}, + {"safe-quoted-expression", "ISSUE-207", 0, ""}, + // toJSON must wrap the untrusted field itself: a toJSON elsewhere in + // the expression, or in another expression on the line, leaves the + // field raw. + {"env-tojson-later-argument", "ISSUE-209", 1, "format('{0} {1}', github.event.comment.body, toJSON(github.sha))"}, + {"env-tojson-other-expression", "ISSUE-209", 1, "github.event.issue.title"}, + {"env-tojson-wrapped", "ISSUE-209", 0, ""}, + {"heredoc-tojson-later-argument", "ISSUE-207", 1, "format('{0} {1}', github.event.comment.body, toJSON(github.sha))"}, + {"heredoc-tojson-other-expression", "ISSUE-207", 1, "github.event.issue.title"}, + {"heredoc-tojson-wrapped", "ISSUE-207", 0, ""}, + } { + matches := 0 + for _, f := range findings { + if f.Code != tc.code || (f.Job != tc.job && !strings.HasSuffix(f.Job, "/"+tc.job)) { + continue + } + matches++ + if tc.subject != "" && f.Subject != tc.subject { + t.Errorf("%s %s: Subject = %q, want %q", tc.job, tc.code, f.Subject, tc.subject) + } + } + if matches != tc.want { + t.Errorf("%s: got %d %s findings, want %d", tc.job, matches, tc.code, tc.want) + } + } +}