Reviewer · Security
Harden security validation logic
When writing security-critical validation (command blocklists, path sandboxing, input filters), treat the check as an attack surface in itself and design it defensively:
When writing security-critical validation (command blocklists, path sandboxing, input filters), treat the check as an attack surface in itself and design it defensively:
-
Anchor matches precisely, per-pattern. A single shared boundary (e.g.
\b) or a single shared “safe” anchor cannot correctly serve every pattern at once —suneeds a trailing(?![\w.-])lookahead to rejectsu-exec/su.shas benign whilemkfsneeds to still matchmkfs.ext4. Give each pattern the anchor its own semantics require instead of reusing one anchor for all. -
Enumerate and test bypass vectors, not just the happy path. Any fixed list of wrappers/prefixes (
sudo,nice,timeout,env,xargs,sh -c,eval,$(), case variants, path-qualified invocations) will have gaps that let a dangerous operation slip through unblocked. For every new “allow” or “block” rule, add explicit test cases for both the intended bypass (should still be blocked) and the intended legitimate use (should still be allowed), and document known residual gaps explicitly rather than silently. -
Keep all checks in the same validation path consistent. If one branch lowercases input, IGNORECASE-compiles, or normalizes whitespace/case, every other branch checking the same input must use the identical normalization — otherwise attacker input can be crafted to pass one check while matching the intent of another.
-
Guard against ReDoS. Regex-based filters that run on user- or agent-controlled strings must be checked for catastrophic backtracking, especially when alternatives in a repeated group can overlap (e.g.
\w+=\S*\s+and\d\S*\s+both matching1=1). Make alternatives mutually exclusive or bound repetition, and benchmark with adversarial inputs at the maximum allowed input length before raising any length cap. -
Validate the exact resource that will be used, and normalize comparisons. For path/resource containment checks (e.g. workspace sandboxing), resolve symlinks (
realpath) before comparing, but be aware of the TOCTOU window if the unresolved path is later reopened — document or close this gap. Also normalize case (os.path.normcase) before comparing paths to avoid false refusals on case-insensitive filesystems. -
Preserve actionable error messages. When collapsing several specific checks into one generalized pattern, keep the matched token/reason in the returned message so the caller can tell exactly what was blocked and why.
Example — per-pattern anchoring instead of one shared boundary:
_BASH_COMMAND_WORDS = (
"sudo",
r"su(?![\w.-])", # blocks `su -`, allows `su-exec`, `su.sh`
"mkfs", # \b already matches `mkfs.ext4`, `mkfs.vfat`
)
Treat every such rule as provisional until it has a passing “should block” test and a passing “should allow” test covering the realistic bypass/false-positive forms.