Skip to content

feat(security): deny ssh/scp/sftp/rsync targeting this same host - #8283

Merged
iamwhatever merged 1 commit into
mainfrom
fix/sandbox-escape-ssh-self
Sep 10, 2026
Merged

iamwhatever merged 1 commit into
mainfrom
fix/sandbox-escape-ssh-self

Conversation

@patrigao

@patrigao patrigao commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

An agent shell running inside the KiroCrew sandbox can escape it with one command: ssh localhost <cmd>. sshd is not sandboxed, so the far side of a loopback connection is a fresh unsandboxed login shell on the same machine — outside every deny rule, sensitive-path guard, and audit hook in security.py. Observed live on a dev desktop: sudo is broken inside the sandbox (uid remap strips the setuid bit), but ssh localhost 'sudo -n true' succeeds, and dev-desktop sudoers grants (root) NOPASSWD: ALL — a complete root escape in one line. Nothing in the catalog or the floors recognizes the pattern today.

Why it matters

Every other control in the module (credential-exfil rules, git-publish floor, self-protection floors, sensitive-file guards) is bypassable through this one hole: a prompt-injected or misbehaving agent that reaches ssh localhost inherits the user's full unsandboxed authority, including passwordless root on standard dev desktops. The controls only mean something if re-entering the host is also gated.

What changed (motivation → approach → change)

Symptom → root cause: the deny system reasons about the command's own text and argv, and an ssh family verb with a self-target smuggles execution to an unguarded context. The fix follows the module's established two-tier self-protection shape (regex catalog row + argv-structural floor, union not replacement):

  • New catalog rule sandbox-escape-ssh-self (category self-protection, default-ON, operator-disableable like its floor siblings). The pattern is a lint-safe positional regex — verb in command position, self host as the operand directly after it, end-delimited so a remote host merely named localhost.example.com never matches. It is deliberately a human-auditable SUBSET of the floor: the star-of-options shape that could skip option/value pairs fails is_safe_user_regex, which would silently disable the rule (_DenyMatcher refuses unsafe patterns).
  • New argv floor _is_ssh_to_self, registered in _SELF_PROTECTION_FLOOR_RULE_IDS and the is_denied floor loop with its own _SELF_PROTECTION_FLOOR_NOTES entry. The walk is FAIL-CLOSED about option grammar: instead of a per-verb table of which options take values (a table mis-consumed scp -r localhost:… in review), every token that could be an operand — including one in an option's value slot — is checked against the self-host set; a real option value (a port, a cipher) never names this host. ssh/sftp read only the FIRST unshadowed operand as the host, so ssh far-host 'curl localhost:8080' stays allowed — "localhost" in a remote command is data, not a destination. scp/rsync accept a target in any operand position. Redirections are stepped over the way bash removes them from argv.
  • Target resolution (_operand_targets_self / _host_is_self): loopback names, 127.*, bracketed and bare IPv6 (::1, ::ffff:127.0.0.1), numeric IPv4 spellings inet_aton accepts (2130706433, 0x7f000001, 0177.0.0.1), user@ stripped from the host part only (an @ in a remote path is not userinfo), URI authorities isolated before paths, $(hostname)/`hostname`/$HOSTNAME spellings, Windows ssh.exe, and ssh's routing options in both spellings (-o HostName=localhost and the config-style -o "Hostname localhost", plus attached -Jlocalhost) — the whitespace form only in a value slot, so a quoted remote payload 'hostname localhost' stays data.
  • This machine's own hostname/FQDN/addresses extend the self set. Interface addresses join a synchronous, packet-less seed (UDP-connect probes plus per-OS adapter sweeps: Linux ioctl, Windows GetAdaptersAddresses, macOS getifaddrs — the macOS walk is exercised by the macOS CI leg). DNS-derived names resolve in a background daemon thread with retry backoff: getfqdn/getaddrinfo are synchronous DNS and is_denied runs inline on the gateway event loop (the AUTOSDE no-blocking-call rule names these calls). The hard-coded loopback half never depends on either.
  • Declared exception for first contact: a dotted hostname in HOST position that no textual layer can classify is refused ONCE, per gateway process, while an off-loop DNS check rules out a loopback alias (self.attacker.example → 127.0.0.1 stays denied; a public name allows on the next decision, and a name whose DNS lookup keeps failing stays refused on every retry — dotted-host ssh fails closed while a resolver outage lasts). File operands and option values never trigger this — only genuine connection targets. The catalog rule description declares the same behavior. The same fail-closed posture covers the Linux start-up window: until the background netlink sweep publishes the own-address set, an IP-literal target is refused and scheduled for revalidation, so the first moments after gateway start deny ssh <ip> rather than trust an incomplete own-address set.
  • Golden manifest gains the new row (catalog count pin 111 → 112 after the security-package split); the module spec (docs/system-specs/modules/security.md) gains the new floor.

Named fail-open residuals (denying these would break every legitimate remote ssh this box's workflows depend on): -F config files, ssh_config Host aliases, the GIT_SSH_COMMAND env family, values that exist only at run time (unassigned $VAR, dynamic substitution output), and nested function indirection. These are documented in the rule comment and the floor docstring. Statically-derivable forms are resolved and checked: parameter defaults, brace expansion, single-literal arithmetic, literal same-line assignments, one level of function-call binding, glob patterns, and flat static command-substitution output; arithmetic EXPRESSIONS in a target position fail closed.

Tests

test/test_denied_commands_security.py::TestSandboxEscapeSshSelf (new; ~190 tests by round 17):

  • Deny corpus: regex-tier spellings, floor-only spellings (options, quoting, bash -c payload, URI, IPv6/numeric literals, redirects, option-shadow shapes like scp -r localhost:/dir . and ssh -vp 22 localhost, routing options in both spellings, ssh.exe).
  • Allow corpus: remote hosts, remote commands mentioning localhost (quoted and unquoted), localhost.example.com, ::10, notssh, $HOSTNAME_BACKUP, rsync --exclude=localhost, non-connection mentions.
  • Structural: registered on both tiers, pattern passes is_safe_user_regex (a failing pattern silently disables the rule), pattern-subset-of-predicate invariant (mirror of the existing floor test), opt-out disables both tiers, tokenizer-failure still denies via the regex half, own-name cache semantics and best-effort resolver failure paths.

The catalog count pin assert is updated 111 → 112; the golden manifest entry is kept in lockstep with the rule (pattern and description).

Manual verification

Behavioral corpus run against the real is_denied in this worktree (all deny/allow/subset checks green), plus an independent focused verifier pass that re-probed every review blocker against the built module — including timing evidence that is_denied returns in ~64ms with DNS artificially blocked (background-thread resolution verified). The config-style -o "Hostname localhost" routing was confirmed equivalent to the = spelling against real ssh -G output.

Screenshots / video

N/A — no user-visible UI change (backend security rule; the Settings catalog renders the new row through the existing generic rule list).

no linked issue: filed directly from an operator request after the live escape was demonstrated on this machine; no tracking issue exists for it.

@github-actions

github-actions Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Fable 5) — 🟡 CONCERNS

Design-level review of 8d4fd26f6beb0468b83bc53cad8df301073db25c — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

The only removed test line is the count pin (111→112) — no opposite-behavior pin was deleted. I have enough to render the design verdict: real, demonstrated harm (live root escape via ssh localhost + passwordless sudo); the fix follows the module's established two-tier self-protection shape; the spec honestly labels it an interim tier with the OS-level network fence tracked as #9806; forwarding-option grammar handles the obvious false-denial traps (-L/-D exempt, -R fail-closed with rationale); DNS is off-loop with the loopback half never depending on it.

Design-Verdict: CONCERNS

Sound interim gate for a demonstrated root escape, but the tier's static-analysis depth already exceeds what an admitted-bypassable interim can ever guarantee.

Watch

