Skip to content

fix(shield): correct L1/L2 detection accuracy - #3

Merged
Unclecheng-li merged 4 commits into
Unclecheng-li:mainfrom
peakpot1:fix/shield-detection-accuracy
Aug 12, 2026
Merged

Unclecheng-li merged 4 commits into
Unclecheng-li:mainfrom
peakpot1:fix/shield-detection-accuracy

Conversation

@peakpot1

Copy link
Copy Markdown
Contributor

Eight defects in the Shield ruleset, each with a reproducer. Together they made the L1/L2 layers both miss common vulnerability shapes and report large volumes of noise.

Detection gaps

1. The SQL rules could not fire on quoted SQL

query = "SELECT * FROM t WHERE id = '" + supplied + "'"

sast_sql_string_concat required the string body to match [^'"]* — no quote characters at all. Concatenated SQL almost always wraps the value in inner quotes, which is exactly the shape the rule exists to catch. Removing the inner quotes made the same rule match. The rule additionally required the variable be named query, sql or statement.

2. Taint was keyed on parameter names

def ping(host):
    subprocess.check_output("ping -c1 " + host, shell=True)

def read(name):
    return open("/var/data/" + name).read()

Neither produced a finding. _looks_user_controlled matched the argument text against request|req|input|params|query|body|form|args, so a sink was only reachable if the author had used framework-idiomatic names. Renaming host to request.args["host"] made the same code report. Taint now starts from the enclosing function's parameters, with request objects still recognised on top of that.

3. The AST allowlist omitted check_output and check_call

_python_ast_findings accepted os.system, subprocess.run, subprocess.call and subprocess.Popen, while the regex counterpart in the same file already covered check_output and check_call.

4. shell=True was not detected

No rule referenced it, despite it being the signal that turns a subprocess call into a shell injection surface. It now has its own rule.

False positives

5. exec( matched in every language

const parts = /(\d+)/.exec(input);

Reported as "exec() executes arbitrary Python code" at high severity. RegExp.prototype.exec is an ordinary JavaScript call and appears throughout compiled bundles. The rule is now Python-only, as are the pickle, yaml, csrf_exempt and Django rules; the Spring rules are limited to Java. eval and exec also no longer match method calls on an object (re.exec, obj.eval).

6. The scanner rediscovered its own report

A report written into the tree being scanned was read back as source on the next run. Reports embed the evidence strings they describe, so scanning a directory twice produced findings at line numbers past the end of the real file.

7. One defect reported two or three times

_deduplicate keyed on (rule, line, evidence). The regex and AST passes match the same construct with different spans, so every AST-backed finding also surfaced as a regex finding. Overlapping rules compounded it — a shell=True call is also a command-injection sink. Deduplication is now per vulnerability class per line.

8. Vendored, generated and test code was scanned

Traversal skipped .git and node_modules but still descended into virtualenvs, site-packages, vendor, build output and minified bundles, where a finding points at code the user cannot change. Test and fixture trees are now skipped by default — a hardcoded credential in a fixture is the fixture doing its job — and can be restored with --include-tests.

Precision

Two cases are deliberately not reported, because flagging them buries the real ones:

subprocess.run([binary, *args])              # argv list without shell=True is the fix, not the defect
open(path, "r")                              # the caller supplied the whole path; that is a helper contract
open(os.path.join(base, name))               # reported: a tainted segment appended to a controlled path

Identifier interpolation is separated from value interpolation. A table name the code itself controls lands at medium with a note to confirm the allowlist, rather than sharing high severity with an injected value:

conn.execute(f"SELECT count(*) FROM [{table}]")   # table from sqlite_master -> medium
conn.execute("SELECT * FROM t WHERE id = '" + uid + "'")  # uid from the caller -> high

Tests

Ten cases in tests/deepsec/test_shield.py, one per boundary above. Full suite passes at 40/40.

peakpot1 added 4 commits July 30, 2026 15:50
Models answer the confidence field with a qualitative word ("high") or a
percentage string ("80%") as readily as with a float. float("high") raises
ValueError and takes down the whole L3 pass, so map words and percentages
onto the 0-1 range and fall back to the previous default when a value
cannot be parsed at all.
_looks_user_controlled decided whether a value was attacker-reachable by
matching its name against request/req/input/params/query/body/form/args.
Real code names its parameters uid, host, filename, so a helper such as

    def ping(host):
        subprocess.check_output("ping -c1 " + host, shell=True)

was invisible to every sink in this module. Taint now starts from the
enclosing function's parameters, with request objects still recognised on
top of that.

Alongside it, four defects in the sinks themselves:

- The SQL rules required the query string to contain no quote characters
  ([^'"]*), but concatenated SQL nearly always wraps a value in inner
  quotes ("... id = '" + x + "'"), so the rules could not fire on the very
  shape they exist to catch. They also demanded the variable be named
  query/sql/statement. Both restrictions are gone, and execute() calls are
  matched through the AST as well.
- The AST command-injection allowlist omitted check_output and check_call,
  which the regex counterpart already covered.
- shell=True was not detected at all; it now has its own rule.
- An argv list without shell=True is the recommended fix rather than a
  finding, and open(path) where path is the caller's own argument is a
  helper contract, not traversal - only a tainted segment appended to a
  path the code controls is reported.

Findings are deduplicated per vulnerability class per line, so a construct
matched by both the regex and the AST pass surfaces once.
insecure_config_python_exec matched \bexec\s*\( in every language. In
JavaScript that spelling is RegExp.prototype.exec, an ordinary call that
appears throughout compiled bundles, which made this single rule the
largest source of false positives in the ruleset. It is now Python-only,
as are the pickle, yaml, csrf_exempt and Django rules, while the Spring
rules are limited to Java. eval and exec additionally no longer match
method calls on an object (re.exec, obj.eval).

Traversal skipped .git and node_modules but still descended into vendored
dependencies, virtualenvs, build output and minified bundles, where a
finding points at code the user cannot change. Test and fixture trees are
also skipped by default - a hardcoded credential in a fixture is the
fixture doing its job - and can be restored with --include-tests.

Finally, a report written into the tree being scanned was picked up as
source on the next run: reports embed the evidence strings they describe,
so the scanner rediscovered its own output and reported findings at line
numbers past the end of the real file.
Each case pins one edge that regressed or was silently missing: taint
through plain parameter names, SQL containing inner quotes, an argv list
that must stay quiet, identifier interpolation landing at medium rather
than high, one finding per defect, RegExp.exec not being read as Python
exec, traversal needing an appended tainted segment, and the traversal
rules for tests, generated files and the scanner's own report.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants