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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,7 @@ schemars = { version = "1", optional = true }

[dev-dependencies]
tempfile = "3"
# Test-only Unicode General_Category oracle for the exhaustive
# forbidden-character class test (src/protocol.rs). Pinned exactly: its
# Unicode version fixes the version of the hand-copied DICP list there.
unicode-general-category = "=1.1.0"
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,8 @@ execute({"argv": ["apt", "install", "nginx"], "description": "Install nginx"})

Each `execute` shows the exact command in the TUI; press `y` to approve,
`N` (default) to deny. For remote hosts, pass `host` to `start_server` and
`execute`.
`execute`. Invisible/format characters (e.g. emoji variation selectors,
zero-width or bidi controls) are removed from `description` before it is shown.

When a prompt appears, the TUI rings the terminal bell and blinks the
question line so a request is not missed while the daemon's terminal is
Expand Down
4 changes: 2 additions & 2 deletions REVIEWING.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ finding.
authentication is owned entirely by `sudo`/`pkexec`. *Attack:* find any path
where sudo-proxy holds, caches, or replays a credential. β†’ `src/executor.rs`.
- **C6 β€” Display fields can't lie.** Fields shown at the prompt are rejected if
they contain control (0x00–0x1F bar tab), zero-width (U+200B–U+200F), or bidi
override (U+202A–U+202E, U+2066–U+2069) characters, so shown text cannot be
they contain control, format, separator or default-ignorable characters
(Cc/Cf/Zl/Zp/DICP bar tab; `protocol::DANGEROUS_RANGES`), so shown text cannot be
made to diverge from real `argv` via those classes. *Attack:* get a
divergence-causing character past the scanner to the prompt. β†’
`src/protocol.rs` (`ValidatedRequest::validate`, `:172`), `has_dangerous_chars`.
Expand Down
3 changes: 1 addition & 2 deletions backlog.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,7 @@ One PR per item; each moves its evidence status in `docs/assurance-case.md`;
every prompt-touching PR gets the pty goldens plus a live manual run.

**Phase 0 β€” close the current gaps** (independent; patch releases 1.2.x):
#86 `has_dangerous_chars` gaps (DEL/C1, U+00AD, U+061C, U+2028/2029,
U+2060–2064, U+FEFF; update the Kani harness and proptest with it) Β· #85 bound
~~#86 `has_dangerous_chars` gaps~~ (done, see changelog) Β· #85 bound
each `Steps:` line like `Command:` Β· #88 `--pkexec` multi-leaf plans (item 6
above) Β· #87 wrapper-aware `runs_shell` (item 5 above).

Expand Down
33 changes: 33 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,39 @@
Most recent at top. See [docs/formalisation-roadmap.md](docs/formalisation-roadmap.md)
for the assurance-ladder context behind the security-formalisation entries.

## Unreleased β€” Widen the prompt's forbidden-character class (#86)

`has_dangerous_chars` rejected C0 controls and three zero-width/bidi ranges
only. DEL and C1 (NEL, CSI, OSC), soft hyphen, ALM, line/paragraph
separators, word joiner and invisible operators, BOM, tag characters and
variation selectors all reached the approval prompt. The class is now one
rule, `c β‰  TAB ∧ c ∈ Cc βˆͺ Cf βˆͺ Zl βˆͺ Zp βˆͺ Default_Ignorable_Code_Point`,
held as a table built from the Unicode 16.0.0 UCD
(`protocol::DANGEROUS_RANGES`) and reused by the audit-record and
`--log-json` escapers.

