diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 45cbb61..23a0144 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -45,6 +45,11 @@ jobs: grep -E -- '--- FAIL|_test\.go:[0-9]+:|^FAIL|panic:' test.log | head -40 | sed 's/^/::error::/' exit 1 } + # The confined agent check end to end: a real console, the client + # on the host and in docker run (lockkit#133). + - name: go test confine e2e (docker) + if: runner.os == 'Linux' + run: go test -tags e2e -count=1 -v ./confine/... - name: go test managed (test build) run: go test -tags lockfamily_managed_test ./managed/ ./console/ - name: pii throughput floor diff --git a/CHANGELOG.md b/CHANGELOG.md index 76b0cbf..7c3ba4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,40 @@ lockkit has no stability promise before v1: pin an exact version. GUIDE.md is the contract between lockkit and the products built on it. +## Unreleased + +### Breaking + +- Unconfined agents are refused by default (#133). Every lock client + reports in `hello` whether it runs confined (new package `confine`: + in a container, no host runtime socket, no Lock Family state, a + read-only `.lockfamily/`), and the console refuses an unconfined one + with `ipc.CodeUnconfined`, as it does a client holding a gid that owns a + runtime socket (`runtime_group`) or one that sends no report + (`old_client`). The profile key `unconfined = true` lets one in on a + non-production profile (a loosening, approved at the console): red + banner, `"unconfined":true` on every audit record of the connection, + `flags.unconfined` on its hub tickets. A production profile with it + does not start; a managed `require_confined_agent = true` refuses + unconfined agents whatever the profile says. No method is served on a + connection before its hello is accepted, and the decision is taken + again at every request. A lock bumping lockkit must ship its client and + console of the same version: an older console refuses the new hello + member, and an older client is refused by the new console. + +### Changes + +- ipc: `Cred.Groups` (the peer's supplementary groups: Linux + `SO_PEERGROUPS`, macOS `cr_groups`) and `Cred.HasGroup`; + `HelloParams.Confinement`; `CodeUnconfined` (-32009). +- console: `--runtime-gids` (`HubOptions.RuntimeGIDs`, written by `lox + run`), `ServerConfig.RuntimeGIDs`, `Profile.Unconfined`, + `UnconfinedBanner`, `DecisionRefusedUnconfined`, `ParseGIDs`. +- config: `Base.Unconfined` (`unconfined`, in `DiffBase`); audit: + `Base.Unconfined`, `Base.UnconfinedReasons`; ticket: `Flags.Unconfined`. +- An end-to-end test (`go test -tags e2e ./confine/...`) runs a real + console and the client on the host and in `docker run`, in CI. + ## v0.19.2 (2026-11-14) ### Changes diff --git a/GUIDE.md b/GUIDE.md index 429d245..72f668f 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -216,6 +216,9 @@ loosen it, and no human can approve beyond it. `File.Fingerprint` is the sha256 of the bytes, `File.Describe()` the "Managed by (sha256:…)" line, `File.Family` (`RequireConfinedAgent`, `RequireSignature`, `Vault`) the family rules. + The console enforces `RequireConfinedAgent` itself: an unconfined agent + is refused whatever the profile's `unconfined` says (§10, Confined + agents). Precedence: hard-coded floor > managed bounds and profiles > project file > user file > managed defaults > built-in defaults. In your config loader: @@ -302,6 +305,25 @@ c, err := client.Dial(P, cwd, profile) // *client.NoConsoleError (errors.Is Err err = c.Call(ctx, "op.run", params, &result) // hello first, no client-side timeout; ctx cancel closes the connection ``` +**Confinement (lockkit#133).** The client's `hello` carries +`ipc.HelloParams.Confinement` (`{"confined":bool,"reasons":[…]}`), the +outcome of `confine.Check(confine.RealEnv())`, computed once per process. +Confined means all four checks hold: `in_container` (`/.dockerenv`, +`/run/.containerenv`, a container in `/proc/1/cgroup` or an overlay root in +`/proc/self/mountinfo`; Linux only), `no_host_runtime` (none of +`confine.RuntimeSockets` connects or refuses for want of permission; a +rootless runtime under `/run/user//` is not one), +`no_family_state` (`$XDG_STATE_HOME/lockfamily` absent or unreadable), +`lockfamily_read_only` (the nearest `.lockfamily/` above the working +directory, if any, fails `access(W_OK)`). Each failed check is its code in +`reasons`; `confine.Text(code)` is its human text. A refusal is +`ipc.CodeUnconfined` (-32009) with the reasons in the message. Use +`client.Dial`: a client that builds its own hello must send the same +report. `ipc.PeerCred` also returns the peer's supplementary groups +(`Cred.Groups`: Linux `SO_PEERGROUPS`, macOS `cr_groups`), which the +console checks (§10). A console older than this one refuses the new +`confinement` member: ship your client and console of the same version. + Several locks of one type (lea mounts each socket volume on `/` and lists them, space separated, in `LEA_INSTANCES`; one lock stays on the shared dir with no such @@ -1080,6 +1102,48 @@ The pieces are exported for a product that assembles its own console: `console.Harden`, `console.Loop`, `console.WithPeer` / `PeerText` / `StampPeer`, `console.Level`, `console.ErrResp` / `OKResp` / `Decode`. +### Confined agents (lockkit#133) + +The console decides in `hello`, from the client's report (§7) and the +kernel's record of the peer: + +| Client | Profile | Outcome | +|---|---|---| +| reports confined, holds no runtime gid | any | served | +| unconfined (any reason) | default | refused: `CodeUnconfined`, audited `refused/refused-unconfined` with `unconfined_reasons` | +| unconfined | `unconfined = true`, not production | served; red banner `console.UnconfinedBanner`; every audit record of the connection has `"unconfined":true` and its reasons; its hub tickets have `flags.unconfined` | +| unconfined | production, or managed `require_confined_agent = true` | refused, whatever `unconfined` says | +| no `confinement` in its hello | any | unconfined, `old_client` | +| holds a gid of `ServerConfig.RuntimeGIDs` | any | unconfined, `runtime_group`, whatever it reports | + +- On a socket connection every method but `hello` is refused + (`CodeInvalidRequest`, "hello first") until a hello is accepted, and the + decision is taken again at every request: a policy in force that becomes + production or drops `unconfined`, or a managed file that comes to + require a confined agent, refuses the next request of an open + unconfined connection. +- Reason codes are the agent's word: the console keeps only known ones + (`confine.Known`), never the console's own codes (`runtime_group`, + `old_client`), at most eight. +- `RuntimeGIDs`: `Run` sets them to the gids of `--runtime-gids` + (`HubOptions.RuntimeGIDs`, comma-separated, registered with the hub + flags but not counted by `Enabled`, so a policy-only console takes it + too; `lox run` writes it for a containerized console) and those of this + machine's runtime sockets whose group may write them + (`confine.RuntimeGIDs`: `docker`'s, not rootful Podman's `root:root + 0600`). A value that is not a list of gids refuses the start (`ErrConfig`). +- `Profile.Unconfined` comes from `config.Base.Unconfined` (profile key + `unconfined = true`, `json:"unconfined,omitempty"`: existing + fingerprints hold). `DiffBase` marks false→true a loosening, true→false + a tightening. `Run` refuses a production profile with it (`ErrConfig`: + "unconfined is never allowed on a production profile"), before any + prompt and again on the policy approved at start, and prints the banner + at start. +- `audit.Base.Unconfined` / `UnconfinedReasons` are set by `StampPeer`, + so a product's records through `Env`/`AuditBase` carry them. + `ticket.Flags.Unconfined` is `omitempty`: a hub that does not know it + refuses only the tickets that carry it. + ## 11. Do not reimplement in your product - a socket, a peer check or the JSON-RPC framing: `ipc`, `client`; diff --git a/README.md b/README.md index 5a1f562..e5a2d3d 100644 --- a/README.md +++ b/README.md @@ -198,12 +198,65 @@ builds on it too. of the human, and on production takes the typed profile name. - In hub mode, a lock executes only on a decision signed by the hub key it pinned, bound to the exact plan that was approved. +- The agent must run confined (lea is the reference containment): + unconfined agents are refused by default, see + [Confined agents](#confined-agents). - Masking is best effort. PII detection quality: precision and recall per detector and language on a synthetic bench, held to a CI baseline, in [pii/testdata/bench/RESULTS.md](pii/testdata/bench/RESULTS.md); its Known gaps section lists what the detectors miss most. +### Confined agents + +The Locks' guarantees hold only if the agent cannot reach what protects +them. An agent run directly on your machine (plain `claude` or `codex` in +a terminal) runs as you: it can read the hub facades' private keys and +sign its own approvals, use Docker to open a lock's container and read its +credentials, and edit `lockfamily.yaml` or stop `lox run`. Unconfined, a +lock protects you against a **confused** agent, not against a +**prompt-injected** one. + +So every lock client checks where it runs and says so in its `hello`; the +console decides. An agent is confined when all of these hold: + +| Check | Reason code when it fails | +|---|---| +| it runs in a container (Linux only; on macOS a client is never confined) | `in_container` | +| no rootful runtime socket is reachable or mounted (`/var/run/docker.sock`, `/run/docker.sock`, `/run/podman/podman.sock`, `/run/containerd/containerd.sock`); a rootless Podman inside the container is fine | `no_host_runtime` | +| the Lock Family's state directory (`$XDG_STATE_HOME/lockfamily`) is absent or unreadable | `no_family_state` | +| the project's `.lockfamily/`, if any, is read-only | `lockfamily_read_only` | + +The console adds what the kernel says: a client holding a group that owns +a runtime socket (`docker`) is unconfined (`runtime_group`), whatever it +reports, and a client too old to report is unconfined (`old_client`). + +- By default an unconfined agent is refused: `refused: this agent does not + run confined (...); run it inside lea, or ask the human to set + unconfined = true on this non-production profile`. +- `unconfined = true` in a profile lets it in. It is part of the reviewed + policy: switching it on is a loosening you approve at the console. The + console then prints a red banner (`unconfined: this lock protects + against mistakes, not against a compromised agent`) at start and at + every unconfined connection, every audit record of that connection says + `"unconfined":true` with its reasons, and its hub tickets say so too. +- Never on production: a production profile with `unconfined = true` does + not start. A managed file with `require_confined_agent = true` refuses + unconfined agents whatever the profile says. +- No method is served on a connection before its `hello` is accepted, and + the decision is taken again at every request: a policy that becomes + production, or a managed file that comes to require a confined agent, + cuts an unconfined connection already open. + +What this proves, and what it does not: the check makes the safe setup the +default and stops honest or confused agents run on the host. It does not +stop a host process that deliberately lies about where it runs: such a +process already runs as you and can drive Docker, so no lock-side check +could stop it. What makes the guarantees hold against prompt injection is +the containment itself: a confined agent (lea) cannot reach the runtime, +the keys or the console's terminal. + Details: [GUIDE.md § 6](GUIDE.md#6-config-and-policy-the-ai-tightens-the-human-loosens), +[§ 7](GUIDE.md#7-ipc-client-tunnel), [§ 10](GUIDE.md#10-the-console-and-the-backend-seam) and [§ 13](GUIDE.md#13-hub-tickets-ticket). diff --git a/audit/audit.go b/audit/audit.go index 61d5a43..2a71e34 100644 --- a/audit/audit.go +++ b/audit/audit.go @@ -119,6 +119,12 @@ type Base struct { // (package managed) when the record was made, so that an action is // tied to the company policy it ran under. Managed string `json:"managed,omitempty"` + // Unconfined marks every record of a connection from an agent that + // does not run confined (lockkit#133), served because its profile sets + // unconfined = true, or refused; UnconfinedReasons are the reason codes + // (package confine). + Unconfined bool `json:"unconfined,omitempty"` + UnconfinedReasons []string `json:"unconfined_reasons,omitempty"` } // AuditEvent implements Record. diff --git a/audit/audit_test.go b/audit/audit_test.go index 8f07d37..a1314c4 100644 --- a/audit/audit_test.go +++ b/audit/audit_test.go @@ -167,7 +167,7 @@ func TestConcurrentWritesStayWholeLines(t *testing.T) { func TestBaseFieldSet(t *testing.T) { want := []string{ "approval", "approver", "code", "decision", "error", "event", "facade", "hub_sig", "inputs", "intent", "managed", "pattern", "peer_pid", "peer_uid", "peer_user", - "prev_hash", "profile", "reason", "span", "ticket", "ts", "warnings", + "prev_hash", "profile", "reason", "span", "ticket", "ts", "unconfined", "unconfined_reasons", "warnings", } l, err := Open(testProduct, t.TempDir()) if err != nil { @@ -178,6 +178,7 @@ func TestBaseFieldSet(t *testing.T) { Approval: "session", Pattern: "orders.phone", PeerUID: new(int), PeerPID: 4, PeerUser: "agent", Code: "E_NO_LIMIT", Span: &refusal.Span{Line: 1, Col: 2, Token: "FROM"}, Ticket: "t", Approver: &ticket.Approver{ID: "u", Display: "d"}, Facade: "tty", HubSig: "s", Inputs: []string{"needle"}, Managed: "sha", + Unconfined: true, UnconfinedReasons: []string{"in_container"}, } if err := l.Append(full); err != nil { t.Fatal(err) diff --git a/client/client.go b/client/client.go index 31d6589..70858d7 100644 --- a/client/client.go +++ b/client/client.go @@ -27,6 +27,7 @@ import ( "time" "github.com/DavidGodefroid/lockkit/config" + "github.com/DavidGodefroid/lockkit/confine" "github.com/DavidGodefroid/lockkit/ipc" "github.com/DavidGodefroid/lockkit/kit" "github.com/DavidGodefroid/lockkit/sysconf" @@ -155,6 +156,13 @@ func sharedDir(p kit.Product, instance string) (string, error) { return filepath.Join(sys.SocketDir, instance), nil } +// confinement is the client's self-check (confine.Check), run once per +// process and sent in every hello; tests replace it. +var confinement = sync.OnceValue(func() ipc.Confinement { + r := confine.Check(confine.RealEnv()) + return ipc.Confinement{Confined: r.Confined, Reasons: r.Reasons} +}) + // dialUnix opens the socket; tests replace it to watch the connection. var dialUnix = func(path string) (net.Conn, error) { return net.Dial("unix", path) } @@ -282,7 +290,8 @@ func (c *Client) handshake(ctx context.Context) error { name = c.product.Name } var hr ipc.HelloResult - if err := c.call(ctx, ipc.MethodHello, ipc.HelloParams{ProtocolMajor: ipc.ProtocolMajor, Client: name}, &hr); err != nil { + conf := confinement() + if err := c.call(ctx, ipc.MethodHello, ipc.HelloParams{ProtocolMajor: ipc.ProtocolMajor, Client: name, Confinement: &conf}, &hr); err != nil { return err } if !ipc.Compatible(hr.ProtocolMajor) { diff --git a/client/client_test.go b/client/client_test.go index a7e7cdf..ed71da3 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -45,6 +45,7 @@ type fakeConsole struct { mu sync.Mutex methods []string clients []string + confs []*ipc.Confinement } func (f *fakeConsole) seen() []string { @@ -88,6 +89,7 @@ func startFake(t *testing.T, cwd, profile string, handler func(req ipc.Request) _ = json.Unmarshal(req.Params, &hp) f.mu.Lock() f.clients = append(f.clients, hp.Client) + f.confs = append(f.confs, hp.Confinement) f.mu.Unlock() resp = result(req.ID, ipc.HelloResult{ProtocolMajor: ipc.ProtocolMajor, ConsoleVersion: "9.9.9", Profile: profile}) } else { @@ -224,6 +226,10 @@ func TestCallSendsHelloFirstAndDecodes(t *testing.T) { if fake.clients[0] != "lockmq" { t.Fatalf("hello client = %q", fake.clients[0]) } + // The hello carries the client's confinement report. + if c := fake.confs[0]; c == nil || c.Confined != confinement().Confined { + t.Fatalf("hello confinement = %+v, want %+v", c, confinement()) + } } func TestCallReturnsRPCError(t *testing.T) { diff --git a/config/policy.go b/config/policy.go index 6b0cdfb..49f8503 100644 --- a/config/policy.go +++ b/config/policy.go @@ -123,6 +123,13 @@ type Base struct { TicketsPerWindow int `json:"tickets_per_window,omitempty"` TicketWindow time.Duration `json:"ticket_window,omitempty"` MaxPending int `json:"max_pending,omitempty"` + // Unconfined lets an agent that does not run confined use the profile + // (lockkit#133; profile key unconfined = true): the lock then protects + // against mistakes, not against a compromised agent. Never on a + // production profile (the console refuses to start). Part of the + // policy and its fingerprint: switching it on is a loosening. Omitted + // when false, so that the fingerprints of existing policies hold. + Unconfined bool `json:"unconfined,omitempty"` } // TicketLimits are the hub client's limits of b (hubclient.Limits, @@ -151,7 +158,7 @@ func ConnectionField(field string) bool { // tls_cert or tls_key, production true→false, any change of the ssh table // (a credentials mode other than ask for the bastion), a longer session // limit, a longer or removed credentials_ttl, more tickets per window, a -// shorter ticket window or more pending tickets. +// shorter ticket window or more pending tickets, unconfined false→true. func DiffBase(a, c Base) []Change { var out []Change same := func(field, o, n string) { @@ -215,6 +222,9 @@ func DiffBase(a, c Base) []Change { out = append(out, Change{Field: "limits.max_pending", Old: strconv.Itoa(a.MaxPending), New: strconv.Itoa(c.MaxPending), Loosens: cl.MaxPending > al.MaxPending}) } + if a.Unconfined != c.Unconfined { + out = append(out, Change{Field: "unconfined", Old: strconv.FormatBool(a.Unconfined), New: strconv.FormatBool(c.Unconfined), Loosens: c.Unconfined}) + } if a.CredentialsTTL != c.CredentialsTTL { out = append(out, Change{Field: "credentials_ttl", Old: a.CredentialsTTL.String(), New: c.CredentialsTTL.String(), Loosens: LooserLimit(int64(a.CredentialsTTL), int64(c.CredentialsTTL))}) diff --git a/config/policy_test.go b/config/policy_test.go index 05c09d1..e6106e1 100644 --- a/config/policy_test.go +++ b/config/policy_test.go @@ -1,12 +1,14 @@ package config import ( + "encoding/json" "errors" "io/fs" "os" "path/filepath" "reflect" "runtime" + "strings" "testing" "time" @@ -196,3 +198,22 @@ func TestConnectionField(t *testing.T) { } } } + +// TestUnconfined: the profile key unconfined is in the fingerprint, +// switching it on loosens and off tightens; false keeps the fingerprint +// of a policy written before the key existed. +func TestUnconfined(t *testing.T) { + off, on := Base{User: "u", Credentials: CredentialsAsk}, Base{User: "u", Credentials: CredentialsAsk, Unconfined: true} + if Fingerprint(off) == Fingerprint(on) { + t.Fatal("unconfined does not change the fingerprint") + } + if b, _ := json.Marshal(off); strings.Contains(string(b), "unconfined") { + t.Fatalf("unconfined = false is encoded: %s", b) + } + if ch := DiffBase(off, on); len(ch) != 1 || ch[0].Field != "unconfined" || !ch[0].Loosens { + t.Fatalf("on: %+v", ch) + } + if ch := DiffBase(on, off); len(ch) != 1 || ch[0].Field != "unconfined" || ch[0].Loosens { + t.Fatalf("off: %+v", ch) + } +} diff --git a/confine/confine.go b/confine/confine.go new file mode 100644 index 0000000..498f848 --- /dev/null +++ b/confine/confine.go @@ -0,0 +1,247 @@ +// Package confine is the client's self-check of its containment +// (lockkit#133): whether the agent behind a lock client runs where it +// cannot reach what protects the Locks: the container runtime, the hub +// facades' keys, the project's .lockfamily directory. +// +// The check runs in the agent's environment, where the facts are visible, +// and its Report travels in the hello handshake (ipc.Confinement). The +// console decides; it also checks, on Linux, the kernel's record of the +// peer's groups (RuntimeGIDs), which the client cannot forge. +// +// What it proves: an honest or confused agent run on the host is told so +// and refused by default. What it does not: a host process that lies runs +// as the human and can drive Docker anyway; no lock-side check stops it. +// Confined agents (lea) cannot reach the runtime, the keys or the console's +// terminal, and that is what makes the guarantees hold against prompt +// injection. +package confine + +import ( + "errors" + "io" + "io/fs" + "net" + "os" + "path/filepath" + "runtime" + "strings" + "time" +) + +// The reasons a client is unconfined: each names the check that failed. +// They are fixed codes, sent on the wire; Text gives the human text. +const ( + // InContainer: the client does not run in a container. + InContainer = "in_container" + // NoHostRuntime: a rootful container runtime socket connects, or is + // there behind permissions. + NoHostRuntime = "no_host_runtime" + // NoFamilyState: the Lock Family's state directory (the facades' + // private keys) is readable. + NoFamilyState = "no_family_state" + // LockfamilyReadOnly: the project's .lockfamily directory is writable. + LockfamilyReadOnly = "lockfamily_read_only" + // RuntimeGroup: the peer holds a group owning a runtime socket + // (decided by the console from the kernel's record, never reported). + RuntimeGroup = "runtime_group" + // OldClient: the client sent no confinement report (decided by the + // console). + OldClient = "old_client" +) + +var texts = map[string]string{ + InContainer: "it does not run in a container", + NoHostRuntime: "it can reach the host's container runtime", + NoFamilyState: "it can read the Lock Family's keys", + LockfamilyReadOnly: "it can write the project's .lockfamily directory", + RuntimeGroup: "it holds a group that owns a container runtime socket", + OldClient: "its client is too old to report its confinement", +} + +// Known reports whether code is one of the reasons above. +func Known(code string) bool { + _, ok := texts[code] + return ok +} + +// Text is the human text of a reason code; "" for an unknown one. +func Text(code string) string { return texts[code] } + +// Report is the outcome of Check. +type Report struct { + Confined bool + // Reasons are the codes of the checks that failed, in check order. + Reasons []string +} + +// RuntimeSockets are the rootful container runtime sockets. A rootless +// runtime socket inside the container (lea's nested Podman under +// /run/user//) is not one: it runs in the container's namespaces. +var RuntimeSockets = []string{ + "/var/run/docker.sock", + "/run/docker.sock", + "/run/podman/podman.sock", + "/run/containerd/containerd.sock", +} + +// Env is what Check reads; tests replace its functions. +type Env struct { + // GOOS is runtime.GOOS: only Linux has containers. + GOOS string + // Exists reports whether a path exists. + Exists func(path string) bool + // ReadFile reads a file (/proc/1/cgroup, /proc/self/mountinfo). + ReadFile func(path string) ([]byte, error) + // Connects reports whether a unix socket at path accepts a connection, + // or refuses it for want of permission: a runtime socket mounted into + // the container counts even when this account may not use it. + Connects func(path string) bool + // Readable reports whether the directory at path can be listed. + Readable func(path string) bool + // Writable reports whether the directory at path is writable + // (access(2) W_OK: a read-only mount is not). + Writable func(path string) bool + Getenv func(string) string + Getwd func() (string, error) + HomeDir func() (string, error) +} + +// RealEnv is the process's own environment. +func RealEnv() Env { + return Env{ + GOOS: runtime.GOOS, + Exists: func(p string) bool { + _, err := os.Lstat(p) + return err == nil + }, + ReadFile: os.ReadFile, + Connects: func(p string) bool { + c, err := net.DialTimeout("unix", p, time.Second) + if err != nil { + return errors.Is(err, fs.ErrPermission) + } + c.Close() + return true + }, + Readable: func(p string) bool { + f, err := os.Open(p) + if err != nil { + return false + } + defer f.Close() + _, err = f.Readdirnames(1) + return err == nil || errors.Is(err, io.EOF) + }, + Writable: writable, + Getenv: os.Getenv, + Getwd: os.Getwd, + HomeDir: os.UserHomeDir, + } +} + +// Check runs the four checks of env. The client is confined when all +// hold: it runs in a container, no rootful runtime socket connects, the +// Lock Family's state directory is absent or unreadable, and the nearest +// .lockfamily directory above the working directory, if any, is not +// writable. +func Check(env Env) Report { + var reasons []string + if !inContainer(env) { + reasons = append(reasons, InContainer) + } + for _, s := range RuntimeSockets { + if env.Connects(s) { + reasons = append(reasons, NoHostRuntime) + break + } + } + if dir := stateDir(env); dir != "" && env.Readable(dir) { + reasons = append(reasons, NoFamilyState) + } + if dir := nearestLockfamily(env); dir != "" && env.Writable(dir) { + reasons = append(reasons, LockfamilyReadOnly) + } + return Report{Confined: len(reasons) == 0, Reasons: reasons} +} + +// inContainer: the runtimes' marker files, or a container in +// /proc/1/cgroup (cgroup v1) or a container root in /proc/self/mountinfo. +// Never on another system than Linux. +func inContainer(env Env) bool { + if env.GOOS != "linux" { + return false + } + if env.Exists("/.dockerenv") || env.Exists("/run/.containerenv") { + return true + } + if b, err := env.ReadFile("/proc/1/cgroup"); err == nil { + s := string(b) + for _, m := range []string{"/docker/", "/docker-", "/kubepods", "/libpod-", "/containerd/", "/lxc/"} { + if strings.Contains(s, m) { + return true + } + } + } + if b, err := env.ReadFile("/proc/self/mountinfo"); err == nil { + return containerRoot(string(b)) + } + return false +} + +// containerRoot reports a mountinfo whose root mount is an overlay (the +// image layers of a container) or that holds a runtime's per-container +// files (/etc/hostname bound from /var/lib/docker/containers/...). +func containerRoot(mountinfo string) bool { + for _, line := range strings.Split(mountinfo, "\n") { + if strings.Contains(line, "/docker/containers/") || strings.Contains(line, "/containers/storage/overlay-containers/") { + return true + } + // ... - + pre, post, ok := strings.Cut(line, " - ") + if !ok { + continue + } + f := strings.Fields(pre) + if len(f) < 5 || f[4] != "/" { + continue + } + if t := strings.Fields(post); len(t) > 0 && (t[0] == "overlay" || t[0] == "fuse-overlayfs") { + return true + } + } + return false +} + +// stateDir is $XDG_STATE_HOME/lockfamily, ~/.local/state/lockfamily by +// default; "" when neither is known. +func stateDir(env Env) string { + if x := env.Getenv("XDG_STATE_HOME"); x != "" && filepath.IsAbs(x) { + return filepath.Join(x, "lockfamily") + } + home, err := env.HomeDir() + if err != nil || home == "" { + return "" + } + return filepath.Join(home, ".local", "state", "lockfamily") +} + +// nearestLockfamily is the first .lockfamily directory at or above the +// working directory, "" when there is none. +func nearestLockfamily(env Env) string { + dir, err := env.Getwd() + if err != nil { + return "" + } + dir = filepath.Clean(dir) + for { + p := filepath.Join(dir, ".lockfamily") + if env.Exists(p) { + return p + } + parent := filepath.Dir(dir) + if parent == dir { + return "" + } + dir = parent + } +} diff --git a/confine/confine_test.go b/confine/confine_test.go new file mode 100644 index 0000000..8e3dbd1 --- /dev/null +++ b/confine/confine_test.go @@ -0,0 +1,152 @@ +package confine + +import ( + "errors" + "slices" + "testing" +) + +// fakeEnv is a confined lea container: /.dockerenv, no runtime socket, no +// family state, a read-only .lockfamily in the project. +type fakeEnv struct { + files map[string]bool + sockets map[string]bool + readable map[string]bool + writable map[string]bool + procFiles map[string]string + env map[string]string + goos string + cwd, home string +} + +func confinedFake() *fakeEnv { + return &fakeEnv{ + files: map[string]bool{"/.dockerenv": true, "/work/proj/.lockfamily": true}, + sockets: map[string]bool{}, + readable: map[string]bool{"/work/proj/.lockfamily": true}, + writable: map[string]bool{"/work/proj": true}, + procFiles: map[string]string{}, + env: map[string]string{}, + goos: "linux", + cwd: "/work/proj/sub", + home: "/home/agent", + } +} + +func (f *fakeEnv) Env() Env { + return Env{ + GOOS: f.goos, + Exists: func(p string) bool { return f.files[p] }, + ReadFile: func(p string) ([]byte, error) { + if s, ok := f.procFiles[p]; ok { + return []byte(s), nil + } + return nil, errors.New("no such file") + }, + Connects: func(p string) bool { return f.sockets[p] }, + Readable: func(p string) bool { return f.readable[p] }, + Writable: func(p string) bool { return f.writable[p] }, + Getenv: func(k string) string { return f.env[k] }, + Getwd: func() (string, error) { return f.cwd, nil }, + HomeDir: func() (string, error) { return f.home, nil }, + } +} + +func TestConfinedWhenAllHold(t *testing.T) { + r := Check(confinedFake().Env()) + if !r.Confined || len(r.Reasons) != 0 { + t.Fatalf("Check = %+v, want confined", r) + } +} + +func TestEachReasonAlone(t *testing.T) { + for _, tc := range []struct { + want string + mutate func(*fakeEnv) + }{ + {InContainer, func(f *fakeEnv) { delete(f.files, "/.dockerenv") }}, + {InContainer, func(f *fakeEnv) { f.goos = "darwin" }}, + {NoHostRuntime, func(f *fakeEnv) { f.sockets["/var/run/docker.sock"] = true }}, + {NoHostRuntime, func(f *fakeEnv) { f.sockets["/run/podman/podman.sock"] = true }}, + {NoHostRuntime, func(f *fakeEnv) { f.sockets["/run/containerd/containerd.sock"] = true }}, + {NoFamilyState, func(f *fakeEnv) { f.readable["/home/agent/.local/state/lockfamily"] = true }}, + {NoFamilyState, func(f *fakeEnv) { + f.env["XDG_STATE_HOME"] = "/xdg" + f.readable["/xdg/lockfamily"] = true + }}, + {LockfamilyReadOnly, func(f *fakeEnv) { f.writable["/work/proj/.lockfamily"] = true }}, + } { + f := confinedFake() + tc.mutate(f) + r := Check(f.Env()) + if r.Confined || !slices.Equal(r.Reasons, []string{tc.want}) { + t.Errorf("want only %s, got %+v", tc.want, r) + } + } +} + +func TestNestedRootlessPodmanAllowed(t *testing.T) { + f := confinedFake() + f.sockets["/run/user/1000/podman/podman.sock"] = true + f.env["DOCKER_HOST"] = "unix:///run/user/1000/podman/podman.sock" + if r := Check(f.Env()); !r.Confined { + t.Fatalf("a rootless podman in the container made it unconfined: %+v", r) + } +} + +func TestHostHasEveryReason(t *testing.T) { + f := confinedFake() + f.files = map[string]bool{"/work/proj/.lockfamily": true} + f.sockets["/run/docker.sock"] = true + f.readable["/home/agent/.local/state/lockfamily"] = true + f.writable["/work/proj/.lockfamily"] = true + r := Check(f.Env()) + want := []string{InContainer, NoHostRuntime, NoFamilyState, LockfamilyReadOnly} + if r.Confined || !slices.Equal(r.Reasons, want) { + t.Fatalf("Check = %+v, want %v", r, want) + } +} + +func TestNoLockfamilyDirIsFine(t *testing.T) { + f := confinedFake() + delete(f.files, "/work/proj/.lockfamily") + if r := Check(f.Env()); !r.Confined { + t.Fatalf("no .lockfamily: %+v", r) + } +} + +func TestContainerDetectedFromProc(t *testing.T) { + for name, files := range map[string]map[string]string{ + "cgroup v1": {"/proc/1/cgroup": "12:pids:/docker/0123abcd\n"}, + "overlay root": {"/proc/self/mountinfo": "22 1 0:21 / / rw,relatime - overlay overlay rw,lowerdir=/l\n" + + "23 22 0:22 / /proc rw - proc proc rw\n"}, + "docker hostname": {"/proc/self/mountinfo": "30 22 8:1 /var/lib/docker/containers/abc/hostname /etc/hostname rw - ext4 /dev/sda1 rw\n"}, + } { + f := confinedFake() + delete(f.files, "/.dockerenv") + f.procFiles = files + if r := Check(f.Env()); !r.Confined { + t.Errorf("%s: %+v", name, r) + } + } + f := confinedFake() + delete(f.files, "/.dockerenv") + f.procFiles = map[string]string{ + "/proc/1/cgroup": "0::/init.scope\n", + "/proc/self/mountinfo": "22 1 8:1 / / rw,relatime - ext4 /dev/sda1 rw\n", + } + if r := Check(f.Env()); r.Confined { + t.Errorf("a host root was taken for a container") + } +} + +func TestReasonTexts(t *testing.T) { + for _, c := range []string{InContainer, NoHostRuntime, NoFamilyState, LockfamilyReadOnly, RuntimeGroup, OldClient} { + if !Known(c) || Text(c) == "" { + t.Errorf("%s has no text", c) + } + } + if Known("whatever") { + t.Error("unknown code known") + } +} diff --git a/confine/e2e/e2e_test.go b/confine/e2e/e2e_test.go new file mode 100644 index 0000000..55f33c3 --- /dev/null +++ b/confine/e2e/e2e_test.go @@ -0,0 +1,245 @@ +//go:build e2e && linux + +// Package e2e runs the confined agent check end to end (lockkit#133): a +// real console server on a unix socket, and a real lock client (package +// client, testdata/client) run on the host and in containers. +// +// go test -tags e2e ./confine/... +// +// It needs a container runtime: docker, or the one LOCKKIT_E2E_RUNTIME +// names (podman), with LOCKKIT_E2E_RUN_ARGS added to every run (rootless +// Podman needs --userns=keep-id for the peer to be the test's uid). +package e2e + +import ( + "context" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" + + "github.com/DavidGodefroid/lockkit/audit" + "github.com/DavidGodefroid/lockkit/config" + "github.com/DavidGodefroid/lockkit/confine" + "github.com/DavidGodefroid/lockkit/console" + "github.com/DavidGodefroid/lockkit/ipc" + "github.com/DavidGodefroid/lockkit/kit" +) + +var product = kit.Product{Name: "locke2e", Account: "locke2e", ClientsGroup: "locke2e-clients", KeychainService: "locke2e", EnvPrefix: "LOCKE2E_"} + +type policy struct { + Base config.Base `json:"base"` +} + +func (p policy) Diff(a config.Policy) []config.Change { + return config.DiffBase(a.(policy).Base, p.Base) +} +func (p policy) Describe() []string { return []string{"e2e"} } +func (p policy) Profile() console.Profile { + return console.Profile{Name: "uat", Where: "nowhere", Credentials: console.CredentialsNone, Unconfined: p.Base.Unconfined} +} + +type session struct{} + +func (session) Close() error { return nil } + +type backend struct{ p policy } + +func (b backend) Methods() map[string]console.Handler { return nil } +func (b backend) Connect(context.Context, console.Credentials) (console.Session, error) { + return session{}, nil +} +func (b backend) Checks(context.Context, console.Session) []console.Finding { return nil } +func (b backend) LoadPolicy() (console.Policy, error) { return b.p, nil } +func (b backend) Status(console.Session) any { return nil } + +type lines struct{} + +func (lines) Println(string) {} +func (lines) Ask(context.Context, string, time.Duration) (string, bool) { + return "", false +} +func (lines) AskSecret(context.Context, string) ([]byte, error) { return nil, fmt.Errorf("no secret") } + +type outcome struct { + Served bool `json:"served"` + Code int `json:"code"` + Message string `json:"message"` + Error string `json:"error"` +} + +func runtimeCmd(t *testing.T) string { + rt := os.Getenv("LOCKKIT_E2E_RUNTIME") + if rt == "" { + rt = "docker" + } + if _, err := exec.LookPath(rt); err != nil { + t.Skipf("no %s: %v", rt, err) + } + if out, err := exec.Command(rt, "info").CombinedOutput(); err != nil { + t.Skipf("%s info: %v\n%s", rt, err, out) + } + return rt +} + +// serve starts a console server for profile uat in a short temp runtime +// directory and returns that directory. +func serve(t *testing.T) string { + t.Helper() + dir, err := os.MkdirTemp("/tmp", "lke2e") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + if err := os.Chmod(dir, 0o755); err != nil { + t.Fatal(err) + } + t.Setenv(product.RuntimeDirEnv(), dir) + path, err := ipc.SocketPath(product, "user", "uat") + if err != nil { + t.Fatal(err) + } + ln, err := ipc.Listen(path) + if err != nil { + t.Fatal(err) + } + log, err := audit.Open(product, t.TempDir()) + if err != nil { + t.Fatal(err) + } + s, err := console.NewServer(console.ServerConfig{Product: product, Backend: backend{}, Policy: policy{}, + Session: session{}, Audit: log, IO: lines{}, RuntimeGIDs: confine.RuntimeGIDs()}) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + _ = s.Loop().Serve(ctx, ln, nil) + }() + t.Cleanup(func() { cancel(); <-done }) + return dir +} + +func buildClient(t *testing.T) string { + t.Helper() + dir := t.TempDir() + cmd := exec.Command("go", "build", "-o", filepath.Join(dir, "client"), "./testdata/client") + cmd.Env = append(os.Environ(), "CGO_ENABLED=0") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("build: %v\n%s", err, out) + } + return filepath.Join(dir, "client") +} + +func parse(t *testing.T, out []byte) outcome { + t.Helper() + var o outcome + if err := json.Unmarshal(out, &o); err != nil { + t.Fatalf("client output %q: %v", out, err) + } + return o +} + +func wantRefused(t *testing.T, o outcome, reasons ...string) { + t.Helper() + if o.Served || o.Code != ipc.CodeUnconfined { + t.Fatalf("not refused unconfined: %+v", o) + } + for _, r := range reasons { + if !strings.Contains(o.Message, r+": ") { + t.Errorf("message %q lacks %s", o.Message, r) + } + } +} + +func TestConfinedAgentE2E(t *testing.T) { + rt := runtimeCmd(t) + bin := buildClient(t) + dir := serve(t) + + // (a) On the host: refused. + t.Run("host", func(t *testing.T) { + if confine.Check(confine.RealEnv()).Confined { + t.Skip("the test host is itself confined (a lea container)") + } + cmd := exec.Command(bin) + cmd.Env = append(os.Environ(), product.RuntimeDirEnv()+"="+dir) + out, err := cmd.Output() + if err != nil { + t.Fatal(err) + } + wantRefused(t, parse(t, out), confine.InContainer) + }) + + // The image: the client binary alone. + ctxDir := t.TempDir() + data, err := os.ReadFile(bin) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(ctxDir, "client"), data, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(ctxDir, "Dockerfile"), []byte("FROM scratch\nCOPY client /client\nENTRYPOINT [\"/client\"]\n"), 0o644); err != nil { + t.Fatal(err) + } + image := "lockkit-confine-e2e:" + strconv.Itoa(os.Getpid()) + if out, err := exec.Command(rt, "build", "-q", "-t", image, ctxDir).CombinedOutput(); err != nil { + t.Fatalf("build image: %v\n%s", err, out) + } + t.Cleanup(func() { _ = exec.Command(rt, "rmi", "-f", image).Run() }) + lf := filepath.Join(t.TempDir(), ".lockfamily") + if err := os.Mkdir(lf, 0o755); err != nil { + t.Fatal(err) + } + // run runs the client in a container with the socket dir and the + // .lockfamily mounted, read-only unless lfMode is "rw". + run := func(t *testing.T, lfMode string, extra ...string) outcome { + t.Helper() + args := []string{"run", "--rm", "--user", fmt.Sprintf("%d:%d", os.Getuid(), os.Getgid()), + "-v", dir + ":" + dir, "-v", lf + ":/work/.lockfamily:" + lfMode, "-w", "/work", + "-e", product.RuntimeDirEnv() + "=" + dir} + args = append(args, strings.Fields(os.Getenv("LOCKKIT_E2E_RUN_ARGS"))...) + args = append(args, extra...) + args = append(args, image) + out, err := exec.Command(rt, args...).Output() + if err != nil { + t.Fatalf("%s %v: %v", rt, args, err) + } + return parse(t, out) + } + + // (b) In a container with only the socket dir and a read-only + // .lockfamily: served. + t.Run("container", func(t *testing.T) { + if o := run(t, "ro"); !o.Served { + t.Fatalf("not served: %+v", o) + } + }) + + // A writable .lockfamily: refused. + t.Run("container+writable", func(t *testing.T) { + wantRefused(t, run(t, "rw"), confine.LockfamilyReadOnly) + }) + + // (c) The same container with the host's runtime socket: refused. + t.Run("container+runtime", func(t *testing.T) { + const sock = "/var/run/docker.sock" + fi, err := os.Stat(sock) + if err != nil || fi.Mode()&os.ModeSocket == 0 { + t.Skipf("no %s on this host", sock) + } + wantRefused(t, run(t, "ro", "-v", sock+":"+sock), confine.NoHostRuntime) + gid := int(fi.Sys().(*syscall.Stat_t).Gid) + wantRefused(t, run(t, "ro", "-v", sock+":"+sock, "--group-add", strconv.Itoa(gid)), confine.NoHostRuntime, confine.RuntimeGroup) + }) +} diff --git a/confine/e2e/testdata/client/main.go b/confine/e2e/testdata/client/main.go new file mode 100644 index 0000000..3b210f0 --- /dev/null +++ b/confine/e2e/testdata/client/main.go @@ -0,0 +1,38 @@ +// Command client is the e2e test's lock client: it dials the console of +// profile uat through package client (whose hello carries the real +// confine.Check of where it runs) and prints the outcome as JSON. +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + + "github.com/DavidGodefroid/lockkit/client" + "github.com/DavidGodefroid/lockkit/ipc" + "github.com/DavidGodefroid/lockkit/kit" +) + +func main() { + p := kit.Product{Name: "locke2e", Account: "locke2e", ClientsGroup: "locke2e-clients", KeychainService: "locke2e", EnvPrefix: "LOCKE2E_"} + out := map[string]any{} + c, err := client.Dial(p, "/", "uat") + if err == nil { + defer c.Close() + err = c.Call(context.Background(), ipc.MethodStatus, nil, nil) + } + var re *ipc.RPCError + switch { + case err == nil: + out["served"] = true + case errors.As(err, &re): + out["code"], out["message"] = re.Code, re.Message + default: + out["error"] = err.Error() + } + b, _ := json.Marshal(out) + fmt.Println(string(b)) + os.Exit(0) +} diff --git a/confine/runtime_other.go b/confine/runtime_other.go new file mode 100644 index 0000000..ea3ccbd --- /dev/null +++ b/confine/runtime_other.go @@ -0,0 +1,6 @@ +//go:build !unix + +package confine + +// RuntimeGIDs is none where sockets have no owning group. +func RuntimeGIDs() []int { return nil } diff --git a/confine/runtime_unix.go b/confine/runtime_unix.go new file mode 100644 index 0000000..868621d --- /dev/null +++ b/confine/runtime_unix.go @@ -0,0 +1,28 @@ +//go:build unix + +package confine + +import ( + "os" + "slices" + "syscall" +) + +// RuntimeGIDs are the groups that own a rootful runtime socket of this +// machine (RuntimeSockets) and may write it: a peer holding one can drive +// the runtime, whatever it reports. A socket its group cannot write (rootful +// Podman's root:root 0600) gives none. A console run on the host computes +// them itself; a containerized one is told them (--runtime-gids). +func RuntimeGIDs() []int { + var out []int + for _, s := range RuntimeSockets { + fi, err := os.Stat(s) + if err != nil || fi.Mode()&os.ModeSocket == 0 || fi.Mode().Perm()&0o020 == 0 { + continue + } + if st, ok := fi.Sys().(*syscall.Stat_t); ok && !slices.Contains(out, int(st.Gid)) { + out = append(out, int(st.Gid)) + } + } + return out +} diff --git a/confine/writable_other.go b/confine/writable_other.go new file mode 100644 index 0000000..1c7a90f --- /dev/null +++ b/confine/writable_other.go @@ -0,0 +1,11 @@ +//go:build !unix + +package confine + +import "os" + +// writable reports a directory whose mode lets its owner write it. +func writable(p string) bool { + fi, err := os.Stat(p) + return err == nil && fi.Mode().Perm()&0o200 != 0 +} diff --git a/confine/writable_unix.go b/confine/writable_unix.go new file mode 100644 index 0000000..854728a --- /dev/null +++ b/confine/writable_unix.go @@ -0,0 +1,8 @@ +//go:build unix + +package confine + +import "golang.org/x/sys/unix" + +// writable is access(2) W_OK: false on a read-only mount (EROFS). +func writable(p string) bool { return unix.Access(p, unix.W_OK) == nil } diff --git a/console/backend.go b/console/backend.go index 55b1d73..be560d7 100644 --- a/console/backend.go +++ b/console/backend.go @@ -97,6 +97,10 @@ type Profile struct { // The console applies them on start and whenever a policy comes in // force, so a raise counts only once reviewed. TicketLimits hubclient.Limits + // Unconfined serves agents that do not run confined + // (config.Base.Unconfined, lockkit#133): refused at start on a + // production profile. + Unconfined bool } // PIIBackend is implemented by a backend whose policy has mask rules: the diff --git a/console/confine.go b/console/confine.go new file mode 100644 index 0000000..8f2da78 --- /dev/null +++ b/console/confine.go @@ -0,0 +1,205 @@ +package console + +import ( + "context" + "fmt" + "slices" + "strconv" + "strings" + + "github.com/DavidGodefroid/lockkit/audit" + "github.com/DavidGodefroid/lockkit/confine" + "github.com/DavidGodefroid/lockkit/ipc" +) + +// The confined agent check (lockkit#133). Every client connection reports +// its confinement in hello (ipc.Confinement, the client's self-check); the +// console adds what the kernel says of the peer (a group owning a runtime +// socket, RuntimeGIDs) and decides: +// +// reported confined, no runtime group → served +// unconfined, profile without unconfined → refused (CodeUnconfined) +// unconfined, unconfined = true, not prod → served, banner, audited unconfined +// unconfined, production or managed require → refused +// +// A hello without a report (an older client) is unconfined (old_client). +// On a socket connection no method is served before an accepted hello, and +// the decision is taken again at every request: a policy that becomes +// production, or a managed file that comes to require a confined agent, +// cuts an unconfined connection already open. + +// DecisionRefusedUnconfined is the decision of the record of a request +// refused because its agent does not run confined. +const DecisionRefusedUnconfined = "refused-unconfined" + +// UnconfinedBanner is printed at start and at every unconfined connection +// when the profile accepts unconfined agents. +const UnconfinedBanner = "unconfined: this lock protects against mistakes, not against a compromised agent" + +// maxReasons bounds the reason codes taken from a client. +const maxReasons = 8 + +// connState is one client connection's state, set by Loop.accept. +type connState struct { + helloed bool + unconfined bool + reasons []string +} + +type connKey struct{} + +// withConn returns ctx carrying a new connection state. +func withConn(ctx context.Context) context.Context { + return context.WithValue(ctx, connKey{}, &connState{}) +} + +func connFrom(ctx context.Context) *connState { + c, _ := ctx.Value(connKey{}).(*connState) + return c +} + +// unconfinedOf returns whether the request of ctx comes from an unconfined +// connection, and its reasons. +func unconfinedOf(ctx context.Context) (bool, []string) { + if c := connFrom(ctx); c != nil && c.unconfined { + return true, c.reasons + } + return false, nil +} + +// confinementReasons are the reasons a hello's client is unconfined: those +// it reports (known codes only: the text is the agent's), runtime_group +// when the kernel says the peer holds one of runtimeGIDs, old_client when +// it sent no report. None: confined. +func confinementReasons(c *ipc.Confinement, cred ipc.Cred, credOK bool, runtimeGIDs []int) []string { + var out []string + add := func(code string) { + if !slices.Contains(out, code) && len(out) < maxReasons { + out = append(out, code) + } + } + switch { + case c == nil: + add(confine.OldClient) + case !c.Confined: + for _, r := range c.Reasons { + if confine.Known(r) && r != confine.RuntimeGroup && r != confine.OldClient { + add(r) + } + } + if len(out) == 0 { + // Unconfined by its own word, without a reason we know. + add(confine.InContainer) + } + } + if credOK && cred.HasGroup(runtimeGIDs) { + add(confine.RuntimeGroup) + } + return out +} + +// unconfinedAllowed reports whether the policy in force serves an +// unconfined agent; when not, why is "" for a profile without +// unconfined = true, else why it may not have it. +func (s *Server) unconfinedAllowed() (ok bool, why string) { + switch { + case s.managed.RequireConfinedAgent(): + return false, "the company's managed configuration requires a confined agent" + case s.profile.Production: + return false, "unconfined is never allowed on a production profile" + } + return s.profile.Unconfined, "" +} + +// unconfinedMessage is the client's error text of a refusal. +func unconfinedMessage(reasons []string, why string) string { + parts := make([]string, len(reasons)) + for i, r := range reasons { + parts[i] = r + ": " + confine.Text(r) + } + msg := "refused: this agent does not run confined (" + strings.Join(parts, "; ") + "); run it inside lea" + if why == "" { + return msg + ", or ask the human to set unconfined = true on this non-production profile" + } + return msg + " (" + why + ")" +} + +// checkConfinement decides the request req of an unconfined or not yet +// greeted connection: nil serves it, else the refusal. +func (s *Server) checkConfinement(ctx context.Context, req ipc.Request) *ipc.Response { + c := connFrom(ctx) + if c == nil || req.Method == ipc.MethodHello { + return nil + } + if !c.helloed { + r := ErrResp(req.ID, ipc.CodeInvalidRequest, "hello first: the console serves a connection once its hello is accepted") + return &r + } + if !c.unconfined { + return nil + } + if ok, why := s.unconfinedAllowed(); !ok { + c.helloed = false + return s.refuseUnconfined(ctx, req, c.reasons, why) + } + return nil +} + +// refuseUnconfined audits and answers the refusal of an unconfined agent. +func (s *Server) refuseUnconfined(ctx context.Context, req ipc.Request, reasons []string, why string) *ipc.Response { + msg := unconfinedMessage(reasons, why) + if why == "" { + why = "the profile does not set unconfined = true" + } + _ = s.record(ctx, audit.Base{Event: audit.EventRefused, Decision: DecisionRefusedUnconfined, Error: why, + Unconfined: true, UnconfinedReasons: reasons}) + s.println(Paint.Fail("refused an unconfined agent (" + strings.Join(reasons, ", ") + "): " + why)) + r := ErrResp(req.ID, ipc.CodeUnconfined, msg) + return &r +} + +// greet takes the confinement decision of a hello whose protocol is +// accepted: nil serves the connection, else the refusal. +func (s *Server) greet(ctx context.Context, req ipc.Request, p ipc.HelloParams) *ipc.Response { + c := connFrom(ctx) + if c == nil { + // Not a socket connection (an in-process call): nothing to decide. + return nil + } + cred, credOK := PeerFrom(ctx) + reasons := confinementReasons(p.Confinement, cred, credOK, s.cfg.RuntimeGIDs) + c.helloed, c.unconfined, c.reasons = false, len(reasons) > 0, reasons + if !c.unconfined { + c.helloed = true + return nil + } + if ok, why := s.unconfinedAllowed(); !ok { + return s.refuseUnconfined(ctx, req, reasons, why) + } + c.helloed = true + s.println(Paint.Fail(UnconfinedBanner + " (" + strings.Join(reasons, ", ") + ")")) + return nil +} + +// stampUnconfined marks b as a record of an unconfined connection. +func stampUnconfined(ctx context.Context, b *audit.Base) { + if u, reasons := unconfinedOf(ctx); u { + b.Unconfined, b.UnconfinedReasons = true, reasons + } +} + +// ParseGIDs parses --runtime-gids: comma-separated gids ("" is none). +func ParseGIDs(v string) ([]int, error) { + var out []int + for _, f := range strings.Split(v, ",") { + if f == "" && v == "" { + continue + } + n, err := strconv.ParseUint(strings.TrimSpace(f), 10, 31) + if err != nil { + return nil, fmt.Errorf("%w: --runtime-gids is not a comma-separated list of gids", ErrConfig) + } + out = append(out, int(n)) + } + return out, nil +} diff --git a/console/confine_test.go b/console/confine_test.go new file mode 100644 index 0000000..c326434 --- /dev/null +++ b/console/confine_test.go @@ -0,0 +1,260 @@ +//go:build unix + +package console + +import ( + "context" + "errors" + "os" + "strings" + "testing" + + "github.com/DavidGodefroid/lockkit/confine" + "github.com/DavidGodefroid/lockkit/ipc" + "github.com/DavidGodefroid/lockkit/managed" +) + +// The tests' Run consoles take no runtime gid of the machine: a CI runner +// is in the docker group (TestRunRuntimeGIDs covers them). +func init() { hostRuntimeGIDs = func() []int { return nil } } + +var ( + confined = &ipc.Confinement{Confined: true} + hostClient = &ipc.Confinement{Reasons: []string{confine.InContainer, confine.NoHostRuntime}} +) + +// conn is a socket connection's context from a peer of the test's uid +// holding groups. +func conn(groups ...int) context.Context { + return withConn(WithPeer(context.Background(), ipc.Cred{UID: os.Getuid(), GID: os.Getgid(), PID: 1, Groups: groups})) +} + +func hello(t *testing.T, h *harness, ctx context.Context, c *ipc.Confinement) ipc.Response { + t.Helper() + return h.call(t, ctx, ipc.MethodHello, ipc.HelloParams{ProtocolMajor: ipc.ProtocolMajor, Client: "lockmq", Confinement: c}) +} + +func unconfinedUAT() fakePolicy { + p := uat() + p.Base.Unconfined = true + return p +} + +func TestConfinedServed(t *testing.T) { + h := newHarness(t, uat(), nil) + ctx := conn() + if r := hello(t, h, ctx, confined); r.Error != nil { + t.Fatalf("hello: %+v", r.Error) + } + if r := h.call(t, ctx, ipc.MethodStatus, nil); r.Error != nil { + t.Fatalf("status: %+v", r.Error) + } +} + +// Unconfined with the default profile: CodeUnconfined naming the reasons, +// audited refused-unconfined, and the connection stays refused. +func TestUnconfinedRefusedByDefault(t *testing.T) { + h := newHarness(t, uat(), nil) + ctx := conn() + r := hello(t, h, ctx, hostClient) + if r.Error == nil || r.Error.Code != ipc.CodeUnconfined { + t.Fatalf("hello: %+v", r) + } + for _, want := range []string{"refused: this agent does not run confined (in_container: ", "no_host_runtime: ", + "run it inside lea, or ask the human to set unconfined = true on this non-production profile"} { + if !strings.Contains(r.Error.Message, want) { + t.Errorf("message %q lacks %q", r.Error.Message, want) + } + } + rec := h.lastRecord(t) + if rec["decision"] != DecisionRefusedUnconfined || rec["unconfined"] != true || rec["event"] != "refused" { + t.Fatalf("audit %v", rec) + } + if rs := rec["unconfined_reasons"].([]any); len(rs) != 2 || rs[0] != confine.InContainer { + t.Fatalf("reasons %v", rs) + } + if r := h.call(t, ctx, ipc.MethodStatus, nil); r.Error == nil { + t.Fatal("a refused connection was served") + } +} + +// unconfined = true on a non-production profile: served, the banner +// printed, every record of the connection marked unconfined. +func TestUnconfinedServedWhenProfileAllows(t *testing.T) { + h := newHarness(t, unconfinedUAT(), nil) + ctx := conn() + if r := hello(t, h, ctx, hostClient); r.Error != nil { + t.Fatalf("hello: %+v", r.Error) + } + if !strings.Contains(h.io.plain(), UnconfinedBanner) { + t.Fatalf("no banner:\n%s", h.io.plain()) + } + h.io.answers = []string{"y"} + before := len(h.records(t)) + h.call(t, ctx, "op.read", map[string]string{"queue": "orders"}) + h.call(t, ctx, ipc.MethodPIIAdd, map[string]string{"pattern": "orders.email"}) + recs := h.records(t)[before:] + if len(recs) == 0 { + t.Fatal("no records") + } + for _, rec := range recs { + if rec["unconfined"] != true || rec["unconfined_reasons"] == nil { + t.Errorf("record of an unconfined connection not marked: %v", rec) + } + } + // A confined connection's records are not marked. + c2 := conn() + hello(t, h, c2, confined) + before = len(h.records(t)) + h.call(t, c2, ipc.MethodPIIAdd, map[string]string{"pattern": "orders.phone"}) + for _, rec := range h.records(t)[before:] { + if _, ok := rec["unconfined"]; ok { + t.Errorf("confined record marked: %v", rec) + } + } +} + +func TestUnconfinedProductionRefusedAtStart(t *testing.T) { + b := &fakeBackend{policy: prod()} + b.policy.Base.Unconfined = true + io := &fakeIO{answers: []string{"y"}, secrets: []string{"pw"}} + err := Run(context.Background(), testProduct, b, Options{Profile: b.policy.Name, Hub: testHub(t), IO: io, StateDir: t.TempDir(), + Isolation: runEnv(t), Harden: func() error { return nil }}) + if !errors.Is(err, ErrConfig) || !strings.Contains(err.Error(), "unconfined is never allowed on a production profile") { + t.Fatalf("Run: %v", err) + } + if io.promptCount() != 0 { + t.Fatalf("prompts %v", io.promptList()) + } +} + +func TestRequireConfinedAgentWins(t *testing.T) { + f, err := managed.Parse([]byte("version = 1\norganisation = \"Example Corp\"\n[family]\nrequire_confined_agent = true\n")) + if err != nil { + t.Fatal(err) + } + h := newHarness(t, unconfinedUAT(), func(c *ServerConfig) { c.Managed = f }) + r := hello(t, h, conn(), hostClient) + if r.Error == nil || r.Error.Code != ipc.CodeUnconfined || !strings.Contains(r.Error.Message, "managed configuration requires a confined agent") { + t.Fatalf("hello: %+v", r) + } + if r := hello(t, h, conn(), confined); r.Error != nil { + t.Fatalf("confined: %+v", r.Error) + } +} + +// A peer holding a runtime gid is unconfined, whatever it reports; its +// primary group counts too. +func TestRuntimeGroupUnconfined(t *testing.T) { + h := newHarness(t, uat(), func(c *ServerConfig) { c.RuntimeGIDs = []int{999} }) + r := hello(t, h, conn(4, 999), confined) + if r.Error == nil || r.Error.Code != ipc.CodeUnconfined || !strings.Contains(r.Error.Message, "runtime_group: ") { + t.Fatalf("hello: %+v", r) + } + h2 := newHarness(t, uat(), func(c *ServerConfig) { c.RuntimeGIDs = []int{os.Getgid()} }) + if r := hello(t, h2, conn(), confined); r.Error == nil { + t.Fatal("primary group in RuntimeGIDs served") + } + if r := hello(t, h, conn(4), confined); r.Error != nil { + t.Fatalf("other groups: %+v", r.Error) + } +} + +func TestOldClientUnconfined(t *testing.T) { + h := newHarness(t, uat(), nil) + r := hello(t, h, conn(), nil) + if r.Error == nil || r.Error.Code != ipc.CodeUnconfined || !strings.Contains(r.Error.Message, "old_client: ") { + t.Fatalf("hello: %+v", r) + } +} + +// Reason codes are the client's word: unknown ones are dropped, and a +// client may not claim the console's own codes. +func TestUnknownReasonsDropped(t *testing.T) { + h := newHarness(t, uat(), nil) + r := hello(t, h, conn(), &ipc.Confinement{Reasons: []string{"\x1b[2Jevil", confine.OldClient}}) + if r.Error == nil || strings.Contains(r.Error.Message, "evil") || strings.Contains(r.Error.Message, "old_client") || + !strings.Contains(r.Error.Message, "in_container") { + t.Fatalf("hello: %+v", r) + } +} + +// (1) On a socket connection no method is served before an accepted hello. +func TestMethodBeforeHelloRefused(t *testing.T) { + h := newHarness(t, unconfinedUAT(), nil) + for _, m := range []string{ipc.MethodStatus, ipc.MethodPIIList, "op.read", ipc.MethodLogout} { + if r := h.call(t, conn(), m, nil); r.Error == nil || r.Error.Code != ipc.CodeInvalidRequest || !strings.Contains(r.Error.Message, "hello first") { + t.Errorf("%s before hello: %+v", m, r) + } + } + if _, ended := h.s.Ended(); ended { + t.Fatal("logout before hello ended the session") + } +} + +// (2) The decision is taken again at every request: a policy that becomes +// production cuts an open unconfined connection. +func TestPolicyFlipCutsUnconfined(t *testing.T) { + h := newHarness(t, unconfinedUAT(), nil) + ctx := conn() + if r := hello(t, h, ctx, hostClient); r.Error != nil { + t.Fatal(r.Error) + } + if r := h.call(t, ctx, ipc.MethodStatus, nil); r.Error != nil { + t.Fatal(r.Error) + } + p := unconfinedUAT() + p.Production = true + h.s.apply(p) + r := h.call(t, ctx, ipc.MethodStatus, nil) + if r.Error == nil || r.Error.Code != ipc.CodeUnconfined || !strings.Contains(r.Error.Message, "never allowed on a production profile") { + t.Fatalf("after the flip: %+v", r) + } + if rec := h.lastRecord(t); rec["decision"] != DecisionRefusedUnconfined { + t.Fatalf("audit %v", rec) + } + // unconfined switched off cuts it too. + h2 := newHarness(t, unconfinedUAT(), nil) + ctx2 := conn() + hello(t, h2, ctx2, hostClient) + h2.s.apply(uat()) + if r := h2.call(t, ctx2, ipc.MethodStatus, nil); r.Error == nil || r.Error.Code != ipc.CodeUnconfined { + t.Fatalf("after unconfined off: %+v", r) + } +} + +func TestParseGIDs(t *testing.T) { + if g, err := ParseGIDs(""); err != nil || g != nil { + t.Fatalf("empty: %v %v", g, err) + } + if g, err := ParseGIDs("999,0"); err != nil || len(g) != 2 || g[0] != 999 || g[1] != 0 { + t.Fatalf("list: %v %v", g, err) + } + for _, bad := range []string{"x", "1,,2", "-1", "1,"} { + if _, err := ParseGIDs(bad); !errors.Is(err, ErrConfig) { + t.Errorf("%q accepted", bad) + } + } + in := HubOptions{RuntimeGIDs: "999,998"} + if a := in.Args(); len(a) != 2 || a[0] != "--runtime-gids" || a[1] != "999,998" || in.Enabled() { + t.Fatalf("args %v enabled %v", a, in.Enabled()) + } +} + +// Run serves with the gids of --runtime-gids and those of the machine. +func TestRunRuntimeGIDs(t *testing.T) { + old := hostRuntimeGIDs + hostRuntimeGIDs = func() []int { return []int{999, 5} } + defer func() { hostRuntimeGIDs = old }() + if g := runtimeGIDs([]int{5, 7}); len(g) != 3 || g[0] != 5 || g[1] != 7 || g[2] != 999 { + t.Fatalf("runtimeGIDs = %v", g) + } + io := &fakeIO{answers: []string{"y"}, secrets: []string{"pw"}} + h := testHub(t) + h.RuntimeGIDs = "x" + err := Run(context.Background(), testProduct, &fakeBackend{policy: uat()}, Options{Profile: "uat", Hub: h, IO: io, StateDir: t.TempDir(), + Isolation: runEnv(t), Harden: func() error { return nil }}) + if !errors.Is(err, ErrConfig) || !strings.Contains(err.Error(), "--runtime-gids") { + t.Fatalf("Run: %v", err) + } +} diff --git a/console/framework_test.go b/console/framework_test.go index 3afef5d..b76ba88 100644 --- a/console/framework_test.go +++ b/console/framework_test.go @@ -64,7 +64,8 @@ func (p fakePolicy) Describe() []string { func (p fakePolicy) Profile() Profile { return Profile{Name: p.Name, Production: p.Production, Where: p.Host + ":5671", Host: p.Host, Port: 5671, DefaultPort: 5671, User: p.Base.User, Credentials: p.Base.Credentials, VaultPath: p.Base.VaultPath, CredentialsTTL: p.Base.CredentialsTTL, - IdleTimeout: p.Base.IdleTimeout, MaxSession: p.Base.MaxSession, TicketLimits: p.Base.TicketLimits()} + IdleTimeout: p.Base.IdleTimeout, MaxSession: p.Base.MaxSession, TicketLimits: p.Base.TicketLimits(), + Unconfined: p.Base.Unconfined} } func uat() fakePolicy { @@ -860,6 +861,13 @@ func runEnv(t *testing.T) *IsolationEnv { } func dialAndCall(t *testing.T, socket, method string, params any) ipc.Response { + t.Helper() + return dialAndCallAs(t, socket, &ipc.Confinement{Confined: true}, method, params) +} + +// dialAndCallAs is dialAndCall from a client reporting conf in its hello +// (sent first unless method is hello). +func dialAndCallAs(t *testing.T, socket string, conf *ipc.Confinement, method string, params any) ipc.Response { t.Helper() var resp ipc.Response deadline := time.Now().Add(5 * time.Second) @@ -867,11 +875,24 @@ func dialAndCall(t *testing.T, socket, method string, params any) ipc.Response { c, err := net.Dial("unix", socket) if err == nil { defer c.Close() + r := bufio.NewReader(c) + if method != ipc.MethodHello { + hp, _ := json.Marshal(ipc.HelloParams{ProtocolMajor: ipc.ProtocolMajor, Client: "test", Confinement: conf}) + if err := ipc.WriteMsg(c, ipc.Request{JSONRPC: "2.0", ID: 1, Method: ipc.MethodHello, Params: hp}); err != nil { + t.Fatal(err) + } + if err := ipc.ReadMsg(r, &resp); err != nil { + t.Fatal(err) + } + if resp.Error != nil { + return resp + } + } raw, _ := json.Marshal(params) - if err := ipc.WriteMsg(c, ipc.Request{JSONRPC: "2.0", ID: 1, Method: method, Params: raw}); err != nil { + if err := ipc.WriteMsg(c, ipc.Request{JSONRPC: "2.0", ID: 2, Method: method, Params: raw}); err != nil { t.Fatal(err) } - if err := ipc.ReadMsg(bufio.NewReader(c), &resp); err != nil { + if err := ipc.ReadMsg(r, &resp); err != nil { t.Fatal(err) } return resp diff --git a/console/hub.go b/console/hub.go index 7cb8b20..77f47c1 100644 --- a/console/hub.go +++ b/console/hub.go @@ -52,6 +52,13 @@ type HubOptions struct { // Home is the lock's home volume, where the instance key lives // (hubclient.InstanceKey, made by `hub-key`); "" is the user's home. Home string + // RuntimeGIDs are the gids, comma-separated, owning a container + // runtime socket of the host (--runtime-gids, written by lox run for a + // containerized console): a peer holding one is unconfined. The + // console adds those of its own machine (confine.RuntimeGIDs), and + // refuses to start on a value that is not a list of gids. Not a hub + // option: Enabled ignores it, and a policy-only console takes it. + RuntimeGIDs string } // Register adds the hub flags to fs. @@ -64,6 +71,7 @@ func (h *HubOptions) Register(fs *flag.FlagSet) { fs.StringVar(&h.FacadeKeysFile, "facade-keys-file", "", "the facade keys this lock pins (JSON, written by lox run): reveals are sealed only to them") fs.StringVar(&h.RequireDevice, "require-device", "", "risk classes (comma-separated) whose approvals must be signed by a pinned device, from any facade") fs.BoolVar(&h.SealClear, "seal-clear", false, "send the clear screen sealed to the pinned devices (end to end; the hub relays ciphertext)") + fs.StringVar(&h.RuntimeGIDs, "runtime-gids", "", "the gids (comma-separated) owning the host's container runtime sockets: a client holding one is unconfined (written by lox run)") } // Args are the flags of h, as Register reads them back: what a product @@ -110,6 +118,13 @@ func (h HubOptions) Args() []string { if h.FacadeKeysFile != "" { out = append(out, "--facade-keys-file", h.FacadeKeysFile) } + if h.RuntimeGIDs != "" { + g := h.RuntimeGIDs + if _, err := ParseGIDs(g); err != nil { + g = refusedValue + } + out = append(out, "--runtime-gids", g) + } return out } @@ -327,6 +342,8 @@ func (a *hubApprover) Submit(ctx context.Context, d Decision) (Pending, error) { // Only a human types a value: a ticket asking for some is never auto // (the hub client gives it its one-use key). t.Flags = ticket.Flags{Production: d.Production, NeverAuto: t.Flags.NeverAuto || d.Screen.NeverAuto || len(h.Inputs) > 0, Retype: d.Retype} + // The facade tells the human the agent does not run confined. + t.Flags.Unconfined, _ = unconfinedOf(ctx) // The screen this console would show: sealed to the pinned devices // only (SubmitClear), never sent as it is. s := d.Screen diff --git a/console/hub_test.go b/console/hub_test.go index a9ad559..44b85ad 100644 --- a/console/hub_test.go +++ b/console/hub_test.go @@ -767,3 +767,59 @@ func TestServerTicketLimitsProductionTypedName(t *testing.T) { t.Fatalf("raise not applied with the typed name: %+v", c.Limits()) } } + +// A ticket of an unconfined connection carries flags.unconfined; one of a +// confined connection does not. +func TestRunHubTicketUnconfined(t *testing.T) { + env := runEnv(t) + home, state := t.TempDir(), t.TempDir() + key, err := hubclient.InstanceKey(home, hubInstance) + if err != nil { + t.Fatal(err) + } + hub := hubtest.New(t, hubInstance, key.Public().(ed25519.PublicKey)) + b := &hubBackend{fakeBackend: fakeBackend{policy: unconfinedUAT()}} + io := &fakeIO{answers: []string{"y"}, secrets: []string{"s3cret"}} + ready := make(chan string, 1) + done := make(chan error, 1) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { + done <- Run(ctx, testProduct, b, Options{Profile: "uat", IO: io, StateDir: state, Isolation: env, + Harden: func() error { return nil }, Quantum: -1, Ready: func(s string) { ready <- s }, + Hub: HubOptions{URL: hub.URL(), KeyFile: writeHubKey(t, hub.Pub), Instance: hubInstance, Home: home}}) + }() + var socket string + select { + case socket = <-ready: + case err := <-done: + t.Fatalf("Run: %v\n%s", err, io.plain()) + case <-time.After(10 * time.Second): + t.Fatal("no socket") + } + if !strings.Contains(io.plain(), UnconfinedBanner) { + t.Fatalf("no banner at start:\n%s", io.plain()) + } + for _, tc := range []struct { + conf *ipc.Confinement + kind ticket.Kind + want bool + }{{&ipc.Confinement{Reasons: []string{"in_container"}}, "", true}, {&ipc.Confinement{Confined: true}, ticket.KindAction, false}} { + params := map[string]any{"hub": true} + if tc.kind != "" { + params["kind"] = tc.kind + } + r := dialAndCallAs(t, socket, tc.conf, "op.write", params) + if r.Error != nil { + t.Fatalf("op.write: %+v", r.Error) + } + raw := hub.Ticket(pendingOf(t, r.Result)["ticket"]) + tk, err := ticket.VerifyTicket(key.Public().(ed25519.PublicKey), raw) + if err != nil || tk.Flags.Unconfined != tc.want { + t.Fatalf("ticket %s: %v", raw, err) + } + if !tc.want && strings.Contains(string(raw), "unconfined") { + t.Fatalf("a confined ticket names unconfined: %s", raw) + } + } +} diff --git a/console/idle_serve_test.go b/console/idle_serve_test.go index 75056cb..7f8bfe3 100644 --- a/console/idle_serve_test.go +++ b/console/idle_serve_test.go @@ -64,7 +64,7 @@ func TestServeStatusPollingEndsOnIdleTimeout(t *testing.T) { clock.advance(time.Minute) method, params := ipc.MethodStatus, any(nil) if i%2 == 1 { - method, params = ipc.MethodHello, ipc.HelloParams{ProtocolMajor: ipc.ProtocolMajor, Client: "lockmq"} + method, params = ipc.MethodHello, ipc.HelloParams{ProtocolMajor: ipc.ProtocolMajor, Client: "lockmq", Confinement: &ipc.Confinement{Confined: true}} } if r := dialAndCall(t, socket, method, params); r.Error != nil { t.Fatalf("%s at minute %d: %+v", method, i+1, r.Error) diff --git a/console/isolation.go b/console/isolation.go index 5b56c9c..3b1a4f2 100644 --- a/console/isolation.go +++ b/console/isolation.go @@ -448,9 +448,11 @@ func PeerFrom(ctx context.Context) (ipc.Cred, bool) { } // StampPeer sets the peer fields of b from the client behind ctx: its uid, -// pid and account name. The process name, chosen by the agent, stays on +// pid and account name, and unconfined with its reasons when the client +// does not run confined. The process name, chosen by the agent, stays on // the screen (PeerText) and out of the audit log. func StampPeer(ctx context.Context, b *audit.Base) { + stampUnconfined(ctx, b) c, ok := PeerFrom(ctx) if !ok { return diff --git a/console/run.go b/console/run.go index 181f468..a4a625e 100644 --- a/console/run.go +++ b/console/run.go @@ -6,12 +6,14 @@ import ( "fmt" "os" "os/signal" + "slices" "strings" "syscall" "time" "github.com/DavidGodefroid/lockkit/audit" "github.com/DavidGodefroid/lockkit/config" + "github.com/DavidGodefroid/lockkit/confine" "github.com/DavidGodefroid/lockkit/kit" "github.com/DavidGodefroid/lockkit/managed" "github.com/DavidGodefroid/lockkit/sanitize" @@ -215,6 +217,13 @@ func Run(ctx context.Context, p kit.Product, b Backend, o Options) error { if cur.Profile().Name != o.Profile { return fmt.Errorf("%w: the backend loaded another profile than --profile names", ErrConfig) } + if err := refuseUnconfinedProduction(cur.Profile()); err != nil { + return err + } + given, err := ParseGIDs(o.Hub.RuntimeGIDs) + if err != nil { + return err + } key := config.ApprovedKey(o.ProjectRoot, o.Profile) // The question the console waits for is kept next to its socket, where // lox attach and lea read it: they attach after it was printed. On a @@ -291,6 +300,9 @@ func Run(ctx context.Context, p kit.Product, b Backend, o Options) error { } pr := approved.Profile() st.profile, st.policy = pr, approved + if err := refuseUnconfinedProduction(pr); err != nil { + return err + } // The start-up refusals of a production profile, applied again by the // server when the policy in force becomes production. refuseProduction := func() error { @@ -334,6 +346,9 @@ func Run(ctx context.Context, p kit.Product, b Backend, o Options) error { } } o.IO.Println(Paint.OK(fmt.Sprintf("profile %s · %s %s", Paint.Bold(pr.Name), where, Paint.Dim("(approved policy)")))) + if pr.Unconfined { + o.IO.Println(Paint.Fail(UnconfinedBanner)) + } // 3. User, credentials and connection; 4. the backend's checks. st.user = pr.User @@ -383,6 +398,7 @@ func Run(ctx context.Context, p kit.Product, b Backend, o Options) error { AllowUnmask: o.AllowUnmask, ShowResults: o.ShowResults, ReconnectPolicy: st.reconnect, Quantum: quantum, PeerAllowed: iso.PeerCheck(), Sanitizer: o.Sanitizer, Refused: refusedFP, RefuseProduction: refuseProduction, Managed: mf, LoadManaged: loadManaged, + RuntimeGIDs: runtimeGIDs(given), }) if err != nil { ln.Close() @@ -796,3 +812,28 @@ func (st *starter) reconnect(ctx context.Context, p Policy) (Session, error) { } return sess, nil } + +// refuseUnconfinedProduction refuses a production profile that sets +// unconfined = true. +func refuseUnconfinedProduction(p Profile) error { + if p.Unconfined && p.Production { + return fmt.Errorf("%w: unconfined is never allowed on a production profile", ErrConfig) + } + return nil +} + +// hostRuntimeGIDs are this machine's runtime gids (confine.RuntimeGIDs); +// tests of this package replace it, a CI runner being in the docker group. +var hostRuntimeGIDs = confine.RuntimeGIDs + +// runtimeGIDs are the gids given (--runtime-gids) and those of this +// machine's runtime sockets. +func runtimeGIDs(given []int) []int { + out := slices.Clone(given) + for _, g := range hostRuntimeGIDs() { + if !slices.Contains(out, g) { + out = append(out, g) + } + } + return out +} diff --git a/console/serve.go b/console/serve.go index 0b0922b..a5d33a5 100644 --- a/console/serve.go +++ b/console/serve.go @@ -187,7 +187,7 @@ func (l *Loop) accept(ctx context.Context, ln net.Listener, jobs chan<- job, wg, wg.Add(1) go func() { defer wg.Done() - serveConn(WithPeer(ctx, cred), c, jobs, inflight) + serveConn(withConn(WithPeer(ctx, cred)), c, jobs, inflight) }() } } diff --git a/console/server.go b/console/server.go index 61bfce4..7e777b6 100644 --- a/console/server.go +++ b/console/server.go @@ -72,6 +72,9 @@ type ServerConfig struct { // PeerAllowed decides which clients are served; nil: the console's own // account. PeerAllowed func(ipc.Cred) bool + // RuntimeGIDs are the groups owning a container runtime socket: a peer + // holding one is unconfined (runtime_group), whatever it reports. + RuntimeGIDs []int // Sanitizer scrubs error text; nil is sanitize.New(). Sanitizer *sanitize.Sanitizer // Refused is the fingerprint of a loosening the human refused at start, @@ -301,9 +304,12 @@ func (s *Server) Loop() *Loop { // client polling status, hello or the console's other methods never keeps // an unattended console open. func (s *Server) Handle(ctx context.Context, req ipc.Request) ipc.Response { + if r := s.checkConfinement(ctx, req); r != nil { + return *r + } switch req.Method { case ipc.MethodHello: - return s.hello(req) + return s.hello(ctx, req) case ipc.MethodStatus: if sa, ok := s.cfg.Backend.(StatusAnswerer); ok { return OKResp(req.ID, sa.StatusAnswer(s.consoleStatus(), s.sess)) @@ -370,7 +376,7 @@ func Decode(req ipc.Request, v any) *ipc.Response { return nil } -func (s *Server) hello(req ipc.Request) ipc.Response { +func (s *Server) hello(ctx context.Context, req ipc.Request) ipc.Response { var p ipc.HelloParams if r := Decode(req, &p); r != nil { return *r @@ -380,6 +386,9 @@ func (s *Server) hello(req ipc.Request) ipc.Response { "protocol mismatch: client speaks %d, console speaks %d; use the same %s version on both sides", p.ProtocolMajor, ipc.ProtocolMajor, s.cfg.Product.Name)) } + if r := s.greet(ctx, req, p); r != nil { + return *r + } return OKResp(req.ID, ipc.HelloResult{ProtocolMajor: ipc.ProtocolMajor, ConsoleVersion: s.cfg.Product.Version, Profile: s.profile.Name}) } diff --git a/ipc/listen.go b/ipc/listen.go index ec2e022..154cbd1 100644 --- a/ipc/listen.go +++ b/ipc/listen.go @@ -9,9 +9,28 @@ import ( ) // Cred is what the kernel says about the process at the other end of a -// socket. PID is -1 when the platform does not report it. +// socket. PID is -1 when the platform does not report it. Groups are the +// peer's supplementary groups (Linux SO_PEERGROUPS, macOS cr_groups); nil +// when the platform does not report them. type Cred struct { UID, GID, PID int + Groups []int +} + +// HasGroup reports whether c's primary or supplementary groups hold one +// of gids. +func (c Cred) HasGroup(gids []int) bool { + for _, g := range gids { + if g == c.GID { + return true + } + for _, h := range c.Groups { + if g == h { + return true + } + } + } + return false } // ErrAlreadyRunning means a live console already listens on the socket. diff --git a/ipc/methods.go b/ipc/methods.go index 7c7ffb0..55cb2a5 100644 --- a/ipc/methods.go +++ b/ipc/methods.go @@ -28,6 +28,9 @@ const ( // for clients of older consoles: no lockkit console answers it since // the standalone console is gone (v0.10.0). CodeWithdrawn = -32008 + // CodeUnconfined: the agent does not run confined and the profile + // does not accept it (lockkit#133); its reasons are in the message. + CodeUnconfined = -32009 CodeParseError = -32700 CodeInvalidRequest = -32600 @@ -50,9 +53,22 @@ type Requester struct { } // HelloParams opens a session; Client is a free-form name and version. +// Confinement is the client's self-check (package confine); a hello +// without it comes from an older client, which the console counts as +// unconfined. type HelloParams struct { - ProtocolMajor int `json:"protocol_major"` - Client string `json:"client,omitempty"` + ProtocolMajor int `json:"protocol_major"` + Client string `json:"client,omitempty"` + Confinement *Confinement `json:"confinement,omitempty"` +} + +// Confinement is the client's report of its containment: confined when +// every check of confine.Check holds, else the codes of those that failed. +// It is the agent's word: the console adds what the kernel says of the +// peer (its groups) and decides. +type Confinement struct { + Confined bool `json:"confined"` + Reasons []string `json:"reasons,omitempty"` } // HelloResult answers hello. diff --git a/ipc/peer_darwin.go b/ipc/peer_darwin.go index 356af68..fbadc8a 100644 --- a/ipc/peer_darwin.go +++ b/ipc/peer_darwin.go @@ -46,8 +46,12 @@ func PeerCred(c net.Conn) (Cred, error) { return Cred{}, fmt.Errorf("ipc: peer check: %w", cerr) } gid := -1 + var groups []int if cred.Ngroups > 0 { gid = int(cred.Groups[0]) } - return Cred{UID: int(cred.Uid), GID: gid, PID: pid}, nil + for i := 0; i < int(cred.Ngroups) && i < len(cred.Groups); i++ { + groups = append(groups, int(cred.Groups[i])) + } + return Cred{UID: int(cred.Uid), GID: gid, PID: pid, Groups: groups}, nil } diff --git a/ipc/peer_groups_test.go b/ipc/peer_groups_test.go new file mode 100644 index 0000000..2091ad8 --- /dev/null +++ b/ipc/peer_groups_test.go @@ -0,0 +1,48 @@ +//go:build linux || darwin + +package ipc + +import ( + "net" + "os" + "slices" + "testing" + + "golang.org/x/sys/unix" +) + +// TestPeerCredGroups: PeerCred reports the peer's supplementary groups, +// here the process's own (a socketpair connects it to itself). +func TestPeerCredGroups(t *testing.T) { + fds, err := unix.Socketpair(unix.AF_UNIX, unix.SOCK_STREAM, 0) + if err != nil { + t.Fatal(err) + } + f := os.NewFile(uintptr(fds[0]), "a") + defer f.Close() + unix.Close(fds[1]) + c, err := net.FileConn(f) + if err != nil { + t.Fatal(err) + } + defer c.Close() + cred, err := PeerCred(c) + if err != nil { + t.Fatal(err) + } + want, err := os.Getgroups() + if err != nil { + t.Fatal(err) + } + for _, g := range want { + if !slices.Contains(cred.Groups, g) { + t.Errorf("group %d missing from %v", g, cred.Groups) + } + } + if cred.UID != os.Getuid() || !cred.HasGroup([]int{os.Getgid()}) { + t.Errorf("cred %+v", cred) + } + if cred.HasGroup([]int{-5}) { + t.Error("HasGroup of a gid it does not hold") + } +} diff --git a/ipc/peer_linux.go b/ipc/peer_linux.go index 3c7a04b..cc1102d 100644 --- a/ipc/peer_linux.go +++ b/ipc/peer_linux.go @@ -6,6 +6,7 @@ import ( "fmt" "net" "os" + "unsafe" "golang.org/x/sys/unix" ) @@ -32,14 +33,43 @@ func PeerCred(c net.Conn) (Cred, error) { return Cred{}, fmt.Errorf("ipc: peer check: %w", err) } var cred *unix.Ucred + var groups []int var cerr error if err := raw.Control(func(fd uintptr) { cred, cerr = unix.GetsockoptUcred(int(fd), unix.SOL_SOCKET, unix.SO_PEERCRED) + if cerr == nil { + groups, cerr = peerGroups(int(fd)) + } }); err != nil { return Cred{}, fmt.Errorf("ipc: peer check: %w", err) } if cerr != nil { return Cred{}, fmt.Errorf("ipc: peer check: %w", cerr) } - return Cred{UID: int(cred.Uid), GID: int(cred.Gid), PID: int(cred.Pid)}, nil + return Cred{UID: int(cred.Uid), GID: int(cred.Gid), PID: int(cred.Pid), Groups: groups}, nil +} + +// peerGroups reads SO_PEERGROUPS: the peer's supplementary groups as the +// kernel recorded them at connect. The buffer grows when the kernel says +// it is too small (ERANGE, with the length it needs). +func peerGroups(fd int) ([]int, error) { + n := 64 + for { + buf := make([]uint32, n) + size := uint32(len(buf) * 4) + _, _, errno := unix.Syscall6(unix.SYS_GETSOCKOPT, uintptr(fd), unix.SOL_SOCKET, unix.SO_PEERGROUPS, + uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&size)), 0) + if errno == unix.ERANGE && int(size/4) > n && n < 1<<16 { + n = int(size / 4) + continue + } + if errno != 0 { + return nil, errno + } + out := make([]int, 0, size/4) + for _, g := range buf[:size/4] { + out = append(out, int(g)) + } + return out, nil + } } diff --git a/ticket/ticket.go b/ticket/ticket.go index 7f2a816..098507a 100644 --- a/ticket/ticket.go +++ b/ticket/ticket.go @@ -57,6 +57,10 @@ type Flags struct { NeverAuto bool `json:"never_auto"` // Retype, when set, is the answer that asks the lock to retype values. Retype string `json:"retype"` + // Unconfined: the agent behind the request does not run confined + // (lockkit#133); the facade says so. Omitted when false, so that a hub + // that does not know it refuses only the tickets that carry it. + Unconfined bool `json:"unconfined,omitempty"` } // Screen is the approval screen, masked by the lock before it leaves the diff --git a/ticket/unconfined_test.go b/ticket/unconfined_test.go new file mode 100644 index 0000000..ef856ec --- /dev/null +++ b/ticket/unconfined_test.go @@ -0,0 +1,36 @@ +package ticket + +import ( + "errors" + "testing" +) + +// TestFlagsUnconfinedOldHub: flags.unconfined is omitted when false, so a +// hub built before it (whose Flags lacks the member) still takes every +// confined ticket and refuses an unconfined one (fail closed). +func TestFlagsUnconfinedOldHub(t *testing.T) { + type oldFlags struct { + Production bool `json:"production"` + NeverAuto bool `json:"never_auto"` + Retype string `json:"retype"` + } + confined, err := Canonical(Flags{Production: true}) + if err != nil { + t.Fatal(err) + } + var o oldFlags + if err := decodeStrict(confined, &o); err != nil || !o.Production { + t.Fatalf("an old hub refuses a confined ticket's flags: %v", err) + } + unconfined, err := Canonical(Flags{Unconfined: true}) + if err != nil { + t.Fatal(err) + } + if err := decodeStrict(unconfined, &o); !errors.Is(err, ErrInvalid) { + t.Fatalf("an old hub takes an unconfined ticket's flags: %v", err) + } + var n Flags + if err := decodeStrict(unconfined, &n); err != nil || !n.Unconfined { + t.Fatalf("this hub: %+v, %v", n, err) + } +}