Skip to content

Computer use CLI for AI agents

fix(sandbox)!: reach the macOS guest through a guest agent instead of SSH (#675)

Lahfir46d2adf88500
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 888010420..903707593 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -154,13 +154,15 @@ jobs:
clang -fobjc-arc -fblocks -Wall -Wextra -Werror -framework AppKit tests/native/appkit_workspace_name_test.m -o "$RUNNER_TEMP/appkit-workspace-name-test"
"$RUNNER_TEMP/appkit-workspace-name-test"
- - name: macOS VM host compiles, signs, and refuses a missing command
+ - name: macOS VM host and guest agent compile, sign, and refuse a missing command
run: |
VM_HOST_DIR="$RUNNER_TEMP/macos"
mkdir -p "$VM_HOST_DIR"
xcrun swiftc -O providers/macos/vmhost.swift -o "$VM_HOST_DIR/vmhost"
codesign -f -s - --entitlements providers/macos/vm.entitlements "$VM_HOST_DIR/vmhost"
codesign -d --entitlements - "$VM_HOST_DIR/vmhost" 2>&1 | grep -q com.apple.security.virtualization
+ xcrun swiftc -O -target arm64-apple-macos13.0 providers/macos/guestagent.swift -o "$VM_HOST_DIR/agent-desktop-guest"
+ codesign -f -s - "$VM_HOST_DIR/agent-desktop-guest"
set +e
"$VM_HOST_DIR/vmhost" > "$VM_HOST_DIR/usage.json" 2>&1
USAGE_STATUS=$?
diff --git a/apps/docs/content/docs/sandboxes/index.mdx b/apps/docs/content/docs/sandboxes/index.mdx
index 19d2fb306..be65c1fcc 100644
--- a/apps/docs/content/docs/sandboxes/index.mdx
+++ b/apps/docs/content/docs/sandboxes/index.mdx
@@ -10,7 +10,7 @@ The `agent-desktop sandbox` commands manage local macOS VMs through the `macos`
## How commands reach the sandbox
-The local provider starts a VM. `sandbox exec` runs each command inside the guest and passes the guest command's stdout and exit status through without adding an envelope; a provider failure becomes a host error envelope. The guest has one state root shared by every `sandbox exec` call, so snapshots, refs, sessions, and traces stay in the guest, not the host.
+The local provider starts a VM. `sandbox exec` runs each command inside the guest through a guest agent and passes the guest command's stdout and exit status through without adding an envelope; a provider failure becomes a host error envelope. The guest has one state root shared by every `sandbox exec` call, so snapshots, refs, sessions, and traces stay in the guest, not the host.
<Diagram name="sandboxes" title="How agent-desktop works with sandboxes" aspectRatio="720 / 468" />
@@ -34,7 +34,7 @@ agent-desktop launch Finder --activate
agent-desktop snapshot --app Finder -i
```
-An automation that already runs in `demo` uses the same two commands without `sandbox exec`. Accessibility permission belongs to the guest app that launches agent-desktop, and the host cannot grant it; the SSH grant from setup covers `sandbox exec`, not a different terminal or harness. See [Grant and check permissions](/desktop/platforms/macos#grant-and-check-permissions).
+An automation that already runs in `demo` uses the same two commands without `sandbox exec`. Accessibility permission belongs to the guest app that launches agent-desktop, and the host cannot grant it; the grant from setup belongs to the guest agent that `sandbox exec` uses, not to a different terminal or harness. See [Grant and check permissions](/desktop/platforms/macos#grant-and-check-permissions).
## Commands
diff --git a/apps/docs/content/docs/sandboxes/macos.mdx b/apps/docs/content/docs/sandboxes/macos.mdx
index 2e39f6cfc..0eccab16a 100644
--- a/apps/docs/content/docs/sandboxes/macos.mdx
+++ b/apps/docs/content/docs/sandboxes/macos.mdx
@@ -1,93 +1,75 @@
---
title: macOS VM sandbox
navTitle: macOS VM
-description: Install the macOS VM provider, create a macOS guest, complete the one-time setup by hand, and clone the configured VM for later sandboxes.
+description: Install the macOS VM provider, create a macOS guest, set it up once, and clone it for later sandboxes.
---
-The `macos` provider runs a macOS guest in a virtual machine on an Apple Silicon Mac. Only the first sandbox needs a person at the guest desktop; every sandbox you clone from it starts headless and comes up already set up. Cloning a set-up VM has been tested end to end. Creating the first VM from a macOS image is experimental.
-
-## What this isolates
-
-Each sandbox is a separate VM with its own disk, desktop, and agent-desktop state. That separates the desktop; it does not separate the network or the host.
-
-- Every sandbox on a host shares one virtual network. A guest can reach the host's network services, so treat a guest as code running on your network. Assume guests on one host can reach each other too.
-- Each sandbox has its own SSH host key. Before a start or a clone boots the guest, the provider writes a fresh key into the stopped guest disk and pins the public key, and SSH then refuses any other host. The host must be able to open the guest disk to do this, so a disk it cannot open fails the start or clone. A freshly installed VM has no host key until Remote Login is enabled, so its first setup connection is trust-on-first-use.
-- The SSH key in the sandbox directory is the guest credential. Anyone who can read `<state root>/sandboxes/<name>/id_ed25519` can run commands as the guest user, so protect the state root like your own account.
-- In the guest, Accessibility is granted to `sshd-keygen-wrapper`, so every SSH session as the guest user can drive its desktop.
-- The VM host runs as you with Apple's virtualization entitlement. The hypervisor and the guest OS are Apple's; agent-desktop does not prevent a guest escape.
-
-Use `agent-desktop sandbox` for a desktop you trust at the same level as your own account. Keep one trust level per host, and use a separate machine or a hosted sandbox for code you do not trust.
+The `macos` provider runs a macOS guest in a virtual machine on an Apple Silicon Mac. You set up the first sandbox once in its window. Every sandbox you clone from it starts headless and needs no setup. Creating the first VM from a macOS image is experimental.
## Requirements
-- An Apple Silicon Mac. On an Intel Mac, `sandbox install macos` reports `unavailable`.
-- macOS 13 or later on the host.
-- Xcode Command Line Tools before the first install, because they provide `swiftc`. Install them with `xcode-select --install`. A VM host that is already built and signed needs no compiler, and an agent-desktop upgrade reuses it unless the VM host's source changed; `sandbox install` then reports `missing`.
+- An Apple Silicon Mac running macOS 13 or later. The guest must also run macOS 13 or later.
+- Xcode Command Line Tools for `swiftc`: `xcode-select --install`.
-## Install the VM host
+## Set up the first sandbox
```bash
-agent-desktop sandbox install macos # compile and sign vmhost
+agent-desktop sandbox install macos # build and sign the VM host and guest agent
+agent-desktop sandbox create base --provider macos --set ipsw=latest # download and install macOS in the background
+agent-desktop sandbox status base # repeat until it stops answering working
+agent-desktop sandbox start base # opens the guest in a window
```
-The command compiles `vmhost.swift`, signs the binary with the virtualization entitlement, and answers `ready`. When the build or the signature fails, the error names the build log to read.
+`--set ipsw=<path>` installs an image you already have instead of downloading one. A failed install answers `broken`; the reason is in `vm/install.log`.
-## Create the first VM
+Then, in the guest window:
-`create` needs exactly one source: an image to install, or a sandbox to clone. Without one it answers `INVALID_ARGS` and does nothing.
+1. Finish macOS setup, and turn on automatic login in **System Settings > Users & Groups**.
+2. Open **Terminal** and run `sh "/Volumes/My Shared Files/guest-setup.sh"`.
+3. When macOS asks, open **System Settings > Privacy & Security > Accessibility** and switch on **agent-desktop-guest**. For `screenshot`, switch it on under **Screen & System Audio Recording** too.
-```bash
-agent-desktop sandbox create base --provider macos --set ipsw=latest # download and install macOS
-agent-desktop sandbox status base # repeat until the state changes
-```
+On the host, `agent-desktop sandbox status base` answers `running` when the setup is complete.
-`create` answers `working` and installs in the background. With `ipsw=latest` it reads Apple's macOS image catalog, takes the newest version this Mac can install, downloads it into the sandbox directory, checks it against the published SHA-1, installs it, and deletes the download. `status` reports the download size or the install progress. A failed install is `broken`; the reason is in `vm/install.log`.
-
-To install an image you already have, pass its path. A relative path resolves from the directory where you run the command.
+## Clone it
```bash
-agent-desktop sandbox create base --provider macos --set ipsw=/path/to/UniversalMac_15.0.ipsw
+agent-desktop sandbox stop base # a clone needs a stopped source
+agent-desktop sandbox create work --provider macos --set from=base # copy the set-up VM
+agent-desktop sandbox start work # starts headless
+agent-desktop sandbox exec work -- snapshot --app Finder -i # run agent-desktop in the guest
```
-`--set user=<name>` sets the guest account name recorded for SSH. The default is your user name on the host. It applies only to an install.
-
-## Complete the guest setup
+A started sandbox keeps running after the command that started it exits, until `sandbox stop`. To watch a sandbox, start it in a window. Closing the window shuts the VM down.
-The setup is one session at the guest desktop. The provider records it, so clones never repeat it.
-
-1. Run `agent-desktop sandbox start base`. Because the guest setup is not recorded yet, the VM starts with a window on the host and the reply state is `needs_setup`. Closing that window shuts the VM down; run `start` again to reopen it.
-2. In the guest, open **Terminal** and run `guest-setup.sh` from the shared folder, which the guest mounts at `/Volumes/My Shared Files`. The host writes that folder to `sandboxes/base/vm/share/` and the VM mounts it read-only. The script adds the sandbox key to `~/.ssh/authorized_keys`, installs agent-desktop and `agent-desktop-macos-helper` at `~/.local/bin`, and requests the macOS permissions it needs.
-3. In the guest, open **System Settings > General > Sharing** and turn on **Remote Login**. agent-desktop reaches the guest over SSH.
-4. In the guest, open **System Settings > Privacy & Security > Accessibility** and allow **sshd-keygen-wrapper**. The setup script prints both of these steps when it finishes.
-5. On the host, run `agent-desktop sandbox status base`. Once SSH answers and the guest reports Accessibility as granted, the state becomes `running` and the setup is recorded.
+```bash
+agent-desktop sandbox start work --window --set title="Review build"
+```
-If a set-up sandbox later loses Remote Login or the Accessibility grant, `status` answers `needs_setup` and tells you to stop and start it. The next `start` opens the window again so you can repeat the steps above.
+## When status answers needs_setup
-## Clone the configured VM
+The guest agent is not answering, Accessibility is off for it, or another process answered in its place. A guest that is only slow to start answers `running` on a later `status`. Otherwise open the sandbox in a window and repeat the three guest steps:
```bash
-agent-desktop sandbox stop base # a clone needs a stopped source
-agent-desktop sandbox create work --provider macos --set from=base # copy the set-up VM
-agent-desktop sandbox start work # start it headless
+agent-desktop sandbox stop base
+agent-desktop sandbox start base --window
```
-A clone copies the disk image, the sandbox key, the setup record, and the guest user name, so it starts without a window and SSH reaches the same account. The source must be stopped and set up; otherwise `create` names its state and stops. `--set from` cannot be combined with `--set ipsw` or `--set user`.
+A sandbox set up by agent-desktop 1.3.0 needs this once, after `agent-desktop sandbox install macos`. Its guest no longer needs Remote Login.
-A set-up sandbox starts headless. To watch or use its desktop, start it in a window:
+## How the host reaches the guest
-```bash
-agent-desktop sandbox start work --window # show the guest desktop on the host
-agent-desktop sandbox start work --window --set title="Review build"
-```
+- `guest-setup.sh` installs a guest agent, `agent-desktop-guest.app`, in the guest's `~/Applications`. It starts with each login. It runs one program, the guest's `agent-desktop`, with the arguments `sandbox exec` passes. It does not run a shell.
+- The host talks to the agent through the virtual machine's own socket device. The guest's network is not involved, and only the process that runs the VM can open that connection.
+- The agent holds a key that only its guest account can read. The host records the public half when setup completes and sends commands only to a process that proves that key, so another account in the guest cannot answer in the agent's place.
+- The guest mounts `sandboxes/<name>/vm/share/` read-only. Before each command the guest agent installs the host's agent-desktop build from it, so the guest always runs your build.
-The window's title is the sandbox name unless you pass `--set title=<text>`. Closing the window shuts the VM down. A sandbox that is already running headless must be stopped before it can open a window.
+## What this isolates
-`start` answers `running` only once the guest answers over SSH. Until then it answers `working`; repeat `sandbox status` before `sandbox exec`. The VM host runs in its own session, so a started sandbox keeps running after the command that started it exits, including when the caller that launched it is later terminated.
+A sandbox has its own disk, desktop, and agent-desktop state. It does not isolate the network: every sandbox on a host shares one virtual network and can reach the host's network services. agent-desktop does not prevent a guest escape; the hypervisor and the guest OS are Apple's. Use a separate machine or a hosted sandbox for code you do not trust.
## Limits
-- macOS allows two macOS VMs running at once. A third start fails, and `vm/vmhost.log` in the sandbox directory holds the reason.
-- The first setup needs a person in the guest window: agent-desktop cannot turn on Remote Login or grant Accessibility inside the guest.
-- `sandbox exec` copies the host binary and `agent-desktop-macos-helper` into the guest when their SHA-1 hashes differ, so the guest always runs the files from your build.
+- macOS runs two macOS VMs at once. A third start fails, and `vm/vmhost.log` holds the reason.
+- The first setup needs a person: nothing outside the guest can grant Accessibility.
- `sandbox exec` waits at most 300 seconds for one guest command.
-- A sandbox keeps a full macOS disk image in `sandboxes/<name>/vm`. `sandbox rm` deletes it.
+- `sandbox rm` deletes the sandbox's disk image.
diff --git a/apps/docs/public/desktop/diagrams/sandboxes/index.html b/apps/docs/public/desktop/diagrams/sandboxes/index.html
index bd78ead28..5de759ada 100644
--- a/apps/docs/public/desktop/diagrams/sandboxes/index.html
+++ b/apps/docs/public/desktop/diagrams/sandboxes/index.html
@@ -57,7 +57,7 @@
<body>
<svg viewBox="0 0 720 468" role="img" aria-labelledby="t d">
<title id="t">How agent-desktop works with sandboxes</title>
- <desc id="d">From top to bottom: the calling agent picks one of two independent routes to a desktop. On the left, agent-desktop sandbox exec runs on your Mac and sends the command over SSH to agent-desktop in a macOS VM. On the right, the @vercel/sandbox SDK calls sandbox.runCommand in a hosted Linux microVM, where agent-desktop drives that desktop. The sandbox commands manage local VMs only, and the Vercel SDK creates and drives its own sandbox.</desc>
+ <desc id="d">From top to bottom: the calling agent picks one of two independent routes to a desktop. On the left, agent-desktop sandbox exec runs on your Mac and sends the command to the guest agent, which runs agent-desktop in a macOS VM. On the right, the @vercel/sandbox SDK calls sandbox.runCommand in a hosted Linux microVM, where agent-desktop drives that desktop. The sandbox commands manage local VMs only, and the Vercel SDK creates and drives its own sandbox.</desc>
<defs>
<marker id="arrow" viewBox="0 0 8 8" refX="6" refY="4" markerWidth="8" markerHeight="8" markerUnits="userSpaceOnUse" orient="auto">
<path d="M1.5 1.5 L5.5 4 L1.5 6.5"/>
@@ -78,7 +78,7 @@
<text class="label" x="438" y="148">@vercel/sandbox</text>
<text class="sub" x="438" y="165">SDK called from your code</text>
<path class="wire strong" d="M184 186V294"/>
- <text class="tag start" x="194" y="209">over SSH</text>
+ <text class="tag start" x="194" y="209">to the guest agent</text>
<path class="wire strong" d="M552 186V294"/>
<text class="tag start" x="562" y="209">sandbox.runCommand</text>
<rect class="box" x="16" y="224" width="336" height="160" rx="8" style="fill:none"/>
diff --git a/crates/core/src/commands/sandbox_tests.rs b/crates/core/src/commands/sandbox_tests.rs
index d9ddd61ca..5fac538e9 100644
--- a/crates/core/src/commands/sandbox_tests.rs
+++ b/crates/core/src/commands/sandbox_tests.rs
@@ -85,7 +85,7 @@ fn a_failed_create_leaves_no_record_unless_the_provider_left_files() {
}
let home = HomeGuard::new();
- let adapter = ScriptedAdapter::new().leaving("id_ed25519");
+ let adapter = ScriptedAdapter::new().leaving("Disk.img");
execute(create_action(), &adapter).expect_err("the provider create fails");
diff --git a/crates/core/src/sandbox/provider_protocol_tests.rs b/crates/core/src/sandbox/provider_protocol_tests.rs
index 1dfd6a6c3..7fb20dbd5 100644
--- a/crates/core/src/sandbox/provider_protocol_tests.rs
+++ b/crates/core/src/sandbox/provider_protocol_tests.rs
@@ -144,7 +144,7 @@ fn exec_failures_report_the_sandbox_error_and_unknown_delivery() {
let no_status = ProviderScriptOutput {
status: None,
stdout: Vec::new(),
- stderr_tail: "ssh died".to_owned(),
+ stderr_tail: "the provider died".to_owned(),
};
let error = adapter(exec_outcome("macos", &no_status).unwrap_err());
assert_eq!(error.code, ErrorCode::ActionFailed);
diff --git a/crates/core/src/sandbox/provider_table.rs b/crates/core/src/sandbox/provider_table.rs
index cbc636ca8..40e8fb7e2 100644
--- a/crates/core/src/sandbox/provider_table.rs
+++ b/crates/core/src/sandbox/provider_table.rs
@@ -6,6 +6,8 @@ const MACOS_VM_PROVIDER: &str = include_str!("../../../../providers/macos/provid
#[cfg(not(test))]
const MACOS_VM_HOST: &str = include_str!("../../../../providers/macos/vmhost.swift");
#[cfg(not(test))]
+const MACOS_VM_GUEST_AGENT: &str = include_str!("../../../../providers/macos/guestagent.swift");
+#[cfg(not(test))]
const MACOS_VM_ENTITLEMENTS: &str = include_str!("../../../../providers/macos/vm.entitlements");
#[cfg(not(test))]
const MACOS_VM_GUEST_SETUP: &str = include_str!("../../../../providers/macos/guest-setup.sh");
@@ -16,6 +18,7 @@ pub(crate) const PROVIDERS: &[ProviderSpec] = &[ProviderSpec {
files: &[
("provider.sh", MACOS_VM_PROVIDER),
("vmhost.swift", MACOS_VM_HOST),
+ ("guestagent.swift", MACOS_VM_GUEST_AGENT),
("vm.entitlements", MACOS_VM_ENTITLEMENTS),
("guest-setup.sh", MACOS_VM_GUEST_SETUP),
],
diff --git a/providers/macos/guest-setup.sh b/providers/macos/guest-setup.sh
index d9fc5e0eb..febdea44c 100644
--- a/providers/macos/guest-setup.sh
+++ b/providers/macos/guest-setup.sh
@@ -2,55 +2,85 @@
set -eu
here=$(cd "$(dirname "$0")" && pwd)
-key_file="$here/id_ed25519.pub"
-binary="$here/agent-desktop"
-helper="$here/agent-desktop-macos-helper"
-ssh_dir="$HOME/.ssh"
-auth_file="$ssh_dir/authorized_keys"
-bin_dir="$HOME/.local/bin"
-installed="$bin_dir/agent-desktop"
-installed_helper="$bin_dir/agent-desktop-macos-helper"
-
-if [ ! -f "$key_file" ]; then
- echo "The public key id_ed25519.pub is not in this folder, so run the sandbox create step on the host again." >&2
- exit 1
-fi
-if [ ! -f "$binary" ]; then
- echo "The agent-desktop binary is not in this folder, so run the sandbox create step on the host again." >&2
- exit 1
-fi
-if [ ! -f "$helper" ]; then
- echo "The agent-desktop-macos-helper binary is not in this folder, so run the sandbox create step on the host again." >&2
+name=agent-desktop-guest
+label=com.agent-desktop.guest
+source_app=$here/$name.app
+app=$HOME/Applications/$name.app
+agent=$app/Contents/MacOS/$name
+plist=$HOME/Library/LaunchAgents/$label.plist
+domain=gui/$(id -u)
+lsregister=/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister
+
+if [ ! -f "$source_app/Contents/MacOS/$name" ]; then
+ echo "$name.app is not in this folder, so run agent-desktop sandbox start on the host again." >&2
exit 1
fi
-mkdir -p -m 700 "$ssh_dir"
-touch "$auth_file"
-chmod 600 "$auth_file"
+loaded() {
+ launchctl print "$domain/$label" >/dev/null 2>&1
+}
-key=$(cat "$key_file")
-if grep -qxF "$key" "$auth_file"; then
- echo "The sandbox key is already in $auth_file."
+mkdir -p "$HOME/Applications" "$HOME/Library/LaunchAgents" "$HOME/Library/Logs"
+if cmp -s "$source_app/Contents/MacOS/$name" "$agent"; then
+ echo "The guest agent at $app is already current."
else
- if [ -s "$auth_file" ] && [ "$(tail -c 1 "$auth_file" | wc -l)" -eq 0 ]; then
- printf '\n' >> "$auth_file"
+ if loaded; then
+ launchctl bootout "$domain/$label" >/dev/null 2>&1 || true
+ tries=0
+ while loaded && [ "$tries" -lt 50 ]; do
+ sleep 0.1
+ tries=$((tries + 1))
+ done
fi
- printf '%s\n' "$key" >> "$auth_file"
- echo "Added the sandbox key to $auth_file."
+ rm -rf "$app"
+ cp -R "$source_app" "$app"
+ "$lsregister" -f "$app" >/dev/null 2>&1 || true
+ tccutil reset Accessibility "$label" >/dev/null 2>&1 || true
+ tccutil reset ScreenCapture "$label" >/dev/null 2>&1 || true
+ echo "Installed the guest agent at $app."
fi
-mkdir -p "$bin_dir"
-cp "$binary" "$installed.new"
-chmod 755 "$installed.new"
-mv -f "$installed.new" "$installed"
-cp "$helper" "$installed_helper.new"
-chmod 755 "$installed_helper.new"
-mv -f "$installed_helper.new" "$installed_helper"
-echo "Installed agent-desktop and agent-desktop-macos-helper at $bin_dir."
-
-echo "Requesting the macOS permissions agent-desktop needs."
-"$installed" permissions --request
-
-echo "Two steps are left, and you do them by hand in System Settings:"
-echo "1. Turn on Remote Login in System Settings > General > Sharing."
-echo "2. If macOS asks, allow Accessibility for \"sshd-keygen-wrapper\", or find it in System Settings > Privacy & Security > Accessibility and switch it on."
+cat > "$plist" <<PLIST
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>$label</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>$agent</string>
+ </array>
+ <key>RunAtLoad</key>
+ <true/>
+ <key>KeepAlive</key>
+ <true/>
+ <key>LimitLoadToSessionType</key>
+ <string>Aqua</string>
+ <key>StandardErrorPath</key>
+ <string>$HOME/Library/Logs/$name.log</string>
+</dict>
+</plist>
+PLIST
+
+if loaded; then
+ start="kickstart -k $domain/$label"
+else
+ start="bootstrap $domain $plist"
+fi
+if ! launchctl $start; then
+ echo "The guest agent could not be started. Log in to the desktop, open Terminal there, and run this script again." >&2
+ exit 1
+fi
+
+sleep 2
+if ! launchctl print "$domain/$label" 2>/dev/null | grep -q 'state = running'; then
+ echo "The guest agent did not stay running. Another process may hold its port; see $HOME/Library/Logs/$name.log." >&2
+ exit 1
+fi
+
+echo "One step is left: when macOS asks, open System Settings > Privacy & Security > Accessibility and switch on $name."
+echo "For screenshots, switch it on under Screen & System Audio Recording too."
+if ! defaults read /Library/Preferences/com.apple.loginwindow autoLoginUser >/dev/null 2>&1; then
+ echo "Automatic login is off. Turn it on in System Settings > Users & Groups, or the sandbox cannot reach its desktop when it starts without a window."
+fi
diff --git a/providers/macos/guestagent.swift b/providers/macos/guestagent.swift
new file mode 100644
index 000000000..eb30cf915
--- /dev/null
+++ b/providers/macos/guestagent.swift
@@ -0,0 +1,386 @@
+import ApplicationServices
+import CryptoKit
+import Darwin
+import Foundation
+
+/// The byte protocol the host speaks to this agent over the virtual machine's socket device.
+enum Wire {
+ static let port: UInt32 = 7273
+ static let agentVersion = 1
+ static let hostAddress: UInt32 = 2
+ static let anyAddress: UInt32 = UInt32.max
+ static let frameLimit = 65536
+ static let requestLimit = 1 << 20
+ static let stdout: UInt8 = 1
+ static let stderr: UInt8 = 2
+ static let exit: UInt8 = 3
+ static let failure: UInt8 = 4
+ static let nonceSize = 32
+ static let proofContext = Data("agent-desktop-guest-v1".utf8)
+}
+
+enum GuestPaths {
+ static var share: String { Transport.share }
+ static let binaries = ["agent-desktop", "agent-desktop-macos-helper"]
+ static var bin: String { Transport.home + "/.local/bin" }
+ static var command: String { bin + "/agent-desktop" }
+ static var installedBuild: String { bin + "/.agent-desktop-build-id" }
+}
+
+struct AgentError: Error {
+ let message: String
+}
+
+struct Request: Decodable {
+ let op: String
+ let build: String?
+ let args: [String]?
+}
+
+/// Layout of `struct sockaddr_vm` in <sys/vsock.h>.
+struct SocketAddress {
+ var length = UInt8(MemoryLayout<SocketAddress>.size)
+ var family = sa_family_t(AF_VSOCK)
+ var reserved: UInt16 = 0
+ var port: UInt32 = 0
+ var address: UInt32 = 0
+}
+
+final class Channel: @unchecked Sendable {
+ private let descriptor: Int32
+ private let lock = NSLock()
+
+ init(_ descriptor: Int32) {
+ self.descriptor = descriptor
+ }
+
+ func read(_ count: Int) -> Data? {
+ var bytes = [UInt8](repeating: 0, count: count)
+ var filled = 0
+ while filled < count {
+ let got = bytes.withUnsafeMutableBytes { Darwin.read(descriptor, $0.baseAddress! + filled, count - filled) }
+ if got < 0 && errno == EINTR { continue }
+ guard got > 0 else { return nil }
+ filled += got
+ }
+ return Data(bytes)
+ }
+
+ func send(_ kind: UInt8, _ payload: Data) {
+ lock.withLock {
+ var offset = 0
+ repeat {
+ let chunk = payload.subdata(in: offset..<min(payload.count, offset + Wire.frameLimit))
+ var frame = Data([kind])
+ withUnsafeBytes(of: UInt32(chunk.count).bigEndian) { frame.append(contentsOf: $0) }
+ frame.append(chunk)
+ guard write(frame) else { return }
+ offset += chunk.count
+ } while offset < payload.count
+ }
+ }
+
+ func fail(_ message: String) {
+ send(Wire.failure, Data(message.utf8))
+ }
+
+ /// Returns once the host closes its end, which is how a cancelled command reaches the guest.
+ func waitForHangup() {
+ var scratch = [UInt8](repeating: 0, count: 512)
+ while true {
+ let got = Darwin.read(descriptor, &scratch, scratch.count)
+ if got < 0 && errno == EINTR { continue }
+ if got <= 0 { return }
+ }
+ }
+
+ func prove(_ proof: Data) -> Bool {
+ lock.withLock { write(proof) }
+ }
+
+ func hangUp() {
+ shutdown(descriptor, SHUT_RDWR)
+ }
+
+ func close() {
+ Darwin.close(descriptor)
+ }
+
+ private func write(_ data: Data) -> Bool {
+ var sent = 0
+ while sent < data.count {
+ let wrote = data.withUnsafeBytes { Darwin.write(descriptor, $0.baseAddress! + sent, data.count - sent) }
+ if wrote < 0 && errno == EINTR { continue }
+ guard wrote > 0 else { return false }
+ sent += wrote
+ }
+ return true
+ }
+}
+
+/// Installs the host's agent-desktop build from the shared folder when the guest holds a different one. The host
+/// shares every build under its own id, because a guest never sees a shared file change after its first read.
+enum BuildSync {
+ private static let lock = NSLock()
+
+ static func apply(_ build: String) throws {
+ try lock.withLock {
+ guard build.count == 40, build.allSatisfy({ $0.isHexDigit }) else {
+ throw AgentError(message: "The host did not name the agent-desktop build to run.")
+ }
+ let files = FileManager.default
+ let installed = GuestPaths.binaries.allSatisfy { files.isExecutableFile(atPath: GuestPaths.bin + "/" + $0) }
+ if installed, let current = files.contents(atPath: GuestPaths.installedBuild), current == Data(build.utf8) { return }
+ let source = GuestPaths.share + "/builds/" + build + "/"
+ do {
+ try files.createDirectory(atPath: GuestPaths.bin, withIntermediateDirectories: true)
+ for name in GuestPaths.binaries {
+ let staged = GuestPaths.bin + "/" + name + ".new"
+ try? files.removeItem(atPath: staged)
+ try files.copyItem(atPath: source + name, toPath: staged)
+ try files.setAttributes([.posixPermissions: 0o755], ofItemAtPath: staged)
+ guard rename(staged, GuestPaths.bin + "/" + name) == 0 else { throw AgentError(message: "") }
+ }
+ try Data(build.utf8).write(to: URL(fileURLWithPath: GuestPaths.installedBuild), options: .atomic)
+ } catch {
+ throw AgentError(message: "agent-desktop could not be copied from the sandbox's shared folder into the guest.")
+ }
+ }
+ }
+}
+
+enum Command {
+ static func run(_ request: Request, over channel: Channel) {
+ do {
+ try BuildSync.apply(request.build ?? "")
+ } catch {
+ channel.fail((error as? AgentError)?.message ?? "agent-desktop could not be prepared in the guest.")
+ return
+ }
+ let process = Process()
+ let output = Pipe()
+ let errors = Pipe()
+ process.executableURL = URL(fileURLWithPath: GuestPaths.command)
+ process.arguments = request.args ?? []
+ process.currentDirectoryURL = URL(fileURLWithPath: Transport.home, isDirectory: true)
+ process.standardInput = FileHandle.nullDevice
+ process.standardOutput = output
+ process.standardError = errors
+ do {
+ try process.run()
+ } catch {
+ channel.fail("agent-desktop could not be started in the guest.")
+ return
+ }
+ let streams = DispatchGroup()
+ forward(output, as: Wire.stdout, to: channel, in: streams)
+ forward(errors, as: Wire.stderr, to: channel, in: streams)
+ let watcher = DispatchSemaphore(value: 0)
+ Thread.detachNewThread {
+ channel.waitForHangup()
+ if process.isRunning { process.terminate() }
+ watcher.signal()
+ }
+ streams.wait()
+ process.waitUntilExit()
+ let status = process.terminationReason == .exit ? process.terminationStatus : 128 + process.terminationStatus
+ var reply = Data()
+ withUnsafeBytes(of: UInt32(bitPattern: status).bigEndian) { reply.append(contentsOf: $0) }
+ channel.send(Wire.exit, reply)
+ channel.hangUp()
+ watcher.wait()
+ }
+
+ private static func forward(_ pipe: Pipe, as kind: UInt8, to channel: Channel, in group: DispatchGroup) {
+ group.enter()
+ Thread.detachNewThread {
+ while true {
+ let data = pipe.fileHandleForReading.availableData
+ if data.isEmpty { break }
+ channel.send(kind, data)
+ }
+ group.leave()
+ }
+ }
+}
+
+enum Permissions {
+ static let probeArgument = "accessibility"
+
+ /// A running process keeps the answer macOS gave it at launch, so a fresh copy of the agent asks each time.
+ static var accessibility: Bool {
+ let probe = Process()
+ probe.executableURL = URL(fileURLWithPath: Bundle.main.executablePath ?? CommandLine.arguments[0])
+ probe.arguments = [probeArgument]
+ probe.standardInput = FileHandle.nullDevice
+ probe.standardOutput = FileHandle.nullDevice
+ probe.standardError = FileHandle.nullDevice
+ guard (try? probe.run()) != nil else { return false }
+ probe.waitUntilExit()
+ return probe.terminationReason == .exit && probe.terminationStatus == 0
+ }
+
+ /// Puts this agent in the Accessibility and Screen Recording lists so a person can allow it.
+ static func request() {
+ if !AXIsProcessTrusted() {
+ let prompt = kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String
+ _ = AXIsProcessTrustedWithOptions([prompt: true] as CFDictionary)
+ }
+ if !CGPreflightScreenCaptureAccess() {
+ _ = CGRequestScreenCaptureAccess()
+ }
+ }
+}
+
+/// Where the agent listens and what it reads from its surroundings. A build with GUEST_AGENT_TEST serves a
+/// socket file and takes its paths and peer address from the environment, so tests run the protocol without a
+/// virtual machine. A release build contains none of that.
+enum Transport {
+#if GUEST_AGENT_TEST
+ static let environment = ProcessInfo.processInfo.environment
+ static var share: String { environment["GUEST_TEST_SHARE"] ?? "" }
+ static var home: String { environment["GUEST_TEST_HOME"] ?? "" }
+
+ static func requestPermissions() {}
+
+ static func peer(of descriptor: Int32) -> SocketAddress? {
+ SocketAddress(address: UInt32(environment["GUEST_TEST_PEER"] ?? "") ?? Wire.hostAddress)
+ }
+
+ static func listen() -> Int32? {
+ let descriptor = socket(AF_UNIX, SOCK_STREAM, 0)
+ guard descriptor >= 0, let path = environment["GUEST_TEST_SOCKET"] else { return nil }
+ var address = sockaddr_un()
+ address.sun_family = sa_family_t(AF_UNIX)
+ withUnsafeMutableBytes(of: &address.sun_path) { $0.copyBytes(from: path.utf8) }
+ let bound = withUnsafePointer(to: &address) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
+ bind(descriptor, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
+ }
+ }
+ guard bound == 0, Darwin.listen(descriptor, 16) == 0 else { return nil }
+ return descriptor
+ }
+#else
+ static let share = "/Volumes/My Shared Files"
+ static var home: String { NSHomeDirectory() }
+
+ static func requestPermissions() {
+ Permissions.request()
+ }
+
+ static func peer(of descriptor: Int32) -> SocketAddress? {
+ var address = SocketAddress()
+ var size = socklen_t(MemoryLayout<SocketAddress>.size)
+ let status = withUnsafeMutablePointer(to: &address) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { getpeername(descriptor, $0, &size) }
+ }
+ return status == 0 ? address : nil
+ }
+
+ static func listen() -> Int32? {
+ let descriptor = socket(AF_VSOCK, SOCK_STREAM, 0)
+ guard descriptor >= 0 else { return nil }
+ var address = SocketAddress(port: Wire.port, address: Wire.anyAddress)
+ let bound = withUnsafePointer(to: &address) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
+ bind(descriptor, $0, socklen_t(MemoryLayout<SocketAddress>.size))
+ }
+ }
+ guard bound == 0, Darwin.listen(descriptor, 16) == 0 else {
+ close(descriptor)
+ return nil
+ }
+ return descriptor
+ }
+#endif
+}
+
+/// Any account in the guest can listen on the agent's port. The agent signs the host's nonce with a key that
+/// only its own account can read, and the host sends work only to the key it recorded when setup completed.
+enum Identity {
+ static let key: Curve25519.Signing.PrivateKey? = load()
+
+ static func proof(for nonce: Data) -> Data? {
+ guard let key, let signature = try? key.signature(for: Wire.proofContext + nonce) else { return nil }
+ return key.publicKey.rawRepresentation + signature
+ }
+
+ private static func load() -> Curve25519.Signing.PrivateKey? {
+ let directory = Transport.home + "/Library/Application Support/agent-desktop-guest"
+ let path = directory + "/key"
+ let files = FileManager.default
+ if let stored = files.contents(atPath: path) {
+ return try? Curve25519.Signing.PrivateKey(rawRepresentation: stored)
+ }
+ let key = Curve25519.Signing.PrivateKey()
+ do {
+ try files.createDirectory(atPath: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
+ } catch {
+ return nil
+ }
+ let saved = files.createFile(atPath: path, contents: key.rawRepresentation, attributes: [.posixPermissions: 0o600])
+ return saved ? key : nil
+ }
+}
+
+enum Agent {
+ static func serve(_ channel: Channel) {
+ defer { channel.close() }
+ guard let nonce = channel.read(Wire.nonceSize), let proof = Identity.proof(for: nonce), channel.prove(proof) else { return }
+ guard let header = channel.read(4) else { return }
+ let length = header.reduce(0) { ($0 << 8) | Int($1) }
+ guard length > 0, length <= Wire.requestLimit, let body = channel.read(length),
+ let request = try? JSONDecoder().decode(Request.self, from: body) else {
+ channel.fail("The guest agent could not read the request.")
+ return
+ }
+ switch request.op {
+ case "status":
+ let state = "{\"accessibility\":\(Permissions.accessibility),\"agent\":\(Wire.agentVersion)}\n"
+ channel.send(Wire.stdout, Data(state.utf8))
+ channel.send(Wire.exit, Data([0, 0, 0, 0]))
+ case "exec":
+ Command.run(request, over: channel)
+ default:
+ channel.fail("The guest agent does not know the operation \(request.op).")
+ }
+ }
+
+ /// Only the host that runs this virtual machine may give the agent work.
+ static func isHost(_ peer: SocketAddress?) -> Bool {
+ guard let peer else { return false }
+ return peer.family == sa_family_t(AF_VSOCK) && peer.address == Wire.hostAddress
+ }
+
+ static func run() -> Int32 {
+ if CommandLine.arguments.dropFirst().first == Permissions.probeArgument {
+ return AXIsProcessTrusted() ? 0 : 1
+ }
+ signal(SIGPIPE, SIG_IGN)
+ guard Identity.key != nil else {
+ FileHandle.standardError.write(Data("agent-desktop-guest: the agent's key cannot be read or created\n".utf8))
+ return 1
+ }
+ guard let listener = Transport.listen() else {
+ FileHandle.standardError.write(Data("agent-desktop-guest: the virtual machine socket is not available: \(String(cString: strerror(errno)))\n".utf8))
+ return 1
+ }
+ Transport.requestPermissions()
+ while true {
+ let descriptor = accept(listener, nil, nil)
+ if descriptor < 0 {
+ if errno == EINTR { continue }
+ return 1
+ }
+ guard isHost(Transport.peer(of: descriptor)) else {
+ close(descriptor)
+ continue
+ }
+ let channel = Channel(descriptor)
+ Thread.detachNewThread { serve(channel) }
+ }
+ }
+}
+
+exit(Agent.run())
diff --git a/providers/macos/provider.sh b/providers/macos/provider.sh
index 358c81b63..480f2a423 100644
--- a/providers/macos/provider.sh
+++ b/providers/macos/provider.sh
@@ -37,9 +37,11 @@ AD_SANDBOX_DIR=${AD_SANDBOX_DIR:-}
AD_PROVIDER_DIR=${AD_PROVIDER_DIR:-}
AD_BINARY=${AD_BINARY:-}
# The built VM host is keyed by its own source, so an agent-desktop upgrade that leaves it unchanged reuses it.
-vmhost_key=$(cat "$AD_PROVIDER_DIR/vmhost.swift" "$AD_PROVIDER_DIR/vm.entitlements" 2>/dev/null | shasum -a 1 | cut -c1-16)
+vmhost_key=$(cat "$AD_PROVIDER_DIR/vmhost.swift" "$AD_PROVIDER_DIR/guestagent.swift" "$AD_PROVIDER_DIR/vm.entitlements" 2>/dev/null | shasum -a 1 | cut -c1-16)
VMHOST=${VMHOST:-$(dirname "$AD_PROVIDER_DIR")/build-$vmhost_key/vmhost}
HELPER_NAME=agent-desktop-macos-helper
+GUEST_AGENT=agent-desktop-guest
+GUEST_APP=$GUEST_AGENT.app
SCRIPT_PATH=$(cd "$(dirname "$0")" && pwd)/$(basename "$0")
verb=${1:-}
if [ "$#" -gt 0 ]; then shift; fi
@@ -86,13 +88,6 @@ valid_name() {
esac
}
-valid_guest_user() {
- case $1 in
- ''|-*|*[!A-Za-z0-9._-]*) return 1 ;;
- *) return 0 ;;
- esac
-}
-
resolve_image_path() {
case $1 in
/*) printf '%s\n' "$1" ;;
@@ -133,7 +128,7 @@ build_tools_available() {
}
provider_ready() {
- [ -f "$BUILD_DIR/vmhost" ] || return 1
+ [ -f "$BUILD_DIR/vmhost" ] && [ -f "$BUILD_DIR/$GUEST_APP/Contents/MacOS/$GUEST_AGENT" ] || return 1
if ! entitlements=$(codesign -d --entitlements - "$BUILD_DIR/vmhost" 2>&1); then return 1; fi
case $entitlements in
*com.apple.security.virtualization*) return 0 ;;
@@ -151,6 +146,38 @@ do_check() {
emit_ok missing "The macOS VM host has not been built and signed." "agent-desktop sandbox install macos"
}
+# The guest agent is an app bundle so that macOS files its Accessibility switch under a bundle id, which is the
+# only kind of entry guest-setup.sh can reset when the agent changes.
+build_guest_agent() {
+ app=$BUILD_DIR/$GUEST_APP
+ rm -rf "$app"
+ mkdir -p "$app/Contents/MacOS" || return 1
+ xcrun swiftc -O -target arm64-apple-macos13.0 "$AD_PROVIDER_DIR/guestagent.swift" -o "$app/Contents/MacOS/$GUEST_AGENT" || return 1
+ cat > "$app/Contents/Info.plist" <<PLIST || return 1
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleIdentifier</key>
+ <string>com.agent-desktop.guest</string>
+ <key>CFBundleName</key>
+ <string>$GUEST_AGENT</string>
+ <key>CFBundleExecutable</key>
+ <string>$GUEST_AGENT</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleVersion</key>
+ <string>1</string>
+ <key>LSMinimumSystemVersion</key>
+ <string>13.0</string>
+ <key>LSUIElement</key>
+ <true/>
+</dict>
+</plist>
+PLIST
+ codesign -f -s - "$app"
+}
+
do_install() {
if provider_ready; then
emit_ok ready "The macOS VM provider is ready."
@@ -162,8 +189,8 @@ do_install() {
emit_fail ACTION_FAILED "The macOS VM build directory is not writable." "Make $AD_PROVIDER_DIR writable, then run agent-desktop sandbox install macos."
return 1
fi
- if [ ! -f "$AD_PROVIDER_DIR/vmhost.swift" ] || [ ! -f "$AD_PROVIDER_DIR/vm.entitlements" ]; then
- printf '%s\n' "The VM host source or entitlements file is missing from $AD_PROVIDER_DIR." >> "$BUILD_LOG"
+ if [ ! -f "$AD_PROVIDER_DIR/vmhost.swift" ] || [ ! -f "$AD_PROVIDER_DIR/guestagent.swift" ] || [ ! -f "$AD_PROVIDER_DIR/vm.entitlements" ]; then
+ printf '%s\n' "The VM host source, guest agent source or entitlements file is missing from $AD_PROVIDER_DIR." >> "$BUILD_LOG"
emit_fail ACTION_FAILED "The macOS VM host could not be installed; see $BUILD_LOG." "Read $BUILD_LOG, then run agent-desktop sandbox install macos again."
return 1
fi
@@ -177,26 +204,28 @@ do_install() {
emit_fail ACTION_FAILED "The macOS VM host could not be signed; see $BUILD_LOG." "Read $BUILD_LOG, then run agent-desktop sandbox install macos again."
return 1
fi
+ if ! build_guest_agent >> "$BUILD_LOG" 2>&1; then
+ rm -rf "$BUILD_DIR/vmhost" "$BUILD_DIR/$GUEST_APP"
+ emit_fail ACTION_FAILED "The macOS guest agent could not be compiled and signed; see $BUILD_LOG." "Read $BUILD_LOG, then run agent-desktop sandbox install macos again."
+ return 1
+ fi
if ! provider_ready; then
rm -f "$BUILD_DIR/vmhost"
printf '%s\n' 'The signed VM host does not contain the virtualization entitlement.' >> "$BUILD_LOG"
emit_fail ACTION_FAILED "The macOS VM host is missing its virtualization entitlement; see $BUILD_LOG." "Read $BUILD_LOG, then run agent-desktop sandbox install macos again."
return 1
fi
- emit_ok ready "The macOS VM host was built and signed; the provider is ready."
+ emit_ok ready "The macOS VM host and guest agent were built and signed; the provider is ready."
}
vm_bundle_complete() {
[ -f "$1/Disk.img" ] && [ -f "$1/AuxiliaryStorage" ] && \
[ -f "$1/HardwareModel" ] && [ -f "$1/MachineIdentifier" ] && [ -f "$1/config.json" ] && \
- [ -f "$1/share/guest-setup.sh" ] && [ -f "$1/share/id_ed25519.pub" ] && \
- [ -f "$1/share/agent-desktop" ]
+ [ -f "$1/share/guest-setup.sh" ]
}
target_has_sandbox_data() {
- [ -e "$VM_DIR" ] || [ -e "$AD_SANDBOX_DIR/id_ed25519" ] || \
- [ -e "$AD_SANDBOX_DIR/id_ed25519.pub" ] || [ -e "$AD_SANDBOX_DIR/known_hosts" ] || \
- [ -e "$AD_SANDBOX_DIR/guest_user" ] || [ -e "$AD_SANDBOX_DIR/setup_done" ]
+ [ -e "$VM_DIR" ] || [ -e "$AD_SANDBOX_DIR/setup_done" ]
}
vmhost_is_live() {
@@ -312,41 +341,47 @@ catalog_firmware() {
'
}
+# The VM mounts <vm dir>/share read-only. A guest keeps the first content it reads from a shared file and loses a
+# name the host replaces, so the host's agent-desktop build goes under builds/<id>, a name that is new for every
+# build, and exec tells the guest agent which id to run. Prints the id.
+share_build() {
+ host_helper=$(host_helper_path)
+ [ -f "$AD_BINARY" ] && [ -x "$host_helper" ] || return 1
+ build_id=$(cat "$AD_BINARY" "$host_helper" 2>/dev/null | shasum -a 1 | cut -c1-40)
+ [ "${#build_id}" -eq 40 ] || return 1
+ builds=$1/share/builds
+ if [ ! -d "$builds/$build_id" ]; then
+ staged=$builds/.$build_id.$$
+ mkdir -p "$staged" && cp "$AD_BINARY" "$staged/agent-desktop" && cp "$host_helper" "$staged/$HELPER_NAME" && \
+ chmod 0755 "$staged/agent-desktop" "$staged/$HELPER_NAME" || return 1
+ mv "$staged" "$builds/$build_id" 2>/dev/null || rm -rf "$staged"
+ [ -d "$builds/$build_id" ] || return 1
+ fi
+ printf '%s\n' "$build_id"
+}
+
+# Fills the shared folder of a stopped sandbox: the setup script, the guest agent, and the current build alone.
+# agent-desktop 1.3.0 calls a sandbox without share/agent-desktop and share/id_ed25519.pub broken and tells its
+# caller to remove it, so both names stay present for a caller that still runs that version.
copy_guest_share() {
share=$1/share
- host_helper=$(host_helper_path)
- if [ ! -f "$AD_BINARY" ] || [ ! -f "$host_helper" ] || [ ! -x "$host_helper" ]; then
- return 1
- fi
+ [ -d "$BUILD_DIR/$GUEST_APP" ] || return 1
mkdir -p "$share" || return 1
- cp "$AD_PROVIDER_DIR/guest-setup.sh" "$share/guest-setup.sh" || return 1
- cp "$AD_SANDBOX_DIR/id_ed25519.pub" "$share/id_ed25519.pub" || return 1
- cp "$AD_BINARY" "$share/agent-desktop" || return 1
- cp "$host_helper" "$share/$HELPER_NAME" || return 1
- chmod 0755 "$share/guest-setup.sh" "$share/agent-desktop" "$share/$HELPER_NAME" || return 1
+ rm -rf "$share/builds" "$share/$GUEST_APP" "$share/$HELPER_NAME" || return 1
+ for required_by_1_3_0 in agent-desktop id_ed25519.pub; do
+ [ -f "$share/$required_by_1_3_0" ] || : > "$share/$required_by_1_3_0" || return 1
+ done
+ cp "$AD_PROVIDER_DIR/guest-setup.sh" "$share/guest-setup.sh" && chmod 0755 "$share/guest-setup.sh" && \
+ cp -R "$BUILD_DIR/$GUEST_APP" "$share/$GUEST_APP" || return 1
+ share_build "$1" >/dev/null
}
-create_guest_identity() {
- guest_user=${AD_SET_USER:-}
- if [ -z "$guest_user" ]; then guest_user=$(id -un 2>/dev/null || true); fi
- if [ -z "$guest_user" ]; then
- emit_fail ACTION_FAILED "The guest user name could not be determined." "Run agent-desktop sandbox create $1 --set user=<name>."
- return 1
- fi
- if ! valid_guest_user "$guest_user"; then
- emit_fail INVALID_ARGS "The guest user name contains unsupported characters." "Run agent-desktop sandbox create $1 --set user=<short-name>."
- return 1
- fi
- if ! ssh-keygen -t ed25519 -N '' -f "$AD_SANDBOX_DIR/id_ed25519" >/dev/null 2>&1; then
- emit_fail ACTION_FAILED "The SSH key for sandbox $1 could not be created." "Run agent-desktop sandbox create $1 again."
- return 1
- fi
- if ! chmod 0600 "$AD_SANDBOX_DIR/id_ed25519" || \
- ! : > "$AD_SANDBOX_DIR/known_hosts" || \
- ! printf '%s\n' "$guest_user" > "$AD_SANDBOX_DIR/guest_user"; then
- emit_fail ACTION_FAILED "The SSH settings for sandbox $1 could not be saved securely." "Run agent-desktop sandbox create $1 again after checking directory permissions."
- return 1
- fi
+# A sandbox that was set up over SSH has no guest agent, so its setup record is dropped with its key files and
+# the next start opens the setup window once.
+retire_ssh_setup() {
+ [ -e "$AD_SANDBOX_DIR/id_ed25519" ] || return 0
+ rm -f "$AD_SANDBOX_DIR/setup_done" "$AD_SANDBOX_DIR/id_ed25519" "$AD_SANDBOX_DIR/id_ed25519.pub" \
+ "$AD_SANDBOX_DIR/known_hosts" "$AD_SANDBOX_DIR/guest_user" "$VM_DIR/host_key.pub" "$VM_DIR/ssh_refused"
}
file_mtime() {
@@ -454,10 +489,9 @@ reject_unknown_settings() {
do_create() {
name=$1
- reject_unknown_settings "ipsw from user" || return 1
+ reject_unknown_settings "ipsw from" || return 1
reject_empty_setting "${AD_SET_IPSW+x}" "${AD_SET_IPSW:-}" ipsw "$name" || return 1
reject_empty_setting "${AD_SET_FROM+x}" "${AD_SET_FROM:-}" from "$name" || return 1
- reject_empty_setting "${AD_SET_USER+x}" "${AD_SET_USER:-}" user "$name" || return 1
case ${AD_SET_FROM:+from}${AD_SET_IPSW:+ipsw} in
from|ipsw) ;;
*)
@@ -465,10 +499,6 @@ do_create() {
return 1
;;
esac
- if [ -n "${AD_SET_FROM:-}" ] && [ -n "${AD_SET_USER:-}" ]; then
- emit_fail INVALID_ARGS "The user setting applies only to an install; a clone keeps its source's guest user." "Run agent-desktop sandbox create $name --set from=$AD_SET_FROM without --set user."
- return 1
- fi
if target_has_sandbox_data; then
emit_fail ACTION_FAILED "Sandbox $name already has provider data." "Run agent-desktop sandbox status $name."
return 1
@@ -498,15 +528,6 @@ do_create() {
return 1
fi
fi
- guest_name=${AD_SET_USER:-$(id -un 2>/dev/null || true)}
- if [ -z "$guest_name" ]; then
- emit_fail ACTION_FAILED "The guest user name could not be determined." "Run agent-desktop sandbox create $name --set user=<name>."
- return 1
- fi
- if ! valid_guest_user "$guest_name"; then
- emit_fail INVALID_ARGS "The guest user name contains unsupported characters." "Run agent-desktop sandbox create $name --set user=<short-name>."
- return 1
- fi
if [ "$image_path" = latest ]; then
if ! resolved=$(latest_image "$AD_SANDBOX_DIR/restore.ipsw.catalog"); then
emit_fail ACTION_FAILED "$resolved" "Run agent-desktop sandbox create $name --set ipsw=<path> with a macOS image this Mac can install, or update macOS on this host."
@@ -516,7 +537,6 @@ do_create() {
AD_IMAGE_SHA1=$(printf '%s\n' "$resolved" | sed -n '2p')
export AD_IMAGE_URL AD_IMAGE_SHA1
fi
- if ! create_guest_identity "$name"; then return 1; fi
start_install_job "$name" "$image_path"
}
@@ -534,165 +554,18 @@ create_clone() {
emit_fail ACTION_FAILED "Sandbox $source_name is $source_phase, and only a stopped, set-up sandbox can be cloned." "Run agent-desktop sandbox status $source_name."
return 1
fi
- if ! cp "$source/id_ed25519" "$source/id_ed25519.pub" "$source/known_hosts" "$source/guest_user" "$source/setup_done" "$AD_SANDBOX_DIR/" || \
- ! chmod 0600 "$AD_SANDBOX_DIR/id_ed25519"; then
- emit_fail ACTION_FAILED "The SSH settings could not be copied from sandbox $source_name." "Run agent-desktop sandbox status $source_name."
- return 1
- fi
if ! clone_reply=$("$VMHOST" clone "$source/vm" "$VM_DIR" 2>&1); then
emit_fail ACTION_FAILED "The VM for sandbox $name could not be cloned: $clone_reply" "Run agent-desktop sandbox rm $name, fix the cause, then create it again."
return 1
fi
- rm -f "$AD_SANDBOX_DIR/known_hosts" "$AD_SANDBOX_DIR/vm/host_key.pub"
- rotate_status=0
- rotate_host_key || rotate_status=$?
- if [ "$rotate_status" -ne 0 ]; then
- emit_fail ACTION_FAILED "Sandbox $name could not be given its own SSH host key." "Run agent-desktop sandbox rm $name and create it again; a guest disk that cannot be opened cannot be cloned safely."
- return 1
- fi
- if ! copy_guest_share "$VM_DIR"; then
- emit_fail ACTION_FAILED "The guest setup files could not be copied into sandbox $name." "Run agent-desktop sandbox status $name."
+ if ! copy_guest_share "$VM_DIR" || \
+ { [ -f "$source/vm/agent.pub" ] && { ! cp "$source/vm/agent.pub" "$VM_DIR/agent.pub" || ! : > "$AD_SANDBOX_DIR/setup_done"; }; }; then
+ emit_fail ACTION_FAILED "The guest files could not be copied into sandbox $name." "Run agent-desktop sandbox rm $name, then create it again."
return 1
fi
emit_ok stopped "Sandbox $name is a stopped copy of sandbox $source_name." "agent-desktop sandbox start $name"
}
-guest_user() {
- [ -s "$AD_SANDBOX_DIR/guest_user" ] || return 1
- stored_guest_user=$(cat "$AD_SANDBOX_DIR/guest_user" 2>/dev/null || true)
- valid_guest_user "$stored_guest_user" || return 1
- printf '%s\n' "$stored_guest_user"
-}
-
-guest_transport() {
- transport_tool=$1
- shift
- host_key_check=accept-new
- [ -s "$AD_SANDBOX_DIR/vm/host_key.pub" ] && host_key_check=yes
- "$transport_tool" -F /dev/null -i "$AD_SANDBOX_DIR/id_ed25519" \
- -o IdentitiesOnly=yes \
- -o "StrictHostKeyChecking=$host_key_check" \
- -o "UserKnownHostsFile=$AD_SANDBOX_DIR/known_hosts" \
- -o BatchMode=yes \
- -o ConnectTimeout=5 \
- -o ConnectionAttempts=1 \
- -o ServerAliveInterval=3 \
- -o ServerAliveCountMax=3 \
- "$@"
-}
-
-PROBE_REPLY_LIMIT=65536
-
-# The guest decides how much a probe prints, so the host reads at most PROBE_REPLY_LIMIT bytes of the reply and
-# closes the pipe on the rest. Returns the ssh exit status.
-guest_probe() {
- {
- reply_status=$(
- {
- {
- probe_ssh_status=0
- guest_transport ssh "$@" 2>/dev/null 3>&- 4>&- || probe_ssh_status=$?
- printf '%s\n' "$probe_ssh_status" >&3
- } | head -c "$PROBE_REPLY_LIMIT" >&4
- } 3>&1
- )
- } 4>&1
- return "${reply_status:-255}"
-}
-
-detach_guest_disk() {
- disk=$1
- for dev in $(hdiutil info 2>/dev/null | awk -v img="$disk" '$1 == "image-path" { path = $0; sub(/^[^:]*:[[:space:]]*/, "", path); found = (path == img) } found && $1 ~ /^\/dev\/disk/ { print $1 }'); do
- hdiutil detach "$dev" >/dev/null 2>&1 || true
- done
-}
-
-# The guest chooses every path on its disk, so the keys are written only through directories and files that are
-# opened without following a symlink and that sit on the mounted volume. Exits 2 when the host key is not on it.
-write_guest_host_key() {
- perl -e '
- BEGIN { $SIG{__DIE__} = sub { exit 1 } }
- use strict;
- use Fcntl qw(:mode O_WRONLY O_CREAT O_NOFOLLOW O_NONBLOCK);
- my ($volume_root, @sources) = @ARGV;
- my @contents;
- for my $source (@sources) {
- open(my $in, "<", $source) or exit 1;
- my $bytes = do { local $/; <$in> };
- defined $bytes or exit 1;
- push @contents, $bytes;
- }
- chdir $volume_root or exit 1;
- my @root = stat "." or exit 1;
- my $volume = $root[0];
- for my $part (qw(private etc ssh)) {
- my @seen = lstat $part or exit($!{ENOENT} ? 2 : 1);
- $seen[0] == $volume or exit 2;
- S_ISDIR($seen[2]) or exit 1;
- chdir $part or exit 1;
- my @entered = stat "." or exit 1;
- $entered[0] == $seen[0] && $entered[1] == $seen[1] or exit 1;
- }
- my @writes;
- for my $target (["ssh_host_ed25519_key", 0], ["ssh_host_ed25519_key.pub", O_CREAT]) {
- my ($name, $create) = @$target;
- sysopen(my $out, $name, O_WRONLY | O_NOFOLLOW | O_NONBLOCK | $create, 0644) or exit($!{ENOENT} ? 2 : 1);
- my @held = stat $out or exit 1;
- S_ISREG($held[2]) && $held[0] == $volume or exit 1;
- push @writes, [$out, shift @contents];
- }
- for my $write (@writes) {
- my ($out, $bytes) = @$write;
- truncate($out, 0) or exit 1;
- (syswrite($out, $bytes) // -1) == length($bytes) or exit 1;
- close($out) or exit 1;
- }
- ' "$1" "$2" "$3"
-}
-
-rotate_host_key() {
- disk=$AD_SANDBOX_DIR/vm/Disk.img
- pub=$AD_SANDBOX_DIR/vm/host_key.pub
- [ -s "$pub" ] && return 0
- [ -f "$disk" ] || return 2
- tmp=$(mktemp -d "${TMPDIR:-/tmp}/ad-host-key.XXXXXX") || return 1
- if ! ssh-keygen -q -t ed25519 -N '' -C agent-desktop-sandbox-host -f "$tmp/key" >/dev/null 2>&1; then
- rm -rf "$tmp"
- return 1
- fi
- detach_guest_disk "$disk"
- if ! attach=$(hdiutil attach "$disk" -imagekey diskimage-class=CRawDiskImage -owners off -noverify -noautoopen 2>/dev/null); then
- rm -rf "$tmp"
- return 1
- fi
- printf '%s\n' "$attach" | awk -F '\t' '$3 ~ /^\// { print $3 }' > "$tmp/mounts"
- write_status=2
- while IFS= read -r mount_point; do
- write_status=0
- write_guest_host_key "$mount_point" "$tmp/key" "$tmp/key.pub" || write_status=$?
- [ "$write_status" -eq 2 ] || break
- done < "$tmp/mounts"
- detach_guest_disk "$disk"
- if [ "$write_status" -ne 0 ]; then
- rm -rf "$tmp"
- return "$write_status"
- fi
- if ! cp "$tmp/key.pub" "$pub"; then
- rm -rf "$tmp"
- return 1
- fi
- rm -rf "$tmp"
- return 0
-}
-
-pin_host_key() {
- ip=$1
- pub=$AD_SANDBOX_DIR/vm/host_key.pub
- [ -s "$pub" ] || return 0
- printf '%s %s\n' "$ip" "$(awk 'NR == 1 { print $1, $2 }' "$pub")" > "$AD_SANDBOX_DIR/known_hosts" || return 1
- chmod 0600 "$AD_SANDBOX_DIR/known_hosts"
-}
-
# A guest that needs a person is only reachable through its window, so a headless one must be restarted.
window_is_open() {
ps -ww -o command= -p "$(cat "$VM_DIR/vmhost.pid" 2>/dev/null)" 2>/dev/null | grep -q -- '--window'
@@ -707,88 +580,74 @@ needs_setup() {
fi
}
-setup_window() {
- needs_setup "Sandbox $1 is running in a setup window; enable Remote Login, run guest-setup.sh in Terminal, and grant Accessibility permission." "$1"
-}
+GUEST_STEPS='In the guest, turn on automatic login in System Settings > Users & Groups, run sh "/Volumes/My Shared Files/guest-setup.sh" in Terminal, then switch on agent-desktop-guest in System Settings > Privacy & Security > Accessibility.'
-ssh_refused_too_long() {
- [ -f "$VM_DIR/ssh_refused" ] || printf '' > "$VM_DIR/ssh_refused" 2>/dev/null || return 1
- refused_since=$(file_mtime "$VM_DIR/ssh_refused")
- case $refused_since in ''|*[!0-9]*|0) return 1 ;; esac
- [ $(( $(date +%s) - refused_since )) -ge 120 ]
+setup_window() {
+ needs_setup "Sandbox $1 is open in a setup window. $GUEST_STEPS" "$1"
}
+# The guest agent starts with the guest's login. Silence may be a slow start as well as a lost agent, so it never
+# drops the setup record: a guest that answers later is running again without anyone touching it.
guest_not_answering() {
- if [ -f "$AD_SANDBOX_DIR/setup_done" ]; then
- if [ -n "${2:-}" ] && ssh_refused_too_long; then
- needs_setup "Sandbox $1 has had a network address for over two minutes, but Remote Login refuses the guest user $2. Check in the guest that Remote Login is on and that this account exists." "$1"
- return 0
- fi
- emit_ok working "Sandbox $1 is running and the guest is still starting." "agent-desktop sandbox status $1"
+ if [ ! -f "$AD_SANDBOX_DIR/setup_done" ]; then
+ needs_setup "The guest agent in sandbox $1 is not answering. $GUEST_STEPS" "$1"
+ return 0
+ fi
+ started=$(file_mtime "$VM_DIR/vmhost.started")
+ case $started in ''|*[!0-9]*) started=0 ;; esac
+ if [ "$started" -gt 0 ] && [ $(( $(date +%s) - started )) -ge 120 ]; then
+ emit_ok needs_setup "Sandbox $1 has run for over two minutes and its guest agent is not answering. A guest that is still starting answers later, so check again. If it stays silent, stop the sandbox and start it with --window. $GUEST_STEPS" "agent-desktop sandbox status $1"
else
- needs_setup "Remote Login is unreachable, agent-desktop is not installed, and Accessibility is not granted in the guest." "$1"
+ emit_ok working "Sandbox $1 is running and the guest is still starting." "agent-desktop sandbox status $1"
fi
}
-missing_guest_binary() {
- next="agent-desktop sandbox status $1"
- [ ! -f "$AD_SANDBOX_DIR/setup_done" ] || next="agent-desktop sandbox exec $1 -- version"
- emit_ok needs_setup "agent-desktop is not installed in the guest, so Accessibility permission cannot yet be checked." "$next"
-}
-
vmhost_missing() {
emit_fail ACTION_FAILED "The macOS VM host is not installed." "Run agent-desktop sandbox install macos."
}
+# Setup is complete when the guest agent reports Accessibility. Its key is recorded with it; from then on the VM
+# host sends work only to a process that proves that key, because any guest account can listen on the agent's port.
+record_setup() {
+ if [ ! -f "$VM_DIR/agent.pub" ]; then
+ agent_key=$(printf '%s\n' "$1" | sed -n 's/.*"key":"\([0-9a-f]\{64\}\)".*/\1/p')
+ [ -n "$agent_key" ] && printf '%s\n' "$agent_key" > "$VM_DIR/agent.pub" || return 1
+ fi
+ [ -f "$AD_SANDBOX_DIR/setup_done" ] || printf '' > "$AD_SANDBOX_DIR/setup_done"
+}
+
check_guest_setup() {
name=$1
- if ! user=$(guest_user); then
- needs_setup "Sandbox $name needs a guest user before SSH setup can continue." "$name"
- return 0
- fi
if [ ! -x "$VMHOST" ]; then
vmhost_missing
return 1
fi
- ip_json=$("$VMHOST" ip "$VM_DIR" 2>/dev/null || true)
- ip=$(printf '%s' "$ip_json" | sed -n 's/.*"ip"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
- if [ -z "$ip" ]; then
- guest_not_answering "$name"
- return 0
- fi
- if ! pin_host_key "$ip"; then
- emit_fail ACTION_FAILED "The SSH host key for sandbox $name could not be saved." "Run agent-desktop sandbox status $name again after checking directory permissions."
- return 1
- fi
- target=$user@$ip
- probe_status=0
- permissions=$(guest_probe "$target" 'if [ ! -x ~/.local/bin/agent-desktop ]; then exit 3; fi; ~/.local/bin/agent-desktop permissions') || probe_status=$?
- if [ "$probe_status" -eq 255 ]; then
- guest_not_answering "$name" "$user"
+ guest_status=0
+ guest_state=$("$VMHOST" status "$VM_DIR" 2>/dev/null) || guest_status=$?
+ if [ "$guest_status" -eq 4 ]; then
+ emit_ok needs_setup "The process answering in sandbox $name is not the guest agent that was set up, so nothing is sent to it. Stop the sandbox, start it with --window, and check which account is logged in. $GUEST_STEPS" "agent-desktop sandbox status $name"
return 0
fi
- rm -f "$VM_DIR/ssh_refused"
- if [ "$probe_status" -eq 3 ]; then
- missing_guest_binary "$name"
+ if [ "$guest_status" -ne 0 ]; then
+ guest_not_answering "$name"
return 0
fi
- compact=$(printf '%s' "$permissions" | tr -d '[:space:]')
- case $compact in
- *'"accessibility":{"state":"granted"'*)
- if [ ! -f "$AD_SANDBOX_DIR/setup_done" ] && ! printf '' > "$AD_SANDBOX_DIR/setup_done"; then
+ case $guest_state in
+ *'"accessibility":true'*)
+ if ! record_setup "$guest_state"; then
emit_fail ACTION_FAILED "The setup record for sandbox $name could not be saved." "Run agent-desktop sandbox status $name again after checking directory permissions."
return 1
fi
emit_ok running "Sandbox $name is running and guest setup is complete."
;;
- *) needs_setup "Accessibility permission is not granted for agent-desktop in the guest." "$name" ;;
+ *) needs_setup "Accessibility is off for agent-desktop-guest in sandbox $name. In the guest, switch it on in System Settings > Privacy & Security > Accessibility." "$name" ;;
esac
}
spawn_vmhost() {
mode=$1
if [ ! -x "$VMHOST" ] || ! command -v nohup >/dev/null 2>&1 || \
- ! : >> "$VM_DIR/vmhost.log" || ! rm -f "$VM_DIR/vmhost.started" "$VM_DIR/ssh_refused"; then
+ ! : >> "$VM_DIR/vmhost.log" || ! rm -f "$VM_DIR/vmhost.started"; then
return 1
fi
if [ "$mode" = window ]; then
@@ -818,10 +677,11 @@ do_start() {
return 1
;;
esac
- mode=headless
- if [ ! -f "$AD_SANDBOX_DIR/setup_done" ] || [ "${AD_SET_WINDOW:-off}" = on ] || [ -n "${AD_SET_TITLE:-}" ]; then mode=window; fi
phase=$(sandbox_phase "$AD_SANDBOX_DIR")
if report_phase "$name" "$phase"; then return 0; fi
+ if [ "$phase" = stopped ]; then retire_ssh_setup; fi
+ mode=headless
+ if [ ! -f "$AD_SANDBOX_DIR/setup_done" ] || [ "${AD_SET_WINDOW:-off}" = on ] || [ -n "${AD_SET_TITLE:-}" ]; then mode=window; fi
if [ "$phase" = running ] && [ "$mode" = window ] && ! window_is_open; then
emit_fail INVALID_ARGS "Sandbox $name is already running without a window." "Run agent-desktop sandbox stop $name, then start it again with --window."
return 1
@@ -832,10 +692,8 @@ do_start() {
vmhost_missing
return 1
fi
- rotate_status=0
- rotate_host_key || rotate_status=$?
- if [ "$rotate_status" -ne 0 ] && [ "$rotate_status" -ne 2 ]; then
- emit_fail ACTION_FAILED "Sandbox $name could not be given its own SSH host key." "Run agent-desktop sandbox status $name; a guest disk that cannot be opened cannot be started safely."
+ if ! copy_guest_share "$VM_DIR"; then
+ emit_fail ACTION_FAILED "The guest files for sandbox $name could not be placed in its shared folder." "Rebuild agent-desktop with its helper, then run agent-desktop sandbox start $name again."
return 1
fi
if ! spawn_vmhost "$mode"; then
@@ -912,32 +770,6 @@ do_rm() {
emit_ok stopped "The VM files for sandbox $name were removed."
}
-shell_quote() {
- printf "'"
- printf '%s' "$1" | sed "s/'/'\\\\''/g"
- printf "'"
-}
-
-sync_guest_file() {
- target=$1
- source_file=$2
- guest_name=$3
- host_hash=$4
- guest_hash=$5
- if [ "$host_hash" = "$guest_hash" ]; then return 0; fi
- staged="~/.local/bin/$guest_name.$$.new"
- if ! guest_transport ssh "$target" 'mkdir -p ~/.local/bin' >/dev/null || \
- ! guest_transport scp "$source_file" "$target:$staged" >/dev/null || \
- ! guest_transport ssh "$target" "chmod 755 $staged && mv -f $staged ~/.local/bin/$guest_name" >/dev/null; then
- guest_transport ssh "$target" "rm -f $staged" >/dev/null 2>&1 || true
- return 1
- fi
-}
-
-remote_login_failure() {
- exec_failure "Remote Login could not be reached in sandbox $1." "Run agent-desktop sandbox status $1."
-}
-
exec_failure() {
emit_fail ACTION_FAILED "$1" "$2"
exit 125
@@ -963,71 +795,14 @@ do_exec() {
if ! require_host_package "Rebuild agent-desktop with its helper, then run sandbox exec $name again."; then
exit 125
fi
- user=$(guest_user || true)
- if [ -z "$user" ]; then
- exec_failure "Sandbox $name has no configured guest user." "Run agent-desktop sandbox status $name."
- fi
if [ ! -x "$VMHOST" ]; then
vmhost_missing
exit 125
fi
- ip_json=$("$VMHOST" ip "$VM_DIR" 2>/dev/null || true)
- ip=$(printf '%s' "$ip_json" | sed -n 's/.*"ip"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
- if [ -z "$ip" ]; then
- exec_failure "Sandbox $name has no reachable guest address yet." "Run agent-desktop sandbox status $name."
- fi
- if ! pin_host_key "$ip"; then
- exec_failure "The SSH host key for sandbox $name could not be saved." "Run agent-desktop sandbox status $name again after checking directory permissions."
- fi
- if ! host_hash_line=$(shasum -a 1 "$AD_BINARY" 2>/dev/null); then
- exec_failure "The host agent-desktop binary could not be hashed." "Rebuild agent-desktop, then run sandbox exec $name again."
- fi
- host_helper=$(host_helper_path)
- if ! host_helper_hash_line=$(shasum -a 1 "$host_helper" 2>/dev/null); then
- exec_failure "The host $HELPER_NAME binary could not be hashed." "Rebuild agent-desktop with its helper, then run sandbox exec $name again."
- fi
- host_hash=$(printf '%s\n' "$host_hash_line" | awk '{ print tolower($1) }')
- host_helper_hash=$(printf '%s\n' "$host_helper_hash_line" | awk '{ print tolower($1) }')
- target=$user@$ip
- probe_status=0
- guest_hash_line=$(guest_probe "$target" 'shasum -a 1 ~/.local/bin/agent-desktop') || probe_status=$?
- if [ "$probe_status" -eq 255 ]; then remote_login_failure "$name"; fi
- guest_hash=$(printf '%s\n' "$guest_hash_line" | awk '{ print tolower($1) }')
- probe_status=0
- guest_helper_hash_line=$(guest_probe "$target" "shasum -a 1 ~/.local/bin/$HELPER_NAME") || probe_status=$?
- if [ "$probe_status" -eq 255 ]; then remote_login_failure "$name"; fi
- guest_helper_hash=$(printf '%s\n' "$guest_helper_hash_line" | awk '{ print tolower($1) }')
- if ! sync_guest_file "$target" "$AD_BINARY" agent-desktop "$host_hash" "$guest_hash"; then
- exec_failure "agent-desktop could not be copied into sandbox $name." "Run agent-desktop sandbox status $name."
- fi
- if ! sync_guest_file "$target" "$host_helper" "$HELPER_NAME" "$host_helper_hash" "$guest_helper_hash"; then
- exec_failure "The macOS clipboard helper could not be copied into sandbox $name." "Run agent-desktop sandbox status $name."
- fi
- exec_marker="AD_EXEC_EXIT_$$"
- remote_command='~/.local/bin/agent-desktop'
- for argument do
- remote_command="$remote_command $(shell_quote "$argument")"
- done
- remote_command="$remote_command; ad_status=\$?; printf '%s:%s\\n' '$exec_marker' \"\$ad_status\" >&2; exit \"\$ad_status\""
- if ! exec_stderr=$(mktemp "$AD_SANDBOX_DIR/exec-stderr.XXXXXX"); then
- exec_failure "The exec output file for sandbox $name could not be created." "Run agent-desktop sandbox status $name."
- fi
- trap 'rm -f "$exec_stderr" "$exec_stderr.status"' EXIT
- # The guest controls how much it writes to stderr, so only the last 64 KiB ever reaches the host disk.
- exec 3>&1
- {
- ssh_status=0
- guest_transport ssh "$target" "$remote_command" 2>&1 >&3 || ssh_status=$?
- printf '%s\n' "$ssh_status" > "$exec_stderr.status"
- } | tail -c 65536 > "$exec_stderr"
- exec 3>&-
- ssh_status=$(cat "$exec_stderr.status" 2>/dev/null || printf '255\n')
- guest_status=$(sed -n "s/^.*$exec_marker:\([0-9][0-9]*\)\$/\1/p" "$exec_stderr" | tail -n 1)
- sed -e "/^$exec_marker:[0-9][0-9]*\$/d" -e "s/$exec_marker:[0-9][0-9]*\$//" "$exec_stderr" >&2
- if [ "$ssh_status" -eq 255 ] && [ -z "$guest_status" ]; then
- remote_login_failure "$name"
+ if ! build_id=$(share_build "$VM_DIR"); then
+ exec_failure "agent-desktop could not be placed in the shared folder of sandbox $name." "Run agent-desktop sandbox status $name."
fi
- return "${guest_status:-$ssh_status}"
+ exec "$VMHOST" exec "$VM_DIR" "$build_id" "$@"
}
require_provider_environment
diff --git a/providers/macos/test-guest-channel.sh b/providers/macos/test-guest-channel.sh
new file mode 100644
index 000000000..25746cbc1
--- /dev/null
+++ b/providers/macos/test-guest-channel.sh
@@ -0,0 +1,178 @@
+#!/bin/sh
+set -eu
+
+here=$(cd "$(dirname "$0")" && pwd)
+tmp=$(mktemp -d /tmp/adgc.XXXXXX)
+vm=$tmp/box/vm
+build=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
+peer_pid=
+agent_pid=
+cleanup() {
+ kill $peer_pid $agent_pid 2>/dev/null || true
+ rm -rf "$tmp"
+}
+trap cleanup 0
+trap 'exit 1' 1 2 3 15
+mkdir -p "$vm" "$tmp/guest" "$tmp/other" "$tmp/share/builds/$build"
+: > "$tmp/out"
+: > "$tmp/err"
+
+fail() {
+ printf 'FAIL: %s\n%s\n' "$1" "$(cat "$tmp/out" "$tmp/err" | head -c 2000)" >&2
+ exit 1
+}
+
+xcrun swiftc -Onone "$here/vmhost.swift" -o "$tmp/vmhost" 2> "$tmp/err" || fail 'the VM host did not compile'
+xcrun swiftc -Onone -D GUEST_AGENT_TEST "$here/guestagent.swift" -o "$tmp/agent" 2> "$tmp/err" || fail 'the guest agent did not compile'
+
+# A process on the agent's port. "impostor" replays a proof the real agent gave for another nonce; every other
+# scenario relays the real agent's proof for this nonce and then answers one request itself.
+cat > "$tmp/guest.py" <<'PY'
+import socket, struct, sys
+path, scenario, agent, record = sys.argv[1:5]
+def frame(kind, payload=b""):
+ return bytes([kind]) + struct.pack(">I", len(payload)) + payload
+replies = {
+ "oversized": bytes([1]) + struct.pack(">I", 65537) + b"x" * 65537,
+ "unknown-kind": frame(9),
+ "truncated": bytes([1]) + struct.pack(">I", 10) + b"abc",
+ "complete": frame(1, b"ran\n") + frame(3, struct.pack(">I", 0)),
+ "status-extra": frame(1, b'{"accessibility":true,"agent":1,"evil":"<x>"}\n') + frame(3, struct.pack(">I", 0)),
+}
+server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+server.bind(path)
+server.listen(1)
+open(path + ".ready", "w").close()
+conn, _ = server.accept()
+nonce = conn.recv(32, socket.MSG_WAITALL)
+real = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+real.connect(agent)
+real.sendall(bytes(32) if scenario == "impostor" else nonce)
+conn.sendall(real.recv(96, socket.MSG_WAITALL))
+if scenario == "impostor":
+ conn.settimeout(1)
+ try:
+ open(record, "wb").write(conn.recv(4096))
+ except OSError:
+ open(record, "wb").close()
+else:
+ header = conn.recv(4, socket.MSG_WAITALL)
+ if len(header) == 4:
+ conn.recv(struct.unpack(">I", header)[0], socket.MSG_WAITALL)
+ conn.sendall(replies[scenario])
+conn.close()
+PY
+
+wait_for() {
+ tries=0
+ while [ ! -e "$1" ]; do
+ tries=$((tries + 1))
+ [ "$tries" -lt 100 ] || fail "$1 never appeared"
+ sleep 0.1
+ done
+}
+
+stop() {
+ [ -n "$1" ] || return 0
+ kill "$1" 2>/dev/null || true
+ wait "$1" 2>/dev/null || true
+}
+
+# agent <socket> <guest directory> [NAME=VALUE...]: starts the real guest agent, built for tests, on a socket file.
+agent() {
+ stop "$agent_pid"
+ rm -f "$vm/$1"
+ agent_socket=$1
+ agent_guest=$2
+ shift 2
+ (cd "$vm" && exec env GUEST_TEST_SOCKET="$agent_socket" GUEST_TEST_SHARE="$tmp/share" GUEST_TEST_HOME="$agent_guest" "$@" "$tmp/agent" 2>> "$tmp/agent.log") &
+ agent_pid=$!
+ wait_for "$vm/$agent_socket"
+}
+
+# scripted_guest <scenario>: puts the scripted process behind the sandbox's control socket.
+scripted_guest() {
+ stop "$peer_pid"
+ rm -f "$vm/vmhost.sock" "$vm/vmhost.sock.ready" "$tmp/received"
+ (cd "$vm" && exec python3 "$tmp/guest.py" vmhost.sock "$1" agent.sock "$tmp/received" 2> /dev/null) &
+ peer_pid=$!
+ wait_for "$vm/vmhost.sock.ready"
+}
+
+# call <vmhost arguments>: runs the real VM host client and keeps its exit status, stdout and stderr.
+call() {
+ status=0
+ "$tmp/vmhost" "$@" > "$tmp/out" 2> "$tmp/err" || status=$?
+}
+
+refused() {
+ [ "$status" = 125 ] && grep -q '"code":"ACTION_FAILED"' "$tmp/out" || fail "$1: exit $status without a provider failure"
+ [ "$(wc -l < "$tmp/out" | tr -d ' ')" = 1 ] && [ "$(wc -c < "$tmp/out" | tr -d ' ')" -lt 1024 ] || fail "$1: guest bytes reached stdout beside the failure"
+}
+
+agent agent.sock "$tmp/guest"
+scripted_guest status-extra
+call status "$vm"
+key=$(sed -n 's/.*"key":"\([0-9a-f]\{64\}\)".*/\1/p' "$tmp/out")
+[ "$status" = 0 ] && [ "$(cat "$tmp/out")" = "{\"accessibility\":true,\"agent\":1,\"key\":\"$key\",\"ok\":true}" ] || fail 'a status reply passed a field the guest added'
+
+scripted_guest complete
+call exec "$vm" "$build" version
+refused 'exec before the guest agent key is recorded'
+printf '%s\n' "$key" > "$vm/agent.pub"
+
+for scenario in oversized unknown-kind truncated; do
+ scripted_guest "$scenario"
+ call exec "$vm" "$build" version
+ refused "a guest that answers with a $scenario frame"
+done
+
+scripted_guest impostor
+call exec "$vm" "$build" type 'a secret'
+refused 'a process that cannot prove the guest agent key'
+wait "$peer_pid" 2>/dev/null || true
+[ -f "$tmp/received" ] && [ ! -s "$tmp/received" ] || fail 'the request reached a process that could not prove the guest agent key'
+
+cat > "$tmp/share/builds/$build/agent-desktop" <<'GUEST'
+#!/bin/sh
+for argument do printf '[%s]\n' "$argument"; done
+[ "${1:-}" != hang ] || { printf '%s\n' "$$" > "$GUEST_TEST_HOME/hang.pid"; exec sleep 60; }
+exit "${2:-0}"
+GUEST
+: > "$tmp/share/builds/$build/agent-desktop-macos-helper"
+stop "$peer_pid"
+peer_pid=
+
+agent vmhost.sock "$tmp/guest"
+call exec "$vm" "$build" leave 7 'two words' ''
+[ "$status" = 7 ] && [ "$(cat "$tmp/out")" = "$(printf '[leave]\n[7]\n[two words]\n[]')" ] || fail 'the guest agent changed the arguments or the exit status'
+call exec "$vm" ../../../../etc version
+refused 'a build id that is a path'
+grep -q 'did not name the agent-desktop build' "$tmp/out" || fail 'a build id that is a path was not refused as a build id'
+
+"$tmp/vmhost" exec "$vm" "$build" hang > /dev/null 2>&1 &
+client_pid=$!
+wait_for "$tmp/guest/hang.pid"
+guest_command=$(cat "$tmp/guest/hang.pid")
+kill "$client_pid"
+tries=0
+while kill -0 "$guest_command" 2>/dev/null; do
+ tries=$((tries + 1))
+ [ "$tries" -lt 50 ] || { kill "$guest_command" 2>/dev/null; fail 'the guest command kept running after the host stopped waiting'; }
+ sleep 0.1
+done
+
+rm -f "$tmp/guest/hang.pid"
+agent vmhost.sock "$tmp/guest" GUEST_TEST_PEER=3
+call exec "$vm" "$build" hang
+refused 'a caller that is not the host'
+[ ! -e "$tmp/guest/hang.pid" ] || fail 'the guest agent ran a command for a caller that is not the host'
+
+agent vmhost.sock "$tmp/other"
+call status "$vm"
+[ "$status" = 4 ] || fail "an agent with another account's key: status exit $status, expected 4"
+call exec "$vm" "$build" hang
+refused "an agent with another account's key"
+[ ! -e "$tmp/other/hang.pid" ] || fail "a command ran under an agent with another account's key"
+
+printf 'guest channel tests passed\n'
diff --git a/providers/macos/test-provider.sh b/providers/macos/test-provider.sh
index d39d433f3..2214888b3 100644
--- a/providers/macos/test-provider.sh
+++ b/providers/macos/test-provider.sh
@@ -10,7 +10,7 @@ cleanup() {
}
trap cleanup 0
trap 'exit 1' 1 2 3 15
-mkdir -p "$tmp/bin" "$tmp/provider/build" "$tmp/sandboxes" "$tmp/guest/.local/bin"
+mkdir -p "$tmp/bin" "$tmp/provider" "$tmp/sandboxes" "$tmp/guest/.local/bin"
AD_PROVIDER_DIR=$tmp/provider
AD_BINARY=$tmp/agent-desktop
@@ -21,7 +21,9 @@ FAKE_GUEST_HOME=$tmp/guest
export AD_PROVIDER_DIR AD_BINARY AD_CALLER_CWD VMHOST FAKE_LOG FAKE_GUEST_HOME
printf '#!/bin/sh\n' > "$AD_PROVIDER_DIR/guest-setup.sh"
-: > "$AD_PROVIDER_DIR/build/vmhost"
+printf 'guest agent source\n' > "$AD_PROVIDER_DIR/guestagent.swift"
+mkdir -p "$tmp/bin/agent-desktop-guest.app/Contents/MacOS"
+printf 'guest agent\n' > "$tmp/bin/agent-desktop-guest.app/Contents/MacOS/agent-desktop-guest"
printf 'binary\n' > "$AD_BINARY"
printf 'helper\n' > "$tmp/agent-desktop-macos-helper"
chmod 0755 "$tmp/agent-desktop-macos-helper"
@@ -46,38 +48,6 @@ fake codesign <<'FAKE'
#!/bin/sh
printf 'com.apple.security.virtualization\n'
FAKE
-fake ssh-keygen <<'FAKE'
-#!/bin/sh
-while [ "$#" -gt 0 ]; do
- if [ "$1" = -f ]; then shift; key=$1; fi
- shift
-done
-n=$(cat "$FAKE_KEY_COUNTER" 2>/dev/null || printf '0')
-n=$((n + 1))
-printf '%s\n' "$n" > "$FAKE_KEY_COUNTER"
-printf 'private key %s\n' "$n" > "$key"
-printf 'public key %s\n' "$n" > "$key.pub"
-FAKE
-FAKE_KEY_COUNTER=$tmp/key-counter
-FAKE_VOLUME=$tmp/volume
-export FAKE_KEY_COUNTER FAKE_VOLUME
-fake hdiutil <<'FAKE'
-#!/bin/sh
-[ "${FAKE_HDIUTIL:-ok}" = ok ] || exit 1
-case ${1:-} in
- attach)
- if [ ! -e "$FAKE_VOLUME" ]; then
- mkdir -p "$FAKE_VOLUME/private/etc/ssh"
- : > "$FAKE_VOLUME/private/etc/ssh/ssh_host_ed25519_key"
- : > "$FAKE_VOLUME/private/etc/ssh/ssh_host_ed25519_key.pub"
- fi
- mkdir -p "$FAKE_VOLUME.preboot"
- printf '/dev/disk99s1\tFAKE\t%s\n/dev/disk99s2\tFAKE\t%s\n' "$FAKE_VOLUME.preboot" "$FAKE_VOLUME"
- ;;
- detach) printf 'hdiutil %s\n' "$*" >> "$FAKE_LOG" ;;
- info) printf 'image-path : %s\n/dev/disk99\n' "$AD_SANDBOX_DIR/vm/Disk.img" ;;
-esac
-FAKE
fake pgrep <<'FAKE'
#!/bin/sh
[ "${FAKE_JOB_ALIVE:-0}" = 1 ]
@@ -97,7 +67,28 @@ case $1 in
mkdir -p "$3"
cp "$2/Disk.img" "$3/Disk.img" 2>/dev/null || :
;;
- ip) printf '{"ok":true,"ip":"192.0.2.2"}\n' ;;
+ status)
+ case ${FAKE_GUEST:-granted} in
+ granted) printf '{"accessibility":true,"agent":1,"key":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","ok":true}\n' ;;
+ denied) printf '{"accessibility":false,"agent":1,"key":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","ok":true}\n' ;;
+ impostor) exit 4 ;;
+ silent)
+ printf '{"message":"The guest agent is not answering.","ok":false,"suggestion":"Run it again."}\n'
+ exit 3
+ ;;
+ esac
+ ;;
+ exec)
+ shift 3
+ case ${FAKE_GUEST:-granted} in
+ silent)
+ printf '{"code":"ACTION_FAILED","message":"The guest agent is not answering.","ok":false,"suggestion":"Run agent-desktop sandbox status demo."}\n'
+ exit 125
+ ;;
+ esac
+ HOME=$FAKE_GUEST_HOME "$FAKE_GUEST_HOME/.local/bin/agent-desktop" "$@"
+ exit $?
+ ;;
run)
[ "${FAKE_BOOT:-ok}" = ok ] || exit 1
printf '%s\n' "$$" > "$2/vmhost.pid"
@@ -118,30 +109,6 @@ case $out in
*) printf '%s' "$FAKE_IMAGE" > "$out" ;;
esac
FAKE
-fake scp <<'FAKE'
-#!/bin/sh
-printf 'scp %s\n' "$*" >> "$FAKE_LOG"
-FAKE
-fake ssh <<'FAKE'
-#!/bin/sh
-printf 'ssh %s\n' "$*" >> "$FAKE_LOG"
-for remote do :; done
-[ "${FAKE_SSH:-ok}" != unreachable ] || exit 255
-[ "${FAKE_SSH:-ok}" != no-binary ] || exit 3
-if [ -n "${FAKE_PROBE_FLOOD:-}" ]; then
- case $remote in
- *permissions*|*'shasum -a 1'*)
- head -c 33554432 /dev/zero | tr '\0' 'x' && : > "$FAKE_PROBE_FLOOD"
- exit
- ;;
- esac
-fi
-case $remote in
- *permissions*) printf '{"data":{"accessibility":{"state":"%s"}}}\n' "${FAKE_ACCESSIBILITY:-granted}" ;;
- *'shasum -a 1'*) printf '%s file\n' "${FAKE_GUEST_SHA:-stale}" ;;
- '~/.local/bin/agent-desktop '*) HOME=$FAKE_GUEST_HOME sh -c "$remote" ;;
-esac
-FAKE
cat > "$tmp/guest/.local/bin/agent-desktop" <<'FAKE'
#!/bin/sh
for argument do printf '[%s]\n' "$argument"; done
@@ -197,11 +164,10 @@ put() {
FAKE_JOB_ALIVE=0
FAKE_VM_DIR=$dir/vm
for file in Disk.img AuxiliaryStorage HardwareModel MachineIdentifier config.json \
- share/guest-setup.sh share/id_ed25519.pub share/agent-desktop install.done; do
+ share/guest-setup.sh share/agent-desktop install.done agent.pub; do
: > "$dir/vm/$file"
done
- for file in id_ed25519 id_ed25519.pub known_hosts setup_done; do : > "$dir/$file"; done
- printf 'guest\n' > "$dir/guest_user"
+ : > "$dir/setup_done"
case $2 in
installing) rm "$dir/vm/install.done" "$dir/vm/Disk.img"; printf '1\n' > "$dir/vm/install.pid"; FAKE_JOB_ALIVE=1 ;;
failed) rm "$dir/vm/install.done" "$dir/vm/Disk.img"; printf '1\n' > "$dir/vm/install.pid" ;;
@@ -219,6 +185,14 @@ provider none FAKE_HV_SUPPORT=0 check
expect 'a Mac that cannot run VMs' 0 state unavailable
provider none check
expect 'a built and signed VM host' 0 state ready
+mv "$tmp/bin/agent-desktop-guest.app" "$tmp/agent-desktop-guest.away"
+fake xcrun <<'FAKE'
+#!/bin/sh
+exit 0
+FAKE
+provider none check
+expect 'a VM host without the guest agent' 0 state missing
+mv "$tmp/agent-desktop-guest.away" "$tmp/bin/agent-desktop-guest.app"
# Every verb in every phase. Columns: phase, then the expected "exit:field=value" for each verb.
while read -r phase status_want start_want stop_want rm_want exec_want; do
@@ -243,32 +217,32 @@ provider demo start demo
vm_pid=$(cat "$tmp/sandboxes/demo/vm/vmhost.pid")
expect 'start boots a stopped sandbox' 0 state running
grep -q "vmhost run $tmp/sandboxes/demo/vm\$" "$FAKE_LOG" || fail 'a set-up sandbox did not start headless'
-[ -s "$tmp/sandboxes/demo/vm/host_key.pub" ] || fail 'start did not give the sandbox its own SSH host key'
-grep -q '^192.0.2.2 ' "$tmp/sandboxes/demo/known_hosts" || fail 'start did not pin the sandbox host key'
-grep -q -- '-o StrictHostKeyChecking=yes' "$FAKE_LOG" || fail 'a pinned sandbox did not verify the host key it pinned'
-grep -q 'hdiutil detach /dev/disk99' "$FAKE_LOG" || fail 'the guest disk stayed mounted after the host key was written'
-grep -q '^private key' "$FAKE_VOLUME/private/etc/ssh/ssh_host_ed25519_key" && grep -q '^public key' "$FAKE_VOLUME/private/etc/ssh/ssh_host_ed25519_key.pub" || fail 'the new host key did not reach the guest disk'
-put demo stopped
-provider demo FAKE_HDIUTIL=broken start demo
-expect 'a guest disk that cannot be opened' 1 code ACTION_FAILED
-[ ! -f "$tmp/sandboxes/demo/vm/vmhost.pid" ] || fail 'a sandbox without its own host key was booted'
-for link in private private/etc private/etc/ssh private/etc/ssh/ssh_host_ed25519_key private/etc/ssh/ssh_host_ed25519_key.pub; do
- rm -rf "$FAKE_VOLUME" "$tmp/host"
- mkdir -p "$FAKE_VOLUME/private/etc/ssh" "$tmp/host"
- printf 'host file\n' > "$FAKE_VOLUME/private/etc/ssh/ssh_host_ed25519_key"
- printf 'host file\n' > "$FAKE_VOLUME/private/etc/ssh/ssh_host_ed25519_key.pub"
- mv "$FAKE_VOLUME/$link" "$tmp/host/target"
- ln -s "$tmp/host/target" "$FAKE_VOLUME/$link"
- put demo stopped
- : > "$FAKE_LOG"
- provider demo start demo
- expect "a guest disk whose $link is a link to the host" 1 code ACTION_FAILED
- [ -z "$(find "$tmp/host" -type f -exec grep -L '^host file$' {} +)" ] || fail "a host file behind the guest link $link was overwritten"
- [ ! -f "$tmp/sandboxes/demo/vm/vmhost.pid" ] || fail "a sandbox whose $link is a link to the host was booted"
- grep -q 'hdiutil detach /dev/disk99' "$FAKE_LOG" || fail "the guest disk stayed mounted after the link at $link was refused"
+put demo stopped
+: > "$tmp/sandboxes/demo/id_ed25519"
+: > "$tmp/sandboxes/demo/known_hosts"
+printf 'guest\n' > "$tmp/sandboxes/demo/guest_user"
+: > "$tmp/sandboxes/demo/vm/host_key.pub"
+provider demo start demo
+vm_pid=$(cat "$tmp/sandboxes/demo/vm/vmhost.pid")
+expect 'start of a sandbox that was set up over SSH' 0 state needs_setup
+grep -q "vmhost run $tmp/sandboxes/demo/vm --window" "$FAKE_LOG" || fail 'a sandbox that was set up over SSH did not reopen its setup window'
+[ ! -e "$tmp/sandboxes/demo/setup_done" ] || fail 'a sandbox that was set up over SSH kept its setup record'
+[ -f "$tmp/sandboxes/demo/vm/share/agent-desktop-guest.app/Contents/MacOS/agent-desktop-guest" ] || fail 'start did not put the guest agent in the shared folder'
+build_id=$(ls "$tmp/sandboxes/demo/vm/share/builds")
+[ "${#build_id}" -eq 40 ] || fail "the shared builds are [$build_id], expected one 40-character id"
+cmp -s "$AD_BINARY" "$tmp/sandboxes/demo/vm/share/builds/$build_id/agent-desktop" || fail 'start did not share the host build under its id'
+rm "$tmp/sandboxes/demo/vm/share/agent-desktop"
+provider demo stop demo
+provider demo start demo
+vm_pid=$(cat "$tmp/sandboxes/demo/vm/vmhost.pid")
+[ -f "$tmp/sandboxes/demo/vm/share/agent-desktop" ] && [ -f "$tmp/sandboxes/demo/vm/share/id_ed25519.pub" ] || fail 'start left out a file that agent-desktop 1.3.0 needs before it calls a sandbox complete'
+printf '%s' "$build_id" | grep -q '[^0-9a-f]' && fail "the build id [$build_id] is not lowercase hex"
+for leftover in id_ed25519 known_hosts guest_user; do
+ [ ! -e "$tmp/sandboxes/demo/$leftover" ] || fail "start kept the leftover $leftover"
done
-rm -rf "$FAKE_VOLUME" "$tmp/host"
+[ ! -e "$tmp/sandboxes/demo/vm/host_key.pub" ] || fail 'start kept the leftover host key file'
+
put demo stopped
provider demo AD_SET_WINDOW=on 'AD_SET_TITLE=Review build' start demo
vm_pid=$(cat "$tmp/sandboxes/demo/vm/vmhost.pid")
@@ -290,46 +264,55 @@ expect 'a sandbox that is not set up starts in a window' 0 state needs_setup
grep -q "vmhost run $tmp/sandboxes/demo/vm --window" "$FAKE_LOG" || fail 'setup did not open a window'
put demo running
-rm "$tmp/sandboxes/demo/setup_done"
+rm "$tmp/sandboxes/demo/setup_done" "$tmp/sandboxes/demo/vm/agent.pub"
provider demo status demo
expect 'status records a finished setup' 0 state running
-[ -f "$tmp/sandboxes/demo/setup_done" ] || fail 'status did not record the finished setup'
-provider demo FAKE_ACCESSIBILITY=denied status demo
+[ -f "$tmp/sandboxes/demo/setup_done" ] && [ "$(cat "$tmp/sandboxes/demo/vm/agent.pub")" = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ] || fail 'status did not record the finished setup and the guest agent key'
+provider demo FAKE_GUEST=impostor status demo
+expect 'a process that is not the recorded guest agent' 0 state needs_setup
+[ -f "$tmp/sandboxes/demo/setup_done" ] || fail 'an impostor in the guest cost the sandbox its setup record'
+provider demo FAKE_GUEST=denied status demo
expect 'accessibility not granted' 0 state needs_setup
[ "$(field next)" = 'agent-desktop sandbox stop demo' ] && [ ! -f "$tmp/sandboxes/demo/setup_done" ] || fail 'a headless sandbox that lost its setup was not sent back to a window'
-: > "$tmp/sandboxes/demo/setup_done"
-provider demo FAKE_SSH=unreachable status demo
+put demo running
+provider demo FAKE_GUEST=silent status demo
expect 'a guest that does not answer yet' 0 state working
-provider demo FAKE_SSH=no-binary status demo
-expect 'a guest without agent-desktop' 0 state needs_setup
-field message | grep -q 'agent-desktop is not installed in the guest' || fail 'the probe lost the exit status that reports a missing guest binary'
+put demo running
+touch -t 202001010000 "$tmp/sandboxes/demo/vm/vmhost.started"
+provider demo FAKE_GUEST=silent status demo
+expect 'a guest agent silent for two minutes' 0 state needs_setup
+[ -f "$tmp/sandboxes/demo/setup_done" ] || fail 'a guest that was only slow to answer lost its setup record'
+provider demo status demo
+expect 'a slow guest that answers after two minutes' 0 state running
+put demo running
: > "$FAKE_LOG"
provider demo exec demo -- type "two words" 'it'"'"'s $HOME `id`' '' --
[ "$status" = 0 ] || fail "exec exited $status"
printf '[type]\n[two words]\n[it'"'"'s $HOME `id`]\n[]\n[--]\n' > "$tmp/want"
cmp -s "$tmp/out" "$tmp/want" || fail 'exec changed the guest arguments'
[ "$(cat "$tmp/err")" = 'guest warning' ] || fail 'exec changed the guest stderr'
-grep -q '^scp ' "$FAKE_LOG" || fail 'exec did not copy a changed agent-desktop into the guest'
-grep '^ssh ' "$FAKE_LOG" | grep -v -e '-F /dev/null .*BatchMode=yes.*ConnectTimeout=5.*ServerAliveInterval=3' > "$tmp/unbounded" || true
-[ ! -s "$tmp/unbounded" ] || fail "an ssh call can hang or read the user's ssh config: $(cat "$tmp/unbounded")"
+build_id=$(ls "$tmp/sandboxes/demo/vm/share/builds")
+grep -q "^vmhost exec $tmp/sandboxes/demo/vm $build_id type " "$FAKE_LOG" || fail 'exec did not tell the guest which build to run'
+cp "$AD_BINARY" "$tmp/host-build"
+cp "$AD_BINARY" "$tmp/sandboxes/demo/vm/share/builds/$build_id/first-read"
+printf 'changed\n' >> "$AD_BINARY"
+: > "$FAKE_LOG"
+provider demo exec demo -- version
+[ "$status" = 0 ] || fail "exec after a host rebuild exited $status"
+new_build_id=$(sed -n "s|^vmhost exec $tmp/sandboxes/demo/vm \([0-9a-f]*\) version\$|\1|p" "$FAKE_LOG")
+[ "${#new_build_id}" -eq 40 ] && [ "$new_build_id" != "$build_id" ] || fail 'exec kept the old build id after the host build changed'
+cmp -s "$AD_BINARY" "$tmp/sandboxes/demo/vm/share/builds/$new_build_id/agent-desktop" || fail 'exec did not share the rebuilt agent-desktop under a new id'
+cmp -s "$tmp/host-build" "$tmp/sandboxes/demo/vm/share/builds/$build_id/agent-desktop" && [ -f "$tmp/sandboxes/demo/vm/share/builds/$build_id/first-read" ] || fail 'exec changed a build the running guest may already have read'
+cp "$tmp/host-build" "$AD_BINARY"
for guest_exit in 3 125 255; do
provider demo FAKE_GUEST_EXIT=$guest_exit exec demo -- version
[ "$status" = "$guest_exit" ] || fail "exec turned guest exit $guest_exit into $status"
done
provider demo FAKE_GUEST_NOISE=300000 FAKE_GUEST_EXIT=7 exec demo -- version
[ "$status" = 7 ] && [ "$(cat "$tmp/out")" = '[version]' ] || fail 'a noisy guest lost its output or exit status'
-[ "$(wc -c < "$tmp/err")" -le 65536 ] || fail 'guest stderr reached the host unbounded'
-provider demo FAKE_SSH=unreachable exec demo -- version
-expect 'exec with no Remote Login' 125 code ACTION_FAILED
-provider demo "FAKE_PROBE_FLOOD=$tmp/flooded" status demo
-expect 'status with a guest that floods its reply' 0 state needs_setup
-[ ! -e "$tmp/flooded" ] || fail 'a status probe accepted the whole guest reply'
-: > "$tmp/sandboxes/demo/setup_done"
-provider demo "FAKE_PROBE_FLOOD=$tmp/flooded" exec demo -- version
-[ "$status" = 0 ] || fail "exec with a guest that floods its reply exited $status"
-[ "$(cat "$tmp/out")" = '[version]' ] || fail 'a guest that floods its reply lost the exec output'
-[ ! -e "$tmp/flooded" ] || fail 'an exec probe accepted the whole guest reply'
+provider demo FAKE_GUEST=silent exec demo -- version
+expect 'exec with a guest agent that does not answer' 125 code ACTION_FAILED
# create: every bad combination of settings is refused before anything is touched.
refuse() {
@@ -352,7 +335,7 @@ refuse 'from and user' AD_SET_FROM=base AD_SET_USER=alice
refuse 'an unknown key' AD_SET_ISPW=latest
refuse 'an empty value' AD_SET_IPSW=
refuse 'a missing image' AD_SET_IPSW=/nowhere/image.ipsw
-refuse 'a bad guest user' AD_SET_IPSW=latest 'AD_SET_USER=not a user!'
+refuse 'the retired user setting' AD_SET_IPSW=latest AD_SET_USER=alice
wait_for_install() {
tries=0
@@ -365,11 +348,10 @@ wait_for_install() {
printf 'image\n' > "$tmp/my image.ipsw"
rm -rf "$tmp/sandboxes/new"
-provider new AD_SET_IPSW='my image.ipsw' AD_SET_USER=alice create new
+provider new AD_SET_IPSW='my image.ipsw' create new
expect 'create from a supplied image' 0 state working
wait_for_install new
grep -q "vmhost install $tmp/sandboxes/new/vm $tmp/my image.ipsw" "$FAKE_LOG" || fail 'a relative image path was not resolved against the caller directory'
-[ "$(cat "$tmp/sandboxes/new/guest_user")" = alice ] || fail 'the guest user was not recorded'
[ -f "$tmp/sandboxes/new/vm/install.done" ] || fail "the install job did not finish: $(cat "$tmp/sandboxes/new/vm/install.log")"
FAKE_IMAGE='newest image this Mac can run'
@@ -420,6 +402,15 @@ field message | grep -q 'clonefile is not supported here' || fail 'the clone fai
rm -rf "$tmp/sandboxes/new"
provider new AD_SET_FROM=base create new
expect 'cloning a stopped, set-up sandbox' 0 state stopped
-[ -f "$tmp/sandboxes/new/setup_done" ] && [ "$(cat "$tmp/sandboxes/new/guest_user")" = guest ] || fail 'the clone did not keep the setup record and guest user'
+[ -f "$tmp/sandboxes/new/setup_done" ] || fail 'the clone has no setup record'
+[ -f "$tmp/sandboxes/new/vm/agent.pub" ] || fail 'the clone has no recorded guest agent key'
+rm -rf "$tmp/sandboxes/old"
+rm "$tmp/sandboxes/base/vm/agent.pub"
+provider old AD_SET_FROM=base create old
+[ "$status" = 0 ] && [ ! -e "$tmp/sandboxes/old/setup_done" ] || fail 'a clone of a sandbox with no recorded guest agent key was recorded as set up'
+[ -n "$(ls "$tmp/sandboxes/new/vm/share/builds" 2>/dev/null)" ] && [ -f "$tmp/sandboxes/new/vm/share/agent-desktop-guest.app/Contents/MacOS/agent-desktop-guest" ] || fail 'the clone has no guest agent or host build in its shared folder'
+for leftover in id_ed25519 known_hosts guest_user; do
+ [ ! -e "$tmp/sandboxes/new/$leftover" ] || fail "the clone holds the leftover $leftover"
+done
printf 'provider tests passed\n'
diff --git a/providers/macos/vmhost.swift b/providers/macos/vmhost.swift
index 45dfef53a..296be55cf 100644
--- a/providers/macos/vmhost.swift
+++ b/providers/macos/vmhost.swift
@@ -1,4 +1,5 @@
import AppKit
+import CryptoKit
import Darwin
import Foundation
@preconcurrency import Virtualization
@@ -26,6 +27,8 @@ struct Bundle {
var startedFile: URL { root.appendingPathComponent("vmhost.started") }
var lockFile: URL { root.appendingPathComponent("vmhost.lock") }
var installLog: URL { root.appendingPathComponent("install.log") }
+ var controlSocket: String { "vmhost.sock" }
+ var agentKey: URL { root.appendingPathComponent("agent.pub") }
}
struct VMConfig: Codable {
@@ -36,7 +39,7 @@ struct VMConfig: Codable {
enum Usage {
static var noCommand: VMError {
- VMError(message: "vmhost needs one of the commands install, run, clone or ip.",
+ VMError(message: "vmhost needs one of the commands install, run, clone, status or exec.",
suggestion: "Run `agent-desktop sandbox create <name>` so the provider calls vmhost itself.")
}
@@ -60,11 +63,16 @@ enum Usage {
suggestion: "Run `agent-desktop sandbox create <name> --set from=<source>` so the provider calls it correctly.")
}
- static var ipArguments: VMError {
- VMError(message: "vmhost ip takes one bundle path.",
+ static var statusArguments: VMError {
+ VMError(message: "vmhost status takes one bundle path.",
suggestion: "Run `agent-desktop sandbox status <name>` so the provider calls it correctly.")
}
+ static var execArguments: VMError {
+ VMError(message: "vmhost exec needs a bundle path and a build id before the guest arguments.",
+ suggestion: "Run `agent-desktop sandbox exec <name> -- <args>` so the provider calls it correctly.")
+ }
+
static var unwritableReply: VMError {
VMError(message: "vmhost cannot write its JSON reply.",
suggestion: "Run the command again, and report the failure if it repeats.")
@@ -77,11 +85,13 @@ enum Output {
FileHandle.standardOutput.write(Data((line + "\n").utf8))
}
- static func fail(_ error: VMError) -> Never {
- if let line = encode(["ok": false, "message": error.message, "suggestion": error.suggestion]) {
+ static func fail(_ error: VMError, status: Int32 = 1, code: String? = nil) -> Never {
+ var fields: [String: Any] = ["ok": false, "message": error.message, "suggestion": error.suggestion]
+ if let code { fields["code"] = code }
+ if let line = encode(fields) {
FileHandle.standardOutput.write(Data((line + "\n").utf8))
}
- exit(1)
+ exit(status)
}
static func encode(_ fields: [String: Any]) -> String? {
@@ -275,6 +285,7 @@ enum VMBuilder {
configuration.storageDevices = [VZVirtioBlockDeviceConfiguration(attachment: disk)]
configuration.networkDevices = [network]
configuration.directorySharingDevices = [share]
+ configuration.socketDevices = [VZVirtioSocketDeviceConfiguration()]
configuration.graphicsDevices = [graphics]
configuration.keyboards = [VZUSBKeyboardConfiguration()]
configuration.pointingDevices = [VZUSBScreenCoordinatePointingDeviceConfiguration()]
@@ -604,13 +615,16 @@ struct RunCommand {
defer {
PidFile.clear(at: bundle.pidFile)
PidFile.clear(at: bundle.startedFile)
+ ControlSocket.remove(from: bundle)
}
- try boot(bundle: bundle, configuration: configuration, showWindow: showWindow)
+ let listener = try ControlSocket.listen(in: bundle)
+ try boot(bundle: bundle, configuration: configuration, showWindow: showWindow, listener: listener)
}
- static func boot(bundle: Bundle, configuration: VZVirtualMachineConfiguration, showWindow: Bool) throws {
+ static func boot(bundle: Bundle, configuration: VZVirtualMachineConfiguration, showWindow: Bool, listener: Int32) throws {
let queue = showWindow ? DispatchQueue.main : DispatchQueue(label: "com.agent-desktop.vmhost")
let machine = VZVirtualMachine(configuration: configuration, queue: queue)
+ GuestRelay(listener: listener, machine: machine, queue: queue).start()
let outcome = ResultBox()
let window = showWindow ? SandboxWindow.make(bundle: bundle, machine: machine) : nil
let finish: (Result<Void, Error>) -> Void = { result in
@@ -732,47 +746,308 @@ struct CloneCommand {
}
}
-enum LeaseTable {
- static func newestAddress(for octets: [Int], in contents: String) -> String? {
- var leases: [(mine: Bool, address: String, expiry: UInt64)] = []
- var record: [String: String] = [:]
- for line in contents.split(whereSeparator: \.isNewline) {
- let trimmed = line.trimmingCharacters(in: .whitespaces)
- if trimmed == "{" {
- record = [:]
- } else if trimmed == "}" {
- if let hardware = record["hw_address"], let address = record["ip_address"] {
- let digits = record["lease"]?.dropFirst(2) ?? ""
- leases.append((MACAddress.octets(hardware) == octets, address, UInt64(digits, radix: 16) ?? 0))
+/// The byte protocol spoken to the agent inside the guest, over the virtual machine's socket device.
+enum GuestWire {
+ static let port: UInt32 = 7273
+ static let agentVersion = 1
+ static let frameLimit = 65536
+ static let statusLimit = 4096
+ static let messageLimit = 512
+ static let stdout: UInt8 = 1
+ static let stderr: UInt8 = 2
+ static let exit: UInt8 = 3
+ static let failure: UInt8 = 4
+ static let nonceSize = 32
+ static let keySize = 32
+ static let signatureSize = 64
+ static let proofContext = Data("agent-desktop-guest-v1".utf8)
+}
+
+/// The socket file in the bundle through which one sandbox command reaches the process that owns the machine.
+enum ControlSocket {
+ static func listen(in bundle: Bundle) throws -> Int32 {
+ let descriptor = try inside(bundle) { address, size -> Int32? in
+ unlink(bundle.controlSocket)
+ let descriptor = socket(AF_UNIX, SOCK_STREAM, 0)
+ guard descriptor >= 0 else { return nil }
+ guard bind(descriptor, address, size) == 0, chmod(bundle.controlSocket, S_IRUSR | S_IWUSR) == 0,
+ Darwin.listen(descriptor, 16) == 0 else {
+ close(descriptor)
+ return nil
+ }
+ return descriptor
+ }
+ guard let descriptor else { throw VMErrors.posix("The sandbox control socket cannot be created") }
+ return descriptor
+ }
+
+ static func connect(in bundle: Bundle) -> Int32? {
+ let descriptor = try? inside(bundle) { address, size -> Int32? in
+ let descriptor = socket(AF_UNIX, SOCK_STREAM, 0)
+ guard descriptor >= 0 else { return nil }
+ guard Darwin.connect(descriptor, address, size) == 0 else {
+ close(descriptor)
+ return nil
+ }
+ return descriptor
+ }
+ return descriptor ?? nil
+ }
+
+ static func remove(from bundle: Bundle) {
+ unlink(bundle.root.appendingPathComponent(bundle.controlSocket).path)
+ }
+
+ /// Only the account that runs the virtual machine may send it guest commands.
+ static func peerIsOwner(_ descriptor: Int32) -> Bool {
+ var user: uid_t = 0
+ var group: gid_t = 0
+ return getpeereid(descriptor, &user, &group) == 0 && user == geteuid()
+ }
+
+ /// A socket path holds 104 bytes, so the socket is named relative to the bundle directory.
+ private static func inside<T>(_ bundle: Bundle, _ body: (UnsafePointer<sockaddr>, socklen_t) -> T) throws -> T {
+ let previous = open(".", O_RDONLY)
+ guard previous >= 0, chdir(bundle.root.path) == 0 else {
+ if previous >= 0 { close(previous) }
+ throw VMErrors.posix("The sandbox directory cannot be opened")
+ }
+ defer {
+ fchdir(previous)
+ close(previous)
+ }
+ var address = sockaddr_un()
+ address.sun_family = sa_family_t(AF_UNIX)
+ withUnsafeMutableBytes(of: &address.sun_path) { path in
+ path.copyBytes(from: bundle.controlSocket.utf8)
+ }
+ return withUnsafePointer(to: &address) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { body($0, socklen_t(MemoryLayout<sockaddr_un>.size)) }
+ }
+ }
+}
+
+/// Joins each control socket client to a new connection to the guest agent and copies bytes both ways.
+final class GuestRelay: @unchecked Sendable {
+ private let listener: Int32
+ private let machine: VZVirtualMachine
+ private let queue: DispatchQueue
+
+ init(listener: Int32, machine: VZVirtualMachine, queue: DispatchQueue) {
+ self.listener = listener
+ self.machine = machine
+ self.queue = queue
+ }
+
+ func start() {
+ Thread.detachNewThread { [self] in
+ while true {
+ let client = accept(listener, nil, nil)
+ if client < 0 {
+ if errno == EINTR { continue }
+ return
}
- } else if let separator = trimmed.firstIndex(of: "=") {
- record[String(trimmed[..<separator])] = String(trimmed[trimmed.index(after: separator)...])
+ guard ControlSocket.peerIsOwner(client) else {
+ close(client)
+ continue
+ }
+ queue.async { self.attach(client) }
}
}
- guard let newest = leases.filter(\.mine).max(by: { $0.expiry < $1.expiry }) else { return nil }
- let reassigned = leases.contains { !$0.mine && $0.address == newest.address && $0.expiry > newest.expiry }
- return reassigned ? nil : newest.address
+ }
+
+ private func attach(_ client: Int32) {
+ guard let device = machine.socketDevices.first as? VZVirtioSocketDevice else {
+ close(client)
+ return
+ }
+ device.connect(toPort: GuestWire.port) { result in
+ guard case let .success(connection) = result else {
+ close(client)
+ return
+ }
+ GuestRelay.splice(client, connection)
+ }
+ }
+
+ private static func splice(_ client: Int32, _ connection: VZVirtioSocketConnection) {
+ let guest = connection.fileDescriptor
+ let finished = DispatchGroup()
+ for (source, sink) in [(client, guest), (guest, client)] {
+ finished.enter()
+ Thread.detachNewThread {
+ Bytes.copy(from: source, to: sink)
+ shutdown(client, SHUT_RDWR)
+ shutdown(guest, SHUT_RDWR)
+ finished.leave()
+ }
+ }
+ finished.notify(queue: .global()) {
+ close(client)
+ connection.close()
+ }
}
}
-struct IpCommand {
- static func execute(_ arguments: [String]) throws {
- guard arguments.count == 1 else { throw Usage.ipArguments }
+enum Bytes {
+ static func copy(from source: Int32, to sink: Int32) {
+ var buffer = [UInt8](repeating: 0, count: GuestWire.frameLimit)
+ while true {
+ let got = Darwin.read(source, &buffer, buffer.count)
+ if got < 0 && errno == EINTR { continue }
+ guard got > 0, write(Data(buffer[0..<got]), to: sink) else { return }
+ }
+ }
+
+ static func write(_ data: Data, to descriptor: Int32) -> Bool {
+ var sent = 0
+ while sent < data.count {
+ let wrote = data.withUnsafeBytes { Darwin.write(descriptor, $0.baseAddress! + sent, data.count - sent) }
+ if wrote < 0 && errno == EINTR { continue }
+ guard wrote > 0 else { return false }
+ sent += wrote
+ }
+ return true
+ }
+
+ static func read(_ count: Int, from descriptor: Int32) -> Data? {
+ var bytes = [UInt8](repeating: 0, count: count)
+ var filled = 0
+ while filled < count {
+ let got = bytes.withUnsafeMutableBytes { Darwin.read(descriptor, $0.baseAddress! + filled, count - filled) }
+ if got < 0 && errno == EINTR { continue }
+ guard got > 0 else { return nil }
+ filled += got
+ }
+ return Data(bytes)
+ }
+}
+
+enum GuestCallFailure: Error {
+ case silent
+ case impostor
+ case unrecorded
+}
+
+/// One request to the guest agent and the frames it answers with. Any guest account can listen on the agent's
+/// port, so the agent first signs a fresh nonce with the key recorded for this sandbox at setup, and the request
+/// is sent only to a process that proves it. The guest decides what it sends back, so every frame is at most
+/// `GuestWire.frameLimit` bytes and nothing is held beyond the frame being copied.
+struct GuestCall {
+ let descriptor: Int32
+ let key: String
+
+ static func open(_ bundle: Bundle, request: [String: Any], timeout: Int = 0, needsRecordedKey: Bool) -> Result<GuestCall, GuestCallFailure> {
+ guard let descriptor = ControlSocket.connect(in: bundle) else { return .failure(.silent) }
+ func refuse(_ failure: GuestCallFailure) -> Result<GuestCall, GuestCallFailure> {
+ close(descriptor)
+ return .failure(failure)
+ }
+ if timeout > 0 {
+ var limit = timeval(tv_sec: timeout, tv_usec: 0)
+ setsockopt(descriptor, SOL_SOCKET, SO_RCVTIMEO, &limit, socklen_t(MemoryLayout<timeval>.size))
+ }
+ var generator = SystemRandomNumberGenerator()
+ let nonce = Data((0..<GuestWire.nonceSize).map { _ in UInt8.random(in: .min ... .max, using: &generator) })
+ guard Bytes.write(nonce, to: descriptor),
+ let proof = Bytes.read(GuestWire.keySize + GuestWire.signatureSize, from: descriptor),
+ let agent = try? Curve25519.Signing.PublicKey(rawRepresentation: proof.prefix(GuestWire.keySize)),
+ agent.isValidSignature(proof.suffix(GuestWire.signatureSize), for: GuestWire.proofContext + nonce) else {
+ return refuse(.silent)
+ }
+ let key = proof.prefix(GuestWire.keySize).map { String(format: "%02x", $0) }.joined()
+ let recorded = (try? String(contentsOf: bundle.agentKey, encoding: .utf8))?.trimmingCharacters(in: .whitespacesAndNewlines)
+ if let recorded, recorded != key { return refuse(.impostor) }
+ if recorded == nil && needsRecordedKey { return refuse(.unrecorded) }
+ guard let body = try? JSONSerialization.data(withJSONObject: request) else { return refuse(.silent) }
+ var message = Data()
+ withUnsafeBytes(of: UInt32(body.count).bigEndian) { message.append(contentsOf: $0) }
+ message.append(body)
+ guard Bytes.write(message, to: descriptor) else { return refuse(.silent) }
+ return .success(GuestCall(descriptor: descriptor, key: key))
+ }
+
+ func frame() -> (kind: UInt8, payload: Data)? {
+ guard let header = Bytes.read(5, from: descriptor) else { return nil }
+ let length = header.dropFirst().reduce(0) { ($0 << 8) | Int($1) }
+ guard length <= GuestWire.frameLimit else { return nil }
+ if length == 0 { return (header[header.startIndex], Data()) }
+ guard let payload = Bytes.read(length, from: descriptor) else { return nil }
+ return (header[header.startIndex], payload)
+ }
+}
+
+struct GuestCommand {
+ static let silentStatus: Int32 = 3
+ static let impostorStatus: Int32 = 4
+ static let providerFailureStatus: Int32 = 125
+
+ static func impostor(_ bundle: Bundle) -> String {
+ "The process answering in sandbox \(bundle.sandboxName) is not the guest agent that was set up, so nothing was sent to it."
+ }
+
+ static func status(_ arguments: [String]) throws {
+ guard arguments.count == 1 else { throw Usage.statusArguments }
let bundle = Bundle(arguments[0])
- let config = try BundleData.config(bundle)
- let octets = MACAddress.octets(config.macAddress)!
- let contents: String
- do {
- contents = try String(contentsOfFile: "/var/db/dhcpd_leases", encoding: .utf8)
- } catch {
- throw VMError(message: "The DHCP lease file /var/db/dhcpd_leases cannot be read.",
- suggestion: "Run `agent-desktop sandbox status \(bundle.sandboxName)` to see whether the sandbox is running.")
+ let again = "Run `agent-desktop sandbox status \(bundle.sandboxName)` again in a few seconds."
+ let silent = VMError(message: "The guest agent in sandbox \(bundle.sandboxName) is not answering.", suggestion: again)
+ let call: GuestCall
+ switch GuestCall.open(bundle, request: ["op": "status"], timeout: 5, needsRecordedKey: false) {
+ case let .success(opened): call = opened
+ case .failure(.impostor): Output.fail(VMError(message: impostor(bundle), suggestion: again), status: impostorStatus)
+ case .failure: Output.fail(silent, status: silentStatus)
}
- guard let address = LeaseTable.newestAddress(for: octets, in: contents) else {
- throw VMError(message: "The VM has no network address yet.",
- suggestion: "Wait a few seconds, then run `agent-desktop sandbox status \(bundle.sandboxName)`.")
+ var reply = Data()
+ while let frame = call.frame() {
+ if frame.kind == GuestWire.stdout {
+ reply.append(frame.payload)
+ guard reply.count <= GuestWire.statusLimit else { break }
+ } else if frame.kind == GuestWire.exit {
+ guard let state = try? JSONSerialization.jsonObject(with: reply) as? [String: Any],
+ let accessibility = state["accessibility"] as? Bool,
+ let agent = state["agent"] as? Int else { break }
+ Output.succeed(["ok": true, "accessibility": accessibility, "agent": agent, "key": call.key])
+ return
+ } else {
+ break
+ }
}
- Output.succeed(["ok": true, "ip": address])
+ Output.fail(silent, status: silentStatus)
+ }
+
+ static func exec(_ arguments: [String]) throws {
+ guard arguments.count >= 2 else { throw Usage.execArguments }
+ let bundle = Bundle(arguments[0])
+ let request: [String: Any] = ["op": "exec", "build": arguments[1], "args": Array(arguments.dropFirst(2))]
+ let call: GuestCall
+ switch GuestCall.open(bundle, request: request, needsRecordedKey: true) {
+ case let .success(opened): call = opened
+ case .failure(.impostor): fail(impostor(bundle), bundle)
+ case .failure(.unrecorded): fail("Sandbox \(bundle.sandboxName) has no recorded guest agent key.", bundle)
+ case .failure(.silent): fail("The guest agent in sandbox \(bundle.sandboxName) is not answering.", bundle)
+ }
+ while let frame = call.frame() {
+ switch frame.kind {
+ case GuestWire.stdout:
+ guard Bytes.write(frame.payload, to: STDOUT_FILENO) else { exit(providerFailureStatus) }
+ case GuestWire.stderr:
+ _ = Bytes.write(frame.payload, to: STDERR_FILENO)
+ case GuestWire.exit:
+ guard frame.payload.count == 4 else { fail("The guest agent sent an unreadable exit status.", bundle) }
+ exit(Int32(truncatingIfNeeded: frame.payload.reduce(0) { ($0 << 8) | Int($1) }))
+ case GuestWire.failure:
+ let reason = String(decoding: frame.payload.prefix(GuestWire.messageLimit), as: UTF8.self)
+ fail(reason.isEmpty ? "The guest agent refused the command." : reason, bundle)
+ default:
+ fail("The guest agent sent a reply this build does not understand.", bundle)
+ }
+ }
+ fail("The guest agent in sandbox \(bundle.sandboxName) stopped answering before the command finished.", bundle)
+ }
+
+ private static func fail(_ message: String, _ bundle: Bundle) -> Never {
+ Output.fail(VMError(message: message, suggestion: "Run agent-desktop sandbox status \(bundle.sandboxName)."),
+ status: providerFailureStatus, code: "ACTION_FAILED")
}
}
@@ -791,6 +1066,7 @@ enum CallerSession {
enum VMHost {
static func run(_ arguments: [String]) -> Int32 {
+ signal(SIGPIPE, SIG_IGN)
do {
guard let command = arguments.first else { throw Usage.noCommand }
let rest = Array(arguments.dropFirst())
@@ -802,8 +1078,10 @@ enum VMHost {
try RunCommand.execute(rest)
case "clone":
try CloneCommand.execute(rest)
- case "ip":
- try IpCommand.execute(rest)
+ case "status":
+ try GuestCommand.status(rest)
+ case "exec":
+ try GuestCommand.exec(rest)
default:
throw Usage.unknown(command)
}
diff --git a/scripts/check_architecture.py b/scripts/check_architecture.py
index 3b08676b5..6b3ff77ec 100644
--- a/scripts/check_architecture.py
+++ b/scripts/check_architecture.py
@@ -103,8 +103,16 @@ STR = re.compile(r"__S(\d+)__")
PROVIDERS_DIR = "providers"
PROVIDERS_SUFFIXES = {".sh", ".swift"}
-PROVIDERS_LISTENER = re.compile(
- r"(?<![A-Za-z0-9_])(?:socket\s*\(|listen\s*\(|bind\s*\(|nc\s|socat|NWListener|VZVirtioSocket)")
+PROVIDERS_NETWORK = re.compile(
+ r"(?<![A-Za-z0-9_])(?:nc\s|socat|NWListener|NWConnection|AF_INET6?|PF_INET6?|sockaddr_in6?)(?![A-Za-z0-9_])")
+PROVIDERS_SOCKET = re.compile(r"(?<![A-Za-z0-9_])(?:socket\s*\(|listen\s*\(|bind\s*\(|VZVirtioSocket)")
+# A provider drives a desktop and serves nothing on a network. Only these files may hold a socket, and only the
+# local kind named beside them; a new entry is a review decision.
+PROVIDERS_SOCKET_ALLOWLIST = {
+ "providers/macos/vmhost.swift": "the machine's socket device, and a socket file in the sandbox for its owner",
+ "providers/macos/guestagent.swift": "the machine's socket device inside the guest, for the host alone",
+ "providers/macos/test-guest-channel.sh": "a socket file standing in for the machine's socket device in tests",
+}
class Source:
@@ -411,13 +419,23 @@ def check(repo):
for stale in sorted(LISTENER_ALLOWLIST - serving):
err("G12", f"LISTENER_ALLOWLIST lists {stale}, which no longer opens a listener")
+ provider_sockets = set()
for path in provider_files(repo):
rel = os.path.relpath(path, repo).replace(os.sep, "/")
with open(path, encoding="utf-8", errors="replace") as fh:
- hit = PROVIDERS_LISTENER.search(fh.read())
- if hit:
- err("G12", f"{rel} opens a listener ({hit.group(0).strip()}); a provider drives a desktop and "
- "serves nothing, so a socket or listener here needs a review decision")
+ text = fh.read()
+ network = PROVIDERS_NETWORK.search(text)
+ local = PROVIDERS_SOCKET.search(text)
+ if network:
+ err("G12", f"{rel} reaches the network ({network.group(0).strip()}); a provider drives a desktop and "
+ "serves nothing on a network")
+ if local and rel not in PROVIDERS_SOCKET_ALLOWLIST:
+ err("G12", f"{rel} opens a socket ({local.group(0).strip()}); a provider drives a desktop and "
+ "serves nothing, so a socket here needs a PROVIDERS_SOCKET_ALLOWLIST entry in review")
+ if local:
+ provider_sockets.add(rel)
+ for stale in sorted(set(PROVIDERS_SOCKET_ALLOWLIST) - provider_sockets):
+ err("G12", f"PROVIDERS_SOCKET_ALLOWLIST lists {stale}, which no longer opens a socket")
for p in PLATFORMS:
if not os.path.exists(os.path.join(repo, "crates", p, "Cargo.toml")):
@@ -614,6 +632,8 @@ PLANTS = {
PLANTS["G12"] = [
("providers/macos/provider.sh", "#!/bin/sh\nsocat TCP-LISTEN:9000,fork EXEC:sh\n"),
("providers/macos/vmhost.swift", "import Network\nlet l = try NWListener(using: .tcp)\n"),
+ ("providers/macos/vmhost.swift", "let d = VZVirtioSocketDeviceConfiguration()\n"),
+ ("providers/macos/guestagent.swift", "let fd = socket(AF_INET, SOCK_STREAM, 0)\n"),
("crates/macos/src/system/host.rs", "fn f() { let _ = std::os::unix::net::UnixListener::bind(\"/tmp/h.sock\"); }\n"),
("crates/core/src/system/host.rs", "fn f() { let _ = std::net::TcpListener::bind((\"127.0.0.1\", 0)); }\n"),
("crates/windows/src/system/host.rs", "fn f() { let _ = CreateNamedPipeW; }\n"),
@@ -625,9 +645,10 @@ SUPPORT = {"G2": {"crates/core/custom.rs": "fn main() {}\n"},
def self_test():
"""Plant one violation per case in a minimal clean workspace; every case must fire, the clean tree must pass."""
- global CORE_OS_ALLOWLIST, LISTENER_ALLOWLIST
+ global CORE_OS_ALLOWLIST, LISTENER_ALLOWLIST, PROVIDERS_SOCKET_ALLOWLIST
saved = CORE_OS_ALLOWLIST
saved_listeners = LISTENER_ALLOWLIST
+ saved_provider_sockets = PROVIDERS_SOCKET_ALLOWLIST
tmp = tempfile.mkdtemp(prefix="arch-selftest-")
try:
def build(overrides):
@@ -649,6 +670,7 @@ def self_test():
CORE_OS_ALLOWLIST = set()
LISTENER_ALLOWLIST = set()
+ PROVIDERS_SOCKET_ALLOWLIST = {}
build({})
clean = check(tmp)
if clean:
@@ -669,9 +691,15 @@ def self_test():
build({})
if not [e for e in check(tmp) if e.startswith("G12:") and "no longer" in e]:
raise SystemExit("self-test: a stale LISTENER_ALLOWLIST entry was not reported")
+ LISTENER_ALLOWLIST = set()
+ PROVIDERS_SOCKET_ALLOWLIST = {"providers/macos/vmhost.swift": "self-test"}
+ build({})
+ if not [e for e in check(tmp) if e.startswith("G12:") and "no longer opens a socket" in e]:
+ raise SystemExit("self-test: a stale PROVIDERS_SOCKET_ALLOWLIST entry was not reported")
finally:
CORE_OS_ALLOWLIST = saved
LISTENER_ALLOWLIST = saved_listeners
+ PROVIDERS_SOCKET_ALLOWLIST = saved_provider_sockets
shutil.rmtree(tmp, ignore_errors=True)
diff --git a/skills/agent-desktop-macos/SKILL.md b/skills/agent-desktop-macos/SKILL.md
index 4d1a6d8d1..3112aa1b3 100644
--- a/skills/agent-desktop-macos/SKILL.md
+++ b/skills/agent-desktop-macos/SKILL.md
@@ -19,7 +19,7 @@ Read the core skill first (`agent-desktop skills get desktop`) for the observe,
## Requirements
-The sandbox provider on macOS is `macos`: a macOS VM that needs an Apple Silicon Mac, macOS 13 or later, and Xcode Command Line Tools. See `agent-browser.dev/desktop/sandboxes/macos`.
+The sandbox provider on macOS is `macos`: a macOS VM that needs an Apple Silicon Mac, macOS 13 or later on the host and in the guest, and Xcode Command Line Tools. The first setup needs a person in the guest window; clones need none. See `agent-browser.dev/desktop/sandboxes/macos`.
- macOS 13 or later, Intel or Apple Silicon.
- Accessibility permission for the app that launches agent-desktop (Terminal, iTerm2, Warp, VS Code, Codex). macOS 27 and later name this list Device Control and Data Access. If System Settings lists the `agent-desktop` binary separately, grant it too.
diff --git a/skills/agent-desktop-macos/references/troubleshooting.md b/skills/agent-desktop-macos/references/troubleshooting.md
index ee56496d6..b847950ed 100644
--- a/skills/agent-desktop-macos/references/troubleshooting.md
+++ b/skills/agent-desktop-macos/references/troubleshooting.md
@@ -94,3 +94,11 @@ The dismiss chain runs in order: the `AXDismiss` and `AXRemoveFromParent` action
**Cause.** The shortcut used `ctrl` where macOS uses `cmd`, or the keys went to the wrong app.
**Fix.** Use `cmd+...`. To send keys to one app without focusing it, use `press cmd+s --app "App"`.
+
+## Sandbox answers needs_setup
+
+**Symptom.** `agent-desktop sandbox status <name>` answers `needs_setup` for a sandbox that worked before.
+
+**Cause.** The guest agent, `agent-desktop-guest`, is not running in the guest, or Accessibility is off for it. The agent starts with each login to the guest account, so the guest needs automatic login.
+
+**Fix.** Run `agent-desktop sandbox stop <name>`, then `agent-desktop sandbox start <name> --window`, and in the guest turn on automatic login, run `sh "/Volumes/My Shared Files/guest-setup.sh"` in Terminal, and switch on **agent-desktop-guest** in System Settings > Privacy & Security > Accessibility. Then check `status` on the host. A sandbox set up by agent-desktop 1.3.0 needs this once.
diff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.md
index 379042bae..54019181f 100644
--- a/skills/agent-desktop/SKILL.md
+++ b/skills/agent-desktop/SKILL.md
@@ -78,7 +78,7 @@ A sandbox is a desktop a provider manages on your machine. The provider is `maco
```sh
agent-desktop sandbox install # report the provider's state
-agent-desktop sandbox install macos # compile and sign the VM host, then report ready
+agent-desktop sandbox install macos # compile and sign the VM host and guest agent, then report ready
```
```sh
@@ -91,7 +91,7 @@ agent-desktop sandbox stop demo # stop the sandbox
agent-desktop sandbox rm demo # remove it
```
-Names are 1–32 lowercase letters, digits or hyphens, starting with a letter or digit. `exec` returns the guest's envelope and exit status; a provider failure returns a host error. `rm` refuses a sandbox reported as `running`; stop it first. `create` needs exactly one source: `--set from=<sandbox>`, `--set ipsw=latest` or `--set ipsw=<path>`. `start` answers `working` until the guest answers; wait for `status` to report `running` before `exec`.
+Names are 1–32 lowercase letters, digits or hyphens, starting with a letter or digit. `exec` returns the guest's envelope and exit status; a provider failure returns a host error. `rm` refuses a sandbox reported as `running`; stop it first. `create` needs exactly one source: `--set from=<sandbox>`, `--set ipsw=latest` or `--set ipsw=<path>`. `start` answers `working`, or `needs_setup` when the guest agent is not answering; wait for `status` to report `running` before `exec`.
Read `state`, `message` and optional `next`; `ok: true` alone does not mean the sandbox is ready.
@@ -104,7 +104,7 @@ Read `state`, `message` and optional `next`; `ok: true` alone does not mean the
- `stopped`: start the sandbox to use it, or remove it.
- `broken`: follow `next`; a broken sandbox may need removal.
-A sandbox separates the desktop, not the network or the host. Sandboxes on one host share a virtual network, and a guest can reach the host's network services; keep one trust level per host. Each sandbox has its own pinned SSH host key, so a guest cannot answer for another sandbox. The SSH key under `<state root>/sandboxes/<name>/` is the guest credential, and in the guest Accessibility belongs to `sshd-keygen-wrapper` for the whole user session.
+A sandbox separates the desktop, not the network or the host. Sandboxes on one host share a virtual network, and a guest can reach the host's network services; keep one trust level per host. The host reaches the guest over the virtual machine's own socket device: only the process that runs the VM can open that connection, and `agent-desktop-guest` refuses any caller that is not the host. The host sends commands only to the agent whose key it recorded at setup, so another guest account cannot answer in its place. The agent runs the guest's `agent-desktop` with the arguments after `--` and never a shell. In the guest, Accessibility belongs to `agent-desktop-guest`.
Cloning a configured macOS VM has been tested end to end. Installing the first VM from a macOS image is experimental and has not been verified end to end. Provider setup steps and limits are in the docs: `agent-browser.dev/desktop/sandboxes/macos`.
diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.md
index 99c0b7919..4f5901577 100644
--- a/skills/agent-desktop/references/commands-system.md
+++ b/skills/agent-desktop/references/commands-system.md
@@ -222,7 +222,7 @@ Multi-agent cursors (macOS and Windows): start with `session start --cursor --mu
A sandbox whose record is missing or malformed, or names a provider this build does not include, appears in `sandbox list` with `state: "broken"`, and every command on it returns `INVALID_ARGS`. `next` and `suggestion` name the directory to delete once nothing in it is still running. A sandbox whose status check failed is also `broken`; follow its `next`, which is not always a removal.
-`sandbox start <name> --window` shows the sandbox's desktop in a window on the host instead of running it headless, and `--set key=value` passes the provider an option for that start. `create`, `start`, `stop` and `rm` on one sandbox run one at a time; a second one fails with `ACTION_FAILED`. `sandbox exec` ends a guest command after 300 seconds with `TIMEOUT`. The host's session and agent id, from flags or from `AGENT_DESKTOP_SESSION` and `AGENT_DESKTOP_AGENT_ID`, do not apply in the guest; pass `--session` after `--`.
+`sandbox start <name> --window` shows the sandbox's desktop in a window on the host instead of running it headless, and `--set key=value` passes the provider an option for that start. `create`, `start`, `stop` and `rm` on one sandbox run one at a time; a second one fails with `ACTION_FAILED`. `sandbox exec` ends a guest command after 300 seconds with `TIMEOUT`. It runs the guest's `~/.local/bin/agent-desktop` through `agent-desktop-guest` with the arguments after `--`; the agent does not run a shell. The host's session and agent id, from flags or from `AGENT_DESKTOP_SESSION` and `AGENT_DESKTOP_AGENT_ID`, do not apply in the guest; pass `--session` after `--`.
## status, permissions, version
diff --git a/src/tests/sandbox_provider_suites.rs b/src/tests/sandbox_provider_suites.rs
index 5deeb7ea7..63bfb8fc4 100644
--- a/src/tests/sandbox_provider_suites.rs
+++ b/src/tests/sandbox_provider_suites.rs
@@ -26,3 +26,8 @@ fn assert_suite_passes(script: &str) {
fn macos_provider_suite_passes() {
assert_suite_passes("providers/macos/test-provider.sh");
}
+
+#[test]
+fn macos_guest_channel_suite_passes() {
+ assert_suite_passes("providers/macos/test-guest-channel.sh");
+}