fix(guardrails): CONCAT before RAW, probe row newline kept, malformed urls handled, sa.text matched

This commit is contained in:
bchanot committed 2026-10-19 12:17:56 +02:00
1 parent 9275e0d82b
commit 63a88bc91d
5 files changed
+47 -15

No files matched your search

@@ -68,16 +68,17 @@ option. `--domain a11y` is now a usage error (exit 2).
Applies when the tree has a source file (`SOURCE_EXTS`) or a `.sql` file.
Skips test, spec, fixture and mock paths. One finding per (path, line):
when two rules match the same line the first in this order wins.
when two rules match the same line the first in this order wins, so a
interpolation inside a raw escape stays INJ-SQL-CONCAT (FAIL).
| Rule | Sev | Catches |
|---|---|---|
| INJ-SQL-RAW-UNSAFE | WARN | a raw escape fed a non-literal first argument: `$queryRawUnsafe(`, `$executeRawUnsafe(`, `knex.raw(`, `.raw(`, `.extra(`, `sequelize.query(`, `Sequelize.literal(`, `text(` when `sqlalchemy` is imported; WARN: a variable may hold a constant |
| INJ-SQL-CONCAT | FAIL | a SQL statement string built from an expression: untagged template literal with `${`, quoted SQL followed by `+ identifier`, Python f-string, `%` operator or `.format(`, PHP `"… $var"` or `. $var`, Ruby `#{}` (including ActiveRecord `.where("… #{`), Rust `format!(`, Go `fmt.Sprintf(` |
| INJ-SQL-RAW-UNSAFE | WARN | a raw escape fed a non-literal first argument: `$queryRawUnsafe(`, `$executeRawUnsafe(`, `knex.raw(`, `.raw(`, `.extra(`, `sequelize.query(`, `Sequelize.literal(`, `text(` when `sqlalchemy` is imported; WARN: a variable may hold a constant |
| INJ-SQL-DYNAMIC-EXEC | WARN | plpgsql `EXECUTE` whose statement uses `\|\|` and is not `format(…)` (SQL files, comments blanked) |
| INJ-POSTGREST-FILTER | WARN | supabase-js `.or(`, `.filter(`, `.not(`, `.match(`, `.textSearch(` with a template `${` or a `+` concatenation |
| INJ-NOSQL-OPERATOR | WARN | Mongo `$where:` with a string, or `find`/`findOne`/`update*`/`delete*`/`countDocuments` whose filter is `req.body`, `req.query`, `req.params` or one field taken straight from them |
| INJ-SHELL-DB-TOOL | FAIL | `exec`, `execSync`, `spawn`, `spawnSync`, `system`, `popen`, `subprocess.*`, `os.system`, `Command::new`, `shell_exec`, `passthru`, `proc_open` naming psql, mysql, mysqldump, pg_dump, pg_restore, mongosh, mongo, mongodump, redis-cli, sqlite3 or clickhouse-client on a line that also interpolates (`${`, `+ x`, `#{`, `{x}`, `%s`, `$x`) |
| INJ-SHELL-DB-TOOL | FAIL | `exec`, `execSync`, `spawn`, `spawnSync`, `system`, `popen`, `subprocess.*`, `os.system`, `Command::new`, `shell_exec`, `passthru`, `proc_open` naming psql, mysql, mysqldump, pg_dump, pg_restore, mongosh, mongo, mongodump, redis-cli, sqlite3 or clickhouse-client on a line that also interpolates (`${`, `+ x`, `#{`, `{x}`, `%s`, `$x`); outside PHP an uppercase `$NAME` is an env reference and stays silent |
Silent by design: tagged templates (`sql\`…\``, `prisma.$queryRaw\`…\``),
placeholders (`$1`, `?`, `%s` with a separate tuple), an argv array
@@ -114,7 +115,7 @@ defaults). Still GET only, same host, shared budget, `--authorized`.
|---|---|
| `sourcemap:<script path>` | for a script of the base page (`<script src>` on the same host, 10 at most, or the plan's `exposure.scripts`): `<url>.map`, the `SourceMap`/`X-SourceMap` header target or the trailing `sourceMappingURL` target answers 200 with `"sources"` |
| `error-body:<path>` | the GET of `/guardrails-probe-<random>` or of a path in `exposure.error_routes` returns a body with a trace marker: `Traceback (most recent call last)`, `at … (file:N:N)`, `File "…", line N`, `SQLSTATE[`, `syntax error at or near`, `node_modules/`, `/var/www/`, `Stack trace:`, `#N /…php(N)` |
| `fields:<path>` | the GET of a plan route returns JSON 200 whose keys (depth 4, 5 list items) match password, passwd, pwd, hash, salt, secret, token, api_key, apikey, service_role, private_key, ssn, iban, cvv, card_number. Only key names are printed, never values. Sent with `GUARDRAILS_JWT2` as bearer when set, anonymous otherwise |
| `fields:<path>` | the GET of a plan route returns JSON 200 whose keys anywhere in the body (1 MB bound; a body that does not parse, too deep included, is SKIPPED) match password, passwd, pwd, hash, salt, secret, token, api_key, apikey, service_role, private_key, ssn, iban, cvv, card_number. Only key names are printed, never values. Sent with `GUARDRAILS_JWT2` as bearer when set, anonymous otherwise |
One shared change, flip-tested: `fetch` keeps the body of a 4xx/5xx
response (today it returns `b""`); headers stay the `HTTPMessage`, whose
+10 -1
View File
@@ -108,6 +108,8 @@ class H(BaseHTTPRequestHandler):
if path == "/offhost.js":
return self._send(200, b"x();\n//# sourceMappingURL="
b"http://other.invalid/o.map\n")
if path == "/badmap.js":
return self._send(200, b"z();\n//# sourceMappingURL=http://[x\n")
if path == "/trunc.js":
return self._send(200, b"a" * 1_000_001)
if path == "/bigmap.js":
@@ -312,7 +314,7 @@ echo "== exposure probes: map channels and fail-closed paths"
cat > "$WORK/maps.json" <<EOF
{"base_url": "$BASE",
"exposure": {"scripts": ["/embed.js", "/redir.js", "/hdr.js", "/cmt.js",
"/offhost.js", "/trunc.js", "/bigmap.js"], "error_routes": []}}
"/offhost.js", "/trunc.js", "/bigmap.js", "/badmap.js"], "error_routes": []}}
EOF
OUT="$(probe --authorized "$WORK/maps.json")"
check "a sourceMappingURL string inside code is CLOSED, not an inline map" \
@@ -325,6 +327,10 @@ check "a map named by the trailing comment is OPEN" \
"$(verdict "$OUT" 'sourcemap:/cmt.js')" OPEN
check "a map url on another host is SKIPPED" \
"$(verdict "$OUT" 'sourcemap:/offhost.js')" SKIPPED
check "a malformed map url is SKIPPED, no traceback" \
"$(verdict "$OUT" 'sourcemap:/badmap.js')" SKIPPED
check "the message line keeps its newline and 11-space indent" \
"$(printf '%s\n' "$OUT" | grep -A1 'sourcemap:/offhost.js' | tail -1 | grep -c '^ [^ ]')" 1
check "a truncated script is SKIPPED" \
"$(verdict "$OUT" 'sourcemap:/trunc.js')" SKIPPED
check "an oversize map is SKIPPED" \
@@ -349,6 +355,9 @@ echo "== plan validation and host guard"
printf '{"base_url": "file:///tmp"}\n' > "$WORK/file.json"
probe --authorized "$WORK/file.json" >/dev/null 2>&1
check "a file:// base_url exits 2" "$?" 2
printf '{"base_url": "http://[x"}\n' > "$WORK/v6.json"
probe --authorized "$WORK/v6.json" >/dev/null 2>&1
check "a malformed base_url exits 2" "$?" 2
printf '{"base_url": 5}\n' > "$WORK/num.json"
ERR="$(probe --authorized "$WORK/num.json" 2>&1 >/dev/null)"
check "a non-string base_url exits 2 without a traceback" \
+10
View File
@@ -191,6 +191,14 @@ mutant sql-ruby-where-interp FAIL INJ-SQL-CONCAT \
"printf '%s\n' 'User.where(\"name = #{name}\")' > src/lib/users.rb"
mutant shell-db-php-upper-var FAIL INJ-SHELL-DB-TOOL \
"printf '%s\n' '<?php shell_exec(\"mysqldump --host=\$Host app\");' > src/lib/dump.php"
mutant concat-in-sqla-text FAIL INJ-SQL-CONCAT \
"printf '%s\n' 'import sqlalchemy' 'conn.execute(text(f\"select id from notes where owner = {owner}\"))' > src/lib/db.py"
mutant concat-in-objects-raw FAIL INJ-SQL-CONCAT \
"printf '%s\n' 'User.objects.raw(f\"select id from notes where owner = {name}\")' > src/lib/db.py"
mutant concat-in-knex-raw FAIL INJ-SQL-CONCAT \
"printf '%s\n' 'knex.raw(base + \" where id = \" + id);' >> $API"
mutant sql-sqla-sa-text WARN INJ-SQL-RAW-UNSAFE \
"printf '%s\n' 'import sqlalchemy as sa' 'conn.execute(sa.text(q))' > src/lib/db.py"
mutant sql-dynamic-exec WARN INJ-SQL-DYNAMIC-EXEC \
"printf '%s\n' \"execute 'select count(*) from ' || tbl into n;\" >> $SQL"
mutant postgrest-filter WARN INJ-POSTGREST-FILTER \
@@ -324,6 +332,8 @@ benign long-line-bundle \
benign sqla-text-method \
"printf '%s\n' 'import sqlalchemy' 'label = project.text(path)' > src/lib/db.py"
benign sqla-resp-text \
"printf '%s\n' 'import sqlalchemy' 'body = resp.text(x)' > src/lib/db.py"
benign shell-db-argv-spawn \
"printf '%s\n' 'spawn(\"psql\", [\"-f\", file], {env});' > src/lib/backup.ts"
benign shell-db-argv-python \
@@ -49,7 +49,8 @@ RAW = {
(".py",): re.compile(
r"\.objects\.raw\(\s*(?![\s'\"`)])|\.extra\(\s*(?![\s'\"`)])"),
}
SQLA_TEXT = re.compile(r"(?<![.\w])text\s*\(\s*(?![\s'\"`)])")
SQLA_TEXT = re.compile(
r"(?:(?<![.\w])|(?<=\bsa\.)|(?<=\bsqlalchemy\.))text\s*\(\s*(?![\s'\"`)])")
DYNAMIC_EXEC = re.compile(r"\bexecute\s+(?:'[^']*'|\w+)\s*\|\|", re.I)
POSTGREST = re.compile(
r"\.(?:or|filter|not|match|textSearch)\(\s*(?:`[^`\n]{0,200}\$\{"
@@ -135,14 +136,14 @@ def _shell_db(project, files):
rule = Rule(DOMAIN, "INJ-SHELL-DB-TOOL", "FAIL")
msg = "DB tool run through a shell with input: pass an argv"
php = _by_ext(files, (".php",))
other = [p for p in files if p not in php]
other = [p for p in files if p.suffix.lower() != ".php"]
return (hits(project, other, SHELL_DB, rule, msg)
+ hits(project, php, SHELL_DB_PHP, rule, msg))
def check(project):
files = code_files(project)
found = _raw_unsafe(project, files) + _concat(project, files)
found = _concat(project, files) + _raw_unsafe(project, files)
found += _dynamic_exec(project) + _postgrest(project, files)
found += _nosql(project, files) + _shell_db(project, files)
return dedupe_lines(found)
+18 -7
View File
@@ -75,7 +75,10 @@ class Probe:
def _stays_on_host(old_url, new_url):
"""Same host and port; the scheme may stay or upgrade, never downgrade."""
old, new = urlsplit(old_url), urlsplit(new_url)
try:
old, new = urlsplit(old_url), urlsplit(new_url)
except ValueError:
return False
return old.netloc == new.netloc and (
old.scheme == new.scheme or (old.scheme, new.scheme)
== ("http", "https"))
@@ -258,7 +261,10 @@ def probe_rate_limit(session, plan):
def _same_host(context, url):
"""Absolute url when it stays on context's host, else None."""
full = urljoin(context, url)
try:
full = urljoin(context, url)
except ValueError:
return None
return full if _stays_on_host(context, full) else None
@@ -447,9 +453,9 @@ def _printable(text):
def _probe_row(probe):
return _printable(
f" {probe.verdict:<8} {probe.domain:<9} {probe.id} "
f"{probe.target}\n {probe.message}")
return (f" {probe.verdict:<8} {probe.domain:<9} "
f"{_printable(probe.id)} {_printable(probe.target)}\n"
f" {_printable(probe.message)}")
def _summary(results):
@@ -474,8 +480,13 @@ def _render_json(plan, results):
def _http_url(value):
return isinstance(value, str) and urlsplit(value).scheme in (
"http", "https") and bool(urlsplit(value).netloc)
if not isinstance(value, str):
return False
try:
parts = urlsplit(value)
except ValueError:
return False
return parts.scheme in ("http", "https") and bool(parts.netloc)
def _load_plan(path):