Skip to content

An open-source, faster Devin alternative

TypeScript

fix(deploy): isolate Flue guest privileges

Igor Zalutski675f8abd7f28
diff --git a/ci/flue-builder-substrate-probe.py b/ci/flue-builder-substrate-probe.py
index 73e310d9..510c4edf 100755
--- a/ci/flue-builder-substrate-probe.py
+++ b/ci/flue-builder-substrate-probe.py
@@ -251,13 +251,6 @@ class LiveProbe:
f"{label} failed with exit {exit_code}, not a curl connection refusal/timeout"
)
- @staticmethod
- def expect_sudo_denied(response: dict[str, Any]) -> None:
- if response["exitCode"] != 1:
- raise ProbeError(
- "runtime `sudo -n true` did not return the expected policy-denied exit 1"
- )
-
@staticmethod
def curl_args(url: str) -> list[str]:
return [
@@ -281,17 +274,15 @@ class LiveProbe:
"/opt/opencomputer/bin/verify-flue-builder-runtime",
),
)
- sudo = self.exec(
- sandbox_id,
- "/usr/bin/sudo",
- ["-n", "/usr/bin/true"],
- )
- self.expect_sudo_denied(sudo)
javascript = r"""
const cp = require("child_process");
const fs = require("fs");
const run = (cmd, args) => cp.execFileSync(cmd, args, {encoding: "utf8"}).trim();
+const endpointPaths = [
+ "/dev/virtio-ports/agent", "/dev/vport0p1", "/dev/vport1p1", "/dev/vport2p1",
+ "/tmp/osb-agent.sock"
+];
const result = {
nodeVersion: process.versions.node,
npmVersion: run("/usr/local/bin/npm", ["--version"]),
@@ -299,6 +290,8 @@ const result = {
ocSha256: run("/usr/bin/sha256sum", ["/opt/opencomputer/bin/oc"]).split(/\s+/)[0],
gitVersion: run("/usr/bin/git", ["--version"]),
runtimeUid: process.getuid(),
+ runtimeGid: process.getgid(),
+ runtimeGroups: process.getgroups().sort((a, b) => a - b),
nodeUid: fs.statSync("/opt/opencomputer/node-v22.19.0/bin/node").uid,
nodeMode: fs.statSync("/opt/opencomputer/node-v22.19.0/bin/node").mode & 0o777,
ocUid: fs.statSync("/opt/opencomputer/bin/oc").uid,
@@ -307,6 +300,11 @@ const result = {
verifierMode: fs.statSync("/opt/opencomputer/bin/verify-flue-builder-runtime").mode & 0o777,
attestationUid: fs.statSync("/opt/opencomputer/agent-build-snapshot.json").uid,
attestationMode: fs.statSync("/opt/opencomputer/agent-build-snapshot.json").mode & 0o777,
+ sudoPresent: fs.existsSync("/usr/bin/sudo") || fs.existsSync("/bin/sudo"),
+ agentEndpoints: endpointPaths.filter((path) => fs.existsSync(path)).map((path) => {
+ const stat = fs.statSync(path);
+ return {path, uid: stat.uid, mode: stat.mode & 0o777};
+ }),
installerRemoved: !fs.existsSync("/tmp/opencomputer-flue-builder-install.sh"),
attestation: JSON.parse(fs.readFileSync("/opt/opencomputer/agent-build-snapshot.json", "utf8"))
};
@@ -325,6 +323,8 @@ process.stdout.write(JSON.stringify(result));
"npmVersion": attestation["npm"]["version"],
"ocSha256": attestation["oc"]["binarySha256"],
"runtimeUid": attestation["security"]["runtimeUid"],
+ "runtimeGid": attestation["security"]["runtimeGid"],
+ "runtimeGroups": [attestation["security"]["runtimeGid"]],
"nodeUid": 0,
"nodeMode": 0o755,
"ocUid": 0,
@@ -333,6 +333,7 @@ process.stdout.write(JSON.stringify(result));
"verifierMode": 0o555,
"attestationUid": 0,
"attestationMode": 0o444,
+ "sudoPresent": False,
"attestation": attestation,
}
for key, value in expected.items():
@@ -345,6 +346,117 @@ process.stdout.write(JSON.stringify(result));
raise ProbeError("builder snapshot is missing git")
if observed.get("installerRemoved") is not True:
raise ProbeError("builder installer was left in the runtime snapshot")
+ endpoints = observed.get("agentEndpoints")
+ if not isinstance(endpoints, list):
+ raise ProbeError("builder endpoint attestation is invalid")
+ for endpoint in endpoints:
+ if (
+ not isinstance(endpoint, dict)
+ or endpoint.get("uid") != 0
+ or endpoint.get("mode") != 0o600
+ ):
+ raise ProbeError("a guest agent transport node is accessible to repository code")
+
+ self.prove_guest_agent_isolation(sandbox_id)
+
+ def prove_guest_agent_isolation(self, sandbox_id: str) -> None:
+ # osb-agent is PID 1 and its unauthenticated RPC surface includes root
+ # exec, root file writes, and binary upgrade. This adversarial probe
+ # runs as uid 1000. It sends an HTTP/2 client preface to guest-local
+ # AF_VSOCK/Unix endpoints and fails if the root gRPC server answers;
+ # it also attempts to open every known virtio-serial agent device.
+ python = r'''
+import array
+import fcntl
+import glob
+import json
+import os
+import socket
+import sys
+
+HTTP2_PREFACE = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
+EMPTY_SETTINGS = b"\x00\x00\x00\x04\x00\x00\x00\x00\x00"
+failures = []
+checked = []
+
+def root_grpc_answered(sock):
+ sock.settimeout(1.0)
+ sock.sendall(HTTP2_PREFACE + EMPTY_SETTINGS)
+ try:
+ return bool(sock.recv(9))
+ except (ConnectionError, OSError, TimeoutError):
+ return False
+
+if hasattr(socket, "AF_VSOCK"):
+ cids = {getattr(socket, "VMADDR_CID_LOCAL", 1)}
+ try:
+ values = array.array("I", [0])
+ with open("/dev/vsock", "rb", buffering=0) as device:
+ fcntl.ioctl(device.fileno(), 0x7B9, values, True)
+ cids.add(values[0])
+ except OSError:
+ pass
+ for cid in sorted(cids):
+ checked.append(f"vsock:{cid}:1024")
+ client = socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM)
+ client.settimeout(1.0)
+ try:
+ client.connect((cid, 1024))
+ if root_grpc_answered(client):
+ failures.append(f"vsock:{cid}:1024")
+ except OSError:
+ pass
+ finally:
+ client.close()
+
+devices = sorted(set(
+ glob.glob("/dev/virtio-ports/agent")
+ + glob.glob("/dev/vport0p1")
+ + glob.glob("/dev/vport1p1")
+ + glob.glob("/dev/vport2p1")
+))
+for path in devices:
+ checked.append(path)
+ try:
+ descriptor = os.open(path, os.O_RDWR | os.O_NONBLOCK)
+ except OSError:
+ continue
+ else:
+ os.close(descriptor)
+ failures.append(path)
+
+unix_path = "/tmp/osb-agent.sock"
+if os.path.exists(unix_path):
+ checked.append(unix_path)
+ client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ client.settimeout(1.0)
+ try:
+ client.connect(unix_path)
+ if root_grpc_answered(client):
+ failures.append(unix_path)
+ except OSError:
+ pass
+ finally:
+ client.close()
+
+print(json.dumps({"checked": checked, "failures": failures}, sort_keys=True))
+if failures:
+ sys.exit(42)
+'''.strip()
+ response = self.exec(
+ sandbox_id,
+ "/usr/bin/python3",
+ ["-c", python],
+ timeout=15,
+ )
+ if response["exitCode"] != 0:
+ raise ProbeError("repository code reached a root guest-agent control transport")
+ try:
+ result = json.loads(str(response.get("stdout", "")))
+ except json.JSONDecodeError as exc:
+ raise ProbeError("guest-agent isolation probe returned invalid JSON") from exc
+ if not isinstance(result.get("checked"), list) or result.get("failures") != []:
+ raise ProbeError("guest-agent isolation probe returned an invalid result")
def prove_control_paths(self, sandbox_id: str) -> None:
private = self.expect_success(
diff --git a/ci/test_flue_builder_substrate_probe.py b/ci/test_flue_builder_substrate_probe.py
index 12585c91..b549616f 100644
--- a/ci/test_flue_builder_substrate_probe.py
+++ b/ci/test_flue_builder_substrate_probe.py
@@ -26,7 +26,10 @@ class SubstrateProbeTest(unittest.TestCase):
{
"runtimeUser": "sandbox",
"runtimeUid": 1000,
- "sudoPolicy": "denied",
+ "runtimeGid": 1000,
+ "supplementaryGroups": [],
+ "sudoPolicy": "binary-removed",
+ "agentControl": "host-only",
"toolchainOwner": "root",
"workspace": "/workspace",
"workspaceWritable": True,
@@ -108,11 +111,22 @@ class SubstrateProbeTest(unittest.TestCase):
with self.subTest(exit_code=exit_code), self.assertRaises(PROBE.ProbeError):
PROBE.LiveProbe.expect_transport_block("target", {"exitCode": exit_code})
- def test_runtime_sudo_must_be_policy_denied(self) -> None:
- PROBE.LiveProbe.expect_sudo_denied({"exitCode": 1})
- for exit_code in (0, 2, 126, 127):
- with self.subTest(exit_code=exit_code), self.assertRaises(PROBE.ProbeError):
- PROBE.LiveProbe.expect_sudo_denied({"exitCode": exit_code})
+ def test_guest_agent_isolation_requires_adversarial_probe_success(self) -> None:
+ live = PROBE.LiveProbe.__new__(PROBE.LiveProbe)
+ live.exec = mock.Mock(
+ return_value={"exitCode": 0, "stdout": '{"checked":["vsock:1:1024"],"failures":[]}'}
+ )
+ live.prove_guest_agent_isolation("sb-test")
+ command = live.exec.call_args.args
+ self.assertEqual(command[:2], ("sb-test", "/usr/bin/python3"))
+ self.assertIn("HTTP2_PREFACE", command[2][1])
+
+ live.exec.return_value = {
+ "exitCode": 42,
+ "stdout": '{"checked":["vsock:1:1024"],"failures":["vsock:1:1024"]}',
+ }
+ with self.assertRaises(PROBE.ProbeError):
+ live.prove_guest_agent_isolation("sb-test")
def test_create_body_is_allowlisted_and_final_topology_is_explicit(self) -> None:
live = PROBE.LiveProbe.__new__(PROBE.LiveProbe)
diff --git a/cmd/agent/listen_linux.go b/cmd/agent/listen_linux.go
index 06f52a8e..162d6a1b 100644
--- a/cmd/agent/listen_linux.go
+++ b/cmd/agent/listen_linux.go
@@ -56,6 +56,11 @@ func listenPortForPTY(port uint32) (net.Listener, error) {
if err != nil {
return nil, fmt.Errorf("pty unix listen port %d: %w", port, err)
}
+ if err := restrictAgentEndpoint(sockPath); err != nil {
+ lis.Close()
+ os.Remove(sockPath)
+ return nil, err
+ }
log.Printf("agent: PTY data listening on %s", sockPath)
return lis, nil
}
@@ -79,6 +84,10 @@ func listenVirtioSerial(path string) (net.Listener, error) {
if err != nil {
return nil, fmt.Errorf("open virtio-serial %s: %w", path, err)
}
+ if err := restrictAgentEndpoint(path); err != nil {
+ f.Close()
+ return nil, err
+ }
// Mark CLOEXEC so the fd is closed on agent re-exec (upgrade).
// Without this, syscall.Exec inherits the fd, the host never sees the
@@ -284,7 +293,7 @@ func (a vsockAddr) String() string { return fmt.Sprintf("vsock(%d:%d)", a.cid,
func (l *vsockListener) Accept() (net.Conn, error) {
for {
- nfd, _, err := unix.Accept(l.fd)
+ nfd, remote, err := unix.Accept(l.fd)
if err != nil {
select {
case <-l.closed:
@@ -293,6 +302,14 @@ func (l *vsockListener) Accept() (net.Conn, error) {
}
return nil, fmt.Errorf("vsock accept: %w", err)
}
+ remoteVM, ok := remote.(*unix.SockaddrVM)
+ if !ok || !isTrustedAgentVsockPeer(remoteVM.CID) {
+ // The agent RPC surface includes root exec, root file writes, and
+ // binary upgrade. It is intentionally reachable only from CID 2,
+ // the hypervisor host. In-guest AF_VSOCK loopback is untrusted.
+ unix.Close(nfd)
+ continue
+ }
return newRawVsockConn(nfd), nil
}
}
@@ -338,6 +355,11 @@ func listenUnix(vsockErr error) (net.Listener, error) {
if err != nil {
return nil, fmt.Errorf("unix listen: %w (vsock: %v)", err, vsockErr)
}
+ if err := restrictAgentEndpoint(sockPath); err != nil {
+ lis.Close()
+ os.Remove(sockPath)
+ return nil, err
+ }
log.Printf("agent: listening on %s (vsock not available: %v)", sockPath, vsockErr)
return lis, nil
}
diff --git a/cmd/agent/listen_other.go b/cmd/agent/listen_other.go
index 4a044ddc..6edb1c71 100644
--- a/cmd/agent/listen_other.go
+++ b/cmd/agent/listen_other.go
@@ -18,6 +18,11 @@ func listenVsock() (net.Listener, error) {
if err != nil {
return nil, err
}
+ if err := restrictAgentEndpoint(sockPath); err != nil {
+ lis.Close()
+ os.Remove(sockPath)
+ return nil, err
+ }
log.Printf("agent: listening on %s (non-Linux, vsock not available)", sockPath)
return lis, nil
}
@@ -31,6 +36,11 @@ func listenPortForPTY(port uint32) (net.Listener, error) {
if err != nil {
return nil, fmt.Errorf("pty unix listen port %d: %w", port, err)
}
+ if err := restrictAgentEndpoint(sockPath); err != nil {
+ lis.Close()
+ os.Remove(sockPath)
+ return nil, err
+ }
log.Printf("agent: PTY data listening on %s (vsock not available)", sockPath)
return lis, nil
}
diff --git a/cmd/agent/transport_security.go b/cmd/agent/transport_security.go
new file mode 100644
index 00000000..438cf85e
--- /dev/null
+++ b/cmd/agent/transport_security.go
@@ -0,0 +1,29 @@
+package main
+
+import (
+ "fmt"
+ "os"
+)
+
+const (
+ // Linux reserves CID 2 for the host side of an AF_VSOCK connection.
+ // Guest-local callers use CID 1 (VMADDR_CID_LOCAL) or the guest's own
+ // transport CID and must never reach the root agent RPC surface.
+ vsockHostCID = uint32(2)
+
+ agentEndpointMode = os.FileMode(0600)
+)
+
+func isTrustedAgentVsockPeer(cid uint32) bool {
+ return cid == vsockHostCID
+}
+
+// restrictAgentEndpoint makes a guest-side transport node usable only by the
+// root agent. Host control continues through the already-open virtio-serial
+// device or the host-owned side of the Unix socket.
+func restrictAgentEndpoint(path string) error {
+ if err := os.Chmod(path, agentEndpointMode); err != nil {
+ return fmt.Errorf("restrict agent endpoint %s: %w", path, err)
+ }
+ return nil
+}
diff --git a/cmd/agent/transport_security_test.go b/cmd/agent/transport_security_test.go
new file mode 100644
index 00000000..712e09da
--- /dev/null
+++ b/cmd/agent/transport_security_test.go
@@ -0,0 +1,43 @@
+package main
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestIsTrustedAgentVsockPeerAllowsOnlyHost(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ cid uint32
+ trusted bool
+ }{
+ {name: "local transport", cid: 1, trusted: false},
+ {name: "host", cid: 2, trusted: true},
+ {name: "guest transport", cid: 3, trusted: false},
+ {name: "wildcard", cid: ^uint32(0), trusted: false},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ if got := isTrustedAgentVsockPeer(test.cid); got != test.trusted {
+ t.Fatalf("isTrustedAgentVsockPeer(%d) = %v, want %v", test.cid, got, test.trusted)
+ }
+ })
+ }
+}
+
+func TestRestrictAgentEndpointRemovesGuestAccess(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "agent-endpoint")
+ if err := os.WriteFile(path, nil, 0666); err != nil {
+ t.Fatal(err)
+ }
+ if err := restrictAgentEndpoint(path); err != nil {
+ t.Fatal(err)
+ }
+ info, err := os.Stat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := info.Mode().Perm(); got != agentEndpointMode {
+ t.Fatalf("endpoint mode = %#o, want %#o", got, agentEndpointMode)
+ }
+}
diff --git a/deploy/flue-builder/README.md b/deploy/flue-builder/README.md
index e3d89460..966407dd 100644
--- a/deploy/flue-builder/README.md
+++ b/deploy/flue-builder/README.md
@@ -4,14 +4,16 @@ This directory owns the immutable runtime used by the managed Flue repository
builder. It is an internal deployment asset, not a customer-selectable image.
Repository code runs here with public-only networking and without GitHub,
OpenComputer, R2, Cloudflare, WfP, or coordinator credentials. It runs as uid
-1000 with no passwordless sudo; the pinned toolchain is root-owned while
-`/workspace` remains writable.
+1000 with no `sudo` binary or supplementary groups; the pinned toolchain is
+root-owned while `/workspace` remains writable. The root guest-agent control
+transport remains available to the trusted host but is unreachable from
+repository processes inside the guest.
## Pinned coordinate
`coordinate.json` is the reviewed logical coordinate. It pins:
-- snapshot name `flue-build-node22-19-0-oc-c39b315-r1` (never reuse it for a
+- snapshot name `flue-build-node22-19-0-oc-c39b315-r2` (never reuse it for a
different recipe or checkpoint);
- Ubuntu 22.04 / x86-64 platform assertion;
- Node 22.19.0 and its upstream archive digest;
@@ -21,8 +23,9 @@ OpenComputer, R2, Cloudflare, WfP, or coordinator credentials. It runs as uid
- the reproducible Linux/amd64 `oc` binary digest;
- raw installer, image-template, and materialized-manifest digests;
- the required runtime `networkPolicy=public`; and
-- the hardened runtime contract: `sandbox` uid 1000, `sudo -n true` denied,
- root-owned read-only toolchain, and writable `/workspace`.
+- the hardened runtime contract: `sandbox` uid/gid 1000 with no supplementary
+ groups, no `sudo` path, host-only guest-agent control, a root-owned read-only
+ toolchain, and writable `/workspace`.
The named snapshot is not the complete physical coordinate. The snapshot API's
ready response supplies its immutable `checkpointId`. `snapshot.py create`
@@ -39,11 +42,20 @@ toolchain versions do not change.
The base image normally grants `sandbox ALL=(ALL) NOPASSWD:ALL`. The recipe uses
that privilege only for trusted installation steps. Its penultimate step runs a
-root finalizer that removes direct sudo grants and administrator-group
-membership, locks the account password, makes `/opt/opencomputer` root-owned
-and non-writable, preserves the user-owned workspace, installs a read-only
-runtime verifier, and removes the installer. The last image step runs that
-verifier as the ordinary sandbox user. No privileged step follows finalization.
+root finalizer that clears every supplementary group, removes every `sudo` path
+from the root filesystem, locks the account password, restricts the active
+virtio-serial/Unix agent nodes to root, makes `/opt/opencomputer` root-owned and
+non-writable, preserves the user-owned workspace, installs a read-only runtime
+verifier, and removes the installer. Removing `sudo` avoids relying on parsing
+its alias/group/include policy language. The last image step runs the verifier
+as the ordinary sandbox user. No privileged step follows finalization.
+
+`osb-agent` is a root PID-1 gRPC server whose trusted host API necessarily
+includes root exec, filesystem operations, and binary upgrade. Its AF_VSOCK
+listener accepts only Linux host CID 2; guest-local/own-CID connections are
+closed before gRPC sees them. The virtio-serial device and Unix fallback are
+mode `0600`. This keeps host orchestration working without exposing that RPC
+surface to untrusted lifecycle scripts.
## Offline validation
@@ -79,8 +91,8 @@ export AGENT_BUILD_SNAPSHOT_ALLOW_CREATE=1
export AGENT_BUILD_SNAPSHOT_ALLOW_PRODUCTION=1
python3 deploy/flue-builder/snapshot.py create \
- --confirm-name flue-build-node22-19-0-oc-c39b315-r1 \
- --receipt /secure/operator-state/flue-build-node22-19-0-oc-c39b315-r1.json
+ --confirm-name flue-build-node22-19-0-oc-c39b315-r2 \
+ --receipt /secure/operator-state/flue-build-node22-19-0-oc-c39b315-r2.json
```
The command never deletes or replaces a snapshot. Its existing-name path is
@@ -95,7 +107,7 @@ not commit environment files or API keys. Configure the build worker from the
receipt:
```text
-AGENT_BUILD_SANDBOX_SNAPSHOT=flue-build-node22-19-0-oc-c39b315-r1
+AGENT_BUILD_SANDBOX_SNAPSHOT=flue-build-node22-19-0-oc-c39b315-r2
AGENT_BUILD_SANDBOX_CHECKPOINT_ID=<receipt checkpointId>
AGENT_BUILD_NODE_VERSION=22.19.0
AGENT_BUILD_NETWORK_POLICY=public
@@ -106,7 +118,7 @@ token-bearing source sandbox and the tokenless build sandbox until a smaller,
independently pinned source image exists:
```text
-AGENT_SOURCE_SANDBOX_SNAPSHOT=flue-build-node22-19-0-oc-c39b315-r1
+AGENT_SOURCE_SANDBOX_SNAPSHOT=flue-build-node22-19-0-oc-c39b315-r2
AGENT_SOURCE_SANDBOX_CHECKPOINT_ID=<same receipt checkpointId>
```
@@ -127,9 +139,13 @@ The live probe creates two short-lived sandboxes from the same checkpoint:
2. the final `networkPolicy=public` sandbox, proving public npm registry and
tarball access succeeds while those targets and inbound exposure fail.
-It also requires `sudo -n true` to fail as uid 1000, writes and deletes a
-workspace probe, verifies exact Node/npm/`oc` versions and the `oc` digest, and
-checks root ownership/read-only modes for the trusted binaries. It checks that
+It also requires the `sudo` binary to be absent, uid/gid 1000 to have no
+supplementary groups, writes and deletes a workspace probe, verifies exact
+Node/npm/`oc` versions and the `oc` digest, and checks root ownership/read-only
+modes for the trusted binaries. An adversarial uid-1000 check sends an HTTP/2
+preface to guest-local AF_VSOCK and Unix agent endpoints and fails if root gRPC
+answers; it also tries to open every known virtio-serial agent node. It checks
+that
the create response has no host port, proves a temporary non-secret server is
publicly reachable through the unrestricted control, then requires preview
creation to return 409 and the equivalent restricted guest server to remain
@@ -149,7 +165,7 @@ credentials in its URL or marker. Then run:
```bash
export OPENCOMPUTER_API_URL='<approved-production-api>'
export OPENCOMPUTER_API_KEY='...'
-export AGENT_BUILD_SANDBOX_SNAPSHOT='flue-build-node22-19-0-oc-c39b315-r1'
+export AGENT_BUILD_SANDBOX_SNAPSHOT='flue-build-node22-19-0-oc-c39b315-r2'
export AGENT_BUILD_SANDBOX_CHECKPOINT_ID='<receipt checkpointId>'
export AGENT_BUILD_NODE_VERSION='22.19.0'
export AGENT_BUILD_PRIVATE_CANARY_URL='http://10.0.0.10:8080/flue-probe'
diff --git a/deploy/flue-builder/coordinate.json b/deploy/flue-builder/coordinate.json
index 0bf5adc9..5d330db7 100644
--- a/deploy/flue-builder/coordinate.json
+++ b/deploy/flue-builder/coordinate.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"snapshot": {
- "name": "flue-build-node22-19-0-oc-c39b315-r1",
+ "name": "flue-build-node22-19-0-oc-c39b315-r2",
"roles": ["source", "build"],
"networkPolicy": "public",
"builderMemoryMB": 4096,
@@ -9,14 +9,14 @@
},
"recipe": {
"installer": "install-snapshot.sh",
- "installerSha256": "60793ed4e3a481dfd6b9df1e3a2b0ec014c7428259bdfd2a122206e8ff50a087",
+ "installerSha256": "0e4eeb46adb311a783890cfe8afff90e88dbff5d2e2bef7c3decba0318b911aa",
"imageTemplate": "image.json",
"imageTemplateSha256": "e5e8827412e76e6da94f8c2f9b97ddfe25579637905ef4e6d2f7fa563712683f",
- "materializedManifestSha256": "f334cd2ee291c707fc1c1efff5c6c38263fb78c2b8d8ca326d0d401b06004f32"
+ "materializedManifestSha256": "d16ba78183df34ea6cfc55e76a78346430bf78c0222a9150dca032762ce91190"
},
"attestation": {
"schemaVersion": 1,
- "snapshotName": "flue-build-node22-19-0-oc-c39b315-r1",
+ "snapshotName": "flue-build-node22-19-0-oc-c39b315-r2",
"baseImage": "base",
"platform": {
"osId": "ubuntu",
@@ -43,7 +43,10 @@
"security": {
"runtimeUser": "sandbox",
"runtimeUid": 1000,
- "sudoPolicy": "denied",
+ "runtimeGid": 1000,
+ "supplementaryGroups": [],
+ "sudoPolicy": "binary-removed",
+ "agentControl": "host-only",
"toolchainOwner": "root",
"workspace": "/workspace",
"workspaceWritable": true
diff --git a/deploy/flue-builder/install-snapshot.sh b/deploy/flue-builder/install-snapshot.sh
index b7cf7899..e67cdf57 100755
--- a/deploy/flue-builder/install-snapshot.sh
+++ b/deploy/flue-builder/install-snapshot.sh
@@ -5,7 +5,7 @@ set -euo pipefail
# downloaded input immutable and verified: the resulting checkpoint is trusted
# to execute arbitrary repository lifecycle code without receiving credentials.
-SNAPSHOT_NAME="flue-build-node22-19-0-oc-c39b315-r1"
+SNAPSHOT_NAME="flue-build-node22-19-0-oc-c39b315-r2"
BASE_IMAGE="base"
OS_ID="ubuntu"
OS_VERSION_ID="22.04"
@@ -32,6 +32,7 @@ ATTESTATION="/opt/opencomputer/agent-build-snapshot.json"
RUNTIME_VERIFIER="/opt/opencomputer/bin/verify-flue-builder-runtime"
RUNTIME_USER="sandbox"
RUNTIME_UID="1000"
+RUNTIME_GID="1000"
WORKSPACE="/workspace"
die() {
@@ -95,7 +96,10 @@ write_attestation() {
"security": {
"runtimeUser": "$RUNTIME_USER",
"runtimeUid": $RUNTIME_UID,
- "sudoPolicy": "denied",
+ "runtimeGid": $RUNTIME_GID,
+ "supplementaryGroups": [],
+ "sudoPolicy": "binary-removed",
+ "agentControl": "host-only",
"toolchainOwner": "root",
"workspace": "$WORKSPACE",
"workspaceWritable": true
@@ -217,6 +221,8 @@ source /etc/os-release
[[ "\$(uname -m)" == "$ARCHITECTURE" ]] || fail "architecture changed"
[[ "\$(id -u)" == "$RUNTIME_UID" ]] || fail "expected uid $RUNTIME_UID"
[[ "\$(id -un)" == "$RUNTIME_USER" ]] || fail "expected user $RUNTIME_USER"
+[[ "\$(id -g)" == "$RUNTIME_GID" ]] || fail "expected gid $RUNTIME_GID"
+[[ "\$(id -G)" == "$RUNTIME_GID" ]] || fail "supplementary groups are present"
[[ "\$(node --version)" == "v${NODE_VERSION}" ]] || fail "Node version changed"
[[ "\$(npm --version)" == "$NPM_VERSION" ]] || fail "npm version changed"
[[ "\$($OC_BIN --version)" == "oc version $OC_SOURCE_COMMIT" ]] || fail "oc version changed"
@@ -227,12 +233,9 @@ printf '%s %s\n' "$attestation_sha" "$ATTESTATION" | sha256sum --check --status
[[ ! -w "$OC_BIN" ]] || fail "oc binary is writable"
[[ ! -w "/opt/opencomputer/bin" ]] || fail "toolchain bin directory is writable"
[[ ! -w "$NODE_ROOT" ]] || fail "Node toolchain is writable"
-[[ -x /usr/bin/sudo ]] || fail "sudo executable is missing"
-[[ "\$(stat -c '%u:%a' /usr/bin/sudo)" == "0:4755" ]] \
- || fail "sudo executable metadata changed"
-sudo_rc=0
-/usr/bin/sudo -n /usr/bin/true >/dev/null 2>&1 || sudo_rc=\$?
-[[ "\$sudo_rc" == "1" ]] || fail "sudo denial changed (exit \$sudo_rc)"
+[[ ! -e /usr/bin/sudo && ! -e /bin/sudo ]] || fail "sudo executable was restored"
+[[ -z "\$(find / -xdev -name sudo -print -quit 2>/dev/null)" ]] \
+ || fail "a sudo path remains on the runtime root filesystem"
[[ -d "$WORKSPACE" && -w "$WORKSPACE" ]] || fail "workspace is not writable"
probe="\$(mktemp "$WORKSPACE/.flue-builder-write.XXXXXX")" \
|| fail "cannot create a workspace file"
@@ -250,32 +253,39 @@ install_runtime_verifier() {
chmod 0555 "$RUNTIME_VERIFIER"
}
-remove_direct_sudo_grants() {
- local file
-
- # The base image currently grants `sandbox ALL=(ALL) NOPASSWD:ALL` directly
- # in /etc/sudoers. Remove any direct sandbox rule as well as membership in
- # conventional administrator groups so a future base-image variant fails
- # closed instead of retaining an equivalent grant.
- sed -i -E '/^[[:space:]]*sandbox[[:space:]]+ALL[[:space:]]*=/d' /etc/sudoers
- if [[ -d /etc/sudoers.d ]]; then
- while IFS= read -r -d '' file; do
- sed -i -E '/^[[:space:]]*sandbox[[:space:]]+ALL[[:space:]]*=/d' "$file"
- done < <(find /etc/sudoers.d -maxdepth 1 -type f -print0)
- fi
- for group in sudo admin wheel; do
- if id -nG "$RUNTIME_USER" | tr ' ' '\n' | grep -Fxq "$group"; then
- gpasswd -d "$RUNTIME_USER" "$group" >/dev/null
- fi
- done
+remove_runtime_privilege_surfaces() {
+ # Empty the complete supplementary-group list. This is intentionally not an
+ # allow/deny list of familiar administrator groups: a base-image change must
+ # not silently preserve privilege through a differently named group.
+ usermod -G '' "$RUNTIME_USER"
usermod --lock "$RUNTIME_USER"
rm -rf "/run/sudo/ts/$RUNTIME_USER" "/var/run/sudo/ts/$RUNTIME_USER"
- visudo -cf /etc/sudoers >/dev/null
+
+ # Sudoers is a rich policy language (aliases, groups, includes, commands).
+ # Trying to prove every policy path denied is brittle, so the managed image
+ # removes the setuid entrypoint itself after the last trusted sudo command.
+ # Search the root filesystem rather than assuming one package path.
+ find / -xdev -name sudo -exec rm -f -- {} + 2>/dev/null
+ [[ -z "$(find / -xdev -name sudo -print -quit 2>/dev/null)" ]] \
+ || die "could not remove every sudo path"
}
-finalize() {
- local sudo_rc=0
+harden_agent_transport_nodes() {
+ local path
+
+ # The root guest agent owns root exec, filesystem, and upgrade RPCs. QEMU's
+ # virtio-serial device and the test-only Unix fallback must not be openable
+ # by repository code. AF_VSOCK peer rejection is enforced by osb-agent and
+ # exercised by the live substrate probe.
+ for path in /dev/virtio-ports/agent /dev/vport0p1 /dev/vport1p1 /dev/vport2p1 \
+ /tmp/osb-agent.sock; do
+ if [[ -e "$path" || -S "$path" ]]; then
+ chmod 0600 "$path"
+ fi
+ done
+}
+finalize() {
require_root
assert_platform
verify
@@ -294,11 +304,10 @@ finalize() {
chown -R "$RUNTIME_USER:$RUNTIME_USER" "$WORKSPACE"
fi
- remove_direct_sudo_grants
- runuser -u "$RUNTIME_USER" -- /usr/bin/sudo -n /usr/bin/true \
- >/dev/null 2>&1 || sudo_rc=$?
- [[ "$sudo_rc" == "1" ]] \
- || die "runtime sudo denial returned unexpected exit $sudo_rc"
+ harden_agent_transport_nodes
+ remove_runtime_privilege_surfaces
+ [[ "$(runuser -u "$RUNTIME_USER" -- id -G)" == "$RUNTIME_GID" ]] \
+ || die "runtime user retains supplementary groups"
# No later image-build operation needs privilege. Remove the root-capable
# installer before returning to the non-root image builder.
diff --git a/deploy/flue-builder/snapshot.py b/deploy/flue-builder/snapshot.py
index 8b222063..13e1bbb2 100755
--- a/deploy/flue-builder/snapshot.py
+++ b/deploy/flue-builder/snapshot.py
@@ -140,7 +140,10 @@ def check_recipe() -> tuple[dict[str, Any], dict[str, Any]]:
if security != {
"runtimeUser": "sandbox",
"runtimeUid": 1000,
- "sudoPolicy": "denied",
+ "runtimeGid": 1000,
+ "supplementaryGroups": [],
+ "sudoPolicy": "binary-removed",
+ "agentControl": "host-only",
"toolchainOwner": "root",
"workspace": "/workspace",
"workspaceWritable": True,
@@ -197,9 +200,9 @@ def check_recipe() -> tuple[dict[str, Any], dict[str, Any]]:
f"generated runtime verifier fails bash -n: {verifier_syntax.stderr.strip()}"
)
for command in (
- "/usr/bin/sudo -n /usr/bin/true",
- "sudo executable metadata changed",
- '[[ "$sudo_rc" == "1" ]]',
+ '[[ "$(id -G)" == "1000" ]]',
+ "sudo executable was restored",
+ "a sudo path remains on the runtime root filesystem",
"sha256sum --check --status",
'mktemp "/workspace/.flue-builder-write.XXXXXX"',
):