Skip to content

slice-sandbox: 5-Ring Zero-Trust OCap Containment, Dynamic SES & Hardware MPK

Every SliceIsolate executes inside a TenantCompartment (slice-sandbox) enforcing five concentric security barriers across Tier-0 SLICESNP, Tier-1 SLICEBC\x01/SLICEBOA (Boa), Tier-2 NumericFunc, Web Workers, Raw Sockets, and WebAssembly (wasmi).


  1. Ring 1 - SES Intrinsic Lockdown & Native 29-Intrinsic Fingerprint Verification (is_frozen_intrinsic + SesProtoSig):
    • Protects all 29 core primordials (Object, Array, Function, String, Number, Boolean, RegExp, Error, Promise, Map, Set, Date, Uint8Array alongside their .prototype objects, plus Reflect, JSON, and Math). Any mutation attempt immediately traps with SandboxViolation::IntrinsicMutationBlocked.
    • Avoiding the ES Override Mistake While Blocking Dynamic & Same-Shape Prototype Pollution: Directly calling Object.freeze(Object.prototype) in ECMAScript marks inherited properties (toString, valueOf, constructor) as writable: false, which causes standard CommonJS modules assigning Child.prototype.toString = ... to fail in strict mode (the ECMAScript specification “override mistake”). Slice solves this with a two-layer defense:
      1. Unified Tier-0 & Tier-1 guards (slice_sandbox::is_frozen_intrinsic) blocking direct property/index mutations, globalThis.* prefixes, Object.assign / Reflect.set targets, and routing destructuring/optional-chaining mutations under --tier=0 to Tier-1 Boa.
      2. Post-evaluation runtime verification across both cold and warm (__slice_rc) turns via native Rust SesProtoSig = (shape_id, proto_addr, storage_fingerprint) over all 29 intrinsics (augmented by __slice_check_ses), catching same-shape method overwrites (Object.assign(Array.prototype, { map: fn })), constructor tampering, and Math.random / Date.now / Promise.prototype.then tampering, quarantining any mutated or unnamed-tenant realm in BOA_CONTEXT_POOL, and trapping with SandboxViolation::IntrinsicMutationBlocked.
  2. Ring 2 - Attenuated VFS Read/Write (FsCap), Subprocess Binary (ExecCap), & Canonical CapabilityToken::attenuate:
    • verify_fs_read and verify_fs_write reject any path containing .. traversal segments, NUL bytes, mixed-slash Win32 UNC shares (\\server\share, \/server\share, /\server\share), or Win32 reserved device names (CON, PRN, AUX, NUL, CONIN$, CONOUT$, COM1..9, LPT1..9), guard /tmp <-> std::env::temp_dir() bidirectional canonical mapping against root (TMPDIR=/ or TMP=C:\), and verify strict directory-boundary containment against pre-normalized allowed_read_prefixes / allowed_write_prefixes.
    • CapabilityToken::attenuate enforces a single monotonic narrowing lattice across Slice.evalSandbox, new Worker, slice mcp, and untrusted inline directives: port-scoped parent grants ("api.internal:443") never widen to bare all-ports ("api.internal"), wildcard "*" never materializes explicit loopback/RFC1918/metadata grants ("127.0.0.1:6379"), and allow_private_networks (default false) can only narrow monotonically (parent && child).
    • verify_exec_binary and exec_binary_matches gate node:child_process (__slice_child_process_spawn_sync in bindings/child_process.rs) against allowed_exec_binaries (--allow-exec, SLICE_ALLOW_EXEC, [capabilities] allow_exec), blocking unlisted binaries and path-spoofed executables (/tmp/evil/git when /usr/bin/git is granted) with catchable ERR_SLICE_EXEC_DENIED (OCap Violation: lacks exec authority for binary '<binary>', recorded in deniedCapabilities, promoted to SandboxViolation::ExecDenied if uncaught), sanitizing child environments via Command::env_clear() to only BOA_ENV_MAP, and scanning child stdout/stderr through verify_egress_secrets_slice.
    • Enforced across both Tier-0 SLICESNP (BytecodeOp::VfsRead) and Tier-1 SLICEBC\x01/SLICEBOA native node:fs and node:child_process host functions. All OCap refusal messages omit host compartment names (SandboxViolation::Display uses OCap Violation: lacks <kind> authority for <target>, while SandboxViolation::tenant_id() preserves host-side telemetry).
  3. Ring 3 - Outbound Network Allowlisting (NetCap) & Pre-Connect DNS Resolved-IP SSRF Firewall:
    • verify_net_connect parses host[:port] or URL authorities in a single pass via parse_net_connect_target, rejecting percent-decoded delimiters/control bytes (%40, %2f, %00, %0d%0a), invalid or :0 ports, and leading-zero non-octal IPv4 (127.0.0.08, 0169.0254.0169.0254) while blocking ungranted hosts/ports with catchable ERR_SLICE_NET_DENIED (SandboxViolation::NetAccessDenied).
    • resolve_and_verify_ssrf_socket_addrs resolves DNS once before connecting across fetch(), redirects, WebSocket, TCP/TLS sockets, and UDP, inspecting every resolved IPv4, IPv6, and IPv6-embedded IPv4 address against is_cloud_metadata_ip (unconditionally blocked) and is_private_or_loopback_ip (blocked for all DNS hostnames by default, whether explicitly granted or wildcard *, unless allow_private_networks = true or explicit literal IP / localhost loopback), defeating DNS-rebinding SSRF attacks.
  4. Ring 4 - Scoped Environment Capabilities (EnvCap), .env Auto-DLP, & aho-corasick Outbound Egress Secret DLP Firewall:
    • verify_env_read isolates tenant secrets in an explicit per-compartment key-value map (SandboxViolation::EnvAccessDenied).
    • When --env-file=.env is loaded via config/mod.rs, is_sensitive_env_key automatically classifies keys matching SECRET, PRIVATE, PASSWORD, PASSWD, CREDENTIAL, TOKEN, KEY, or AUTH (excluding standalone PUBLIC_KEY / PUBLISHABLE_KEY unless paired with SECRET/PRIVATE) as egress-protected secrets.
    • verify_egress_secrets_slice scans stdout, returnValue, HTTP response bodies, SSE chunks, outbound fetch() URLs/headers/bodies, WebSocket frames, subprocess stdio, and raw TCP/UDP payloads in a single O(payload) pass using a cached aho-corasick automaton covering raw, lowercase/uppercase hex, encodeURIComponent/percent-encoded, padded/unpadded Base64 & Base64URL, and all 3 Base64 byte-alignment (offset = 0, 1, 2) interior slices, trapping with SandboxViolation::EgressSecretLeakBlocked (0.00 ns cost when no secrets are registered).
  5. Ring 5 - Deterministic CPU Fuel & Memory Cage + Linux x86_64 WRPKRU Protection-Key Scaffolding:
    • Every operation deducts instruction fuel (consume_fuel) and tracks heap bytes (alloc_memory), preempting infinite while (true) {} loops in < 10 us (SandboxViolation::CpuFuelExhausted).
    • Before evaluating code in SliceIsolate::exec_boa_full_es_vm, Slice configures realm.ctx.runtime_limits_mut().set_loop_iteration_limit(remaining_fuel) and set_recursion_limit(512), translating loop or call-stack exhaustion inside Boa directly into SandboxViolation::CpuFuelExhausted.
    • On PKU-capable Linux x86_64 hosts, HardwareProtectionDomain allocates kernel protection keys (1..=15) via SYS_pkey_alloc (syscall 330) and switches the per-thread PKRU register in < 20 CPU cycles using WRPKRU (note: SYS_pkey_mprotect page tagging is not yet wired to tenant heap slabs; see Section 3 below).

