Skip to content

Proposal: Replace regex-based shell command analysis with tree-sitter-bash #2721

Open

Description

@VascoSch92

Problem

The security module (openhands-sdk/openhands/sdk/security/defense_in_depth/) relies on regex pattern matching against flattened shell command text. The terminal module (openhands-tools/openhands/tools/terminal/) uses bashlex for command splitting and escaping. Both approaches have fundamental limitations that a proper parser would solve.

Regex cannot understand shell syntax

The patterns in pattern.py (lines 70–107) and policy_rails.py (lines 78–94) are well-designed and hardened with normalization, but regex fundamentally cannot understand quoting, escaping, operators, or nesting. This creates bypass classes that no amount of regex refinement can close:

Bypass Why it works Reference
r"m" -rf / Quoted segment breaks \brm\b word boundary pattern.py:73
/bin/rm -rf / Path-qualified command breaks \brm\s+ anchor pattern.py:73
dd with of=/dev/ beyond 100 chars .{0,100} window is too small pattern.py:80, policy_rails.py:105
curl ... | node node not in hardcoded interpreter list (sh|bash|python|perl|ruby) policy_rails.py:82, documented xfail in test_adversarial.py:294–314
curl x|bash Escaped pipe is literal text, but regex sees | as pipe operator pattern.py:92
bash -c 'rm -rf /' Nested command inside -c argument is opaque to regex pattern.py:73
Payload past 30KB _EXTRACT_HARD_CAP truncates to prevent ReDoS utils.py:41, documented xfail in test_adversarial.py:241–259
rm --no-preserve-root -rf / Intervening flag breaks the strict ordering regex expects pattern.py:73, policy_rails.py:87–94 (subject of PR #2718)

bashlex is unmaintained and crashes on valid input

openhands-tools depends on bashlex>=0.18 (pyproject.toml:9). It's used in two functions in terminal/utils/command.py:

  • split_bash_commands() (lines 14–67): parses multi-command strings to enforce single-command execution. Catches four exception types (ParsingError, NotImplementedError, TypeError, AttributeError) because bashlex crashes on various valid shell constructs. On any failure, it silently returns the raw string — bypassing multi-command validation entirely.

  • escape_bash_special_chars() (lines 70–151): walks the bashlex AST to escape unquoted operators. Uses regex on word text (lines 109–113) to detect quoted strings and command substitutions ("...", '...', $(...), `...`), because bashlex doesn't expose these as distinct node types. Same 4-exception catch-all with silent fallback.

bashlex was last meaningfully updated around 2020, has a single maintainer, and has no error recovery — any malformed input (common from LLM output) produces a ParsingError.

PR #2718 is heading in the right direction but adds complexity

PR #2718 improved rm -rf detection by replacing the regex with shlex tokenization + a hand-rolled shell segment splitter. This correctly fixes the flag-ordering bypass, but adds ~170 lines of new parsing code to utils.py: a 60-line char-by-char parser for ;/&&/||/|, a shlex.split() wrapper with fallback, regex-based redirection detection, and token-based flag inspection.

shlex is not a shell parser — it doesn't understand pipes, redirections, command substitution, or compound commands. Every new detection pattern will require more hand-rolled parsing on top of it.

The codebase parses bash three different ways

Package Module Approach Limitations
openhands-sdk security/defense_in_depth/pattern.py Compiled regex patterns Can't understand syntax
openhands-sdk security/defense_in_depth/policy_rails.py Composed regex conditions Same
openhands-sdk security/defense_in_depth/utils.py (PR #2718) shlex + hand-rolled splitter Not a shell parser
openhands-tools terminal/utils/command.py bashlex Crashes on valid input, unmaintained, no error recovery
openhands-sdk context/skills/execute.py Regex for !`cmd` extraction No security check before subprocess.run(shell=True)

Proposal

Replace all shell parsing with tree-sitter + tree-sitter-bash.

Why tree-sitter

  • Full parse tree: commands, arguments, flags, operators, redirections, quoting — all understood structurally
  • Error recovery: malformed shell (common from LLM output) still produces a partial AST with error nodes instead of raising exceptions. This directly solves the bashlex crash problem
  • O(n) parsing: eliminates the 30KB hard cap (utils.py:41) currently needed to prevent regex ReDoS (documented xfail in test_adversarial.py:241–259)
  • Actively maintained: used by GitHub (syntax highlighting for every repo), Neovim, Zed; the bash grammar is comprehensive and regularly tested
  • Small footprint: tree-sitter (~2 MB) + tree-sitter-bash grammar

What changes

1. PatternSecurityAnalyzer (pattern.py)

Replace the HIGH-risk regex patterns (lines 70–101) with tree-sitter queries. Example for rm -rf:

import tree_sitter_bash as tsbash
from tree_sitter import Language, Parser

BASH = Language(tsbash.language())
parser = Parser(BASH)

def _has_rm_recursive_force(command: str) -> bool:
    tree = parser.parse(command.encode())
    for node in _walk_commands(tree.root_node):
        words = [c.text.decode() for c in node.children if c.type == "word"]
        if not words or not (words[0] == "rm" or words[0].endswith("/rm")):
            continue
        flags = set()
        for w in words[1:]:
            if w == "--":
                break
            if w == "--recursive":
                flags.add("r")
            elif w == "--force":
                flags.add("f")
            elif w.startswith("-") and w != "-":
                flags.update(w[1:])
        if {"r", "f"} <= flags or {"R", "f"} <= flags:
            return True
    return False

This immediately fixes:

  • /bin/rm -rf / — words[0].endswith("/rm") handles path-qualified commands
  • rm --no-preserve-root -rf / — flags in any position
  • rm / -rf — flags after positional args

Similarly for dd of=/dev/ (extract of= from word nodes, no char-count window), curl | sh (query pipeline nodes, check RHS command name — not a hardcoded list), and mkfs.

Patterns that are not shell-specific stay as regex:

  • Injection patterns (inject.override, inject.mode_switch, inject.identity) — NLP, not syntax
  • Python code patterns (eval(), os.system(), subprocess.*()) — not bash

2. PolicyRailSecurityAnalyzer (policy_rails.py)

  • Fetch-to-exec rail (lines 78–102): query the parse tree for pipeline nodes. Check if LHS is curl/wget and RHS is any command — eliminates the hardcoded interpreter list. This fixes the curl | node xfail (test_adversarial.py:294–314)
  • Raw-disk-op rail (lines 104–112): parse dd command, extract of= value from word nodes, check if it starts with /dev/. No fixed-width window
  • Catastrophic-delete rail (lines 114–128): reuse _has_rm_recursive_force from above, then check target arguments against the critical path list

3. Utils cleanup (utils.py)

If PR #2718 merges first, delete the hand-rolled parsing it adds:

  • _split_shell_segments() — replaced by tree-sitter's understanding of ;, &&, ||, |
  • _tokenize_shell_segment() — replaced by tree-sitter node children
  • _is_redirection_token() — tree-sitter has a redirect node type
  • _segment_has_rm_recursive_force() and _has_rm_recursive_force() — replaced by tree-sitter version

The normalization pipeline (_normalize, lines 310–338) stays — invisible char stripping and NFKC normalization are still valuable as pre-processing before tree-sitter parsing.

The extraction logic (_extract_exec_segments, _extract_content, etc.) stays — it controls which fields are scanned.

4. openhands-tools: replace bashlex (terminal/utils/command.py)

split_bash_commands() (lines 14–67):

  • tree-sitter parses malformed input gracefully (partial AST with error nodes) instead of raising 4 exception types
  • The catch-all fallback that silently bypasses multi-command validation disappears
  • Multi-command detection becomes: walk the tree for top-level command nodes

escape_bash_special_chars() (lines 70–151):

  • tree-sitter provides explicit node types for string (double-quoted), raw_string (single-quoted), command_substitution, heredoc_body — no need to detect these via regex on string content (lines 109–113)
  • The recursive visit_node() + regex approach becomes a tree walk

Dependency change in openhands-tools/pyproject.toml:

- "bashlex>=0.18",
+ "tree-sitter>=0.24",
+ "tree-sitter-bash>=0.23",

The public API of both functions stays the same — only the internal implementation changes.

5. Skill execution (context/skills/execute.py)

Currently, commands extracted via the !`command` regex (line 44–48) are executed directly via subprocess.run(shell=True) (line 66) with no security analysis. With tree-sitter available in openhands-sdk, extracted commands should be run through the security analyzer before execution.

6. Shared parser across packages

The key benefit: both packages share one parser. Today openhands-sdk (security) uses regex + shlex and openhands-tools (terminal) uses bashlex. With tree-sitter-bash, both share one dependency and one parsing strategy. Security checks can run on the same AST the terminal uses for command splitting.


What stays the same

  • Normalization pipeline (utils.py:310–338) — invisible char stripping, NFKC, whitespace collapse remain as pre-processing
  • Extraction architecture (utils.py:75–157) — whitelisted field extraction, per-segment evaluation, hard cap (can be raised or removed with O(n) parsing)
  • Injection patterns (pattern.py:112–132) — NLP patterns, not shell syntax; regex is appropriate
  • Python code patterns (pattern.py:82–89) — eval(), os.system(), subprocess.*() are not bash
  • Per-segment evaluation (policy_rails.py:68–130) — correct architecture, each segment is now parsed instead of regex-scanned
  • Terminal escape filtering (openhands-tools/.../escape_filter.py) — byte-level ANSI patterns, not bash syntax

Out of scope

  • Cyrillic homoglyph bypasses — charset problem, requires Unicode TR39 confusable tables (documented xfail in test_adversarial.py:201–219)
  • Combining mark bypasses — requires diacritic stripping (documented xfail in test_adversarial.py:221–239)
  • Variable indirection (x=rm; $x -rf /) — requires runtime evaluation
  • Alias/function expansion — requires shell state

Test plan

  • All existing tests in test_pattern.py, test_policy_rails.py, test_adversarial.py must pass
  • The hard-cap xfail (test_adversarial.py:241–259) can be converted to a passing test if the cap is raised/removed
  • The curl | node xfail (test_adversarial.py:294–314) can be converted to a passing test with pipeline-based detection
  • Add regression tests for bypasses tree-sitter fixes:
    • /bin/rm -rf / (path-qualified command)
    • bash -c 'rm -rf /' (nested command)
    • dd if=/dev/zero of=/dev/sda with of= beyond 100 chars
  • All existing openhands-tools tests for split_bash_commands and escape_bash_special_chars must pass

(cc. @csmith49 @Fieldnote-Echo )

Activity

  1. Fieldnote-Echo commented on Apr 6, 2026

    @Fieldnote-Echo
    Member

    @VascoSch92 Insightful. I fully support dropping the old bashlex (GPL) fallback in favor of a structural AST parser like Tree‑sitter. Tree‑sitter’s Bash grammar (MIT-licensed, actively maintained in v0.25+) provides comprehensive shell syntax parsing, so our analyzer sees the real command structure. Wrapping the parser to fail closed on any syntax error (ERROR nodes) instead of defaulting to raw text, preventing silent bypasses.

    In practice, this means our normalized patterns (flag checks, banned commands, etc.) will now operate on a true AST. This change should eliminate bypasses caused by trick flags or nested bash -c calls, while still allowing us to handle complex cases safely.

  2. VascoSch92 commented on Apr 8, 2026

    @VascoSch92
    MemberAuthor

    Hey @Fieldnote-Echo

    Would you like to help with this proposal?

  3. Fieldnote-Echo commented on Apr 19, 2026

    @Fieldnote-Echo
    Member

    @VascoSch92, back from the flu and caught up on this thread, Kushal's #2718, and my own polish cycle.

    The architectural call here is the maintainers', not mine. What I can offer as the original analyzer contributor is perspective on what it was trying to be and where tree-sitter amplifies or strains that intent.

    Original design intent:

    • Two corpora: shell-destructive patterns scan only executable fields; injection patterns scan the full context. Signal-to-noise split.
    • Small analyzers, ensemble fusion. The composition surface was the primary design contribution, not the individual detectors.
    • Bounded regex + 30K cap: explicit ReDoS defense.
    • Stable detector IDs: telemetry-ready, implementation-swappable.
    • Normalization runs before any pattern (invisible chars, NFKC, whitespace). Attack-class-agnostic.
    • UNKNOWN is first-class in ensemble fusion: visibility without over-blocking.

    What tree-sitter amplifies:

    • O(n) parsing lets the 30K cap be revisited on the exec corpus. The ReDoS motivation goes away for parsed-path patterns.
    • Structural matching closes bypass classes regex cannot see by construction: nested bash -c, path-qualified commands, long operands.
    • The two-corpus split clarifies rather than blurs: exec gets structure, text (injection, Python) stays regex. Two paradigms, two corpora, clean.
    • Replaces bashlex in openhands-tools. That silent-fallback catch-all (ParsingError / NotImplementedError / TypeError / AttributeError at terminal/utils/command.py) is currently the weakest link in multi-command detection. Removing it is good independent of the security angle.

    What needs careful consideration:

    • Grammar pinning becomes security-critical. A silent grammar update can alter what we detect. Name an owner for upgrade review.
    • ERROR-node policy should be explicit. Fail-closed (ERROR → HIGH) vs. fail-scan (walk ERROR-span text) is a design call, not a default.
    • Parse-vs-execute divergence is a novel attack class. If tree-sitter parses one way and bash executes another, the gap didn't exist in the regex world. A small fuzzing pass would surface it early.
    • Contributor threshold: non-shell corpora (injection, Python) shouldn't require AST scaffolding to extend. "Shell goes through the parser, everything else stays regex-shaped" keeps the community path open.

    What gives hope:

    • The ensemble composition surface doesn't need to change. Tree-sitter can land as a new analyzer or a substrate swap inside PatternSecurityAnalyzer; both preserve the contract.
    • UNKNOWN fusion has a natural home for ERROR spans: emit UNKNOWN from the shell analyzer on ERROR spans, let the ensemble handle it. Neither fail-closed nor fail-scan by default; the design already has a mechanism for "structurally unclear."
    • The normalization pipeline is orthogonal and keeps working unchanged.

    Thank you for this. You're offering to make the security analyzer more robust, and it's clear you have the capability to execute it: the bypass catalog at the top of your proposal and the decision to keep injection/Python as regex demonstrate this. That's the harder half of proposing a migration like this, and volunteering to carry it is the rest.

    I'm here during the design review if you need me, or on Slack if you want to brainstorm.

  4. VascoSch92 commented on May 13, 2026

    @VascoSch92
    MemberAuthor

    Phased migration plan

    Splitting this proposal into two stages so we can ship the license fix immediately and pace the security analyzer work normally.

    Verified the licenses:

    Package License
    bashlex GPLv3+
    tree-sitter (Python bindings + C core) MIT
    tree-sitter-bash (Python package + grammar) MIT

    This repo is MIT, so the bashlex transitive dependency is a real license-compatibility concern, not just hygiene. That motivates pulling the license fix forward.

    The key observation: bashlex is used in exactly one file — openhands-tools/openhands/tools/terminal/utils/command.py (two functions: split_bash_commands, escape_bash_special_chars) plus the dep line in openhands-tools/pyproject.toml:9. The security analyzers in openhands-sdk already use regex and have zero dependency on bashlex. So removing GPL is a much smaller scope than the full proposal.

    Phase 1 — Drop bashlex (one PR, ship ASAP)

    Goal: zero GPL code in the dependency tree. Tightly scoped, fast to review.

    • openhands-tools/pyproject.toml:9 — replace "bashlex>=0.18" with "tree-sitter>=0.24" and "tree-sitter-bash>=0.23".
    • Rewrite split_bash_commands in openhands-tools/openhands/tools/terminal/utils/command.py against tree-sitter, preserving the public signature and the silent-passthrough fallback semantics. Drop the 4-exception catch-all (ParsingError, NotImplementedError, TypeError, AttributeError) — tree-sitter recovers via ERROR nodes instead of raising.
    • Rewrite escape_bash_special_chars similarly, using first-class node types (string, raw_string, command_substitution, heredoc_body) instead of the regex-on-word-text check at lines 109–113.
    • Module-level cached Parser so grammar load happens once.
    • All existing tests in tests/tools/terminal/test_terminal_parsing.py must pass unchanged. That's the contract: same inputs → same outputs.

    Explicitly out of scope for Phase 1:

    • No changes to openhands-sdk/.../security/defense_in_depth/* — no GPL there.
    • No shared parser module yet (keeps review surface small; introduced in Phase 2a).
    • No ERROR-node policy change, no UNKNOWN emission, no xfail conversions, no new bypass-class regression tests. Those all belong in Phase 2.
    • No coordination needed with fix(security): close rm flag-ordering bypasses #2718 — it doesn't touch bashlex.

    PR framing: lead with "Remove GPLv3 transitive dependency (bashlex); replace with MIT-licensed tree-sitter-bash. Public API of split_bash_commands and escape_bash_special_chars unchanged. Security analyzer migration tracked in #2721."

    Phase 2 — Shared parser module + security analyzer migration

    Once GPL is gone, the rest of the proposal at a normal pace, split into focused PRs:

    • 2a — Shared module. Create openhands-sdk/openhands/sdk/security/shell_parser.py. Move tree-sitter deps from openhands-tools into openhands-sdk/pyproject.toml (tools gets them transitively). Refactor command.py (from Phase 1) to call the shared module. No behavior change.
    • 2b — pattern.py. Replace HIGH shell patterns (pattern.py:70–80, 91–100) with parser-backed detectors. Keep stable detector IDs. Keep Python-code patterns (pattern.py:82–89) and injection patterns (pattern.py:112–131) as regex — they're not bash. Decide ERROR-node policy here (proposed: emit UNKNOWN from the shell analyzer, let EnsembleSecurityAnalyzer decide — picks up @Fieldnote-Echo's suggestion).
    • 2c — policy_rails.py. Rewrite _evaluate_rail_segments (lines 68–130) using parser queries. Drop the hardcoded sh|bash|python|perl|ruby interpreter list (fixes the curl | node xfail). Drop the .{0,100} window on dd of=/dev/ (fixes the windowed-bypass xfail).
    • 2d — utils.py. If fix(security): close rm flag-ordering bypasses #2718 has merged by this point, delete the ~170 lines of hand-rolled parsing it added. Raise or remove _EXTRACT_HARD_CAP = 30_000 on the exec corpus (ReDoS motivation is gone with O(n) parsing). Keep _normalize, _extract_*, _walk_json_strings.
    • 2e — context/skills/execute.py. Wire the parser-backed analyzer into the !`cmd` execution path before subprocess.run(shell=True) at line 66. New decision: refuse vs. log on HIGH risk during skill rendering.
    • 2f — Tests. Convert xfails in test_adversarial.py:241–259 and :294–314 to passing tests. Add regression tests for the bypass classes listed in the proposal (/bin/rm -rf /, bash -c 'rm -rf /', dd of=/dev/sda beyond 100 chars, quoted segments). Add a small fuzz pass for parse-vs-execute divergence (per @Fieldnote-Echo's note).

    Open decisions for Phase 2

    • ERROR-node policy: UNKNOWN vs fail-closed vs fail-scan. Proposing UNKNOWN so the ensemble fusion path handles it.
    • Grammar pinning owner: needed before Phase 2 ships, since a silent tree-sitter-bash upgrade could change detection behavior. Pin to a fixed minor for security-critical pinning.
    • Coordination with fix(security): close rm flag-ordering bypasses #2718: by the time Phase 2d is ready, either fix(security): close rm flag-ordering bypasses #2718 has merged (and we delete the helpers it added) or we supersede it. Phase 1 is unaffected either way.
  5. VascoSch92 commented on May 13, 2026

    @VascoSch92
    MemberAuthor

    Hey @Fieldnote-Echo and @eeee2345,

    I know you are both interested in these types of problems.

    We would like to move away from bashlex because of its license (as pointed out by @Fieldnote-Echo) and because it is no longer maintained. I’ve divided the issue into two parts. The first part is simply moving away from bashlex; I’ll handle that so it’s done.

    For the second part, let me know if you are interested in working on any of the points. We can also divide the scope of the second part even further.

  6. Fieldnote-Echo commented on May 19, 2026

    @Fieldnote-Echo
    Member

    @VascoSch92, surfacing the Slack ask for Phase 2c:

    Have parse() return a ParseResult dataclass exposing root_node as a public, read-only field alongside the convenience iterators (iter_simple_commands, iter_pipelines, etc.). Detectors that need structural context get it directly; others use the iterators. Detector classes can then live outside shell_parser.py without private accessors. No re-parsing across composed analyzers.

    Adjacent design question: ERROR-node handling. Existing ensemble convention is UNKNOWN on parse failure, not HIGH. Promoting parse errors to HIGH distorts max(concrete) fusion since sibling analyzers degrade to UNKNOWN when unconfigured. Design-intent context from #2472 if helpful.

    /cc @csmith49.

  7. eeee2345 commented on May 19, 2026

    @eeee2345
    Contributor

    @VascoSch92 — yes, interested in Phase 2. Given ATR's focus on security detection at the tool-call boundary, the points that make the most sense to take on are Phase 2b (integrating ATR pattern signatures as a concrete ShellAnalyzer implementation) and Phase 2c (ParseResult dataclass — @Fieldnote-Echo's write-up covers this well already).

    Happy to open a draft PR for 2b once Phase 1 (bashlex replacement) lands, so the detection layer builds on the clean tree-sitter foundation. If you're dividing scope further, let me know which sub-points are already claimed.

  8. 6 remaining items

  9. eeee2345 commented on Jun 29, 2026

    @eeee2345
    Contributor

    @VascoSch92 picking this back up now that Phase 1 and the shared _shell_ast view have all landed. Before I open the 2b draft I want to make sure I am not overlapping #3563, which already adds a parser-backed supply-chain analyzer on the same shared view. My read is that 2b proper is still open: replacing the HIGH shell patterns in pattern.py with parser-backed detectors, keeping the stable detector IDs, and leaving the injection and Python patterns as regex since they are not bash. Does that scoping still match what you want, or has part of it been folded into the work already in flight?

    On the ERROR-node policy I agree with @Fieldnote-Echo: emit UNKNOWN from the shell analyzer and let the ensemble decide, rather than promoting parse errors to HIGH and distorting the max-of-concrete fusion.

    I will keep it to a draft PR so it is easy to review in pieces. Disclosure: I maintain ATR, an open-source detection ruleset, which is where my interest in the tool-call boundary comes from.

  10. VascoSch92 commented on Jun 30, 2026

    @VascoSch92
    MemberAuthor

    @eeee2345 please go haed. Tag me for a review. ;-)

  11. eeee2345 commented on Jul 1, 2026

    @eeee2345
    Contributor

    @VascoSch92 opened #3944 — the scoped first cut we discussed: AST-backed command-name resolution on the shared _shell_ast view, closing the quoted (r"m" -rf /), path-qualified (/bin/rm), and nested--c (bash -c 'rm -rf /') bypasses, with the detector ID exec.destruct.rm_rf preserved. Command-substitution and ANSI-C-quoting stay strict xfails for a follow-up (they need a runtime-decode-vs-fail-closed policy call). Unresolvable destructive-flag shapes emit UNKNOWN, benign text stays LOW.

    Full tests/sdk/security/ suite green (363 passed / 10 xfailed); pre-commit, whole-project pyright, and the import-layering check all clean. Tagged you for review whenever you have a moment.

  12. github-actions commented on Aug 11, 2026

    @github-actions
    Contributor

    This issue is stale because it has been open for 40 days with no activity. Remove the stale label or leave a comment, otherwise it will be closed in 10 days.

  13. eeee2345 commented on Aug 14, 2026

    @eeee2345
    Contributor

    @VascoSch92 @Fieldnote-Echo — not idle, but the bot cannot see why, so here is the state against the six items in the proposal. Checked on main today rather than from memory.

    Item 6, the shared parser view: landed. openhands-sdk/openhands/sdk/security/_shell_ast.py is on main.

    Item 1, pattern.py: in review, and it is one person away. #3944 does AST-backed command-name resolution for the HIGH destructive detectors — the quoted, path-qualified and nested-runner bypasses. @VascoSch92 approved it on 4 Aug and asked @Fieldnote-Echo whether it can merge. It has been sitting on that question for a week. Its only remaining red is the unresolved-review-threads gate, which is stuck in action_required rather than failing.

    Items 2 and 3: untouched. policy_rails.py still evaluates entirely by regex — six re.search/re.compile calls, zero AST — so the composed rails carry the same quoting and nesting blind spots #3944 closes for the pattern layer. utils.py has no AST usage either.

    So the plan is roughly one sixth landed, one sixth approved-and-waiting, and the rest open. That is a reason for this issue to stay open, but only if someone intends to pick up items 2 through 5.

    @VascoSch92 — you said in May you did not have much time for this, which is completely fair. Two honest options:

    Either is fine. What I would rather avoid is the bot deciding it on 21 Aug, with an approved PR still pointing at a closed issue.

  14. VascoSch92 commented on Aug 14, 2026

    @VascoSch92
    MemberAuthor

    Hey @eeee2345

    sorry for that. I merged the PR #3944

    I will take this Issue open and continue with the points :-)

  15. all-hands-bot commented on Sep 18, 2026

    @all-hands-bot
    Collaborator

    [Automatic Post]: This issue has had no activity for 34 days (labels: proposal, security-related). @enyst @neubig @xingyaoww, could you take a look when you have a chance and help figure out next steps?

    Generated by OpenHands automation on behalf of the user.

  16. Fieldnote-Echo commented on Oct 12, 2026

    @Fieldnote-Echo
    Member

    @VascoSch92 I can take the remaining work here. I will start by migrating PolicyRailSecurityAnalyzer to the shared shell AST while preserving the current rail IDs and result ordering. I will keep the extraction-limit and skill-execution policy changes separate.

  17. Fieldnote-Echo commented on Oct 13, 2026

    @Fieldnote-Echo
    Member

    @VascoSch92 I ran #5724 against 19,812 shell-call records from the public
    OpenHands feedback and Data Agent Harbor datasets. The set contains 13,876
    unique command strings. The harness passed command text to the analyzers. It
    did not execute a corpus command.

    At tested implementation commit a8a4ef5, 37 records contain 42
    component-result changes from PR base acca181a: 20 policy-rail changes from
    LOW to HIGH, 16 policy-rail changes from LOW to UNKNOWN, and six
    pattern-analyzer changes from LOW to UNKNOWN.

    The projected default ensemble result changed for 25 records: 20 changed from
    MEDIUM to HIGH, and five changed from LOW to UNKNOWN. No analyzer error
    occurred. No concrete risk result in this corpus became lower.

    Projected default combined result PR base PR head
    HIGH 34 54
    MEDIUM 151 131
    LOW 19,627 19,622
    UNKNOWN 0 5

    All 37 changed records came from the 2,697-record OpenHands feedback corpus,
    which contains 1,252 unique command strings. The 17,115-record Data Agent
    Harbor corpus contains 12,624 unique command strings and had no changed record.

    The 20 promotions include 18 NodeSource installer occurrences across four
    exact command strings. They also include one signing-key setup and one
    curl | grep pipeline. The five new combined UNKNOWN results contain dynamic
    eval input.

    The component results are measured. The ensemble and confirmation counts are
    computed projections, not observed user prompts. The corpus has no threat
    labels or full task authorization context. It cannot establish precision or
    recall.

    The corpus found one implementation defect that belongs in #5724. Bash
    command -v and command -V are inspection modes, but the rail treated them
    as unsupported execution. The fix does not promote the inspected name to an
    executed command. It still scans nested substitutions, later commands, normal
    command -p execution, and supported builtin wrapper chains. A related review
    also found base-to-head regressions through builtin command and
    builtin exec; the same focused fix covers them.

    The remaining findings need separate policy decisions.

    1. What should fetch-to-exec mean?

      Proposal: Replace regex-based shell command analysis with tree-sitter-bash #2721 specifies a fetch whose output reaches another command in the same
      pipeline. This catches remote script execution, but it also makes
      curl | grep HIGH. Five curl | python -m json.tool records were already
      HIGH before this PR.

      I recommend a follow-up policy that distinguishes resolved code execution
      or privileged mutation, unresolved downstream behavior, and resolved data
      transformation. The rule must inspect arguments and execution structure. An
      executable-name allowlist is not sufficient. I would keep Replace policy rail regexes with shell AST analysis #5724 aligned
      with the current written rule until maintainers select a new policy.

      The AST rail also does not track fetched values across separate statements.
      For example, v=$(curl -s URL); echo "$v" | python3 remains LOW.
      Segment-wide correlation is not a sound fix because it would also flag
      curl x; echo y | python, where the fetched output does not reach Python.
      Cross-statement value tracking is a separate data-flow policy. It should not
      be added as a special case to this parser migration. In
      $(curl -s URL) | python3, fetched text becomes an unresolved command name.
      The rail returns UNKNOWN. The default ensemble can replace that result
      with LOW, which belongs to the separate ensemble decision below.

    2. Should a concrete analyzer result hide another analyzer's UNKNOWN?

      The default ensemble filters UNKNOWN when another child returns a concrete
      result. Strict mode propagates it. With unknown confirmation enabled, the
      projected HIGH-threshold confirmations are 34 at base, 59 with the default
      fixed-head ensemble, and 60 with the strict fixed-head ensemble.

      I recommend no ensemble default change in Replace policy rail regexes with shell AST analysis #5724. A default change affects
      confirmation behavior and compatibility. It needs a separate decision with
      an end-to-end prompt evaluation.

    3. What does LOW guarantee?

      For these analyzers, LOW means that no configured detector matched and no
      relevant unresolved structure remained. It does not mean read-only,
      authorized, or generally safe.

      The sampled LOW records include answer-file writes, package installation,
      Git push, migrations, and background service startup. State change alone
      cannot be a threat rule because state change is normal agent work. General
      effect and authorization policy should remain separate from this migration.

    4. Which existing text rules need their own policy review?

      Five unchanged Harbor HIGH records came from subprocess.run() text.
      Similar direct package commands remained LOW. The subprocess.run() text
      signature caused this difference. The corpus did not measure a difference
      in command effects. It is not a Replace policy rail regexes with shell AST analysis #5724 regression. I recommend a separate
      issue for Python-code signatures and severity.

    I will keep the bulk corpus outside normal SDK CI. Small sanitized cases can
    remain as regression tests. Future corpus reports should show component
    results, final ensemble results, and projected confirmation decisions
    separately. They should also report record counts, unique commands, and each
    corpus separately.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    proposalsecurity-related

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions