# CAIN-42 Sovereign Extension Containment: Architecture & Trust Boundaries

**Document Reference:** `CAIN42-ARCH-SOVEREIGN-EXT-v1`  
**Classification:** Runtime Specification  
**Status:** VALIDATED  

---

## 1. Architectural Overview

The **CAIN-42 Sovereign Extension Containment Architecture** is partitioned into three complementary vectors operating in unison:

```mermaid
flowchart TD
    subgraph Vector3["VECTOR 3: Local Governance & Policy Plane"]
        MasterKey["Customer Offline Ed25519 Master Key"] -->|Signs Policy| PolFile["SovereignLocalPolicy (current_policy.json)"]
        PolFile --> SyncDaemon["SovereignSyncDaemon"]
        SyncDaemon -->|Maintains| Ledger["SovereignAuditLedger (SQLite WAL)"]
        SyncDaemon -->|Enforces| OffWindow["Bounded Offline Validity (< max_offline_hours)"]
        SyncDaemon -->|Programs| NetRules["Allowlist & DNS Pinning Rules"]
    end

    subgraph Vector2["VECTOR 2: Kernel eBPF Sentinel"]
        NetRules -->|Updates BPF Maps| Sentinel["CainPluginSentinel (cain_plugin_sentinel.bpf.o)"]
        Sentinel -->|Pins Maps & Filter| BpfFS["/sys/fs/bpf/cain_sentinel_*"]
        Sentinel -->|Attaches Hook| CgroupHook["cgroup_skb/egress (Drops Unauthorized Packets)"]
        Sentinel -->|Telemetry Ringbuf| RingBufMap["cain_sentinel_ringbuf (4MB)"]
        TraceConnect["tracepoint: sys_enter_connect"] -.->|Audit Observability| RingBufMap
        TraceOpenat["tracepoint: sys_enter_openat"] -.->|Audit Observability| RingBufMap
    end

    subgraph Vector1["VECTOR 1: Extension Hypervisor Execution Boundary"]
        SyncDaemon -->|Validates Manifest| Hyp["CainExtensionHypervisor"]
        Hyp -->|Wasm Mode| WasmEngine["Wasmedge / Wazero (Capability Restricted)"]
        Hyp -->|Native Mode| Bwrap["Bubblewrap Linux Sandbox (bwrap)"]
        
        subgraph ContainerIsolation["Sandboxed Container Perimeters"]
            Bwrap --> NS["Linux Namespaces (User, Net, PID, IPC, UTS)"]
            Bwrap --> RO["Read-Only Filesystem (--remount-ro /)"]
            Bwrap --> SecFilter["Seccomp-BPF Filter (Blocks 17 Dangerous Syscalls)"]
            Bwrap --> CgLimits["Cgroup v2 Resource Ceilings (memory.max, pids.max)"]
            Bwrap --> ProcessReaper["Process-Tree Cleanup (--die-with-parent, killpg)"]
        end
    end

    Hyp -->|Generates| Receipt["Ed25519 Signed Execution Receipt"]
    Receipt -->|Logged to| Ledger
```

---

## 2. Vector 1: Sovereign Extension Hypervisor (`cain_extension_hypervisor.py`)

### 2.1 Execution Modes
1. **WebAssembly (WASM):** For compatible modules, executed using `wasmedge` or `wazero`. Capabilities (memory, CPU fuel, IO size limits, execution deadlines) are enforced before and during execution.
2. **Native Container Sandbox (NATIVE_SANDBOX):** For native binaries, scripts, and MCP plugin servers, executed using Bubblewrap (`/usr/bin/bwrap`).

### 2.2 Security Invariants Enforced by the Hypervisor
- **Invariant I1 (Zero Unsandboxed Execution):** If neither Wasm nor Bubblewrap is available, or if entrypoints fail validation, execution is REFUSED. The hypervisor NEVER executes code directly on the host.
- **Invariant I2 (User Namespace & Dedicated Identity):** Container processes run mapped to `UID 65534` / `GID 65534` (`nobody`). `PR_SET_NO_NEW_PRIVS` is set before execve, preventing privilege escalation.
- **Invariant I3 (Read-Only Root Filesystem):** System directories (`/usr`, `/bin`, `/lib`, `/lib64`, `/etc`) are mounted read-only. As the final mount layout step, `--remount-ro /` is applied, guaranteeing that unauthorized writes to system directories fail with `EROFS` (Read-only file system). Only the isolated ephemeral workspace (`/workspace`) and memory tmpfs (`/tmp`) are writable.
- **Invariant I4 (Seccomp-BPF Syscall Filter):** A compiled Seccomp-BPF program is loaded via `--seccomp <fd>` blocking 17 high-risk syscalls:
  - Process tracing / inspection: `ptrace` (101)
  - Filesystem manipulation: `pivot_root` (155), `mount` (165), `umount2` (166)
  - Namespace creation: `unshare` (272), `setns` (308)
  - Kernel & driver modification: `init_module` (175), `delete_module` (176), `finit_module` (313), `kexec_load` (246), `bpf` (321)
  - Performance & security subsystem: `perf_event_open` (298), `keyctl` (250), `reboot` (169)
  - Asynchronous ring buffer exploits: `io_uring_setup` (425), `io_uring_enter` (426), `io_uring_register` (427)
  All blocked syscalls immediately return `-EPERM` (errno 1).