- **Resolves paths.** Paths shown on `Resolves:` (tui and zenity) are printed
through `escape_dangerous`: a symlink's target name never goes through
validation, so a same-UID caller could put ESC or a newline on the prompt
that way.
- **Env-key message.** The "env key contains forbidden characters" error no
longer echoes the key. For consistency only: the key reached only the
response, and the audit copy was already escaped.
- **MCP.** `sudo-proxy-mcp` strips the class from `description` before it
becomes `reason`, so an emoji with U+FE0F no longer fails the request. The
daemon gate stays strict.
- **Newly rejected input.** Soft hyphens, emoji presentation sequences with
U+FE0F in `reason` from non-MCP clients, Arabic/Syriac text using U+061C,
U+0600–0605 or U+070F, a leading BOM, and tag characters now get the
existing validation error; drop the character.
- **Tests.** An exhaustive unit test checks the table over every `char`
against a General_Category oracle (`unicode-general-category`, a pinned
dev-dependency) plus a verbatim copy of the DICP list; a regression table;
integration tests over argv/reason/session/env value/plan leaves; a
non-ASCII accept test; an audit escape test; a `Resolves:` symlink test;
the property test with valid env keys and multibyte text; and the Kani
harnesses over the whole `char` domain.

## Unreleased β€” Audit log for every request outcome (#65)