2. Untrusted Entrypoint & AI Code-Mode Directive Lockdown (// @slice-*)

Section titled “2. Untrusted Entrypoint & AI Code-Mode Directive Lockdown (// @slice-*)”

Implemented in ResolvedExecutionConfig::apply_inline_directives and SliceManifest:

  • Default Monotonic Attenuation (trust_directives == false): By default, top-of-file // @slice-* source directives parsed by parse_inline_directives cannot escalate privileges when executing untrusted or AI-generated entrypoints (slice run agent_script.ts):
    • fuel, memory_bytes, and max_checkpoints are clamped via .min(...), and allow_checkpoints can only disable (false) guest checkpoints, never re-enable them once disabled by host configuration.
    • allow_read, allow_write, allow_net, allow_exec, and allow_env are strictly intersected against existing host-granted capabilities in self.caps (slice_sandbox::vfs_prefix_matches for VFS prefixes, slice_sandbox::exec_binary_matches for subprocess binaries, wildcard/exact host matching for allowed_net_hosts, and existing key membership preserving host values for allowed_env_keys).
    • env_file, tls_cert, and tls_key inline directives are ignored unless trust_directives is true, while audit_egress remains always-additive.
  • Explicit Host Opt-In (--trust-directives / SLICE_TRUST_DIRECTIVES=1 / trust_directives = true): Only when the host explicitly enables trust_directives (via [capabilities] trust_directives = true in slice.toml, SLICE_TRUST_DIRECTIVES=1, or --trust-directives) do inline directives apply additively. Passing --no-directives or --untrusted bypasses apply_inline_directives altogether.
  • In-Process Slice.evalSandbox & slice mcp Immunity: SliceIsolate::eval_sandbox and slice_eval_ts never call apply_inline_directives, guaranteeing that embedded // @slice-allow-* or // @slice-fuel comments inside sandboxed code snippets have zero effect on child CapabilityToken or resource budgets.

3. HardwareProtectionDomain (compartment/pkey.rs) Implementation & Scope

Section titled “3. HardwareProtectionDomain (compartment/pkey.rs) Implementation & Scope”

HardwareProtectionDomain is a 12-byte #[repr(C)] RAII handle (pkey: i32, pkru_mask: u32, hardware_enforced: bool) embedded in every TenantCompartment:

  • Key Allocation & PKRU Bitmask (HardwareProtectionDomain::allocate):
    • On #[cfg(all(target_os = "linux", target_arch = "x86_64"))], invokes libc::syscall(330, 0usize, 0usize) (SYS_pkey_alloc). When the kernel returns pkey in 1..=15, computes pkru_mask = !(0b11u32 | (0b11u32 << (pkey * 2))) (leaving default kernel key 0 and pkey set to 0b00 read/write while setting all other keys 1..=15 to 0b11 PKEY_DISABLE_ACCESS | PKEY_DISABLE_WRITE) and sets hardware_enforced = true.
    • When SYS_pkey_alloc is unsupported (ENOSYS/EPERM), all 15 process-wide keys are occupied (ENOSPC), or on non-Linux-x86_64 targets (Windows, macOS, Linux aarch64 - ARM POE is not implemented), assigns a deterministic virtual slot ((tenant_slot % 15) + 1) with hardware_enforced = false.
  • Per-Thread Scoped Domain Switch (PkruDomainGuard), Warm Rebind & Unwind Cleanup:
    • enter_domain() reads the caller’s active PKRU (rdpkru on PKU hardware or thread-local virtual PKRU state elsewhere), writes the compartment’s pkru_mask (wrpkru), and returns a !Send #[must_use] PkruDomainGuard whose Drop restores the caller’s prior PKRU across nested Slice.evalSandbox / Worker domains and panic unwinds (isolate/mod.rs, isolate/exec_bytecode.rs, isolate/http_and_ws.rs).
    • Thread-local compartment session state (BoaSessionUnwindGuard in exec_boa.rs, ActiveHttpReqGuard in http_and_ws.rs, and WorkerTurnUnwindGuard in workers.rs) is likewise guarded by Drop RAII wrappers so std::panic::catch_unwind on server/MCP/worker threads scrubs all active OCap grants, HTTP headers/bodies, and GLOBAL_ACTIVE_WORKERS slots before another tenant runs.
    • rebind_slot(slot_id) preserves an already-allocated hardware key across warm SliceIsolate::reset_for_request cycles without SYS_pkey_free / SYS_pkey_alloc syscall churn.
    • Clone allocates a fresh independent key when hardware_enforced is true; Drop calls libc::syscall(331, pkey) (SYS_pkey_free) when the compartment owns a hardware key without clobbering any active outer PKRU domain.
  • Current Page-Tagging Boundary (SYS_pkey_mprotect Not Yet Wired):
    • No call sites in crates/ currently invoke SYS_pkey_mprotect (syscall 329) to move Boa GC arenas, wasmi linear memories, EDGE_KV_SLAB, or VFS buffers off default key 0. On OSPKE-enabled Linux x86_64 hosts (CPUID.07H:ECX.OSPKE), HardwareProtectionDomain::allocate saves and immediately restores the calling thread’s PKRU register across SYS_pkey_alloc(0, PKEY_DISABLE_ACCESS | PKEY_DISABLE_WRITE) so nested compartment creation never alters an active outer PKRU mask before enter_domain(). All runtime memory isolation and --memory ceiling enforcement today is provided by safe-Rust bounds checking, SES realm lockdown, OCap capability verification, and byte-level budget tracking (BOA_KV_MEM_BUDGET + SliceWasmLimiter), with HardwareProtectionDomain serving as verified PKRU register-switch groundwork and exposing hardware_enforced in slice doctor and to Rust embedders.