From b05330e48061eea0d1188304547f88b60e4b3e73 Mon Sep 17 00:00:00 2001 From: Edimar Cardoso Date: Fri, 13 Nov 2026 14:44:57 -0300 Subject: [PATCH 1/5] broker: confirm policy refuses completion and history recall Under --policy confirm only the first Enter an agent types is held; every byte before it reached the shell at once. Tab therefore ran shell completion in the person's unconfined shell, and bash-completion runs project files to complete (./configure --help, make -npq evaluating $(shell ...)), so an agent that wrote such a file got code execution with no approval (review COT-1). Up and Down recalled commands typed in private mode onto the screen, where the agent could read them (COT-3). The allowed keys are now decided per key from the default readline and zle bindings (emacs and vi mode), with the reasoning in keys.go: Tab, BTab, Up, Down, PgUp and PgDn are refused; text may no longer hold tabs, history expansion (! and ^, which magic-space expands without an Enter and which change the line that runs after approval) or, outside a UTF-8 locale, bytes above 0x7f (readline's convert-meta reads them as Meta keys, and M-C-e runs command substitutions). Private mode cannot keep a line out of every shell's history, and under the auto policy an agent can always run `history`; README and docs/broker.md now state that where private mode is described, with the shells the confirm refusals cover. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++++ README.md | 9 +++- docs/broker.md | 54 ++++++++++++++++++++ docs/mcp.md | 4 +- docs/protocol.md | 2 +- docs/security.md | 18 ++++--- internal/broker/broker.go | 21 +++++--- internal/broker/keys.go | 95 +++++++++++++++++++++++++++++++++--- internal/broker/unit_test.go | 55 +++++++++++++++++++-- internal/mcp/format.go | 3 +- internal/mcp/tools.go | 3 +- 11 files changed, 243 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 113bfb4..f593a1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ ## Unreleased +- Confirm policy: agents may no longer press Tab or BTab (completion ran + project files such as `./configure --help` and Makefile `$(shell ...)` + in your shell before any approval), Up, Down, PgUp or PgDn (they + recalled commands typed in private mode), nor type tabs, history + expansion (`!`, `^`) or, outside a UTF-8 locale, bytes above 0x7f + (Meta keys for readline). Left: text, held Enter, Backspace, Delete, + Space, Left, Right, Home, End and C-c (docs/broker.md, Confirm policy). +- Docs: private mode does not keep a command out of the shell's history; + README and docs/broker.md say so where private mode is described. - The pts exception list lapses with cotty-guard's daemon: a clean stop empties it in the kernel, and the programs stop honouring it once the daemon's heartbeat is 90 s old, so a listed pinentry is refused while diff --git a/README.md b/README.md index 2a3173f..5ca6114 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,14 @@ channels are opt-in. `cat ~/.config/x/token` prints a secret cotty does not know about. - Not a guard for secrets typed with echo on. `export TOKEN=...` is visible to the agent unless you turned on private mode first or the value is on - the masking list. + the masking list. Private mode hides the rows, not the shell's history: + once it is off, an agent can draw the command again (Up, `history`, + `!!`, a zsh autosuggestion) and read it. Under `--policy confirm` the + keys and characters that recall history are refused to agents in bash + and zsh; under the default policy nothing stops it. Start such a command + with a space and have the shell skip it (bash + `HISTCONTROL=ignorespace`, zsh `setopt HIST_IGNORE_SPACE`), or put the + value on the masking list. - Not a defence against a malicious kernel or root. - Not a network filter. A confined agent can reach any TCP or UDP service you can, including services on localhost. diff --git a/docs/broker.md b/docs/broker.md index 62bde12..2568ab1 100644 --- a/docs/broker.md +++ b/docs/broker.md @@ -32,6 +32,41 @@ for a running session (and closes the weak agents already connected); `--require-confined=false` turns it off; plain `cotty share` keeps the setting. +## Confirm policy + +`--policy confirm` holds every Enter an agent types until you accept the +line (`^] y`) or reject it (`^] n`). What the agent types before the Enter +reaches the shell at once, so under this policy agents are refused +(`policy_denied`) every key and character that makes the line editor act +on its own: + +- Tab and BTab. Completion runs programs: bash-completion runs + `./configure --help` to list its options and `make -npq`, which + evaluates `$(shell ...)` in a Makefile, and zsh's completion does the + same. A file the agent wrote in the project would run with your rights + before you were asked anything. +- Up, Down, PgUp and PgDn: they recall the shell's history, commands + typed in private mode included (see Private mode below). +- Esc, Insert, F1 to F12 and every Ctrl and Meta key except C-c: among + them C-p, C-r, M-. and M-< recall history, and C-x C-e, M-C-e + (shell-expand-line) and C-o run or submit the line. +- In text: tabs, control characters other than Enter, Backspace and C-c, + escape sequences, history expansion (`!` followed by anything but a + blank, `=` or `(`, and `^`), and, when the shell's locale is not UTF-8, + bytes above 0x7f. Space bound to magic-space (oh-my-zsh does that) + expands `!!` or `^old^new` on the screen without an Enter, and after an + Enter the expanded line, not the one you approved, would run. In a C or + POSIX locale readline reads bytes above 0x7f as Meta keys, and M-C-e + runs the command substitutions of the line. + +Left are text, Enter (held), Backspace, Delete, Space, Left, Right, Home, +End and C-c. These decisions follow the default bindings of bash +(readline) and zsh (zle), in emacs and vi mode. A binding of your own that +makes one of the keys left run something (a widget on Space or End) is not +known to cotty, and neither is readline's `convert-meta` turned on in a +UTF-8 locale. Under the default policy (`auto`) an agent types and runs +whatever it wants. + ## The session's shell The shell runs with `HISTFILE` set to @@ -94,6 +129,25 @@ Hotkeys: `Ctrl-]` then | ? | help | | Ctrl-] | send a literal Ctrl-] | +## Private mode + +`^] p` turns private mode on: agent input is refused with +`private_mode`, and what agents read is frozen at the moment it started; +rows written meanwhile read `[private]` afterwards. Private mode hides +rows, not what the shell keeps. A command line you type in private mode +stays in the shell's history, and once private mode is off an agent can +draw it on the screen again and read it: with Up or `!!`, with `history` +or `fc -l`, or through a zsh autosuggestion that shows history while it +types. Under `--policy confirm` the history keys and history expansion +are refused to agents (Confirm policy above), which covers bash and zsh +with their default bindings, but a `history` you approve still prints the +line, and autosuggestions still show it. Under the default policy nothing +stops it. cotty cannot keep a line out of every shell's history, so for a +secret typed with echo on: start the command with a space and set +`HISTCONTROL=ignorespace` (bash) or `setopt HIST_IGNORE_SPACE` (zsh, which +still keeps the line until the next command runs: run any command right +after it), or put the value on the masking list (`cotty secrets add`). + ## The lock A secret prompt is ECHO off with ICANON on in the PTY's termios (sudo, su, diff --git a/docs/mcp.md b/docs/mcp.md index 13af34a..7ff94e2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -153,7 +153,9 @@ error. The result ends with the bottom 20 rows of the screen. asterisks) reads `[private]` afterwards. - Private mode hides rows, not what programs keep: after it ends, shell history, a redraw or a pager can print the text again as ordinary - output (docs/security.md, Known limits). + output (docs/broker.md, Private mode; docs/security.md, Known limits). + Under the confirm policy agents cannot press Up, Down or Tab, nor type + history expansion. - Before a read the broker waits for the output to pause (80 ms quiet, at most 400 ms) so a value is not caught half printed. This is best effort: a value that arrives in pieces more than 80 ms apart can show diff --git a/docs/protocol.md b/docs/protocol.md index 90ae3b0..06a6db1 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -492,7 +492,7 @@ Agent `type` and `keys` are refused, with these codes, in this order: | `keyboard_held` | the person holds the keyboard | | `person_typing` | the person typed in the last 1.5 s; `retry_after_ms` set | | `confirmation_pending` | an agent line waits for the person's answer | -| `policy_denied` | under the confirm policy: control characters other than Enter, Tab, Backspace and C-c, or escape sequences in `text` | +| `policy_denied` | under the confirm policy: keys other than Enter, Backspace, Delete, Space, Left, Right, Home, End and C-c; in `text`, tabs, control characters other than Enter, Backspace and C-c, escape sequences, history expansion (`!` not followed by a blank, `=` or `(`, and `^`) and, when the shell's locale is not UTF-8, bytes above 0x7f (broker.md, Confirm policy) | Under the confirm policy the text before an Enter is typed, the Enter is held and the person sees "agent wants to run: LINE" (or, when the line diff --git a/docs/security.md b/docs/security.md index 8864145..2b9c6c1 100644 --- a/docs/security.md +++ b/docs/security.md @@ -358,12 +358,18 @@ item says what can happen and what to do meanwhile. ### Private mode and reads - Private mode hides rows, not what programs keep. After it ends, the - shell's history (Up arrow), a redraw (`C-l` in a full screen program - that kept the text) or a pager's buffer can draw the text again, now - as ordinary output the agent reads. Start commands typed in private - mode with a space and set `HISTCONTROL=ignorespace` (bash) or - `setopt HIST_IGNORE_SPACE` (zsh), and leave pagers and editors that - showed private text before turning private mode off. + shell's history (Up arrow, `history`, `!!`, zsh autosuggestions), a + redraw (`C-l` in a full screen program that kept the text) or a pager's + buffer can draw the text again, now as ordinary output the agent reads. + Under `--policy confirm` agents cannot press Up, Down, PgUp, PgDn or any + Ctrl or Meta key but C-c, nor type history expansion (`!`, `^`), which + closes the recall keys of bash and zsh with their default bindings; an + approved `history` and autosuggestions still show the line, and under + the default policy nothing stops it (broker.md, Private mode). Start + commands typed in private mode with a space and set + `HISTCONTROL=ignorespace` (bash) or `setopt HIST_IGNORE_SPACE` (zsh, + then run one more command), and leave pagers and editors that showed + private text before turning private mode off. - `cursor_since` stops during private mode and jumps when it ends; the jump tells how many lines scrolled meanwhile (not what they held). - `sudo-rs` (the default `sudo` on Ubuntu 26.04) and `sudo` with diff --git a/internal/broker/broker.go b/internal/broker/broker.go index 54b18f6..7e6f5f2 100644 --- a/internal/broker/broker.go +++ b/internal/broker/broker.go @@ -116,11 +116,15 @@ type Broker struct { model *Model logf func(string, ...any) - ptmx *os.File - cmd *exec.Cmd - ptsPath string - ptsRdev uint64 - ln *net.UnixListener + ptmx *os.File + cmd *exec.Cmd + // shellUTF8: the shell's environment selects a UTF-8 locale, so its + // line editor reads bytes above 0x7f as characters, not Meta keys + // (confirmTextOK). Set before the session serves anybody. + shellUTF8 bool + ptsPath string + ptsRdev uint64 + ln *net.UnixListener // agentLn serves the agent endpoint (paths.AgentSocket) while the // session is shared; nil otherwise. Guarded by mu. agentLn *net.UnixListener @@ -422,6 +426,7 @@ func (b *Broker) startShell() error { _ = tty.Close() b.mu.Lock() b.ptmx, b.cmd = ptmx, cmd + b.shellUTF8 = localeIsUTF8(env) b.mu.Unlock() b.classifier.ShellPID = cmd.Process.Pid b.classifier.ShellSID = cmd.Process.Pid // the shell leads its session (Setsid) @@ -1350,8 +1355,10 @@ func (b *Broker) agentType(c *conn, text string, enter bool, keys []string) (pro if len(text) > maxAgentText { return deny(proto.Errorf(proto.ErrBadRequest, "text longer than %d bytes", maxAgentText)) } - if confirm && !confirmTextOK(text) { - return deny(proto.Errorf(proto.ErrPolicyDenied, "control characters and escape sequences are not allowed under the confirm policy")) + if confirm && !confirmTextOK(text, b.shellUTF8) { + return deny(proto.Errorf(proto.ErrPolicyDenied, "under the confirm policy agent text may not hold tabs (completion runs programs), "+ + "control characters, escape sequences, history expansion (! followed by anything but a blank, = or (, and ^) "+ + "or, outside a UTF-8 locale, bytes above 0x7f")) } seq = []byte(text) if enter { diff --git a/internal/broker/keys.go b/internal/broker/keys.go index 4e5ac1d..d39c855 100644 --- a/internal/broker/keys.go +++ b/internal/broker/keys.go @@ -87,25 +87,104 @@ var fKeys = map[string]string{ } // confirmKeys are the keys an agent may send under the confirm policy: -// nothing that can submit a line without the person seeing it. +// nothing that can submit a line, run a program or draw earlier commands +// without the person seeing it first. The decision per key follows what +// GNU readline (bash) and zle (zsh) do with the bytes by default, in the +// emacs and the vi keymaps (review COT-1, COT-3): +// +// - Enter is held for the person's answer (agentType). +// - Backspace (DEL), Delete (CSI 3 ~), Left, Right, Home, End only edit +// or move within the line. A sequence a shell does not bind (zsh's +// emacs keymap leaves Delete unbound) beeps or inserts its last +// character; in vi mode its ESC switches to the command keymap, where +// none of the remaining bytes ([, digits, ~, A to H, O) accepts the +// line or runs anything. +// - Space inserts a blank. Where it is bound to magic-space (oh-my-zsh +// does that) it expands history references already on the line; the +// characters that start one are refused in text (confirmTextOK). +// - C-c interrupts; it never runs anything. +// +// Refused, although they do not submit a line: +// +// - Tab and BTab: completion runs programs and files the agent may have +// written (bash-completion runs `./configure --help` for options and +// `make -npq`, which evaluates $(shell ...) in a Makefile; zsh's +// _configure and _make do the same) in the person's unconfined shell. +// - Up, Down, PgUp, PgDn: they recall the shell's history onto the +// screen, including commands typed in private mode. +// - Esc, Insert, F-keys, every C- and M- key: M-., M-_, M-p, M-<, C-p, +// C-r recall history; C-x C-e, M-C-e (shell-expand-line) and C-o run +// or submit something; M-?, M-*, M-/ and C-x * complete or expand. var confirmKeys = map[string]bool{ - "Enter": true, "Tab": true, "Backspace": true, "Delete": true, "Space": true, - "Left": true, "Right": true, "Up": true, "Down": true, "Home": true, "End": true, + "Enter": true, "Backspace": true, "Delete": true, "Space": true, + "Left": true, "Right": true, "Home": true, "End": true, "C-c": true, } // confirmTextOK reports whether agent text is allowed under the confirm -// policy: printable characters, tab, backspace, C-c and Enter only. Other -// control characters (C-o, C-j variants, C-x C-e) and escape sequences -// could submit or edit a line in ways the person does not see coming. -func confirmTextOK(s string) bool { +// policy: printable characters, backspace, C-c and Enter only. Refused: +// +// - Tab (completion runs programs, see confirmKeys) and every other +// control character and escape sequence (C-o, C-x C-e, Meta +// sequences), which could submit or edit a line in ways the person +// does not see coming; +// - history expansion: a '!' that starts a history reference in bash and +// zsh (any '!' not followed by a blank, '=' or '('; a '!' at the end +// of the text too, as the next text may complete it) and '^' (quick +// substitution, ^old^new): with Space bound to magic-space they draw +// earlier commands, private ones included, on the screen without an +// Enter, and after an Enter the line that runs is not the line the +// person approved; +// - bytes with the eighth bit set unless the shell's locale is UTF-8 +// (utf8): with readline's convert-meta, on by default in 8-bit +// locales such as C or POSIX, each such byte is a Meta key, and +// M-C-e (0x85) runs the command substitutions of the line. +func confirmTextOK(s string, utf8 bool) bool { for i := 0; i < len(s); i++ { c := s[i] switch { - case c == '\t' || c == '\r' || c == '\n' || c == 0x7f || c == 0x08 || c == 0x03: + case c == '\r' || c == '\n' || c == 0x7f || c == 0x08 || c == 0x03: case c < 0x20: return false + case c == '^': + return false + case c == '!': + if i+1 == len(s) { + return false + } + switch s[i+1] { + case ' ', '\t', '\r', '\n', '=', '(': + default: + return false + } + case c >= 0x80 && !utf8: + return false } } return true } + +// localeIsUTF8 reports whether an environment selects a UTF-8 character +// set for the shell (LC_ALL, then LC_CTYPE, then LANG, as setlocale reads +// them). Readline then leaves convert-meta off and reads bytes with the +// eighth bit set as characters, not as Meta keys. +func localeIsUTF8(env []string) bool { + get := func(k string) string { + v := "" + for _, e := range env { + if rest, ok := strings.CutPrefix(e, k+"="); ok { + v = rest + } + } + return v + } + v := get("LC_ALL") + if v == "" { + v = get("LC_CTYPE") + } + if v == "" { + v = get("LANG") + } + v = strings.ToLower(v) + return strings.Contains(v, "utf-8") || strings.Contains(v, "utf8") +} diff --git a/internal/broker/unit_test.go b/internal/broker/unit_test.go index 8adfe14..a3e235c 100644 --- a/internal/broker/unit_test.go +++ b/internal/broker/unit_test.go @@ -52,14 +52,61 @@ func TestKeys(t *testing.T) { } func TestConfirmText(t *testing.T) { - if !confirmTextOK("ls -la\r") || !confirmTextOK("x\x7f\t") { - t.Error("plain text refused") + for _, s := range []string{"ls -la\r", "x\x7f", "git commit -m 'café'", "[ $a != b ]", "if ! true; then :; fi", "echo $((1 + 2))"} { + if !confirmTextOK(s, true) { + t.Errorf("%q refused under confirm", s) + } } - for _, s := range []string{"\x0f", "\x1b[A", "a\x18\x05"} { - if confirmTextOK(s) { + for _, s := range []string{"\x0f", "\x1b[A", "a\x18\x05", + // Completion runs programs the agent may have written (COT-1). + "./configure --\t", "make \t", + // History expansion draws earlier commands, private ones too (COT-3). + "echo !!", "!-1 ", "echo !?TOKEN?", "!$", "echo hi!", "^e^e ", "x^y", + } { + if confirmTextOK(s, true) { t.Errorf("%q allowed under confirm", s) } } + // Outside a UTF-8 locale readline's convert-meta reads 0x85 as M-C-e + // (shell-expand-line, which runs command substitutions). + if confirmTextOK("$(touch x)\u00c5", false) || !confirmTextOK("$(touch x)\u00c5", true) { + t.Error("eighth-bit bytes: wrong decision for the locale") + } +} + +func TestConfirmKeys(t *testing.T) { + // COT-1, COT-3: completion and history recall are not sent without + // approval. + for _, k := range []string{"Tab", "BTab", "Up", "Down", "PgUp", "PgDn", "Esc", "M-.", "M-_", "C-p", "C-r", "C-x", "C-e", "M-?", "F1"} { + if confirmKeys[k] { + t.Errorf("%s allowed under confirm", k) + } + } + for _, k := range []string{"Enter", "Backspace", "Delete", "Space", "Left", "Right", "Home", "End", "C-c"} { + if !confirmKeys[k] { + t.Errorf("%s refused under confirm", k) + } + } +} + +func TestLocaleIsUTF8(t *testing.T) { + cases := []struct { + env []string + want bool + }{ + {[]string{"LANG=en_US.UTF-8"}, true}, + {[]string{"LANG=C.utf8"}, true}, + {[]string{"LANG=C"}, false}, + {nil, false}, + {[]string{"LANG=en_US.UTF-8", "LC_ALL=C"}, false}, + {[]string{"LANG=C", "LC_CTYPE=pt_BR.UTF-8"}, true}, + {[]string{"LC_ALL=pt_BR.UTF-8", "LC_CTYPE=C"}, true}, + } + for _, c := range cases { + if got := localeIsUTF8(c.env); got != c.want { + t.Errorf("%v: %v", c.env, got) + } + } } func TestCodes(t *testing.T) { diff --git a/internal/mcp/format.go b/internal/mcp/format.go index 6cdd638..65d6d88 100644 --- a/internal/mcp/format.go +++ b/internal/mcp/format.go @@ -18,7 +18,8 @@ var hints = map[string]string{ proto.ErrPersonTyping: "The person is typing right now. Wait until retry_after_ms passes and try again; never type over them.", proto.ErrConfirmationPending: "Your previous line waits for the person's approval (confirm policy). " + "Call term_wait with for=confirmation, then read the screen.", - proto.ErrPolicyDenied: "This session uses the confirm policy: send plain text, and only the keys Enter, Tab, Backspace and C-c.", + proto.ErrPolicyDenied: "This session uses the confirm policy: send plain text without tabs or history expansion (! and ^), " + + "and only the keys Enter, Backspace, Delete, Space, Left, Right, Home, End and C-c. Type whole commands; do not complete them with Tab.", proto.ErrNotShared: "The person has not shared this session with agents. Ask them to run `cotty share SESSION`, " + "or to start a shared session with `cotty new --ai`.", proto.ErrSessionEnded: "The session ended or closed this connection. Call term_sessions to see what is shared now.", diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go index aff2cb5..4c87236 100644 --- a/internal/mcp/tools.go +++ b/internal/mcp/tools.go @@ -91,7 +91,8 @@ func toolList() []tool { Description: "Press named keys in the shared terminal, in order: Enter, Tab, BTab, Esc, Backspace, Delete, Insert, Home, End, PgUp, PgDn, " + "Up, Down, Left, Right, F1 to F12, Space, C-a to C-z (C-c interrupts, C-d ends input), C-@, C-[, C-\\, C-], C-^, C-_, M-. " + "Use it for menus, editors, pagers and to interrupt a command. " + refusals + - " Under the confirm policy only Enter, Tab, Backspace and C-c are allowed.", + " Under the confirm policy only Enter, Backspace, Delete, Space, Left, Right, Home, End and C-c are allowed " + + "(Tab completion runs programs, and Up and Down recall history).", InputSchema: obj(map[string]any{ "keys": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "key names, 1 to 64"}, "session": str(sessionDesc), From d074af06f5d0799933a2d3fff45ca81d21c8a5b3 Mon Sep 17 00:00:00 2001 From: Edimar Cardoso Date: Fri, 13 Nov 2026 14:49:25 -0300 Subject: [PATCH 2/5] peer: assurance rests on a confinement the cotty binary built agentAssurance reported an agent `confined` for being in another user or pid namespace, or in a cgroup named cotty-agent*, and `strong` once the guard also had a tag for it. Any process can give itself all three (`unshare -U`, a cgroup in its delegated subtree, the guard's tag-self), so an unconfined agent could pass --require-confined and hide the person's red warning (review COT-2). The broker now checks what a process cannot give itself: pid 1 of the peer's pid namespace must be the broker's own root-owned cotty binary running cotty agent's init stage, and the peer must be in that namespace's user namespace and mount view (a process that entered the namespaces from outside is not), with no_new_privs and, where cotty has a seccomp filter, one in place. Everything that cannot be verified is weak: an invisible pid, unreadable /proc entries, a user-writable cotty binary. A guard tag only lifts a verified agent to strong; a self-tag never raises the level, so tag-self can stay open to everyone. The docs say what the level still cannot tell: it describes the MCP server process that connects, and a program that already has all of the person's rights can start a confined MCP server for itself. The broker matrix gains rows for unshare and tag-self forgeries. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++ README.md | 10 +- docs/PLAN.md | 9 +- docs/broker.md | 8 +- docs/confinement.md | 5 +- docs/guard.md | 2 +- docs/protocol.md | 20 +++- docs/security.md | 29 +++++- internal/broker/broker.go | 2 + internal/confine/stage_test.go | 15 +++ internal/peer/classify.go | 28 +++--- internal/peer/launch.go | 153 +++++++++++++++++++++++++++++++ internal/peer/launch_test.go | 147 +++++++++++++++++++++++++++++ internal/peer/peer_test.go | 41 +++++---- tests/attacks/broker.sh | 11 +++ tests/attacks/guardprobe/main.go | 23 +++++ 16 files changed, 465 insertions(+), 47 deletions(-) create mode 100644 internal/confine/stage_test.go create mode 100644 internal/peer/launch.go create mode 100644 internal/peer/launch_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index f593a1b..b607c88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ ## Unreleased +- Assurance: an agent is `confined` only when the broker sees that the + trusted cotty binary built its confinement (pid 1 of its pid namespace + runs cotty agent's init stage, and the agent is in that namespace's + user namespace and mount view with no_new_privs and seccomp). Its own + user namespace (`unshare -U`), a `cotty-agent*` cgroup or a guard tag + no longer raise the level, so they no longer pass `--require-confined` + or hide the red warning. Agents under the guard without layer 2, peers + whose pid the broker cannot see, and every agent while the cotty binary + is writable by the user now read `weak`. - Confirm policy: agents may no longer press Tab or BTab (completion ran project files such as `./configure --help` and Makefile `$(shell ...)` in your shell before any approval), Up, Down, PgUp or PgDn (they diff --git a/README.md b/README.md index 5ca6114..0937934 100644 --- a/README.md +++ b/README.md @@ -70,11 +70,15 @@ weakest one in the status line: | Level | Meaning | | --- | --- | | `strong` | the guard is loaded and confirms the session pts protection, and the agent runs under `cotty agent` and is tagged by the guard | -| `confined` | the agent runs under `cotty agent`, no guard (or the guard without `cotty agent`) | -| `weak` | no confinement evidence: an agent CLI started without `cotty agent`, or any other program of yours | +| `confined` | the agent runs under `cotty agent` (the broker checks that the agent's namespaces were built by the installed cotty binary), no guard | +| `weak` | no confinement evidence: an agent CLI started without `cotty agent`, a program in namespaces it made itself or tagged by the guard on its own request, or any other program of yours | | `insecure` | broker started with `--dev-insecure` (development only) | -What each level stops, case by case, is in docs/security.md. +The level describes the agent's MCP server, the process that connects to +the session. It keeps out agents that did not go through `cotty agent`; +it is not proof against a program that already runs with all your rights, +which can start a confined MCP server for itself. What each level stops, +case by case, is in docs/security.md. ## Requirements diff --git a/docs/PLAN.md b/docs/PLAN.md index b371347..1639c13 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -114,10 +114,11 @@ knows it reached the session's broker (docs/protocol.md section 7). The resulting assurance is reported, like basalt-shell's modes: `strong` (guard loaded, the session's pts protection confirmed by the guard, and -the agent tagged by it and under layer 2), `confined` (layer 2 active, no -guard; or the guard without layer 2), `weak` (agent not started through -`cotty agent`; the docs say what that means), `insecure` (development -only). +the agent tagged by it and under layer 2), `confined` (layer 2 active and +built by the trusted cotty binary, no guard), `weak` (agent not started +through `cotty agent`, including one under the guard without layer 2: a +tag or namespaces a process can give itself raise nothing; the docs say +what that means), `insecure` (development only). ## 4. Enforcement layers diff --git a/docs/broker.md b/docs/broker.md index 2568ab1..ed89625 100644 --- a/docs/broker.md +++ b/docs/broker.md @@ -23,7 +23,13 @@ attaching and prints the reattach code. `--require-confined` (off by default) refuses agent connections whose assurance is `weak`: agents started without `cotty agent`, or any program -of yours that speaks the protocol. They get `confinement_required`, the +of yours that speaks the protocol, including one in namespaces it made +itself (`unshare -U`) or tagged by the guard at its own request. The +broker accepts a confinement only when the trusted cotty binary built it +(docs/security.md, Assurance levels); a program that already has your +rights can still start a confined MCP server for itself, so this keeps +out agents that skipped `cotty agent`, not a program that is out to +deceive you. They get `confinement_required`, the audit log records the refusal and the status line counts it. Without the option such agents are accepted and the status line shows them in red ("1 unconfined agent"), so you always know when an agent could reach more diff --git a/docs/confinement.md b/docs/confinement.md index ad26ec1..e8157bd 100644 --- a/docs/confinement.md +++ b/docs/confinement.md @@ -405,7 +405,10 @@ included): `cotty agent` prints the level when it starts and passes it to the agent as `COTTY_ASSURANCE`. The broker's own assurance levels (`strong`, -`confined`, `weak`, `insecure`, PLAN section 3) build on this. +`confined`, `weak`, `insecure`, PLAN section 3) build on this: the broker +does not read `COTTY_ASSURANCE` (the agent could change it) but checks +that pid 1 of the agent's pid namespace is the trusted cotty binary +running the init stage (docs/security.md, Assurance levels). `cotty doctor` then names the level a session created now can reach: `strong available for new sessions (cotty-guard running)`, `confined diff --git a/docs/guard.md b/docs/guard.md index 15f930c..cfc682d 100644 --- a/docs/guard.md +++ b/docs/guard.md @@ -337,7 +337,7 @@ from `SO_PEERCRED` and `SO_PEERPIDFD` (Linux 6.5), never from the message: | Request | Who | What | | --- | --- | --- | | `register` (+ socket and directory fds) | a process that is not an agent, in a cgroup whose name starts with `cotty-agent` and which it owns (at most 1024 per user) | its own cgroup becomes an agent cgroup; the sockets go on that agent's allowlist; the directories are guarded, the last `guard` of them without connect rights | -| `tag-self` | anyone | the caller is tagged (it only restricts) | +| `tag-self` | anyone | the caller is tagged (it only restricts; the broker never counts a tag as confinement, so a self-tag cannot raise an agent's assurance) | | `protect-pts` (+ terminal fd, `O_PATH` is enough, and its master) | a registered broker that holds the terminal's master, when no other live process protects it (at most 1024 per user) | while the caller runs, the terminal opens only for the caller and for the processes whose controlling terminal it is, never for an agent | | `check-pts`, `release-pts` (+ terminal fd) | the process that protected it | whether the protection is in place for the caller; end it | | `register-broker` (+ session name, the runtime directory and its agent directory) | a broker: the installed cotty binary (root-owned, at a configured path, in root-owned directories, none writable by group or others) running `__broker` without `-dev-insecure`, not dumpable, not traced, not an agent; a session name no other live broker of the user holds (at most 256 per user) | the caller becomes the registered broker of that session name (by pid and start time, until it exits; the first registrant keeps the name); the directories (its user's, mode 0700) become cotty runtime directories | diff --git a/docs/protocol.md b/docs/protocol.md index 06a6db1..2333667 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -299,11 +299,21 @@ by the user (otherwise the person assurance is `weak`); on SELinux, SO_PEERSEC not an agent domain. Everything else is an agent. See `internal/peer` for the exact code. -Assurance, reported in hello and state: `strong` (guard loaded and the -agent tagged), `confined` (agent peer in its own namespaces or agent -cgroup), `weak` (no confinement evidence, or the cotty binary is writable -by the user), `insecure` (broker started with `--dev-insecure`; every -same-uid peer counts as a person; development only). +Assurance, reported in hello and state: `strong` (`confined`, and the +guard is loaded and has tagged the agent), `confined` (the agent runs in a +confinement the trusted cotty binary built: its pid namespace's pid 1 is +the broker's own root-owned binary running `cotty agent`'s init stage, it +is in that namespace's user namespace and mount view, and it has +no_new_privs and, where cotty has a filter for the architecture, a seccomp +filter), `weak` (anything else, including a peer whose pid the broker +cannot see, a peer in namespaces or a `cotty-agent*` cgroup it made +itself, a peer tagged by the guard without that confinement, or a cotty +binary writable by the user), `insecure` (broker started with +`--dev-insecure`; every same-uid peer counts as a person; development +only). The level describes the process that connected (the agent's MCP +server), not what talks to it over its stdio: a program that already has +all of the user's rights can start a confined MCP server for itself +(docs/security.md, Assurance levels). ## 7. Admission of person and control connections diff --git a/docs/security.md b/docs/security.md index 2b9c6c1..acc8e62 100644 --- a/docs/security.md +++ b/docs/security.md @@ -17,6 +17,30 @@ for the session, in the status line and in `term_read`'s state): | `strong` | the guard (`cotty-guard`, BPF LSM, layer 3) is loaded, the agent is tagged, and the guard confirms that the session's pts protection is in place (the broker asks every two seconds; while the guard does not answer the session is `confined`, and after a lapse of the protection it never returns to `strong`) | | `confined` | the agent runs under `cotty agent` (its own namespaces, Landlock, seccomp, own cgroup), no guard | | `weak` | no confinement evidence: an agent CLI started without `cotty agent`, or any other program of yours that speaks the protocol. It can do everything you can do as a program, outside cotty's view | + +How the broker tells `confined` from `weak` (review COT-2): only from +what a process cannot give itself. Its own user namespace (`unshare -U`), +a cgroup named `cotty-agent*` (the user can create one in the delegated +part of the cgroup tree) or a guard tag (any process may ask the guard to +tag itself; that only restricts it) count for nothing. The agent must run +in a pid namespace whose pid 1 is the broker's own cotty binary, which +must be root-owned and not writable by you, running the init stage of +`cotty agent`; it must be in that namespace's user namespace and in the +mount view the init stage built (a process that entered the namespaces +from outside is not), with no_new_privs and, on x86_64 and aarch64, a +seccomp filter. A peer the broker cannot check (its pid is not visible, +its /proc entries cannot be read) is `weak`. `strong` needs all of that +plus the guard's tag. + +What the level does not say: it describes the process that connected to +the session, which is the agent's MCP server (`cotty mcp`), not the agent +CLI behind its stdio. A program that already runs with all your rights +can start a confined MCP server for itself (`cotty agent -- cotty mcp`), +or hand the init stage a plan of its own, and is then reported +`confined` (`strong` with the guard). `--require-confined` keeps out +agents that did not go through `cotty agent` at all; it is not proof +against a program that has your rights already, which the guard limits +in the kernel (rows below) and only confinement from the start avoids. | `insecure` | broker started with `--dev-insecure` (development only) | A session that must never serve a `weak` agent is started (or shared) with @@ -536,8 +560,9 @@ are in the PR that added them and in `tests/attacks/results/`. directories (`node_modules`, `vendor`) or below its depth limit: a `git init` there is not reported. - The level `cotty agent` reports does not lower for weakening flags: a - run with `--allow-abstract-sockets` on Landlock ABI below 6, or any - `unshare -U` program, still reads `confined`; `--quiet` hides the + run with `--allow-abstract-sockets` on Landlock ABI below 6 still reads + `confined` (a program that only made its own namespaces with `unshare + -U` is `weak` to the broker since review COT-2); `--quiet` hides the security notes (a replaceable link, scan limits, "the cotty binary is in a directory the agent can write"). - Links inside a protected directory (`~/.claude/skills/x -> diff --git a/internal/broker/broker.go b/internal/broker/broker.go index 7e6f5f2..1f2b442 100644 --- a/internal/broker/broker.go +++ b/internal/broker/broker.go @@ -27,6 +27,7 @@ import ( "golang.org/x/sys/unix" "github.com/openbasalt/cotty/internal/audit" + "github.com/openbasalt/cotty/internal/confine" "github.com/openbasalt/cotty/internal/guard" "github.com/openbasalt/cotty/internal/peer" "github.com/openbasalt/cotty/internal/proto" @@ -312,6 +313,7 @@ func New(cfg Config) (*Broker, error) { b.codeLimits = map[codeLimitKey]*codeLimiter{} b.classifier = peer.Self() b.classifier.Guard = cfg.Guard + b.classifier.SeccompFilter = confine.SeccompSupported() b.classifier.Insecure = cfg.Insecure dir, name := cfg.Dir, cfg.Name b.classifier.OtherTTYs = func() []uint64 { return session.OtherTTYs(dir, name) } diff --git a/internal/confine/stage_test.go b/internal/confine/stage_test.go new file mode 100644 index 0000000..76e8e72 --- /dev/null +++ b/internal/confine/stage_test.go @@ -0,0 +1,15 @@ +package confine + +import ( + "testing" + + "github.com/openbasalt/cotty/internal/peer" +) + +// The broker recognises a confined agent by pid 1 of its namespace +// running the init stage (peer.verifyLaunch): the names must agree. +func TestInitStageName(t *testing.T) { + if StageInit != peer.InitStage { + t.Fatalf("confine.StageInit %q != peer.InitStage %q", StageInit, peer.InitStage) + } +} diff --git a/internal/peer/classify.go b/internal/peer/classify.go index ba05365..d168b88 100644 --- a/internal/peer/classify.go +++ b/internal/peer/classify.go @@ -55,6 +55,9 @@ type Classifier struct { Guard Guard Insecure bool AgentDomain func(typ string) bool + // SeccompFilter: `cotty agent` installs its seccomp filter on this + // system (confine.SeccompSupported), so a confined agent shows one. + SeccompFilter bool } // Verdict is the result of classifying one peer. @@ -203,21 +206,24 @@ func (c *Classifier) Classify(in Info) Verdict { } // agentAssurance tells how well an agent peer is kept away from what cotty -// hides. +// hides. Only a confinement the trusted cotty binary built counts +// (verifyLaunch); a guard tag adds layer 3 on top of it but never raises +// an agent on its own, since any process may ask the guard to tag itself +// (review COT-2). Anything that cannot be verified is weak. func (c *Classifier) agentAssurance(in Info, tag string) (string, string) { - // Layer 2 shows as other namespaces (or no visible pid at all). - layer2 := in.PID <= 0 || (in.UserNS != "" && in.UserNS != c.SelfUserNS) || (in.PidNS != "" && in.PidNS != c.SelfPidNS) + why := c.verifyLaunch(in) + loaded := c.Guard != nil && c.Guard.Loaded() switch { - case tag != "" && layer2 && c.Guard.Loaded(): + case why == "" && tag != "" && loaded: return proto.AssuranceStrong, "" - case tag != "" && c.Guard.Loaded(): - // The guard alone keeps the session pts and the runtime directory - // away, not the person's files and other terminals (review N21). - return proto.AssuranceConfined, "agent tagged by the guard without layer 2 (cotty agent): the person's files and other terminals stay reachable" - case layer2 || IsAgentCgroup(in.Cgroup): - return proto.AssuranceConfined, "agent in its own namespaces or agent cgroup (layer 2), no guard" + case why == "" && loaded: + return proto.AssuranceConfined, "agent started by cotty agent but not tagged by the guard (started before the guard ran)" + case why == "": + return proto.AssuranceConfined, "agent started by cotty agent (layer 2), no guard" + case tag != "": + return proto.AssuranceWeak, "tagged by the guard but not confined by cotty agent (" + why + "): the person's files stay reachable" } - return proto.AssuranceWeak, "agent not started through cotty agent" + return proto.AssuranceWeak, "agent not confined by cotty agent: " + why } func (c *Classifier) isOtherSessionTTY(nr uint64) bool { diff --git a/internal/peer/launch.go b/internal/peer/launch.go new file mode 100644 index 0000000..9c7e192 --- /dev/null +++ b/internal/peer/launch.go @@ -0,0 +1,153 @@ +package peer + +import ( + "fmt" + "os" + "path/filepath" + "strconv" + "strings" +) + +// InitStage is the hidden subcommand of the cotty binary that runs as pid +// 1 of a confined agent's pid namespace (confine.StageInit; a test keeps +// the two equal). +const InitStage = "__cotty-confine-init" + +// verifyLaunch reports whether an agent peer runs inside a confinement +// that the cotty binary itself built (`cotty agent`), from what the +// kernel shows about it. It returns "" when it does, else why not. +// +// Review COT-2: being in a user namespace of its own, in a cgroup named +// cotty-agent*, or tagged by the guard proves nothing, since any process +// can give itself each of those (`unshare -U`, a cgroup it creates in its +// delegated subtree, the guard's tag-self). What a process cannot give +// itself is a pid namespace whose pid 1 is the cotty binary the broker +// trusts (root-owned, not replaceable by the user) running the init +// stage: that binary builds the agent's mount view, drops every +// capability and starts the agent with no_new_privs, seccomp and +// Landlock. The peer must be in that namespace and in its mount view, +// with no_new_privs and a seccomp filter in place. +// +// Not covered, and documented (docs/security.md, Assurance levels): this +// describes the process that connected, the agent's MCP server, not what +// talks to it over its stdio. A program that already runs with all of the +// person's rights can start a confined MCP server for itself (`cotty agent +// -- cotty mcp`), or feed the init stage a plan of its own, and is then +// reported confined. +func (c *Classifier) verifyLaunch(in Info) string { + if !c.ExeTrusted { + return "the cotty binary can be replaced by the user (" + c.ExeReason + "), so a confinement it reports proves nothing" + } + if in.PID <= 0 { + return "its pid is not visible from the session, so its confinement cannot be checked" + } + if in.UserNS == "" || in.PidNS == "" || in.UserNS == c.SelfUserNS || in.PidNS == c.SelfPidNS { + return "not in a user and pid namespace of its own" + } + self, err := readTask(in.PID) + if err != nil { + return "cannot read its process: " + err.Error() + } + if self.stat.StartTime != in.StartTime { + return "the process exited during classification" + } + if self.noNewPrivs != 1 { + return "no_new_privs is not set" + } + if c.SeccompFilter && self.seccomp != 2 { + return "no seccomp filter" + } + // pid 1 of the peer's pid namespace: the last ancestor in it. + initPID := 0 + for _, p := range in.ChainPIDs { + ns, err := os.Readlink(filepath.Join(procRoot, strconv.Itoa(p), "ns", "pid")) + if err != nil { + return fmt.Sprintf("cannot read the pid namespace of its ancestor %d: %v", p, err) + } + if ns != in.PidNS { + break + } + initPID = p + } + if initPID == 0 { + return "its parent is outside its pid namespace (the namespace was entered from outside)" + } + init, err := readTask(initPID) + if err != nil { + return fmt.Sprintf("cannot read pid 1 of its namespace (%d): %v", initPID, err) + } + switch { + case init.nsPID != 1: + return fmt.Sprintf("its oldest ancestor in its pid namespace (%d) is not that namespace's pid 1", initPID) + case init.exe == "" || init.exe != c.SelfExe: + return fmt.Sprintf("pid 1 of its namespace runs %q, not the cotty binary %q", init.exe, c.SelfExe) + case len(init.argv) < 2 || init.argv[1] != InitStage: + return "pid 1 of its namespace is not cotty agent's init stage" + case init.userNS != in.UserNS: + return "pid 1 of its namespace is in another user namespace" + case init.mntNS == "" || init.mntNS != self.mntNS: + return "not in the mount view cotty agent built" + case init.stat.StartTime > in.StartTime: + return "pid 1 of its namespace started after it (pid reused)" + } + // The ancestor read above is still the one in the chain (no pid + // reuse between the reads). + if st, err := ReadStat(initPID); err != nil || st.StartTime != init.stat.StartTime { + return "pid 1 of its namespace exited during classification" + } + return "" +} + +// task is what verifyLaunch reads about one process. +type task struct { + stat Stat + exe string + argv []string + userNS string + mntNS string + nsPID int // pid in the innermost pid namespace (NSpid's last field) + noNewPrivs int + seccomp int +} + +func readTask(pid int) (task, error) { + var t task + p := filepath.Join(procRoot, strconv.Itoa(pid)) + st, err := ReadStat(pid) + if err != nil { + return t, err + } + t.stat = st + if exe, err := os.Readlink(filepath.Join(p, "exe")); err == nil { + t.exe = strings.TrimSuffix(exe, " (deleted)") + } + if b, err := os.ReadFile(filepath.Join(p, "cmdline")); err == nil { + t.argv = strings.Split(strings.TrimRight(string(b), "\x00"), "\x00") + } + t.userNS, _ = os.Readlink(filepath.Join(p, "ns", "user")) + t.mntNS, _ = os.Readlink(filepath.Join(p, "ns", "mnt")) + b, err := os.ReadFile(filepath.Join(p, "status")) + if err != nil { + return t, err + } + t.nsPID, t.noNewPrivs, t.seccomp = -1, -1, -1 + for _, l := range strings.Split(string(b), "\n") { + k, v, ok := strings.Cut(l, ":") + if !ok { + continue + } + f := strings.Fields(v) + if len(f) == 0 { + continue + } + switch k { + case "NSpid": + t.nsPID, _ = strconv.Atoi(f[len(f)-1]) + case "NoNewPrivs": + t.noNewPrivs, _ = strconv.Atoi(f[0]) + case "Seccomp": + t.seccomp, _ = strconv.Atoi(f[0]) + } + } + return t, nil +} diff --git a/internal/peer/launch_test.go b/internal/peer/launch_test.go new file mode 100644 index 0000000..f62d7b6 --- /dev/null +++ b/internal/peer/launch_test.go @@ -0,0 +1,147 @@ +package peer + +import ( + "os" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/openbasalt/cotty/internal/proto" +) + +// fakeTask is one process of a fake /proc tree. +type fakeTask struct { + pid, ppid int + start uint64 + exe string + argv []string + user, pns string + mnt string + nspid string // NSpid field + nnp, secc int +} + +func writeProc(t *testing.T, root string, tasks []fakeTask) { + t.Helper() + for _, k := range tasks { + d := filepath.Join(root, strconv.Itoa(k.pid)) + if err := os.MkdirAll(filepath.Join(d, "ns"), 0o755); err != nil { + t.Fatal(err) + } + stat := strconv.Itoa(k.pid) + " (x) S " + strconv.Itoa(k.ppid) + " 1 1 0 -1 0 0 0 0 0 0 0 0 0 20 0 1 0 " + + strconv.FormatUint(k.start, 10) + " 0 0" + status := "Name:\tx\nNSpid:\t" + k.nspid + "\nNoNewPrivs:\t" + strconv.Itoa(k.nnp) + "\nSeccomp:\t" + strconv.Itoa(k.secc) + "\n" + for name, body := range map[string]string{"stat": stat, "status": status, "cmdline": strings.Join(k.argv, "\x00") + "\x00"} { + if err := os.WriteFile(filepath.Join(d, name), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + for name, target := range map[string]string{"exe": k.exe, "ns/user": k.user, "ns/pid": k.pns, "ns/mnt": k.mnt} { + if target != "" { + if err := os.Symlink(target, filepath.Join(d, name)); err != nil { + t.Fatal(err) + } + } + } + } +} + +// launchTree is a cotty agent run as the broker sees it: the launcher +// (outside), pid 1 of the agent's namespace (the init stage), the agent +// CLI and its MCP server, the peer. +func launchTree() []fakeTask { + return []fakeTask{ + {pid: 700, ppid: 600, start: 100, exe: "/usr/bin/cotty", argv: []string{"/usr/bin/cotty", "agent", "--", "claude"}, + user: "user:[1]", pns: "pid:[2]", mnt: "mnt:[3]", nspid: "700", nnp: 0, secc: 0}, + {pid: 701, ppid: 700, start: 110, exe: "/usr/bin/cotty", argv: []string{"/proc/self/exe", InitStage}, + user: "user:[9]", pns: "pid:[9]", mnt: "mnt:[9]", nspid: "701\t1", nnp: 0, secc: 0}, + {pid: 702, ppid: 701, start: 120, exe: "/usr/bin/claude", argv: []string{"claude"}, + user: "user:[9]", pns: "pid:[9]", mnt: "mnt:[9]", nspid: "702\t2", nnp: 1, secc: 2}, + {pid: 703, ppid: 702, start: 130, exe: "/usr/bin/cotty", argv: []string{"cotty", "mcp"}, + user: "user:[9]", pns: "pid:[9]", mnt: "mnt:[9]", nspid: "703\t3", nnp: 1, secc: 2}, + } +} + +func peerOf(k fakeTask) Info { + return Info{UID: 1000, PID: k.pid, PPID: k.ppid, StartTime: k.start, UserNS: k.user, PidNS: k.pns, + Cgroup: "/user.slice/cotty-agent-1.scope", ChainPIDs: []int{702, 701, 700, 600, 1}} +} + +func useProc(t *testing.T, tasks []fakeTask) { + t.Helper() + root := t.TempDir() + writeProc(t, root, tasks) + old := procRoot + procRoot = root + t.Cleanup(func() { procRoot = old }) +} + +func TestLaunchVerified(t *testing.T) { + tasks := launchTree() + useProc(t, tasks) + c := classifier() + c.SeccompFilter = true + in := peerOf(tasks[3]) + if why := c.verifyLaunch(in); why != "" { + t.Fatalf("cotty agent run refused: %s", why) + } + if v := c.Classify(in); v.Person || v.Assurance != proto.AssuranceConfined { + t.Errorf("no guard: %+v", v) + } + c.Guard = fakeGuard{tags: map[int]string{703: "agent:7"}} + if v := c.Classify(in); v.Assurance != proto.AssuranceStrong { + t.Errorf("guard and tag: %+v", v) + } + c.Guard = fakeGuard{} + if v := c.Classify(in); v.Assurance != proto.AssuranceConfined { + t.Errorf("guard without tag: %+v", v) + } +} + +func TestLaunchForgeries(t *testing.T) { + cases := map[string]func(ts []fakeTask, in *Info, c *Classifier){ + // unshare -Upf: pid 1 of the namespace is not cotty's init stage. + "unshare init": func(ts []fakeTask, _ *Info, _ *Classifier) { + ts[1].exe, ts[1].argv = "/usr/bin/unshare", []string{"unshare", "-Upf", "cotty", "mcp"} + }, + // The real binary run as init by another program, under a name. + "init stage argv": func(ts []fakeTask, _ *Info, _ *Classifier) { ts[1].argv = []string{"cotty", "mcp"} }, + // A copy of cotty the user can write. + "init exe copy": func(ts []fakeTask, _ *Info, _ *Classifier) { ts[1].exe = "/home/u/bin/cotty" }, + // nsenter into a real agent's namespaces from outside: the parent + // is outside the namespace. + "entered namespace": func(ts []fakeTask, in *Info, _ *Classifier) { in.ChainPIDs = []int{650, 600, 1} }, + // Entered and then orphaned (reparented to pid 1), but outside + // the agent's mount view. + "other mount view": func(ts []fakeTask, _ *Info, _ *Classifier) { ts[3].mnt = "mnt:[3]" }, + "no no_new_privs": func(ts []fakeTask, _ *Info, _ *Classifier) { ts[3].nnp = 0 }, + "no seccomp": func(ts []fakeTask, _ *Info, _ *Classifier) { ts[3].secc = 0 }, + "oldest not pid 1": func(ts []fakeTask, _ *Info, _ *Classifier) { ts[1].nspid = "701\t4" }, + "init user ns": func(ts []fakeTask, _ *Info, _ *Classifier) { ts[1].user = "user:[8]" }, + "pid reused": func(ts []fakeTask, in *Info, _ *Classifier) { in.StartTime = 999 }, + "init newer": func(ts []fakeTask, _ *Info, _ *Classifier) { ts[1].start = 200 }, + "same namespaces": func(ts []fakeTask, in *Info, _ *Classifier) { + in.UserNS, in.PidNS = "user:[1]", "pid:[2]" + }, + "untrusted binary": func(ts []fakeTask, _ *Info, c *Classifier) { c.ExeTrusted, c.ExeReason = false, "test" }, + "init unreadable": func(ts []fakeTask, _ *Info, _ *Classifier) { ts[1].exe = "" }, + } + for name, mut := range cases { + t.Run(name, func(t *testing.T) { + ts := launchTree() + c := classifier() + c.SeccompFilter = true + in := peerOf(ts[3]) + mut(ts, &in, c) + useProc(t, ts) + if why := c.verifyLaunch(in); why == "" { + t.Fatal("verified") + } + c.Guard = fakeGuard{tags: map[int]string{703: "agent:7"}} + if v := c.Classify(in); v.Person || v.Assurance != proto.AssuranceWeak { + t.Errorf("not weak: %+v", v) + } + }) + } +} diff --git a/internal/peer/peer_test.go b/internal/peer/peer_test.go index 8be6b5d..e914d1e 100644 --- a/internal/peer/peer_test.go +++ b/internal/peer/peer_test.go @@ -90,26 +90,29 @@ func TestClassify(t *testing.T) { t.Errorf("%s: no failed check reported", name) } } - // Agent assurance. - in := person() - in.UserNS = "user:[9]" - if v := c.Classify(in); v.Assurance != proto.AssuranceConfined { - t.Errorf("namespaced agent: %+v", v) - } - in = person() - in.Exe = "/usr/bin/claude" - if v := c.Classify(in); v.Assurance != proto.AssuranceWeak { - t.Errorf("plain agent: %+v", v) + // Agent assurance: properties any process can give itself prove + // nothing (review COT-2); TestLaunch covers the verified cases. + for name, mut := range map[string]func(*Info){ + "own user ns (unshare -U)": func(i *Info) { i.UserNS = "user:[9]" }, + "own user and pid ns": func(i *Info) { i.UserNS, i.PidNS = "user:[9]", "pid:[9]" }, + "agent cgroup it made": func(i *Info) { i.Cgroup = "/user.slice/cotty-agent-x" }, + "pid not visible": func(i *Info) { i.PID = 0 }, + "plain agent": func(i *Info) { i.Exe = "/usr/bin/claude" }, + } { + in := person() + mut(&in) + if v := c.Classify(in); v.Person || v.Assurance != proto.AssuranceWeak { + t.Errorf("%s: %+v", name, v) + } } + // A guard tag (tag-self) never raises an agent on its own. c.Guard = fakeGuard{tags: map[int]string{500: "agent:7"}} - // Tagged but without layer 2 (guard-only): not strong (review N21). - if v := c.Classify(person()); v.Person || v.Assurance != proto.AssuranceConfined { - t.Errorf("tagged agent without layer 2: %+v", v) - } - in = person() - in.UserNS = "user:[9]" - if v := c.Classify(in); v.Person || v.Assurance != proto.AssuranceStrong { - t.Errorf("tagged agent with layer 2: %+v", v) + for _, mut := range []func(*Info){func(*Info) {}, func(i *Info) { i.UserNS, i.PidNS = "user:[9]", "pid:[9]" }} { + in := person() + mut(&in) + if v := c.Classify(in); v.Person || v.Assurance != proto.AssuranceWeak { + t.Errorf("self-tagged agent: %+v", v) + } } // A cotty binary the user can replace makes persons weak. c = classifier() @@ -120,7 +123,7 @@ func TestClassify(t *testing.T) { // Insecure mode. c = classifier() c.Insecure = true - in = person() + in := person() in.Exe = "/tmp/x" if v := c.Classify(in); !v.Person || v.Assurance != proto.AssuranceInsecure { t.Errorf("insecure: %+v", v) diff --git a/tests/attacks/broker.sh b/tests/attacks/broker.sh index 36559d0..d36d27e 100755 --- a/tests/attacks/broker.sh +++ b/tests/attacks/broker.sh @@ -269,6 +269,17 @@ fi known_open S22 gap u-pts-pidfd-getfd "pidfd_getfd of the shell's fd 0 skips file_open; review S22" "$PROBE" pidfd-getfd "$SHELL_PID" "$PTS" deny u-hello-agent-require-confined "$PROBE" hello "$RT/cotty/agent/$RS.sock" agent +# Namespaces any process can make for itself are no confinement (review +# COT-2): an unconfined program in its own user and pid namespace, or one +# that asked the guard to tag it, stays weak and is refused. +if unshare -U --map-current-user true 2>/dev/null; then + deny u-hello-agent-unshare-require-confined unshare -Upf --map-current-user "$PROBE" hello "$RT/cotty/agent/$RS.sock" agent +else + row SKIP u-hello-agent-unshare-require-confined "unprivileged unshare -U is not allowed here" +fi +if [ "$GUARD_STATE" = loaded ] && [ -x "$GUARDPROBE" ]; then + deny u-hello-agent-tagself-require-confined "$GUARDPROBE" tag-self-then unshare -Upf --map-current-user "$PROBE" hello "$RT/cotty/agent/$RS.sock" agent +fi # --- confined (assurance confined) --- "$COTTY" agent --profile generic --pty always --project "$P" --ro "$T" -- \ diff --git a/tests/attacks/guardprobe/main.go b/tests/attacks/guardprobe/main.go index 1a4b968..5798d0f 100644 --- a/tests/attacks/guardprobe/main.go +++ b/tests/attacks/guardprobe/main.go @@ -18,6 +18,10 @@ // guardprobe register-again ask the daemon to register our cgroup again // (an agent must not be able to register) // guardprobe tag-self ask to be tagged (allowed: it only restricts) +// guardprobe tag-self-then CMD... +// ask to be tagged, then exec CMD (a tag must +// never raise an agent's assurance, review +// COT-2) // guardprobe steal-pts PTS protect a pts somebody else protects, with // ourselves as its owner (must be refused) // guardprobe protect-pts protect a pty of our own (we hold its @@ -79,6 +83,25 @@ func main() { } fmt.Println(tag) }) + case "tag-self-then": + if len(args) == 0 { + fmt.Fprintln(os.Stderr, "usage: guardprobe tag-self-then CMD...") + os.Exit(2) + } + withConn(func(c *guard.Conn) { + if _, err := c.TagSelf(); err != nil { + fmt.Println(err) + os.Exit(1) + } + }) + path, err := exec.LookPath(args[0]) + if err != nil { + fmt.Println(err) + os.Exit(2) + } + err = syscall.Exec(path, args, os.Environ()) + fmt.Println(err) + os.Exit(2) default: fmt.Fprintf(os.Stderr, "unknown subcommand %s\n", os.Args[1]) os.Exit(2) From 298228c83d9339c4643505b06629f5ac05b82688 Mon Sep 17 00:00:00 2001 From: Edimar Cardoso Date: Fri, 13 Nov 2026 14:50:27 -0300 Subject: [PATCH 3/5] confine: no Landlock at all fails closed and reads weak With Landlock absent from the kernel (ABI 0), ApplyLandlock returned an error the exec stage ignored, and on a host without a display or bus the launcher accepted ABI < 6 with no flag, so the agent ran with only the mount view, seccomp and its cgroup while the session reported it `confined` (review COT-4). The launcher now refuses ABI 0 unless the person passes --allow-no-landlock, and records that decision in the spec; the exec stage goes on without Landlock only with it and stops on any other Landlock failure. The broker treats a kernel without Landlock as no confinement, so --require-confined refuses such agents, and cotty doctor reports sessions as weak there. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++++ README.md | 7 +++--- cmd/cotty/cmd_agent.go | 1 + cmd/cotty/cmd_doctor.go | 2 ++ cmd/cotty/doctor_test.go | 1 + docs/confinement.md | 11 +++++++++- internal/broker/broker.go | 1 + internal/confine/doctor_linux.go | 4 ++-- internal/confine/exec_linux.go | 2 +- internal/confine/landlockgate_test.go | 31 +++++++++++++++++++++++++++ internal/confine/launch_linux.go | 4 ++++ internal/confine/plan.go | 4 ++++ internal/confine/spec.go | 31 +++++++++++++++++++++++++++ internal/peer/classify.go | 4 ++++ internal/peer/launch.go | 3 +++ internal/peer/launch_test.go | 2 ++ internal/peer/peer_test.go | 2 +- 17 files changed, 106 insertions(+), 8 deletions(-) create mode 100644 internal/confine/landlockgate_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index b607c88..bdfa829 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- `cotty agent` refuses a kernel without Landlock (ABI 0) unless given + `--allow-no-landlock`; it used to start the agent without Landlock and + the session still reported it `confined`. Sessions now report every + agent `weak` on such a kernel, and `cotty doctor` says so. - Assurance: an agent is `confined` only when the broker sees that the trusted cotty binary built its confinement (pid 1 of its pid namespace runs cotty agent's init stage, and the agent is in that namespace's diff --git a/README.md b/README.md index 0937934..493a542 100644 --- a/README.md +++ b/README.md @@ -149,9 +149,10 @@ without `.git` (its hooks and config are then the agent's), `--allow-git-links` accepts a project whose `.git`, git config or hooks are symbolic links, and `--allow-abstract-sockets` starts on kernels below Landlock ABI 6 even though a display or session bus is reachable -through abstract sockets there. `--show-hidden` leaves a profile's -hidden directories visible (for Claude Code, `~/.claude/ide`, whose lock -files hold your IDE's auth token). +through abstract sockets there. `--allow-no-landlock` starts on a kernel +without Landlock, where sessions then report the agent `weak`. +`--show-hidden` leaves a profile's hidden directories visible (for Claude +Code, `~/.claude/ide`, whose lock files hold your IDE's auth token). The lock does not light for a password prompt inside a program that relays the terminal in raw mode (`sudo -i`, `ssh`, `tmux`, `screen`): diff --git a/cmd/cotty/cmd_agent.go b/cmd/cotty/cmd_agent.go index 36d1009..eb6100f 100644 --- a/cmd/cotty/cmd_agent.go +++ b/cmd/cotty/cmd_agent.go @@ -39,6 +39,7 @@ func runAgent(args []string) int { fs.BoolVar(&opts.Quiet, "quiet", false, "no banner (gaps are printed anyway)") fs.BoolVar(&opts.AllowGitInit, "allow-git-init", false, "in a project without .git, let the agent create one (its hooks and config would run with your rights when you use git there)") fs.BoolVar(&opts.AllowAbstractSockets, "allow-abstract-sockets", false, "start on Landlock ABI < 6 even when X11 or D-Bus listen on abstract sockets the agent could reach") + fs.BoolVar(&opts.AllowNoLandlock, "allow-no-landlock", false, "start on a kernel without Landlock, where only the mount view limits the agent's files (sessions report the agent weak)") fs.BoolVar(&opts.AllowGitLinks, "allow-git-links", false, "start even when a git file cotty protects (.git, its config or hooks, core.hooksPath) is a symbolic link the agent could replace") fs.BoolVar(&opts.ShowHidden, "show-hidden", false, "leave the profile's hidden directories visible (claude: ~/.claude/ide, whose lock files hold your IDE's auth token; needed when the agent should talk to your IDE)") fs.BoolVar(&list, "list-profiles", false, "list the profiles and exit") diff --git a/cmd/cotty/cmd_doctor.go b/cmd/cotty/cmd_doctor.go index 380fc5e..75f6955 100644 --- a/cmd/cotty/cmd_doctor.go +++ b/cmd/cotty/cmd_doctor.go @@ -68,6 +68,8 @@ func sessionsSummary(layer2 string, checks []confine.Check) (string, string) { return "unavailable (cotty agent cannot start here)", "" case status["binary"] == "warn": return "weak (the cotty binary can be replaced by your user)", "Sessions report weak until cotty is installed root-owned (see the binary line above)." + case status["landlock"] == "fail": + return "weak (no Landlock: agents cannot be confined here)", "Sessions report every agent weak on a kernel without Landlock (see the landlock line above)." case guardRunning: return "strong available for new sessions (cotty-guard running)", "Sessions created before cotty-guard started stay at their level (confined); start a new session to get strong." diff --git a/cmd/cotty/doctor_test.go b/cmd/cotty/doctor_test.go index acb75c2..d14d7e5 100644 --- a/cmd/cotty/doctor_test.go +++ b/cmd/cotty/doctor_test.go @@ -21,6 +21,7 @@ func TestSessionsSummary(t *testing.T) { {"guard not running", "confined", []confine.Check{check("binary", "ok"), check("guard", "info")}, "confined (cotty-guard not running)", "before cotty-guard starts stay confined"}, {"guard not answering", "confined", []confine.Check{check("binary", "ok"), check("guard", "warn")}, "confined (cotty-guard not answering)", ""}, {"untrusted binary", "confined", []confine.Check{check("binary", "warn"), check("guard", "ok")}, "weak", ""}, + {"no landlock", "partial", []confine.Check{check("binary", "ok"), check("landlock", "fail"), check("guard", "ok")}, "weak (no Landlock", "every agent weak"}, {"no namespaces", "unavailable", []confine.Check{check("binary", "ok"), check("guard", "ok")}, "unavailable", ""}, } { got, note := sessionsSummary(tc.layer2, tc.checks) diff --git a/docs/confinement.md b/docs/confinement.md index e8157bd..bd59405 100644 --- a/docs/confinement.md +++ b/docs/confinement.md @@ -10,7 +10,7 @@ optional, see [guard.md](guard.md). ``` cotty agent [--profile P] [--project DIR] [--ro PATH] [--rw PATH] [--agent-dir DIR] [--no-mcp] - [--allow-git-init] [--allow-git-links] [--allow-abstract-sockets] [--quiet] [--] CMD [ARGS...] + [--allow-git-init] [--allow-git-links] [--allow-abstract-sockets] [--allow-no-landlock] [--quiet] [--] CMD [ARGS...] cotty agent --profile claude # runs the profile's own command cotty agent --list-profiles cotty agent --dry-run -- claude -p hi # print the computed plan as JSON @@ -279,6 +279,15 @@ count. `--allow-abstract-sockets` accepts the risk. The exec stage refuses a ker launcher made that decision, so Landlock's best-effort mode never drops the scoping silently. +A kernel without Landlock at all (ABI 0: not built in, or not in the +`lsm=` boot list, as on some older enterprise kernels and cloud images) is +refused too: only the mount view would limit the agent's files, and +abstract sockets and signals would not be scoped. `--allow-no-landlock` +starts the agent anyway; the exec stage then goes on without Landlock +only because the launcher recorded that decision, and sessions report +the agent `weak`, since what it can reach is no longer what `confined` +means (review COT-4). + ### Seccomp A classic BPF filter written in Go (`internal/confine/seccomp_linux.go`), diff --git a/internal/broker/broker.go b/internal/broker/broker.go index 1f2b442..9479f0f 100644 --- a/internal/broker/broker.go +++ b/internal/broker/broker.go @@ -314,6 +314,7 @@ func New(cfg Config) (*Broker, error) { b.classifier = peer.Self() b.classifier.Guard = cfg.Guard b.classifier.SeccompFilter = confine.SeccompSupported() + b.classifier.LandlockABI = confine.LandlockABI() b.classifier.Insecure = cfg.Insecure dir, name := cfg.Dir, cfg.Name b.classifier.OtherTTYs = func() []uint64 { return session.OtherTTYs(dir, name) } diff --git a/internal/confine/doctor_linux.go b/internal/confine/doctor_linux.go index 5f31302..fa79a5c 100644 --- a/internal/confine/doctor_linux.go +++ b/internal/confine/doctor_linux.go @@ -46,7 +46,7 @@ func Assess(f Features, userns bool) (string, []string) { switch { case f.LandlockABI == 0: partial = true - gaps = append(gaps, "no Landlock: only the mount view limits files, and abstract Unix sockets (X11's @/tmp/.X11-unix) and signals to outside processes are not scoped") + gaps = append(gaps, "no Landlock: only the mount view limits files, and abstract Unix sockets (X11's @/tmp/.X11-unix) and signals to outside processes are not scoped; cotty agent refuses to start unless given --allow-no-landlock, and sessions report such an agent weak") case f.LandlockABI < 6: partial = true gaps = append(gaps, fmt.Sprintf("Landlock ABI %d (< 6): abstract Unix sockets (X11's @/tmp/.X11-unix, abstract D-Bus addresses) are reachable from the agent; cotty agent refuses to start while one of those listens, unless given --allow-abstract-sockets", f.LandlockABI)) @@ -83,7 +83,7 @@ func Doctor() Report { abi := LandlockABI() switch { case abi == 0: - add("landlock", "fail", "absent", "Landlock is not built into this kernel or not in the lsm= boot list. cotty agent still hides files with namespaces, but nothing restricts the agent inside that view and X11's abstract socket stays reachable.") + add("landlock", "fail", "absent", "Landlock is not built into this kernel or not in the lsm= boot list. cotty agent refuses to start unless given --allow-no-landlock: it would still hide files with namespaces, but nothing would restrict the agent inside that view and X11's abstract socket would stay reachable. Sessions report such an agent weak.") case abi < 6: ex := "Landlock restricts files, but ABI 6 (Linux 6.12) is needed to keep the agent away from abstract Unix sockets (X11) and from signalling your other processes." if risky := abstractSocketsAtRisk(); len(risky) > 0 { diff --git a/internal/confine/exec_linux.go b/internal/confine/exec_linux.go index 570ac6b..9c16df2 100644 --- a/internal/confine/exec_linux.go +++ b/internal/confine/exec_linux.go @@ -44,7 +44,7 @@ func RunExec() { if abi := LandlockABI(); abi < 6 && !sp.Landlock.NoScopesOK { execFail(125, "landlock ABI %d cannot scope abstract sockets and signals, and the launcher did not accept that", abi) } - if abi, err := ApplyLandlock(sp.Landlock); err != nil && abi > 0 { + if abi, err := ApplyLandlock(sp.Landlock); landlockApplied(abi, err, sp.Landlock.NoLandlockOK) != nil { execFail(125, "landlock: %v", err) } if sp.Seccomp && SeccompSupported() { diff --git a/internal/confine/landlockgate_test.go b/internal/confine/landlockgate_test.go new file mode 100644 index 0000000..b004acc --- /dev/null +++ b/internal/confine/landlockgate_test.go @@ -0,0 +1,31 @@ +package confine + +import ( + "errors" + "testing" +) + +// Review COT-4: no Landlock at all is a refused start unless the person +// accepted it, and the exec stage never ignores a failed Landlock +// otherwise. +func TestLandlockGate(t *testing.T) { + if landlockGate(0, false) == nil { + t.Error("ABI 0 accepted without --allow-no-landlock") + } + if landlockGate(0, true) != nil || landlockGate(1, false) != nil { + t.Error("refused a start that should go on") + } + fail := errors.New("landlock is not available") + if landlockApplied(0, fail, false) == nil { + t.Error("exec stage went on without Landlock and without the launcher's consent") + } + if landlockApplied(0, fail, true) != nil { + t.Error("exec stage refused an accepted run without Landlock") + } + if landlockApplied(3, fail, true) == nil { + t.Error("a Landlock failure on a kernel that has it was ignored") + } + if landlockApplied(6, nil, false) != nil { + t.Error("success refused") + } +} diff --git a/internal/confine/launch_linux.go b/internal/confine/launch_linux.go index ba514a6..5645bc5 100644 --- a/internal/confine/launch_linux.go +++ b/internal/confine/launch_linux.go @@ -149,6 +149,10 @@ func runOutside(pl *Plan, opts Options, cg string) int { sp.PTY = sp.PTY || stdioTTY f := Features{LandlockABI: LandlockABI(), Seccomp: SeccompSupported(), Cgroup: cg, PTY: sp.PTY} level, gaps := Assess(f, true) + if err := landlockGate(f.LandlockABI, opts.AllowNoLandlock); err != nil { + return fail("%v", err) + } + sp.Landlock.NoLandlockOK = f.LandlockABI == 0 sp.Env = SetEnv(sp.Env, map[string]string{"COTTY_ASSURANCE": level}) // Without Landlock scoping (ABI < 6) abstract sockets are reachable: // refuse when a display, bus or input method listens on one, unless diff --git a/internal/confine/plan.go b/internal/confine/plan.go index f06d685..aa0f689 100644 --- a/internal/confine/plan.go +++ b/internal/confine/plan.go @@ -35,6 +35,10 @@ type Options struct { // AllowAbstractSockets starts the agent on Landlock ABI < 6 even when // abstract X11 or D-Bus sockets are listening. AllowAbstractSockets bool + // AllowNoLandlock starts the agent on a kernel without Landlock (ABI + // 0), where only the mount view limits its files. Sessions report + // such an agent weak. + AllowNoLandlock bool // AllowGitLinks starts the agent even when a git file cotty protects // (the .git entry, config, hooks, core.hooksPath) is a symbolic link, // which the agent could replace. diff --git a/internal/confine/spec.go b/internal/confine/spec.go index c839300..4eb9cec 100644 --- a/internal/confine/spec.go +++ b/internal/confine/spec.go @@ -1,5 +1,11 @@ package confine +import "errors" + +var errNoLandlock = errors.New("this kernel has no Landlock (not built in, or not in the lsm= boot list): " + + "only the mount view would limit the agent's files, and abstract sockets and signals would not be scoped. " + + "Use a kernel with Landlock, or start with --allow-no-landlock to accept that (sessions then report the agent weak)") + // Spec is everything the confined stages need, computed outside by the // launcher and passed to them as JSON on a pipe (never in the environment // or on the command line, which the agent could read). @@ -66,6 +72,31 @@ type LandlockPlan struct { // abstract sockets and signals (ABI < 6); the launcher sets it only // after its own check or the person's explicit override. NoScopesOK bool `json:"noScopesOK"` + // NoLandlockOK lets the exec stage go on without Landlock at all (ABI + // 0); the launcher sets it only on the person's explicit + // --allow-no-landlock (review COT-4). + NoLandlockOK bool `json:"noLandlockOK,omitempty"` +} + +// landlockGate decides, from the kernel's Landlock ABI, whether the +// launcher may start the agent: without Landlock (ABI 0) only when the +// person accepted that explicitly (review COT-4: the agent used to start +// without it, still reported confined). +func landlockGate(abi int, allowNone bool) error { + if abi > 0 || allowNone { + return nil + } + return errNoLandlock +} + +// landlockApplied decides, in the exec stage, whether a failed +// ApplyLandlock stops the start: always, unless the kernel has no +// Landlock and the launcher accepted that (NoLandlockOK). +func landlockApplied(abi int, err error, noLandlockOK bool) error { + if err == nil || (abi == 0 && noLandlockOK) { + return nil + } + return err } // Link is a symbolic link recreated inside the confinement. diff --git a/internal/peer/classify.go b/internal/peer/classify.go index d168b88..18d2156 100644 --- a/internal/peer/classify.go +++ b/internal/peer/classify.go @@ -58,6 +58,10 @@ type Classifier struct { // SeccompFilter: `cotty agent` installs its seccomp filter on this // system (confine.SeccompSupported), so a confined agent shows one. SeccompFilter bool + // LandlockABI is the kernel's Landlock ABI (confine.LandlockABI). At + // 0, cotty agent runs the agent without Landlock (only on + // --allow-no-landlock), which is not confined (review COT-4). + LandlockABI int } // Verdict is the result of classifying one peer. diff --git a/internal/peer/launch.go b/internal/peer/launch.go index 9c7e192..6fd7202 100644 --- a/internal/peer/launch.go +++ b/internal/peer/launch.go @@ -38,6 +38,9 @@ func (c *Classifier) verifyLaunch(in Info) string { if !c.ExeTrusted { return "the cotty binary can be replaced by the user (" + c.ExeReason + "), so a confinement it reports proves nothing" } + if c.LandlockABI <= 0 { + return "the kernel has no Landlock, so cotty agent cannot restrict the agent's files" + } if in.PID <= 0 { return "its pid is not visible from the session, so its confinement cannot be checked" } diff --git a/internal/peer/launch_test.go b/internal/peer/launch_test.go index f62d7b6..7422d89 100644 --- a/internal/peer/launch_test.go +++ b/internal/peer/launch_test.go @@ -126,6 +126,8 @@ func TestLaunchForgeries(t *testing.T) { }, "untrusted binary": func(ts []fakeTask, _ *Info, c *Classifier) { c.ExeTrusted, c.ExeReason = false, "test" }, "init unreadable": func(ts []fakeTask, _ *Info, _ *Classifier) { ts[1].exe = "" }, + // COT-4: without Landlock the agent is not confined. + "no landlock": func(ts []fakeTask, _ *Info, c *Classifier) { c.LandlockABI = 0 }, } for name, mut := range cases { t.Run(name, func(t *testing.T) { diff --git a/internal/peer/peer_test.go b/internal/peer/peer_test.go index e914d1e..2805d24 100644 --- a/internal/peer/peer_test.go +++ b/internal/peer/peer_test.go @@ -54,7 +54,7 @@ func person() Info { func classifier() *Classifier { return &Classifier{UID: 1000, SelfPID: 300, SelfUserNS: "user:[1]", SelfPidNS: "pid:[2]", SelfExe: "/usr/bin/cotty", ExeTrusted: true, ShellPID: 310, ShellSID: 310, - SessionTTY: unix.Mkdev(136, 7), Guard: NoGuard{}, + SessionTTY: unix.Mkdev(136, 7), Guard: NoGuard{}, LandlockABI: 6, OtherTTYs: func() []uint64 { return []uint64{unix.Mkdev(136, 9)} }} } From 491ad7a4d309792f5bf84228792d0abfc666212a Mon Sep 17 00:00:00 2001 From: Edimar Cardoso Date: Fri, 13 Nov 2026 14:51:30 -0300 Subject: [PATCH 4/5] ci: Go 1.27.4, actions pinned by SHA, Dependabot CI installs exactly the go line of go.mod, which said 1.26.0, so the binaries were built with an old standard library; it now names 1.27.4, the current release. The workflow's actions were pinned by tag and are now pinned by commit SHA (checkout v7.0.1, setup-go v7.0.0) with persist-credentials off, and a Dependabot config keeps Go modules and actions current, matching the sibling repos (review COT-5). No CI check that the committed BPF object matches bpf/guard.bpf.c is added: CI has no clang/llvm toolchain today and the object is regenerated by hand in a lab VM (make bpf). Co-Authored-By: Claude Opus 5.5 --- .github/dependabot.yml | 21 +++++++++++++++++++++ .github/workflows/ci.yml | 9 +++++++-- CHANGELOG.md | 3 +++ go.mod | 2 +- 4 files changed, 32 insertions(+), 3 deletions(-) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..a97a288 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,21 @@ +# Dependency update pull requests: Go modules (and the toolchain line of +# go.mod) and the GitHub Actions, which the workflows pin by full commit +# SHA. One grouped pull request per ecosystem per week. +version: 2 +updates: + - package-ecosystem: gomod + directory: / + schedule: + interval: weekly + groups: + go-modules: + patterns: ["*"] + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + groups: + actions: + patterns: ["*"] + commit-message: + prefix: ci diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 55b72bc..a12caa3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,8 +16,13 @@ jobs: env: CGO_ENABLED: "0" steps: - - uses: actions/checkout@v4 - - uses: actions/setup-go@v5 + # Actions are pinned by commit SHA; Dependabot keeps them current. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # go-version-file installs exactly the go line of go.mod, so that + # line names the patch release the binaries are built with. + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: go-version-file: go.mod - name: gofmt, vet, unit tests diff --git a/CHANGELOG.md b/CHANGELOG.md index bdfa829..453196e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- Build: go.mod names Go 1.27.4 (CI builds with that line); the CI + actions are pinned by commit SHA, and Dependabot proposes Go module + and action updates weekly. - `cotty agent` refuses a kernel without Landlock (ABI 0) unless given `--allow-no-landlock`; it used to start the agent without Landlock and the session still reported it `confined`. Sessions now report every diff --git a/go.mod b/go.mod index f77dc31..540930f 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/openbasalt/cotty -go 1.26.0 +go 1.27.4 require ( github.com/charmbracelet/ultraviolet v0.0.0-20260303162955-0b88c25f3fff From 63fc4ab7252dc09f5f0bf35bff4056dd6b09c22f Mon Sep 17 00:00:00 2001 From: Edimar Cardoso Date: Fri, 13 Nov 2026 15:11:41 -0300 Subject: [PATCH 5/5] broker tests: a prompt stand-in that sleeps under any name TestShortHelperDoesNotStickLock and TestLateExecPromptDetected copied the system's sleep to pinentry-tty to stand for a listed prompt program. GitHub's ubuntu-latest moved to Ubuntu 26.04, where sleep is the uutils multicall binary: it picks the utility from its own name, so the copy exits at once as "pinentry-tty" and the lock never lights (CI run 43477142151; the last green run on main used ubuntu-24.04). The copy is now of the test binary, which TestMain turns into sleep(1) when started under that name. The assertions are unchanged. Co-Authored-By: Claude Opus 5.5 --- internal/broker/main_test.go | 29 +++++++++++++++++++++++++++++ internal/broker/round4_test.go | 15 ++++++++++----- internal/broker/unit_test.go | 13 +------------ 3 files changed, 40 insertions(+), 17 deletions(-) create mode 100644 internal/broker/main_test.go diff --git a/internal/broker/main_test.go b/internal/broker/main_test.go new file mode 100644 index 0000000..aca27e0 --- /dev/null +++ b/internal/broker/main_test.go @@ -0,0 +1,29 @@ +package broker + +import ( + "os" + "path/filepath" + "strconv" + "testing" + "time" +) + +// sleeperName is the name under which the test binary acts as sleep(1): +// promptCopy copies it there to stand for a listed prompt program. +const sleeperName = "pinentry-tty" + +// TestMain lets the test binary, started as sleeperName, sleep for its +// first argument (seconds) and exit, like sleep(1) under any name. A +// copy of the system's sleep does not do that everywhere (the uutils +// multicall binary chooses the utility by its own name). +func TestMain(m *testing.M) { + if filepath.Base(os.Args[0]) == sleeperName { + secs := 0.0 + if len(os.Args) > 1 { + secs, _ = strconv.ParseFloat(os.Args[1], 64) + } + time.Sleep(time.Duration(secs * float64(time.Second))) + os.Exit(0) + } + os.Exit(m.Run()) +} diff --git a/internal/broker/round4_test.go b/internal/broker/round4_test.go index 2e417f3..1165dc2 100644 --- a/internal/broker/round4_test.go +++ b/internal/broker/round4_test.go @@ -26,17 +26,22 @@ func startGroup(t *testing.T, script string) *exec.Cmd { } // promptCopy copies sleep to a file named like a listed prompt program. +// +// The copy is of the test binary, which sleeps when started under that +// name (TestMain), not of the system's sleep: on Ubuntu 25.10 and later +// sleep is the uutils multicall binary, which picks the utility by its +// own name and exits at once as "pinentry-tty" (CI on ubuntu-26.04). func promptCopy(t *testing.T) string { t.Helper() - sleepBin, err := exec.LookPath("sleep") + self, err := os.Executable() if err != nil { - t.Skip(err) + t.Fatal(err) } - data, err := os.ReadFile(sleepBin) + data, err := os.ReadFile(self) if err != nil { - t.Skip(err) + t.Fatal(err) } - p := filepath.Join(t.TempDir(), "pinentry-tty") + p := filepath.Join(t.TempDir(), sleeperName) if err := os.WriteFile(p, data, 0o755); err != nil { t.Fatal(err) } diff --git a/internal/broker/unit_test.go b/internal/broker/unit_test.go index a3e235c..a4ed925 100644 --- a/internal/broker/unit_test.go +++ b/internal/broker/unit_test.go @@ -229,18 +229,7 @@ func TestRawSetuidPrompt(t *testing.T) { // list described while the group was young. The secret program rule // shares the path with the setuid rule and needs no root binary. func TestLateExecPromptDetected(t *testing.T) { - sleepBin, err := exec.LookPath("sleep") - if err != nil { - t.Skip(err) - } - data, err := os.ReadFile(sleepBin) - if err != nil { - t.Skip(err) - } - prompt := filepath.Join(t.TempDir(), "pinentry-tty") - if err := os.WriteFile(prompt, data, 0o755); err != nil { - t.Fatal(err) - } + prompt := promptCopy(t) job := exec.Command("sh", "-c", "sleep 0.7; exec "+prompt+" 30") job.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} if err := job.Start(); err != nil {