The daemon logged prompted requests and unattended runs, and only with `-v`. It
Expand Down
8 changes: 4 additions & 4 deletions docs/assurance-case.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,17 +99,17 @@ a sanitized environment.*
| **Sn3.1** | `Command::new(argv[0]).args(…)`, never `sh -c` (`src/executor.rs`); the multi-stage `shell_escape` fuzzed with 5000 inputs, round-tripped through `/bin/sh` byte-for-byte. | 2 | [partial] β†’ Flux boundary type (Rung 3) |
| **G3.2** | The environment is a hard-reject allowlist; `LD_PRELOAD`/`LD_*`/`IFS`/`BASH_ENV`/`SSH_AUTH_SOCK` are rejected, not stripped. | β€” | |
| **Sn3.2** | `src/executor.rs` env sanitization; login defaults from `getpwuid(geteuid())`, not the request. | 1–2 | [discharged] |
| **G3.3** | Inputs carrying control / zero-width / bidi characters are rejected before use. | β€” | |
| **Sn3.3** | `has_dangerous_chars()` over every `pipeline` arg and `env` key/value; `tests/validation.rs`. | 2 | [discharged] |
| **G3.3** | Inputs carrying control, format, separator and default-ignorable (Cc/Cf/Zl/Zp/DICP) characters are rejected before use. | β€” | |
| **Sn3.3** | `has_dangerous_chars()` over every `pipeline` arg and `env` key/value; `tests/validation.rs` (widened in #86; class checked exhaustively against the UCD; Kani proves string/char agreement). | 2 | [discharged] |

### G4 β€” Faithful display at the gate

*The TUI shows the operator the real command and nothing that misrepresents it.*

| Node | Claim / Evidence | Rung | Status |
|------|------------------|------|--------|
| **G4.1** | No request field rendered to `/dev/tty` can inject ANSI / control / bidi sequences. | β€” | |
| **Sn4.1** | After **F1** fix: `has_dangerous_chars()` is applied to `reason`, `session`, `host`, `version`, `id`, `requester` in `validate_request`, covering both MCP and direct-socket paths; regression test. | 2 | [discharged] |
| **G4.1** | No request field rendered to `/dev/tty` can inject ANSI or control, format, separator and default-ignorable (Cc/Cf/Zl/Zp/DICP) characters. | β€” | |
| **Sn4.1** | After **F1** fix: `has_dangerous_chars()` is applied to `reason`, `session`, `host`, `version`, `id`, `requester` in `validate_request`, covering both MCP and direct-socket paths; regression test (widened in #86; class checked exhaustively against the UCD; Kani proves string/char agreement). | 2 | [discharged] |
| **G4.2** | The resolved absolute path of argv[0] is shown, with `-> target` when it is a symlink, so redirection cannot be hidden. | β€” | |
| **Sn4.2** | `src/tui.rs` path canonicalisation + explicit failure message. | 1 | [discharged] |
| **G4.3** | A large command cannot push the real command or the `[y/N]` line off-screen. | β€” | |
Expand Down
1 change: 1 addition & 0 deletions docs/security-audit.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ and covers both the MCP and direct-socket paths. Residual after fix: printable-r
Unicode look-alikes/NBSP in `reason` β€” a far weaker, passive social-engineering vector
that cannot hide the real command (documented, see F3 for the length dimension).
Regression test mirrors the existing argv bidi/control tests in `tests/validation.rs`.
Class widened under #86 (to Cc/Cf/Zl/Zp/DICP; filesystem-derived `Resolves:` paths escaped).

---

Expand Down
9 changes: 5 additions & 4 deletions docs/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,11 @@ in [usage.md](usage.md)).
**No shell invocation:** commands are executed via `Command::new(argv[0]).args(…)`,
never `sh -c`. This prevents `;`, `|`, `&&` injection.

**Input validation:** argv and env strings are rejected if they contain control
characters (0x00–0x1F except tab), zero-width characters (U+200B–U+200F), or
bidi override characters (U+202A–U+202E, U+2066–U+2069) that could mislead
the user during TUI approval.
**Input validation:** argv and env strings are rejected if they contain control,
format, separator or default-ignorable characters (Unicode Cc, Cf, Zl, Zp and
Default_Ignorable_Code_Point, except tab: e.g. ESC, DEL, C1, soft hyphen,
zero-width, bidi controls, BOM, tag characters, variation selectors) that could
mislead the user during TUI approval.

**Replay protection:** request UUIDs are tracked in a set that is cleared every
1000 entries. Duplicate IDs are rejected. Requests must carry a non-empty
Expand Down
6 changes: 5 additions & 1 deletion docs/threat-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ invariant at a given boundary are omitted.

| STRIDE | Threat | Control | Ref |
|--------|--------|---------|-----|
| Spoofing | ANSI / control / bidi sequences forge a benign-looking command in the prompt. | `has_dangerous_chars()` rejects control/zero-width/bidi on every displayed field; resolved absolute path of argv[0] shown with `-> target` on symlinks. | G4.1, G4.2 / F1 |
| Spoofing | ANSI / control / bidi sequences forge a benign-looking command in the prompt. | `has_dangerous_chars()` rejects control, format, separator and default-ignorable (Cc/Cf/Zl/Zp/DICP) characters on every displayed field; resolved absolute path of argv[0] shown with `-> target` on symlinks; filesystem-derived `Resolves:` paths escaped (#86). | G4.1, G4.2 / F1 |
| Tampering | A huge argument pushes the real command and `[y/N]` off-screen. | Displayed command length bounded with a hidden-bytes marker. | G4.3 / F3 |
| DoS | Operator never answers, leaving the gate open. | 60 s timeout, default **deny**. | G5.2 |
| Elevation | Social-engineer the human into approving. | Covered by G4; residual printable-range look-alikes accepted. | G4.4 (residual) |
Expand Down Expand Up @@ -186,6 +186,10 @@ is unaccounted for. The residuals β€” already on record and accepted β€” are:
or the multiplexer's socket.
- **3.4 β€” look-alike `reason` (F1 residual).** Printable Unicode can mislead but
cannot conceal the real command line, which is printed separately.
Combining overlays (U+0334–0338), RTL letters and whitespace look-alikes
(U+00A0, U+2000–200A, U+3000) remain accepted after #86: they are printable,
and `shquote` single-quotes any non-ASCII token, so they cannot sit next to an
operator.
- **4.2 β€” SSH first-contact MITM (assumption A4).** The ssh invocation sets no
`StrictHostKeyChecking`; safety depends on the remote being in `known_hosts`
first, or configuring `StrictHostKeyChecking=accept-new`.
Expand Down
5 changes: 3 additions & 2 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,8 +225,9 @@ declared one), `host`, `privileged`,
`command` (only for requests that passed validation), `detail` (the error sent
to the client), `status` and `exit_codes` (for requests that ran). Request
`env` values, `reason`, and the raw bytes of an invalid request are never
recorded. Request-derived strings are clipped to 256 characters, and control,
bidi and zero-width characters are written as `\u{…}` escapes (as on stderr), so
recorded. Request-derived strings are clipped to 256 characters, and tab,
newline and every character the prompt forbids (control, format, separator and
default-ignorable) are written as `\u{…}` escapes (as on stderr), so
the file is safe to `cat` or `tail -f` in a terminal.

The file belongs to the daemon's UID, which is also the requester's UID, so a
Expand Down
14 changes: 6 additions & 8 deletions src/audit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use std::sync::Mutex;

use serde::Serialize;

use crate::protocol::{Response, Status};
use crate::protocol::{is_dangerous_char, Response, Status};

/// Longest a single untrusted field may be in a record. A request that fails
/// validation can carry up to 1 MiB in `id`/`session`/`host`; the log must not
Expand Down Expand Up @@ -312,17 +312,15 @@ fn clip(s: &str) -> String {
}
}