- **Invariant I5 (Resource Ceilings & Fork Bomb Defense):**
  - Cgroup v2 limits: `memory.max` (e.g. 128 MB) and `pids.max` (e.g. 16 PIDs).
  - POSIX resource limits (`RLIMIT_AS`, `RLIMIT_NPROC`, `RLIMIT_CPU`) applied as defence-in-depth backstop.
- **Invariant I6 (Process-Tree Destruction):**
  - `bwrap --die-with-parent` ensures the container dies if the parent exits.
  - Subprocess setup configures `prctl(PR_SET_PDEATHSIG, SIGKILL)`.
  - On timeout or termination, the hypervisor triggers `cgroup.kill` and sends `SIGKILL` to the entire process group via `os.killpg()`, preventing orphan or zombie sleeper processes.
- **Invariant I7 (Bounded IO):**
  - Inputs exceeding `max_input_bytes` raise `ExtensionCapabilityViolation` prior to execution.
  - Outputs exceeding `max_output_bytes` are truncated, and `OUTPUT_LIMIT_EXCEEDED` is recorded in the execution receipt.

---

## 3. Vector 2: Kernel eBPF Plugin Sentinel (`cain_plugin_sentinel.bpf.c`)

### 3.1 Kernel Boundary Enforcement
- **Attachment Point:** `SEC("cgroup_skb/egress")` attached to the extension's target cgroup directory.
- **Packet Verdict:**
  - IPv4 packets are inspected at the IP header boundary.
  - Loopback (`127.0.0.0/8`) is allowed.
  - Non-loopback destinations are checked against the BPF hash map `cain_allowed_ipv4`.
  - Non-allowlisted packets are DROPPED (`return CAIN_VERDICT_DROP`), triggering `EPERM` (errno 1) at the sender's syscall boundary, and an audit event is submitted to the eBPF ring buffer.
  - IPv6 egress is default-denied in sovereign mode.
- **Observation Tracepoints:**
  - `SEC("tracepoint/syscalls/sys_enter_connect")` and `SEC("tracepoint/syscalls/sys_enter_openat")` provide high-throughput kernel audit observability into `cain_sentinel_ringbuf`.
  - In strict compliance with Linux kernel safety invariants, tracepoints are strictly used for observation/telemetry and never for imaginary syscall-return overrides.
- **Fail-Closed Loader:**
  - Inspects kernel capabilities (`cgroup2`, `bpf_fs`, `clang`, `bpftool`, `btf`).
  - If mandatory prerequisites are missing, `load(fail_closed=True)` raises `KernelRequirementsError` and refuses to start without boundary enforcement.

---

## 4. Vector 3: Sovereign Sync Daemon (`sovereign_sync_daemon.py`)

### 4.1 Cryptographic Policy Schema & Anti-Rollback
- **Policy Envelope:** Contains `policy_id`, `version`, `tenant_id`, `valid_from_utc`, `valid_until_utc`, `max_offline_hours`, `destinations`, `pinned_hosts`, `revoked_extensions`, `revoked_keys`.
- **Ed25519 Signature:** Verified using canonical RFC 8785 JSON serialization (`cain45.canon`).
- **Anti-Rollback:** Policy version must strictly exceed the active version ($\text{version}_{\text{new}} > \text{version}_{\text{current}}$).

### 4.2 Bounded Offline Operation
- **Offline Ceiling:** If $(t_{\text{current}} - t_{\text{last\_sync}}) > \text{max\_offline\_hours}$, the daemon enters `DaemonState.EXPIRED_HALT` and logs `OFFLINE_HALT`.
- **Temporal Window:** If $t_{\text{current}} > \text{valid\_until\_utc}$, the daemon halts.
- **Admissibility Gate:** In `EXPIRED_HALT`, `REVOKED_HALT`, or `CORRUPTION_HALT`, all extension admissibility checks return `(False, reason)` fail-closed.

### 4.3 Durable Tamper-Evident Local Audit Trail
- **Substrate:** SQLite database in Write-Ahead Logging mode (`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;`).
- **Cryptographic Hash Chaining:**
  $$H_k = \text{SHA256}(H_{k-1} \parallel \text{canon}(\text{Event}_k))$$
- **Checkpoint Attestation:** Periodically produces Ed25519-signed checkpoints binding the block sequence and block hash.
- **Restart Verification:** Upon service startup or recovery, `verify_integrity()` walks the chain from genesis ($H_0 = 0^{64}$) to head. Any byte alteration or row deletion raises `AuditLogTamperingError` and halts operation.

### 4.4 Network & Proxy Protection
- **Proxy Scrubbing:** Detects and strips `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, `FTP_PROXY`, and `NO_PROXY` environment variables to prevent accidental or malicious traffic redirection.
- **Host Pinning:** Enforces domain-to-IP mapping (`pinned_hosts`) to mitigate DNS rebinding attacks.
