Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,60 @@ this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm

## [Unreleased]

- Niubash no longer refuses to prepare its runtime when a full-access session's workspace contains
the default `~/.dsh` home (#870). The workspace boundary stays armed in read-only and
workspace-write modes, where host workspace labeling and write gating could otherwise reach the
executable; full access runs without confinement, so the refusal only made a default `DSH_HOME`
under a home workspace unusable.
- Niubash 在 full-access 会话的 workspace 包含默认 `~/.dsh` 时不再拒绝准备运行时(#870)。
workspace 边界在 read-only 与 workspace-write 模式仍然生效——host 的 workspace 标注与写限制
本可能经由 workspace 触及可执行文件;full access 本就不经过 confinement,该拒绝只会让默认
`DSH_HOME` 落在 home workspace 下的会话完全不可用。
- ops_bash classifies the msys-2.0.dll shared-section startup failure
("CreateFileMapping S-<user SID>.<n>, Win32 error 5", printed without any "fatal
error" prefix) as EXECUTOR_UNAVAILABLE with `sandbox.runnerFailed`, so a restricted
token hitting an unrestricted MSYS holder's per-user section is no longer presented
as a bare non-zero exit (#409).
- ops_bash 将 msys-2.0.dll 的共享段启动失败("CreateFileMapping S-<用户 SID>.<n>,
Win32 error 5",打印时不带任何 "fatal error" 前缀)归类为 EXECUTOR_UNAVAILABLE 并带
`sandbox.runnerFailed`:受限令牌撞上非受限 MSYS 持有者的用户级共享段时,不再只呈现
一个裸的非零退出码(#409)。
- A regression guard locks the full-access projection of ops_bash: the selected
payload spawns without sandbox.confine and a plain bashPath runs directly, while
confined modes still route through confinement (#581). The reported full-access
child carrying a Low token (S-1-16-4096) did not reproduce on 0.5.5 — a
full-access child reported the caller's own integrity label here — so the guard
and the token-comparison diagnosis document the boundary instead of claiming a
code fix.
- 回归守卫锁定 ops_bash 的 full-access 投影:所选载荷不经 sandbox.confine 直接 spawn,
普通 bashPath 直接运行,受限模式仍走 confinement(#581)。报告的 full-access 子进程
Low 令牌(S-1-16-4096)在 0.5.5 上未能复现——本机 full-access 子进程回报调用方自身的
完整性标签——因此以守卫与令牌对照诊断记录该边界,而非声称代码修复。
- Document the niu-Git hook failure whose only difference is the shebang:
`#!/usr/bin/env sh` fails while `#!/bin/sh` runs, so husky v9 hooks are
affected. The entry records the observed diagnostic pair and the `#!/bin/sh`
workaround; the interpreter-resolution attribution is an upstream inference,
not a verified root cause (#958, unresolved-upstream).
- 记录 niu-Git 钩子失败:唯一差异是 shebang——`#!/usr/bin/env sh` 失败而
`#!/bin/sh` 可运行,husky v9 钩子同样受影响。条目记录实测诊断对照与
`#!/bin/sh` 缓解;解释器解析的归因是上游推断,不是已证根因(#958,
unresolved-upstream)。
- Document the per-call console flash on Windows 10 when Windows Terminal is
the default terminal. The entry gives the default-terminal comparison as the
diagnosis; the console-host hand-off explanation is an upstream inference, and
the hidden-console build remains upstream work, because no dsh-ops setting
controls console hosting (#828, unresolved-upstream).
- 记录 Windows 10 默认终端为 Windows Terminal 时每次调用的控制台闪烁。条目给出
默认终端对照作为诊断;控制台宿主交接的解释是上游推断,隐藏控制台构建仍属
上游工作——没有任何 dsh-ops 设置控制控制台宿主(#828,unresolved-upstream)。
- Document the antivirus pattern for Niubash: all pinned files intact except a
quarantined `niu.exe`, named by the #844 member diagnostic. The entry gives
the Defender/ESET event collection, the provision restore and the fixed-location
allow-list guidance, and marks the quarantine an external event rather than a
code defect (#771).
- 记录 Niubash 的杀毒软件模式:全部 pinned 文件完好、仅 `niu.exe` 被隔离,由 #844
的成员级诊断点名。条目给出 Defender/ESET 事件收集、provision 恢复与固定位置允许
列表指引,并把隔离标注为外部事件而非代码缺陷(#771)。
- Native tool construction and the publication refusal queue no longer attach listeners or lifetime effects to the composition root. The evidence observer and result admission subscribe on the caller's context with global dispatch, and the refusal queue falls back to the caller lifetime when the root refuses an effect. dsh-tui 0.20 refuses `root.events.on` and `root.effect` from a plugin activation, and the native-tools row is one, so every `dsh-tui --resume` aborted with "cannot resume session" before the agent mounted.
- 原生工具构造与发布拒绝队列不再向组合根挂监听或生命周期 effect:证据观察者与 result admission 改为在调用方上下文订阅并声明 global 分发,拒绝队列在 root 拒绝 effect 时回落到调用方生命周期。dsh-tui 0.20 会拒绝插件激活期内的 `root.events.on` 与 `root.effect`,而原生工具行正是插件激活,导致每次 `dsh-tui --resume` 都在 agent 挂载前报 "cannot resume session"。
- The Bash tool description now states the parse contract of `stdout`/`stderr` where the model reads it: `text` may be a partial fragment, `truncated` marks one that must not be parsed as complete structured output, and `spillPath` is optional and not a completeness guarantee. The typed output schema is unchanged: repeating the contract there would cost every PTC request without saying anything the tool text does not. Command semantics, exit codes, result values, limits, spill files, permissions and rendering are unchanged.
Expand Down
98 changes: 91 additions & 7 deletions docs/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,28 @@ What to do:
- Or switch the session to `danger-full-access`, where `bashPath` runs directly.
- Check with the profile's own copy: `node "<profile>\node_modules\dsh-ops\bin\dsh-ops.mjs" ladder --config <file>` reports `restricted: yes/no` for the resolved bash.

### A full-access `ops_bash` child seems to keep the restricted Low token

The session mode projects straight through in full access: the selected payload
spawns without `sandbox.confine`, a plain `bashPath` runs directly, and the child
carries the session's own token. Compare the tokens from the same caller before
assigning a cause (#581):

```console
MSYS2_ARG_CONV_EXCL='*' /c/Windows/System32/whoami.exe /groups
```

The `Mandatory Label` line is the child's integrity level: `S-1-16-4096` is Low,
`S-1-16-8192` Medium, and an elevated caller reports higher. A confined-mode child
is expected to differ from the host shell; a full-access child must match the
session's own level. A full-access child that still reports Low is a host
token-construction difference, not a dsh-ops setting: collect both `whoami.exe
/groups` outputs, the DSH core, OPS and Bash payload versions, and the exact
executable paths, and report them with the [runtime evidence
guide](windows-runtime-evidence.md). The plugin-side projection is guarded by
`test/shells-full-access-confinement.test.mjs`, which fails if a full-access
call ever routes through `confinedBash` or `sandbox.confine`.

### Restricted Bash is still preparing, or its last preparation was interrupted

Symptom, in a read-only or workspace-write session: an `EXECUTOR_UNAVAILABLE` whose second segment names a stage, for example `EXECUTOR_UNAVAILABLE: bash-staging-failed: …`, `bash-generation-quarantine-failed: …` or `bash-lifecycle-lock-busy: …`.
Expand All @@ -134,17 +156,19 @@ publishes the completed tree with an atomic sibling rename. Later calls check on
prepared `niu.exe` still exists; they do not clone, hash, seal, write an execution receipt or
dispose a per-call tree. Files the shell writes into its state directories are never inspected.

The prepared runtime must be **outside the session workspace**. Every call checks that boundary
and still uses the host's subprocess service and sandbox `confine` in restricted modes. In read-only and
workspace-write modes, the host denies writes to both the source and prepared payload outside the
workspace. Full-access mode keeps its normal host policy; the prepared directory is not a separate
security boundary against the account or an administrator.
The prepared runtime must be **outside the session workspace** in confined sessions. Read-only and
workspace-write modes check that boundary on every call and still use the host's subprocess service
and sandbox `confine`; the host denies writes to both the source and prepared payload outside the
workspace. Full-access mode keeps its normal host policy and runs a prepared root inside the
workspace — the default `~/.dsh` under a home workspace — instead of refusing it, because it is
not a separate security boundary against the account or an administrator (#870).

- On first preparation only, Windows scanner/indexer handles can delay the atomic publication
rename. Only `EPERM`/`EACCES`/`EBUSY` rename refusals are backed off, asynchronously, for up to 10 seconds;
a persistent failure names the rename in `EXECUTOR_UNAVAILABLE`. Commands are never retried.
- Put `DSH_HOME` outside the workspace before starting DSH. A workspace containing the prepared
runtime is refused rather than silently moving the runtime or running without confinement.
- For confined sessions, put `DSH_HOME` outside the workspace before starting DSH. A workspace
containing the prepared runtime is refused in read-only and workspace-write modes rather than
silently moving the runtime or running without confinement; full access runs it where it is.
- `DSH_OPS_EXEC_ROOT` and `NIUBASH_VERIFY=deep` are deprecated and ignored for new calls. Antivirus
allow-list rules should target the fixed prepared location, not a per-call temporary directory.
- For leftovers from older releases, stop **every OPS host and Bash job**, then use the installed
Expand Down Expand Up @@ -177,6 +201,66 @@ security boundary against the account or an administrator.
switching sessions do not repair it. Selecting an arbitrary Git Bash is not a restricted-mode
workaround: only a compatible pinned MSYS build may run restricted, never an unconfined fallback.

### `niu`-Git hooks fail with `#!/usr/bin/env sh` while `#!/bin/sh` works

Symptom: a repository hook installed through the niu-Git command — for example a
husky v9 hook — fails when its shebang is `#!/usr/bin/env sh`, while the same
script with `#!/bin/sh` runs. The observed pair is the diagnosis. The likely
mechanism — the `env sh` lookup resolving through the payload's own interpreter
machinery instead of the direct `sh` face — is an upstream inference this
repository has not verified inside the niu-Git binary tree (#958).

What to do:

- Confirm the pair from the same hook file: only the shebang differs, and the
`#!/bin/sh` form succeeds.
- Rewrite the affected hooks to `#!/bin/sh`; husky hooks are plain shell
scripts, so the shebang is the whole change.
- Report the payload version and both hook texts to the payload maintainers;
they can confirm or correct the interpreter-resolution attribution
(unresolved-upstream).

### `ops_bash` flashes a console window on Windows 10 with Windows Terminal

Symptom: every `ops_bash` call briefly flashes a black console window when
Windows Terminal is the system's default terminal application on Windows 10.
What is observed is the comparison, not the mechanism: switch the default back
to the Windows Console Host and see whether the flashing stops. The likely
mechanism — niubash being a console-subsystem binary launched without an
interactive parent, so each call asks for a console host and the Windows-10
terminal hand-off re-creates a visible console — is an upstream inference this
repository has not verified; no dsh-ops setting controls console hosting, and
the shipped binary cannot be patched here (#828).

What to do:

- Verify the default terminal setting (Settings → For developers → Terminal)
and compare the flashing with the default switched back to the Windows
Console Host; that observation pair is the diagnosis.
- A hidden-console niubash build is upstream payload work (unresolved-upstream).

### Antivirus quarantined `niu.exe` from the payload

Symptom: selection reports `EXECUTOR_UNAVAILABLE ... Incomplete Niubash payload:
niu.exe` while every other pinned file is intact — only `niu.exe` is missing
(#771). Preparation copies each pinned member verbatim, so a preparation that
stops at one executable is not a dsh-ops bug: the matching Defender or ESET
event is the security product quarantining that executable. This is an external
event; no repository change can prevent it, and the diagnostic naming the
missing member landed with #844.

What to do:

- Collect the matching event before restoring: Defender
`Get-MpThreat` / `Get-MpThreatDetection` (or the ESET detection log) with its
timestamp, action and the exact file path.
- Restore the complete pinned tree with `dsh-ops provision-shells --bash`, which
re-verifies every member.
- An allow-list rule, if you choose one, targets the fixed prepared location —
never disable protection or broadly trust the payload tree.
- If tampering is suspected, hash the restored `niu.exe` and compare it with the
receipt.

### A second restricted Bash fails while another Bash is still running

The `CreateFileMapping S-<user SID>.<version>, Win32 error 5` failure in #363 came
Expand Down
6 changes: 6 additions & 0 deletions docs/windows-runtime-evidence.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@ payload/root, whether an owned normal-token holder is alive, stderr, exit value,
and a restricted positive control. Stop only jobs you own; do not kill all Bash
processes or rewrite foreign ACLs to make a comparison pass.

An unrestricted MSYS process that created the per-user section first omits every
restricted-logon ACE, so the restricted token cannot reopen it; the proxy only arms
**new** objects. `ops_bash` classifies this message as `EXECUTOR_UNAVAILABLE` with
`sandbox.runnerFailed`, like the signal-pipe failure, instead of presenting a bare
non-zero exit (#409); it is never a user authorization denial.

`3221225794` and `-1073741502` represent `0xC0000142`. The status alone does not
identify the failing DLL or prove which process reached the command. A manual
launch of a staged restricted payload under a normal token is unsupported: its
Expand Down
5 changes: 5 additions & 0 deletions docs/windows-runtime-evidence.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ Get-FileHash -LiteralPath '<实际 msys-2.0.dll 路径>' -Algorithm SHA256
是否仍存活、stderr、退出值及受限正向对照。只停止自己拥有的任务,不要杀死所有 Bash
或重写外部对象 ACL 来让测试通过。

先以非受限令牌创建该用户 section 的 MSYS 进程不包含任何受限登录会话 ACE,受限令牌因此
无法重新打开它;代理只为**新建**对象附加权限。`ops_bash` 现在把这条消息与信号管失败一样
归类为 `EXECUTOR_UNAVAILABLE`(带 `sandbox.runnerFailed`),不再只呈现裸的非零退出码(#409);
它绝不是一次用户授权拒绝。

`3221225794` 与 `-1073741502` 都表示 `0xC0000142`;数字本身不说明哪个 DLL
失败,也不证明哪个进程已执行命令。不支持用普通令牌手动启动 staged 受限载荷:其 IPC
代理要求受限 Low 令牌。请通过 OPS 工具测试宿主实际 confinement 路径,保留完整 stderr,
Expand Down
7 changes: 5 additions & 2 deletions src/niubash/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,13 +163,16 @@ async function physicalPath(file: string): Promise<string> {

/** Command-time runtime for a selected payload. Host workspace labeling must never reach an
* executable through the workspace or a junction into it, so the prepared root is checked first.
* Full access runs without confinement and keeps the account's own authority over every path
* (#870); the refusal guards exactly the confined modes that label and gate the workspace.
*/
export async function prepareNiubash(selected: string, inheritedPath = process.env.PATH ?? process.env.Path ?? '', signal: AbortSignal,
{ workspaceRoot, env = process.env }: { workspaceRoot?: string; env?: NodeJS.ProcessEnv } = {}): Promise<NativeShellRuntime> {
{ workspaceRoot, mode, env = process.env }: { workspaceRoot?: string; mode?: 'read-only' | 'workspace-write' | 'danger-full-access'; env?: NodeJS.ProcessEnv } = {}): Promise<NativeShellRuntime> {
signal.throwIfAborted()
if (!path.isAbsolute(selected) || !isNiubashExecutable(selected)) throw unavailable('expected an absolute niu.exe path')
const source = path.dirname(selected), target = niubashPreparedRoot(env)
if (workspaceRoot && (inside(target, path.resolve(workspaceRoot)) || inside(await physicalPath(target), await physicalPath(workspaceRoot)))) {
if (workspaceRoot && mode !== 'danger-full-access'
&& (inside(target, path.resolve(workspaceRoot)) || inside(await physicalPath(target), await physicalPath(workspaceRoot)))) {
throw unavailable('the prepared payload must be outside the session workspace; move DSH_HOME outside the workspace')
}
let file: string
Expand Down
7 changes: 5 additions & 2 deletions src/shells/session-execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export function startSessionBash({ ctx, bash, active }: { ctx: ShellContext; bas
assertAuthority()
try {
const runtime = native ? await prepareNiubash(bash.file, dshEnv.PATH ?? dshEnv.Path ?? process.env.PATH, signal,
{ workspaceRoot: typeof policy.workspaceRoot === 'string' ? policy.workspaceRoot : undefined })
{ workspaceRoot: typeof policy.workspaceRoot === 'string' ? policy.workspaceRoot : undefined, mode: policy.mode })
: policy.mode === 'danger-full-access' ? { file: bash.file } : confinedBash(bash.file, { source: bash.source })
if (native) for (const key of Object.keys(env)) if (['PATH', 'NIU_ROOT', 'WINUXCMD_PATH', 'NIU_SKIP_WINUXCMD_ACTIVATION'].includes(key.toUpperCase())) delete env[key]
Object.assign(env, native ? runtime.env : { ...runtime.env, ...dshEnv })
Expand All @@ -57,7 +57,10 @@ export function startSessionBash({ ctx, bash, active }: { ctx: ShellContext; bas
(!rule.allowedExitCodes || (value.exitCode != null && rule.allowedExitCodes.includes(value.exitCode))) &&
stderr.split(/\r?\n/).filter(line => !rule.informationalLines?.some(info => info.toLowerCase() === line.toLowerCase()))
.some(line => rule.fatalSignatures?.some(signature => line.toLowerCase().includes(signature.toLowerCase()))))
const unavailable = runnerFailed || /couldn't create signal pipe|fatal error.*win32 error|sandbox_unavailable/i.test(stderr)
// msys-2.0.dll reports a shared-section conflict as "CreateFileMapping %W, %E."
// without any "fatal error" prefix: an unrestricted MSYS process created the per-user
// section first with no restricted-logon ACE, so the restricted token cannot reopen it (#409).
const unavailable = runnerFailed || /couldn't create signal pipe|createfilemapping\b.*win32 error|fatal error.*win32 error|sandbox_unavailable/i.test(stderr)
const denied = !unavailable && value.exitCode !== 0 && confinement?.denialSignatures?.some(signature => stderr.toLowerCase().includes(signature.toLowerCase()))
return withBashStatus({ ...value,
...(unavailable ? { error: 'EXECUTOR_UNAVAILABLE: the sandbox runtime failed before the command ran; this is not a user authorization denial. Restore the runtime or confinement provider; changing the DSH selector is not a repair. Do not bypass confinement.' } : {}),
Expand Down
Loading
Loading