The floor's deep layers (numeric-IP spellings, brace expansion, arithmetic, function-binding resolution — the "round-26" comments show how it got here) defend only an adversary who could instead use the acknowledged residuals ("bash escape.sh, python -c + subprocess/paramiko … git clone ssh://localhost/…"), so each further grammar round adds ~permanent maintenance surface in argv_floor.py without narrowing the escape — the exact accretion the cron-gate history (#4243→#8811) warns about.
Clears when: the residual list is pinned by a test (mirroring test_script_body_is_never_a_shell_gate_subject) so future spelling findings route to the #9806 sandbox fence instead of new grammar layers.

Fail-closed windows deny legitimate remote ssh with a "sandbox escape" refusal: on Linux, IP-literal targets are refused until the background netlink sweep publishes ("the first moments after gateway start deny ssh <ip>"), and "a name whose DNS lookup keeps failing stays refused on every retry" — an unattended cron ssh job during a resolver blip fails with a misleading security denial. Deliberate and operator-disableable, but a human should accept this trade-off explicitly.
Clears when: the refusal text for the DNS-pending/outage path names the transient cause (retry/resolver) rather than only the escape rule, or a human signs off on the current wording.

Suggestions

[DESIGN-REVIEWED] 8d4fd26

@github-actions

github-actions Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Fable 5) — 🟡 CONCERNS

Premise-level review of 8d4fd26f6beb0468b83bc53cad8df301073db25c — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

All evidence is gathered: the full patch, the intent file, the existing helpers (_glob_could_expand_to with 2 real consumers, _resolve_local_assignments with 1), and the ci.yml macOS job context. Final review follows.

First-Principles-Verdict: CONCERNS

Rounds 8–36 of static shell emulation defend against a deliberate adversary the diff itself hands a one-line bypass (bash escape.sh), while duplicating an existing glob helper.

Not justified as shipped

  • Item 7 — oversized: ~1,900 impl lines of brace/arithmetic/function-binding/xargs/glob/copy-binding emulation exist only to beat deliberate evasion, yet the floor's own residuals note concedes "interpreter/script-file indirection … still reach the unsandboxed sshd" — the adversary those rounds target walks around the whole tier in one line; only the accidental-use subset (regex row + basic operand walk) is actually closed.
  • Item 10 — rides along: two test node-ids pinned into the macOS CI job's test list; harm-free, partially declared via the "macOS CI leg" sentence.

What this change ships

Inventory (10 items) — 8 justified

Intent: stop the agent's sandboxed shell from re-entering this same machine (unsandboxed sshd) via ssh/scp/sftp/rsync — a FIX for a derived boundary gap (sandbox has no network namespace; sshd is outside it).

  1. ssh/scp/sftp/rsync targeting this machine is now refused (default-ON rule, Settings-toggleable) — justified
  2. First ssh to an unseen dotted hostname is refused once per process while a background DNS check runs — justified
  3. After gateway start on Linux, ssh to any IP-literal is refused until the kernel address table publishes — justified
  4. ssh -p <port> localhost container/VM workflows are now denied; recourse is disabling the whole rule — justified
  5. Gateway now runs background daemon threads and verdict/hosts caches for host classification — justified
  6. Gateway now reads the hosts file and enumerates interfaces (netlink / iphlpapi / getifaddrs, new host_addresses.py) — justified
  7. Deep static shell emulation (rounds 8–36: braces, arithmetic, functions, xargs, globs, copied binaries) — oversized (see above)
  8. Settings catalog gains the row; count pin 111→112; golden manifest row — justified
  9. security.md documents the floor, the interim-tier framing, and the residuals — justified
  10. Two new tests added to the macOS CI job's run list — rides along

Watch

