mirror of
https://github.com/zed-industries/zed.git
synced 2026-11-19 06:59:22 +01:00
sandbox: New linux sandbox (#67062)
Note: this PR does not change any behaviour of zed itself. The old sandbox implementation is still in use. The code in this PR is not considered secure. I'll need more time to torture it before I'm confident :) The old sandbox used `bwrap` to set up mounts to restrict FS access, and an in-sandbox network proxy to forward HTTP requests. It has significant limitations however: - it cannot restrict FS access to paths that don't exist at sandbox creation time. This means that files that become available while a command is running are unprotected - it cannot restrict FS access based on a glob - each individual mount must be specified explicitly - it cannot restrict network access that is not HTTP (i.e. SSH traffic). - it cannot change permissions while a sandboxed command is running - the grants given at the start of the execution are fixed. Agents can request to re-run the app with broader permissions, which is fine, but not great UX - it cannot detect whether a command failed because it hit the sandbox boundary or not. Again, agents can guess, but we'd like something more robust - it cannot dynamically prompt the user to escalate privileges The new sandbox has a different different design which solves these problems: - all restrictions go through seccomp user notifications - this allows us to register a supervisor process with the kernel to validate the syscalls of another program. This supervisor can run arbitrary userspace code to inspect syscalls before allowing/denying/modifying them - we create and upload a policy object to this supervisor which checks syscalls against this policy - if the policy says that the operation requires "ask"-ing, the supervisor will ask zed to show a prompt to the user and report a decision This design is a lot more unified, and since it is much more flexible, is also potentially suitable for sandboxing more parts of zed (user terminals, LSP servers, etc.). Release Notes: - N/A
This commit is contained in:
committed by
GitHub
parent
e5be9608dd
commit
3dcdee6d2b
@@ -118,4 +118,7 @@ check-filename = true
|
||||
[default.extend-words]
|
||||
flate = "flate"
|
||||
scap = "scap"
|
||||
# `RTA_OIF` in `crates/sandbox_linux/src/net.rs` is a rtnetlink attribute
|
||||
# ("output interface"), not a misspelling of "of".
|
||||
OIF = "OIF"
|
||||
writeable = "writeable"
|
||||
|
||||
Generated
+14
-2
@@ -15810,13 +15810,24 @@ dependencies = [
|
||||
"log",
|
||||
"nix 0.30.1",
|
||||
"seccompiler",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"smol",
|
||||
"tempfile",
|
||||
"windows-registry 0.6.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sandbox_linux"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"libc",
|
||||
"log",
|
||||
"nix 0.30.1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scc"
|
||||
version = "3.8.8"
|
||||
@@ -22619,6 +22630,7 @@ dependencies = [
|
||||
"reqwest_client",
|
||||
"rope",
|
||||
"sandbox",
|
||||
"sandbox_linux",
|
||||
"search",
|
||||
"semver",
|
||||
"serde",
|
||||
|
||||
@@ -188,6 +188,7 @@ members = [
|
||||
"crates/rope",
|
||||
"crates/rpc",
|
||||
"crates/sandbox",
|
||||
"crates/sandbox_linux",
|
||||
"crates/scheduler",
|
||||
"crates/schema_generator",
|
||||
"crates/search",
|
||||
@@ -464,6 +465,7 @@ rodio = { git = "https://github.com/RustAudio/rodio", rev = "3ee9745862279ce1d18
|
||||
rope = { path = "crates/rope" }
|
||||
rpc = { path = "crates/rpc" }
|
||||
sandbox = { path = "crates/sandbox" }
|
||||
sandbox_linux = { path = "crates/sandbox_linux" }
|
||||
scheduler = { path = "crates/scheduler" }
|
||||
search = { path = "crates/search" }
|
||||
session = { path = "crates/session" }
|
||||
|
||||
@@ -12,15 +12,6 @@ workspace = true
|
||||
path = "src/http_proxy.rs"
|
||||
doctest = false
|
||||
|
||||
[features]
|
||||
# Compiles in the `ZED_SANDBOX_PROXY_ALLOW_LOCAL_IPS` escape hatch that lets the
|
||||
# proxy reach loopback/private/link-local addresses. This disables the proxy's
|
||||
# DNS-rebinding/SSRF protection, so it must NEVER be enabled in a real Zed
|
||||
# build (debug or release) — it exists solely for the NixOS sandbox integration
|
||||
# tests, whose echo servers live on the VM's private network. Enabled only via
|
||||
# `sandbox/nixos-test` when building `bwrap-test-helper`.
|
||||
nixos-integration-tests = []
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
base64.workspace = true
|
||||
|
||||
@@ -156,16 +156,6 @@ impl PinnedHost {
|
||||
/// blocks them for direct connections from the sandbox; code running outside the
|
||||
/// sandbox (the proxy, the fetch tool) must not reopen them.
|
||||
pub fn is_forbidden_ip(ip: IpAddr) -> bool {
|
||||
// Escape hatch for the NixOS sandbox integration tests only: their echo
|
||||
// servers live on the VM's private network, which this filter would
|
||||
// otherwise reject. It is compiled in ONLY under the
|
||||
// `nixos-integration-tests` feature (enabled via `sandbox/nixos-test` when
|
||||
// building `bwrap-test-helper`), so in a real Zed build the env var has no
|
||||
// effect and cannot disable DNS-rebinding/SSRF protection.
|
||||
#[cfg(feature = "nixos-integration-tests")]
|
||||
if std::env::var_os("ZED_SANDBOX_PROXY_ALLOW_LOCAL_IPS").is_some() {
|
||||
return false;
|
||||
}
|
||||
match ip {
|
||||
IpAddr::V4(v4) => is_forbidden_ipv4(v4),
|
||||
IpAddr::V6(v6) => {
|
||||
|
||||
@@ -13,30 +13,11 @@ path = "src/sandbox.rs"
|
||||
doctest = false
|
||||
|
||||
[features]
|
||||
# Builds `bwrap-test-helper`, the behavior helper driven by the NixOS sandbox
|
||||
# VM tests in `nix/tests/sandboxing`. Off by default so normal builds don't
|
||||
# produce the test binary. Pulls in serde only when enabled (the helper parses
|
||||
# its check list as JSON), and enables the matching `http_proxy` escape hatch so
|
||||
# the in-process proxy can reach the VM's private-network echo servers.
|
||||
nixos-test = [
|
||||
"dep:serde",
|
||||
"dep:serde_json",
|
||||
"http_proxy/nixos-integration-tests",
|
||||
]
|
||||
|
||||
# Builds `wsl-sandbox-test-helper`, the Windows analog of `bwrap-test-helper`.
|
||||
# It drives the real WSL/Bubblewrap sandbox end-to-end (see
|
||||
# Builds `wsl-sandbox-test-helper`, which drives the WSL/Bubblewrap sandbox (see
|
||||
# `script/test-wsl-sandbox.ps1` / `cargo xtask wsl-sandbox-tests`). Off by
|
||||
# default so normal builds and the workspace test run don't produce it.
|
||||
wsl-test = []
|
||||
|
||||
# Behavior test helper for the Linux Bubblewrap sandbox. Only built when the
|
||||
# `nixos-test` feature is enabled (and only meaningful on Linux).
|
||||
[[bin]]
|
||||
name = "bwrap-test-helper"
|
||||
path = "src/bwrap_test_helper.rs"
|
||||
required-features = ["nixos-test"]
|
||||
|
||||
# Behavior test helper for the Windows WSL/Bubblewrap sandbox. Only built when
|
||||
# the `wsl-test` feature is enabled (and only meaningful on Windows).
|
||||
[[bin]]
|
||||
@@ -49,14 +30,9 @@ anyhow.workspace = true
|
||||
futures.workspace = true
|
||||
http_proxy.workspace = true
|
||||
log.workspace = true
|
||||
# Used only by the `nixos-test` helper binary to parse its check list; gated
|
||||
# behind the `nixos-test` feature so normal builds don't pull it in.
|
||||
serde = { workspace = true, features = ["derive"], optional = true }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
libc.workspace = true
|
||||
# The `nixos-test` helper binary only parses its check list on Linux.
|
||||
serde_json = { workspace = true, optional = true }
|
||||
# Safe wrappers for the SCM_RIGHTS fd-passing and `fstat` the bind validator
|
||||
# needs, so that code doesn't hand-roll `msghdr`/`CMSG_*`/`mem::zeroed` unsafe.
|
||||
nix = { workspace = true, features = ["fs", "socket", "uio"] }
|
||||
|
||||
@@ -1,609 +0,0 @@
|
||||
//! Test binary used exclusively by the NixOS integration tests for the
|
||||
//! Bubblewrap sandbox at `nix/tests/sandboxing`. See the comment there.
|
||||
//!
|
||||
//! It drives the sandbox crate's *public* API only (`Sandbox`, `SandboxPolicy`,
|
||||
//! …) — never platform internals — so it doubles as a check that the public API
|
||||
//! is sufficient to express and enforce the policies the agent needs.
|
||||
//!
|
||||
//! The list of checks to run is *data*, declared by the Nix test and handed to
|
||||
//! this binary as a JSON file (path in `ZED_SANDBOX_CHECKS`). Each check
|
||||
//! describes a sandbox policy, an operation to attempt under that policy, and
|
||||
//! the expected outcome; this binary executes each and asserts the result.
|
||||
|
||||
#![allow(
|
||||
clippy::disallowed_methods,
|
||||
reason = "a single-threaded test helper that intentionally blocks on child processes"
|
||||
)]
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn main() {
|
||||
eprintln!("bwrap-test-helper is only supported on Linux");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn main() {
|
||||
imp::main();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod imp {
|
||||
use std::io::{Read as _, Write as _};
|
||||
use std::net::TcpStream;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
use sandbox::{
|
||||
CommandAndArgs, HostFilesystemLocation, Sandbox, SandboxError, SandboxFsPolicy,
|
||||
SandboxNetPolicy, SandboxPolicy,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
|
||||
/// Internal subcommand: round-trip a byte through the echo server at the
|
||||
/// given `host:port`, honoring `HTTP_PROXY` when set (the restricted-network
|
||||
/// case routes through the sandbox proxy via HTTP CONNECT). Exits 0 on a
|
||||
/// successful round-trip, non-zero otherwise. Run *inside* the sandbox.
|
||||
const SUBCOMMAND_ECHO_CHECK: &str = "__echo_check";
|
||||
|
||||
/// Internal subcommand: connect to the unix-domain socket at the given path
|
||||
/// and round-trip a byte through it. Exits 0 on a successful round-trip,
|
||||
/// non-zero on any failure (including `socket(AF_UNIX)` being blocked once
|
||||
/// the seccomp guard lands). Run *inside* the sandbox.
|
||||
const SUBCOMMAND_UNIX_CONNECT_CHECK: &str = "__unix_connect_check";
|
||||
|
||||
/// Default port for echo targets given as a bare hostname (e.g. `echo1`).
|
||||
const DEFAULT_ECHO_PORT: &str = "7000";
|
||||
|
||||
pub fn main() {
|
||||
// If we were re-exec'd as the restricted-network bridge, this starts the
|
||||
// bridge and execs the wrapped command without returning.
|
||||
sandbox::run_sandbox_launcher_if_invoked();
|
||||
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let result = match args.get(1).map(String::as_str) {
|
||||
Some(SUBCOMMAND_ECHO_CHECK) => run_echo_check(args.get(2).map(String::as_str)),
|
||||
Some(SUBCOMMAND_UNIX_CONNECT_CHECK) => {
|
||||
run_unix_connect_check(args.get(2).map(String::as_str))
|
||||
}
|
||||
_ => run_checks(),
|
||||
};
|
||||
|
||||
if let Err(error) = result {
|
||||
eprintln!("[sandbox_test]: FAILED: {error:#}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Filesystem policy as declared in a check (`fs` field).
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum FsMode {
|
||||
/// Reads allowed everywhere; writes confined to `writablePaths`.
|
||||
#[default]
|
||||
Restricted,
|
||||
/// Writes allowed anywhere.
|
||||
Unrestricted,
|
||||
}
|
||||
|
||||
/// Network policy as declared in a check (`networkAccess` field).
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum NetMode {
|
||||
/// All outbound network blocked.
|
||||
#[default]
|
||||
Blocked,
|
||||
/// All outbound network allowed.
|
||||
Unrestricted,
|
||||
/// Outbound HTTP(S) allowed only to `allowedDomains`.
|
||||
Restricted,
|
||||
}
|
||||
|
||||
/// One declarative check: a sandbox policy, an operation, and the expected
|
||||
/// result. Deserialized from the JSON the Nix test produces.
|
||||
///
|
||||
/// Exactly one operation field (`read`, `write`, `network`, `socketPath`, or
|
||||
/// `canCreate`) must be set. Policy fields default to the most-confined policy
|
||||
/// (restricted filesystem with no writable paths, blocked network).
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct Check {
|
||||
/// Optional human label; falls back to an auto-generated description.
|
||||
#[serde(default)]
|
||||
name: Option<String>,
|
||||
|
||||
// ---- policy ----
|
||||
#[serde(default)]
|
||||
fs: FsMode,
|
||||
#[serde(default)]
|
||||
writable_paths: Vec<String>,
|
||||
/// Regular files to create before the policy is built. Used to set up a
|
||||
/// single-file-worktree fixture: a protected path like
|
||||
/// `<file>/settings.json/.git` then routes through a real file, so
|
||||
/// capturing it reports `NotADirectory` — the case production must skip
|
||||
/// rather than fail on (the `settings.json/.git` regression).
|
||||
#[serde(default)]
|
||||
seed_files: Vec<String>,
|
||||
#[serde(default)]
|
||||
network_access: NetMode,
|
||||
#[serde(default)]
|
||||
allowed_domains: Vec<String>,
|
||||
/// Paths to protect from writes even if they fall under a writable path.
|
||||
#[serde(default)]
|
||||
protected_paths: Vec<String>,
|
||||
|
||||
// ---- operation (exactly one) ----
|
||||
/// Read this host path from inside the sandbox.
|
||||
#[serde(default)]
|
||||
read: Option<String>,
|
||||
/// Write to this host path from inside the sandbox.
|
||||
#[serde(default)]
|
||||
write: Option<String>,
|
||||
/// Connect to this echo host (`hostname` or `hostname:port`) from inside
|
||||
/// the sandbox.
|
||||
#[serde(default)]
|
||||
network: Option<String>,
|
||||
/// Connect to this unix-domain socket path from inside the sandbox.
|
||||
#[serde(default)]
|
||||
socket_path: Option<String>,
|
||||
/// Assert that `Sandbox::can_create` for this policy matches the value:
|
||||
/// `true` => the sandbox can be created, `false` => it cannot.
|
||||
#[serde(default)]
|
||||
can_create: Option<bool>,
|
||||
|
||||
// ---- expectation ----
|
||||
/// Expected outcome for `read` / `write` / `network`.
|
||||
#[serde(default)]
|
||||
succeeds: Option<bool>,
|
||||
/// Expected error kind for `canCreate = false`
|
||||
/// (`bwrap_not_found` | `setuid_rejected` | `probe_failed`). When
|
||||
/// omitted, any creation failure is accepted.
|
||||
#[serde(default)]
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
fn run_checks() -> Result<()> {
|
||||
// The restricted-network proxy runs in *this* process and the echo
|
||||
// servers live on the VM's private network, which the proxy's
|
||||
// DNS-rebinding protection would otherwise reject. The proxy only honors
|
||||
// this var when built with `http_proxy/nixos-integration-tests` (pulled
|
||||
// in by `sandbox/nixos-test`, which this binary requires), so it has no
|
||||
// effect in a real Zed build.
|
||||
// SAFETY: single-threaded at this point.
|
||||
unsafe {
|
||||
std::env::set_var("ZED_SANDBOX_PROXY_ALLOW_LOCAL_IPS", "1");
|
||||
}
|
||||
|
||||
let checks_path =
|
||||
std::env::var("ZED_SANDBOX_CHECKS").context("ZED_SANDBOX_CHECKS must be set")?;
|
||||
let raw = std::fs::read_to_string(&checks_path)
|
||||
.with_context(|| format!("failed to read checks file {checks_path}"))?;
|
||||
let specs: Vec<Check> =
|
||||
serde_json::from_str(&raw).context("failed to parse checks JSON")?;
|
||||
let echo_port =
|
||||
std::env::var("ZED_TEST_ECHO_PORT").unwrap_or_else(|_| DEFAULT_ECHO_PORT.to_string());
|
||||
|
||||
println!("[sandbox_test]: running {} check(s)", specs.len());
|
||||
|
||||
let mut checks = Checks::new();
|
||||
for spec in &specs {
|
||||
run_check(spec, &echo_port, &mut checks)?;
|
||||
}
|
||||
checks.finish()
|
||||
}
|
||||
|
||||
fn policy_of(check: &Check) -> Result<SandboxPolicy> {
|
||||
let fs = match check.fs {
|
||||
FsMode::Unrestricted => SandboxFsPolicy::Unrestricted {
|
||||
protected_paths: capture_protected_paths(&check.protected_paths),
|
||||
protected_file_names: Vec::new(),
|
||||
},
|
||||
FsMode::Restricted => {
|
||||
let mut writable_paths = Vec::new();
|
||||
for path in &check.writable_paths {
|
||||
// A granted directory must exist before its inode can be
|
||||
// pinned, so create it up front, then capture it.
|
||||
std::fs::create_dir_all(path)
|
||||
.with_context(|| format!("failed to create writable path {path}"))?;
|
||||
writable_paths.push(
|
||||
HostFilesystemLocation::capture(path)
|
||||
.with_context(|| format!("failed to capture writable path {path}"))?,
|
||||
);
|
||||
}
|
||||
let protected_paths = capture_protected_paths(&check.protected_paths);
|
||||
SandboxFsPolicy::Restricted {
|
||||
writable_paths,
|
||||
protected_paths,
|
||||
protected_file_names: Vec::new(),
|
||||
}
|
||||
}
|
||||
};
|
||||
let network = match check.network_access {
|
||||
NetMode::Unrestricted => SandboxNetPolicy::Unrestricted,
|
||||
NetMode::Blocked => SandboxNetPolicy::Blocked,
|
||||
NetMode::Restricted => SandboxNetPolicy::Restricted {
|
||||
allowed_domains: check.allowed_domains.clone(),
|
||||
},
|
||||
};
|
||||
Ok(SandboxPolicy { fs, network })
|
||||
}
|
||||
|
||||
/// Capture protected paths best-effort, mirroring production
|
||||
/// (`SandboxWrap::to_policy`): protect only the ones that exist right now
|
||||
/// (`capture` succeeding is the existence check) and silently drop the rest.
|
||||
/// A protection can't be materialized, and `.git` protection has an inherent
|
||||
/// accepted loophole (`git init` in a non-git dir), so a currently-absent or
|
||||
/// otherwise-uncapturable protected path is dropped rather than fatal. These
|
||||
/// are never created here; whether one exists is exactly what several checks
|
||||
/// turn on.
|
||||
fn capture_protected_paths(paths: &[String]) -> Vec<HostFilesystemLocation> {
|
||||
paths
|
||||
.iter()
|
||||
.filter_map(|path| HostFilesystemLocation::capture(path).ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn describe(check: &Check) -> String {
|
||||
if let Some(name) = &check.name {
|
||||
return name.clone();
|
||||
}
|
||||
let protected = if check.protected_paths.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(",protected_paths={:?}", check.protected_paths)
|
||||
};
|
||||
let seed = if check.seed_files.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(",seed_files={:?}", check.seed_files)
|
||||
};
|
||||
let policy = format!(
|
||||
"fs={:?},net={:?}{protected}{seed}",
|
||||
check.fs, check.network_access
|
||||
);
|
||||
let op = if let Some(path) = &check.read {
|
||||
format!("read {path}")
|
||||
} else if let Some(path) = &check.write {
|
||||
format!("write {path}")
|
||||
} else if let Some(host) = &check.network {
|
||||
format!("network {host}")
|
||||
} else if let Some(path) = &check.socket_path {
|
||||
format!("socket_connect {path}")
|
||||
} else if let Some(expected) = check.can_create {
|
||||
format!("can_create == {expected}")
|
||||
} else {
|
||||
"<no operation>".to_string()
|
||||
};
|
||||
format!("[{policy}] {op}")
|
||||
}
|
||||
|
||||
fn run_check(check: &Check, echo_port: &str, checks: &mut Checks) -> Result<()> {
|
||||
let label = describe(check);
|
||||
|
||||
if let Some(expect_can_create) = check.can_create {
|
||||
let policy = policy_of(check)?;
|
||||
let outcome = Sandbox::can_create(&policy);
|
||||
let passed = match (&outcome, expect_can_create) {
|
||||
(Ok(()), true) => true,
|
||||
(Ok(()), false) => false,
|
||||
(Err(_), true) => false,
|
||||
(Err(error), false) => check
|
||||
.error
|
||||
.as_deref()
|
||||
.map(|expected| error_matches(error, expected))
|
||||
.unwrap_or(true),
|
||||
};
|
||||
checks.check(&format!("{label} (got {outcome:?})"), passed);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let succeeds = check
|
||||
.succeeds
|
||||
.with_context(|| format!("check {label:?} has an operation but no `succeeds`"))?;
|
||||
|
||||
// Create any regular-file fixtures before the policy is built, so a
|
||||
// protected path routed through one (e.g. `<file>/.git`) reports
|
||||
// `NotADirectory` at capture time.
|
||||
for path in &check.seed_files {
|
||||
let path = Path::new(path);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).with_context(|| {
|
||||
format!("failed to create parent of seed file {}", path.display())
|
||||
})?;
|
||||
}
|
||||
std::fs::write(path, b"seed\n")
|
||||
.with_context(|| format!("failed to create seed file {}", path.display()))?;
|
||||
}
|
||||
|
||||
let actual = if let Some(path) = &check.read {
|
||||
run_read(check, path)?
|
||||
} else if let Some(path) = &check.write {
|
||||
run_write(check, path)?
|
||||
} else if let Some(host) = &check.network {
|
||||
run_network(check, host, echo_port)?
|
||||
} else if let Some(path) = &check.socket_path {
|
||||
run_socket_connect(check, path)?
|
||||
} else {
|
||||
bail!("check {label:?} has no operation");
|
||||
};
|
||||
|
||||
checks.check(&label, actual == succeeds);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Seed a host file, then `cat` it from inside the sandbox. Reads are always
|
||||
/// granted (root is bound read-only), so this proves the sandbox doesn't
|
||||
/// *block* reads of existing host files.
|
||||
fn run_read(check: &Check, path: &str) -> Result<bool> {
|
||||
let path = Path::new(path);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)
|
||||
.with_context(|| format!("failed to create parent of {}", path.display()))?;
|
||||
}
|
||||
std::fs::write(path, b"sandbox-test\n")
|
||||
.with_context(|| format!("failed to seed readable file {}", path.display()))?;
|
||||
|
||||
// Build the policy only after the fixtures exist: capturing a
|
||||
// `HostFilesystemLocation` pins the inode, so the path must be present.
|
||||
let policy = policy_of(check)?;
|
||||
let mut sandbox = Sandbox::new(policy).map_err(sandbox_err)?;
|
||||
run_command(
|
||||
&mut sandbox,
|
||||
"sh",
|
||||
&["-c", &format!("cat {}", shell_quote(path))],
|
||||
)
|
||||
}
|
||||
|
||||
/// Attempt to write a host file from inside the sandbox. "Succeeded" means
|
||||
/// the command exited 0 *and* the bytes actually landed on the host file —
|
||||
/// a write that only hits the sandbox's ephemeral tmpfs counts as blocked,
|
||||
/// since it never escaped the sandbox.
|
||||
fn run_write(check: &Check, path: &str) -> Result<bool> {
|
||||
let path = Path::new(path);
|
||||
if let Some(parent) = path.parent() {
|
||||
// Create the parent on the host so the only thing under test is the
|
||||
// sandbox's write permission, not a missing directory. This also
|
||||
// makes a protected parent exist before the policy captures it.
|
||||
std::fs::create_dir_all(parent)
|
||||
.with_context(|| format!("failed to create parent of {}", path.display()))?;
|
||||
}
|
||||
// Start from a clean slate so `exists()` afterwards is meaningful.
|
||||
let _ = std::fs::remove_file(path);
|
||||
|
||||
// Build the policy only after the fixtures exist: capturing a
|
||||
// `HostFilesystemLocation` pins the inode, so the path must be present.
|
||||
let policy = policy_of(check)?;
|
||||
let mut sandbox = Sandbox::new(policy).map_err(sandbox_err)?;
|
||||
let command_ok = run_command(
|
||||
&mut sandbox,
|
||||
"sh",
|
||||
&[
|
||||
"-c",
|
||||
&format!("printf sandbox-test > {}", shell_quote(path)),
|
||||
],
|
||||
)?;
|
||||
Ok(command_ok && path.exists())
|
||||
}
|
||||
|
||||
/// Connect to `host` (`hostname` or `hostname:port`) from inside the
|
||||
/// sandbox via the `__echo_check` subcommand, which honors `HTTP_PROXY` for
|
||||
/// the restricted-network case.
|
||||
fn run_network(check: &Check, host: &str, echo_port: &str) -> Result<bool> {
|
||||
let target = if host.contains(':') {
|
||||
host.to_string()
|
||||
} else {
|
||||
format!("{host}:{echo_port}")
|
||||
};
|
||||
let exe = current_exe_str()?;
|
||||
let policy = policy_of(check)?;
|
||||
let mut sandbox = Sandbox::new(policy).map_err(sandbox_err)?;
|
||||
run_command(&mut sandbox, &exe, &[SUBCOMMAND_ECHO_CHECK, &target])
|
||||
}
|
||||
|
||||
/// Attempt to connect to the unix-domain socket at `path` from inside the
|
||||
/// sandbox via the `__unix_connect_check` subcommand, returning whether the
|
||||
/// round-trip succeeded. A read-only bind mount of `/` leaves the socket
|
||||
/// reachable, so a sandboxed command can currently `connect()` to a session
|
||||
/// IPC socket owned by a process *outside* the sandbox — the escape a
|
||||
/// `socket(AF_UNIX)` seccomp filter is meant to block. When that guard lands,
|
||||
/// `socket(AF_UNIX)` returns `EPERM`, the subcommand fails, and this returns
|
||||
/// `false`.
|
||||
fn run_socket_connect(check: &Check, path: &str) -> Result<bool> {
|
||||
let exe = current_exe_str()?;
|
||||
let policy = policy_of(check)?;
|
||||
let mut sandbox = Sandbox::new(policy).map_err(sandbox_err)?;
|
||||
run_command(&mut sandbox, &exe, &[SUBCOMMAND_UNIX_CONNECT_CHECK, path])
|
||||
}
|
||||
|
||||
fn error_matches(error: &SandboxError, expected: &str) -> bool {
|
||||
matches!(
|
||||
(error, expected),
|
||||
(SandboxError::BwrapNotFound, "bwrap_not_found")
|
||||
| (SandboxError::BwrapSetuidRejected, "setuid_rejected")
|
||||
| (SandboxError::SandboxProbeFailed, "probe_failed")
|
||||
)
|
||||
}
|
||||
|
||||
fn sandbox_err(error: SandboxError) -> anyhow::Error {
|
||||
anyhow::anyhow!("failed to create sandbox: {error}")
|
||||
}
|
||||
|
||||
/// Inner command: prove (or fail to prove) reachability of an echo server.
|
||||
///
|
||||
/// With `HTTP_PROXY` set we open an HTTP `CONNECT` tunnel through the proxy
|
||||
/// and then echo a byte; a policy denial shows up as a non-200 status. With
|
||||
/// no proxy we connect directly. Either way, a clean round-trip means the
|
||||
/// destination was reachable under the active network policy.
|
||||
fn run_echo_check(target: Option<&str>) -> Result<()> {
|
||||
let target = target.context("echo check requires a host:port argument")?;
|
||||
let proxy = std::env::var("HTTP_PROXY")
|
||||
.ok()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.or_else(|| {
|
||||
std::env::var("http_proxy")
|
||||
.ok()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
});
|
||||
|
||||
let mut stream = match proxy {
|
||||
Some(proxy_url) => {
|
||||
let proxy_addr = proxy_url
|
||||
.trim()
|
||||
.strip_prefix("http://")
|
||||
.unwrap_or(proxy_url.trim())
|
||||
.trim_end_matches('/')
|
||||
.to_string();
|
||||
let mut stream = TcpStream::connect(&proxy_addr)
|
||||
.with_context(|| format!("failed to connect to proxy {proxy_addr}"))?;
|
||||
stream.set_read_timeout(Some(Duration::from_secs(10)))?;
|
||||
write!(
|
||||
stream,
|
||||
"CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n"
|
||||
)
|
||||
.context("failed to send CONNECT to proxy")?;
|
||||
let status = read_status_line(&mut stream)?;
|
||||
if !status.contains(" 200") {
|
||||
bail!("proxy refused CONNECT to {target}: {status:?}");
|
||||
}
|
||||
stream
|
||||
}
|
||||
None => {
|
||||
let stream = TcpStream::connect(target)
|
||||
.with_context(|| format!("failed to connect to {target}"))?;
|
||||
stream.set_read_timeout(Some(Duration::from_secs(10)))?;
|
||||
stream
|
||||
}
|
||||
};
|
||||
|
||||
stream
|
||||
.write_all(b"ping\n")
|
||||
.context("failed to write to echo server")?;
|
||||
let mut buffer = [0u8; 32];
|
||||
let read = stream
|
||||
.read(&mut buffer)
|
||||
.context("failed to read from echo server")?;
|
||||
let echoed = String::from_utf8_lossy(&buffer[..read]);
|
||||
if echoed.contains("ping") {
|
||||
Ok(())
|
||||
} else {
|
||||
bail!("echo server returned unexpected data: {echoed:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Inner command: connect to the unix-domain socket at `path` and round-trip
|
||||
/// a byte through it.
|
||||
///
|
||||
/// Any failure — `socket(AF_UNIX)` being denied (how the seccomp guard will
|
||||
/// manifest, as `EPERM`), `connect()` failing, or a bad round-trip — exits
|
||||
/// non-zero, so the caller reads it as "not connected". A clean round-trip
|
||||
/// (exit 0) means the socket outside the sandbox was reachable.
|
||||
fn run_unix_connect_check(path: Option<&str>) -> Result<()> {
|
||||
use std::os::unix::net::UnixStream;
|
||||
|
||||
let path = path.context("unix connect check requires a socket path argument")?;
|
||||
let mut stream = UnixStream::connect(path)
|
||||
.with_context(|| format!("failed to connect to unix socket {path}"))?;
|
||||
stream.set_read_timeout(Some(Duration::from_secs(10)))?;
|
||||
stream
|
||||
.write_all(b"ping\n")
|
||||
.context("failed to write to unix socket")?;
|
||||
let mut buffer = [0u8; 32];
|
||||
let read = stream
|
||||
.read(&mut buffer)
|
||||
.context("failed to read from unix socket")?;
|
||||
let echoed = String::from_utf8_lossy(&buffer[..read]);
|
||||
if echoed.contains("ping") {
|
||||
Ok(())
|
||||
} else {
|
||||
bail!("unix socket returned unexpected data: {echoed:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Read an HTTP status line (up to the first CRLF), then drain the rest of
|
||||
/// the header block (up to the blank line) so the stream is positioned at
|
||||
/// the tunneled body.
|
||||
fn read_status_line(stream: &mut TcpStream) -> Result<String> {
|
||||
let mut header = Vec::new();
|
||||
let mut byte = [0u8; 1];
|
||||
loop {
|
||||
let read = stream
|
||||
.read(&mut byte)
|
||||
.context("failed reading proxy reply")?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
header.push(byte[0]);
|
||||
if header.ends_with(b"\r\n\r\n") {
|
||||
break;
|
||||
}
|
||||
if header.len() > 64 * 1024 {
|
||||
bail!("proxy reply headers too large");
|
||||
}
|
||||
}
|
||||
let text = String::from_utf8_lossy(&header);
|
||||
Ok(text.lines().next().unwrap_or_default().to_string())
|
||||
}
|
||||
|
||||
/// Tracks assertion results so we can report a summary and a single exit code.
|
||||
struct Checks {
|
||||
passed: usize,
|
||||
failed: usize,
|
||||
}
|
||||
|
||||
impl Checks {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
passed: 0,
|
||||
failed: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn check(&mut self, description: &str, condition: bool) {
|
||||
if condition {
|
||||
self.passed += 1;
|
||||
println!("[sandbox_test]: PASS: {description}");
|
||||
} else {
|
||||
self.failed += 1;
|
||||
println!("[sandbox_test]: FAIL: {description}");
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self) -> Result<()> {
|
||||
println!(
|
||||
"[sandbox_test]: summary: {} passed, {} failed",
|
||||
self.passed, self.failed
|
||||
);
|
||||
if self.failed > 0 {
|
||||
bail!("{} sandbox assertion(s) failed", self.failed);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrap and run a command inside `sandbox`, returning whether it exited 0.
|
||||
fn run_command(sandbox: &mut Sandbox, program: &str, args: &[&str]) -> Result<bool> {
|
||||
let command = CommandAndArgs {
|
||||
program: program.to_string(),
|
||||
args: args.iter().map(|arg| arg.to_string()).collect(),
|
||||
env: Default::default(),
|
||||
cwd: None,
|
||||
};
|
||||
let output = futures::executor::block_on(sandbox.execute(&command))
|
||||
.map_err(|error| anyhow::anyhow!("failed to run sandboxed command: {error}"))?;
|
||||
Ok(output.status.success())
|
||||
}
|
||||
|
||||
fn current_exe_str() -> Result<String> {
|
||||
Ok(std::env::current_exe()
|
||||
.context("failed to resolve current executable")?
|
||||
.to_str()
|
||||
.context("current executable path is not valid UTF-8")?
|
||||
.to_string())
|
||||
}
|
||||
|
||||
/// Single-quote a path for safe interpolation into an `sh -c` script.
|
||||
fn shell_quote(path: &Path) -> String {
|
||||
let raw = path.to_string_lossy();
|
||||
format!("'{}'", raw.replace('\'', "'\\''"))
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,7 @@
|
||||
//! Behavior test helper for the Windows WSL Bubblewrap sandbox — the Windows
|
||||
//! analog of `bwrap-test-helper`.
|
||||
//! Behavior test helper for the Windows WSL Bubblewrap sandbox.
|
||||
//!
|
||||
//! Where the Linux helper is the sandboxed process itself (it re-execs under
|
||||
//! the launcher), here the sandboxed process is a *Linux* program inside WSL
|
||||
//! while this helper runs on Windows. So instead of a status channel and a
|
||||
//! launcher, the helper drives the real [`sandbox::Sandbox`] (`new` + `wrap`),
|
||||
//! The sandboxed process is a *Linux* program inside WSL while this helper runs
|
||||
//! on Windows. The helper drives the real [`sandbox::Sandbox`] (`new` + `wrap`),
|
||||
//! spawns the command line it produces, and inspects exit codes and
|
||||
//! host-side filesystem effects to confirm every grant the sandbox makes and
|
||||
//! every restriction it imposes actually holds — including the Windows-specific
|
||||
@@ -13,8 +10,8 @@
|
||||
//!
|
||||
//! It targets the **default** WSL distro (matching real Zed usage for native
|
||||
//! Windows paths); provision that distro before running (see
|
||||
//! `script/test-wsl-sandbox.ps1`). Like the Linux helper, it **skips** (rather
|
||||
//! than fails) the enforcement assertions when the environment can't actually
|
||||
//! `script/test-wsl-sandbox.ps1`). It **skips** (rather than fails) the
|
||||
//! enforcement assertions when the environment can't actually
|
||||
//! enforce a sandbox, so a misconfigured WSL doesn't masquerade as a sandbox
|
||||
//! regression. Set `ZED_TEST_SANDBOX_REQUIRE_ENFORCED=1` to turn that skip into
|
||||
//! a failure once you've provisioned an environment that *should* enforce.
|
||||
@@ -70,8 +67,6 @@ mod imp {
|
||||
allow_fs_write: bool,
|
||||
}
|
||||
|
||||
/// Tag prefixed to every result line, matching `bwrap-test-helper` so both
|
||||
/// helpers' output reads the same.
|
||||
const RESULT_TAG: &str = "[sandbox_test]:";
|
||||
|
||||
/// `CREATE_NO_WINDOW`: keep `wsl.exe` (a console-subsystem binary) from
|
||||
@@ -723,8 +718,7 @@ mod imp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tracks assertion results so the helper can report a summary and a single
|
||||
/// exit code, mirroring `bwrap-test-helper`.
|
||||
/// Tracks assertion results so the helper can report a summary and a single exit code.
|
||||
struct Checks {
|
||||
passed: usize,
|
||||
failed: usize,
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
[package]
|
||||
name = "sandbox_linux"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
publish.workspace = true
|
||||
license = "GPL-3.0-or-later"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[lib]
|
||||
path = "src/sandbox_linux.rs"
|
||||
doctest = false
|
||||
|
||||
# The end-to-end harness is an example, not a test target: CI runs the suite
|
||||
# with `cargo nextest run --workspace`, which skips targets whose
|
||||
# required-features are unset. The NixOS VM tests build it explicitly
|
||||
# (nix/tests/sandboxing/helper.nix).
|
||||
[features]
|
||||
__end_to_end_harness = []
|
||||
|
||||
[[example]]
|
||||
name = "end_to_end"
|
||||
path = "examples/end_to_end.rs"
|
||||
required-features = ["__end_to_end_harness"]
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
anyhow.workspace = true
|
||||
libc.workspace = true
|
||||
log.workspace = true
|
||||
nix = { workspace = true, features = ["net", "socket", "uio"] }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -0,0 +1,173 @@
|
||||
# Design
|
||||
|
||||
This is a (currently experimental) re-implementation of the sandbox on Linux, with the following goals:
|
||||
- dynamic changes to the sandbox policy, without restarting the untrusted process
|
||||
- more flexible policies (e.g. globs, restricting files that don't exist yet)
|
||||
- reduced "false rejections" (e.g. allowing non-HTTP traffic)
|
||||
|
||||
The "ultimate goal" is that such a sandbox should be reasonable to leave *enabled by default for all processes* (e.g. user terminals, LSP servers, MCP servers, git clients, etc.).
|
||||
|
||||
## Security posture
|
||||
|
||||
Traditional wisdom is that there is a fundamental difference between "missing functionality" and "security issues". I disagree - if the sandbox doesn't allow users to do what they want, the vast majority will simply disable the sandbox. To put it another way, a highly effective privilege escalation attack for an agent is to:
|
||||
- try to use docker (or similar) to run a legitimate task
|
||||
- explain to the user: "I can't use docker because of the sandbox, can you disable it?"
|
||||
- the user disables the sandbox
|
||||
|
||||
## Limitations of the current Zed sandbox
|
||||
|
||||
The current Zed sandbox is, in a vacuum, very secure. However, users can still be exposed to risk in various ways. These ways usually look something like:
|
||||
- edit the project using sandboxed tools
|
||||
- this edited configuration triggers an out-of-sandbox program to run malicious code
|
||||
|
||||
For example, a malicious agent can edit your project to add a new Rust proc-macro crate that downloads and runs a malicious script. Rust-analyzer, which runs outside the sandbox, will then execute this proc-macro code and you are compromised.
|
||||
|
||||
We cannot just "run everything in the sandbox", because the current sandbox is only really usable for the agent terminal because it's not very flexible. For example, if we sandbox your user terminal, if you need internet access, we need to kill that process, and restart with the right permissions.
|
||||
|
||||
On Linux, we also have the restriction that filesystem protections can only apply to:
|
||||
- specific files and directories (globs not supported)
|
||||
- files/directories that exist at sandbox creation time
|
||||
|
||||
The implementation is also (subjectively) ugly:
|
||||
- `HostFilesystemLocation` is a bit of a monstrosity, but is required for security on Linux/WSL, due to race conditions when creating namespaces through `bwrap`
|
||||
- It also doesn't fully guarantee TOCTOU-freedom on WSL when going across the plan9 bridge to the NTFS side
|
||||
- The HTTP proxy is an entirely separate mechanism to FS sandboxing
|
||||
- There's lots of "wrapper programs" and awkward message passing
|
||||
|
||||
The new design unifies a lot of this.
|
||||
|
||||
## The new design
|
||||
|
||||
The new design aims to fix this by broadly shifting from "setting up an environment with restricted permissions" to "intercepting syscalls and dynamically resolving them against the policy".
|
||||
|
||||
There are two components to this:
|
||||
- filesystem (including domain sockets and friends)
|
||||
- networking
|
||||
|
||||
Both of these rely on seccomp user notifications. This is a Linux kernel feature that extends seccomp's syscall-filtering ability, by allowing a user "supervisor" program to (conceptually) dynamically allow/deny[^1] syscalls. This supervisor can run arbitrary code, including code that sends a prompt to the user to confirm the action.
|
||||
|
||||
The rough flow would then become:
|
||||
- each sandboxed program has a policy, which is uploaded to the supervisor
|
||||
- when the untrusted program tries to make a syscall that is sensitive, the supervisor approves/denies/prompts the user, depending on the policy, and the specific syscall made
|
||||
- when the user changes the policy (either manually, or by approving a prompt), the new policy is uploaded to the supervisor, and takes effect immediately
|
||||
|
||||
### Implementation
|
||||
|
||||
I will refer to three processes:
|
||||
- the owner process - the process that sets up the sandbox (i.e. Zed)
|
||||
- the sandbox process - the process that the untrusted command runs in
|
||||
- technically this is actually two processes, an in-sandbox helper that then spawns the untrusted command
|
||||
- the supervisor process - the process that is registered with the kernel to validate syscalls made by the sandbox process
|
||||
|
||||
There is a `SandboxPolicy` object which contains a list of rules. For example, for filesystem sandboxing a rule looks like:
|
||||
```rust
|
||||
struct FsRule {
|
||||
path: PathPattern,
|
||||
read: Option<Access>, // read a file at this path
|
||||
write: Option<Access>, // write a file at this path
|
||||
connect: Option<Access>, // connect to a socket at this path
|
||||
}
|
||||
|
||||
enum Access {
|
||||
Allow,
|
||||
Deny,
|
||||
Ask,
|
||||
}
|
||||
```
|
||||
|
||||
The owner process sets the policy, and a more cache-friendly representation gets sent to the supervisor. When the sandbox process tries to make a syscall that is not explicitly allowed to run untrapped, the arguments get sent to the supervisor.
|
||||
|
||||
The supervisor makes the call on behalf of the sandboxed program, and copies arguments into its own memory to close a TOCTOU where the sandboxed process can pass a pointer to the supervisor, get the data validated, then change the data behind that pointer before the syscall is actually executed.
|
||||
|
||||
### Network-specific considerations
|
||||
|
||||
The same principle applies to network sandboxing, with some extra machinery.
|
||||
|
||||
In particular, the kernel deals only with IP addresses, but we would like to be able to grant permission to access domain names such as `google.com`. We do this by (loosely):
|
||||
- configuring the namespace such that DNS queries go to a resolver running in the supervisor process
|
||||
- when the sandboxed process makes a DNS request for `google.com`, we return a synthetic IP address
|
||||
- the supervisor records the mapping between `google.com` and the synthetic IP address
|
||||
- when the sandboxed process tries to connect to that synthetic IP address, the supervisor can convert it back to `google.com`, and look at the policy to understand how to react (allow, deny, ask)
|
||||
- the real DNS lookup also goes through a rebinding check, so I can't grant access to `attacker_controlled_domain.com` and have that grant access to `127.0.0.1` for example
|
||||
|
||||
There is then a relay, that maps these synthetic IP addresses outside the sandbox. This lives in the supervisor. It creates real connections to the actual IP addresses for the domains (using the system DNS resolver). So when it succeeds, there are two legs:
|
||||
- sandbox <-> supervisor
|
||||
- supervisor <-> `google.com`
|
||||
|
||||
The relay just plainly copies bytes from one to the other.
|
||||
|
||||
### `Ask` mode
|
||||
|
||||
When a permission is in `Ask` mode, it blocks the syscall indefinitely(ish) until the owner process responds. The `Handler` type in a `Ask` variant is created by providing a callback that takes a `Responder`. This type is how the custom user code can indicate to the supervisor what the result was. It *must* do this using the dedicated methods. Dropping it is considered an error, which:
|
||||
- panics in debug mode
|
||||
- fails closed and warns in release mode
|
||||
|
||||
When it responds, by default it responds *only for the current syscall*. Unlike the old sandbox implementation, there's no obvious way to say "allow this syscall again in the future", because it often refers to ephemeral state (e.g. file descriptors). For example, if you allow writes to `/foo/bar/baz.rs`, and you want that approval to persist for the rest of the sandbox, should that apply to:
|
||||
- only `/foo/bar/baz.rs`
|
||||
- `/foo/bar`
|
||||
- `/foo`
|
||||
- `/`
|
||||
|
||||
The `linux_sandbox` crate doesn't address this issue, but provides the `Decision` type, which is what a `Responder` actually responds with. It contains a decision for this syscall, but also a list of rules to remember for the rest of this session. It is up zed to determine what options to show to the user.
|
||||
|
||||
It's almost always wrong to not supply any extra rules to remember.
|
||||
|
||||
## Tradeoffs
|
||||
|
||||
The one major tradeoff is performance: this design imposes a round trip to the supervisor on every syscall that may be blocked (opening files and sockets, writing, connecting). On a 9950x3d, a trapped `open` costs ~10 microseconds compared to ~0.4 microseconds untrapped. Relaying a 1 gigabit stream cost about 2.5% of a CPU core.. `stat` and friends, directory listing, and `execve` are not restricted, so don't get the overhead.
|
||||
|
||||
## Implementation ideas (ai generated)
|
||||
|
||||
### Future improvements
|
||||
|
||||
#### Synthetic IPv6 addresses for domains
|
||||
|
||||
The sandbox's DNS only hands out synthetic IPv4 addresses (from `198.18.0.0/15`). A connection to a domain has two legs, joined by the supervisor's relay, which copies bytes rather than translating packets:
|
||||
|
||||
1. app to relay, inside the sandbox, using the synthetic address;
|
||||
2. supervisor to the real server, on the host network, using whatever the name resolves to there (IPv6 included).
|
||||
|
||||
So leg 1 is always IPv4, while the real server can still be IPv6-only. Queries for IPv6 addresses (`AAAA`) get an empty answer (`NOERROR`, no records) rather than `NXDOMAIN`, so resolvers fall back to the IPv4 answer cleanly.
|
||||
|
||||
Raw IPv6 addresses (IPv6 grants, `curl http://[2606:4700::1]`) still work: the relay listens at the exact address the app connects to, with `IP_FREEBIND` set on the socket. Without it, IPv6 `bind()` only accepts addresses assigned to an interface and ignores the namespace's local routes, unlike IPv4.
|
||||
|
||||
What this gives up, all uncommon:
|
||||
- explicitly IPv6-only invocations (`curl -6`, `ssh -6`) get no address for a domain;
|
||||
- tools in IPv6-only environments that query only `AAAA` records;
|
||||
- agents debugging IPv6 itself get a confusing result.
|
||||
|
||||
If one of these matters, add a synthetic IPv6 range (a ULA `/64`) alongside the IPv4 one, using the same `IP_FREEBIND` relay path.
|
||||
|
||||
#### Revoking network grants
|
||||
|
||||
Narrowing the policy currently leaves existing TCP connections and UDP flows alive, just as already-open files keep working. If revoking a grant should cut access off, `update_policy` could report the connections and flows the new policy wouldn't allow (like `still_open` does for files) and offer to close them.
|
||||
|
||||
#### Relaying DNS to real servers
|
||||
|
||||
Port 53 of every address in the sandbox is answered by the supervisor's DNS. That's how queries reach it whatever server `resolv.conf` names, but it also means `dig @8.8.8.8` gets our answers: it's indistinguishable from the system resolver asking its configured server. Relaying instead has costs: real answers make later connections raw-IP requests, so domain rules no longer apply, and an allowed resolver is a channel for exfiltrating data in queries. A middle ground: relay port 53 only when an `Ip` rule names that exact address and port, and answer everything else ourselves (including under `Any` or `LocalNetwork` rules).
|
||||
|
||||
#### Async supervisor
|
||||
|
||||
Every relayed TCP connection takes two threads, and every UDP flow and DNS query one, so a busy `npm install` can mean hundreds of threads. An event loop in the supervisor (`smol`, which Zed already uses: `async-io` plus a small executor) would make these tasks instead; seccomp notifications would stay with their leader/follower receivers, since prompts block.
|
||||
|
||||
Measured (9950X3D; benchmark harness in the benchmarking thread): at 1 Gbit/s every relay model costs 2.5–3% of a core, so throughput alone doesn't motivate this. For bursts of short connections, async halves the relay's CPU per exchange (21 vs 48 µs) and replaces 626 threads at 1000 concurrent connections with 3. Not urgent; revisit if supervisor resource usage becomes a problem.
|
||||
|
||||
#### Exact errors for non-blocking connects
|
||||
|
||||
A `connect` on a non-blocking socket succeeds as soon as it's allowed, and the host connection is made in the background: holding the syscall instead would freeze the app's event loop for a round trip per connection. A host that refuses or can't be reached then shows up as a reset after a successful connect (`curl: (56) Recv failure: Connection reset by peer` instead of `Connection refused`). Most clients use non-blocking sockets (curl, Go, Node, Python sockets with a timeout), so this is the common case. A middle ground: wait briefly for the host connect (a few milliseconds, enough for local and fast failures) before returning early.
|
||||
|
||||
#### Sandbox differences skill
|
||||
|
||||
In-sandbox behaviour is subtly different from unsandboxed Linux (exact error codes on denied operations, resets instead of refusals after non-blocking connects, `getsockname` paths, `SO_PEERCRED` pids). Collect the differences into a documented "skill" that agents can be given, so tools don't misread sandbox artefacts as environment failures.
|
||||
|
||||
#### Datagram unix sockets
|
||||
|
||||
`socket` and `socketpair` refuse `SOCK_DGRAM` unix sockets: one could send to any socket by path with `sendmsg`, whose address is behind a pointer, and seccomp can't read the address to notice. The same trap would also let unconnected UDP `sendto` reach ports no rule names: today those datagrams go nowhere, because a relay socket only exists for ports the policy names. This breaks `sd_notify`, syslog clients and datagram pairs used for IPC.
|
||||
|
||||
Measured (9950X3D; benchmark harness in the benchmarking thread): trapping every `send*` costs +10.8 µs of CPU per send with the current notification path — the supervisor saturates a core at 1 Gbit/s of QUIC-sized datagrams. An optimized path (answer on the receiving thread, `SYNC_WAKE_UP`, cached pidfds) brings it to ~+2.2 µs per send: +28% of a core at 1 Gbit/s, and +1% or less with GSO or `sendmmsg` batches of 16. Whether that budget is acceptable is a product call.
|
||||
|
||||
#### Unix socket peer credentials
|
||||
|
||||
The supervisor makes brokered `connect` calls on its copy of the app's socket, so a server's `SO_PEERCRED` reports the supervisor's pid (the uid is the same). Servers that authorize by pid would see the wrong process.
|
||||
|
||||
[^1]: Technically, the supervisor doesn't "allow or deny" the syscall, since this introduces a race condition, where a malicious program makes a syscall, then, in between approval and the kernel executing it, changes the contents of one of the arguments which is behind a pointer (e.g. file paths). Instead, the syscall arguments (including any data behind a pointer) are copied into the supervisor, and the supervisor *makes the syscall on behalf of the sandboxed program*, and returns the result.
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../LICENSE-GPL
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,162 @@
|
||||
//! Run a command in a `sandbox_linux` sandbox.
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo run -p sandbox_linux --example run -- \
|
||||
//! --write /tmp/sandbox-escape-test-x/proj --protect /tmp/sandbox-escape-test-x/proj/.git \
|
||||
//! --hide '/**/*.env' --ask /tmp/sandbox-escape-test-x/ask \
|
||||
//! --allow-net '*.github.com:443' --ask-net '*' -- sh
|
||||
//! ```
|
||||
//!
|
||||
//! Everything is readable and nothing writable, and nothing on the network
|
||||
//! is reachable, except:
|
||||
//! - `--write PATTERN` allows writes, `--protect PATTERN` denies them;
|
||||
//! - `--hide PATTERN` denies reads;
|
||||
//! - `--ask PATTERN` asks on the terminal before each write;
|
||||
//! - `--connect PATTERN` allows connecting to unix sockets;
|
||||
//! - `--allow-net`, `--deny-net` and `--ask-net DESTINATION` for
|
||||
//! connections, with destinations as `NetRule::parse` reads them, e.g.
|
||||
//! `tcp/*.github.com:22,443`, `udp/10.0.0.0/8:53`, `loopback:5432`.
|
||||
//!
|
||||
//! Rules apply in the order given, last match wins.
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn main() {}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[allow(
|
||||
clippy::disallowed_methods,
|
||||
reason = "a manual test driver that blocks on the child"
|
||||
)]
|
||||
fn main() -> anyhow::Result<()> {
|
||||
use std::io::{BufRead as _, Write as _};
|
||||
|
||||
use anyhow::{Context as _, bail};
|
||||
use sandbox_linux::{
|
||||
Access, Decision, FsRule, Handler, NetRule, PortSet, RequestedAccess, Rule, SandboxContext,
|
||||
SandboxPolicy, UntrustedCommand,
|
||||
};
|
||||
|
||||
sandbox_linux::run_hidden_entrypoint_if_invoked();
|
||||
|
||||
// Asks on the terminal. `a` allows and remembers the exact path (or host
|
||||
// and port) for the rest of the run.
|
||||
let ask = Handler::new(|request, responder| {
|
||||
// The handler must not block, so ask on another thread.
|
||||
std::thread::spawn(move || {
|
||||
let answer = (|| -> std::io::Result<String> {
|
||||
let tty = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open("/dev/tty")?;
|
||||
let mut writer = &tty;
|
||||
writeln!(writer, "\n[sandbox] {:?} wants:", request.executable)?;
|
||||
for item in &request.items {
|
||||
match item {
|
||||
RequestedAccess::Fs { permission, path } => {
|
||||
writeln!(writer, " {permission:?} {}", path.display())?
|
||||
}
|
||||
RequestedAccess::Net {
|
||||
host,
|
||||
port,
|
||||
protocol,
|
||||
} => writeln!(writer, " {protocol:?} connection to {host}:{port}")?,
|
||||
}
|
||||
}
|
||||
write!(writer, "allow? [y/a(lways)/N] ")?;
|
||||
let mut answer = String::new();
|
||||
std::io::BufReader::new(&tty).read_line(&mut answer)?;
|
||||
Ok(answer.trim().to_lowercase())
|
||||
})()
|
||||
.unwrap_or_default();
|
||||
let decision = match answer.as_str() {
|
||||
"y" => Decision::allow(),
|
||||
"a" => Decision {
|
||||
allow: true,
|
||||
remember: request
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
RequestedAccess::Fs { permission, path } => {
|
||||
let rule = FsRule::new(path.to_str()?).ok()?;
|
||||
Some(Rule::Fs(match permission {
|
||||
sandbox_linux::Permission::Read => rule.read(Access::Allow),
|
||||
sandbox_linux::Permission::Write => rule.write(Access::Allow),
|
||||
sandbox_linux::Permission::Connect => {
|
||||
rule.connect(Access::Allow)
|
||||
}
|
||||
}))
|
||||
}
|
||||
RequestedAccess::Net {
|
||||
host,
|
||||
port,
|
||||
protocol,
|
||||
} => {
|
||||
let target = match host {
|
||||
sandbox_linux::NetHost::Domain(name) => {
|
||||
sandbox_linux::NetTarget::Domain(
|
||||
sandbox_linux::DomainPattern::new(name.as_str())
|
||||
.ok()?,
|
||||
)
|
||||
}
|
||||
sandbox_linux::NetHost::Ip(address) => {
|
||||
sandbox_linux::NetTarget::Ip(
|
||||
address.to_string().parse().ok()?,
|
||||
)
|
||||
}
|
||||
};
|
||||
let rule = NetRule::new(target, Access::Allow)
|
||||
.ports(PortSet::single(*port));
|
||||
Some(Rule::Net(match protocol {
|
||||
sandbox_linux::Protocol::Tcp => rule.tcp_only(),
|
||||
sandbox_linux::Protocol::Udp => rule.udp_only(),
|
||||
}))
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
_ => Decision::deny(),
|
||||
};
|
||||
responder.respond(decision);
|
||||
});
|
||||
});
|
||||
|
||||
let mut rules = vec![FsRule::new("/")?.read(Access::Allow)];
|
||||
let mut net = Vec::new();
|
||||
let mut arguments = std::env::args().skip(1);
|
||||
let mut command = Vec::new();
|
||||
while let Some(argument) = arguments.next() {
|
||||
let mut value = || arguments.next().context("flag needs a value");
|
||||
match argument.as_str() {
|
||||
"--write" => rules.push(FsRule::new(value()?)?.write(Access::Allow)),
|
||||
"--protect" => rules.push(FsRule::new(value()?)?.write(Access::Deny)),
|
||||
"--hide" => rules.push(FsRule::new(value()?)?.read(Access::Deny)),
|
||||
"--ask" => rules.push(FsRule::new(value()?)?.write(Access::Ask(ask.clone()))),
|
||||
"--connect" => rules.push(FsRule::new(value()?)?.connect(Access::Allow)),
|
||||
"--allow-net" => net.push(NetRule::parse(&value()?, Access::Allow)?),
|
||||
"--deny-net" => net.push(NetRule::parse(&value()?, Access::Deny)?),
|
||||
"--ask-net" => net.push(NetRule::parse(&value()?, Access::Ask(ask.clone()))?),
|
||||
"--" => command.extend(arguments.by_ref()),
|
||||
other => bail!("unexpected argument {other}"),
|
||||
}
|
||||
}
|
||||
let Some((cmd, args)) = command.split_first() else {
|
||||
bail!(
|
||||
"usage: run [--write P] [--protect P] [--hide P] [--ask P] [--connect P] [--allow-net D] \
|
||||
[--deny-net D] [--ask-net D] -- COMMAND..."
|
||||
);
|
||||
};
|
||||
|
||||
let context = SandboxContext::new()?;
|
||||
let sandbox = context.create_sandbox(SandboxPolicy { fs: rules, net })?;
|
||||
let status = sandbox
|
||||
.execute(&UntrustedCommand {
|
||||
cmd: cmd.clone(),
|
||||
args: args.to_vec(),
|
||||
env: std::env::vars().collect(),
|
||||
cwd: std::env::current_dir()?,
|
||||
})?
|
||||
.wait()?;
|
||||
drop(sandbox);
|
||||
drop(context);
|
||||
std::process::exit(status.code().unwrap_or(1));
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,380 @@
|
||||
//! The sandbox's DNS server.
|
||||
//!
|
||||
//! Every DNS query from the sandbox reaches the supervisor: port 53 of every
|
||||
//! address in the sandbox's namespace is a socket it serves, whichever server
|
||||
//! the command thinks it's asking. Names are answered with fake IPv4
|
||||
//! addresses from `198.18.0.0/15` (one per name per sandbox), so a later
|
||||
//! connection to one says which name it's for, and the policy is checked
|
||||
//! against the name.
|
||||
//!
|
||||
//! - A name no rule could allow doesn't exist (`NXDOMAIN`).
|
||||
//! - A name only `Ask` rules cover gets an address without a host lookup:
|
||||
//! nothing about it leaves the machine before the user decides.
|
||||
//! - A name an `Allow` rule covers is looked up on the host first, so names
|
||||
//! that don't exist still fail to resolve.
|
||||
//!
|
||||
//! Only `A` queries get answers: `AAAA` and other types get none, so clients
|
||||
//! fall back to IPv4. `PTR` queries for fake addresses return their names.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::{self, Read as _, Write as _};
|
||||
use std::net::{Ipv4Addr, TcpListener, TcpStream, ToSocketAddrs as _};
|
||||
use std::os::fd::{AsFd as _, OwnedFd};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::net::{self, lock};
|
||||
use crate::policy::{NameVerdict, normalize_domain};
|
||||
use crate::supervisor::{Execution, SandboxState};
|
||||
|
||||
const FAKE_BASE: u32 = u32::from_be_bytes([198, 18, 0, 0]);
|
||||
const FAKE_SIZE: u32 = 1 << 17;
|
||||
/// Short, so a fake address isn't used long after a policy change.
|
||||
const TTL: u32 = 10;
|
||||
const HOST_LOOKUP_CACHE: Duration = Duration::from_secs(10);
|
||||
const MAX_CONCURRENT_QUERIES: usize = 32;
|
||||
const TCP_IDLE_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
const TYPE_A: u16 = 1;
|
||||
const TYPE_PTR: u16 = 12;
|
||||
const TYPE_ANY: u16 = 255;
|
||||
const CLASS_IN: u16 = 1;
|
||||
const FORMAT_ERROR: u16 = 1;
|
||||
const NAME_ERROR: u16 = 3;
|
||||
const NOT_IMPLEMENTED: u16 = 4;
|
||||
|
||||
pub(crate) fn is_fake(address: Ipv4Addr) -> bool {
|
||||
u32::from(address).wrapping_sub(FAKE_BASE) < FAKE_SIZE
|
||||
}
|
||||
|
||||
/// A sandbox's fake addresses, which last as long as it does.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Names {
|
||||
by_name: HashMap<String, Ipv4Addr>,
|
||||
by_address: HashMap<Ipv4Addr, String>,
|
||||
allocated: u32,
|
||||
/// Whether names exist on the host, as recently looked up.
|
||||
host_lookups: HashMap<String, (Instant, bool)>,
|
||||
}
|
||||
|
||||
impl Names {
|
||||
fn address_for(&mut self, name: &str) -> Option<Ipv4Addr> {
|
||||
if let Some(address) = self.by_name.get(name) {
|
||||
return Some(*address);
|
||||
}
|
||||
if self.allocated + 1 >= FAKE_SIZE {
|
||||
return None;
|
||||
}
|
||||
self.allocated += 1;
|
||||
let address = Ipv4Addr::from(FAKE_BASE + self.allocated);
|
||||
self.by_name.insert(name.to_string(), address);
|
||||
self.by_address.insert(address, name.to_string());
|
||||
Some(address)
|
||||
}
|
||||
|
||||
pub fn name_for(&self, address: Ipv4Addr) -> Option<String> {
|
||||
self.by_address.get(&address).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn serve_udp(execution: &Arc<Execution>, socket: &Arc<OwnedFd>) {
|
||||
let in_flight = Arc::new(AtomicUsize::new(0));
|
||||
let mut buffer = vec![0; 4096];
|
||||
while !execution.network.is_closed() {
|
||||
let datagram = match net::receive_datagram(socket.as_fd(), &mut buffer) {
|
||||
Ok(Some(datagram)) => datagram,
|
||||
Ok(None) => continue,
|
||||
Err(error) if error.raw_os_error() == Some(libc::EINTR) => continue,
|
||||
Err(error) => {
|
||||
eprintln!("zed sandbox supervisor: receiving DNS queries: {error}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let query = buffer[..datagram.length].to_vec();
|
||||
let respond = {
|
||||
let execution = execution.clone();
|
||||
let socket = socket.clone();
|
||||
move || {
|
||||
if let Some(response) = answer(&execution.sandbox, &query) {
|
||||
// The reply comes from the address that was asked.
|
||||
if let Err(error) = net::send_datagram(
|
||||
socket.as_fd(),
|
||||
&response,
|
||||
datagram.source,
|
||||
datagram.destination,
|
||||
) {
|
||||
eprintln!("zed sandbox supervisor: answering a DNS query: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
// Answering may wait for a host lookup, so answer concurrently (up
|
||||
// to a limit).
|
||||
if in_flight.fetch_add(1, Ordering::SeqCst) < MAX_CONCURRENT_QUERIES {
|
||||
let in_flight = in_flight.clone();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("zed-sandbox-dns-query".to_string())
|
||||
.spawn(move || {
|
||||
respond();
|
||||
in_flight.fetch_sub(1, Ordering::SeqCst);
|
||||
});
|
||||
if let Err(error) = spawned {
|
||||
eprintln!("zed sandbox supervisor: answering a DNS query: {error}");
|
||||
}
|
||||
} else {
|
||||
in_flight.fetch_sub(1, Ordering::SeqCst);
|
||||
respond();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn serve_tcp(execution: &Arc<Execution>, socket: &Arc<OwnedFd>) {
|
||||
let listener = match socket.try_clone() {
|
||||
Ok(listener) => TcpListener::from(listener),
|
||||
Err(error) => {
|
||||
eprintln!("zed sandbox supervisor: serving DNS over TCP: {error}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
while !execution.network.is_closed() {
|
||||
match listener.accept() {
|
||||
Ok((stream, _)) => {
|
||||
let execution = execution.clone();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("zed-sandbox-dns-tcp".to_string())
|
||||
.spawn(move || serve_tcp_connection(&execution.sandbox, stream));
|
||||
if let Err(error) = spawned {
|
||||
eprintln!("zed sandbox supervisor: serving DNS over TCP: {error}");
|
||||
}
|
||||
}
|
||||
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
|
||||
// Shut down with the execution.
|
||||
Err(_) => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Length-prefixed queries and answers, until the client stops.
|
||||
fn serve_tcp_connection(sandbox: &SandboxState, mut stream: TcpStream) {
|
||||
let mut serve = || -> io::Result<()> {
|
||||
stream.set_read_timeout(Some(TCP_IDLE_TIMEOUT))?;
|
||||
loop {
|
||||
let mut length = [0; 2];
|
||||
stream.read_exact(&mut length)?;
|
||||
let mut query = vec![0; usize::from(u16::from_be_bytes(length))];
|
||||
stream.read_exact(&mut query)?;
|
||||
let Some(response) = answer(sandbox, &query) else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut message = (response.len() as u16).to_be_bytes().to_vec();
|
||||
message.extend(response);
|
||||
stream.write_all(&message)?;
|
||||
}
|
||||
};
|
||||
// Ending (or timing out, or a malformed length) closes the connection,
|
||||
// which is all a DNS client needs to know.
|
||||
serve().ok();
|
||||
}
|
||||
|
||||
struct Question {
|
||||
name: String,
|
||||
record_type: u16,
|
||||
class: u16,
|
||||
/// Where the question ends in the query.
|
||||
end: usize,
|
||||
}
|
||||
|
||||
/// The response to one query, if it is one.
|
||||
fn answer(sandbox: &SandboxState, query: &[u8]) -> Option<Vec<u8>> {
|
||||
let flags = u16::from_be_bytes(query.get(2..4)?.try_into().ok()?);
|
||||
if flags & 0x8000 != 0 {
|
||||
return None;
|
||||
}
|
||||
let opcode = (flags >> 11) & 0xf;
|
||||
let question_count = u16::from_be_bytes(query.get(4..6)?.try_into().ok()?);
|
||||
if opcode != 0 {
|
||||
return Some(response(query, NOT_IMPLEMENTED, None, None));
|
||||
}
|
||||
let question = match question_count {
|
||||
1 => parse_question(query),
|
||||
_ => None,
|
||||
};
|
||||
let Some(question) = question else {
|
||||
return Some(response(query, FORMAT_ERROR, None, None));
|
||||
};
|
||||
let echoed = &query[12..question.end];
|
||||
if question.class != CLASS_IN {
|
||||
return Some(response(query, NOT_IMPLEMENTED, Some(echoed), None));
|
||||
}
|
||||
if question.record_type == TYPE_PTR {
|
||||
let name = reverse_lookup(sandbox, &question.name);
|
||||
return Some(match name {
|
||||
Some(name) => response(query, 0, Some(echoed), Some((TYPE_PTR, encode_name(&name)))),
|
||||
None => response(query, NAME_ERROR, Some(echoed), None),
|
||||
});
|
||||
}
|
||||
Some(match resolve(sandbox, &question.name) {
|
||||
None => response(query, NAME_ERROR, Some(echoed), None),
|
||||
Some(address) if matches!(question.record_type, TYPE_A | TYPE_ANY) => response(
|
||||
query,
|
||||
0,
|
||||
Some(echoed),
|
||||
Some((TYPE_A, address.octets().to_vec())),
|
||||
),
|
||||
// The name exists, but has no records of this type.
|
||||
Some(_) => response(query, 0, Some(echoed), None),
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_question(query: &[u8]) -> Option<Question> {
|
||||
let mut position = 12;
|
||||
let mut labels = Vec::new();
|
||||
loop {
|
||||
let length = usize::from(*query.get(position)?);
|
||||
position += 1;
|
||||
if length == 0 {
|
||||
break;
|
||||
}
|
||||
// Longer "labels" are compression pointers, which questions don't use.
|
||||
if length > 63 {
|
||||
return None;
|
||||
}
|
||||
let label = query.get(position..position + length)?;
|
||||
position += length;
|
||||
if label.contains(&b'.') {
|
||||
return None;
|
||||
}
|
||||
labels.push(String::from_utf8_lossy(label).into_owned());
|
||||
}
|
||||
let record_type = u16::from_be_bytes(query.get(position..position + 2)?.try_into().ok()?);
|
||||
let class = u16::from_be_bytes(query.get(position + 2..position + 4)?.try_into().ok()?);
|
||||
Some(Question {
|
||||
name: normalize_domain(&labels.join(".")),
|
||||
record_type,
|
||||
class,
|
||||
end: position + 4,
|
||||
})
|
||||
}
|
||||
|
||||
fn response(
|
||||
query: &[u8],
|
||||
code: u16,
|
||||
question: Option<&[u8]>,
|
||||
answer: Option<(u16, Vec<u8>)>,
|
||||
) -> Vec<u8> {
|
||||
let query_flags = u16::from_be_bytes([query[2], query[3]]);
|
||||
// A response, with the query's opcode and "recursion desired", and
|
||||
// recursion available.
|
||||
let flags = 0x8000 | (query_flags & 0x7800) | (query_flags & 0x0100) | 0x0080 | code;
|
||||
let mut message = query[0..2].to_vec();
|
||||
message.extend(flags.to_be_bytes());
|
||||
message.extend(u16::from(question.is_some()).to_be_bytes());
|
||||
message.extend(u16::from(answer.is_some()).to_be_bytes());
|
||||
message.extend([0; 4]);
|
||||
if let Some(question) = question {
|
||||
message.extend(question);
|
||||
}
|
||||
if let Some((record_type, data)) = answer {
|
||||
// The name: a pointer to the question's, right after the header.
|
||||
message.extend([0xc0, 12]);
|
||||
message.extend(record_type.to_be_bytes());
|
||||
message.extend(CLASS_IN.to_be_bytes());
|
||||
message.extend(TTL.to_be_bytes());
|
||||
message.extend((data.len() as u16).to_be_bytes());
|
||||
message.extend(data);
|
||||
}
|
||||
message
|
||||
}
|
||||
|
||||
fn encode_name(name: &str) -> Vec<u8> {
|
||||
let mut encoded = Vec::new();
|
||||
for label in name.split('.').filter(|label| !label.is_empty()) {
|
||||
encoded.push(label.len() as u8);
|
||||
encoded.extend(label.as_bytes());
|
||||
}
|
||||
encoded.push(0);
|
||||
encoded
|
||||
}
|
||||
|
||||
/// The fake address for `name`, if it should resolve.
|
||||
fn resolve(sandbox: &SandboxState, name: &str) -> Option<Ipv4Addr> {
|
||||
let exists = match sandbox.policy().name_verdict(name) {
|
||||
NameVerdict::Deny => false,
|
||||
NameVerdict::Ask => true,
|
||||
NameVerdict::Allow => exists_on_host(sandbox, name),
|
||||
};
|
||||
if !exists {
|
||||
return None;
|
||||
}
|
||||
lock(&sandbox.names).address_for(name)
|
||||
}
|
||||
|
||||
fn exists_on_host(sandbox: &SandboxState, name: &str) -> bool {
|
||||
if let Some((looked_up, exists)) = lock(&sandbox.names).host_lookups.get(name)
|
||||
&& looked_up.elapsed() < HOST_LOOKUP_CACHE
|
||||
{
|
||||
return *exists;
|
||||
}
|
||||
let exists = !name.is_empty()
|
||||
&& (name, 0)
|
||||
.to_socket_addrs()
|
||||
.is_ok_and(|mut addresses| addresses.next().is_some());
|
||||
let mut names = lock(&sandbox.names);
|
||||
names
|
||||
.host_lookups
|
||||
.retain(|_, (looked_up, _)| looked_up.elapsed() < HOST_LOOKUP_CACHE);
|
||||
names
|
||||
.host_lookups
|
||||
.insert(name.to_string(), (Instant::now(), exists));
|
||||
exists
|
||||
}
|
||||
|
||||
/// The name of a fake address, from its `in-addr.arpa` name.
|
||||
fn reverse_lookup(sandbox: &SandboxState, name: &str) -> Option<String> {
|
||||
let reversed = name.strip_suffix(".in-addr.arpa")?;
|
||||
let mut octets = [0u8; 4];
|
||||
let mut parts = reversed.split('.');
|
||||
for octet in octets.iter_mut().rev() {
|
||||
*octet = parts.next()?.parse().ok()?;
|
||||
}
|
||||
if parts.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
lock(&sandbox.names).name_for(Ipv4Addr::from(octets))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn query(name: &str, record_type: u16) -> Vec<u8> {
|
||||
let mut query = vec![0x12, 0x34, 0x01, 0x00, 0, 1, 0, 0, 0, 0, 0, 0];
|
||||
query.extend(encode_name(name));
|
||||
query.extend(record_type.to_be_bytes());
|
||||
query.extend(CLASS_IN.to_be_bytes());
|
||||
query
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_question_round_trip() {
|
||||
let query = query("Example.COM", TYPE_A);
|
||||
let question = parse_question(&query).unwrap();
|
||||
assert_eq!(question.name, "example.com");
|
||||
assert_eq!(question.record_type, TYPE_A);
|
||||
assert_eq!(question.end, query.len());
|
||||
|
||||
let response = response(
|
||||
&query,
|
||||
0,
|
||||
Some(&query[12..question.end]),
|
||||
Some((TYPE_A, vec![198, 18, 0, 1])),
|
||||
);
|
||||
assert_eq!(&response[0..2], &[0x12, 0x34]);
|
||||
assert_eq!(u16::from_be_bytes([response[2], response[3]]), 0x8180);
|
||||
assert_eq!(&response[6..8], &[0, 1]);
|
||||
assert_eq!(&response[response.len() - 4..], &[198, 18, 0, 1]);
|
||||
assert!(is_fake(Ipv4Addr::new(198, 19, 255, 255)));
|
||||
assert!(!is_fake(Ipv4Addr::new(198, 20, 0, 0)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
//! The helper (`zed --zed-sandbox-linux-helper`), which becomes the parent of
|
||||
//! the sandboxed command.
|
||||
//!
|
||||
//! Spawned by Zed with two inherited sockets: [`SETUP_FD`] carries the
|
||||
//! [`HelperSetup`], and [`ATTACH_FD`] reaches the supervisor. It then:
|
||||
//!
|
||||
//! 1. creates user, mount, network and IPC namespaces. The mount namespace
|
||||
//! is a copy of the host's, made read-only: the kernel-enforced backstop
|
||||
//! for any write syscall the supervisor doesn't handle. Paths are the
|
||||
//! same inside and out. In the network namespace every address routes
|
||||
//! to loopback, and DNS sockets are created for the supervisor
|
||||
//! ([`crate::net`]).
|
||||
//! 2. becomes a child subreaper, so every process the command spawns stays
|
||||
//! its descendant (that's how the supervisor tells them apart);
|
||||
//! 3. forks the command, which drops all capabilities, installs the seccomp
|
||||
//! filter, hands the listener (and DNS sockets) to the supervisor and
|
||||
//! execs;
|
||||
//! 4. serves the supervisor's requests for sockets in the namespace, while
|
||||
//! it waits for the command; then kills whatever it left running, and exits with
|
||||
//! its status.
|
||||
|
||||
#![allow(
|
||||
clippy::disallowed_methods,
|
||||
reason = "the helper is a standalone process that must block on its command"
|
||||
)]
|
||||
|
||||
use std::os::fd::{AsFd as _, AsRawFd as _, BorrowedFd, FromRawFd as _, OwnedFd, RawFd};
|
||||
use std::os::unix::process::{CommandExt as _, ExitStatusExt as _};
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use anyhow::{Context as _, Result};
|
||||
|
||||
use crate::protocol::{AttachInfo, HelperSetup, receive_message, send_message};
|
||||
use crate::sys::{self, cvt};
|
||||
|
||||
pub(crate) const HELPER_FLAG: &str = "--zed-sandbox-linux-helper";
|
||||
pub(crate) const SETUP_FD: RawFd = 3;
|
||||
pub(crate) const ATTACH_FD: RawFd = 4;
|
||||
|
||||
/// Exit status for failures before the command runs (as with `env`/`bwrap`).
|
||||
const SETUP_FAILED: i32 = 126;
|
||||
|
||||
pub(crate) fn run() -> ! {
|
||||
match run_helper() {
|
||||
Ok(code) => std::process::exit(code),
|
||||
Err(error) => {
|
||||
eprintln!("zed sandbox: {error:#}");
|
||||
std::process::exit(SETUP_FAILED);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_helper() -> Result<i32> {
|
||||
sys::set_parent_death_signal()?;
|
||||
// SAFETY: Zed spawns the helper with exactly these two descriptors.
|
||||
let (setup_socket, attach_socket) = unsafe {
|
||||
(
|
||||
sys::inherited_fd(SETUP_FD).context("missing setup socket")?,
|
||||
sys::inherited_fd(ATTACH_FD).context("missing attach socket")?,
|
||||
)
|
||||
};
|
||||
let (setup, _) = receive_message::<HelperSetup>(setup_socket.as_fd())?
|
||||
.context("Zed closed the setup channel")?;
|
||||
drop(setup_socket);
|
||||
|
||||
// SAFETY: getuid/getgid can't fail.
|
||||
let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) };
|
||||
let namespaces =
|
||||
libc::CLONE_NEWUSER | libc::CLONE_NEWNS | libc::CLONE_NEWNET | libc::CLONE_NEWIPC;
|
||||
// SAFETY: plain unshare; we're single-threaded.
|
||||
if let Err(error) = cvt(unsafe { libc::unshare(namespaces) }) {
|
||||
anyhow::bail!(
|
||||
"creating sandbox namespaces failed: {error}. Unprivileged user namespaces may be \
|
||||
disabled, or (on Ubuntu 23.10+) restricted by AppArmor"
|
||||
);
|
||||
}
|
||||
// Keep our own uid/gid inside. Capabilities come from having created the
|
||||
// user namespace, and the command drops them.
|
||||
std::fs::write("/proc/self/setgroups", "deny").context("writing setgroups")?;
|
||||
std::fs::write("/proc/self/uid_map", format!("{uid} {uid} 1")).context("writing uid_map")?;
|
||||
std::fs::write("/proc/self/gid_map", format!("{gid} {gid} 1")).context("writing gid_map")?;
|
||||
bring_up_loopback()?;
|
||||
crate::net::configure_namespace()?;
|
||||
let dns_sockets = crate::net::create_dns_sockets()?;
|
||||
|
||||
// Nothing done here may propagate back to the host.
|
||||
sys::mount(
|
||||
None,
|
||||
Path::new("/"),
|
||||
None,
|
||||
libc::MS_REC | libc::MS_PRIVATE,
|
||||
None,
|
||||
)
|
||||
.context("making mounts private")?;
|
||||
sys::mount_setattr(Path::new("/"), sys::MOUNT_ATTR_RDONLY, true)
|
||||
.context("making the filesystem read-only")?;
|
||||
// SAFETY: plain prctl.
|
||||
cvt(unsafe { libc::prctl(libc::PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) })
|
||||
.context("becoming a subreaper")?;
|
||||
|
||||
install_terminate_handler()?;
|
||||
let command = spawn_command(&setup, &attach_socket, dns_sockets)?;
|
||||
start_factory(attach_socket)?;
|
||||
let status = wait_for_command(command)?;
|
||||
kill_remaining();
|
||||
Ok(status)
|
||||
}
|
||||
|
||||
static TERMINATE_REQUESTED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
extern "C" fn on_terminate(_signal: libc::c_int) {
|
||||
TERMINATE_REQUESTED.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// `SIGTERM` stops the whole execution: the command and everything it
|
||||
/// spawned (which `SIGKILL`ing the helper alone would orphan). The handler
|
||||
/// is installed without `SA_RESTART`, so it interrupts `waitpid`. The
|
||||
/// command gets default dispositions back when it execs.
|
||||
fn install_terminate_handler() -> Result<()> {
|
||||
// SAFETY: plain old data.
|
||||
let mut action: libc::sigaction = unsafe { std::mem::zeroed() };
|
||||
action.sa_sigaction = on_terminate as extern "C" fn(libc::c_int) as libc::sighandler_t;
|
||||
action.sa_flags = 0;
|
||||
// SAFETY: valid pointers to a sigaction we own.
|
||||
unsafe {
|
||||
libc::sigemptyset(&mut action.sa_mask);
|
||||
cvt(libc::sigaction(
|
||||
libc::SIGTERM,
|
||||
&action,
|
||||
std::ptr::null_mut(),
|
||||
))
|
||||
.context("installing the SIGTERM handler")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn wait_for_command(command: libc::pid_t) -> Result<i32> {
|
||||
loop {
|
||||
if TERMINATE_REQUESTED.load(Ordering::SeqCst) {
|
||||
return Ok(128 + libc::SIGTERM);
|
||||
}
|
||||
let mut status = 0;
|
||||
// SAFETY: plain waitpid.
|
||||
let pid = unsafe { libc::waitpid(-1, &mut status, 0) };
|
||||
if pid == command {
|
||||
return Ok(exit_code(status));
|
||||
}
|
||||
if pid < 0 {
|
||||
let error = std::io::Error::last_os_error();
|
||||
if error.raw_os_error() != Some(libc::EINTR) {
|
||||
return Err(error).context("waiting for the command");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Kill everything the command left behind. As a subreaper we inherit each
|
||||
/// orphan, so repeat until there are no children left.
|
||||
fn kill_remaining() {
|
||||
// SAFETY: getpid can't fail.
|
||||
let helper = unsafe { libc::getpid() };
|
||||
loop {
|
||||
for process in crate::process::all_processes() {
|
||||
if process.parent == helper {
|
||||
// SAFETY: plain kill.
|
||||
unsafe { libc::kill(process.pid, libc::SIGKILL) };
|
||||
}
|
||||
}
|
||||
let mut status = 0;
|
||||
// SAFETY: plain waitpid.
|
||||
let pid = unsafe { libc::waitpid(-1, &mut status, 0) };
|
||||
if pid < 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ECHILD) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn exit_code(status: i32) -> i32 {
|
||||
let status = std::process::ExitStatus::from_raw(status);
|
||||
status
|
||||
.code()
|
||||
.unwrap_or_else(|| 128 + status.signal().unwrap_or(0))
|
||||
}
|
||||
|
||||
fn bring_up_loopback() -> Result<()> {
|
||||
// SAFETY: plain socket call.
|
||||
let socket =
|
||||
cvt(unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM | libc::SOCK_CLOEXEC, 0) })?;
|
||||
// SAFETY: freshly created, owned here.
|
||||
let socket = unsafe { OwnedFd::from_raw_fd(socket) };
|
||||
// SAFETY: `ifreq` is plain old data.
|
||||
let mut request: libc::ifreq = unsafe { std::mem::zeroed() };
|
||||
for (slot, byte) in request.ifr_name.iter_mut().zip(b"lo") {
|
||||
*slot = *byte as libc::c_char;
|
||||
}
|
||||
// SAFETY: SIOC[GS]IFFLAGS with a valid `ifreq`.
|
||||
unsafe {
|
||||
cvt(libc::ioctl(
|
||||
socket.as_raw_fd(),
|
||||
libc::SIOCGIFFLAGS,
|
||||
&mut request,
|
||||
))?;
|
||||
request.ifr_ifru.ifru_flags |= libc::IFF_UP as libc::c_short;
|
||||
cvt(libc::ioctl(
|
||||
socket.as_raw_fd(),
|
||||
libc::SIOCSIFFLAGS,
|
||||
&request,
|
||||
))
|
||||
.context("bringing up loopback")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Serve the supervisor's requests for sockets in our namespace, on a thread
|
||||
/// that leaves `SIGTERM` to the main one (where it interrupts `waitpid`).
|
||||
fn start_factory(attach_socket: OwnedFd) -> Result<()> {
|
||||
// SAFETY: plain old data, initialized by sigemptyset.
|
||||
let mut terminate: libc::sigset_t = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: valid signal set pointers.
|
||||
unsafe {
|
||||
libc::sigemptyset(&mut terminate);
|
||||
libc::sigaddset(&mut terminate, libc::SIGTERM);
|
||||
libc::pthread_sigmask(libc::SIG_BLOCK, &terminate, std::ptr::null_mut());
|
||||
}
|
||||
// The new thread inherits the blocked mask.
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("zed-sandbox-factory".to_string())
|
||||
.spawn(move || crate::net::serve_factory(attach_socket));
|
||||
// SAFETY: as above.
|
||||
unsafe { libc::pthread_sigmask(libc::SIG_UNBLOCK, &terminate, std::ptr::null_mut()) };
|
||||
spawned.context("starting the socket factory")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn spawn_command(
|
||||
setup: &HelperSetup,
|
||||
attach_socket: &OwnedFd,
|
||||
dns_sockets: Vec<OwnedFd>,
|
||||
) -> Result<libc::pid_t> {
|
||||
let filter = crate::seccomp::build_filter();
|
||||
let mut command = Command::new(&setup.command.cmd);
|
||||
command
|
||||
.args(&setup.command.args)
|
||||
.env_clear()
|
||||
.envs(&setup.command.env)
|
||||
.current_dir(&setup.command.cwd);
|
||||
let attach = attach_socket.as_raw_fd();
|
||||
let dns: Vec<RawFd> = dns_sockets
|
||||
.iter()
|
||||
.map(|socket| socket.as_raw_fd())
|
||||
.collect();
|
||||
// SAFETY: runs in the forked child before exec. The helper is
|
||||
// single-threaded, so no lock can be held across the fork.
|
||||
unsafe {
|
||||
command.pre_exec(move || {
|
||||
sys::set_parent_death_signal()?;
|
||||
drop_capabilities()?;
|
||||
let helper_pid = libc::getppid();
|
||||
let listener = crate::seccomp::install(&filter)?;
|
||||
// From here on, opens go to the supervisor, which can't answer
|
||||
// until it has the listener: send it before anything else.
|
||||
// SAFETY: `attach` stays open in the child until exec (CLOEXEC).
|
||||
let attach = BorrowedFd::borrow_raw(attach);
|
||||
let mut fds = vec![listener.as_raw_fd()];
|
||||
fds.extend(&dns);
|
||||
send_message(attach, &AttachInfo { helper_pid }, &fds)
|
||||
.map_err(std::io::Error::other)?;
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let child = command
|
||||
.spawn()
|
||||
.with_context(|| format!("running {}", setup.command.cmd))?;
|
||||
// The supervisor has them now (they were close-on-exec in the command).
|
||||
drop(dns_sockets);
|
||||
Ok(child.id() as libc::pid_t)
|
||||
}
|
||||
|
||||
/// Clear every capability set. `exec` as a non-root uid already does this;
|
||||
/// being explicit also covers a user running Zed as root.
|
||||
fn drop_capabilities() -> std::io::Result<()> {
|
||||
#[repr(C)]
|
||||
struct CapabilityHeader {
|
||||
version: u32,
|
||||
pid: i32,
|
||||
}
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
struct CapabilityData {
|
||||
effective: u32,
|
||||
permitted: u32,
|
||||
inheritable: u32,
|
||||
}
|
||||
const LINUX_CAPABILITY_VERSION_3: u32 = 0x2008_0522;
|
||||
|
||||
for capability in 0..64 {
|
||||
// SAFETY: plain prctl; EINVAL past the last capability is expected.
|
||||
unsafe { libc::prctl(libc::PR_CAPBSET_DROP, capability, 0, 0, 0) };
|
||||
}
|
||||
// SAFETY: plain prctl.
|
||||
cvt(unsafe {
|
||||
libc::prctl(
|
||||
libc::PR_CAP_AMBIENT,
|
||||
libc::PR_CAP_AMBIENT_CLEAR_ALL,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
)
|
||||
})?;
|
||||
let header = CapabilityHeader {
|
||||
version: LINUX_CAPABILITY_VERSION_3,
|
||||
pid: 0,
|
||||
};
|
||||
let data = [CapabilityData {
|
||||
effective: 0,
|
||||
permitted: 0,
|
||||
inheritable: 0,
|
||||
}; 2];
|
||||
// SAFETY: capset with a v3 header and two data words.
|
||||
cvt(unsafe { libc::syscall(libc::SYS_capset, &header, data.as_ptr()) as i32 })?;
|
||||
Ok(())
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,130 @@
|
||||
//! Which host processes belong to an execution.
|
||||
//!
|
||||
//! There's no pid namespace, so sandboxed processes share the host's pid
|
||||
//! space. Every process of an execution descends from its helper, which is a
|
||||
//! child subreaper: orphans are reparented to it rather than escaping to the
|
||||
//! host's init.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Component, Path};
|
||||
|
||||
pub(crate) struct ProcessInfo {
|
||||
pub pid: i32,
|
||||
pub parent: i32,
|
||||
pub group: i32,
|
||||
}
|
||||
|
||||
/// Parse `/proc/<pid>/stat`. The command name is in parentheses and may
|
||||
/// itself contain spaces and parentheses, so fields are read after the last
|
||||
/// `)`.
|
||||
pub(crate) fn process_info(pid: i32) -> Option<ProcessInfo> {
|
||||
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
|
||||
let (_, fields) = stat.rsplit_once(')')?;
|
||||
let mut fields = fields.split_whitespace();
|
||||
let _state = fields.next()?;
|
||||
let parent = fields.next()?.parse().ok()?;
|
||||
let group = fields.next()?.parse().ok()?;
|
||||
Some(ProcessInfo { pid, parent, group })
|
||||
}
|
||||
|
||||
/// The controlling terminal device of `pid` (0: none).
|
||||
pub(crate) fn controlling_terminal(pid: i32) -> Option<u64> {
|
||||
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
|
||||
let (_, fields) = stat.rsplit_once(')')?;
|
||||
// state ppid pgrp session tty_nr
|
||||
fields
|
||||
.split_whitespace()
|
||||
.nth(4)?
|
||||
.parse::<i64>()
|
||||
.ok()
|
||||
.map(|tty| tty as u64)
|
||||
}
|
||||
|
||||
pub(crate) fn thread_group(tid: i32) -> Option<i32> {
|
||||
read_status_head(tid)?
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("Tgid:"))
|
||||
.and_then(|value| value.trim().parse().ok())
|
||||
}
|
||||
|
||||
/// The start of `/proc/<tid>/status` (`Name`, `Umask`, `State`, `Tgid`,
|
||||
/// ...), in one `read`. Reading the whole file makes the kernel format
|
||||
/// dozens of lines, through a growing buffer.
|
||||
pub(crate) fn read_status_head(tid: i32) -> Option<String> {
|
||||
use std::io::Read as _;
|
||||
let mut file = std::fs::File::open(format!("/proc/{tid}/status")).ok()?;
|
||||
let mut buffer = [0u8; 512];
|
||||
let length = file.read(&mut buffer).ok()?;
|
||||
Some(String::from_utf8_lossy(&buffer[..length]).into_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn all_processes() -> Vec<ProcessInfo> {
|
||||
let Ok(entries) = std::fs::read_dir("/proc") else {
|
||||
return Vec::new();
|
||||
};
|
||||
entries
|
||||
.filter_map(|entry| entry.ok()?.file_name().to_str()?.parse().ok())
|
||||
.filter_map(process_info)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The pid in a `/proc/<pid>/...` path, if it is one.
|
||||
pub(crate) fn proc_path_pid(path: &Path) -> Option<i32> {
|
||||
let mut components = path.components();
|
||||
if components.next() != Some(Component::RootDir)
|
||||
|| components.next() != Some(Component::Normal("proc".as_ref()))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
match components.next()? {
|
||||
Component::Normal(name) => name.to_str()?.parse().ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct ProcessTree {
|
||||
pub helper: i32,
|
||||
}
|
||||
|
||||
impl ProcessTree {
|
||||
/// Whether `pid` (a process or thread id) strictly descends from the
|
||||
/// helper.
|
||||
pub fn contains(&self, pid: i32) -> bool {
|
||||
let mut current = pid;
|
||||
for _ in 0..4096 {
|
||||
let Some(info) = process_info(current) else {
|
||||
return false;
|
||||
};
|
||||
if info.parent == self.helper {
|
||||
return true;
|
||||
}
|
||||
if info.parent <= 1 {
|
||||
return false;
|
||||
}
|
||||
current = info.parent;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub fn members(&self) -> Vec<ProcessInfo> {
|
||||
let processes = all_processes();
|
||||
let mut children: HashMap<i32, Vec<usize>> = HashMap::new();
|
||||
for (index, process) in processes.iter().enumerate() {
|
||||
children.entry(process.parent).or_default().push(index);
|
||||
}
|
||||
let mut members = Vec::new();
|
||||
let mut stack = vec![self.helper];
|
||||
while let Some(parent) = stack.pop() {
|
||||
for &index in children.get(&parent).into_iter().flatten() {
|
||||
stack.push(processes[index].pid);
|
||||
members.push(index);
|
||||
}
|
||||
}
|
||||
let mut processes: Vec<Option<ProcessInfo>> = processes.into_iter().map(Some).collect();
|
||||
members
|
||||
.into_iter()
|
||||
.filter_map(|index| processes[index].take())
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
//! Messages between Zed, the supervisor and the helper.
|
||||
//!
|
||||
//! Every channel is an anonymous `SOCK_SEQPACKET` socketpair, so each message
|
||||
//! is one packet: a JSON body plus any descriptors as `SCM_RIGHTS`. Packets
|
||||
//! are capped by the socket buffer (~200 KiB by default), so larger bodies
|
||||
//! (e.g. a big environment) travel in a memfd passed as the first fd.
|
||||
//!
|
||||
//! ```text
|
||||
//! Zed <--control--> supervisor ZedMessage / SupervisorMessage
|
||||
//! Zed --setup-----> helper HelperSetup (once)
|
||||
//! helper --attach----> supervisor AttachInfo + the seccomp listener (once)
|
||||
//! helper <-attach----> supervisor FactoryRequest / FactoryResponse (then)
|
||||
//! ```
|
||||
|
||||
use std::io::{IoSlice, IoSliceMut};
|
||||
use std::net::SocketAddr;
|
||||
use std::os::fd::{AsRawFd as _, BorrowedFd, FromRawFd as _, OwnedFd, RawFd};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
use nix::sys::socket::{ControlMessage, ControlMessageOwned, MsgFlags, recvmsg, sendmsg};
|
||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
|
||||
use crate::UntrustedCommand;
|
||||
use crate::net::SocketKind;
|
||||
use crate::policy::{HandlerId, RequestedAccess, WirePolicy, WireRule};
|
||||
|
||||
const MAX_FDS: usize = 8;
|
||||
const MAX_INLINE_SIZE: usize = 64 * 1024;
|
||||
const MAX_MESSAGE_SIZE: usize = 16 * 1024 * 1024;
|
||||
|
||||
const INLINE_BODY: u8 = 0;
|
||||
const MEMFD_BODY: u8 = 1;
|
||||
|
||||
pub(crate) type SandboxId = u64;
|
||||
pub(crate) type RequestId = u64;
|
||||
pub(crate) type PromptId = u64;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(crate) enum ZedMessage {
|
||||
Request {
|
||||
id: RequestId,
|
||||
request: Request,
|
||||
},
|
||||
PromptReply {
|
||||
prompt: PromptId,
|
||||
allow: bool,
|
||||
/// Appended to the sandbox's policy before the syscall is answered.
|
||||
remember: Vec<WireRule>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(crate) enum Request {
|
||||
/// `sandbox` is chosen by Zed, so it can register the policy's handlers
|
||||
/// under it before the supervisor can ask any of them.
|
||||
CreateSandbox {
|
||||
sandbox: SandboxId,
|
||||
policy: WirePolicy,
|
||||
},
|
||||
UpdatePolicy {
|
||||
sandbox: SandboxId,
|
||||
policy: WirePolicy,
|
||||
},
|
||||
DestroySandbox {
|
||||
sandbox: SandboxId,
|
||||
},
|
||||
/// Descriptors: the supervisor's end of a fresh attach socketpair, whose
|
||||
/// other end goes to the helper of one execution in `sandbox`.
|
||||
AttachExecution {
|
||||
sandbox: SandboxId,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(crate) enum SupervisorMessage {
|
||||
Response {
|
||||
id: RequestId,
|
||||
response: Response,
|
||||
},
|
||||
Prompt(PromptRequest),
|
||||
/// The syscall behind a prompt was abandoned or timed out; a reply is no
|
||||
/// longer needed.
|
||||
PromptCancelled {
|
||||
prompt: PromptId,
|
||||
},
|
||||
Denied {
|
||||
sandbox: SandboxId,
|
||||
denial: Denial,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(crate) enum Response {
|
||||
PolicyUpdated { still_open: Vec<OpenFile> },
|
||||
Done,
|
||||
Error { message: String },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub(crate) struct PromptRequest {
|
||||
pub prompt: PromptId,
|
||||
pub sandbox: SandboxId,
|
||||
/// The handler (in Zed's table) that decides.
|
||||
pub handler: HandlerId,
|
||||
pub requests: Vec<RequestedAccess>,
|
||||
pub pid: i32,
|
||||
pub executable: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// An operation the policy, or a handler answering an [`Access::Ask`],
|
||||
/// denied.
|
||||
///
|
||||
/// [`Access::Ask`]: crate::Access::Ask
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Denial {
|
||||
/// What the denied syscall needed that wasn't granted.
|
||||
pub requests: Vec<RequestedAccess>,
|
||||
/// The thread that made the syscall.
|
||||
pub pid: i32,
|
||||
pub executable: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// A file a sandboxed process still has open with access the current policy
|
||||
/// no longer grants. Revoking a grant never affects open descriptors.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct OpenFile {
|
||||
pub pid: i32,
|
||||
pub path: PathBuf,
|
||||
pub read: bool,
|
||||
pub write: bool,
|
||||
}
|
||||
|
||||
/// Sent by the helper's command (before it execs) with its seccomp listener,
|
||||
/// followed by the sandbox's DNS sockets.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(crate) struct AttachInfo {
|
||||
/// Every process of the execution descends from the helper, which is a
|
||||
/// child subreaper.
|
||||
pub helper_pid: i32,
|
||||
}
|
||||
|
||||
/// Asks the helper for a socket in the sandbox's network namespace, where
|
||||
/// only it can create them, or for a duplicate of a descriptor of one of its
|
||||
/// processes. Answered with a [`FactoryResponse`], carrying the socket if
|
||||
/// there was one.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(crate) enum FactoryRequest {
|
||||
CreateSocket {
|
||||
kind: SocketKind,
|
||||
address: SocketAddr,
|
||||
},
|
||||
/// Fetching a descriptor is `pidfd_getfd(2)`, which the kernel gates on
|
||||
/// ptrace access. The supervisor may be denied that as a mere sibling of
|
||||
/// the command (by Yama's `ptrace_scope`, or AppArmor's restriction of
|
||||
/// unprivileged user namespaces), so it asks the helper, every command's
|
||||
/// parent, instead.
|
||||
FetchFd { pid: i32, fd: i32 },
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(crate) enum FactoryResponse {
|
||||
Created,
|
||||
Fetched,
|
||||
Failed { errno: i32 },
|
||||
}
|
||||
|
||||
/// Everything the helper needs to set up the sandbox and run the command.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(crate) struct HelperSetup {
|
||||
pub command: UntrustedCommand,
|
||||
}
|
||||
|
||||
pub(crate) fn send_message<T: Serialize>(
|
||||
socket: BorrowedFd<'_>,
|
||||
message: &T,
|
||||
fds: &[RawFd],
|
||||
) -> Result<()> {
|
||||
let body = serde_json::to_vec(message).context("serializing sandbox message")?;
|
||||
if body.len() > MAX_MESSAGE_SIZE {
|
||||
bail!("sandbox message too large ({} bytes)", body.len());
|
||||
}
|
||||
if fds.len() >= MAX_FDS {
|
||||
bail!(
|
||||
"too many descriptors in one sandbox message ({})",
|
||||
fds.len()
|
||||
);
|
||||
}
|
||||
let memfd;
|
||||
let mut all_fds = Vec::with_capacity(fds.len() + 1);
|
||||
let packet = if body.len() <= MAX_INLINE_SIZE {
|
||||
let mut packet = vec![INLINE_BODY];
|
||||
packet.extend_from_slice(&body);
|
||||
packet
|
||||
} else {
|
||||
memfd = body_memfd(&body)?;
|
||||
all_fds.push(memfd.as_raw_fd());
|
||||
vec![MEMFD_BODY]
|
||||
};
|
||||
all_fds.extend_from_slice(fds);
|
||||
let iov = [IoSlice::new(&packet)];
|
||||
let control = [ControlMessage::ScmRights(&all_fds)];
|
||||
let control: &[ControlMessage] = if all_fds.is_empty() { &[] } else { &control };
|
||||
sendmsg::<()>(
|
||||
socket.as_raw_fd(),
|
||||
&iov,
|
||||
control,
|
||||
MsgFlags::MSG_NOSIGNAL,
|
||||
None,
|
||||
)
|
||||
.context("sending sandbox message")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Receive one message. `Ok(None)` means the peer closed the channel.
|
||||
pub(crate) fn receive_message<T: DeserializeOwned>(
|
||||
socket: BorrowedFd<'_>,
|
||||
) -> Result<Option<(T, Vec<OwnedFd>)>> {
|
||||
let mut body = vec![0u8; MAX_INLINE_SIZE + 1];
|
||||
let mut control = nix::cmsg_space!([RawFd; MAX_FDS]);
|
||||
let mut fds = Vec::new();
|
||||
let (length, flags) = {
|
||||
let mut iov = [IoSliceMut::new(&mut body)];
|
||||
let message = recvmsg::<()>(
|
||||
socket.as_raw_fd(),
|
||||
&mut iov,
|
||||
Some(&mut control),
|
||||
MsgFlags::MSG_CMSG_CLOEXEC,
|
||||
)
|
||||
.context("receiving sandbox message")?;
|
||||
for control_message in message.cmsgs().context("reading descriptors")? {
|
||||
if let ControlMessageOwned::ScmRights(raw_fds) = control_message {
|
||||
for raw_fd in raw_fds {
|
||||
// SAFETY: the kernel installed each received descriptor
|
||||
// fresh in our table; we take sole ownership here.
|
||||
fds.push(unsafe { OwnedFd::from_raw_fd(raw_fd) });
|
||||
}
|
||||
}
|
||||
}
|
||||
(message.bytes, message.flags)
|
||||
};
|
||||
if flags.intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC) {
|
||||
bail!("sandbox message was truncated");
|
||||
}
|
||||
if length == 0 && fds.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let message = match body.first() {
|
||||
Some(&INLINE_BODY) => serde_json::from_slice(&body[1..length]),
|
||||
Some(&MEMFD_BODY) if length == 1 && !fds.is_empty() => {
|
||||
let mut file = std::fs::File::from(fds.remove(0));
|
||||
let mut contents = Vec::new();
|
||||
std::io::Read::read_to_end(
|
||||
&mut std::io::Read::take(&mut file, MAX_MESSAGE_SIZE as u64),
|
||||
&mut contents,
|
||||
)?;
|
||||
serde_json::from_slice(&contents)
|
||||
}
|
||||
_ => bail!("malformed sandbox message"),
|
||||
}
|
||||
.context("parsing sandbox message")?;
|
||||
Ok(Some((message, fds)))
|
||||
}
|
||||
|
||||
fn body_memfd(body: &[u8]) -> Result<OwnedFd> {
|
||||
// SAFETY: valid NUL-terminated name.
|
||||
let fd = crate::sys::cvt(unsafe {
|
||||
libc::memfd_create(c"zed-sandbox-message".as_ptr(), libc::MFD_CLOEXEC)
|
||||
})?;
|
||||
// SAFETY: a freshly returned descriptor that nothing else owns.
|
||||
let mut file = std::fs::File::from(unsafe { OwnedFd::from_raw_fd(fd) });
|
||||
std::io::Write::write_all(&mut file, body)?;
|
||||
std::io::Seek::rewind(&mut file)?;
|
||||
Ok(file.into())
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
//! Path resolution on behalf of a sandboxed thread.
|
||||
//!
|
||||
//! The supervisor never opens a path string the target gave it in one go:
|
||||
//! the kernel would resolve `/proc/self` (and symlinks through it, like
|
||||
//! `/dev/stdin`) as the *supervisor*, and a racing target could swap
|
||||
//! components between our check and our use. Instead we walk one component
|
||||
//! at a time from a root fd, holding each directory, and decide on the
|
||||
//! object we end up holding.
|
||||
//!
|
||||
//! Most paths take a fast path: `openat2` resolves the whole path in the
|
||||
//! kernel, confined to the root (`RESOLVE_IN_ROOT`, so `..` and absolute
|
||||
//! symlinks behave as for the target) and refusing magic links. The result
|
||||
//! is only used when it isn't on procfs, the one place where resolving as the
|
||||
//! supervisor differs from resolving as the target; anything else falls back
|
||||
//! to the walk.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::ffi::{CString, OsStr, OsString};
|
||||
use std::io;
|
||||
use std::os::fd::{AsFd as _, AsRawFd as _, BorrowedFd, OwnedFd};
|
||||
use std::os::unix::ffi::OsStrExt as _;
|
||||
use std::path::{Component, Path};
|
||||
|
||||
use crate::process::{ProcessTree, proc_path_pid};
|
||||
use crate::sys::{self, errno};
|
||||
|
||||
const MAX_SYMLINKS: usize = 40;
|
||||
const PROC_SUPER_MAGIC: i64 = 0x9fa0;
|
||||
|
||||
// Syscalls added after the per-arch tables were unified share one number.
|
||||
const SYS_OPENAT2: libc::c_long = 437;
|
||||
const RESOLVE_NO_MAGICLINKS: u64 = 0x02;
|
||||
const RESOLVE_IN_ROOT: u64 = 0x10;
|
||||
|
||||
pub(crate) enum Resolved {
|
||||
/// The final component, unopened: in [`Mode::Entry`], or because it
|
||||
/// doesn't exist.
|
||||
Entry { parent: OwnedFd, name: CString },
|
||||
/// The final object, opened `O_PATH`.
|
||||
Object(OwnedFd),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum Mode {
|
||||
/// Resolve the parent directory, and never look at the final component.
|
||||
Entry,
|
||||
/// Open the final component, following it if it's a symlink and `follow`.
|
||||
Object { follow: bool },
|
||||
}
|
||||
|
||||
pub(crate) struct Resolver<'a> {
|
||||
pub root: BorrowedFd<'a>,
|
||||
/// The thread the path belongs to, for `/proc/self` and
|
||||
/// `/proc/thread-self`.
|
||||
pub tid: i32,
|
||||
/// The thread's process, looked up only if `/proc/self` is reached.
|
||||
pub tgid: &'a dyn Fn() -> io::Result<i32>,
|
||||
pub tree: ProcessTree,
|
||||
}
|
||||
|
||||
impl Resolver<'_> {
|
||||
pub fn resolve(&self, path: &Path, mode: Mode) -> io::Result<Resolved> {
|
||||
if let Some(resolved) = self.resolve_fast(path, mode) {
|
||||
return Ok(resolved);
|
||||
}
|
||||
self.resolve_walk(path, mode)
|
||||
}
|
||||
|
||||
/// `None` whenever the walk has to decide (errors included, so that
|
||||
/// error cases behave exactly as the walk makes them).
|
||||
fn resolve_fast(&self, path: &Path, mode: Mode) -> Option<Resolved> {
|
||||
match mode {
|
||||
Mode::Object { follow } => {
|
||||
let flags = if follow { 0 } else { libc::O_NOFOLLOW };
|
||||
let object = self.open_in_root(path.as_os_str(), flags).ok()?;
|
||||
(!is_procfs(object.as_fd()).ok()?).then_some(Resolved::Object(object))
|
||||
}
|
||||
Mode::Entry => {
|
||||
let name = match path.components().next_back()? {
|
||||
Component::Normal(name) => name,
|
||||
_ => return None,
|
||||
};
|
||||
let parent = self
|
||||
.open_in_root(path.parent()?.as_os_str(), libc::O_DIRECTORY)
|
||||
.ok()?;
|
||||
if is_procfs(parent.as_fd()).ok()? {
|
||||
return None;
|
||||
}
|
||||
Some(Resolved::Entry {
|
||||
parent,
|
||||
name: sys::cstring(name.as_bytes()).ok()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn open_in_root(&self, path: &OsStr, flags: i32) -> io::Result<OwnedFd> {
|
||||
#[repr(C)]
|
||||
struct OpenHow {
|
||||
flags: u64,
|
||||
mode: u64,
|
||||
resolve: u64,
|
||||
}
|
||||
let path = sys::cstring(path.as_bytes())?;
|
||||
let how = OpenHow {
|
||||
flags: (libc::O_PATH | libc::O_CLOEXEC | flags) as u64,
|
||||
mode: 0,
|
||||
resolve: RESOLVE_IN_ROOT | RESOLVE_NO_MAGICLINKS,
|
||||
};
|
||||
// SAFETY: a NUL-terminated path and a correctly sized `open_how`.
|
||||
let fd = unsafe {
|
||||
libc::syscall(
|
||||
SYS_OPENAT2,
|
||||
self.root.as_raw_fd(),
|
||||
path.as_ptr(),
|
||||
&how as *const OpenHow,
|
||||
size_of::<OpenHow>(),
|
||||
)
|
||||
};
|
||||
if fd < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
// SAFETY: a freshly returned descriptor that nothing else owns.
|
||||
Ok(unsafe { std::os::fd::FromRawFd::from_raw_fd(fd as i32) })
|
||||
}
|
||||
|
||||
fn resolve_walk(&self, path: &Path, mode: Mode) -> io::Result<Resolved> {
|
||||
let mut pending = components(path);
|
||||
let mut current = self.reopen_root()?;
|
||||
let mut symlinks = 0;
|
||||
loop {
|
||||
let Some(component) = pending.pop_front() else {
|
||||
// The path ended on a directory: `/`, `a/.`, `a/..`.
|
||||
return match mode {
|
||||
Mode::Entry => Err(errno(libc::EBUSY)),
|
||||
Mode::Object { .. } => Ok(Resolved::Object(current)),
|
||||
};
|
||||
};
|
||||
if component == "." {
|
||||
continue;
|
||||
}
|
||||
if component == ".." {
|
||||
if !self.is_root(current.as_fd())? {
|
||||
current = open_path(current.as_fd(), OsStr::new(".."), libc::O_DIRECTORY)?;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let last = pending.is_empty();
|
||||
let name = sys::cstring(component.as_bytes())?;
|
||||
if last && matches!(mode, Mode::Entry) {
|
||||
return Ok(Resolved::Entry {
|
||||
parent: current,
|
||||
name,
|
||||
});
|
||||
}
|
||||
let next = match open_path(current.as_fd(), &component, libc::O_NOFOLLOW) {
|
||||
Ok(next) => next,
|
||||
Err(error) if last && error.raw_os_error() == Some(libc::ENOENT) => {
|
||||
return Ok(Resolved::Entry {
|
||||
parent: current,
|
||||
name,
|
||||
});
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let follow = !last || matches!(mode, Mode::Object { follow: true });
|
||||
let is_symlink = sys::fstat(next.as_fd())?.st_mode & libc::S_IFMT == libc::S_IFLNK;
|
||||
if !(is_symlink && follow) {
|
||||
if last {
|
||||
return Ok(Resolved::Object(next));
|
||||
}
|
||||
current = next;
|
||||
continue;
|
||||
}
|
||||
|
||||
symlinks += 1;
|
||||
if symlinks > MAX_SYMLINKS {
|
||||
return Err(errno(libc::ELOOP));
|
||||
}
|
||||
if is_procfs(current.as_fd())? {
|
||||
let directory = sys::fd_path(current.as_fd())?;
|
||||
if directory == Path::new("/proc") {
|
||||
// Ordinary symlinks, some relative to `self`
|
||||
// (`mounts -> self/mounts`). `self` itself is rewritten
|
||||
// to the target, since the kernel would answer for us.
|
||||
let target = match component.as_bytes() {
|
||||
b"self" => OsString::from((self.tgid)()?.to_string()),
|
||||
b"thread-self" => {
|
||||
OsString::from(format!("{}/task/{}", (self.tgid)()?, self.tid))
|
||||
}
|
||||
_ => readlink(next.as_fd())?.into_os_string(),
|
||||
};
|
||||
prepend(&mut pending, Path::new(&target));
|
||||
continue;
|
||||
}
|
||||
// Inside `/proc/<pid>`, symlinks are magic links (`cwd`,
|
||||
// `exe`, `fd/N`, ...) that jump straight to an object. Follow
|
||||
// them only for our own processes; the kernel would let us
|
||||
// (as the supervisor) reach other processes' objects too.
|
||||
if !proc_path_pid(&directory).is_some_and(|pid| self.tree.contains(pid)) {
|
||||
return Err(errno(libc::EACCES));
|
||||
}
|
||||
let target = open_path(current.as_fd(), &component, 0)?;
|
||||
if last {
|
||||
return Ok(Resolved::Object(target));
|
||||
}
|
||||
current = target;
|
||||
continue;
|
||||
}
|
||||
let target = readlink(next.as_fd())?;
|
||||
if target.is_absolute() {
|
||||
current = self.reopen_root()?;
|
||||
}
|
||||
prepend(&mut pending, &target);
|
||||
}
|
||||
}
|
||||
|
||||
fn reopen_root(&self) -> io::Result<OwnedFd> {
|
||||
open_path(self.root, OsStr::new("."), libc::O_DIRECTORY)
|
||||
}
|
||||
|
||||
fn is_root(&self, directory: BorrowedFd<'_>) -> io::Result<bool> {
|
||||
let directory = sys::fstat(directory)?;
|
||||
let root = sys::fstat(self.root)?;
|
||||
Ok((directory.st_dev, directory.st_ino) == (root.st_dev, root.st_ino))
|
||||
}
|
||||
}
|
||||
|
||||
fn components(path: &Path) -> VecDeque<OsString> {
|
||||
let mut pending = VecDeque::new();
|
||||
prepend(&mut pending, path);
|
||||
pending
|
||||
}
|
||||
|
||||
fn prepend(pending: &mut VecDeque<OsString>, path: &Path) {
|
||||
let names: Vec<OsString> = path
|
||||
.components()
|
||||
.filter_map(|component| match component {
|
||||
Component::Normal(name) => Some(name.to_os_string()),
|
||||
Component::ParentDir => Some(OsString::from("..")),
|
||||
Component::RootDir | Component::CurDir | Component::Prefix(_) => None,
|
||||
})
|
||||
.collect();
|
||||
for name in names.into_iter().rev() {
|
||||
pending.push_front(name);
|
||||
}
|
||||
}
|
||||
|
||||
fn open_path(directory: BorrowedFd<'_>, name: &OsStr, flags: i32) -> io::Result<OwnedFd> {
|
||||
sys::openat(
|
||||
directory.as_raw_fd(),
|
||||
&sys::cstring(name.as_bytes())?,
|
||||
libc::O_PATH | flags,
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
/// The content of the symlink `link` (an `O_PATH | O_NOFOLLOW` fd).
|
||||
fn readlink(link: BorrowedFd<'_>) -> io::Result<std::path::PathBuf> {
|
||||
let mut buffer = vec![0u8; libc::PATH_MAX as usize];
|
||||
// SAFETY: an empty path with a symlink fd reads that symlink; the buffer
|
||||
// is valid for its length.
|
||||
let length = unsafe {
|
||||
libc::readlinkat(
|
||||
link.as_raw_fd(),
|
||||
c"".as_ptr(),
|
||||
buffer.as_mut_ptr().cast(),
|
||||
buffer.len(),
|
||||
)
|
||||
};
|
||||
if length < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
buffer.truncate(length as usize);
|
||||
Ok(OsString::from(OsStr::from_bytes(&buffer)).into())
|
||||
}
|
||||
|
||||
fn is_procfs(directory: BorrowedFd<'_>) -> io::Result<bool> {
|
||||
// SAFETY: plain old data, filled in by the kernel.
|
||||
let mut stat: libc::statfs = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: valid fd and pointer.
|
||||
sys::cvt(unsafe { libc::fstatfs(directory.as_raw_fd(), &mut stat) })?;
|
||||
Ok(stat.f_type as i64 == PROC_SUPER_MAGIC)
|
||||
}
|
||||
@@ -0,0 +1,703 @@
|
||||
//! Linux sandboxing by syscall interception.
|
||||
//!
|
||||
//! - [`SandboxContext`] owns a supervisor process (this binary, re-executed
|
||||
//! with a hidden flag).
|
||||
//! - [`SandboxContext::create_sandbox`] registers a [`SandboxPolicy`] with
|
||||
//! the supervisor. [`Sandbox::update_policy`] replaces it while commands
|
||||
//! run.
|
||||
//! - [`Sandbox::execute`] spawns the helper (also this binary), which sets up
|
||||
//! namespaces, installs a seccomp filter whose notifications go to the
|
||||
//! supervisor, and runs the command.
|
||||
//!
|
||||
//! The sandbox sees the host filesystem at the same paths, mounted read-only.
|
||||
//! Every open and every write-intent syscall goes to the supervisor, which
|
||||
//! checks the policy and performs the operation itself.
|
||||
//!
|
||||
//! Each command gets a network namespace from which nothing outside is
|
||||
//! reachable; the supervisor answers its DNS queries and relays the TCP
|
||||
//! connections and UDP flows the policy allows (see `net.rs`).
|
||||
//!
|
||||
//! The binary must call [`run_hidden_entrypoint_if_invoked`] first thing in
|
||||
//! `main`.
|
||||
|
||||
#![cfg(target_os = "linux")]
|
||||
|
||||
mod broker;
|
||||
mod dns;
|
||||
mod helper;
|
||||
mod net;
|
||||
mod policy;
|
||||
mod process;
|
||||
mod protocol;
|
||||
mod resolve;
|
||||
mod seccomp;
|
||||
mod supervisor;
|
||||
mod sys;
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::os::fd::{AsFd as _, AsRawFd as _, OwnedFd, RawFd};
|
||||
use std::os::unix::process::CommandExt as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, Command, Output, Stdio};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, mpsc};
|
||||
use std::thread::JoinHandle;
|
||||
|
||||
use anyhow::{Context as _, Result, anyhow, bail};
|
||||
use nix::sys::socket::{AddressFamily, SockFlag, SockType, socketpair};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub use policy::{
|
||||
Access, AccessRequest, AddressClass, Decision, DomainPattern, FsRule, Handler, IpNet, NetHost,
|
||||
NetRule, NetTarget, PathPattern, Permission, PortSet, Protocol, RequestedAccess, Rule,
|
||||
SandboxPolicy,
|
||||
};
|
||||
pub use protocol::{Denial, OpenFile};
|
||||
|
||||
use policy::{HandlerId, WireAccess, WireFsRule, WirePolicy};
|
||||
use protocol::{
|
||||
HelperSetup, PromptId, Request, RequestId, Response, SandboxId, SupervisorMessage, ZedMessage,
|
||||
};
|
||||
|
||||
/// A command to run inside a sandbox.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct UntrustedCommand {
|
||||
pub cmd: String,
|
||||
pub args: Vec<String>,
|
||||
pub env: HashMap<String, String>,
|
||||
pub cwd: PathBuf,
|
||||
}
|
||||
|
||||
/// Answers one [`AccessRequest`] passed to a [`Handler`]. Answer from any
|
||||
/// thread, at any time.
|
||||
///
|
||||
/// Every request must be answered with [`Responder::respond`]: a decision
|
||||
/// usually also remembers a rule, and silently dropping the responder would
|
||||
/// lose that. Dropping it unanswered is treated as a bug: it panics in debug
|
||||
/// builds, and logs a warning and denies in release builds. Dropping is fine
|
||||
/// once [`Responder::is_cancelled`] is true, or while unwinding from a panic
|
||||
/// (both deny).
|
||||
pub struct Responder {
|
||||
prompt: PromptId,
|
||||
sandbox: SandboxId,
|
||||
handlers: Arc<HandlerTable>,
|
||||
control: Arc<OwnedFd>,
|
||||
cancelled: Arc<AtomicBool>,
|
||||
answered: bool,
|
||||
}
|
||||
|
||||
impl Responder {
|
||||
pub fn respond(mut self, decision: Decision) {
|
||||
self.send(decision);
|
||||
}
|
||||
|
||||
/// Whether the blocked syscall was abandoned (e.g. the process was
|
||||
/// killed) or timed out, so an answer would no longer have any effect.
|
||||
pub fn is_cancelled(&self) -> bool {
|
||||
self.cancelled.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn send(&mut self, decision: Decision) {
|
||||
if std::mem::replace(&mut self.answered, true) {
|
||||
return;
|
||||
}
|
||||
self.handlers.forget_prompt(self.prompt);
|
||||
let mut register = |handler: &Handler| self.handlers.register(self.sandbox, handler);
|
||||
let remember = decision
|
||||
.remember
|
||||
.iter()
|
||||
.map(|rule| rule.to_wire(&mut register))
|
||||
.collect();
|
||||
let reply = ZedMessage::PromptReply {
|
||||
prompt: self.prompt,
|
||||
allow: decision.allow,
|
||||
remember,
|
||||
};
|
||||
if let Err(error) = protocol::send_message(self.control.as_fd(), &reply, &[]) {
|
||||
eprintln!("zed sandbox: answering prompt failed: {error:#}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Responder {
|
||||
fn drop(&mut self) {
|
||||
if self.answered {
|
||||
return;
|
||||
}
|
||||
let is_bug = !self.is_cancelled() && !std::thread::panicking();
|
||||
// Deny before panicking, so the syscall isn't left blocked until the
|
||||
// prompt times out.
|
||||
self.send(Decision::deny());
|
||||
if is_bug {
|
||||
if cfg!(debug_assertions) {
|
||||
panic!("a sandbox Responder was dropped without responding");
|
||||
}
|
||||
log::warn!("[sandbox] a Responder was dropped without responding; denying");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every sandbox's handlers, by the id the supervisor refers to them with.
|
||||
#[derive(Default)]
|
||||
struct HandlerTable {
|
||||
state: Mutex<HandlerTableState>,
|
||||
}
|
||||
|
||||
type DenialHandler = Arc<dyn Fn(Denial) + Send + Sync>;
|
||||
|
||||
#[derive(Default)]
|
||||
struct HandlerTableState {
|
||||
handlers: HashMap<HandlerId, (SandboxId, Handler)>,
|
||||
denial_handlers: HashMap<SandboxId, DenialHandler>,
|
||||
/// Unanswered prompts, so a cancellation can reach their responders.
|
||||
prompts: HashMap<PromptId, Arc<AtomicBool>>,
|
||||
next: HandlerId,
|
||||
}
|
||||
|
||||
impl HandlerTable {
|
||||
fn state(&self) -> std::sync::MutexGuard<'_, HandlerTableState> {
|
||||
match self.state.lock() {
|
||||
Ok(state) => state,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The id of `handler` for `sandbox`, reusing the existing one if it was
|
||||
/// registered before.
|
||||
fn register(&self, sandbox: SandboxId, handler: &Handler) -> HandlerId {
|
||||
let mut state = self.state();
|
||||
let existing = state
|
||||
.handlers
|
||||
.iter()
|
||||
.find(|(_, (owner, known))| *owner == sandbox && Arc::ptr_eq(&known.0, &handler.0));
|
||||
if let Some((&id, _)) = existing {
|
||||
return id;
|
||||
}
|
||||
let id = state.next;
|
||||
state.next += 1;
|
||||
state.handlers.insert(id, (sandbox, handler.clone()));
|
||||
id
|
||||
}
|
||||
|
||||
fn get(&self, id: HandlerId) -> Option<(SandboxId, Handler)> {
|
||||
self.state().handlers.get(&id).cloned()
|
||||
}
|
||||
|
||||
/// Drop `sandbox`'s handlers except those in `keep`.
|
||||
fn retain(&self, sandbox: SandboxId, keep: &HashSet<HandlerId>) {
|
||||
self.state()
|
||||
.handlers
|
||||
.retain(|id, (owner, _)| *owner != sandbox || keep.contains(id));
|
||||
}
|
||||
|
||||
fn denial_handler(&self, sandbox: SandboxId) -> Option<DenialHandler> {
|
||||
self.state().denial_handlers.get(&sandbox).cloned()
|
||||
}
|
||||
|
||||
fn track_prompt(&self, prompt: PromptId) -> Arc<AtomicBool> {
|
||||
let cancelled = Arc::new(AtomicBool::new(false));
|
||||
self.state().prompts.insert(prompt, cancelled.clone());
|
||||
cancelled
|
||||
}
|
||||
|
||||
fn forget_prompt(&self, prompt: PromptId) {
|
||||
self.state().prompts.remove(&prompt);
|
||||
}
|
||||
|
||||
fn cancel_prompt(&self, prompt: PromptId) {
|
||||
if let Some(cancelled) = self.state().prompts.remove(&prompt) {
|
||||
cancelled.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// The supervisor is gone: no answer can have an effect any more.
|
||||
fn cancel_all_prompts(&self) {
|
||||
for (_, cancelled) in self.state().prompts.drain() {
|
||||
cancelled.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the supervisor or helper if this process was started as one; never
|
||||
/// returns in that case. Call before anything else in `main`: the helper's
|
||||
/// command line must not be interpreted as the host program's own.
|
||||
pub fn run_hidden_entrypoint_if_invoked() {
|
||||
match std::env::args_os()
|
||||
.nth(1)
|
||||
.as_deref()
|
||||
.and_then(|flag| flag.to_str())
|
||||
{
|
||||
Some(supervisor::SUPERVISOR_FLAG) => run_supervisor(),
|
||||
Some(helper::HELPER_FLAG) => helper::run(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The supervisor process's main loop. Expects its control socket at fd 3.
|
||||
pub fn run_supervisor() -> ! {
|
||||
supervisor::run()
|
||||
}
|
||||
|
||||
/// Owns the supervisor process. Dropping it stops the supervisor; commands
|
||||
/// still running then fail every trapped syscall with `ENOSYS`.
|
||||
pub struct SandboxContext {
|
||||
inner: Arc<ContextInner>,
|
||||
}
|
||||
|
||||
struct ContextInner {
|
||||
executable: PathBuf,
|
||||
control: Arc<OwnedFd>,
|
||||
supervisor: Mutex<Child>,
|
||||
reader: Mutex<Option<JoinHandle<()>>>,
|
||||
pending: Arc<Mutex<HashMap<RequestId, mpsc::Sender<Response>>>>,
|
||||
handlers: Arc<HandlerTable>,
|
||||
next_request: AtomicU64,
|
||||
next_sandbox: AtomicU64,
|
||||
}
|
||||
|
||||
impl SandboxContext {
|
||||
/// Start a supervisor by re-executing the current binary.
|
||||
pub fn new() -> Result<Self> {
|
||||
let executable = std::env::current_exe().context("locating the current executable")?;
|
||||
Self::with_executable(executable)
|
||||
}
|
||||
|
||||
/// Start a supervisor using `executable`, which must call
|
||||
/// [`run_hidden_entrypoint_if_invoked`].
|
||||
#[allow(
|
||||
clippy::disallowed_methods,
|
||||
reason = "PoC: blocking spawn; callers must stay off the UI thread"
|
||||
)]
|
||||
pub fn with_executable(executable: PathBuf) -> Result<Self> {
|
||||
let (ours, theirs) = seqpacket_pair()?;
|
||||
let mut command = Command::new(&executable);
|
||||
command
|
||||
.arg(supervisor::SUPERVISOR_FLAG)
|
||||
.stdin(Stdio::null());
|
||||
let child_fds = inherit_fds(&mut command, &[(theirs, supervisor::CONTROL_FD)])?;
|
||||
let supervisor = command.spawn().context("starting the sandbox supervisor")?;
|
||||
drop(child_fds);
|
||||
|
||||
let control = Arc::new(ours);
|
||||
let pending: Arc<Mutex<HashMap<RequestId, mpsc::Sender<Response>>>> = Arc::default();
|
||||
let handlers: Arc<HandlerTable> = Arc::default();
|
||||
let reader = std::thread::Builder::new()
|
||||
.name("zed-sandbox-control".to_string())
|
||||
.spawn({
|
||||
let control = control.clone();
|
||||
let pending = pending.clone();
|
||||
let handlers = handlers.clone();
|
||||
move || read_control(&control, &pending, &handlers)
|
||||
})
|
||||
.context("starting the sandbox control thread")?;
|
||||
Ok(Self {
|
||||
inner: Arc::new(ContextInner {
|
||||
executable,
|
||||
control,
|
||||
supervisor: Mutex::new(supervisor),
|
||||
reader: Mutex::new(Some(reader)),
|
||||
pending,
|
||||
handlers,
|
||||
next_request: AtomicU64::new(0),
|
||||
next_sandbox: AtomicU64::new(0),
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn create_sandbox(&self, policy: SandboxPolicy) -> Result<Sandbox> {
|
||||
let id = self.inner.next_sandbox.fetch_add(1, Ordering::Relaxed);
|
||||
let temp_dir = create_temp_dir()?;
|
||||
// Dropping `sandbox` on an error below cleans up its directory and
|
||||
// handlers without asking the supervisor to destroy it.
|
||||
let mut sandbox = Sandbox {
|
||||
context: self.inner.clone(),
|
||||
id,
|
||||
temp_dir,
|
||||
created: false,
|
||||
};
|
||||
let policy = sandbox.to_wire(&policy)?;
|
||||
self.inner.call(
|
||||
Request::CreateSandbox {
|
||||
sandbox: id,
|
||||
policy,
|
||||
},
|
||||
&[],
|
||||
)?;
|
||||
sandbox.created = true;
|
||||
Ok(sandbox)
|
||||
}
|
||||
}
|
||||
|
||||
fn read_control(
|
||||
control: &Arc<OwnedFd>,
|
||||
pending: &Mutex<HashMap<RequestId, mpsc::Sender<Response>>>,
|
||||
handlers: &Arc<HandlerTable>,
|
||||
) {
|
||||
loop {
|
||||
let message = match protocol::receive_message::<SupervisorMessage>(control.as_fd()) {
|
||||
Ok(Some((message, _))) => message,
|
||||
Ok(None) => break,
|
||||
Err(error) => {
|
||||
eprintln!("zed sandbox: reading from supervisor failed: {error:#}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
match message {
|
||||
SupervisorMessage::Response { id, response } => {
|
||||
let sender = pending
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut pending| pending.remove(&id));
|
||||
if let Some(sender) = sender {
|
||||
sender.send(response).ok();
|
||||
}
|
||||
}
|
||||
SupervisorMessage::Prompt(request) => {
|
||||
// An unknown (or another sandbox's) handler, e.g. one a policy
|
||||
// update just removed: deny.
|
||||
let handler = handlers
|
||||
.get(request.handler)
|
||||
.filter(|(owner, _)| *owner == request.sandbox);
|
||||
let Some((_, handler)) = handler else {
|
||||
let reply = ZedMessage::PromptReply {
|
||||
prompt: request.prompt,
|
||||
allow: false,
|
||||
remember: Vec::new(),
|
||||
};
|
||||
if let Err(error) = protocol::send_message(control.as_fd(), &reply, &[]) {
|
||||
eprintln!("zed sandbox: answering prompt failed: {error:#}");
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let responder = Responder {
|
||||
prompt: request.prompt,
|
||||
sandbox: request.sandbox,
|
||||
handlers: handlers.clone(),
|
||||
control: control.clone(),
|
||||
cancelled: handlers.track_prompt(request.prompt),
|
||||
answered: false,
|
||||
};
|
||||
let access_request = AccessRequest {
|
||||
items: request.requests,
|
||||
pid: request.pid,
|
||||
executable: request.executable,
|
||||
};
|
||||
// A panicking handler drops the responder while unwinding,
|
||||
// which denies; keep this thread alive for everyone else.
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
(handler.0)(access_request, responder)
|
||||
}));
|
||||
if result.is_err() {
|
||||
eprintln!("zed sandbox: an access handler panicked; denying");
|
||||
}
|
||||
}
|
||||
SupervisorMessage::PromptCancelled { prompt } => handlers.cancel_prompt(prompt),
|
||||
SupervisorMessage::Denied { sandbox, denial } => {
|
||||
if let Some(handler) = handlers.denial_handler(sandbox) {
|
||||
let result =
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handler(denial)));
|
||||
if result.is_err() {
|
||||
eprintln!("zed sandbox: a denial handler panicked");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Fail anyone still waiting for a response.
|
||||
if let Ok(mut pending) = pending.lock() {
|
||||
pending.clear();
|
||||
}
|
||||
handlers.cancel_all_prompts();
|
||||
}
|
||||
|
||||
impl ContextInner {
|
||||
fn call(&self, request: Request, fds: &[RawFd]) -> Result<Response> {
|
||||
let id = self.next_request.fetch_add(1, Ordering::Relaxed);
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
self.pending
|
||||
.lock()
|
||||
.map_err(|_| anyhow!("sandbox state poisoned"))?
|
||||
.insert(id, sender);
|
||||
protocol::send_message(
|
||||
self.control.as_fd(),
|
||||
&ZedMessage::Request { id, request },
|
||||
fds,
|
||||
)?;
|
||||
match receiver.recv().context("sandbox supervisor exited")? {
|
||||
Response::Error { message } => Err(anyhow!(message)),
|
||||
response => Ok(response),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ContextInner {
|
||||
fn drop(&mut self) {
|
||||
// The supervisor exits on EOF. Shut down rather than close: the
|
||||
// control thread (and any unanswered prompt) shares the socket.
|
||||
// SAFETY: shutdown on a socket we own.
|
||||
unsafe { libc::shutdown(self.control.as_raw_fd(), libc::SHUT_WR) };
|
||||
if let Ok(mut supervisor) = self.supervisor.lock()
|
||||
&& let Err(error) = supervisor.wait()
|
||||
{
|
||||
eprintln!("zed sandbox: waiting for supervisor failed: {error}");
|
||||
}
|
||||
if let Some(reader) = self.reader.lock().ok().and_then(|mut reader| reader.take()) {
|
||||
reader.join().ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A policy registered with the supervisor. Commands run in it share the
|
||||
/// policy (and its updates), but each gets its own namespaces.
|
||||
///
|
||||
/// Each sandbox has a private temporary directory, passed to commands as
|
||||
/// `TMPDIR` and usable (read, write, connect) regardless of the policy.
|
||||
/// Device files commands commonly need (`/dev/null`, terminals, ...) are readable and writable
|
||||
/// unless the policy says otherwise.
|
||||
pub struct Sandbox {
|
||||
context: Arc<ContextInner>,
|
||||
id: SandboxId,
|
||||
temp_dir: PathBuf,
|
||||
/// Whether the supervisor knows about this sandbox.
|
||||
created: bool,
|
||||
}
|
||||
|
||||
/// Device files a sandbox may use unless its policy overrides them.
|
||||
const DEFAULT_DEVICES: [&str; 8] = [
|
||||
"/dev/null",
|
||||
"/dev/zero",
|
||||
"/dev/full",
|
||||
"/dev/random",
|
||||
"/dev/urandom",
|
||||
"/dev/tty",
|
||||
"/dev/ptmx",
|
||||
"/dev/pts",
|
||||
];
|
||||
|
||||
impl Sandbox {
|
||||
pub fn temp_dir(&self) -> &Path {
|
||||
&self.temp_dir
|
||||
}
|
||||
|
||||
/// Call `handler` whenever the policy, or an [`Access::Ask`] handler,
|
||||
/// denies an operation in this sandbox (after the syscall has failed).
|
||||
/// Like handlers, it runs on a background thread shared by every
|
||||
/// sandbox in the context and must return promptly. Replaces any
|
||||
/// previous one.
|
||||
pub fn on_denial(&self, handler: impl Fn(Denial) + Send + Sync + 'static) {
|
||||
self.context
|
||||
.handlers
|
||||
.state()
|
||||
.denial_handlers
|
||||
.insert(self.id, Arc::new(handler));
|
||||
}
|
||||
|
||||
/// Replace the policy, including any rules handlers asked to remember.
|
||||
/// Applies to every operation from now on, including in commands already
|
||||
/// running; descriptors they already hold keep working, and are returned
|
||||
/// if the new policy wouldn't grant them.
|
||||
pub fn update_policy(&self, policy: &SandboxPolicy) -> Result<Vec<OpenFile>> {
|
||||
let policy = self.to_wire(policy)?;
|
||||
let request = Request::UpdatePolicy {
|
||||
sandbox: self.id,
|
||||
policy,
|
||||
};
|
||||
let still_open = match self.context.call(request, &[])? {
|
||||
Response::PolicyUpdated { still_open } => still_open,
|
||||
other => bail!("unexpected supervisor response: {other:?}"),
|
||||
};
|
||||
Ok(still_open)
|
||||
}
|
||||
|
||||
/// The policy as the supervisor enforces it, registering its handlers:
|
||||
/// default devices first (so the policy can override them), the
|
||||
/// temporary directory last (so it can't).
|
||||
///
|
||||
/// Handlers no longer referenced are dropped, which denies any prompt
|
||||
/// still waiting on them.
|
||||
fn to_wire(&self, policy: &SandboxPolicy) -> Result<WirePolicy> {
|
||||
let handlers = &self.context.handlers;
|
||||
let mut used = HashSet::new();
|
||||
let mut register = |handler: &Handler| {
|
||||
let id = handlers.register(self.id, handler);
|
||||
used.insert(id);
|
||||
id
|
||||
};
|
||||
let allow_all = |path: PathPattern| WireFsRule {
|
||||
path,
|
||||
read: Some(WireAccess::Allow),
|
||||
write: Some(WireAccess::Allow),
|
||||
connect: Some(WireAccess::Allow),
|
||||
};
|
||||
let mut fs = Vec::with_capacity(policy.fs.len() + DEFAULT_DEVICES.len() + 1);
|
||||
for device in DEFAULT_DEVICES {
|
||||
fs.push(allow_all(PathPattern::new(device)?));
|
||||
}
|
||||
fs.extend(policy.fs.iter().map(|rule| rule.to_wire(&mut register)));
|
||||
fs.push(allow_all(PathPattern::literal(&self.temp_dir)?));
|
||||
let net = policy
|
||||
.net
|
||||
.iter()
|
||||
.map(|rule| rule.to_wire(&mut register))
|
||||
.collect();
|
||||
handlers.retain(self.id, &used);
|
||||
Ok(WirePolicy { fs, net })
|
||||
}
|
||||
|
||||
/// Spawn `command` in this sandbox with inherited stdio.
|
||||
pub fn execute(&self, command: &UntrustedCommand) -> Result<Child> {
|
||||
Ok(self.prepare(command)?.spawn()?)
|
||||
}
|
||||
|
||||
/// Prepare `command` without spawning it. The supervisor is told about
|
||||
/// the execution now; if it's never spawned, the supervisor forgets it
|
||||
/// once the returned value is dropped.
|
||||
pub fn prepare(&self, command: &UntrustedCommand) -> Result<SandboxedCommand> {
|
||||
// The helper hands its seccomp listener to the supervisor over this
|
||||
// pair; the supervisor learns which sandbox it belongs to from the
|
||||
// request that delivered the other end.
|
||||
let (supervisor_end, helper_attach) = seqpacket_pair()?;
|
||||
self.context.call(
|
||||
Request::AttachExecution { sandbox: self.id },
|
||||
&[supervisor_end.as_raw_fd()],
|
||||
)?;
|
||||
drop(supervisor_end);
|
||||
|
||||
let mut command = command.clone();
|
||||
command.env.insert(
|
||||
"TMPDIR".to_string(),
|
||||
self.temp_dir.to_string_lossy().into_owned(),
|
||||
);
|
||||
// The setup message sits in the socket buffer until the helper reads
|
||||
// it, so it can be sent before spawning.
|
||||
let (zed_setup, helper_setup) = seqpacket_pair()?;
|
||||
protocol::send_message(zed_setup.as_fd(), &HelperSetup { command }, &[])?;
|
||||
drop(zed_setup);
|
||||
|
||||
let mut process = Command::new(&self.context.executable);
|
||||
process.arg(helper::HELPER_FLAG);
|
||||
let child_fds = inherit_fds(
|
||||
&mut process,
|
||||
&[
|
||||
(helper_setup, helper::SETUP_FD),
|
||||
(helper_attach, helper::ATTACH_FD),
|
||||
],
|
||||
)?;
|
||||
Ok(SandboxedCommand {
|
||||
command: process,
|
||||
_child_fds: child_fds,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Sandbox {
|
||||
fn drop(&mut self) {
|
||||
self.context.handlers.retain(self.id, &HashSet::new());
|
||||
if self.created
|
||||
&& let Err(error) = self
|
||||
.context
|
||||
.call(Request::DestroySandbox { sandbox: self.id }, &[])
|
||||
{
|
||||
eprintln!("zed sandbox: destroying sandbox failed: {error:#}");
|
||||
}
|
||||
// Only now: the destroy round trip went through the control thread
|
||||
// after every denial the supervisor sent before it, so all of them
|
||||
// have been delivered.
|
||||
self.context
|
||||
.handlers
|
||||
.state()
|
||||
.denial_handlers
|
||||
.remove(&self.id);
|
||||
if let Err(error) = std::fs::remove_dir_all(&self.temp_dir) {
|
||||
eprintln!(
|
||||
"zed sandbox: removing {} failed: {error}",
|
||||
self.temp_dir.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A sandboxed command that hasn't been spawned yet. Configure stdio through
|
||||
/// [`SandboxedCommand::command_mut`]; don't change its program or arguments.
|
||||
pub struct SandboxedCommand {
|
||||
command: Command,
|
||||
_child_fds: Vec<OwnedFd>,
|
||||
}
|
||||
|
||||
impl SandboxedCommand {
|
||||
pub fn command_mut(&mut self) -> &mut Command {
|
||||
&mut self.command
|
||||
}
|
||||
|
||||
#[allow(
|
||||
clippy::disallowed_methods,
|
||||
reason = "PoC: blocking spawn; callers must stay off the UI thread"
|
||||
)]
|
||||
pub fn spawn(mut self) -> std::io::Result<Child> {
|
||||
self.command.spawn()
|
||||
}
|
||||
|
||||
#[allow(
|
||||
clippy::disallowed_methods,
|
||||
reason = "PoC: blocking spawn; callers must stay off the UI thread"
|
||||
)]
|
||||
pub fn output(mut self) -> std::io::Result<Output> {
|
||||
self.command.output()
|
||||
}
|
||||
}
|
||||
|
||||
fn create_temp_dir() -> Result<PathBuf> {
|
||||
use std::os::unix::fs::DirBuilderExt as _;
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let base = std::env::temp_dir()
|
||||
.canonicalize()
|
||||
.context("resolving the temporary directory")?;
|
||||
let nanos = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |elapsed| elapsed.subsec_nanos());
|
||||
let path = base.join(format!(
|
||||
"zed-sandbox-{}-{}-{nanos}",
|
||||
std::process::id(),
|
||||
COUNTER.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
std::fs::DirBuilder::new()
|
||||
.mode(0o700)
|
||||
.create(&path)
|
||||
.with_context(|| format!("creating {}", path.display()))?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn seqpacket_pair() -> Result<(OwnedFd, OwnedFd)> {
|
||||
socketpair(
|
||||
AddressFamily::Unix,
|
||||
SockType::SeqPacket,
|
||||
None,
|
||||
SockFlag::SOCK_CLOEXEC,
|
||||
)
|
||||
.context("creating sandbox socketpair")
|
||||
}
|
||||
|
||||
/// Arrange for each `(fd, number)` to be inherited by `command` at `number`.
|
||||
/// Returns the descriptors the caller must keep open until spawning.
|
||||
fn inherit_fds(command: &mut Command, fds: &[(OwnedFd, RawFd)]) -> Result<Vec<OwnedFd>> {
|
||||
// Move every source above the target range first, so one `dup2` can't
|
||||
// clobber another source.
|
||||
let mut moved = Vec::new();
|
||||
let mut mapping = Vec::new();
|
||||
for (fd, number) in fds {
|
||||
let high = sys::duplicate_above(fd.as_fd(), 64)?;
|
||||
mapping.push((high.as_raw_fd(), *number));
|
||||
moved.push(high);
|
||||
}
|
||||
// SAFETY: only async-signal-safe `dup2` calls between fork and exec.
|
||||
unsafe {
|
||||
command.pre_exec(move || {
|
||||
for (source, target) in &mapping {
|
||||
// `dup2` leaves the new descriptor without CLOEXEC.
|
||||
sys::cvt(libc::dup2(*source, *target))?;
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
Ok(moved)
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
//! The seccomp filter installed on the untrusted command.
|
||||
//!
|
||||
//! It sends to the supervisor (`SECCOMP_RET_USER_NOTIF`):
|
||||
//! - every open except `O_PATH` (read rules need the supervisor to decide);
|
||||
//! - write-intent filesystem syscalls, decided from register arguments;
|
||||
//! - syscalls that act on another process by pid;
|
||||
//! - `connect` and `bind`.
|
||||
//!
|
||||
//! It denies syscalls the sandbox never needs (non-IP sockets, new user
|
||||
//! namespaces, io_uring, ptrace, ...) and returns `ENOSYS` for every syscall
|
||||
//! newer than the ones listed here, so a future kernel's additions are
|
||||
//! unavailable rather than unreviewed.
|
||||
|
||||
use std::io;
|
||||
use std::os::fd::{FromRawFd as _, OwnedFd, RawFd};
|
||||
|
||||
use crate::sys::cvt;
|
||||
|
||||
const SECCOMP_FILTER_FLAG_NEW_LISTENER: libc::c_ulong = 1 << 3;
|
||||
const SECCOMP_FILTER_FLAG_WAIT_KILLABLE_RECV: libc::c_ulong = 1 << 5;
|
||||
const SECCOMP_RET_USER_NOTIF: u32 = 0x7fc0_0000;
|
||||
const SECCOMP_RET_KILL_PROCESS: u32 = 0x8000_0000;
|
||||
|
||||
// Syscalls added after the per-arch tables were unified share one number.
|
||||
const SYS_PIDFD_OPEN: i64 = 434;
|
||||
const SYS_CLONE3: i64 = 435;
|
||||
const SYS_OPENAT2: i64 = 437;
|
||||
const SYS_FACCESSAT2: i64 = 439;
|
||||
const SYS_PROCESS_MADVISE: i64 = 440;
|
||||
const SYS_FCHMODAT2: i64 = 452;
|
||||
/// The first syscall number this filter hasn't been reviewed against
|
||||
/// (`setxattrat`, Linux 6.13).
|
||||
const FIRST_UNREVIEWED_SYSCALL: u32 = 463;
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
const AUDIT_ARCH: u32 = 0xc000_003e;
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const AUDIT_ARCH: u32 = 0xc000_00b7;
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
const X32_SYSCALL_BIT: u32 = 0x4000_0000;
|
||||
|
||||
/// The syscalls the supervisor handles. Anything else that writes (e.g.
|
||||
/// `fchownat`, `setxattr`, `mknodat`) isn't trapped yet and fails against the
|
||||
/// read-only mounts. TODO: broker every write-capable path syscall.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Brokered {
|
||||
OpenAt,
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
Open,
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
Creat,
|
||||
MkdirAt,
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
Mkdir,
|
||||
UnlinkAt,
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
Unlink,
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
Rmdir,
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
RenameAt,
|
||||
RenameAt2,
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
Rename,
|
||||
LinkAt,
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
Link,
|
||||
SymlinkAt,
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
Symlink,
|
||||
FchmodAt,
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
Chmod,
|
||||
Truncate,
|
||||
FaccessAt,
|
||||
FaccessAt2,
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
Access,
|
||||
UtimensAt,
|
||||
Kill,
|
||||
Tkill,
|
||||
Tgkill,
|
||||
RtSigqueueinfo,
|
||||
RtTgsigqueueinfo,
|
||||
PidfdOpen,
|
||||
// Argument 0 is a pid, with 0 meaning the caller.
|
||||
Prlimit64,
|
||||
SchedSetaffinity,
|
||||
SchedSetscheduler,
|
||||
SchedSetparam,
|
||||
SchedSetattr,
|
||||
Setpriority,
|
||||
IoprioSet,
|
||||
Connect,
|
||||
Bind,
|
||||
}
|
||||
|
||||
/// What the filter does with one syscall number.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Action {
|
||||
Return(u32),
|
||||
/// Do `matched` if argument `arg`, masked with `mask`, equals one of
|
||||
/// `values`, else do `otherwise`.
|
||||
ArgumentIn {
|
||||
arg: usize,
|
||||
mask: u32,
|
||||
values: &'static [u32],
|
||||
matched: &'static Action,
|
||||
otherwise: &'static Action,
|
||||
},
|
||||
/// Return `set` if argument `arg` has any bit of `mask` set.
|
||||
ArgumentHasBits {
|
||||
arg: usize,
|
||||
mask: u32,
|
||||
set: u32,
|
||||
clear: u32,
|
||||
},
|
||||
/// Return `non_null` if the 64-bit argument `arg` is non-zero.
|
||||
ArgumentNonNull {
|
||||
arg: usize,
|
||||
non_null: u32,
|
||||
null: u32,
|
||||
},
|
||||
}
|
||||
|
||||
const ALLOW: u32 = libc::SECCOMP_RET_ALLOW;
|
||||
const NOTIFY: u32 = SECCOMP_RET_USER_NOTIF;
|
||||
|
||||
const fn errno(code: i32) -> u32 {
|
||||
libc::SECCOMP_RET_ERRNO | (code as u32 & libc::SECCOMP_RET_DATA)
|
||||
}
|
||||
|
||||
/// `O_PATH` opens grant no access to contents; every other open is brokered.
|
||||
const fn opens_contents(arg: usize) -> Action {
|
||||
Action::ArgumentHasBits {
|
||||
arg,
|
||||
mask: libc::O_PATH as u32,
|
||||
set: ALLOW,
|
||||
clear: NOTIFY,
|
||||
}
|
||||
}
|
||||
|
||||
const fn checks_write_access(arg: usize) -> Action {
|
||||
Action::ArgumentHasBits {
|
||||
arg,
|
||||
mask: libc::W_OK as u32,
|
||||
set: NOTIFY,
|
||||
clear: ALLOW,
|
||||
}
|
||||
}
|
||||
|
||||
const ALWAYS_NOTIFY: Action = Action::Return(NOTIFY);
|
||||
|
||||
/// Syscalls the supervisor handles, with when to send them to it.
|
||||
const BROKERED: &[(i64, Brokered, Action)] = {
|
||||
use Brokered::*;
|
||||
let always = ALWAYS_NOTIFY;
|
||||
&[
|
||||
(libc::SYS_openat, OpenAt, opens_contents(2)),
|
||||
(libc::SYS_mkdirat, MkdirAt, always),
|
||||
(libc::SYS_unlinkat, UnlinkAt, always),
|
||||
(libc::SYS_renameat2, RenameAt2, always),
|
||||
(libc::SYS_linkat, LinkAt, always),
|
||||
(libc::SYS_symlinkat, SymlinkAt, always),
|
||||
(libc::SYS_fchmodat, FchmodAt, always),
|
||||
(libc::SYS_truncate, Truncate, always),
|
||||
(libc::SYS_faccessat, FaccessAt, checks_write_access(2)),
|
||||
(SYS_FACCESSAT2, FaccessAt2, checks_write_access(2)),
|
||||
// `utimensat(fd, NULL, ...)` is `futimens` on an already-open fd.
|
||||
(
|
||||
libc::SYS_utimensat,
|
||||
UtimensAt,
|
||||
Action::ArgumentNonNull {
|
||||
arg: 1,
|
||||
non_null: NOTIFY,
|
||||
null: ALLOW,
|
||||
},
|
||||
),
|
||||
(libc::SYS_kill, Kill, always),
|
||||
(libc::SYS_tkill, Tkill, always),
|
||||
(libc::SYS_tgkill, Tgkill, always),
|
||||
(libc::SYS_rt_sigqueueinfo, RtSigqueueinfo, always),
|
||||
(libc::SYS_rt_tgsigqueueinfo, RtTgsigqueueinfo, always),
|
||||
(SYS_PIDFD_OPEN, PidfdOpen, always),
|
||||
(libc::SYS_prlimit64, Prlimit64, always),
|
||||
(libc::SYS_sched_setaffinity, SchedSetaffinity, always),
|
||||
(libc::SYS_sched_setscheduler, SchedSetscheduler, always),
|
||||
(libc::SYS_sched_setparam, SchedSetparam, always),
|
||||
(libc::SYS_sched_setattr, SchedSetattr, always),
|
||||
(libc::SYS_setpriority, Setpriority, always),
|
||||
(libc::SYS_ioprio_set, IoprioSet, always),
|
||||
(libc::SYS_connect, Connect, always),
|
||||
(libc::SYS_bind, Bind, always),
|
||||
]
|
||||
};
|
||||
|
||||
/// The pre-`*at` path syscalls that only x86_64 still has.
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
const BROKERED_LEGACY: &[(i64, Brokered, Action)] = {
|
||||
use Brokered::*;
|
||||
let always = ALWAYS_NOTIFY;
|
||||
&[
|
||||
(libc::SYS_open, Open, opens_contents(1)),
|
||||
(libc::SYS_creat, Creat, always),
|
||||
(libc::SYS_mkdir, Mkdir, always),
|
||||
(libc::SYS_unlink, Unlink, always),
|
||||
(libc::SYS_rmdir, Rmdir, always),
|
||||
(libc::SYS_renameat, RenameAt, always),
|
||||
(libc::SYS_rename, Rename, always),
|
||||
(libc::SYS_link, Link, always),
|
||||
(libc::SYS_symlink, Symlink, always),
|
||||
(libc::SYS_chmod, Chmod, always),
|
||||
(libc::SYS_access, Access, checks_write_access(1)),
|
||||
]
|
||||
};
|
||||
|
||||
#[cfg(not(target_arch = "x86_64"))]
|
||||
const BROKERED_LEGACY: &[(i64, Brokered, Action)] = &[];
|
||||
|
||||
fn brokered_entries() -> impl Iterator<Item = &'static (i64, Brokered, Action)> {
|
||||
BROKERED.iter().chain(BROKERED_LEGACY)
|
||||
}
|
||||
|
||||
pub(crate) fn brokered_syscall(number: i64) -> Option<Brokered> {
|
||||
brokered_entries()
|
||||
.find_map(|&(candidate, brokered, _)| (candidate == number).then_some(brokered))
|
||||
}
|
||||
|
||||
const DENIED_WITH_EPERM: Action = Action::Return(errno(libc::EPERM));
|
||||
const DENIED_WITH_ENOSYS: Action = Action::Return(errno(libc::ENOSYS));
|
||||
|
||||
/// Syscalls the sandbox never needs, with how they're refused.
|
||||
const DENIED: &[(i64, Action)] = {
|
||||
const IP_FAMILIES: &[u32] = &[
|
||||
libc::AF_INET as u32,
|
||||
libc::AF_INET6 as u32,
|
||||
libc::AF_NETLINK as u32,
|
||||
];
|
||||
const UNIX_FAMILY: &[u32] = &[libc::AF_UNIX as u32];
|
||||
const ICMP_PROTOCOLS: &[u32] = &[libc::IPPROTO_ICMP as u32, libc::IPPROTO_ICMPV6 as u32];
|
||||
const DATAGRAM: &[u32] = &[libc::SOCK_DGRAM as u32];
|
||||
/// The type argument without `SOCK_NONBLOCK` / `SOCK_CLOEXEC`.
|
||||
const SOCKET_TYPE_MASK: u32 = 0xf;
|
||||
const ALLOWED: &Action = &Action::Return(ALLOW);
|
||||
const REFUSED: &Action = &DENIED_WITH_EPERM;
|
||||
// A datagram unix socket can send to any socket by path with
|
||||
// `sendmsg`, whose address sits behind a pointer; trapping every
|
||||
// `sendmsg` would slow all UDP. Stream and seqpacket sockets only reach
|
||||
// a path through `connect`, which is brokered.
|
||||
const UNIX_UNLESS_DATAGRAM: &Action = &Action::ArgumentIn {
|
||||
arg: 1,
|
||||
mask: SOCKET_TYPE_MASK,
|
||||
values: DATAGRAM,
|
||||
matched: REFUSED,
|
||||
otherwise: ALLOWED,
|
||||
};
|
||||
const NEW_USER_NAMESPACE: Action = Action::ArgumentHasBits {
|
||||
arg: 0,
|
||||
mask: libc::CLONE_NEWUSER as u32,
|
||||
set: errno(libc::EPERM),
|
||||
clear: ALLOW,
|
||||
};
|
||||
&[
|
||||
(
|
||||
libc::SYS_socket,
|
||||
Action::ArgumentIn {
|
||||
// Ping sockets: every address is local in the sandbox, so
|
||||
// every ping would get an answer.
|
||||
arg: 2,
|
||||
mask: u32::MAX,
|
||||
values: ICMP_PROTOCOLS,
|
||||
matched: &Action::Return(errno(libc::EACCES)),
|
||||
otherwise: &Action::ArgumentIn {
|
||||
arg: 0,
|
||||
mask: u32::MAX,
|
||||
values: IP_FAMILIES,
|
||||
matched: ALLOWED,
|
||||
otherwise: &Action::ArgumentIn {
|
||||
arg: 0,
|
||||
mask: u32::MAX,
|
||||
values: UNIX_FAMILY,
|
||||
matched: UNIX_UNLESS_DATAGRAM,
|
||||
otherwise: REFUSED,
|
||||
},
|
||||
},
|
||||
},
|
||||
),
|
||||
(
|
||||
libc::SYS_socketpair,
|
||||
Action::ArgumentIn {
|
||||
arg: 0,
|
||||
mask: u32::MAX,
|
||||
values: UNIX_FAMILY,
|
||||
matched: UNIX_UNLESS_DATAGRAM,
|
||||
otherwise: REFUSED,
|
||||
},
|
||||
),
|
||||
// A nested user namespace could mount, creating new names for files
|
||||
// the read rules deny.
|
||||
(libc::SYS_unshare, NEW_USER_NAMESPACE),
|
||||
(libc::SYS_clone, NEW_USER_NAMESPACE),
|
||||
// Flags live behind a pointer; libc falls back to `clone`.
|
||||
(SYS_CLONE3, DENIED_WITH_ENOSYS),
|
||||
// Flags/modes live behind pointers; libc falls back to `openat` /
|
||||
// `fchmodat`, which we can inspect.
|
||||
(SYS_OPENAT2, DENIED_WITH_ENOSYS),
|
||||
(SYS_FCHMODAT2, DENIED_WITH_ENOSYS),
|
||||
(libc::SYS_io_uring_setup, DENIED_WITH_EPERM),
|
||||
(libc::SYS_io_uring_enter, DENIED_WITH_EPERM),
|
||||
(libc::SYS_io_uring_register, DENIED_WITH_EPERM),
|
||||
(libc::SYS_ptrace, DENIED_WITH_EPERM),
|
||||
(libc::SYS_process_vm_readv, DENIED_WITH_EPERM),
|
||||
(libc::SYS_process_vm_writev, DENIED_WITH_EPERM),
|
||||
(libc::SYS_setns, DENIED_WITH_EPERM),
|
||||
(libc::SYS_perf_event_open, DENIED_WITH_EPERM),
|
||||
(libc::SYS_kcmp, DENIED_WITH_EPERM),
|
||||
(libc::SYS_migrate_pages, DENIED_WITH_EPERM),
|
||||
(libc::SYS_move_pages, DENIED_WITH_EPERM),
|
||||
(SYS_PROCESS_MADVISE, DENIED_WITH_EPERM),
|
||||
]
|
||||
};
|
||||
|
||||
fn statement(code: u32, k: u32) -> libc::sock_filter {
|
||||
libc::sock_filter {
|
||||
code: code as u16,
|
||||
jt: 0,
|
||||
jf: 0,
|
||||
k,
|
||||
}
|
||||
}
|
||||
|
||||
fn jump(code: u32, k: u32, jt: u8, jf: u8) -> libc::sock_filter {
|
||||
libc::sock_filter {
|
||||
code: code as u16,
|
||||
jt,
|
||||
jf,
|
||||
k,
|
||||
}
|
||||
}
|
||||
|
||||
// Classic BPF opcodes. The filter is a tiny program over one register (the
|
||||
// accumulator); each opcode ORs together an instruction class, an operand
|
||||
// size and an addressing mode.
|
||||
|
||||
/// `A = *(u32 *)(seccomp_data + k)`: load a 32-bit field of the syscall.
|
||||
const LOAD_OPCODE: u32 = libc::BPF_LD | libc::BPF_W | libc::BPF_ABS;
|
||||
/// `if A == k` jump `jt` instructions forward, else `jf`.
|
||||
const JUMP_EQUAL_OPCODE: u32 = libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K;
|
||||
/// `if A >= k` (unsigned) jump `jt`, else `jf`.
|
||||
const JUMP_AT_LEAST_OPCODE: u32 = libc::BPF_JMP | libc::BPF_JGE | libc::BPF_K;
|
||||
/// `if A & k != 0` jump `jt`, else `jf`.
|
||||
const JUMP_ANY_BITS_OPCODE: u32 = libc::BPF_JMP | libc::BPF_JSET | libc::BPF_K;
|
||||
/// `A &= k`.
|
||||
const AND_OPCODE: u32 = libc::BPF_ALU | libc::BPF_AND | libc::BPF_K;
|
||||
/// Stop and return `k`: the seccomp verdict (allow, errno, notify, kill).
|
||||
const RETURN_OPCODE: u32 = libc::BPF_RET | libc::BPF_K;
|
||||
|
||||
// Field offsets in `struct seccomp_data` (the program's input).
|
||||
const NR_OFFSET: u32 = 0;
|
||||
const ARCH_OFFSET: u32 = 4;
|
||||
|
||||
/// Offset of the low 32 bits of argument `index` in `seccomp_data` (both
|
||||
/// supported architectures are little-endian).
|
||||
fn argument_offset(index: usize) -> u32 {
|
||||
16 + 8 * index as u32
|
||||
}
|
||||
|
||||
fn compile_action(action: Action) -> Vec<libc::sock_filter> {
|
||||
match action {
|
||||
Action::Return(value) => vec![statement(RETURN_OPCODE, value)],
|
||||
Action::ArgumentIn {
|
||||
arg,
|
||||
mask,
|
||||
values,
|
||||
matched,
|
||||
otherwise,
|
||||
} => {
|
||||
// Comparisons, then `otherwise` (reached by falling through
|
||||
// them all), then `matched`. Both end in a return.
|
||||
let otherwise = compile_action(*otherwise);
|
||||
let mut program = vec![statement(LOAD_OPCODE, argument_offset(arg))];
|
||||
if mask != u32::MAX {
|
||||
program.push(statement(AND_OPCODE, mask));
|
||||
}
|
||||
let count = values.len();
|
||||
for (index, value) in values.iter().enumerate() {
|
||||
// Jump over the remaining comparisons and `otherwise`.
|
||||
let skip = count - index - 1 + otherwise.len();
|
||||
program.push(jump(JUMP_EQUAL_OPCODE, *value, skip as u8, 0));
|
||||
}
|
||||
program.extend(otherwise);
|
||||
program.extend(compile_action(*matched));
|
||||
program
|
||||
}
|
||||
Action::ArgumentHasBits {
|
||||
arg,
|
||||
mask,
|
||||
set,
|
||||
clear,
|
||||
} => vec![
|
||||
statement(LOAD_OPCODE, argument_offset(arg)),
|
||||
jump(JUMP_ANY_BITS_OPCODE, mask, 0, 1),
|
||||
statement(RETURN_OPCODE, set),
|
||||
statement(RETURN_OPCODE, clear),
|
||||
],
|
||||
Action::ArgumentNonNull {
|
||||
arg,
|
||||
non_null,
|
||||
null,
|
||||
} => vec![
|
||||
statement(LOAD_OPCODE, argument_offset(arg)),
|
||||
jump(JUMP_EQUAL_OPCODE, 0, 0, 2),
|
||||
statement(LOAD_OPCODE, argument_offset(arg) + 4),
|
||||
jump(JUMP_EQUAL_OPCODE, 0, 1, 0),
|
||||
statement(RETURN_OPCODE, non_null),
|
||||
statement(RETURN_OPCODE, null),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn build_filter() -> Vec<libc::sock_filter> {
|
||||
let mut program = vec![
|
||||
statement(LOAD_OPCODE, ARCH_OFFSET),
|
||||
jump(JUMP_EQUAL_OPCODE, AUDIT_ARCH, 1, 0),
|
||||
statement(RETURN_OPCODE, SECCOMP_RET_KILL_PROCESS),
|
||||
statement(LOAD_OPCODE, NR_OFFSET),
|
||||
];
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
program.extend([
|
||||
jump(JUMP_ANY_BITS_OPCODE, X32_SYSCALL_BIT, 0, 1),
|
||||
statement(RETURN_OPCODE, SECCOMP_RET_KILL_PROCESS),
|
||||
]);
|
||||
program.extend([
|
||||
jump(JUMP_AT_LEAST_OPCODE, FIRST_UNREVIEWED_SYSCALL, 0, 1),
|
||||
statement(RETURN_OPCODE, errno(libc::ENOSYS)),
|
||||
]);
|
||||
|
||||
let entries = DENIED
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(brokered_entries().map(|&(number, _, action)| (number, action)));
|
||||
for (number, action) in entries {
|
||||
// Every compiled action ends in a return, so the accumulator (the
|
||||
// syscall number) is intact on the fall-through path.
|
||||
let body = compile_action(action);
|
||||
program.push(jump(JUMP_EQUAL_OPCODE, number as u32, 0, body.len() as u8));
|
||||
program.extend(body);
|
||||
}
|
||||
program.push(statement(RETURN_OPCODE, ALLOW));
|
||||
program
|
||||
}
|
||||
|
||||
/// Install `filter` on the calling thread and return the listener fd. Called
|
||||
/// after `fork`, before `exec`.
|
||||
pub(crate) fn install(filter: &[libc::sock_filter]) -> io::Result<OwnedFd> {
|
||||
let program = libc::sock_fprog {
|
||||
len: filter.len() as u16,
|
||||
filter: filter.as_ptr().cast_mut(),
|
||||
};
|
||||
// SAFETY: plain prctl.
|
||||
cvt(unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) })?;
|
||||
let install = |flags: libc::c_ulong| {
|
||||
// SAFETY: `program` points at `filter`, which outlives the call.
|
||||
unsafe {
|
||||
libc::syscall(
|
||||
libc::SYS_seccomp,
|
||||
libc::SECCOMP_SET_MODE_FILTER,
|
||||
flags,
|
||||
&program as *const libc::sock_fprog,
|
||||
)
|
||||
}
|
||||
};
|
||||
// WAIT_KILLABLE_RECV (5.19): once the supervisor has picked up a
|
||||
// notification, only a fatal signal can interrupt it. Otherwise a signal
|
||||
// (e.g. Go's SIGURG preemption) arriving while we perform a mkdir or
|
||||
// rename, or while a prompt is open, makes the target retry it.
|
||||
let mut listener =
|
||||
install(SECCOMP_FILTER_FLAG_NEW_LISTENER | SECCOMP_FILTER_FLAG_WAIT_KILLABLE_RECV);
|
||||
if listener < 0 && io::Error::last_os_error().raw_os_error() == Some(libc::EINVAL) {
|
||||
listener = install(SECCOMP_FILTER_FLAG_NEW_LISTENER);
|
||||
}
|
||||
if listener < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
// SAFETY: a freshly returned descriptor that nothing else owns.
|
||||
Ok(unsafe { OwnedFd::from_raw_fd(listener as RawFd) })
|
||||
}
|
||||
@@ -0,0 +1,657 @@
|
||||
//! The supervisor process (`zed --zed-sandbox-linux-supervisor`).
|
||||
//!
|
||||
//! One per [`SandboxContext`](crate::SandboxContext). The main thread polls:
|
||||
//! - the control socket from Zed ([`CONTROL_FD`]): requests, prompt replies;
|
||||
//! - pending attach sockets, each waiting for one helper's listener fd;
|
||||
//! - seccomp listeners, one per running execution, for when it ends.
|
||||
//!
|
||||
//! Each execution's notifications are received and handled by its own
|
||||
//! [`Receivers`].
|
||||
//!
|
||||
//! A notification can only arrive on the listener of the filter that trapped
|
||||
//! it, so the listener identifies the sandbox; nothing the sandboxed process
|
||||
//! sends can claim another identity.
|
||||
//!
|
||||
//! The process exits when Zed shuts down the control socket. Listeners close
|
||||
//! with it, after which every trapped syscall fails with `ENOSYS`.
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::os::fd::{AsFd as _, AsRawFd as _, BorrowedFd, OwnedFd, RawFd};
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex, OnceLock, RwLock, mpsc};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
|
||||
use crate::broker;
|
||||
use crate::dns;
|
||||
use crate::net::{self, Network};
|
||||
use crate::policy::{HandlerId, Permission, RequestedAccess, WireAccess, WirePolicy, WireRule};
|
||||
use crate::process::ProcessTree;
|
||||
use crate::protocol::{
|
||||
AttachInfo, Denial, OpenFile, PromptId, PromptRequest, Request, Response, SandboxId,
|
||||
SupervisorMessage, ZedMessage, receive_message, send_message,
|
||||
};
|
||||
use crate::sys;
|
||||
|
||||
pub(crate) const SUPERVISOR_FLAG: &str = "--zed-sandbox-linux-supervisor";
|
||||
pub(crate) const CONTROL_FD: RawFd = 3;
|
||||
|
||||
const PROMPT_TIMEOUT: Duration = Duration::from_secs(5 * 60);
|
||||
/// Per execution.
|
||||
const MAX_RECEIVERS: usize = 64;
|
||||
/// Idle receivers beyond this many exit.
|
||||
const SPARE_RECEIVERS: usize = 2;
|
||||
|
||||
// From <linux/seccomp.h>.
|
||||
const SECCOMP_IOCTL_NOTIF_SET_FLAGS: libc::c_ulong = 0x4008_2104;
|
||||
const SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP: libc::c_ulong = 1;
|
||||
|
||||
pub(crate) struct SandboxState {
|
||||
pub id: SandboxId,
|
||||
policy: RwLock<Arc<WirePolicy>>,
|
||||
pub names: Mutex<dns::Names>,
|
||||
}
|
||||
|
||||
impl SandboxState {
|
||||
pub fn policy(&self) -> Arc<WirePolicy> {
|
||||
match self.policy.read() {
|
||||
Ok(policy) => policy.clone(),
|
||||
Err(poisoned) => poisoned.into_inner().clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn modify_policy(&self, modify: impl FnOnce(&mut WirePolicy)) {
|
||||
let mut current = match self.policy.write() {
|
||||
Ok(current) => current,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
modify(Arc::make_mut(&mut current));
|
||||
}
|
||||
}
|
||||
|
||||
struct PromptReply {
|
||||
allow: bool,
|
||||
remember: Vec<WireRule>,
|
||||
}
|
||||
|
||||
/// One running command (and everything it spawns).
|
||||
pub(crate) struct Execution {
|
||||
pub listener: OwnedFd,
|
||||
pub sandbox: Arc<SandboxState>,
|
||||
pub tree: ProcessTree,
|
||||
pub network: Network,
|
||||
/// The root of its mount namespace, once opened.
|
||||
pub root: OnceLock<OwnedFd>,
|
||||
receivers: Receivers,
|
||||
}
|
||||
|
||||
/// The threads answering one execution's notifications, as leader and
|
||||
/// followers: one thread at a time waits on the listener, and once it
|
||||
/// receives a notification it leaves the waiting to another and handles the
|
||||
/// notification itself. Answering on the receiving thread saves a hand-off
|
||||
/// and lets the kernel wake it synchronously when the next notification
|
||||
/// arrives. Handling can block (a prompt, a FIFO, a slow filesystem), so a
|
||||
/// thread is added whenever none is left to wait.
|
||||
#[derive(Default)]
|
||||
struct Receivers {
|
||||
leader: Mutex<()>,
|
||||
/// Threads not handling a notification.
|
||||
idle: AtomicUsize,
|
||||
threads: AtomicUsize,
|
||||
}
|
||||
|
||||
fn start_receiver(shared: &Arc<Shared>, execution: &Arc<Execution>) {
|
||||
let receivers = &execution.receivers;
|
||||
if receivers.threads.fetch_add(1, Ordering::SeqCst) >= MAX_RECEIVERS {
|
||||
receivers.threads.fetch_sub(1, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
receivers.idle.fetch_add(1, Ordering::SeqCst);
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("zed-sandbox-receiver".to_string())
|
||||
.spawn({
|
||||
let shared = shared.clone();
|
||||
let execution = execution.clone();
|
||||
move || run_receiver(&shared, &execution)
|
||||
});
|
||||
if let Err(error) = spawned {
|
||||
receivers.threads.fetch_sub(1, Ordering::SeqCst);
|
||||
receivers.idle.fetch_sub(1, Ordering::SeqCst);
|
||||
eprintln!("zed sandbox supervisor: starting a receiver: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
fn run_receiver(shared: &Arc<Shared>, execution: &Arc<Execution>) {
|
||||
let receivers = &execution.receivers;
|
||||
let exit = || {
|
||||
receivers.idle.fetch_sub(1, Ordering::SeqCst);
|
||||
receivers.threads.fetch_sub(1, Ordering::SeqCst);
|
||||
};
|
||||
loop {
|
||||
let notification = {
|
||||
let _leader = net::lock(&receivers.leader);
|
||||
loop {
|
||||
let mut entry = poll_fd(execution.listener.as_raw_fd());
|
||||
// SAFETY: one valid pollfd.
|
||||
let ready = unsafe { libc::poll(&mut entry, 1, -1) };
|
||||
if ready < 0 {
|
||||
if std::io::Error::last_os_error().raw_os_error() == Some(libc::EINTR) {
|
||||
continue;
|
||||
}
|
||||
return exit();
|
||||
}
|
||||
if entry.revents & libc::POLLIN != 0 {
|
||||
if let Some(notification) = broker::receive(execution.listener.as_fd()) {
|
||||
break notification;
|
||||
}
|
||||
} else if entry.revents & (libc::POLLHUP | libc::POLLERR | libc::POLLNVAL) != 0 {
|
||||
// Every task under this filter has exited.
|
||||
return exit();
|
||||
}
|
||||
}
|
||||
};
|
||||
if receivers.idle.fetch_sub(1, Ordering::SeqCst) == 1 {
|
||||
start_receiver(shared, execution);
|
||||
}
|
||||
broker::handle(shared, execution, notification);
|
||||
if receivers.idle.fetch_add(1, Ordering::SeqCst) >= SPARE_RECEIVERS {
|
||||
return exit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`Shared::ask`] concluded.
|
||||
pub(crate) enum AskOutcome {
|
||||
Decided(bool),
|
||||
/// Another prompt to the same handler finished while this one waited;
|
||||
/// re-evaluate the (possibly extended) policy before asking.
|
||||
Retry,
|
||||
}
|
||||
|
||||
/// The prompts of one handler in one sandbox, shown one at a time.
|
||||
///
|
||||
/// While one is open, an identical request waits for and shares its
|
||||
/// decision; any other request waits for it to finish and then retries, so
|
||||
/// it sees rules the first one remembered.
|
||||
#[derive(Default)]
|
||||
struct PromptQueue {
|
||||
state: Mutex<PromptQueueState>,
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct PromptQueueState {
|
||||
open: Option<Vec<RequestedAccess>>,
|
||||
/// Number of prompts finished so far.
|
||||
finished: u64,
|
||||
/// Recent `(prompt number, requests, decision)`, for identical requests
|
||||
/// that waited on them.
|
||||
recent: VecDeque<(u64, Vec<RequestedAccess>, bool)>,
|
||||
}
|
||||
|
||||
const RECENT_DECISIONS: usize = 64;
|
||||
|
||||
impl PromptQueue {
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, PromptQueueState> {
|
||||
match self.state.lock() {
|
||||
Ok(state) => state,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// State workers share with the main thread.
|
||||
pub(crate) struct Shared {
|
||||
control: OwnedFd,
|
||||
prompts: Mutex<HashMap<PromptId, mpsc::Sender<PromptReply>>>,
|
||||
next_prompt: AtomicU64,
|
||||
queues: Mutex<HashMap<(SandboxId, HandlerId), Arc<PromptQueue>>>,
|
||||
host_root: OwnedFd,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
/// `/`, opened once.
|
||||
pub fn host_root(&self) -> BorrowedFd<'_> {
|
||||
self.host_root.as_fd()
|
||||
}
|
||||
|
||||
fn send(&self, message: &SupervisorMessage) {
|
||||
// SEQPACKET sends are atomic, so workers and the main thread can
|
||||
// share the socket.
|
||||
if let Err(error) = send_message(self.control.as_fd(), message, &[]) {
|
||||
eprintln!("zed sandbox supervisor: {error:#}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask Zed's `handler` whether to allow `requests`, through the
|
||||
/// handler's [`PromptQueue`]. Blocks until it answers, the prompt times
|
||||
/// out (deny), or the syscall is abandoned (`still_valid` turns false).
|
||||
/// Rules the handler asks to remember are added to the sandbox's policy
|
||||
/// before any waiting request wakes up.
|
||||
pub fn ask(
|
||||
&self,
|
||||
sandbox: &SandboxState,
|
||||
handler: HandlerId,
|
||||
requests: Vec<RequestedAccess>,
|
||||
tid: i32,
|
||||
still_valid: impl Fn() -> bool,
|
||||
) -> AskOutcome {
|
||||
let queue = match self.queues.lock() {
|
||||
Ok(mut queues) => queues.entry((sandbox.id, handler)).or_default().clone(),
|
||||
Err(_) => return AskOutcome::Decided(false),
|
||||
};
|
||||
let mut state = queue.lock();
|
||||
if let Some(open) = &state.open {
|
||||
let identical = *open == requests;
|
||||
let awaited = state.finished + 1;
|
||||
while state.finished < awaited {
|
||||
if !still_valid() {
|
||||
return AskOutcome::Decided(false);
|
||||
}
|
||||
state = match queue.changed.wait_timeout(state, Duration::from_secs(1)) {
|
||||
Ok((state, _)) => state,
|
||||
Err(poisoned) => poisoned.into_inner().0,
|
||||
};
|
||||
}
|
||||
let shared = state
|
||||
.recent
|
||||
.iter()
|
||||
.find(|(number, _, _)| *number == awaited)
|
||||
.filter(|(_, decided, _)| identical && *decided == requests)
|
||||
.map(|(_, _, allow)| *allow);
|
||||
return match shared {
|
||||
Some(allow) => AskOutcome::Decided(allow),
|
||||
None => AskOutcome::Retry,
|
||||
};
|
||||
}
|
||||
state.open = Some(requests.clone());
|
||||
drop(state);
|
||||
|
||||
let allow = self.prompt(sandbox, handler, requests.clone(), tid, still_valid);
|
||||
|
||||
let mut state = queue.lock();
|
||||
state.open = None;
|
||||
state.finished += 1;
|
||||
let number = state.finished;
|
||||
state.recent.push_back((number, requests, allow));
|
||||
if state.recent.len() > RECENT_DECISIONS {
|
||||
state.recent.pop_front();
|
||||
}
|
||||
queue.changed.notify_all();
|
||||
AskOutcome::Decided(allow)
|
||||
}
|
||||
|
||||
fn prompt(
|
||||
&self,
|
||||
sandbox: &SandboxState,
|
||||
handler: HandlerId,
|
||||
requests: Vec<RequestedAccess>,
|
||||
tid: i32,
|
||||
still_valid: impl Fn() -> bool,
|
||||
) -> bool {
|
||||
let prompt = self.next_prompt.fetch_add(1, Ordering::Relaxed);
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
if let Ok(mut prompts) = self.prompts.lock() {
|
||||
prompts.insert(prompt, sender);
|
||||
}
|
||||
self.send(&SupervisorMessage::Prompt(PromptRequest {
|
||||
prompt,
|
||||
sandbox: sandbox.id,
|
||||
handler,
|
||||
requests,
|
||||
pid: tid,
|
||||
executable: std::fs::read_link(format!("/proc/{tid}/exe")).ok(),
|
||||
}));
|
||||
let start = Instant::now();
|
||||
let decision = loop {
|
||||
match receiver.recv_timeout(Duration::from_secs(1)) {
|
||||
Ok(reply) => break Some(reply),
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {
|
||||
if !still_valid() || start.elapsed() > PROMPT_TIMEOUT {
|
||||
break None;
|
||||
}
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break None,
|
||||
}
|
||||
};
|
||||
if let Ok(mut prompts) = self.prompts.lock() {
|
||||
prompts.remove(&prompt);
|
||||
}
|
||||
let Some(reply) = decision else {
|
||||
self.send(&SupervisorMessage::PromptCancelled { prompt });
|
||||
return false;
|
||||
};
|
||||
if !reply.remember.is_empty() {
|
||||
sandbox.modify_policy(|policy| {
|
||||
for rule in reply.remember {
|
||||
policy.add(rule);
|
||||
}
|
||||
});
|
||||
}
|
||||
reply.allow
|
||||
}
|
||||
|
||||
/// Whether `request` is allowed, asking its handler if the policy says
|
||||
/// so. Denials are reported.
|
||||
pub fn authorize(
|
||||
&self,
|
||||
sandbox: &SandboxState,
|
||||
request: &RequestedAccess,
|
||||
tid: i32,
|
||||
still_valid: &dyn Fn() -> bool,
|
||||
) -> bool {
|
||||
let allowed = loop {
|
||||
match sandbox.policy().access(request) {
|
||||
WireAccess::Allow => break true,
|
||||
WireAccess::Deny => break false,
|
||||
WireAccess::Ask(handler) => {
|
||||
match self.ask(sandbox, handler, vec![request.clone()], tid, still_valid) {
|
||||
AskOutcome::Decided(allowed) => break allowed,
|
||||
// Re-check the policy, which may now decide.
|
||||
AskOutcome::Retry => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if !allowed {
|
||||
self.report_denial(sandbox.id, vec![request.clone()], tid);
|
||||
}
|
||||
allowed
|
||||
}
|
||||
|
||||
/// Tell Zed a policy rule (or a handler) denied an operation.
|
||||
pub fn report_denial(&self, sandbox: SandboxId, requests: Vec<RequestedAccess>, tid: i32) {
|
||||
self.send(&SupervisorMessage::Denied {
|
||||
sandbox,
|
||||
denial: Denial {
|
||||
requests,
|
||||
pid: tid,
|
||||
executable: std::fs::read_link(format!("/proc/{tid}/exe")).ok(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
fn reply(&self, prompt: PromptId, reply: PromptReply) {
|
||||
let sender = self
|
||||
.prompts
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut prompts| prompts.remove(&prompt));
|
||||
if let Some(sender) = sender {
|
||||
sender.send(reply).ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn run() -> ! {
|
||||
// Relays write to sockets whose peer may be gone: that's an error to
|
||||
// handle, not a reason to die.
|
||||
// SAFETY: plain signal disposition change.
|
||||
unsafe { libc::signal(libc::SIGPIPE, libc::SIG_IGN) };
|
||||
if let Err(error) = sys::set_parent_death_signal() {
|
||||
eprintln!("zed sandbox supervisor: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
// SAFETY: Zed spawns the supervisor with exactly this descriptor.
|
||||
let control = match unsafe { sys::inherited_fd(CONTROL_FD) } {
|
||||
Ok(control) => control,
|
||||
Err(error) => {
|
||||
eprintln!("zed sandbox supervisor: missing control socket: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
let host_root = match sys::open(Path::new("/"), libc::O_PATH | libc::O_DIRECTORY) {
|
||||
Ok(root) => root,
|
||||
Err(error) => {
|
||||
eprintln!("zed sandbox supervisor: opening /: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
let shared = Arc::new(Shared {
|
||||
control,
|
||||
prompts: Mutex::new(HashMap::new()),
|
||||
next_prompt: AtomicU64::new(0),
|
||||
queues: Mutex::new(HashMap::new()),
|
||||
host_root,
|
||||
});
|
||||
Supervisor {
|
||||
shared,
|
||||
sandboxes: HashMap::new(),
|
||||
pending: Vec::new(),
|
||||
executions: Vec::new(),
|
||||
}
|
||||
.run();
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
struct Supervisor {
|
||||
shared: Arc<Shared>,
|
||||
sandboxes: HashMap<SandboxId, Arc<SandboxState>>,
|
||||
/// Attach sockets whose helper hasn't sent its listener yet.
|
||||
pending: Vec<(OwnedFd, Arc<SandboxState>)>,
|
||||
/// Running executions. Each holds its own reference to its sandbox, so
|
||||
/// destroying a sandbox doesn't strand its commands.
|
||||
executions: Vec<Arc<Execution>>,
|
||||
}
|
||||
|
||||
impl Supervisor {
|
||||
fn run(&mut self) {
|
||||
loop {
|
||||
let mut poll_fds = vec![poll_fd(self.shared.control.as_raw_fd())];
|
||||
poll_fds.extend(self.pending.iter().map(|(fd, _)| poll_fd(fd.as_raw_fd())));
|
||||
// Only for hang-ups: receivers take the notifications.
|
||||
poll_fds.extend(self.executions.iter().map(|execution| libc::pollfd {
|
||||
fd: execution.listener.as_raw_fd(),
|
||||
events: 0,
|
||||
revents: 0,
|
||||
}));
|
||||
// SAFETY: a valid array of pollfds.
|
||||
let ready = unsafe { libc::poll(poll_fds.as_mut_ptr(), poll_fds.len() as _, -1) };
|
||||
if ready < 0 {
|
||||
let error = std::io::Error::last_os_error();
|
||||
if error.raw_os_error() == Some(libc::EINTR) {
|
||||
continue;
|
||||
}
|
||||
eprintln!("zed sandbox supervisor: poll failed: {error}");
|
||||
return;
|
||||
}
|
||||
|
||||
let pending_count = self.pending.len();
|
||||
let (control_ready, rest) = poll_fds.split_at(1);
|
||||
let (pending_ready, listeners_ready) = rest.split_at(pending_count);
|
||||
|
||||
// Walk backwards so removals don't shift indices still to visit.
|
||||
for (index, entry) in listeners_ready.iter().enumerate().rev() {
|
||||
if entry.revents & (libc::POLLHUP | libc::POLLERR | libc::POLLNVAL) != 0 {
|
||||
// Every task under this filter has exited.
|
||||
self.executions.swap_remove(index).network.close();
|
||||
}
|
||||
}
|
||||
for (index, entry) in pending_ready.iter().enumerate().rev() {
|
||||
if entry.revents == 0 {
|
||||
continue;
|
||||
}
|
||||
let (socket, sandbox) = self.pending.swap_remove(index);
|
||||
match receive_message::<AttachInfo>(socket.as_fd()) {
|
||||
Ok(Some((info, mut fds))) if !fds.is_empty() => {
|
||||
let listener = fds.remove(0);
|
||||
// Wake the receiver that answers on the target's
|
||||
// CPU right away (Linux 6.6). Older kernels refuse the
|
||||
// flag, which only costs that optimization.
|
||||
// SAFETY: SET_FLAGS takes the flags by value.
|
||||
unsafe {
|
||||
libc::ioctl(
|
||||
listener.as_raw_fd(),
|
||||
SECCOMP_IOCTL_NOTIF_SET_FLAGS as _,
|
||||
SECCOMP_USER_NOTIF_FD_SYNC_WAKE_UP,
|
||||
)
|
||||
};
|
||||
let execution = Arc::new(Execution {
|
||||
listener,
|
||||
sandbox,
|
||||
tree: ProcessTree {
|
||||
helper: info.helper_pid,
|
||||
},
|
||||
// From now on the helper serves socket requests
|
||||
// on the attach socket.
|
||||
network: Network::new(socket),
|
||||
root: OnceLock::new(),
|
||||
receivers: Receivers::default(),
|
||||
});
|
||||
start_receiver(&self.shared, &execution);
|
||||
net::start(&self.shared, &execution, fds);
|
||||
self.executions.push(execution);
|
||||
}
|
||||
// The helper exited (or misbehaved) before attaching. Its
|
||||
// command never ran, since it attaches before exec.
|
||||
Ok(_) => {}
|
||||
Err(error) => eprintln!("zed sandbox supervisor: attach failed: {error:#}"),
|
||||
}
|
||||
}
|
||||
if control_ready[0].revents != 0 && !self.handle_control() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle one control message. Returns `false` once Zed has gone away.
|
||||
fn handle_control(&mut self) -> bool {
|
||||
let (message, fds) = match receive_message::<ZedMessage>(self.shared.control.as_fd()) {
|
||||
Ok(Some(message)) => message,
|
||||
Ok(None) => return false,
|
||||
Err(error) => {
|
||||
eprintln!("zed sandbox supervisor: bad control message: {error:#}");
|
||||
return false;
|
||||
}
|
||||
};
|
||||
match message {
|
||||
ZedMessage::PromptReply {
|
||||
prompt,
|
||||
allow,
|
||||
remember,
|
||||
} => self.shared.reply(prompt, PromptReply { allow, remember }),
|
||||
ZedMessage::Request { id, request } => {
|
||||
let response =
|
||||
self.handle_request(request, fds)
|
||||
.unwrap_or_else(|error| Response::Error {
|
||||
message: format!("{error:#}"),
|
||||
});
|
||||
self.shared
|
||||
.send(&SupervisorMessage::Response { id, response });
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn handle_request(&mut self, request: Request, mut fds: Vec<OwnedFd>) -> Result<Response> {
|
||||
match request {
|
||||
Request::CreateSandbox { sandbox, policy } => {
|
||||
if self.sandboxes.contains_key(&sandbox) {
|
||||
bail!("sandbox {sandbox} already exists");
|
||||
}
|
||||
self.sandboxes.insert(
|
||||
sandbox,
|
||||
Arc::new(SandboxState {
|
||||
id: sandbox,
|
||||
policy: RwLock::new(Arc::new(policy)),
|
||||
names: Mutex::default(),
|
||||
}),
|
||||
);
|
||||
Ok(Response::Done)
|
||||
}
|
||||
Request::UpdatePolicy { sandbox, policy } => {
|
||||
let state = self.sandbox(sandbox)?;
|
||||
state.modify_policy(|current| *current = policy);
|
||||
let policy = state.policy();
|
||||
let mut still_open = Vec::new();
|
||||
for execution in &self.executions {
|
||||
if Arc::ptr_eq(&execution.sandbox, &state) {
|
||||
still_open.extend(open_files_beyond(execution, &policy));
|
||||
net::ensure_udp_ports(&self.shared, execution);
|
||||
}
|
||||
}
|
||||
Ok(Response::PolicyUpdated { still_open })
|
||||
}
|
||||
Request::DestroySandbox { sandbox } => {
|
||||
self.sandboxes.remove(&sandbox);
|
||||
if let Ok(mut queues) = self.shared.queues.lock() {
|
||||
queues.retain(|(owner, _), _| *owner != sandbox);
|
||||
}
|
||||
Ok(Response::Done)
|
||||
}
|
||||
Request::AttachExecution { sandbox } => {
|
||||
let state = self.sandbox(sandbox)?;
|
||||
if fds.len() != 1 {
|
||||
bail!("attach request needs exactly one socket");
|
||||
}
|
||||
self.pending.push((fds.remove(0), state));
|
||||
Ok(Response::Done)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sandbox(&self, sandbox: SandboxId) -> Result<Arc<SandboxState>> {
|
||||
self.sandboxes
|
||||
.get(&sandbox)
|
||||
.cloned()
|
||||
.with_context(|| format!("unknown sandbox {sandbox}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Files the execution's processes hold open with access `policy` no longer
|
||||
/// grants.
|
||||
fn open_files_beyond(execution: &Execution, policy: &WirePolicy) -> Vec<OpenFile> {
|
||||
let mut open_files = Vec::new();
|
||||
for process in execution.tree.members() {
|
||||
let Ok(entries) = std::fs::read_dir(format!("/proc/{}/fd", process.pid)) else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let Ok(path) = std::fs::read_link(entry.path()) else {
|
||||
continue;
|
||||
};
|
||||
if !path.is_absolute() || path.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let fdinfo = format!(
|
||||
"/proc/{}/fdinfo/{}",
|
||||
process.pid,
|
||||
entry.file_name().to_string_lossy()
|
||||
);
|
||||
let Some(flags) = std::fs::read_to_string(fdinfo).ok().and_then(|info| {
|
||||
info.lines()
|
||||
.find_map(|line| line.strip_prefix("flags:"))
|
||||
.and_then(|flags| i32::from_str_radix(flags.trim(), 8).ok())
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
if flags & libc::O_PATH != 0 {
|
||||
continue;
|
||||
}
|
||||
let access_mode = flags & libc::O_ACCMODE;
|
||||
let read = access_mode != libc::O_WRONLY
|
||||
&& policy.fs_access(&path, Permission::Read) != WireAccess::Allow;
|
||||
let write = access_mode != libc::O_RDONLY
|
||||
&& policy.fs_access(&path, Permission::Write) != WireAccess::Allow;
|
||||
if read || write {
|
||||
open_files.push(OpenFile {
|
||||
pid: process.pid,
|
||||
path,
|
||||
read,
|
||||
write,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
open_files
|
||||
}
|
||||
|
||||
fn poll_fd(fd: RawFd) -> libc::pollfd {
|
||||
libc::pollfd {
|
||||
fd,
|
||||
events: libc::POLLIN,
|
||||
revents: 0,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
//! Thin wrappers over the raw syscalls the sandbox needs that `libc` / `nix`
|
||||
//! don't wrap (or that we want with exact semantics).
|
||||
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::io;
|
||||
use std::os::fd::{AsRawFd as _, BorrowedFd, FromRawFd as _, OwnedFd, RawFd};
|
||||
use std::os::unix::ffi::OsStrExt as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub(crate) const MOUNT_ATTR_RDONLY: u64 = 0x1;
|
||||
|
||||
// Syscalls added after the per-arch tables were unified share one number.
|
||||
const SYS_PIDFD_OPEN: libc::c_long = 434;
|
||||
const SYS_PIDFD_GETFD: libc::c_long = 438;
|
||||
const SYS_MOUNT_SETATTR: libc::c_long = 442;
|
||||
const AT_RECURSIVE: libc::c_uint = 0x8000;
|
||||
|
||||
pub(crate) fn errno(code: i32) -> io::Error {
|
||||
io::Error::from_raw_os_error(code)
|
||||
}
|
||||
|
||||
pub(crate) fn cvt(result: libc::c_int) -> io::Result<libc::c_int> {
|
||||
if result < 0 {
|
||||
Err(io::Error::last_os_error())
|
||||
} else {
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn cstring(bytes: &[u8]) -> io::Result<CString> {
|
||||
CString::new(bytes).map_err(|_| errno(libc::EINVAL))
|
||||
}
|
||||
|
||||
pub(crate) fn path_cstring(path: &Path) -> io::Result<CString> {
|
||||
cstring(path.as_os_str().as_bytes())
|
||||
}
|
||||
|
||||
/// `openat(2)`. `O_CLOEXEC` is always added.
|
||||
pub(crate) fn openat(dirfd: RawFd, path: &CStr, flags: i32, mode: u32) -> io::Result<OwnedFd> {
|
||||
// SAFETY: valid NUL-terminated path.
|
||||
let fd = cvt(unsafe { libc::openat(dirfd, path.as_ptr(), flags | libc::O_CLOEXEC, mode) })?;
|
||||
// SAFETY: a freshly returned descriptor that nothing else owns.
|
||||
Ok(unsafe { OwnedFd::from_raw_fd(fd) })
|
||||
}
|
||||
|
||||
pub(crate) fn open(path: &Path, flags: i32) -> io::Result<OwnedFd> {
|
||||
openat(libc::AT_FDCWD, &path_cstring(path)?, flags, 0)
|
||||
}
|
||||
|
||||
/// `/proc/self/fd/N`: opening or operating on this path reaches exactly the
|
||||
/// object `fd` refers to, through the mount `fd` was opened on.
|
||||
pub(crate) fn proc_self_fd(fd: BorrowedFd<'_>) -> PathBuf {
|
||||
PathBuf::from(format!("/proc/self/fd/{}", fd.as_raw_fd()))
|
||||
}
|
||||
|
||||
/// The path of the object `fd` refers to, as rendered by the kernel.
|
||||
///
|
||||
/// For objects in another mount namespace (e.g. a sandbox's), the kernel
|
||||
/// renders the path as seen from that namespace's root.
|
||||
pub(crate) fn fd_path(fd: BorrowedFd<'_>) -> io::Result<PathBuf> {
|
||||
std::fs::read_link(proc_self_fd(fd))
|
||||
}
|
||||
|
||||
pub(crate) fn fstat(fd: BorrowedFd<'_>) -> io::Result<libc::stat> {
|
||||
// SAFETY: `stat` is plain old data, filled in by the kernel.
|
||||
let mut stat: libc::stat = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: valid fd and pointer to a `stat`.
|
||||
cvt(unsafe { libc::fstat(fd.as_raw_fd(), &mut stat) })?;
|
||||
Ok(stat)
|
||||
}
|
||||
|
||||
pub(crate) fn mount(
|
||||
source: Option<&Path>,
|
||||
target: &Path,
|
||||
filesystem: Option<&str>,
|
||||
flags: libc::c_ulong,
|
||||
data: Option<&str>,
|
||||
) -> io::Result<()> {
|
||||
let source = source.map(path_cstring).transpose()?;
|
||||
let target = path_cstring(target)?;
|
||||
let filesystem = filesystem
|
||||
.map(|name| cstring(name.as_bytes()))
|
||||
.transpose()?;
|
||||
let data = data.map(|data| cstring(data.as_bytes())).transpose()?;
|
||||
let pointer = |value: &Option<CString>| {
|
||||
value
|
||||
.as_ref()
|
||||
.map_or(std::ptr::null(), |value| value.as_ptr())
|
||||
};
|
||||
// SAFETY: every pointer is null or a valid NUL-terminated string.
|
||||
cvt(unsafe {
|
||||
libc::mount(
|
||||
pointer(&source),
|
||||
target.as_ptr(),
|
||||
pointer(&filesystem),
|
||||
flags,
|
||||
pointer(&data).cast(),
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct MountAttr {
|
||||
attr_set: u64,
|
||||
attr_clr: u64,
|
||||
propagation: u64,
|
||||
userns_fd: u64,
|
||||
}
|
||||
|
||||
/// `mount_setattr(2)`: add `attributes` to the mount at `target` (and, with
|
||||
/// `recursive`, every mount beneath it).
|
||||
pub(crate) fn mount_setattr(target: &Path, attributes: u64, recursive: bool) -> io::Result<()> {
|
||||
let target = path_cstring(target)?;
|
||||
let attr = MountAttr {
|
||||
attr_set: attributes,
|
||||
attr_clr: 0,
|
||||
propagation: 0,
|
||||
userns_fd: 0,
|
||||
};
|
||||
let flags = if recursive { AT_RECURSIVE } else { 0 };
|
||||
// SAFETY: valid path and a correctly sized `mount_attr`.
|
||||
let result = unsafe {
|
||||
libc::syscall(
|
||||
SYS_MOUNT_SETATTR,
|
||||
libc::AT_FDCWD,
|
||||
target.as_ptr(),
|
||||
flags,
|
||||
&attr as *const MountAttr,
|
||||
size_of::<MountAttr>(),
|
||||
)
|
||||
};
|
||||
if result < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Duplicate `fd` to the lowest free descriptor `>= minimum`, close-on-exec.
|
||||
pub(crate) fn duplicate_above(fd: BorrowedFd<'_>, minimum: RawFd) -> io::Result<OwnedFd> {
|
||||
// SAFETY: fcntl on a valid descriptor.
|
||||
let duplicate = cvt(unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_DUPFD_CLOEXEC, minimum) })?;
|
||||
// SAFETY: a freshly returned descriptor that nothing else owns.
|
||||
Ok(unsafe { OwnedFd::from_raw_fd(duplicate) })
|
||||
}
|
||||
|
||||
fn own_syscall_fd(result: libc::c_long) -> io::Result<OwnedFd> {
|
||||
if result < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
// SAFETY: a freshly returned descriptor that nothing else owns.
|
||||
Ok(unsafe { OwnedFd::from_raw_fd(result as RawFd) })
|
||||
}
|
||||
|
||||
/// A duplicate of descriptor `fd` of process `pid` (a thread group leader).
|
||||
pub(crate) fn pidfd_getfd(pid: i32, fd: RawFd) -> io::Result<OwnedFd> {
|
||||
// SAFETY: plain syscalls; each returns a new descriptor or fails.
|
||||
let pidfd = own_syscall_fd(unsafe { libc::syscall(SYS_PIDFD_OPEN, pid, 0) })?;
|
||||
// SAFETY: as above.
|
||||
own_syscall_fd(unsafe { libc::syscall(SYS_PIDFD_GETFD, pidfd.as_raw_fd(), fd, 0) })
|
||||
}
|
||||
|
||||
/// `socket(2)`. `SOCK_CLOEXEC` is always added.
|
||||
pub(crate) fn socket(domain: i32, kind: i32, protocol: i32) -> io::Result<OwnedFd> {
|
||||
// SAFETY: plain socket call.
|
||||
let fd = cvt(unsafe { libc::socket(domain, kind | libc::SOCK_CLOEXEC, protocol) })?;
|
||||
// SAFETY: a freshly returned descriptor that nothing else owns.
|
||||
Ok(unsafe { OwnedFd::from_raw_fd(fd) })
|
||||
}
|
||||
|
||||
pub(crate) fn socket_option(fd: BorrowedFd<'_>, level: i32, name: i32) -> io::Result<i32> {
|
||||
let mut value: libc::c_int = 0;
|
||||
let mut length = size_of::<libc::c_int>() as libc::socklen_t;
|
||||
// SAFETY: an int-sized buffer with its length.
|
||||
cvt(unsafe {
|
||||
libc::getsockopt(
|
||||
fd.as_raw_fd(),
|
||||
level,
|
||||
name,
|
||||
(&mut value as *mut libc::c_int).cast(),
|
||||
&mut length,
|
||||
)
|
||||
})?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub(crate) fn set_socket_option(
|
||||
fd: BorrowedFd<'_>,
|
||||
level: i32,
|
||||
name: i32,
|
||||
value: i32,
|
||||
) -> io::Result<()> {
|
||||
// SAFETY: an int-sized value with its length.
|
||||
cvt(unsafe {
|
||||
libc::setsockopt(
|
||||
fd.as_raw_fd(),
|
||||
level,
|
||||
name,
|
||||
(&value as *const libc::c_int).cast(),
|
||||
size_of::<libc::c_int>() as libc::socklen_t,
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Wait until `fd` has one of `events`, giving up after `timeout` or as
|
||||
/// soon as `keep_waiting` returns false.
|
||||
pub(crate) fn wait_for(
|
||||
fd: BorrowedFd<'_>,
|
||||
events: libc::c_short,
|
||||
timeout: std::time::Duration,
|
||||
keep_waiting: &dyn Fn() -> bool,
|
||||
) -> io::Result<()> {
|
||||
let deadline = std::time::Instant::now() + timeout;
|
||||
loop {
|
||||
let mut poll_fd = libc::pollfd {
|
||||
fd: fd.as_raw_fd(),
|
||||
events,
|
||||
revents: 0,
|
||||
};
|
||||
// SAFETY: one valid pollfd.
|
||||
let ready = unsafe { libc::poll(&mut poll_fd, 1, 250) };
|
||||
if ready > 0 {
|
||||
return Ok(());
|
||||
}
|
||||
if ready < 0 {
|
||||
let error = io::Error::last_os_error();
|
||||
if error.raw_os_error() != Some(libc::EINTR) {
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
if !keep_waiting() {
|
||||
return Err(errno(libc::ECONNABORTED));
|
||||
}
|
||||
if std::time::Instant::now() >= deadline {
|
||||
return Err(errno(libc::ETIMEDOUT));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_parent_death_signal() -> io::Result<()> {
|
||||
// SAFETY: plain prctl.
|
||||
cvt(unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL, 0, 0, 0) })?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Take ownership of a descriptor this process inherited at a fixed number.
|
||||
///
|
||||
/// # Safety
|
||||
/// `fd` must be open and not owned by anything else in this process.
|
||||
pub(crate) unsafe fn inherited_fd(fd: RawFd) -> io::Result<OwnedFd> {
|
||||
// SAFETY: fcntl on a possibly-closed descriptor only reports EBADF.
|
||||
let flags = cvt(unsafe { libc::fcntl(fd, libc::F_GETFD) })?;
|
||||
// SAFETY: as above.
|
||||
cvt(unsafe { libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) })?;
|
||||
// SAFETY: guaranteed by the caller.
|
||||
Ok(unsafe { OwnedFd::from_raw_fd(fd) })
|
||||
}
|
||||
@@ -248,6 +248,9 @@ gpui = { workspace = true, features = ["profiler", "windows-manifest"] }
|
||||
[target.'cfg(target_os = "windows")'.build-dependencies]
|
||||
windows_resources.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
sandbox_linux.workspace = true
|
||||
|
||||
[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies]
|
||||
gpui = { workspace = true, features = ["profiler", "wayland", "x11"] }
|
||||
ashpd = { workspace = true, features = ["notification"] }
|
||||
|
||||
@@ -215,6 +215,8 @@ fn main() {
|
||||
// args are appended verbatim and would otherwise be misinterpreted as Zed's
|
||||
// own arguments.
|
||||
sandbox::run_sandbox_launcher_if_invoked();
|
||||
#[cfg(target_os = "linux")]
|
||||
sandbox_linux::run_hidden_entrypoint_if_invoked();
|
||||
|
||||
#[cfg(unix)]
|
||||
util::prevent_root_execution();
|
||||
|
||||
@@ -22,7 +22,6 @@
|
||||
a11y-test = import ../tests/a11y.nix {
|
||||
inherit pkgs inputs;
|
||||
};
|
||||
}
|
||||
// import ../tests/sandboxing { inherit pkgs inputs; };
|
||||
} // import ../tests/sandboxing { inherit pkgs inputs; };
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
# Linux sandbox VM tests
|
||||
|
||||
These are `pkgs.testers.nixosTest` checks exported by the root flake on Linux.
|
||||
They require Nix with flakes and a Linux builder with usable `/dev/kvm`
|
||||
(including access for the Nix build user). No Zed UI is involved.
|
||||
|
||||
The existing entrypoint discovers all `sandbox-*` checks:
|
||||
|
||||
```sh
|
||||
cargo xtask sandbox-tests --list
|
||||
cargo xtask sandbox-tests
|
||||
cargo xtask sandbox-tests sandbox-linux-working sandbox-linux-userns-disabled
|
||||
```
|
||||
|
||||
Run individual checks or debug interactively with the NixOS test driver:
|
||||
|
||||
```sh
|
||||
nix build .#checks.x86_64-linux.sandbox-linux-working -L --accept-flake-config
|
||||
nix build .#checks.x86_64-linux.sandbox-linux-userns-disabled -L --accept-flake-config
|
||||
nix run .#checks.x86_64-linux.sandbox-linux-working.driverInteractive
|
||||
```
|
||||
|
||||
Replace `x86_64-linux` with `aarch64-linux` on an appropriate builder.
|
||||
`cargo xtask sandbox-tests --rebuild ...` passes `--rebuild` to Nix to rerun a
|
||||
previously built check rather than reuse its successful cached result.
|
||||
|
||||
For an untracked working tree (Nix's Git flake source omits new files), or a
|
||||
shallow checkout whose Nix version cannot determine `revCount`, use `path:.`
|
||||
instead of `.` in the direct Nix commands. Do not commit just to run a check.
|
||||
|
||||
## Experimental `sandbox_linux`
|
||||
|
||||
`sandbox-linux-working` builds the crate's `end_to_end` example with Crane and
|
||||
installs that executable in the VM. It is an example rather than a test target,
|
||||
gated behind the `__end_to_end_harness` feature, so CI's
|
||||
`cargo nextest run --workspace` never builds or runs it. Its hidden
|
||||
supervisor/helper re-exec entrypoints are preserved. The harness runs as a
|
||||
normal user, not root, with namespace creation enabled and a 180-second outer
|
||||
timeout. `--require-sandbox` makes setup failure fatal instead of taking the
|
||||
optional host-test skip path.
|
||||
|
||||
Coverage includes namespace separation, read/write globs and symlink/hard-link
|
||||
escape attempts, host-side integrity checks, Ask decisions (including handler
|
||||
panic and concurrent requests), live policy changes, process cleanup, TCP,
|
||||
synthetic DNS, UDP and Unix socket permission checks, and nonblocking TCP
|
||||
responsiveness/cancellation. Echo peers run locally outside the sandbox, inside
|
||||
the disposable VM; no Internet service is needed. Escape targets and other
|
||||
filesystem fixtures live under an automatically cleaned
|
||||
`/tmp/sandbox-escape-test-*` directory.
|
||||
|
||||
`sandbox-linux-userns-disabled` boots with `user.max_user_namespaces=0`. It
|
||||
requires namespace setup to fail and verifies that the untrusted command's
|
||||
canary was never written. This is an expected failure assertion, not a skip.
|
||||
|
||||
For faster host-side checks (the strict test needs usable user namespaces,
|
||||
seccomp notification support, Python 3, coreutils and util-linux on `PATH`):
|
||||
|
||||
```sh
|
||||
cargo test -p sandbox_linux --lib --locked
|
||||
./script/clippy -p sandbox_linux
|
||||
cargo build -p sandbox_linux --example end_to_end --features __end_to_end_harness --locked
|
||||
target/debug/examples/end_to_end --require-sandbox
|
||||
```
|
||||
|
||||
Without `--require-sandbox`, the end-to-end harness may skip if host namespace
|
||||
creation is unavailable. Do not use that optional invocation as VM evidence.
|
||||
|
||||
## CI
|
||||
|
||||
These VM checks exercise `sandbox_linux`, not the existing Bubblewrap backend.
|
||||
The Bubblewrap backend and its WSL tests remain in place.
|
||||
|
||||
The generated `nix_build` GitHub workflow (`run-nix` / `run-bundling` labels)
|
||||
currently builds only `.#default`; it does **not** execute these VM checks.
|
||||
Run the commands above explicitly on a KVM-capable builder. The new checks are
|
||||
also included in `nix flake check` on Linux and in the existing xtask's default
|
||||
selection; no separate CI/test framework is introduced.
|
||||
@@ -1,117 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Ad-hoc smoke test for the static `bwrap` binary. Exercises filesystem
|
||||
# read/write isolation and network isolation by trying to "break out" of the
|
||||
# sandbox in ways that must fail, alongside controls that must succeed.
|
||||
#
|
||||
# Usage: bwrap_smoke_test.sh /path/to/bwrap
|
||||
set -u
|
||||
|
||||
BWRAP=${1:?usage: bwrap_smoke_test.sh /path/to/bwrap}
|
||||
|
||||
# Resolve real binaries (works on NixOS, where /bin is mostly empty).
|
||||
CAT=$(command -v cat)
|
||||
TOUCH=$(command -v touch)
|
||||
SH=$(command -v sh)
|
||||
PY=$(command -v python3)
|
||||
|
||||
# Bind enough of the host (read-only) for dynamically-linked helpers to run.
|
||||
# On NixOS that means the closure under /nix/store; /usr/bin elsewhere.
|
||||
BASE=(--ro-bind /nix /nix --ro-bind /run /run --proc /proc --dev /dev --unshare-user)
|
||||
[ -d /usr ] && BASE+=(--ro-bind /usr /usr)
|
||||
[ -e /bin ] && BASE+=(--ro-bind /bin /bin)
|
||||
[ -e /lib ] && BASE+=(--ro-bind /lib /lib)
|
||||
[ -e /lib64 ] && BASE+=(--ro-bind /lib64 /lib64)
|
||||
[ -e /etc ] && BASE+=(--ro-bind /etc /etc)
|
||||
|
||||
PASS=0
|
||||
FAIL=0
|
||||
ok() { echo "PASS: $1"; PASS=$((PASS + 1)); }
|
||||
bad() { echo "FAIL: $1"; FAIL=$((FAIL + 1)); }
|
||||
|
||||
# expect_ok <desc> <cmd...> -> command must exit 0
|
||||
expect_ok() {
|
||||
desc=$1; shift
|
||||
if "$@"; then ok "$desc"; else bad "$desc (expected success, got exit $?)"; fi
|
||||
}
|
||||
# expect_fail <desc> <cmd...> -> command must exit non-zero
|
||||
expect_fail() {
|
||||
desc=$1; shift
|
||||
if "$@"; then bad "$desc (expected failure, but it succeeded)"; else ok "$desc"; fi
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Set up a host scratch tree:
|
||||
# $ROOT/secret/secret.txt -> must NOT be visible unless explicitly bound
|
||||
# $ROOT/allowed/note.txt -> bound read-only into the sandbox
|
||||
# $ROOT/writable/ -> bound read-write into the sandbox
|
||||
# ---------------------------------------------------------------------------
|
||||
ROOT=$(mktemp -d /tmp/bwrap-smoke.XXXXXX)
|
||||
trap 'rm -rf "$ROOT"' EXIT
|
||||
mkdir -p "$ROOT/secret" "$ROOT/allowed" "$ROOT/writable"
|
||||
echo "TOP SECRET" > "$ROOT/secret/secret.txt"
|
||||
echo "you may read me" > "$ROOT/allowed/note.txt"
|
||||
|
||||
echo "=================================================================="
|
||||
echo "bwrap: $BWRAP"
|
||||
"$BWRAP" --version
|
||||
echo "=================================================================="
|
||||
echo "## Filesystem isolation"
|
||||
|
||||
# The host secret must be invisible: sandbox sees a fresh tmpfs at $ROOT,
|
||||
# so the secret path simply doesn't exist.
|
||||
expect_fail "host secret file is NOT readable from sandbox" \
|
||||
"$BWRAP" "${BASE[@]}" --tmpfs "$ROOT" "$CAT" "$ROOT/secret/secret.txt"
|
||||
|
||||
# Likewise nothing under /tmp leaks in by default (no bind for it).
|
||||
expect_fail "host /tmp is NOT visible from sandbox" \
|
||||
"$BWRAP" "${BASE[@]}" --tmpfs /tmp "$CAT" "$ROOT/allowed/note.txt"
|
||||
|
||||
# An explicitly read-only bind IS readable...
|
||||
expect_ok "explicitly ro-bound file IS readable" \
|
||||
"$BWRAP" "${BASE[@]}" --ro-bind "$ROOT/allowed" /data "$CAT" /data/note.txt
|
||||
|
||||
# ...but writing to a read-only bind must fail.
|
||||
expect_fail "writing to a ro-bound dir is denied" \
|
||||
"$BWRAP" "${BASE[@]}" --ro-bind "$ROOT/allowed" /data "$TOUCH" /data/evil
|
||||
|
||||
# Confirm the host file was not modified/created behind the sandbox's back.
|
||||
expect_fail "ro-bind write did not leak to host" test -e "$ROOT/allowed/evil"
|
||||
|
||||
# A read-write bind allows writes...
|
||||
expect_ok "writing to a rw-bound dir succeeds" \
|
||||
"$BWRAP" "${BASE[@]}" --bind "$ROOT/writable" /data "$TOUCH" /data/hello
|
||||
|
||||
# ...and the write really lands on the host file (proves the bind, not a tmpfs).
|
||||
expect_ok "rw-bind write is visible on host" test -e "$ROOT/writable/hello"
|
||||
|
||||
# Writing to a tmpfs overlay succeeds inside, but must NOT touch the host dir.
|
||||
expect_ok "writing into a tmpfs works inside sandbox" \
|
||||
"$BWRAP" "${BASE[@]}" --tmpfs "$ROOT/writable" "$TOUCH" "$ROOT/writable/ephemeral"
|
||||
expect_fail "tmpfs write did not leak to host" test -e "$ROOT/writable/ephemeral"
|
||||
|
||||
echo "------------------------------------------------------------------"
|
||||
echo "## Network isolation"
|
||||
|
||||
NETCHECK='import socket; s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.settimeout(5); s.connect(("1.1.1.1",53)); print("connected")'
|
||||
|
||||
# With --unshare-net the sandbox has only loopback: outbound TCP must fail.
|
||||
expect_fail "outbound TCP is blocked with --unshare-net" \
|
||||
"$BWRAP" "${BASE[@]}" --unshare-net "$PY" -c "$NETCHECK"
|
||||
|
||||
# Loopback still exists inside the isolated netns.
|
||||
expect_ok "loopback is up inside --unshare-net" \
|
||||
"$BWRAP" "${BASE[@]}" --unshare-net "$PY" -c \
|
||||
'import socket; socket.socket().bind(("127.0.0.1",0)); print("lo ok")'
|
||||
|
||||
# Without --unshare-net the host network is shared, so the same connect works
|
||||
# (skipped automatically if the host itself has no outbound connectivity).
|
||||
if timeout 6 "$PY" -c "$NETCHECK" >/dev/null 2>&1; then
|
||||
expect_ok "outbound TCP works when network is shared" \
|
||||
"$BWRAP" "${BASE[@]}" "$PY" -c "$NETCHECK"
|
||||
else
|
||||
echo "SKIP: host has no outbound TCP; cannot test shared-network case"
|
||||
fi
|
||||
|
||||
echo "=================================================================="
|
||||
echo "Summary: $PASS passed, $FAIL failed"
|
||||
[ "$FAIL" -eq 0 ]
|
||||
@@ -1,424 +1,52 @@
|
||||
# NixOS VM tests for the Linux Bubblewrap (`bwrap`) sandbox.
|
||||
#
|
||||
# What actually changes the sandbox's behavior is the *host configuration* —
|
||||
# whether a usable `bwrap` exists and whether the kernel lets us create user
|
||||
# namespaces. We can only set those at boot, which is exactly what a VM gives
|
||||
# us. So we run one machine per host configuration:
|
||||
#
|
||||
# working - `bwrap` present, unprivileged user namespaces available;
|
||||
# the sandbox must be enforced.
|
||||
# no-bwrap - no `bwrap` on PATH; `Sandbox::can_create` must report
|
||||
# `BwrapNotFound` and the consumer must fail closed.
|
||||
# setuid-bwrap - the only `bwrap` is setuid-root; `can_create` must report
|
||||
# `BwrapSetuidRejected` (we refuse to run setuid bwrap).
|
||||
# userns-disabled - `bwrap` present but unprivileged user namespaces are
|
||||
# disabled via sysctl; `can_create` must report
|
||||
# `SandboxProbeFailed`.
|
||||
#
|
||||
# The behavior to assert is declared *here* as a list of `checks`, serialized to
|
||||
# JSON and handed to the `bwrap-test-helper` binary, which builds the described
|
||||
# sandbox policy via the sandbox crate's public API, performs the operation, and
|
||||
# asserts the outcome. Each check is one of:
|
||||
#
|
||||
# { read = "/path"; succeeds = true; } # read a host file
|
||||
# { write = "/path"; succeeds = false; } # write a host file
|
||||
# { network = "echo1"; succeeds = true; } # connect to an echo server
|
||||
# { socketPath = "/run/x.sock"; succeeds = false; } # connect a unix socket
|
||||
# { canCreate = false; error = "bwrap_not_found"; } # Sandbox::can_create
|
||||
#
|
||||
# plus optional policy fields applied to that check (defaults shown):
|
||||
#
|
||||
# fs = "restricted"; # or "unrestricted"
|
||||
# writablePaths = [ ]; # writable subtrees when fs = "restricted"
|
||||
# seedFiles = [ ]; # regular files to create before building the
|
||||
# # policy (e.g. a single-file-worktree root)
|
||||
# networkAccess = "blocked"; # or "unrestricted" / "restricted"
|
||||
# allowedDomains = [ ]; # allowed hosts when networkAccess = "restricted"
|
||||
# protectedPaths = [ ]; # paths that remain readable but not writable,
|
||||
# # even if they fall under a writable subtree.
|
||||
#
|
||||
# Two echo servers (`echo1`, `echo2`) on separate nodes give the network checks
|
||||
# real peers, so a restricted-network policy that allowlists `echo1` can be
|
||||
# shown to reach `echo1` while `echo2` is blocked.
|
||||
#
|
||||
# Build one scenario:
|
||||
# nix build .#checks.x86_64-linux.sandbox-working
|
||||
# Interactive:
|
||||
# nix run .#checks.x86_64-linux.sandbox-working.driverInteractive
|
||||
{
|
||||
pkgs,
|
||||
inputs,
|
||||
}:
|
||||
{ pkgs, inputs }:
|
||||
let
|
||||
lib = pkgs.lib;
|
||||
|
||||
bwrap-test-helper = import ./helper.nix { inherit pkgs inputs; };
|
||||
|
||||
# Both echo nodes listen on the same port; the helper appends it to a bare
|
||||
# hostname (`echo1` -> `echo1:7000`).
|
||||
echoPort = 7000;
|
||||
|
||||
# A node running a raw TCP echo server (socat EXEC:cat). The helper round-trips
|
||||
# a byte through it, directly or via the sandbox's HTTP CONNECT proxy.
|
||||
mkEchoNode = {
|
||||
networking.firewall.allowedTCPPorts = [ echoPort ];
|
||||
systemd.services.echo-server = {
|
||||
description = "TCP echo server";
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
after = [ "network.target" ];
|
||||
serviceConfig = {
|
||||
ExecStart = "${pkgs.socat}/bin/socat -d TCP-LISTEN:${toString echoPort},reuseaddr,fork EXEC:cat";
|
||||
DynamicUser = true;
|
||||
Restart = "on-failure";
|
||||
};
|
||||
};
|
||||
helper = import ./helper.nix {
|
||||
inherit pkgs inputs;
|
||||
};
|
||||
|
||||
# A unix-domain socket, owned by a process *outside* the sandbox, that a
|
||||
# sandboxed command must not be able to `connect()` to. It lives under `/run`
|
||||
# (which the sandbox `--ro-bind`s along with the rest of `/`) and NOT under
|
||||
# `/tmp` (which the restricted-fs sandbox masks with a tmpfs, hiding anything
|
||||
# there), so it stays visible inside the sandbox and the block is what's
|
||||
# actually under test.
|
||||
unixSocketPath = "/run/zed-sandbox-test.sock";
|
||||
|
||||
# Quiet boot + a couple of cores; shared by every machine-under-test.
|
||||
baseMachine = {
|
||||
boot.consoleLogLevel = lib.mkForce 3; # be quiet pls :)
|
||||
services.journald.extraConfig = lib.mkAfter "MaxLevelConsole=notice";
|
||||
environment.systemPackages = [ bwrap-test-helper ];
|
||||
virtualisation = {
|
||||
memorySize = 1024;
|
||||
cores = 2;
|
||||
};
|
||||
|
||||
# A unix-socket echo server outside the sandbox, so a sandboxed `connect()`
|
||||
# has a real peer: without a listener the connect would fail with
|
||||
# ECONNREFUSED even absent the sandbox, giving a false "blocked" pass.
|
||||
systemd.services.unix-echo-server = {
|
||||
description = "Unix-domain-socket echo server";
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
serviceConfig = {
|
||||
ExecStart = "${pkgs.socat}/bin/socat -d UNIX-LISTEN:${unixSocketPath},fork,reuseaddr EXEC:cat";
|
||||
Restart = "on-failure";
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
# Per-scenario host configuration. Each entry layers onto `baseMachine`.
|
||||
machineConfigs = {
|
||||
# Plain, working host: bwrap on PATH, user namespaces available.
|
||||
working =
|
||||
{ ... }:
|
||||
lib.mkMerge [
|
||||
baseMachine
|
||||
{ environment.systemPackages = [ pkgs.bubblewrap ]; }
|
||||
];
|
||||
|
||||
# No bwrap anywhere on PATH.
|
||||
no-bwrap = { ... }: baseMachine;
|
||||
|
||||
# The only bwrap is a setuid-root wrapper. We deliberately do NOT also put a
|
||||
# plain `pkgs.bubblewrap` on PATH: `locate_bwrap` returns the first `bwrap`
|
||||
# it finds on PATH, and we want that to be the setuid one so the helper sees
|
||||
# `BwrapSetuidRejected`.
|
||||
setuid-bwrap =
|
||||
{ ... }:
|
||||
lib.mkMerge [
|
||||
baseMachine
|
||||
{
|
||||
security.wrappers.bwrap = {
|
||||
source = "${pkgs.bubblewrap}/bin/bwrap";
|
||||
owner = "root";
|
||||
group = "root";
|
||||
setuid = true;
|
||||
};
|
||||
}
|
||||
];
|
||||
|
||||
# bwrap present, but unprivileged user namespaces disabled at boot. Capping
|
||||
# the count at 0 makes `bwrap --unshare-user` fail, exactly like a hardened
|
||||
# host, so the probe reports `SandboxProbeFailed`.
|
||||
userns-disabled =
|
||||
{ ... }:
|
||||
lib.mkMerge [
|
||||
baseMachine
|
||||
{
|
||||
environment.systemPackages = [ pkgs.bubblewrap ];
|
||||
boot.kernel.sysctl."user.max_user_namespaces" = 0;
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
# Build a VM test for `machine` that runs `checks` through the helper.
|
||||
mkTest =
|
||||
{
|
||||
name,
|
||||
machine,
|
||||
checks,
|
||||
}:
|
||||
let
|
||||
checksFile = pkgs.writeText "${name}-checks.json" (builtins.toJSON checks);
|
||||
in
|
||||
{ name, userNamespaces }:
|
||||
pkgs.testers.nixosTest {
|
||||
inherit name;
|
||||
|
||||
nodes = {
|
||||
echo1 = { ... }: mkEchoNode;
|
||||
echo2 = { ... }: mkEchoNode;
|
||||
machine = machine;
|
||||
nodes.machine = {
|
||||
boot.consoleLogLevel = pkgs.lib.mkForce 3;
|
||||
services.journald.settings.Journal.MaxLevelConsole = pkgs.lib.mkForce "notice";
|
||||
boot.kernel.sysctl."user.max_user_namespaces" = if userNamespaces then 1024 else 0;
|
||||
users.users.sandbox-test = {
|
||||
isNormalUser = true;
|
||||
uid = 1000;
|
||||
};
|
||||
environment.systemPackages = [
|
||||
helper
|
||||
pkgs.python3
|
||||
pkgs.util-linux
|
||||
];
|
||||
virtualisation = {
|
||||
memorySize = 1024;
|
||||
cores = 2;
|
||||
};
|
||||
};
|
||||
|
||||
testScript = ''
|
||||
start_all()
|
||||
|
||||
echo1.wait_for_unit("echo-server.service")
|
||||
echo1.wait_for_open_port(${toString echoPort})
|
||||
echo2.wait_for_unit("echo-server.service")
|
||||
echo2.wait_for_open_port(${toString echoPort})
|
||||
|
||||
machine.start()
|
||||
machine.wait_for_unit("multi-user.target")
|
||||
machine.wait_until_succeeds("getent hosts echo1", timeout=30)
|
||||
machine.wait_until_succeeds("getent hosts echo2", timeout=30)
|
||||
|
||||
# The unix-socket checks need a real peer outside the sandbox; wait for
|
||||
# the listener to be up before running the helper.
|
||||
machine.wait_until_succeeds("test -S ${unixSocketPath}", timeout=30)
|
||||
|
||||
# The helper logs each check tagged `[sandbox_test]:`. `succeed` fails the
|
||||
# whole test on a non-zero exit; we print its output so the per-check
|
||||
# results show up in the build log.
|
||||
print(machine.succeed(
|
||||
"ZED_SANDBOX_CHECKS=${checksFile} "
|
||||
"ZED_TEST_ECHO_PORT=${toString echoPort} "
|
||||
"bwrap-test-helper 2>&1"
|
||||
"su -l sandbox-test -c 'timeout 180 sandbox-linux-test-helper ${
|
||||
if userNamespaces then "--require-sandbox" else "--expect-userns-disabled"
|
||||
}' 2>&1",
|
||||
timeout=200,
|
||||
))
|
||||
'';
|
||||
};
|
||||
|
||||
in
|
||||
{
|
||||
sandbox-working = mkTest {
|
||||
name = "sandbox-working";
|
||||
machine = machineConfigs.working;
|
||||
# Each check is written out in full (no shared fragments) so the policy and
|
||||
# expected outcome for every case are obvious at a glance.
|
||||
checks = [
|
||||
# Reads of host files are always allowed, regardless of the write policy.
|
||||
{
|
||||
fs = "restricted";
|
||||
writablePaths = [ "/sandbox-test/writable" ];
|
||||
networkAccess = "blocked";
|
||||
read = "/sandbox-test/readable/host.txt";
|
||||
succeeds = true;
|
||||
}
|
||||
|
||||
# Write inside the granted subtree: allowed.
|
||||
{
|
||||
fs = "restricted";
|
||||
writablePaths = [ "/sandbox-test/writable" ];
|
||||
networkAccess = "blocked";
|
||||
write = "/sandbox-test/writable/ok.txt";
|
||||
succeeds = true;
|
||||
}
|
||||
|
||||
# Write outside the granted subtree: denied.
|
||||
{
|
||||
fs = "restricted";
|
||||
writablePaths = [ "/sandbox-test/writable" ];
|
||||
networkAccess = "blocked";
|
||||
write = "/sandbox-test/forbidden/no.txt";
|
||||
succeeds = false;
|
||||
}
|
||||
|
||||
# A writable path that doesn't exist yet must be bound at its exact
|
||||
# location (created up front), never widened to an existing ancestor. If it
|
||||
# widened to `/sandbox-test`, this write to a read-only file under that
|
||||
# ancestor would succeed — the scope-widening sandbox escape this guards
|
||||
# against. It must be denied.
|
||||
{
|
||||
fs = "restricted";
|
||||
writablePaths = [ "/sandbox-test/not-yet-created/deep" ];
|
||||
networkAccess = "blocked";
|
||||
write = "/sandbox-test/readable/host.txt";
|
||||
succeeds = false;
|
||||
}
|
||||
|
||||
# ...and the not-yet-existing path itself is created and writable.
|
||||
{
|
||||
fs = "restricted";
|
||||
writablePaths = [ "/sandbox-test/not-yet-created/deep" ];
|
||||
networkAccess = "blocked";
|
||||
write = "/sandbox-test/not-yet-created/deep/ok.txt";
|
||||
succeeds = true;
|
||||
}
|
||||
|
||||
# Regression: a protected `.git` path routed through a regular file must
|
||||
# not break sandbox creation. A single-file worktree (e.g. `settings.json`
|
||||
# opened on its own) is rooted at the file, so the agent synthesizes
|
||||
# `settings.json/.git` as a protected path; capturing it reports
|
||||
# `NotADirectory`. That case must be *skipped* (the path can't exist, so
|
||||
# there's nothing to protect), not treated as a fatal capture error — the
|
||||
# bug that surfaced as a "cannot capture protected sandbox path
|
||||
# .../settings.json/.git" popup. `seedFiles` makes `settings.json` a real
|
||||
# file so the protected path routes through it; the sandbox must still be
|
||||
# created and a normal write inside the worktree must succeed.
|
||||
{
|
||||
name = "protected .git routed through a regular file is skipped, not fatal";
|
||||
fs = "restricted";
|
||||
writablePaths = [ "/sandbox-test/single-file-worktree" ];
|
||||
seedFiles = [ "/sandbox-test/single-file-worktree/settings.json" ];
|
||||
protectedPaths = [ "/sandbox-test/single-file-worktree/settings.json/.git" ];
|
||||
networkAccess = "blocked";
|
||||
write = "/sandbox-test/single-file-worktree/ok.txt";
|
||||
succeeds = true;
|
||||
}
|
||||
|
||||
# The fs escape hatch lets a command write anywhere.
|
||||
{
|
||||
fs = "unrestricted";
|
||||
networkAccess = "blocked";
|
||||
write = "/sandbox-test/forbidden/anywhere.txt";
|
||||
succeeds = true;
|
||||
}
|
||||
|
||||
# ---- Protected paths ---------------------------------------------------
|
||||
# A path inside a writable subtree can be re-bound read-only over the
|
||||
# writable bind (order matters: later binds win). On Linux, protected paths
|
||||
# remain readable but writes are denied.
|
||||
{
|
||||
fs = "restricted";
|
||||
writablePaths = [ "/sandbox-test/repo" ];
|
||||
protectedPaths = [ "/sandbox-test/repo/protected" ];
|
||||
networkAccess = "blocked";
|
||||
write = "/sandbox-test/repo/protected/test";
|
||||
succeeds = false;
|
||||
}
|
||||
|
||||
# Protected paths affect only the protected subtree: ordinary writes
|
||||
# elsewhere in the writable worktree are unaffected.
|
||||
{
|
||||
fs = "restricted";
|
||||
writablePaths = [ "/sandbox-test/repo" ];
|
||||
protectedPaths = [ "/sandbox-test/repo/protected" ];
|
||||
networkAccess = "blocked";
|
||||
write = "/sandbox-test/repo/src/main.rs";
|
||||
succeeds = true;
|
||||
}
|
||||
|
||||
# Protected paths block writes but NOT reads on Linux because the protected
|
||||
# subtree is read-only.
|
||||
{
|
||||
fs = "restricted";
|
||||
writablePaths = [ "/sandbox-test/repo" ];
|
||||
protectedPaths = [ "/sandbox-test/repo/protected" ];
|
||||
networkAccess = "blocked";
|
||||
read = "/sandbox-test/repo/protected/HEAD";
|
||||
succeeds = true;
|
||||
}
|
||||
|
||||
# Protected paths stay read-only even when ordinary filesystem writes are
|
||||
# otherwise unrestricted.
|
||||
{
|
||||
fs = "unrestricted";
|
||||
protectedPaths = [ "/sandbox-test/repo/protected" ];
|
||||
networkAccess = "blocked";
|
||||
write = "/sandbox-test/repo/protected/test";
|
||||
succeeds = false;
|
||||
}
|
||||
|
||||
# Blocked network: the echo server is unreachable.
|
||||
{
|
||||
fs = "restricted";
|
||||
writablePaths = [ "/sandbox-test/writable" ];
|
||||
networkAccess = "blocked";
|
||||
network = "echo1";
|
||||
succeeds = false;
|
||||
}
|
||||
|
||||
# Unrestricted network: both echo servers are reachable.
|
||||
{
|
||||
fs = "restricted";
|
||||
writablePaths = [ "/sandbox-test/writable" ];
|
||||
networkAccess = "unrestricted";
|
||||
network = "echo1";
|
||||
succeeds = true;
|
||||
}
|
||||
{
|
||||
fs = "restricted";
|
||||
writablePaths = [ "/sandbox-test/writable" ];
|
||||
networkAccess = "unrestricted";
|
||||
network = "echo2";
|
||||
succeeds = true;
|
||||
}
|
||||
|
||||
# Restricted network: only the allowlisted host is reachable.
|
||||
{
|
||||
fs = "restricted";
|
||||
writablePaths = [ "/sandbox-test/writable" ];
|
||||
networkAccess = "restricted";
|
||||
allowedDomains = [ "echo1" ];
|
||||
network = "echo1";
|
||||
succeeds = true;
|
||||
}
|
||||
{
|
||||
fs = "restricted";
|
||||
writablePaths = [ "/sandbox-test/writable" ];
|
||||
networkAccess = "restricted";
|
||||
allowedDomains = [ "echo1" ];
|
||||
network = "echo2";
|
||||
succeeds = false;
|
||||
}
|
||||
|
||||
# ---- Unix-domain socket escape ----------------------------------------
|
||||
# A sandboxed command must NOT be able to connect to a unix-domain socket
|
||||
# owned by a process outside the sandbox (session-IPC escape). Currently
|
||||
# FAILS (no seccomp guard yet); becomes a regression test once the
|
||||
# socket(AF_UNIX) seccomp filter lands.
|
||||
{
|
||||
fs = "restricted";
|
||||
writablePaths = [ "/sandbox-test/writable" ];
|
||||
networkAccess = "blocked";
|
||||
socketPath = unixSocketPath;
|
||||
succeeds = false;
|
||||
}
|
||||
|
||||
# The unix-socket block must hold regardless of network policy: our design
|
||||
# decouples unix-socket blocking from the network grant, so even an
|
||||
# unrestricted-network command must not reach an outside-the-sandbox
|
||||
# session IPC socket. Also currently FAILS until the seccomp filter lands.
|
||||
{
|
||||
fs = "restricted";
|
||||
writablePaths = [ "/sandbox-test/writable" ];
|
||||
networkAccess = "unrestricted";
|
||||
socketPath = unixSocketPath;
|
||||
succeeds = false;
|
||||
}
|
||||
|
||||
# On a working host the sandbox can be created.
|
||||
{
|
||||
fs = "restricted";
|
||||
networkAccess = "blocked";
|
||||
canCreate = true;
|
||||
}
|
||||
];
|
||||
sandbox-linux-working = mkTest {
|
||||
name = "sandbox-linux-working";
|
||||
userNamespaces = true;
|
||||
};
|
||||
|
||||
sandbox-no-bwrap = mkTest {
|
||||
name = "sandbox-no-bwrap";
|
||||
machine = machineConfigs.no-bwrap;
|
||||
checks = [ { canCreate = false; error = "bwrap_not_found"; } ];
|
||||
};
|
||||
|
||||
sandbox-setuid-bwrap = mkTest {
|
||||
name = "sandbox-setuid-bwrap";
|
||||
machine = machineConfigs.setuid-bwrap;
|
||||
checks = [ { canCreate = false; error = "setuid_rejected"; } ];
|
||||
};
|
||||
|
||||
sandbox-userns-disabled = mkTest {
|
||||
name = "sandbox-userns-disabled";
|
||||
machine = machineConfigs.userns-disabled;
|
||||
checks = [ { canCreate = false; error = "probe_failed"; } ];
|
||||
sandbox-linux-userns-disabled = mkTest {
|
||||
name = "sandbox-linux-userns-disabled";
|
||||
userNamespaces = false;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
# Builds the `bwrap-test-helper` binary (sandbox crate, `nixos-test` feature)
|
||||
# used by the Bubblewrap sandbox VM tests in this directory.
|
||||
# Builds the re-executable sandbox_linux end-to-end harness for the VM tests.
|
||||
{
|
||||
pkgs,
|
||||
inputs,
|
||||
@@ -30,15 +29,18 @@ let
|
||||
".config"
|
||||
".cargo"
|
||||
];
|
||||
name = "bwrap-test-helper-source";
|
||||
name = "sandbox-linux-test-helper-source";
|
||||
};
|
||||
|
||||
commonArgs = {
|
||||
pname = "bwrap-test-helper";
|
||||
pname = "sandbox-linux-test-helper";
|
||||
# An example, not a test target (see crates/sandbox_linux/Cargo.toml):
|
||||
# built and run here only, never by CI's `cargo nextest run --workspace`.
|
||||
cargoExtraArgs = "-p sandbox_linux --example end_to_end --features __end_to_end_harness --locked";
|
||||
cargoBuildCommand = "cargoWithProfile test --no-run";
|
||||
version = "0.0.0";
|
||||
inherit src;
|
||||
cargoLock = ../../../Cargo.lock;
|
||||
cargoExtraArgs = "-p sandbox --bin bwrap-test-helper --features sandbox/nixos-test --locked";
|
||||
CARGO_PROFILE = "dev";
|
||||
doCheck = false;
|
||||
|
||||
@@ -58,12 +60,19 @@ craneLib.buildPackage (
|
||||
installPhase = ''
|
||||
runHook preInstall
|
||||
mkdir -p $out/bin
|
||||
cp target/debug/bwrap-test-helper $out/bin/bwrap-test-helper
|
||||
# Dependency artifacts can contain a dummy harness with another hash.
|
||||
helper="$(${pkgs.jq}/bin/jq -ers '
|
||||
[.[] | select(.reason == "compiler-artifact"
|
||||
and .target.name == "end_to_end" and .profile.test == true)
|
||||
| .executable | select(. != null)]
|
||||
| if length == 1 then .[0] else error("expected one test executable") end
|
||||
' "$cargoBuildLog")"
|
||||
cp "$helper" $out/bin/sandbox-linux-test-helper
|
||||
runHook postInstall
|
||||
'';
|
||||
|
||||
meta = {
|
||||
description = "Bubblewrap sandbox behavior test helper";
|
||||
description = "Sandbox behavior test helper";
|
||||
platforms = lib.platforms.linux;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ enum CliCommand {
|
||||
/// Inspect the GPUI publish plan and its dependencies.
|
||||
#[command(subcommand)]
|
||||
Gpui(tasks::gpui::GpuiCommand),
|
||||
/// Runs the Linux Bubblewrap sandboxing NixOS VM tests.
|
||||
/// Runs the sandbox_linux NixOS VM tests.
|
||||
SandboxTests(tasks::sandbox_tests::SandboxTestsArgs),
|
||||
/// Runs the Windows WSL Bubblewrap sandbox behavior tests.
|
||||
WslSandboxTests(tasks::wsl_sandbox_tests::WslSandboxTestsArgs),
|
||||
|
||||
@@ -5,18 +5,17 @@ use std::process::Command;
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
use clap::Parser;
|
||||
|
||||
/// Runs the Linux Bubblewrap sandboxing NixOS VM tests (see `nix/tests/sandboxing`).
|
||||
/// Runs the Linux sandboxing NixOS VM tests (see `nix/tests/sandboxing`).
|
||||
///
|
||||
/// Each test boots a real kernel under QEMU to exercise bwrap behavior across
|
||||
/// host configurations: a working host (the sandbox must be enforced and the
|
||||
/// full fs x network policy matrix must hold), and degraded hosts (no bwrap,
|
||||
/// setuid-only bwrap, user namespaces disabled) where `Sandbox::can_create`
|
||||
/// must report the specific failure and the consumer must fail closed. They
|
||||
/// therefore only run on Linux with `/dev/kvm` available, and require `nix`
|
||||
/// with flakes enabled.
|
||||
/// Each test boots a real kernel under QEMU. The sandbox_linux checks run its
|
||||
/// re-executable end-to-end harness (an example, never a cargo test target) as
|
||||
/// an unprivileged user, requiring successful sandbox setup on the working host
|
||||
/// and fail-closed execution when user namespaces are disabled.
|
||||
/// They require Linux with `/dev/kvm` available, and `nix` with flakes enabled.
|
||||
/// Nothing in CI runs these; this task and `nix flake check` are the entry points.
|
||||
#[derive(Parser)]
|
||||
pub struct SandboxTestsArgs {
|
||||
/// Names of specific tests to run (e.g. `sandbox-working`). Defaults
|
||||
/// Names of specific tests to run (e.g. `sandbox-linux-working`). Defaults
|
||||
/// to all.
|
||||
tests: Vec<String>,
|
||||
|
||||
|
||||
Reference in New Issue
Block a user