Skip to content

fix(builtins,executor): #866/#867 — unforgeable background-wrapper handshake + expected-parent PDEATHSIG race check - #873

Merged
caomengxuan666 merged 5 commits into
masterfrom
fix/866-867
Oct 19, 2026
Merged

caomengxuan666 merged 5 commits into
masterfrom
fix/866-867

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

Closes #866. Closes #867.

What was wrong

#866 — compound_exec.rs inserted the plain constant __RUBASH_BACKGROUND_WRAPPER=1 into the wrapper's env and kill.rs child_pre_exec_reset() re-checked that exact value, so any script doing export __RUBASH_BACKGROUND_WRAPPER=1 imposed the wrapper's PR_SET_PDEATHSIG semantics on every child the shell spawned afterwards (third-party programs included). Same reserved-namespace collision class as #735.

#867 — the PDEATHSIG fork-race patch compared getppid() against the constant 1. Inside a PID namespace a healthy child of the namespace's PID 1 observes getppid() == 1 before any race is possible and deterministically SIGKILLed itself at spawn (unshare --pid --fork + forged marker: every background job died at creation, rc=137 at pid 3).

The fix

  • user-forgeable __RUBASH_BACKGROUND_WRAPPER env var imposes PDEATHSIG semantics on every spawned child #866: the marker is now an unguessable spawn-time nonce (SplitMix64 over clock nanos / pid / process-local counter / ASLR stack anchor — 128 bits, no RNG crate) carried by two handshake channels: the env key and a consumed --internal-bg-wrapper=<nonce> argv flag (main.rs, before any parser, same consume-on-read face as NIU_INVOKED_AS / --internal-*). The wrapper role arms in-process (AtomicBool static in kill.rs) only when both channels agree; the env key is scrubbed at startup either way. A forged export arms nothing and leaks nowhere.
  • getppid() == 1 orphan-race check self-kills healthy children under PID namespaces #867: the expected parent pid (the wrapper's own pid at handshake time) is captured in-process; an armed child self-kills only when getppid() diverges from it — never against the constant 1.
  • Exact predicate swap (the key parity argument): pre_exec runs in the forked child before execve, so the old env::var probe always read the forking parent's environ — the check was always a parent-state predicate. Swapping "parent env has the marker" for "parent holds the in-process role" keeps every spawn's arming decision identical in clean environments: the main shell never arms (a wrapper survives its shell's exit, as GNU background jobs do), a wrapper arms every child it spawns ([S9] process ownership: kill does not terminate background shell children (and wait fabricates 128+n); no SIGPIPE for builtin writers #737 contract), nested wrappers arm exactly as before. The only intended divergence is the forged value, which now arms nothing.
  • Side benefit: the post-fork hook no longer calls std::env::var (heap allocation inside pre_exec); it is syscalls + atomic loads only.

Adversarial probes (WSL, arm = Linux build, oracle = GNU bash 5.3.0 /usr/local/bin/bash)

probe pre-fix (master 45f537ea/e6a54457) post-fix GNU
#866: export __RUBASH_BACKGROUND_WRAPPER=1 + direct-path sh -c 'sleep 2; echo SURVIVED' &, shell exits child killed at shell exit → empty SURVIVED SURVIVED
#867: unshare --pid --fork env __RUBASH_BACKGROUND_WRAPPER=1 rubash -c 'sh -c "sleep 2; echo ALIVE" & wait' Killed … rc=137 (self-kill at spawn, ns pid 3) ALIVE rc=0 ALIVE rc=0
#737 contract: kill -9 on a wrapper-path job wrapper killed, child dies identical (also under forged env) —
kill builtin spot-checks (kill -l 15, kill -l TERM, kill 999999, kill -0 999999, kill %nosuch) byte-identical to GNU, rc identical unchanged ✓

Regression pins

Verification

  • fmt clean; RUSTFLAGS="-D warnings" cargo check --lib --bins + the two new test targets clean (the pre-existing -D warnings failures in issue531/issue621/issue804 test targets reproduce on master untouched); cargo check --target x86_64-unknown-linux-gnu clean.
  • Windows full suite (--test-threads=1, --no-fail-fast): 3835 passed / 19 failed — cli_tests 13 (missing c helper, passwd-home; env), executor_tests 5 (cd/PWD/-p/-V — identical set fails on master), lib 1 (flaky; clean on immediate rerun, 689/689). Zero new semantic failures.
  • WSL Linux lane: --lib 615/615; family files issue294 (4), issue549 (11), issue550 (3), issue866 (4), issue867 (2) all green; kill semantics byte-identical to the 5.3.0 oracle.
  • Full-suite bidirectional re-run deferred to the main session's serial batches (desktop window-flash concern); the branch is merged onto current master (bd24cf8b) and ready for it.

GNU source note

PDEATHSIG arming is rubash-internal #737 machinery — GNU bash spawns background jobs as plain forks (execute_cmd.c:5562+ execute_connection &, execute_in_subshell) and imposes no parent-death signal; the parity obligations pinned here are exactly those: bg children survive shell exit (jobs.c no-op on exit), kill $! wording/rc (jobs.c:3064 wait_for / kill.def), unchanged pre/post.

…shake + expected-parent PDEATHSIG race check

#866: __RUBASH_BACKGROUND_WRAPPER was a plain user-guessable env var
(constant "1") inserted by the wrapper spawn path and re-checked verbatim
by child_pre_exec_reset, so 'export __RUBASH_BACKGROUND_WRAPPER=1' imposed
PDEATHSIG semantics on every child the shell spawned afterwards — third-
party programs included. The marker is now an unguessable spawn-time nonce
(SplitMix64 over clock/pid/counter/ASLR anchor) carried by TWO handshake
channels — the env key and a consumed --internal-bg-wrapper=<nonce> argv
flag (main.rs, before any parser); the wrapper role arms in-process only
when the channels agree, and the env key is scrubbed at startup.

The role check is an exact predicate swap: pre_exec runs in the forked
child BEFORE execve, so the old env::var probe always read the forking
PARENT's environ — 'parent env has the marker' and 'parent holds the
in-process role' decide every spawn identically in clean environments
(the main shell never arms, so a wrapper survives its shell's exit as
GNU's background jobs do; a wrapper arms every child it spawns — #737
contract), while forged values arm nothing.

#867: the fork-race check compared getppid() against the constant 1,
which a healthy child of a namespace's PID 1 matches before any race and
deterministically self-SIGKILLed at spawn (repro: unshare --pid --fork
with the forged marker -> every background job rc=137 at creation). The
expected parent pid (the wrapper's own pid at handshake time) is now
captured in-process and the child self-kills only when getppid() DIVERGES
from it.

Probes (WSL, GNU bash 5.3.0 oracle): forged-env child killed at shell
exit pre-fix / survives post-fix; forged+namespace child killed at spawn
(pid 3, rc=137) pre-fix / survives post-fix; kill -l/kill wording/rc
byte-identical to GNU pre and post; kill -9 on a wrapper still takes its
child (#737). Catalog case issue-866 (must-match).
… — ExitStatusExt import caught by the WSL lane
@caomengxuan666

Copy link
Copy Markdown
Member Author

独立评审:APPROVE-WITH-NITS

评审对象:PR #873(fix/866-867 @ 99b8c6e,base master@bd24cf8b)。自建 detached worktree 独立复跑,未触碰他人 worktree。

BLOCKER:无。

安全审计(攻击者思维,逐项)

  • 双通道握手不可伪造性(user-forgeable __RUBASH_BACKGROUND_WRAPPER env var imposes PDEATHSIG semantics on every spawned child #866 主张):成立。伪造 env 单通道 → 不 arm 且被无条件清洗(探针:伪造值下直接后台子 SURVIVED,与 WSL GNU bash 5.3.0 oracle 同形输出字节一致);伪造 argv 单通道 → flag 在 main() 任何 parser 之前 consume-on-read、不 arm、无 parser 报错、env 计数 0。
  • nonce 熵:SplitMix64 双 draw,种子 = 时钟 ns ^ pid·C ^ 进程内计数器·C ^ ASLR 栈锚。理论有效熵 < 128 bit(同时刻紧夹逼 + pid 空间 + ASLR ~2^60+),但对同 UID 握手场景远超需求;flag 侧 nonce 本就同 UID 可经 /proc/*/cmdline 读到,无额外越界。可接受。
  • 残留(设计注记,非阻塞):握手证明的是「spawn 方对两个通道写入了同值」,不是「spawn 方是 compound_exec」——env __RUBASH_BACKGROUND_WRAPPER=x rubash --internal-bg-wrapper=x … 会 arm(已实测)。后果被限制在 arming 者自己的进程树(对其自建子进程施加 PDEATHSIG 耦合);user-forgeable __RUBASH_BACKGROUND_WRAPPER env var imposes PDEATHSIG semantics on every spawned child #866 的跨边界攻击(shell 内脚本 export 劫持用户 shell 后续 spawn)已关闭。建议握手 doc-comment 补一句承认该残留,防止后人把 nonce 误当 capability。
  • env 清洗时机:main() 中 materialize_command_file 之后、Executor 创建与任何脚本执行之前;wrapper 内实测 env | grep -c __RUBASH_… = 0,孙进程零继承。
  • TOCTOU:ROLE/EXPECTED_PARENT startup 一次写入(Release)、pre_exec fork 子内 Acquire 读,无 un-arm 路径;测试模块改全局态由 .cargo/config.toml 强制 RUST_TEST_THREADS=1 + CI nextest 进程隔离兜底。
  • getppid() == 1 orphan-race check self-kills healthy children under PID namespaces #867 语义:expected-parent = 握手时捕获的 wrapper 自身 pid,仅 getppid() 偏离时自尽;PID namespace 下 healthy child 不再误杀(L1 实跑确认),fork→prctl 竞争窗口仍被覆盖(单测 child_whose_parent_diverges_from_expected_self_kills 平台精确钉死)。

语义对等独立复核

  • pre_exec 旧 env::var 读的是 forking 父 environ(fork 后 COW)→ 父状态谓词;换 in-process role 是精确谓词替换,clean env 下逐 spawn 等价 —— 论证成立。三处 hook 装点(fd/unix.rs spawn_whitelisted、compound_exec 直通路径、external_inner.rs 前台)同走新谓词。
  • 三层场景实测:外层 shell → wrapper A(nonce 双通道)→ wrapper B(新 nonce)→ 孙子 C:env 逐层清洗、A 死→B 死→C 死 cascade 正确;wrapper 存活外层 shell 退出、直接后台子存活 shell 退出,两者与 GNU oracle 一致。
  • [S9] process ownership: kill does not terminate background shell children (and wait fabricates 128+n); no SIGPIPE for builtin writers #737 契约:kill -9 wrapper → 子进程随之死(实测,含嵌套中层)。

回归(全部自跑)

项 结果
cargo fmt --check clean
-D warnings(Windows all-targets) PR 新目标与 lib 干净;仅 tests/issue523、issue528 两个既有失败(文件不在 diff、与 master 字节相同,按构造即既有)
WSL --lib 615/615(含新增 5 handshake + 2 pdeathsig 单测)
tests/issue866 + issue867 6/6(L1/L2 的 unshare --pid --fork 实跑,非 skip)
catalog issue-866 must-match → match(GATE ok)
catalog issue-737 diverges → 仍 DIVERGES(#794 follow-up 未被碰)✓
Windows 家族 issue294(×2)/382/549/550 28/28 绿
全量 --tests(WSL) cli_tests 11 failed —— 我另建 base worktree(bd24cf8b)对跑,failure 名单 diff 为空:PR 引入 0 新失败
夹带扫描 commit 粒度 8 文件(c2=master #865 合入、c3=linux-gate 编译修复);无 Cargo.lock/依赖变更、无 GPL 文本
红线 kill builtin 解析/执行面零改动;测试仅 kill 自建子进程

NITS(非阻塞)

  1. 注释漂移:src/executor/compound_exec.rs:422-426 直通路径注释仍写 "The [S9] process ownership: kill does not terminate background shell children (and wait fabricates 128+n); no SIGPIPE for builtin writers #737 pdeathsig arm keys off __RUBASH_BACKGROUND_WRAPPER, which is never set here" —— 新机制下 arm 只看 in-process role(主 shell 永不 arm),env 任何位置都不再被读。结论句仍真(直通异步子活过 shell 退出,W2+catalog 已钉),仅机制描述过时。
  2. 设计注记:见上「残留」条 —— 建议在 consume_background_wrapper_handshake doc-comment 加一句:握手证明「双通道同值」而非「compound_exec 来源」,同值双通道的自设 spawn 会 arm(自作用域)。
  3. exec 分叉(GNU 方向,知情即可):wrapper 内 exec rubash … 替换 wrapper 后,替换进程无握手、其子进程失去 [S9] process ownership: kill does not terminate background shell children (and wait fabricates 128+n); no SIGPIPE for builtin writers #737 cascade(旧 ambient-env 机制可穿透 exec)。新行为更贴近 GNU(GNU 无 cascade);若 [S9] process ownership: kill does not terminate background shell children (and wait fabricates 128+n); no SIGPIPE for builtin writers #737 契约要求穿透 exec 属 follow-up 范畴。

验证声明核对

实现代理 5 项主张中:#866 双通道 nonce、#867 expected-pid、对等论证、对抗探针、验证清单——逐项复跑均属实(唯一出入:全量失败计数其称 19、我测 11,属 lane 范围差异;base==head 集合精确相同才是关键,已证)。

结论:APPROVE-WITH-NITS(无 BLOCKER;nit 1 建议随本 PR 或紧随 hygiene PR 修掉)

# Conflicts:
#	scripts/regression-catalog/manifest.tsv
# Conflicts:
#	scripts/regression-catalog/manifest.tsv
@caomengxuan666

Copy link
Copy Markdown
Member Author

发版阻塞后续(niubash master CI 两红):本 PR 的 argv 旗标通道被 wrapper 重spawn 无条件附加,不消费握手的主机 CLI(niubash 的 niu 启动器;或任意 bash 面)会以 bash: --internal-bg-wrapper=<nonce>: invalid option + usage 拒收,后台命令 spawn 即死。

修复(两层,已开 PR):

本仓全量验证见 #906 描述(WSL lib 634/634、issue866 4/4、issue867 2/2、家族 28/28、catalog 866 match / 737 维持 diverges、fmt + lib/bins -D warnings clean)。

caomengxuan666 added a commit that referenced this pull request Oct 20, 2026
…e argv flag only when the host CLI consumes it (#906)

The --internal-bg-wrapper=<nonce> channel is niu-CLI-specific. The wrapper
spawn site attached it unconditionally, so any host that never consumes the
handshake received an unknown option in its respawned argv: the niubash
launcher (which embeds this engine) answers with the GNU-aligned usage
error — bash: --internal-bg-wrapper=<nonce>: invalid option + usage, rc 2 —
and every wrapper background command died at spawn (niubash master CI,
tests/background_spawn_args.rs 2 red). A foreign bash face would reject it
the same way.

Gate the attach on a process-level consumer bit:
consume_background_wrapper_handshake now marks the CLI at its very top
(rubash main.rs calls it at every startup; adopting hosts make the same one
call — niubash does, in the companion launcher commit), and the spawn site
splices the flag only when background_wrapper_flag_consumer_present() is
set. Non-consuming hosts get env-nonce-only respawns: the env key is inert
for a non-consumer (never read; any rubash that does start scrubs it) and a
single channel can never arm, so the #866 forgery contract is unchanged;
#867's expected-parent check and the #737 cascade are untouched for
consuming hosts.

cfg(test) keeps the attach unconditional in this crate's unit tests: the
harness process never runs main.rs, so without it the attach would be
order-dependent on the handshake unit tests; there the respawn target is
always this repo's own engine binary (CARGO_BIN_EXE /
test_rubash_binary_from_current_exe), a consumer by construction.

Verified: WSL lib 634/634 (incl. the new consumer-bit unit test), tests
issue866 4/4 (W1 #737 cascade intact through the real binary) + issue867
2/2 (unshare namespace probes), Windows family issue294/382/549/550 28/28,
catalog issue-866 match + issue-737 still diverges, fmt clean, -D warnings
clean for lib+bins; niubash companion branch flips the two CI-red tests
green against this tree.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant