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
19 changes: 10 additions & 9 deletions backlog.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,15 +86,14 @@ shipped in PR #67 (see changelog).
arguments (like a wrapper-aware resolver, and flag an unresolvable one), or
allow non-allowlisted names in `setenv` for non-root subtrees so the `env`
wrapper is unnecessary. Found live-testing case 22.
6. **`--pkexec` with a multi-step `privileged: true` plan** (issue #88; also
Phase 0 of *"Display fidelity — Option A"* below). Each escalated
step raises its own pkexec dialog, which shows only that step (and, since
steps run as `pkexec env -C <dir> -- argv`, names `/usr/bin/env` as the
program). With the `pkexec-cache` polkit rule, steps after the first run with
no dialog at all. Options: reject multi-leaf plans in `--pkexec` mode, or
show the whole plan in the TUI and use pkexec only to authenticate. Plans
that escalate only via `run-as` already take the TUI prompt (PR #59 review
fix). Found in the PR #59 review.
6. **pkexec dialog names `/usr/bin/env`** (left over from #88). Use
`pkexec --keep-cwd` when polkit ≥ 121 (probe once, like
`env_supports_chdir`), or skip `env -C` when the cwd is the target user's
home.
7. **Does a single-leaf plan's `setenv` reach the program under `--pkexec`?**
pkexec resets the environment. If it does not, either pass it as `env K=V`
arguments (so the dialog shows it) or route `setenv` plans to the TUI and
sudo. Found in the #88 plan review.

## Cap far-future request timestamps, then re-climb the ladder to Rung 4

Expand Down Expand Up @@ -156,6 +155,8 @@ U+2060–2064, U+FEFF; update the Kani harness and proptest with it) · #85 boun
each `Steps:` line like `Command:` · #88 `--pkexec` multi-leaf plans (item 6
above) · #87 wrapper-aware `runs_shell` (item 5 above).

Done: #88.

