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. The Five Concentric Containment Rings
Section titled “1. The Five Concentric Containment Rings”- 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,Uint8Arrayalongside their.prototypeobjects, plusReflect,JSON, andMath). Any mutation attempt immediately traps withSandboxViolation::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) aswritable: false, which causes standard CommonJS modules assigningChild.prototype.toString = ...to fail in strict mode (the ECMAScript specification “override mistake”). Slice solves this with a two-layer defense:- Unified Tier-0 & Tier-1 guards (
slice_sandbox::is_frozen_intrinsic) blocking direct property/index mutations,globalThis.*prefixes,Object.assign/Reflect.settargets, and routing destructuring/optional-chaining mutations under--tier=0to Tier-1Boa. - Post-evaluation runtime verification across both cold and warm (
__slice_rc) turns via native RustSesProtoSig = (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, andMath.random/Date.now/Promise.prototype.thentampering, quarantining any mutated or unnamed-tenant realm inBOA_CONTEXT_POOL, and trapping withSandboxViolation::IntrinsicMutationBlocked.
- Unified Tier-0 & Tier-1 guards (
- Protects all 29 core primordials (
- Ring 2 - Attenuated VFS Read/Write (
FsCap), Subprocess Binary (ExecCap), & CanonicalCapabilityToken::attenuate:verify_fs_readandverify_fs_writereject 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=/orTMP=C:\), and verify strict directory-boundary containment against pre-normalizedallowed_read_prefixes/allowed_write_prefixes.CapabilityToken::attenuateenforces a single monotonic narrowing lattice acrossSlice.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"), andallow_private_networks(defaultfalse) can only narrow monotonically (parent && child).verify_exec_binaryandexec_binary_matchesgatenode:child_process(__slice_child_process_spawn_syncinbindings/child_process.rs) againstallowed_exec_binaries(--allow-exec,SLICE_ALLOW_EXEC,[capabilities] allow_exec), blocking unlisted binaries and path-spoofed executables (/tmp/evil/gitwhen/usr/bin/gitis granted) with catchableERR_SLICE_EXEC_DENIED(OCap Violation: lacks exec authority for binary '<binary>', recorded indeniedCapabilities, promoted toSandboxViolation::ExecDeniedif uncaught), sanitizing child environments viaCommand::env_clear()to onlyBOA_ENV_MAP, and scanning childstdout/stderrthroughverify_egress_secrets_slice.- Enforced across both Tier-0
SLICESNP(BytecodeOp::VfsRead) and Tier-1SLICEBC\x01/SLICEBOAnativenode:fsandnode:child_processhost functions. All OCap refusal messages omit host compartment names (SandboxViolation::DisplayusesOCap Violation: lacks <kind> authority for <target>, whileSandboxViolation::tenant_id()preserves host-side telemetry).
- Ring 3 - Outbound Network Allowlisting (
NetCap) & Pre-Connect DNS Resolved-IP SSRF Firewall:verify_net_connectparseshost[:port]or URL authorities in a single pass viaparse_net_connect_target, rejecting percent-decoded delimiters/control bytes (%40,%2f,%00,%0d%0a), invalid or:0ports, and leading-zero non-octal IPv4 (127.0.0.08,0169.0254.0169.0254) while blocking ungranted hosts/ports with catchableERR_SLICE_NET_DENIED(SandboxViolation::NetAccessDenied).resolve_and_verify_ssrf_socket_addrsresolves DNS once before connecting acrossfetch(), redirects,WebSocket, TCP/TLS sockets, and UDP, inspecting every resolved IPv4, IPv6, and IPv6-embedded IPv4 address againstis_cloud_metadata_ip(unconditionally blocked) andis_private_or_loopback_ip(blocked for all DNS hostnames by default, whether explicitly granted or wildcard*, unlessallow_private_networks = trueor explicit literal IP /localhostloopback), defeating DNS-rebinding SSRF attacks.
- Ring 4 - Scoped Environment Capabilities (
EnvCap),.envAuto-DLP, &aho-corasickOutbound Egress Secret DLP Firewall:verify_env_readisolates tenant secrets in an explicit per-compartment key-value map (SandboxViolation::EnvAccessDenied).- When
--env-file=.envis loaded viaconfig/mod.rs,is_sensitive_env_keyautomatically classifies keys matchingSECRET,PRIVATE,PASSWORD,PASSWD,CREDENTIAL,TOKEN,KEY, orAUTH(excluding standalonePUBLIC_KEY/PUBLISHABLE_KEYunless paired withSECRET/PRIVATE) as egress-protected secrets. verify_egress_secrets_slicescansstdout,returnValue, HTTP response bodies, SSE chunks, outboundfetch()URLs/headers/bodies, WebSocket frames, subprocess stdio, and raw TCP/UDP payloads in a singleO(payload)pass using a cachedaho-corasickautomaton 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 withSandboxViolation::EgressSecretLeakBlocked(0.00 nscost when no secrets are registered).
- Ring 5 - Deterministic CPU Fuel & Memory Cage + Linux
x86_64WRPKRUProtection-Key Scaffolding:- Every operation deducts instruction fuel (
consume_fuel) and tracks heap bytes (alloc_memory), preempting infinitewhile (true) {}loops in< 10 us(SandboxViolation::CpuFuelExhausted). - Before evaluating code in
SliceIsolate::exec_boa_full_es_vm, Slice configuresrealm.ctx.runtime_limits_mut().set_loop_iteration_limit(remaining_fuel)andset_recursion_limit(512), translating loop or call-stack exhaustion insideBoadirectly intoSandboxViolation::CpuFuelExhausted. - On PKU-capable Linux
x86_64hosts,HardwareProtectionDomainallocates kernel protection keys (1..=15) viaSYS_pkey_alloc(syscall 330) and switches the per-threadPKRUregister in< 20CPU cycles usingWRPKRU(note:SYS_pkey_mprotectpage tagging is not yet wired to tenant heap slabs; see Section 3 below).
- Every operation deducts instruction fuel (
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 byparse_inline_directivescannot escalate privileges when executing untrusted or AI-generated entrypoints (slice run agent_script.ts):fuel,memory_bytes, andmax_checkpointsare clamped via.min(...), andallow_checkpointscan only disable (false) guest checkpoints, never re-enable them once disabled by host configuration.allow_read,allow_write,allow_net,allow_exec, andallow_envare strictly intersected against existing host-granted capabilities inself.caps(slice_sandbox::vfs_prefix_matchesfor VFS prefixes,slice_sandbox::exec_binary_matchesfor subprocess binaries, wildcard/exact host matching forallowed_net_hosts, and existing key membership preserving host values forallowed_env_keys).env_file,tls_cert, andtls_keyinline directives are ignored unlesstrust_directivesistrue, whileaudit_egressremains always-additive.
- Explicit Host Opt-In (
--trust-directives/SLICE_TRUST_DIRECTIVES=1/trust_directives = true): Only when the host explicitly enablestrust_directives(via[capabilities] trust_directives = trueinslice.toml,SLICE_TRUST_DIRECTIVES=1, or--trust-directives) do inline directives apply additively. Passing--no-directivesor--untrustedbypassesapply_inline_directivesaltogether. - In-Process
Slice.evalSandbox&slice mcpImmunity:SliceIsolate::eval_sandboxandslice_eval_tsnever callapply_inline_directives, guaranteeing that embedded// @slice-allow-*or// @slice-fuelcomments inside sandboxed code snippets have zero effect on childCapabilityTokenor 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 &
PKRUBitmask (HardwareProtectionDomain::allocate):- On
#[cfg(all(target_os = "linux", target_arch = "x86_64"))], invokeslibc::syscall(330, 0usize, 0usize)(SYS_pkey_alloc). When the kernel returnspkeyin1..=15, computespkru_mask = !(0b11u32 | (0b11u32 << (pkey * 2)))(leaving default kernel key0andpkeyset to0b00read/write while setting all other keys1..=15to0b11PKEY_DISABLE_ACCESS | PKEY_DISABLE_WRITE) and setshardware_enforced = true. - When
SYS_pkey_allocis unsupported (ENOSYS/EPERM), all 15 process-wide keys are occupied (ENOSPC), or on non-Linux-x86_64targets (Windows, macOS, Linuxaarch64- ARMPOEis not implemented), assigns a deterministic virtual slot((tenant_slot % 15) + 1)withhardware_enforced = false.
- On
- Per-Thread Scoped Domain Switch (
PkruDomainGuard), Warm Rebind & Unwind Cleanup:enter_domain()reads the caller’s activePKRU(rdpkruon PKU hardware or thread-local virtualPKRUstate elsewhere), writes the compartment’spkru_mask(wrpkru), and returns a!Send#[must_use] PkruDomainGuardwhoseDroprestores the caller’s priorPKRUacross nestedSlice.evalSandbox/Workerdomains and panic unwinds (isolate/mod.rs,isolate/exec_bytecode.rs,isolate/http_and_ws.rs).- Thread-local compartment session state (
BoaSessionUnwindGuardinexec_boa.rs,ActiveHttpReqGuardinhttp_and_ws.rs, andWorkerTurnUnwindGuardinworkers.rs) is likewise guarded byDropRAII wrappers sostd::panic::catch_unwindon server/MCP/worker threads scrubs all active OCap grants, HTTP headers/bodies, andGLOBAL_ACTIVE_WORKERSslots before another tenant runs. rebind_slot(slot_id)preserves an already-allocated hardware key across warmSliceIsolate::reset_for_requestcycles withoutSYS_pkey_free/SYS_pkey_allocsyscall churn.Cloneallocates a fresh independent key whenhardware_enforcedistrue;Dropcallslibc::syscall(331, pkey)(SYS_pkey_free) when the compartment owns a hardware key without clobbering any active outerPKRUdomain.
- Current Page-Tagging Boundary (
SYS_pkey_mprotectNot Yet Wired):- No call sites in
crates/currently invokeSYS_pkey_mprotect(syscall329) to moveBoaGC arenas,wasmilinear memories,EDGE_KV_SLAB, or VFS buffers off default key0. OnOSPKE-enabled Linuxx86_64hosts (CPUID.07H:ECX.OSPKE),HardwareProtectionDomain::allocatesaves and immediately restores the calling thread’sPKRUregister acrossSYS_pkey_alloc(0, PKEY_DISABLE_ACCESS | PKEY_DISABLE_WRITE)so nested compartment creation never alters an active outerPKRUmask beforeenter_domain(). All runtime memory isolation and--memoryceiling 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), withHardwareProtectionDomainserving as verifiedPKRUregister-switch groundwork and exposinghardware_enforcedinslice doctorand to Rust embedders.
- No call sites in