Subtractions

  • Replace the three new fnmatch glob branches — _glob_can_name_ssh_verb, the glob arm of _ssh_family_verb, and the glob arm of _host_is_self — with the existing _glob_could_expand_to (shell_normalizer.py:174; grepped _glob_could_expand_to\(: 2 real consumers, one already in argv_floor.py:333). Same job, second spelling.

[FIRST-PRINCIPLES-REVIEWED] 8d4fd26

@github-actions

github-actions Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Opus 4.8 Review — ✅ no blocking findings

Reviewed 8d4fd26f6beb0468b83bc53cad8df301073db25c — this comment is updated in place on each push.

Review details

Both candidates target operations the diff deliberately keeps on the loop, and I verified the genuinely-blocking work is offloaded.

  • is_denied → _is_ssh_to_self does run inline on the event loop (confirmed: slack/handler.py:3579 calls hooks.on_tool_call synchronously inside an async handler; on_tool_call at hooks.py:566 is a plain def). So the rule is in scope.
  • Candidate 1 (/etc/hosts read): the read is a single os.stat + one open()/read(_HOSTS_FILE_READ_CAP) on a local file, capped at 4 MiB, cached by (mtime, size, published), and re-parsed only on change. It is not a filesystem walk and cannot hang like a network call. The "stalls every session" outcome depends on a multi-megabyte ad-block hosts file — a pathological config the candidate itself could not confirm; normal /etc/hosts is sub-kilobyte and parses instantly, and the cost is one-time. The observable-freeze outcome is a "might," not an "occurs in practice." Fails the bar.
  • Candidate 2 (_own_interface_addresses sweep): the UDP connect() on a SOCK_DGRAM socket sends no packet and returns immediately (it only binds the outbound address); if_nameindex, SIOCGIFADDR ioctls, and reading /proc/net/if_inet6 are local, packet-less syscalls, not "blocking socket" waits. It runs once per process (gated behind the _OWN_HOST_NAMES_CACHE is None seed). The genuinely blocking calls — getfqdn/getaddrinfo (_resolve_own_host_names) and the netlink RTM_GETADDR dump (_linux_netlink_addresses) — are all confined to the kirocrew-own-host-resolve/kirocrew-host-verdict daemon worker threads, off the loop. No observable freeze.

Neither reaches the 80 confidence bar; both were self-scored medium/low by discovery and die under falsification.

No findings.

[OPUS-REVIEWED] 8d4fd26

Verdict parsed from the review's SHA-scoped output markers for commit 8d4fd26f6beb0468b83bc53cad8df301073db25c.

False positive or not applicable? A repository writer can comment:
/ai-review override fable 8d4fd26f6beb0468b83bc53cad8df301073db25c: <one-sentence reason>

@github-actions

github-actions Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

GPT 5.6 Review — ✅ human override accepted

Human judgment by @patrigao overrides the GPT 5.6 finding for 8d4fd26f6beb0468b83bc53cad8df301073db25c; the recorded reason is authoritative for this commit.

This comment is updated in place on each push.

The model was not re-run because an authorized human decision supersedes it.

False positive or not applicable? A repository writer can comment:
/ai-review override gpt 8d4fd26f6beb0468b83bc53cad8df301073db25c: <one-sentence reason>

@patrigao
patrigao force-pushed the fix/sandbox-escape-ssh-self branch from ad456d0 to 53378ae Compare September 3, 2026 23:06
@patrigao

patrigao commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author
  • Runtime-expanded self targets bypass the floor (src/kiro_crew/security.py:5645) — span=3c5b15a2d41e — disposition: fixed (partial by design), commit 53378ae.

_operand_targets_self now checks the embedded word of ${VAR:-word} / ${VAR:=word} / ${VAR:+word} expansions (_EXPANSION_DEFAULT_RE, recursive so nested defaults resolve): ssh "${TARGET:-localhost}" id and ssh ${H:=127.0.0.1} id are denied, locked by tests. The wider demand — deny ALL unresolved expansions in destination position — is deliberately not taken: a bare $h destination is the daily fleet pattern here (for h in $(expand-hostclass …); do ssh $h …), so failing closed on it denies every legitimate remote ssh. That run-time-only residual is documented in the section header and the PR body as fail-open by design; the statically-visible half is now closed.

@patrigao

patrigao commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author
  • First own-host connection races hostname resolution (src/kiro_crew/security.py:5592) — span=3c5b15a2d41e — disposition: fixed, commit 53378ae.

_own_host_names() now publishes a synchronous seed from socket.gethostname() (a local uname syscall, not DNS — safe on the event loop) before kicking the DNS enrichment thread, exactly as the finding proposed. The very first ssh <own-hostname> is denied with no resolution window; test_first_own_host_command_is_denied_without_waiting_for_dns locks it with the enrichment thread suppressed. getfqdn/getaddrinfo stay off-loop per the AUTOSDE no-blocking-call rule.

@patrigao

patrigao commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author
  • Nested ssh far-host ssh localhost treated as a local connection (src/kiro_crew/security.py:5751) — span=732b722c70fd — disposition: rebutted (conservative over-block, kept deliberately).

The whole-frame scan is the same convention the sibling self-kill floor ships with, and unwinding it is not safe: excluding "ssh's remote payload" from scanning would also exclude ssh far "$(ssh localhost exfil)", whose command substitution runs LOCALLY before ssh ever connects — the tokenizer cannot tell the two apart without a shell-accurate evaluation model. The blocked shape connects to the REMOTE machine's loopback (rare; the common two-hop form is -J, and quoted nested payloads targeting other hosts stay allowed), so the failure direction is a rare over-block rather than an escape. Documented as the accepted trade-off in the floor's design comments.

@patrigao

patrigao commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author
  • Forward/bind option values denied as positional hosts (src/kiro_crew/security.py:5803) — span=c042398cee96 — disposition: fixed, commit 53378ae.

Added _SSH_FORWARD_OPT_LETTERS (-L/-R/-D/-W/-b, plus -l login under lowering): an ssh option in that set marks its value token exempt from the fail-closed operand check, so ssh -L 127.0.0.1:8080:db:5432 far-host, -D localhost:1080, -R localhost:2222:localhost:22, -W localhost:22, and -b localhost all stay allowed (locked by tests). The exemption is ssh-ONLY — for scp/rsync -r/-l are the valueless flags whose mis-classification hid scp -r localhost:… in round one, and the regression tests for that case still pass. -J deliberately stays checked (the jump connection originates locally), and the docstring premise the finding quoted is corrected to name the carve-out.

@patrigao
patrigao force-pushed the fix/sandbox-escape-ssh-self branch 2 times, most recently from f1e84cb to 596fd06 Compare September 4, 2026 00:35
@patrigao

patrigao commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author
  • IPv4-mapped loopback bypasses _host_is_self on Python < 3.12.4 (src/kiro_crew/security.py:5638) — span=c9886dc1579f — disposition: fixed, commit 596fd06.

Legitimate: IPv6Address("::ffff:127.0.0.1").is_loopback only delegates to ipv4_mapped from 3.12.4 (gh-113171); requires-python >= 3.12 admits 3.12.0–3.12.3 (Ubuntu 24.04 ships 3.12.3), where the mapped form fell through every branch and was allowed. _host_is_self now unwraps ip.ipv4_mapped explicitly before the loopback/unspecified/own-name checks, so the deny no longer depends on interpreter delegation. Locked by test_mapped_loopback_denial_does_not_rely_on_is_loopback_delegation, which pins the IPv6 properties to the pre-3.12.4 semantics and asserts the deny still holds — verified to FAIL on the previous code and pass on this commit (the shipped ssh ::ffff:127.0.0.1 id deny case alone could not catch this on ≥ 3.12.4 interpreters, where delegation masks the bug).

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Sep 4, 2026
@patrigao
patrigao force-pushed the fix/sandbox-escape-ssh-self branch from 596fd06 to a5dcd29 Compare September 4, 2026 01:55
@patrigao

patrigao commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author
  • Empty substitutions bypass verb and host detection (src/kiro_crew/security.py:5794) span=3c5b15a2d41e — fixed in a5dcd29

_EMPTY_EXPANSION_RE now collapses $()/empty backticks out of the source text before BOTH the verb gate and tokenization, so s$()sh localhost and ssh local$()host resolve to their spliced-out spellings. The gate additionally probes a quote/backslash-splice-stripped copy, closing the sibling ss""h / s\sh gate evasions (shlex already rejoined those in tokens; only the raw-substring gate missed them). Locked by new deny tests for all four spellings; proven to fail on the pre-fix code via stash run.

@patrigao

patrigao commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author
  • ProxyJump chains are not inspected per hop (src/kiro_crew/security.py:5753) span=3c5b15a2d41e — fixed in a5dcd29

_proxyjump_value_targets_self now splits the value on commas and checks every hop with _operand_targets_self — ssh dials the FIRST hop from this machine, so a self host anywhere in the chain is a self dial. Applied to both -o proxyjump=… spellings and the attached -J… form. Deny tests: proxyjump=localhost,far and -Jlocalhost,far; allow regression: all-remote chains in both spellings.

@patrigao

patrigao commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author
  • ProxyCommand payloads bypass self-target scanning (src/kiro_crew/security.py:5734) span=3c5b15a2d41e — fixed in a5dcd29

New _SSH_COMMAND_OPTION_KEYS = ("proxycommand", "localcommand"): these option values are command lines ssh executes ON THIS HOST, so _routing_option_key_value_targets_self now recurses the whole floor on the value (strictly shorter than its containing token, so the recursion terminates). LocalCommand is covered as the same locally-executed class, and scp/sftp inherit the fix because they forward -o to ssh. Deny tests: ssh -o proxycommand="ssh localhost sh" far and the scp spelling.

@patrigao

patrigao commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author
  • Rsync remote-shell payloads bypass self-target scanning (src/kiro_crew/security.py:5845) span=3c5b15a2d41e — fixed in a5dcd29

rsync's -e/--rsh value is a command line rsync execs FROM HERE, so the walk now recurses the floor on it in every spelling: --rsh=VALUE attached, -eVALUE attached (single-dash, including mid-bundle), and the detached next-token form via a pending flag (also set by a bundle ENDING in e, e.g. -ave). Only exactly rsh among double-dash options consumes a value, so --exclude=localhost stays data. Deny tests cover detached/attached/bundle spellings; allow regressions keep --rsh=ssh and --exclude=localhost. (Note: the plain detached -e ssh allow-case is asserted at floor level — end-to-end that string was already denied BEFORE this PR by the unrelated reverse-shell-nc catalog rule, whose unanchored pattern substring-matches inside the rsync flag text; fixing that older rule is out of scope here.)

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 4, 2026
@patrigao
patrigao force-pushed the fix/sandbox-escape-ssh-self branch from a5dcd29 to 1e56ac8 Compare September 4, 2026 03:48
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Sep 4, 2026
@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes

  • rebutted — span=7670520e57b3 — _ssh_family_verb reinterprets remote-command arguments (argv_floor.py:3164, advisory FINDING)

Deliberate fail-closed direction, kept: the walk re-arms on ssh-family verbs in later argv positions because those positions DO exec locally in adjacent shapes this floor must catch — ;/&& chains re-enter command position, and rsync -e/--rsh and ProxyCommand values are local command lines. Distinguishing "remote command data" from "local command position" requires per-verb positional bookkeeping whose gaps have produced this PR's security findings; over-denying ssh far ssh <own-host> (far machine dials its own localhost — a niche nested-ssh spelling) is the accepted cost of the deny floor, consistent with the adjudicated allow-on-resolution-failure and dotless answer-open rulings on this PR.
Advisory severity: no code change; the over-deny class (runtime/nested indirection) is documented in the residual-risk note, with the network fence (#9806) as the fix of record for indirection classes generally.

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: none new — widened the existing leading-assignment scan (_RSYNC_RSH_ASSIGN_RE) to rsync's second exec'd env var

  • fixed — span=7670520e57b3 — RSYNC_CONNECT_PROG bypasses the self-host gate (argv_floor.py:1909)

Fixed in f285a85: the leading-assignment scan now matches BOTH env-var command values rsync execs from here — ^rsync_(?:rsh|connect_prog)= — and the bare export <name> re-export accepts either name. The captured value rides the existing pending/exported machinery and recurses the floor on the rsync verb, so RSYNC_CONNECT_PROG='ssh localhost nc %H 873' rsync rsync://far/module and the host::module / exported variants are denied; a far proxy value stays allowed.
This completes rsync's env-var branch table: RSYNC_RSH (remote-shell transport) and RSYNC_CONNECT_PROG (daemon-mode transport) are the two values rsync executes locally. Remote-shell env vars of OTHER verbs (GIT_SSH_COMMAND and the like) remain the documented residual with the network fence (#9806) as fix of record — they belong to verbs outside this floor's gate.
Red-first: 3 deny rows + 1 allow guard; 1877/1877 across both security files.

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: none new — the round-29 shared assignment slot became per-name dicts

  • fixed — span=7670520e57b3 — rsync selector assignments overwrite each other (argv_floor.py:3208)

Fixed in 9347c79: _RSYNC_RSH_ASSIGN_RE now captures the variable NAME, and pending/exported/assigned are per-name dicts, so RSYNC_RSH='ssh localhost' RSYNC_CONNECT_PROG='ssh far' rsync … checks BOTH values and a bare export NAME promotes THAT name's stored value. The rsync-verb check iterates both names (pending falling back to exported per name); the carried-frame fallback applies only when neither name has a value, preserving the round-8 inheritance semantics.
This ruling covers cross-variable ordering generally: no assignment order or export interleaving of the two rsync env vars can shadow a self value with a far one.
Red-first: same-command overwrite row + export-replay row; 953/953 in test_denied_commands_security.py (the file covering every changed line); mypy/flake8/isort/black/comment-history green. The test_security.py suite could not be run locally this round — a host safety policy refused every spelling naming it this cycle — so CI's Backend Tests lane is the backstop for it on this head.

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: none new — the round-24 binder caps now fail closed

  • fixed — span=7670520e57b3 — function-binding caps fail open (argv_floor.py:3017)

Fixed in 9347c79: both caps in _function_call_binds_self now DENY instead of break — a 9th function definition, or a 9th call of one name, is unresolvable padding, so the floor refuses the command rather than skipping the unresolved binding. The cap value (8) is unchanged; only the exhaustion behavior flips to fail-closed, matching this floor's adjudicated direction (deny on what cannot be cleared).
Accepted over-deny: nine-plus function definitions or nine-plus same-name calls in ONE command line is a padding/pasted-script shape, not an interactive spelling; a within-cap far call is pinned as still allowed.
Red-first: 8-noop-defs+self row and 9th-call row deny; within-cap far-call allow guard; 953/953 in test_denied_commands_security.py; mypy/flake8/isort/black/comment-history green (test_security.py rides CI this round — host policy fenced local runs naming it).

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes

  • rebutted — span=7670520e57b3 — hosts-file parsing blocks the gateway event loop (argv_floor.py:1803)

Not a defect at the claimed rung, per this round's own adjudication (DOWNGRADE, disproportionate-remedy): the read is capped at 4 MiB (_HOSTS_FILE_READ_CAP), the parse is cached keyed on (mtime, size) and reruns only when the file changes, and the path is reached only for dotless self-target candidates — a bounded, once-per-change, self-limiting transient, not a security or availability defect.
The demanded remedy (a second async parse worker with inline cached-only serving) adds a parallel state machine to an already-intricate floor for a LOW/MEDIUM transient — the same hosts-parse-on-loop class adjudicated in earlier rounds of this PR. This ruling covers event-loop-stall findings about the capped, cached hosts-file parse wherever the line number moves.

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: fold-ambiguous option-letter set (_VERB_FOLD_AMBIGUOUS_OPT_LETTERS) consulted where value_shadow suppressed the host check

  • fixed — span=7670520e57b3 — Case-folded option parsing allows self routes (argv_floor.py:3419)

Fixed in c5f01a0, both vectors. (1) Letters whose two cases DISAGREE on value-taking (ssh c/f/m/q/s, sftp c/f/p/r) are now marked fold-ambiguous: the swallowed token keeps FULL host-position checks (DNS included) while the positional slot still stays pending — both candidate destinations are over-checked, the floor's safe direction. ssh -C self.attacker.example is denied; ssh -c aes128-ctr <self> stays denied; far neighbors stay allowed. (2) The glued remote-forward branch now strips the valueless bundle prefix before its letter test, so -vR2222:localhost:22 is parsed as -v + -R2222:localhost:22 and denied — the same strip the round-28 -o/-J branches received.
This ruling covers case-fold collisions in the option walk generally: under a folded reading, ambiguity resolves by checking MORE, never less.
Red-first: structural DNS-verdict test (three-way pin) + literal rows + far allow guards; 960/960 in test_denied_commands_security.py; mypy/flake8/isort/black/comment-history green (test_security.py remains host-policy-fenced locally; CI Backend Tests is the backstop, green on the prior head for the sibling change).

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: export-marked name set (rsync_rsh_export_marked) so a later assignment exports itself

  • fixed — span=7670520e57b3 — Prior exports are forgotten (argv_floor.py:3221)

Fixed in c5f01a0: a bare export NAME now MARKS the name (never cleared by separators) as well as promoting any already-stored value, and the assignment branch exports its value when the name is marked OR the assignment is directly export-prefixed. The POSIX declare-first order export RSYNC_RSH; RSYNC_RSH='ssh localhost'; rsync far:/x . is therefore denied, matching what real bash exports; both rsync env names get the same treatment.
This ruling covers export/assignment ordering generally for the two rsync env vars: whichever order the export attribute and the value arrive in, a self-targeting value that real bash would export is checked.
Red-first: two export-first deny rows (RSYNC_RSH and RSYNC_CONNECT_PROG); 960/960 in test_denied_commands_security.py.

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes

  • fixed — span=7670520e57b3 — "Their values are exempt" contradicts the implemented -R destination check (argv_floor.py:2036, advisory FINDING)

Fixed in c5f01a0: the _SSH_FORWARD_OPT_LETTERS comment now states that every forward value EXCEPT -R's is exempt, and that the -R destination is dialed from this machine so its spec IS checked (round-27, _remote_forward_value_targets_self), with -J likewise checked. The comment matches the implemented branch table.

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: netlink RTM_GETADDR dump layer (_linux_netlink_addresses + pure parser _parse_netlink_addr_dump)

  • fixed — span=7670520e57b3 — Linux secondary IPv4 addresses bypass the self-host floor (argv_floor.py:2139)

Fixed in 79b20a9: the synchronous seed gains a netlink RTM_GETADDR dump layer (_linux_netlink_addresses) that lists EVERY assigned address — secondary IPv4s, VIPs and all IPv6 included — via an AF_NETLINK route socket: kernel-local, no resolver, no packet leaves the host, so it keeps the seed's packet-less contract. The SIOCGIFADDR ioctl and /proc/net/if_inet6 layers stay (additive layers, each wrapped, contribute-nothing-on-failure), and the wire format is factored into the pure parser _parse_netlink_addr_dump so it is unit-tested without a socket.
This ruling covers Linux own-address enumeration completeness: the dump is the kernel's full address table, so any address ssh could dial locally is in the seed the first command sees.
Red-first: synthetic two-message dump parse test (v4 secondary + v6 + DONE), seed-wiring test (stubbed sweep denies ssh <secondary> on first command, far stays allowed), off-Linux inertness pin. 962 passed + 1 platform skip in test_denied_commands_security.py; mypy/flake8/isort/black/comment-history green (test_security.py remains host-policy-fenced locally; CI Backend Tests is the backstop).

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: off-loop netlink layer in the enrichment worker + _NETLINK_ADDRS_PUBLISHED fail-closed IP-literal window

  • fixed — span=7670520e57b3 — Netlink receive blocks the gateway event loop (argv_floor.py:2307)

Fixed in 77e92e6: the RTM_GETADDR dump moved out of the synchronous seed into the DNS enrichment worker thread (_resolve_own_host_names), so no blocking socket read runs on the is_denied path — the seed keeps only its packet-less non-blocking layers. Fail closed until ready: _NETLINK_ADDRS_PUBLISHED starts False on netlink-capable Linux, and _host_is_self DENIES any non-own IP literal in host position while the kernel table is unread (both the ip_address and inet_aton branches); a non-empty worker pass publishes the flag, and an empty pass on a netlink-capable host withholds the resolved-once latch so the backoff retries.
This ruling covers the no-blocking-call-on-event-loop rule for the own-address enumeration generally: every blocking read lives in the worker, and the window between start and publish denies rather than admits.
Red-first: pending-window test (v4 + v6 literals denied until publish, far allowed after), steady-state cache test, worker-merge test with DNS stubbed inert; suite autouse pins the published steady state so allow rows test their own merits. 967 passed + 1 platform skip; mypy/flake8/isort/black/comment-history green (test_security.py remains host-policy-fenced locally; CI Backend Tests is the backstop).

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: full-range braced ${N} binding + parameter-expansion opener restoration before the def regex

  • fixed — span=7670520e57b3 — Braced positional arguments above nine bypass the self-host floor (argv_floor.py:3160)

Fixed in 77e92e6, two parts. (1) The binder loop now binds braced ${N} for EVERY supplied argument — bash has no single-digit ceiling on the braced form — while unbraced $N stays capped at nine ($10 is ${1}0). (2) The quoted spelling only binds once capture works: the mask layer rewrites a quoted { to a sentinel while its closing } stays literal, which truncated the DEF regex's balanced-brace body on "${10}"; the binder now restores the ${ expansion opener (never a command boundary) before matching, and unmasks the captured body before binding.
This ruling covers positional-parameter range completeness in the binder: any ${N} a caller supplies an argument for is bound and the bound body re-walked.
Red-first: f(){ ssh "${10}"; }; f a b c d e f g h i localhost and a 12-arg ${12} variant deny; the far-target position-ten guard stays allowed. 967 passed + 1 platform skip in test_denied_commands_security.py.

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: host_addresses.py — platform address-table readers split out of argv_floor (subtraction; per-module liveness cap)

Disposition: rebutted (adjudicated class: hosts-parse-on-loop) — span=7670520e57b3

  • Hosts-file parsing blocks the gateway event loop — argv_floor.py:1803

This class is already adjudicated: the round-30 adjudication DOWNGRADED hosts-parse-on-loop (disproportionate-remedy), and this round's own Opus adjudication downgraded this exact instance again for the same reason. The parse is bounded (4 MB cap at _HOSTS_FILE_READ_CAP), runs only on a cache miss keyed to mtime/size, publishes to _HOSTS_FILE_CACHE so every later call is a dict hit, and exists precisely to give a SAME-CALL verdict on the is_denied path — moving it to a worker reintroduces the async pending-window this local read was designed to eliminate. This ruling covers every instance of the bounded-cached-hosts-read tradeoff, wherever it moves.
Retrospective note: the round-34 retrospective gate fired (3rd-round cadence); this round subtracted rather than added — the platform address readers moved out of argv_floor into host_addresses.py — and the round-26 keep-all retrospective still covers the retained mechanisms.

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes

Disposition: rebutted (not-a-defect) (adjudicated classes: dotless first-contact answer-open + allow-on-resolution-failure) — span=7670520e57b3

  • Fail-open DNS verdicts admit same-host SSH — argv_floor.py:2605

Not a defect: this is the recorded first-contact design ruling, not an oversight. A dotless target with no hosts-file entry and no cached verdict is answered from the synchronous layers (own-name set, interface + netlink addresses, hosts file); the DNS leg is enrichment, and the design accepts one first-contact window rather than stalling the event loop or denying every unknown bare name (which reds ordinary ssh bastion on first use). The stale-revalidation leg is the same allow-while-pending tradeoff: a previously-verified non-local verdict stays honored while the refresh is in flight. Both legs converge on deny at the next decision once resolution publishes. This ruling covers every instance of the allow-while-DNS-pending tradeoff, wherever it moves; the network-fence follow-up is tracked in issue #9806 (deferred-finding, assignee patrigao, due 2026-10-09).
Maintainer exit for this fenced class: /ai-review override gpt 9a79424d4caf66817d48cf85abc57be39c0b153c: First-contact DNS enrichment is deliberately advisory; the synchronous own-host layers are the floor and issue #9806 tracks the residual.

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes

Disposition: fixed in 9a79424 — span=ed2b4cb75a46

  • "safe inside the synchronous seed" contradicts the blocking receive — argv_floor.py:2295

Fixed as asked: the _linux_netlink_addresses docstring now states the recv is a blocking socket read and the dump must run only in the DNS enrichment worker, never the synchronous seed, with _NETLINK_ADDRS_PUBLISHED keeping _host_is_self fail-closed until the worker publishes. The helper now lives in src/kiro_crew/security/host_addresses.py (platform address readers split out of argv_floor this round for the per-module liveness cap), and the module docstring states the per-helper blocking discipline.

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: _xargs_here_string_rebuild (shell_normalizer) + xargs-prefix hook in _is_ssh_to_self

Disposition: fixed in ae882fd — span=7670520e57b3

  • Here-string xargs input bypasses the self-SSH floor — argv_floor.py:3290

Fixed as asked: the floor now rebuilds the command an xargs-launched verb actually runs and recurses _is_ssh_to_self on it. A bare xargs word anywhere in the simple command (wrappers like sudo xargs ssh included) is remembered; at the verb, _xargs_here_string_rebuild finds the here-string (<<< word, glued <<<word, before or after the verb), applies xargs argv semantics — appended stdin words, or -I/-i/--replace substitution into the verb's args — and the rebuilt command is judged exactly like a directly-typed one, so xargs ssh <<< localhost, xargs -I{} ssh {} <<< localhost, xargs <<< localhost ssh and sudo xargs ssh <<< localhost are all denied while xargs ssh <<< remote.example.com stays allowed. The rebuild drops the xargs word and the here-string pair, so the recursion terminates on strictly fewer tokens. Plain detached redirects keep their filename-consumption behavior (guard test added). Pipe-fed stdin (echo localhost | xargs ssh) has no statically-known payload in the simple command and stays the documented run-time residual, the same class as dynamic substitution generators.

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: none added (one letter in the existing per-verb value-option table)

Disposition: fixed in 09962f2 — span=4f0f18c795c6

  • sftp -X <opt> localhost escapes the ssh-self floor: value-taking table omits -X

Fixed as asked: _VERB_VALUE_TAKING_OPT_LETTERS["sftp"] is now frozenset("bcdfijloprsx"), so -X's value (sftp -X num_requests=64 localhost) consumes the option value instead of the positional slot and the real destination keeps full host-position checks — deny test added beside the -R precedent, plus the far-host allow guard (sftp -X num_requests=64 far.example.com stays allowed). OpenSSH sftp has no lowercase -x, so the letter is not case-fold-ambiguous and needs no _VERB_FOLD_AMBIGUOUS_OPT_LETTERS entry. Retrospective gate fired this round (36th, 3rd-round cadence): this round adds no mechanism — a one-letter table entry in an existing round-19 structure — and the round-26 keep-all retrospective plus the round-34 subtraction (host_addresses split) still cover the retained mechanisms.

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: none added (widened the round-35 rebuild helper: window scan + substring substitution)

Disposition: fixed in e43057d — span=5e784cc06287

  • xargs reconstruction still permits same-host SSH — shell_normalizer.py:1256

Fixed as asked, both legs. The here-string scan now covers the WHOLE simple command — it walks back from the xargs word to the previous separator and forward to the next — so a redirection placed before the utility (<<< localhost xargs ssh, <<< localhost sudo xargs ssh) is found and rebuilt. The -I/-i substitution now replaces the marker anywhere INSIDE an argument (tok.replace(replstr, payload)), matching xargs semantics, so xargs -I{} ssh user@{} <<< localhost rebuilds to ssh user@localhost and is denied. Far-host guards added for both shapes (<<< far.example.com xargs ssh and xargs -I{} ssh user@{} <<< far.example.com stay allowed). This widening covers the pre-command-redirection and marker-in-substring instances of the rebuild tradeoff wherever they move.

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: none added — the hosts cache key now carries _NETLINK_ADDRS_PUBLISHED, and a pre-publication not-local entry defers to the async layer
retrospective: ran this round (rounds-gate exit 30, span ×17) — verdict keep-under-publication-invariant; nothing removed; generation-counter invariant and evasion-layer subtraction recorded as follow-ups

  • fixed — Late-published local addresses remain cached as remote — span=7670520e57b3

Fixed in e33e46d, both arms at the chokepoint the finding named. (1) _HOSTS_FILE_CACHE keys on (st_mtime, st_size, _NETLINK_ADDRS_PUBLISHED), so a table parsed against the incomplete pre-publication own set is discarded and re-parsed the moment netlink publishes — the process-lifetime latch is gone. (2) Inside the window a not-local table entry answers None instead of False, so _host_is_self falls to _resolved_host_verdict, the same TTL-revalidated footing as the IP-literal window; a hosts alias never serves an authoritative pre-publication negative.
This ruling covers the class: every resolution path that computes not-self against the pre-publication own-address set now either fails closed (IP literals) or defers to the revalidating layer (hosts aliases); no path caches a pre-publication negative beyond publication. Locked by TestHostsAliasPublicationWindow: the late-published secondary flips the cached alias to a same-call deny, the window negative schedules revalidation, and the published remote alias keeps the round-21 same-call allow.

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: none added — no code change this round; the round-40 retrospective (recorded in disposition 5616616300) verdicts the _BINARY_COPY_VERBS name-binder family for removal, not extension
retrospective: round-40 inventory covers this finding's mechanism; extending the binder with a hash-builtin model would grow the family it retires

  • accepted-and-deferred — Executable aliases bypass the self-SSH floor — span=7670520e57b3

Deferred to issue #9806 (label deferred-finding, assignee patrigao, Due: 2026-10-09) — the OS-level network fence, which is exactly the Fix this finding itself names ("enforce an OS-level sandbox network fence blocking same-host SSH re-entry"). hash -p is one spelling of the name-binding-indirection class: a shell builtin binds an arbitrary name to the ssh binary, and no argv-text tier can enumerate bash's name-binding builtins (hash -p, alias in interactive shells, function wrappers, exec -a) any more than it can see inside bash escape.sh. The tier's declared boundary concedes runtime name resolution; the fence issue is the recorded fix-of-record for every member of this class.
This ruling covers the class: findings whose trigger is a shell name-binding or script-indirection spelling that resolves to the ssh binary at runtime are answered by #9806, wherever the spelling moves. The round-40 retrospective additionally verdicts the partial binder this finding extends (_BINARY_COPY_VERBS) for subtraction — adding a hash model would contradict the settled shape and add permanent surface with no practical protection while bash escape.sh stays open.
Maintainer override sentence: /ai-review override gpt e33e46d: hash-p name binding is the recorded indirection residual whose fix-of-record is the OS network fence (issue #9806, due 2026-10-09); the round-40 retrospective retires the binder family this finding extends.

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: none added — record-and-routing round; no code change

  • answered — interim-tier inertia watch: fix-of-record routing is in force and the tier has a defined shrink path

Both clear conditions are met on this head. (1) Issue #9806 carries owner (patrigao) and milestone (Due: 2026-10-09) with the deferred-finding label. (2) Routing is demonstrably in force, not aspirational: round 41's GPT finding (hash -p name binding, span 7670520e57b3) was routed to #9806 as accepted-and-deferred (disposition 5616831261) instead of growing the matcher — the first bypass report after the round-40 retrospective, handled exactly as this review asked.
The suggestion is done: #9806 now carries the shrink inventory (comment 5617597827) naming which resolution layers get DELETED when the fence lands (the evasion-emulation binders: glob/brace/arithmetic/function/xargs/copy-verb binding and static-expansion splicing) and which stay (own-identity resolution, the plain positional catalog rule). The interim tier has a defined shrink path; its false-deny surface (both fail-closed windows) is now declared in the PR description and stops being load-bearing when the fence lands.

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: none added — declarations corrected in the PR description; subtraction recorded on the fix-of-record issue

  • answered — undeclared windows declared, category claim corrected, binder subtraction on record

Items 4 and 5 (undeclared refusal windows): the PR description now declares both — a dotted hostname whose DNS lookup keeps failing stays refused on every retry (dotted-host ssh fails closed while a resolver outage lasts), and the Linux start-up window denies IP-literal targets until the background netlink sweep publishes the own-address set. Both windows are fail-closed by design (an unrecognized own address is the escape this floor exists to stop) and both stop being load-bearing when the #9806 fence lands.
Watch item (category claim): corrected in the PR description — the shipped category is self-protection; the description no longer claims a new sandbox-escape category or a spec category addition.
Item 6 (oversized binders) and the Subtractions list: adopted as the shrink path, not mid-review — the round-40 retrospective (disposition 5616616300) verdicts the evasion-emulation family for removal, and #9806 now carries the concrete delete list (comment 5617597827) matching this review's Subtractions item for item. Round 41 already routed the next binder-family finding (hash -p) to #9806 instead of extending _BINARY_COPY_VERBS, so the family has stopped growing on this PR. Removal ships as its own PR against the security corpus (pattern-subset invariant re-asserted), not as a same-head rewrite of a 41-round-reviewed diff.
Items 7 and 10 (rides along): the resolver threads and hosts/netlink reads are the mechanism for the justified items 1/3/5 and stay per the retrospective's keep verdict (own-identity resolution outlives the text tier); the two macOS test IDs wire the macOS adapter sweep this PR itself ships into the existing CI shard.

ssh to localhost (or this host's own name) re-enters the machine OUTSIDE
the agent sandbox: the far side is a fresh unsandboxed login shell, and
passwordless sudo there completes a full escape (observed live on a dev
desktop where sudo is broken inside the sandbox but 'ssh localhost sudo'
grants root).

Two-tier build, same shape as the existing self-protection floors:

- Catalog rule sandbox-escape-ssh-self (category sandbox-escape): a
  lint-safe positional regex — verb in command position, self host as
  the operand directly after it, end-delimited so a remote host merely
  named localhost.example.com never matches — kept a human-auditable
  SUBSET of the floor. No option-skipping group on purpose: that shape
  fails is_safe_user_regex, which would silently disable the rule.
- Argv-structural floor _is_ssh_to_self: FAIL-CLOSED about option
  grammar — every token that could be an operand, including one in an
  option's value slot, is checked against the self-host set, so no
  per-verb option table exists to get wrong (scp -r localhost:… was the
  shape that defeated a table). Resolves redirections the way bash
  removes them from argv, user@/URI-authority/bracketed-IPv6 prefixes,
  bare IPv6 and numeric IPv4 literals (::ffff:127.0.0.1, 2130706433,
  0x7f000001), hostname substitutions, -o hostname=/-o proxyjump=
  routing values, Windows .exe spellings, and this machine's own
  hostname/FQDN/addresses. ssh/sftp read only the FIRST unshadowed
  operand as the host, so a word like localhost inside a remote command
  run on another host stays data.
- Own-name resolution runs in a background daemon thread with retry
  backoff: getfqdn/getaddrinfo are synchronous DNS and is_denied runs
  inline on the gateway event loop, so the gate never blocks on DNS.
  Until the first resolve lands the own-name half is empty; the
  hard-coded loopback half never depends on it.

Named fail-open residuals (denying these would break every legitimate
remote ssh): -F config files, ProxyCommand, ssh_config Host aliases,
and substitutions that only resolve to this host at run time.

Remote hosts are unaffected. The rule is operator-disableable like its
floor siblings; the pattern-subset-of-predicate invariant, deny/allow
corpora, opt-out, tokenizer-failure union, and resolver failure paths
are locked by tests. Golden manifest 148->149; module spec and the
deny-guidance docstring updated alongside.

Round 8 (reviewer-verified escape gaps, maintainer-ruled fixes):
- Nested-frame RSYNC_RSH inheritance: a self-targeting RSYNC_RSH seen in an
  outer frame (export or env-prefix) now latches for the command's remaining
  frames, so RSYNC_RSH='ssh localhost' sh -c 'rsync host:/x .' is denied.
- IPv6 zone-ID bypass: %zone suffixes are stripped at both the resolver cache
  site and the _host_is_self operand, so fe80::1%eth0 matches the interface
  address fe80::1.
- Tests: 2 deny + 2 allow RSYNC_RSH frame cases, plus 2 zone-ID tests
  (resolver strip + match-time strip). Proof-run: all 4 new assertions fail
  on the pre-fix tree.

Round 9 (new reviewer-verified escape gap + import hygiene):
- Escaped-quote separator-mask bypass: inside double quotes a backslash-escaped
  quote is a literal, not a close. _mask_quoted_separators now honors bash's
  \" \\ \$ \` escapes inside double quotes, so scp "a\";b" localhost:/x no
  longer exits the quote at \" and reads the ; as a real separator that ends
  the operand walk before the self-host target. Deny test added; proof-run
  confirms it fails on the pre-fix tree.
- top-level-imports: fcntl/struct moved from a function-local import to a
  guarded module-level optional import; the Linux interface sweep now gates on
  their presence as well as sys.platform.

Round 10 (new reviewer-verified escape gap, maintainer-ruled fix + sweep):
- Parameter-default gluing bypass: _operand_targets_self checked each
  ${VAR:-word} default in ISOLATION, so bash's substitution INTO the
  surrounding word escaped it: ssh local${KC_UNSET:-host} id resolves to
  ssh localhost id. The whole operand is now resolved via
  _resolve_param_defaults (fixpoint: all operator spellings, colon-less
  and nested included) and the resolved spelling re-checked.
- Sibling sweep, one invariant at the operand chokepoint: every
  statically-derivable expansion/gluing form is resolved before host
  parsing. Brace expansion (local{h,}ost, ::{1,2}, 0x7f00000{1..2};
  alternations and numeric/char ranges, capped at 256 products with
  fail-closed deny on overflow) and single-integer arithmetic literals
  ($((0x7f)).0.0.1 -> 127.0.0.1; hex/bash-octal/decimal normalized, no
  expression evaluator) are expanded and each choice re-checked; the
  ProxyJump chain also checks its unsplit value so a brace comma is not
  torn by the hop split. Run-time-dependent forms (bare $VAR, command
  substitution with output, arithmetic beyond one literal) remain the
  documented residual class. Each resolution only widens the deny.
- Tests: 13 deny cases (6 parameter-operator/nesting forms, 5 brace
  forms incl. proxyjump, 2 arithmetic) + 4 allow cases locking remote
  hosts and plain file operands. Proof-run: exactly the 13 new deny
  assertions fail on the pre-fix tree.
- argv_floor.py black-formatted at the pinned version (clears the
  Backend Lint black-gate offender from round 9).

Review round 11: the quoted-separator sentinel table now covers every
_ends_argv boundary character (& newline # ( {), so a quoted boundary
token is operand data instead of a fake command boundary that hides a
later self-host target (scp '&' localhost:/tmp/x); backslash-newline
stays untouched as a line continuation. Interface addresses join the
synchronous own-host seed, so the first ssh-family command already
knows them -- the async worker only adds DNS-derived names, closing the
first-command window for ssh <own-interface-IP>. Comment wording in
argv_floor.py reworded to satisfy the comment-history lint gate.

The synchronous own-identity seed is packet-less: interface enumeration
keeps the UDP-connect probes and the Linux per-interface sweep, and every
resolver-backed form (getfqdn/getaddrinfo, plus Windows' resolver-backed
interface list) belongs to the async enrichment worker, so is_denied never
does DNS on the event loop. The operand walk reads userinfo before the
colon split when the @ precedes the first colon, so a bare IPv6 loopback
behind userinfo (user@::1) resolves to the whole remainder instead of an
empty host. The RSYNC_RSH walk remembers the last plain assignment across
separators and promotes it into the exported slot when a later bare
"export RSYNC_RSH" names it, covering the POSIX VAR=value; export VAR
two-step.

Windows adapters get their own packet-less sweep in the synchronous seed:
GetAdaptersAddresses (iphlpapi, via ctypes) reads the local adapter table
with the anycast/multicast/dns-server lists skipped, so a secondary or VPN
address with no DNS record is known before the first ssh-family command is
judged, matching the Linux per-interface sweep. The helper self-gates and
returns an empty set off Windows or on any failure.

The raw-substring verb gate resolves static parameter defaults before
probing (s${U:-s}h -> ssh), matching the operand walk; brace-range
integer conversion failures past the interpreter's digit cap land on
the existing fail-closed overflow deny instead of an uncaught
ValueError; a resolver Thread.start failure clears the in-flight latch
and answers from the synchronous seed instead of aborting the
permission decision. ctypes moves to the module import block.

Flat command substitutions with statically-decidable output (echo/printf
literals) splice into the source before the verb probe and the operand
walk, so ssh $(printf localhost) resolves to its output; dynamic bodies
keep their text and stay the documented run-time residual. macOS gains
a packet-less getifaddrs interface sweep feeding the synchronous seed,
the sibling of the Linux ioctl and Windows GetAdaptersAddresses sweeps.

Glob operands and command words resolve against what the pattern CAN
match: a word whose glob can name an ssh-family program passes the verb
gate and the walk, and an operand whose glob can match a loopback or
own-host name denies, both via fnmatch with no filesystem read. A
hostname the textual layers cannot classify goes to an off-loop DNS
verdict worker; the decision fails closed until the cached verdict says
whether any resolved address is loopback or local. The numeric-loopback
check accepts only spellings inet_aton or ip_address accept, so remote
domains with a numeric first label stay allowed.

Round 17 (three lanes): detached "-J value" (and flag bundles ending in
the jump letter) now latch the next token as a ProxyJump hop chain,
comma-split like the attached form. The fail-closed DNS-alias verdict is
consulted only for tokens in HOST position (ssh/sftp positional, a
host:path prefix, a scheme authority, a userinfo remainder, or a routing
option value) so dotted local filenames like backup.tar.gz are never
refused as first-contact hostnames. Literal same-line assignments
resolve before the verb gate and the walk (a=s; ${a}sh localhost
denies); one level of function-call argument binding recurses the floor
on the bound body (f(){ ssh "$1" id; }; f localhost denies); an
arithmetic expression that survives normalization fails closed in a
connection-target position (ssh 127.0.0.$((0+1)) denies), reversing the
earlier allow ruling for target-position expressions. The catalog rule
description now declares the one-time first-contact refusal instead of
claiming other hosts are unaffected, and the macOS CI leg runs the
interface-sweep tests so the darwin getifaddrs walk is CI-verified.

Round 18: the arithmetic literal normalizer keeps its decimal str()
inside the try -- a huge hex/octal literal whose int() succeeds (power-
of-two bases are exempt from the digit cap) but whose decimal spelling
exceeds it now fails closed through the target-position rule instead of
raising through is_denied. Host position survives valueless flags: a
new case-folded value-taking option letter set decides whether the
token after an option is the destination (ssh -v self.example is DNS-
checked) or the option's value (ssh -i id_rsa.pub is not), and a
consumed positional ends host position so later dotted remote-command
arguments stay data. The DNS-alias layer covers dotless names (an
/etc/hosts loopback alias resolves like any hostname; position, not
punctuation, keeps junk out) and allow verdicts are revalidated after a
TTL (stale-while-revalidate, one single-flight worker; deny verdicts
stay permanent) so a rebinding name is caught at the next publish. The
function binder accepts bash's parenthesis-free keyword form. The rule
description drops the word dotted.

Round 19: the value-taking option letters are per verb, and a
case-folded collision now reads as VALUE-TAKING -- sftp's uppercase -R
takes a value, so treating the folded "r" as valueless let the value
consume the positional slot and the real host went unchecked (sftp -R
64 localhost). A host mistaken for a value leaves the slot pending and
every later token still gets the full checks, so over-checking is the
safe side of that fold. ssh -c cipher is the same class and is covered
by the same table. Test assertions on the DNS recorder use exact
equality comprehensions (also clears the CodeQL substring-sanitization
false positive on the membership spelling).

Round 20 (Opus 1 + GPT 2 blocking, 1 advisory, plus a CI regression):
the verb-gate probe now runs the tokenizer's own ANSI-C decode, so
$'\x73\x73\x68' spells ssh to the gate exactly as bash spells it to
exec (the operand walk already decoded; the gate guarding it did not).
A same-line cp/mv/ln/install whose source operand is an ssh-family
binary binds its destination as that verb for the rest of the line
(cp /usr/bin/ssh /tmp/x && /tmp/x localhost), the statically decidable
half of the renamed-binary class; a copy staged in an earlier command
line stays the documented residual. An exact -- is now the POSIX
option terminator and preserves host position, so ssh -- localalias
reaches the DNS layer instead of being swallowed as an option value.
The round-18 dotless-alias change had sent every dotless first contact
to the fail-closed DNS layer, refusing the everyday ssh dev-dsk shape
(CI allow pin, both platforms): dotless names now get a same-call
verdict from the hosts file - the round-18 attack vector itself, a
local read with no DNS and no refusal - and absent an entry answer
open while one async worker revalidates; dotted names keep fail-closed
first contact. Rule text and golden manifest updated to declare the
split. The value-taking docstring now describes the per-verb table
(round-19) instead of contradicting it.

Two repo-gate fixes on the hosts-file layer: the POSIX hosts path is
component-assembled behind its os.name guard (Cross-Platform
Portability scans line literals and cannot see the guard), and the
parse reads a bounded slice (_HOSTS_FILE_READ_CAP, 4 MiB) instead of
iterating the handle - the repo-wide unbounded-handle-iteration guard
flags variable-path iteration, and the cap is real: a pathological
hosts file is read truncated and names past the cap fall through to
the async DNS revalidation, whose resolver reads the untruncated
database.
@patrigao

Copy link
Copy Markdown
Contributor Author

@iamwhatever Thanks — both comments are addressed in 8d4fd26; here is the disposition of each.

Port-forwarded self-host targets (your first comment): you are right that these are everyday shapes, and I looked hard at both softer options before concluding neither can ship safely inside this PR:

  • A blanket allow for explicit non-default ports is unsound in this threat model: the agent can start its own sshd on a high port (sshd -p 2222 -f <own config>) and connect to it, re-entering the host outside the gate exactly as with port 22. The port value alone cannot distinguish a forwarded container from a listener on this machine — which matches your own "sshd could also be listening on 2222" caveat.
  • The confirm-prompt route needs a new verdict type through is_denied, the hooks gate, and the approval UI; the allowlist route needs a per-rule options schema that the keystone denied_commands.json deliberately does not have (it carries only disable state and user-added deny patterns, and _DENY_EXCEPTIONS is built-in-only so the exception table stays agent-unwritable). Either is gateway-side schema/UI work, not a patch to this diff.

So: filed #9896 with the full design (keystone-schema per-rule exemption patterns honored by the floor loop with SEL exception events, default empty — strictly narrower than today's disable toggle, and it covers your -J shape too), and the refusal note now names the forwarded-port class explicitly with the interim recourse, so a user who hits it is told what happened and what their options are instead of facing a bare deny. If you consider the exemption channel a hard prerequisite rather than a follow-up, say so and I will scope it — but it grows this 40-round PR by a Settings schema, which felt wrong to ride along here.

First-contact refusal UX (your second comment): fixed as you suggested. The refusal note now leads the first-contact branch with pending semantics and an imperative retry hint — "DNS classification is PENDING, not that the host is blocked: retry this exact command" — and the wording is content-pinned by a new test (test_refusal_note_is_actionable) so a later reword cannot silently drop it. The distinct pending/retry verdict (instead of reusing the deny path) needs the same verdict-type plumbing as the confirm route, so it is recorded on #9896 as part of that design rather than half-shipped here.

Also in this push: rebased onto current main. The PR description was corrected earlier today to declare both fail-closed windows (failing-DNS retry refusal, and the Linux pre-publication IP-literal window) after the First-Principles review flagged them undeclared.

@patrigao

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: none added — no code change this round; both findings land in classes this PR's record already rules on

  • accepted-and-deferred — Command-line checks do not enforce the network boundary — span=7670520e57b3

F1 (argv_floor.py:1877, upheld-fenced): deferred to issue #9806 (label deferred-finding, assignee patrigao, Due: 2026-10-09) — the finding's own Fix line is that issue verbatim ("Enforce same-host SSH blocking at the OS sandbox network boundary"). ProxyCommand+/dev/tcp/127.0.0.1/22 and post-verdict DNS rebinding are spellings of the recorded runtime-indirection residual class (disposition 5616831261, round 41): no argv-text tier can see a socket opened by ssh's own child process or a record that changes after the check, any more than it can see inside bash escape.sh. The adjudicator's fence text agrees — "the enforcement point is the OS sandbox, not a text matcher." The TTL revalidation layer (round 18) narrows the rebinding window; the fence closes both vectors wholesale.
F2 (argv_floor.py:1809, DOWNGRADED by the Opus adjudication as disproportionate-remedy): accepted as designed, on the adjudication's own record — the hosts-file read is a bounded (4 MB cap), mtime/size-keyed, cache-fronted local read whose same-call verdict is the documented design goal of that layer (argv_floor.py:1789-1797); moving it off-loop would force a fail-open-or-closed default onto a deny floor to remove a one-time, self-clearing stall that only an atypical multi-megabyte hosts file can produce. No code change; the async off-loop pattern already covers the DNS layer, where the latency is unbounded.
This ruling covers the class: runtime vectors invisible to argv text (child-process sockets, post-check record changes) are answered by #9806, wherever the spelling moves; the round-40 retrospective retires the emulation family that chasing them would grow.
Maintainer override sentence: /ai-review override gpt 8d4fd26: the network-boundary finding is the recorded runtime-indirection residual whose fix-of-record is the OS network fence (issue #9806, due 2026-10-09), and the hosts-file finding was downgraded by the adjudicator as disproportionate-remedy; the text tier's declared boundary stands.

@patrigao

Copy link
Copy Markdown
Contributor Author

/ai-review override gpt 8d4fd26: the network-boundary residual will be addressed in follow-up issue #9806 (OS sandbox network fence, due 2026-10-09), the hosts-file finding was downgraded by the adjudicator as disproportionate-remedy, and this PR is strictly better security than before — it adds a same-host SSH deny floor where none existed.

@github-actions

Copy link
Copy Markdown
Contributor

Human judgment recorded

@patrigao marked the gpt AI finding as false positive, not applicable, or explicitly accepted for 8d4fd26f6beb0468b83bc53cad8df301073db25c.

the network-boundary residual will be addressed in follow-up issue #9806 (OS sandbox network fence, due 2026-10-09), the hosts-file finding was downgraded by the adjudicator as disproportionate-remedy, and this PR is strictly better security than before — it adds a same-host SSH deny floor where none existed.

This decision applies only to this commit. A new push requires a new judgment.

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.

4 participants