**Phase 1 — state the invariant, make it literally true** (release 1.3.0):
1. Docs first: G4.6 *"syntax is daemon-owned"* (no wire field printed verbatim
in the command slot); split Sn4.5 into a syntactic half (render ⇒ shell
Expand Down
22 changes: 22 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,28 @@
Most recent at top. See [docs/formalisation-roadmap.md](docs/formalisation-roadmap.md)
for the assurance-ladder context behind the security-formalisation entries.

## Unreleased — `--pkexec` delegates only single-step privileged requests to pkexec (#88)

Under `--pkexec`, every `privileged: true` request went to pkexec, one dialog
per escalated step. A dialog shows a single argv (named `/usr/bin/env`, since
steps run as `pkexec env -C DIR -- argv`) and never the files the daemon opens
for a redirection, so no dialog showed the whole plan, and with `pkexec-cache`
the later steps ran with no dialog at all. Now only a `privileged: true`
request that compiles to one step with no redirection is delegated to pkexec
(`delegate_to_pkexec` in `src/server.rs`, reading the same views the prompt
renders). Every other privileged request (multi-step, redirected, or escalating
only through `run-as`) gets the TUI prompt and runs through sudo; a `--pkexec`
user without sudo rights now gets a sudo failure after approving such a plan,
as `run-as` plans already did, and these requests are audited as
`approved`/`denied`/`timeout` instead of `pkexec`. Unchanged: the dialog still
names `/usr/bin/env` and omits env and accepted exit codes (backlog items
"pkexec dialog names `/usr/bin/env`" and "Does a single-leaf plan's `setenv`
reach the program under `--pkexec`?"). Tests: a unit table for the predicate, `tests/plan_exec.rs`
`pkexec_mode_prompts_for_multi_leaf_privileged_plans` (run/seq/alt/pipe,
redirect, with-stdin-from; one `denied` audit record each, none `pkexec`), and
the pty test `pkexec_flag_multi_step_plan_gets_the_tui_prompt` through the real
CLI with `DISPLAY` set. G5.4 / Sn5.4 and threat-model leaf 4.5 added.

## Unreleased — Audit log for every request outcome (#65)

The daemon logged prompted requests and unattended runs, and only with `-v`. It
Expand Down
4 changes: 3 additions & 1 deletion docs/assurance-case.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,12 +126,14 @@ keypress binds to the command shown.*

| Node | Claim / Evidence | Rung | Status |
|------|------------------|------|--------|
| **G5.1** | `privileged:true` always reaches the Y/N gate regardless of any policy. | — | |
| **G5.1** | `privileged:true` always reaches the Y/N gate regardless of any policy. Exception: under the opt-in `--pkexec` flag, polkit's dialog replaces the Y/N gate for a single unredirected escalated step; see G5.4. | — | |
| **Sn5.1** | TLC-checked: the `PolicyFlipsOnlyOnKeypress` invariant of [`proofs/tla/`](../proofs/tla/) proves the policy flag flips only via an interactive `a` keypress on an unprivileged request — never a request field, replay, MCP flag, or timeout — over all attacker forgeries/replays and operator choices. `src/server.rs`. | 4 | [discharged] (model-checked) |
| **G5.2** | The prompt reads a single keypress in non-canonical mode and times out after 60 s (default **deny**). | — | |
| **Sn5.2** | `src/tui.rs` prompt; timeout test. | 1 | [discharged] |
| **G5.3** | No policy value relaxes the **privileged** gate: `privileged:true` requires a `y` keypress regardless of `unattended_eligible` or the session grant. | — | |
| **Sn5.3** | TLC-checked: `PrivilegedGateIndependentOfPolicy` ([`proofs/tla/`](../proofs/tla/)) proves the privileged gate requires a `y` keypress for *any* eligibility/grant state. The *unprivileged* side (eligibility + session grant) is the second invariant **G7** below. | 4 | [discharged] (model-checked) |
| **G5.4** | Under `--pkexec`, approval is delegated to polkit only for a request whose dialog shows one escalated argv with no redirection (`privileged: true`, one leaf, no redirection); every other privileged request reaches the TUI Y/N gate. | — | |
| **Sn5.4** | `src/server.rs` `delegate_to_pkexec` (unit table `delegate_to_pkexec_only_for_a_single_plain_leaf`; it reads the same `plan_display` views the prompt renders); `tests/plan_exec.rs` `pkexec_mode_prompts_for_multi_leaf_privileged_plans`, `pkexec_mode_still_prompts_for_run_as_plans`; `tests/pty_e2e.rs` `pkexec_flag_multi_step_plan_gets_the_tui_prompt`. Residuals: the dialog names `/usr/bin/env` and shows the working directory only as `env -C DIR`; it does not show plan `setenv`, request env or `with-accepted-exit-codes` (whether `setenv` reaches the program under pkexec at all is unverified; see backlog); `pkexec-cache` makes even a single-step request run with no dialog (documented as not recommended). | 1–2 | [discharged] |

### G6 — Adversary cannot bypass the gate

Expand Down
15 changes: 9 additions & 6 deletions docs/pkexec.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,15 @@ There is no middle ground in polkit. The TUI mode solves this by always
prompting for approval (one keypress, no password) while letting the OS
handle password authentication separately.

Only requests sent with `privileged: true` go to pkexec. In those, every step
escalates, so each one raises its own dialog. A structured plan that escalates
only some steps (through `run-as` nodes) still gets the TUI prompt and runs
through sudo, even in `--pkexec` mode. A pkexec dialog shows a single step, so
the unescalated steps of such a plan would otherwise run with no approval at
all.
Only a request sent with `privileged: true` that is a single step without
redirection goes to pkexec. Any other privileged request (a multi-step plan, a
step with a redirection or `with-stdin-from`, or a plan escalating only through
`run-as` nodes) gets the TUI prompt and runs through sudo, even in `--pkexec`
mode. A pkexec dialog shows one argv and no redirection: the daemon opens
redirected files itself, so the dialog never names them, and with
`pkexec-cache` the later steps of a plan would run with no dialog at all. Even
for a single step, the dialog does not show plan `setenv`, request env or
accepted exit codes, and shows the working directory only as `env -C`.

Each escalated step runs as `pkexec env -C <dir> -- <argv>`, so it starts in
the plan's working directory rather than the target user's home, which is
Expand Down
16 changes: 13 additions & 3 deletions docs/threat-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,9 +152,13 @@ A A root command runs that the human did NOT approve
│ · blocked (residual: first-contact MITM, assumption A4)]
├─ 4.3 Exhaust resources to make the gate fail open
│ [caps + default-deny timeout → G5.2 / G6.4 · blocked]
└─ 4.4 Tamper hosts.json to weaken the gate
[enforced owner/mode check / F4; privileged gate independent → G5.3 · blocked
(residual: unprivileged auto-approve, by design)]
├─ 4.4 Tamper hosts.json to weaken the gate
│ [enforced owner/mode check / F4; privileged gate independent → G5.3 · blocked
│ (residual: unprivileged auto-approve, by design)]
└─ 4.5 Use `--pkexec` delegation to run a multi-step plan behind single-step
dialogs (or none, under `pkexec-cache`)
[single-leaf delegation → G5.4 / #88 · blocked (residual: dialog names
`/usr/bin/env` and omits env / exit codes; `pkexec-cache` documented as unsafe)]
```

## Coverage and residuals
Expand Down Expand Up @@ -195,6 +199,12 @@ is unaccounted for. The residuals — already on record and accepted — are:
it. It is tamper-evident against other users, not against the requester. The
syslog copy, held by the system logger, is the stronger record; ship it off
the host for a record the requester cannot reach.
- **4.5 — `--pkexec` delegation (#88, narrowed).** Only a `privileged: true`
request that is one step with no redirection is delegated to pkexec's dialog;
every other privileged plan gets the TUI prompt and sudo. The dialog still
names `/usr/bin/env`, shows the working directory only as `env -C`, and omits
plan `setenv`, request env and accepted exit codes; `pkexec-cache` (opt-in,
documented as unsafe) removes the dialog altogether.

These residuals were the inputs to **Rung 4**, now discharged
([roadmap](formalisation-roadmap.md#the-rigor-ladder)): the policy-transition
Expand Down
2 changes: 1 addition & 1 deletion src/bin/sudo-proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ fn parse_args(args: &[String]) -> Opts {
eprintln!("Options:");
eprintln!(" --socket PATH Socket path (default: $XDG_RUNTIME_DIR/sudo-proxy.sock)");
eprintln!(" --host HOST Connect to remote host via SSH tunnel");
eprintln!(" --pkexec Use pkexec directly (no TUI prompt, pkexec handles both auth and approval)");
eprintln!(" --pkexec Delegate approval of single-step, unredirected privileged requests to pkexec's dialog (no TUI prompt); other privileged plans still get the TUI prompt and sudo");
eprintln!(" --verbose, -v Print startup info and log each request to stderr");
eprintln!(" --log-json Log each request's plan as pretty-printed JSON to stderr");
eprintln!(" --unattended-eligible Allow a human to grant unattended unprivileged execution");
Expand Down
79 changes: 71 additions & 8 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use std::thread;
use std::time::{Duration, Instant};

use crate::audit::{AuditConfig, AuditLog, Event, Outcome, Reject};
use crate::executor::{exec_direct, exec_pkexec, exec_sudo, sanitize_env};
use crate::executor::{exec_direct, exec_pkexec, exec_sudo, sanitize_env, LeafPrivilege, LeafView};
use crate::mode::Mode;
use crate::protocol::{Request, Response, ValidatedRequest};
use crate::tui::{self, Prompter, ResultSink};
Expand Down Expand Up @@ -656,6 +656,25 @@ fn escape_for_terminal(s: &str) -> String {
out
}

/// `--pkexec` delegates approval to pkexec's dialog only when that dialog
/// shows one escalated argv with no redirection: privileged as a whole, one
/// leaf, no redirects. Everything else takes the TUI prompt and sudo.
///
/// `req_privileged` is the request's raw `privileged` flag, not
/// `effective_privileged()`: a plan escalating only through `run-as` may carry
/// unescalated leaves that pkexec never shows, so it must not delegate.
fn delegate_to_pkexec(
pkexec_only: bool,
mode: Mode,
req_privileged: bool,
views: &[LeafView],
) -> bool {
pkexec_only
&& mode == Mode::Local
&& req_privileged
&& matches!(views, [v] if v.redirects.is_empty() && v.privilege != LeafPrivilege::Direct)
}

#[allow(clippy::too_many_arguments)]
fn handle_connection(
mut stream: UnixStream,
Expand Down Expand Up @@ -921,13 +940,15 @@ fn handle_connection(
);
}

// --pkexec hands approval to pkexec's own dialog, which shows only one
// escalated leaf's argv. That is sound only for a request that is
// privileged as a whole (every leaf escalates, so every leaf raises a
// dialog). A request that is privileged only through `run-as` nodes may
// carry unescalated leaves that pkexec never sees, so it takes the TUI
// prompt (and sudo) like any other privileged plan.
let use_pkexec = pkexec_only && mode == Mode::Local && req.privileged;
// --pkexec hands approval to pkexec's own dialog, which shows a single
// escalated argv (as `env -C DIR -- BIN args`) and no redirection. So it
// delegates only a request that is `privileged: true`, compiles to exactly
// one leaf, and has no redirection on it (the daemon opens redirected
// files itself; the dialog never names them). Everything else — a
// multi-step plan, a redirected step, or a plan privileged only through
// `run-as` — takes the TUI prompt and runs through sudo. The predicate
// reads the same `views` the prompt renders.
let use_pkexec = delegate_to_pkexec(pkexec_only, mode, req.privileged, &views);

let (resp, outcome) = if effective_privileged {
if use_pkexec {
Expand Down Expand Up @@ -1113,6 +1134,48 @@ mod tests {
use crate::prop::Rng;
use std::sync::{Arc, Mutex};

fn leaf_view(privilege: LeafPrivilege, redirects: &str) -> LeafView {
LeafView {
stage_id: 0,
argv: vec!["id".into()],
privilege,
resolved_bin: None,
opaque: false,
redirects: redirects.into(),
in_pipe: false,
}
}

#[test]
fn delegate_to_pkexec_only_for_a_single_plain_leaf() {
let root = || leaf_view(LeafPrivilege::Root, "");
let nobody = || leaf_view(LeafPrivilege::User("nobody".into()), "");
let d = |views: &[LeafView]| delegate_to_pkexec(true, Mode::Local, true, views);

// The only shape that delegates: one escalated leaf, no redirection.
assert!(d(&[root()]));
assert!(d(&[nobody()]));

// More or fewer than one leaf.
assert!(!d(&[root(), root()]));
assert!(!d(&[root(), nobody()]));
assert!(!d(&[]));

// A redirected single leaf: the dialog would not show the file.
assert!(!d(&[leaf_view(LeafPrivilege::Root, "> /tmp/x")]));
assert!(!d(&[leaf_view(LeafPrivilege::Root, "< /etc/hosts")]));
assert!(!d(&[leaf_view(LeafPrivilege::Root, "2>&1")]));

// Defensive: an unescalated leaf never delegates.
assert!(!d(&[leaf_view(LeafPrivilege::Direct, "")]));

// The other conjuncts.
assert!(!delegate_to_pkexec(false, Mode::Local, true, &[root()]));
assert!(!delegate_to_pkexec(true, Mode::Remote, true, &[root()]));
// privileged: false (e.g. a run-as-only plan) never delegates.
assert!(!delegate_to_pkexec(true, Mode::Local, false, &[nobody()]));
}

/// `--log-json` prints request bytes before validation, on the approval
/// terminal: escape, C1, DEL and bidi characters must come out inert.
#[test]
Expand Down
8 changes: 5 additions & 3 deletions tests/common/pty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
//! `ICANON` cleared before writing the key.
//!
//! The daemon runs with a cleared environment: no `DISPLAY`/`WAYLAND_DISPLAY`
//! (so `Mode::Remote`: TUI prompt + sudo), a private `HOME`/`XDG_CONFIG_HOME`
//! (so `Mode::Remote`: TUI prompt + sudo) unless `PtyOpts::env` sets one, a
//! private `HOME`/`XDG_CONFIG_HOME`
//! (no developer `hosts.json` policy leaks in), and `tests/shims` first on
//! `PATH`, so privileged steps reach the logging `sudo` shim, not real sudo.

Expand Down Expand Up @@ -52,8 +53,9 @@ pub struct PtyOpts {
/// Directories put first on the daemon's own PATH (before the shims), as
/// a dev shell would. Requested commands must not be resolved on it.
pub extra_path: Vec<PathBuf>,
/// Extra environment for the daemon, on top of the cleared base (e.g.
/// `TERM=tmux-256color` to look like an injectable terminal).
/// Extra environment for the daemon, set after `env_clear` and the
/// harness's own (e.g. `TERM=tmux-256color` to look like an injectable
/// terminal, or `DISPLAY` so `Mode::detect` returns `Local`).
pub env: Vec<(String, String)>,
}

Expand Down
91 changes: 91 additions & 0 deletions tests/plan_exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -380,3 +380,94 @@ fn pkexec_mode_still_prompts_for_run_as_plans() {
assert_eq!(resp.status, Status::Denied, "got {resp:?}");
assert!(!marker.exists(), "an unescalated step ran without approval");
}

/// `--pkexec` delegates to pkexec's dialog only a `privileged: true` request
/// that compiles to one leaf with no redirection: the dialog shows one argv
/// and never the files the daemon opens for a redirect. Every other privileged
/// shape — several leaves, or a redirected single leaf — must reach the TUI
/// prompt (#88).
///
/// Safety: every argv[0] is a nonexistent program. If the gate regresses and a
/// request reaches `exec_pkexec`, `check_pkexec_leaves` spawns its harmless
/// `env -C / -- true` probe once, then `build_command` fails with "command not
/// found" before any real pkexec runs the test argv: the response is an error,
/// the audit outcome is `pkexec`, the prompt count does not move, and no
/// polkit dialog ever names the test program.
#[test]
fn pkexec_mode_prompts_for_multi_leaf_privileged_plans() {
const NO_SUCH: &str = "sudo-proxy-test-88-no-such-cmd";
let server = common::start_test_server(common::TestServerOpts {
pkexec_only: true,
..Default::default()
});
server.prompter.set_response(|_| {
(
std::time::Duration::ZERO,
sudo_proxy::tui::PromptResult::Denied,
)
});
let dir = tempfile::tempdir_in("/tmp").expect("tempdir");
let target = dir.path().join("redirected");
let leaf = |n: &str| exec(&[NO_SUCH, n]);
let two = || vec![leaf("1"), leaf("2")];

let shapes: Vec<(&str, Plan)> = vec![
("run", Plan::Run { steps: two() }),
("seq", Plan::Seq { steps: two() }),
("alt", Plan::Alt { steps: two() }),
("pipe", Plan::Pipe { stages: two() }),
(
"redirect",
Plan::Redirect {
stream: Stream::Stdout,
target: RedirTarget::File {
path: target.to_string_lossy().into_owned(),
mode: WriteMode::Truncate,
},
body: Box::new(leaf("1")),
},
),
(
"with-stdin-from",
Plan::WithStdinFrom {
path: "/dev/null".into(),
body: Box::new(leaf("1")),
},
),
];

for (i, (name, plan)) in shapes.iter().enumerate() {
let mut req = Request::new_plan(
String::new(),
"test".into(),
plan.clone(),
HashMap::new(),
String::new(),
true,
false,
);
req.id = format!("pkexec-88-{name}");
let before = server.prompter.call_count();
let resp = server.send(&req);
assert_eq!(
server.prompter.call_count(),
before + 1,
"{name}: the TUI prompt was skipped"
);
assert_eq!(resp.status, Status::Denied, "{name}: got {resp:?}");
let rec = server.audit_for(&req.id);
assert_eq!(rec["outcome"], "denied", "{name}: {rec}");
assert_eq!(server.audit_records().len(), i + 1, "{name}: record count");
}
assert!(
!target.exists(),
"a redirect target was opened without approval"
);

let records = server.audit_records();
assert_eq!(records.len(), shapes.len());
assert!(
records.iter().all(|r| r["outcome"] != "pkexec"),
"a request was delegated to pkexec: {records:?}"
);
}
Loading
Loading