Skip to main content

keel_enforce/
local_process.rs

1//! `local-process` backend: Landlock (Linux) / Seatbelt (macOS) via nono.
2//!
3//! ## Default semantics (`isolate_apply = true`)
4//!
5//! - Host process is **not** sandboxed.
6//! - On `spawn`, the child applies the kernel sandbox in `pre_exec` (after fork).
7//! - On Linux, deny paths are enforced with **bubblewrap** bind-over (read-deny).
8//! - Parent keeps network for LLM/MCP.
9//! - `DenyAll`: child net blocked (kernel Blocked / Linux seccomp).
10//! - `Allowlist`: parent runs a localhost CONNECT proxy; children get proxy env
11//!   and kernel `ProxyOnly` so they may only dial the proxy port.
12//!
13//! ## Legacy (`isolate_apply = false`)
14//!
15//! - `apply()` sandboxes the **current** process (irreversible, one policy per process).
16
17use crate::backend::{base_command, BackendInfo, EnforceBackend, SpawnRequest, SpawnedProcess};
18use crate::error::{EnforceError, EnforceResult};
19use crate::process_guard;
20use async_trait::async_trait;
21use chrono::Utc;
22use keel_policy::{ExecPolicy, NetworkPolicy, Policy, SpaceId};
23use keel_record::{EventKind, RecordEvent, RecordSink};
24use std::path::Path;
25use std::sync::atomic::{AtomicBool, Ordering};
26use std::sync::{Arc, OnceLock};
27use tracing::{info, warn};
28
29#[cfg(all(unix, feature = "kernel"))]
30use crate::sandbox_child;
31
32/// Process-global: policy id when host-applied (isolate_apply = false only).
33static KERNEL_APPLIED_POLICY: OnceLock<String> = OnceLock::new();
34
35/// Options for [`LocalProcessBackend`].
36#[derive(Debug, Clone)]
37pub struct LocalProcessOptions {
38    /// Fail if the platform cannot enforce kernel FS (default true).
39    pub require_kernel: bool,
40    /// Block network for the sandboxed process via nono (default false).
41    pub block_process_network: bool,
42    /// If true (default), apply kernel sandbox only in children, not the host.
43    pub isolate_apply: bool,
44}
45
46impl Default for LocalProcessOptions {
47    fn default() -> Self {
48        Self {
49            require_kernel: true,
50            block_process_network: false,
51            isolate_apply: true,
52        }
53    }
54}
55
56/// Landlock / Seatbelt enforce backend.
57pub struct LocalProcessBackend {
58    opts: LocalProcessOptions,
59    applied: AtomicBool,
60    restrict_child_net: AtomicBool,
61    /// Active egress proxy when policy is an allowlist.
62    egress: tokio::sync::Mutex<Option<Arc<crate::egress_proxy::EgressProxy>>>,
63}
64
65impl LocalProcessBackend {
66    pub fn new() -> Self {
67        Self::with_options(LocalProcessOptions::default())
68    }
69
70    pub fn with_options(opts: LocalProcessOptions) -> Self {
71        Self {
72            opts,
73            applied: AtomicBool::new(false),
74            restrict_child_net: AtomicBool::new(false),
75            egress: tokio::sync::Mutex::new(None),
76        }
77    }
78
79    pub fn process_has_kernel_sandbox() -> bool {
80        KERNEL_APPLIED_POLICY.get().is_some()
81    }
82
83    pub fn is_applied(&self) -> bool {
84        self.applied.load(Ordering::Acquire)
85    }
86
87    pub fn restricts_child_network(&self) -> bool {
88        self.restrict_child_net.load(Ordering::Acquire)
89    }
90
91    pub fn options(&self) -> &LocalProcessOptions {
92        &self.opts
93    }
94}
95
96impl Default for LocalProcessBackend {
97    fn default() -> Self {
98        Self::new()
99    }
100}
101
102#[async_trait]
103impl EnforceBackend for LocalProcessBackend {
104    fn info(&self) -> BackendInfo {
105        BackendInfo {
106            name: "local-process",
107            kernel_fs: cfg!(all(
108                feature = "kernel",
109                any(target_os = "linux", target_os = "macos")
110            )),
111            child_network: cfg!(target_os = "linux"),
112        }
113    }
114
115    async fn apply(&self, policy: &Policy, sink: Arc<dyn RecordSink>) -> EnforceResult<()> {
116        if policy.is_expired(Utc::now()) {
117            return Err(EnforceError::PolicyExpired);
118        }
119        policy.validate()?;
120
121        #[cfg(all(unix, feature = "kernel"))]
122        {
123            if self.opts.isolate_apply {
124                return self.apply_isolated_prepare(policy, sink).await;
125            }
126            return self.apply_on_host(policy, sink).await;
127        }
128
129        #[cfg(not(all(unix, feature = "kernel")))]
130        {
131            let msg = "local-process kernel backend requires unix + feature `kernel`";
132            if self.opts.require_kernel {
133                return Err(EnforceError::Unsupported(msg.into()));
134            }
135            warn!("{msg}; soft process-guard only");
136            let _ = sink;
137            self.applied.store(true, Ordering::Release);
138            Ok(())
139        }
140    }
141
142    async fn check_fs(&self, policy: &Policy, path: &Path, write: bool) -> EnforceResult<bool> {
143        Ok(process_guard::soft_fs_allowed(policy, path, write))
144    }
145
146    async fn spawn(
147        &self,
148        space_id: &SpaceId,
149        policy: &Policy,
150        req: SpawnRequest,
151        sink: Arc<dyn RecordSink>,
152    ) -> EnforceResult<SpawnedProcess> {
153        if policy.is_expired(Utc::now()) {
154            return Err(EnforceError::PolicyExpired);
155        }
156        if matches!(policy.exec, ExecPolicy::Deny) {
157            let _ = sink
158                .emit(RecordEvent::new(
159                    space_id.clone(),
160                    policy.id.clone(),
161                    policy.task_id.clone(),
162                    EventKind::Exec {
163                        program: req.program.clone(),
164                        args: req.args.clone(),
165                        allowed: false,
166                    },
167                ))
168                .await;
169            return Err(EnforceError::Denied("exec denied by policy".into()));
170        }
171
172        if let Some(cwd) = &req.cwd {
173            if !process_guard::soft_fs_allowed(policy, cwd, false) {
174                return Err(EnforceError::Denied(format!(
175                    "cwd not allowed: {}",
176                    cwd.display()
177                )));
178            }
179        }
180
181        let _ = sink
182            .emit(RecordEvent::new(
183                space_id.clone(),
184                policy.id.clone(),
185                policy.task_id.clone(),
186                EventKind::Exec {
187                    program: req.program.clone(),
188                    args: req.args.clone(),
189                    allowed: true,
190                },
191            ))
192            .await;
193
194        #[cfg(all(unix, feature = "kernel"))]
195        {
196            return self.spawn_sandboxed(policy, req).await;
197        }
198
199        #[cfg(not(all(unix, feature = "kernel")))]
200        {
201            let mut cmd = base_command(&req);
202            let child = cmd.spawn()?;
203            Ok(SpawnedProcess { child })
204        }
205    }
206
207    async fn destroy(&self, _policy: &Policy, _sink: Arc<dyn RecordSink>) -> EnforceResult<()> {
208        let mut guard = self.egress.lock().await;
209        if let Some(proxy) = guard.take() {
210            proxy.shutdown();
211        }
212        Ok(())
213    }
214}
215
216#[cfg(all(unix, feature = "kernel"))]
217impl LocalProcessBackend {
218    /// Prepare only: validate mapping; start egress proxy for allowlists.
219    async fn apply_isolated_prepare(
220        &self,
221        policy: &Policy,
222        sink: Arc<dyn RecordSink>,
223    ) -> EnforceResult<()> {
224        // Start egress proxy before prepare_kernel so ProxyOnly port can be known
225        // at spawn time (injected via env for child pre_exec).
226        let mut egress_note = String::new();
227        if matches!(policy.network, NetworkPolicy::Allowlist(_)) {
228            let proxy =
229                crate::egress_proxy::EgressProxy::start(policy.network.clone()).await?;
230            egress_note = format!("egress proxy on {}", proxy.proxy_url());
231            info!(%egress_note, "started egress allowlist proxy");
232            *self.egress.lock().await = Some(Arc::new(proxy));
233        }
234
235        // prepare_kernel without proxy env still validates FS mapping.
236        match sandbox_child::prepare_kernel(policy, self.opts.block_process_network) {
237            Ok(()) => {}
238            Err(e) if !self.opts.require_kernel => {
239                warn!(error = %e, "kernel prepare failed; children will soft-check only");
240                self.applied.store(true, Ordering::Release);
241                return Ok(());
242            }
243            Err(e) => return Err(e),
244        }
245
246        #[cfg(target_os = "linux")]
247        {
248            let mut denies = crate::bwrap::deny_paths_for_bwrap(policy);
249            if let Ok(extra) = crate::deny_glob::expand_deny_globs(policy) {
250                denies.extend(extra);
251            }
252            if !denies.is_empty() && !crate::bwrap::bwrap_available() {
253                let msg = "Linux read-deny requires bubblewrap (bwrap); install it or clear deny paths";
254                if self.opts.require_kernel {
255                    return Err(EnforceError::ApplyFailed(msg.into()));
256                }
257                warn!("{msg}");
258            }
259        }
260
261        // DenyAll → block child net at kernel/seccomp. Allowlist uses ProxyOnly instead.
262        if matches!(policy.network, NetworkPolicy::DenyAll) || self.opts.block_process_network {
263            self.restrict_child_net.store(true, Ordering::Release);
264        }
265        self.applied.store(true, Ordering::Release);
266        info!(
267            policy_id = %policy.id,
268            isolate = true,
269            "local-process ready (kernel apply deferred to children)"
270        );
271        let msg = if egress_note.is_empty() {
272            "local-process isolate_apply: host unsandboxed; children apply kernel FS".into()
273        } else {
274            format!(
275                "local-process isolate_apply: host unsandboxed; children apply kernel FS; {egress_note}"
276            )
277        };
278        let _ = sink
279            .emit(RecordEvent::new(
280                SpaceId::from_string("pending"),
281                policy.id.clone(),
282                policy.task_id.clone(),
283                EventKind::Note { message: msg },
284            ))
285            .await;
286        Ok(())
287    }
288
289    /// Legacy: sandbox the host process.
290    async fn apply_on_host(
291        &self,
292        policy: &Policy,
293        sink: Arc<dyn RecordSink>,
294    ) -> EnforceResult<()> {
295        use nono::Sandbox;
296
297        let support = Sandbox::support_info();
298        if !support.is_supported {
299            let details = support.details.clone();
300            if self.opts.require_kernel {
301                return Err(EnforceError::Unsupported(details));
302            }
303            warn!(details = %details, "kernel sandbox unsupported; soft-only");
304            self.applied.store(true, Ordering::Release);
305            return Ok(());
306        }
307
308        if let Some(existing) = KERNEL_APPLIED_POLICY.get() {
309            if existing != policy.id.as_str() {
310                return Err(EnforceError::AlreadyApplied {
311                    applied: existing.clone(),
312                    requested: policy.id.to_string(),
313                });
314            }
315            self.applied.store(true, Ordering::Release);
316            return Ok(());
317        }
318
319        sandbox_child::apply_kernel_here(policy, self.opts.block_process_network)?;
320        let _ = KERNEL_APPLIED_POLICY.set(policy.id.to_string());
321        self.applied.store(true, Ordering::Release);
322        if matches!(policy.network, NetworkPolicy::DenyAll) || self.opts.block_process_network {
323            self.restrict_child_net.store(true, Ordering::Release);
324        }
325        let _ = sink
326            .emit(RecordEvent::new(
327                SpaceId::from_string("pending"),
328                policy.id.clone(),
329                policy.task_id.clone(),
330                EventKind::Note {
331                    message: format!(
332                        "kernel sandbox applied on host via nono ({})",
333                        support.platform
334                    ),
335                },
336            ))
337            .await;
338        Ok(())
339    }
340
341    async fn spawn_sandboxed(
342        &self,
343        policy: &Policy,
344        mut req: SpawnRequest,
345    ) -> EnforceResult<SpawnedProcess> {
346        // Full block only for DenyAll; allowlist uses ProxyOnly + CONNECT proxy.
347        let restrict_net = self.restrict_child_net.load(Ordering::Acquire)
348            || matches!(policy.network, NetworkPolicy::DenyAll);
349        let isolate = self.opts.isolate_apply;
350        let block_net = self.opts.block_process_network;
351        let require_kernel = self.opts.require_kernel;
352
353        // Inject egress proxy env for allowlisted spaces (proxy-aware tools).
354        let proxy_port = {
355            let guard = self.egress.lock().await;
356            if let Some(proxy) = guard.as_ref() {
357                for (k, v) in proxy.env_vars() {
358                    if !req.env.iter().any(|(ek, _)| ek == &k) {
359                        req.env.push((k, v));
360                    }
361                }
362                Some(proxy.port())
363            } else {
364                None
365            }
366        };
367
368        // Validate mapping early (parent).
369        if isolate {
370            if let Err(e) = sandbox_child::prepare_kernel(policy, block_net) {
371                if require_kernel {
372                    return Err(e);
373                }
374                warn!(error = %e, "spawn without kernel apply");
375            }
376        }
377
378        let policy_file = if isolate {
379            Some(sandbox_child::write_spawn_policy_file(policy)?)
380        } else {
381            None
382        };
383
384        // Prefer bwrap outer command when Linux deny paths exist.
385        #[cfg(target_os = "linux")]
386        let mut cmd = {
387            let mut deny_paths = crate::bwrap::deny_paths_for_bwrap(policy);
388            // Phase 2: expand deny globs into concrete paths for bwrap.
389            match crate::deny_glob::expand_deny_globs(policy) {
390                Ok(extra) => deny_paths.extend(extra),
391                Err(e) if require_kernel => return Err(e),
392                Err(e) => warn!(error = %e, "deny glob expand failed"),
393            }
394            deny_paths.sort();
395            deny_paths.dedup();
396            if let Some(mut bwrap_cmd) = crate::bwrap::wrap_command(
397                &req.program,
398                &req.args,
399                &deny_paths,
400                req.cwd.as_deref(),
401                &req.env,
402            )? {
403                bwrap_cmd
404                    .stdin(std::process::Stdio::null())
405                    .stdout(std::process::Stdio::piped())
406                    .stderr(std::process::Stdio::piped());
407                let mut cmd = tokio::process::Command::from(bwrap_cmd);
408                attach_child_hooks(
409                    &mut cmd,
410                    isolate,
411                    policy_file.clone(),
412                    block_net,
413                    restrict_net,
414                    proxy_port,
415                );
416                cmd
417            } else {
418                let mut cmd = base_command(&req);
419                attach_child_hooks(
420                    &mut cmd,
421                    isolate,
422                    policy_file.clone(),
423                    block_net,
424                    restrict_net,
425                    proxy_port,
426                );
427                cmd
428            }
429        };
430        #[cfg(not(target_os = "linux"))]
431        let mut cmd = {
432            let mut cmd = base_command(&req);
433            attach_child_hooks(
434                &mut cmd,
435                isolate,
436                policy_file.clone(),
437                block_net,
438                restrict_net,
439                proxy_port,
440            );
441            cmd
442        };
443
444        let child = cmd.spawn().map_err(|e| {
445            if let Some(pf) = &policy_file {
446                let _ = std::fs::remove_file(pf);
447            }
448            e
449        })?;
450
451        Ok(SpawnedProcess { child })
452    }
453}
454
455#[cfg(all(unix, feature = "kernel"))]
456fn attach_child_hooks(
457    cmd: &mut tokio::process::Command,
458    isolate: bool,
459    policy_file: Option<std::path::PathBuf>,
460    block_net: bool,
461    restrict_net: bool,
462    proxy_port: Option<u16>,
463) {
464    // tokio::process::Command::pre_exec requires the Unix CommandExt trait.
465    #[allow(unused_imports)]
466    use std::os::unix::process::CommandExt as _;
467    if isolate {
468        if let Some(pf) = policy_file {
469            unsafe {
470                cmd.pre_exec(move || {
471                    if let Some(port) = proxy_port {
472                        // SAFETY: child-only; configures ProxyOnly for apply_kernel_here.
473                        std::env::set_var(
474                            crate::egress_proxy::EGRESS_PROXY_PORT_ENV,
475                            port.to_string(),
476                        );
477                    }
478                    match sandbox_child::apply_policy_file_and_ready(&pf, block_net) {
479                        Ok(_) => {}
480                        Err(e) => return Err(std::io::Error::other(e.to_string())),
481                    }
482                    // DenyAll still uses coarse seccomp; allowlist relies on ProxyOnly.
483                    if restrict_net {
484                        crate::child_net::install_child_network_filter()?;
485                    }
486                    let _ = std::fs::remove_file(&pf);
487                    Ok(())
488                });
489            }
490        }
491    } else if restrict_net {
492        #[cfg(target_os = "linux")]
493        unsafe {
494            cmd.pre_exec(|| crate::child_net::install_child_network_filter());
495        }
496        #[cfg(not(target_os = "linux"))]
497        let _ = restrict_net;
498    }
499}
500
501#[cfg(test)]
502mod tests {
503    use super::*;
504    use keel_policy::profile_workspace;
505    use keel_record::MemorySink;
506    use std::sync::Arc;
507
508    #[tokio::test]
509    async fn isolate_prepare_does_not_mark_host_kernel() {
510        let dir = tempfile::tempdir().unwrap();
511        let policy = profile_workspace(dir.path()).unwrap();
512        let sink = Arc::new(MemorySink::new());
513        let backend = LocalProcessBackend::new(); // isolate_apply default true
514        // On macOS/Linux with kernel support this succeeds without host apply.
515        let result = backend.apply(&policy, sink).await;
516        // May fail on unsupported platforms in CI — only assert structure when ok.
517        if result.is_ok() {
518            assert!(backend.is_applied());
519            // Host should not have KERNEL_APPLIED_POLICY set in isolate mode.
520            assert!(!LocalProcessBackend::process_has_kernel_sandbox());
521        }
522    }
523
524    #[tokio::test]
525    async fn maps_and_reports_info() {
526        let b = LocalProcessBackend::new();
527        assert_eq!(b.info().name, "local-process");
528        assert!(b.options().isolate_apply);
529    }
530
531    /// Host apply path — only when explicitly requested.
532    #[tokio::test]
533    async fn optional_host_kernel_apply_smoke() {
534        if std::env::var("KEEL_KERNEL_TEST").ok().as_deref() != Some("1") {
535            return;
536        }
537        let dir = tempfile::tempdir().unwrap();
538        let policy = profile_workspace(dir.path()).unwrap();
539        let sink = Arc::new(MemorySink::new());
540        let backend = LocalProcessBackend::with_options(LocalProcessOptions {
541            require_kernel: true,
542            block_process_network: false,
543            isolate_apply: false,
544        });
545        backend.apply(&policy, sink).await.unwrap();
546        assert!(backend.is_applied());
547        assert!(LocalProcessBackend::process_has_kernel_sandbox());
548    }
549}