/// Clip, then make terminal-safe: every C0/C1 control (newline and tab
/// included β€” a record is one line), DEL, and the zero-width / bidi characters
/// `has_dangerous_chars` forbids are written as `\u{…}` escapes.
/// Clip, then make terminal-safe: newline, tab (a record is one line) and
/// every character `protocol::is_dangerous_char` forbids on the prompt
/// (control, format, separator, default-ignorable) are written as `\u{…}`
/// escapes.
fn safe(s: &str) -> String {
let mut out = String::new();
for c in clip(s).chars() {
let u = c as u32;
if u < 0x20
|| (0x7F..=0x9F).contains(&u)
|| matches!(u, 0x200B..=0x200F | 0x202A..=0x202E | 0x2066..=0x2069)
{
if c == '\t' || c == '\n' || is_dangerous_char(c) {
out.push_str(&format!("\\u{{{u:x}}}"));
} else {
out.push(c);
Expand Down
10 changes: 8 additions & 2 deletions src/gui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::process::{Command, Stdio};
use std::time::Duration;

use crate::executor::{plan_display, which};
use crate::protocol::ValidatedRequest;
use crate::protocol::{escape_dangerous, ValidatedRequest};
use crate::tui::{self, pipeline_join, Prompter, PromptResult};

const PROMPT_TIMEOUT: Duration = Duration::from_secs(60);
Expand Down Expand Up @@ -73,7 +73,13 @@ fn format_prompt_text(req: &ValidatedRequest) -> String {
None => "(not found in PATH)".to_string(),
};
if shown != *cmd_name && seen.insert((cmd_name.clone(), shown.clone())) {
lines.push(format!("Resolves: {cmd_name} β†’ {shown}"));
// Escaped for display only (issue #86): `shown` is built from the
// validated argv[0]/cwd and the constant login PATH, so this is
// defence in depth; the comparison above uses the raw string.
lines.push(format!(
"Resolves: {cmd_name} β†’ {}",
escape_dangerous(&shown)
));
}
}
lines.push(String::new());
Expand Down
38 changes: 36 additions & 2 deletions src/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,18 @@ fn read_timeout_for(privileged: bool, timeout_ms: Option<u64>) -> Option<Duratio
}
}

/// Strip every forbidden prompt character (`protocol::is_dangerous_char`:
/// controls, format, separators, default-ignorables such as emoji variation
/// selectors) from the MCP `description` before it becomes `reason`. The daemon
/// rejects any request whose `reason` holds one, so without this an agent's
/// `"Restart nginx ⚠️"` (U+FE0F) would fail validation. The daemon gate itself
/// stays strict; this only keeps the common MCP path working.
fn sanitize_description(desc: &str) -> String {
desc.chars()
.filter(|c| !protocol::is_dangerous_char(*c))
.collect()
}

/// Build the outgoing `Request` from the tool parameters. Exactly one command
/// form is accepted: a structured `plan`, or the legacy `pipeline` / `argv`.
/// The daemon re-validates; this is only the client-side assembly.
Expand All @@ -60,7 +72,7 @@ fn build_request(params: &ExecuteParams, host: String) -> Result<Request, String

let session = "sudo-proxy-mcp".to_string();
let env = params.env.clone().unwrap_or_default();
let reason = params.description.clone().unwrap_or_default();
let reason = sanitize_description(params.description.as_deref().unwrap_or_default());

let mut req = if let Some(plan_json) = &params.plan {
let plan: protocol::Plan = serde_json::from_value(plan_json.clone())
Expand Down Expand Up @@ -288,7 +300,7 @@ impl McpProxy {
}

#[tool(
description = "Execute a command (or multi-stage pipeline) on a sudo-proxy host after a human approves it at that host's terminal. Provide `argv` for a single command or `pipeline` for piped stages (e.g. [[\"ls\", \"/tmp\"], [\"wc\", \"-l\"]]); `host` targets a remote daemon started via start_server (omit for localhost). Unprivileged commands on the local machine are refused β€” use your Bash tool, which applies the same controls. `timeout` is in milliseconds (max 600000); it defaults to 120000 for privileged commands but is opt-in for unprivileged ones (omitted = wait as long as the daemon needs, so an approved-but-slow command is not falsely timed out). Blocks until the human answers, then returns the final stage's stdout plus per-stage stderr and exit codes. Errors: 'Request denied by user.' if the human declines, a timeout error if unanswered within 60s, and 'sudo-proxy is not running' if the daemon is down β€” call start_server first."
description = "Execute a command (or multi-stage pipeline) on a sudo-proxy host after a human approves it at that host's terminal. Provide `argv` for a single command or `pipeline` for piped stages (e.g. [[\"ls\", \"/tmp\"], [\"wc\", \"-l\"]]); `host` targets a remote daemon started via start_server (omit for localhost). Unprivileged commands on the local machine are refused β€” use your Bash tool, which applies the same controls. `timeout` is in milliseconds (max 600000); it defaults to 120000 for privileged commands but is opt-in for unprivileged ones (omitted = wait as long as the daemon needs, so an approved-but-slow command is not falsely timed out). Invisible/format characters (e.g. emoji variation selectors, zero-width or bidi controls) are removed from `description` before it is shown to the approver. Blocks until the human answers, then returns the final stage's stdout plus per-stage stderr and exit codes. Errors: 'Request denied by user.' if the human declines, a timeout error if unanswered within 60s, and 'sudo-proxy is not running' if the daemon is down β€” call start_server first."
)]
async fn execute(
&self,
Expand Down Expand Up @@ -1255,6 +1267,28 @@ fn touch_host(host: &str, version: &str) {
mod tests {
use super::*;

/// Issue #86: the MCP `description` loses every forbidden prompt character
/// before it becomes `reason`, so the daemon's widened gate never rejects
/// an agent's emoji-presentation or zero-width text; printable non-ASCII
/// is kept.
#[test]
fn description_is_sanitised_of_forbidden_chars() {
assert_eq!(
sanitize_description("Restart nginx \u{26a0}\u{fe0f}"),
"Restart nginx \u{26a0}"
);
assert_eq!(sanitize_description("a\u{200b}b\u{2065}c"), "abc");
let benign = "cafΓ© ζΌ’ε­— β†’ πŸ™‚";
assert_eq!(sanitize_description(benign), benign);
for s in [
"x\u{1b}[2J\ny",
"\u{feff}bom\u{ad}\u{2028}\u{e0041}\u{85}",
"Restart nginx \u{26a0}\u{fe0f}",
] {
assert!(!protocol::has_dangerous_chars(&sanitize_description(s)));
}
}

/// The routing contract behind C9 and the Bash-delegation refusal: a
/// loopback/self alias resolves to the local target (`None`), a genuine
/// remote stays `Some`. (The full self/loopback classification, including
Expand Down
Loading
Loading