Skip to main content

keel_enforce/
process_guard.rs

1//! Soft process-level policy checks (no kernel). Used by all backends as a
2//! first line; kernel backends will fail closed even if this has bugs.
3
4use crate::backend::{base_command, BackendInfo, EnforceBackend, SpawnRequest, SpawnedProcess};
5use crate::error::{EnforceError, EnforceResult};
6use async_trait::async_trait;
7use chrono::Utc;
8use keel_policy::{ExecPolicy, FsAccess, NetworkPolicy, Policy, SpaceId};
9use keel_record::{EventKind, RecordEvent, RecordSink};
10use std::path::{Component, Path, PathBuf};
11use std::sync::Arc;
12use tracing::info;
13
14/// Normalize for prefix checks (best-effort; not a security boundary alone).
15pub fn normalize(path: &Path) -> PathBuf {
16    let mut out = PathBuf::new();
17    for c in path.components() {
18        match c {
19            Component::Prefix(p) => out.push(p.as_os_str()),
20            Component::RootDir => out.push(Component::RootDir.as_os_str()),
21            Component::CurDir => {}
22            Component::ParentDir => {
23                out.pop();
24            }
25            Component::Normal(s) => out.push(s),
26        }
27    }
28    out
29}
30
31/// Resolve `path` against the policy workspace when it is relative.
32fn resolve_against_workspace(policy: &Policy, path: &Path) -> PathBuf {
33    if path.is_absolute() {
34        normalize(path)
35    } else {
36        normalize(&policy.workspace.join(path))
37    }
38}
39
40/// Soft filesystem allow check.
41///
42/// Rules:
43/// - Any matching `Deny` (prefix or exact) → deny
44/// - Write requires a `ReadWrite` prefix match
45/// - Read allowed if `default_read` or any Read/ReadWrite prefix match
46///
47/// Relative paths are resolved against `policy.workspace`.
48pub fn soft_fs_allowed(policy: &Policy, path: &Path, write: bool) -> bool {
49    let path = resolve_against_workspace(policy, path);
50    let path_str = path.to_string_lossy();
51
52    for rule in policy.deny_paths() {
53        if rule.glob {
54            // v0: simple suffix / contains heuristics for `**/.env` style.
55            let pat = rule.path.to_string_lossy();
56            let leaf = pat.rsplit('/').next().unwrap_or("");
57            if leaf.starts_with('.') || leaf.contains('*') {
58                let cleaned = leaf.trim_start_matches('*').trim_start_matches('/');
59                if !cleaned.is_empty() && path_str.contains(cleaned) {
60                    return false;
61                }
62            }
63            continue;
64        }
65        let deny = resolve_against_workspace(policy, &rule.path);
66        if path.starts_with(&deny) || path == deny {
67            return false;
68        }
69    }
70
71    // Deny globs (soft).
72    if crate::deny_glob::path_matches_deny_glob(policy, &path) {
73        return false;
74    }
75
76    if write {
77        for p in policy.read_write_paths() {
78            let allow = resolve_against_workspace(policy, p);
79            if path.starts_with(&allow) || path == allow {
80                return true;
81            }
82        }
83        return false;
84    }
85
86    if policy.default_read {
87        return true;
88    }
89    for rule in &policy.fs {
90        if matches!(rule.access, FsAccess::Read | FsAccess::ReadWrite) && !rule.glob {
91            let allow = resolve_against_workspace(policy, &rule.path);
92            if path.starts_with(&allow) || path == allow {
93                return true;
94            }
95        }
96    }
97    false
98}
99
100pub struct ProcessGuardBackend {
101    /// When true, refuse spawn if network is DenyAll (cannot hard-block; documents intent).
102    pub soft_block_on_deny_all_net: bool,
103}
104
105impl ProcessGuardBackend {
106    pub fn new() -> Self {
107        Self {
108            soft_block_on_deny_all_net: false,
109        }
110    }
111}
112
113impl Default for ProcessGuardBackend {
114    fn default() -> Self {
115        Self::new()
116    }
117}
118
119#[async_trait]
120impl EnforceBackend for ProcessGuardBackend {
121    fn info(&self) -> BackendInfo {
122        BackendInfo {
123            name: "process-guard",
124            kernel_fs: false,
125            child_network: false,
126        }
127    }
128
129    async fn apply(&self, policy: &Policy, _sink: Arc<dyn RecordSink>) -> EnforceResult<()> {
130        if policy.is_expired(Utc::now()) {
131            return Err(EnforceError::PolicyExpired);
132        }
133        policy.validate()?;
134        info!(
135            policy_id = %policy.id,
136            backend = "process-guard",
137            "policy applied (soft process guard)"
138        );
139        Ok(())
140    }
141
142    async fn check_fs(&self, policy: &Policy, path: &Path, write: bool) -> EnforceResult<bool> {
143        Ok(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 self.soft_block_on_deny_all_net && matches!(policy.network, NetworkPolicy::DenyAll) {
173            // We cannot hard-block network without seccomp/Seatbelt; optional fail-closed for demos.
174            tracing::warn!("process-guard: DenyAll network is advisory without kernel backend");
175        }
176
177        if let Some(cwd) = &req.cwd {
178            if !soft_fs_allowed(policy, cwd, false) {
179                return Err(EnforceError::Denied(format!(
180                    "cwd not allowed: {}",
181                    cwd.display()
182                )));
183            }
184        }
185
186        // Program path soft-check when absolute.
187        let prog = Path::new(&req.program);
188        if prog.is_absolute() && !soft_fs_allowed(policy, prog, false) {
189            return Err(EnforceError::Denied(format!(
190                "program path not readable under policy: {}",
191                prog.display()
192            )));
193        }
194
195        let _ = sink
196            .emit(RecordEvent::new(
197                space_id.clone(),
198                policy.id.clone(),
199                policy.task_id.clone(),
200                EventKind::Exec {
201                    program: req.program.clone(),
202                    args: req.args.clone(),
203                    allowed: true,
204                },
205            ))
206            .await;
207
208        let child = base_command(&req).spawn()?;
209        Ok(SpawnedProcess { child })
210    }
211
212    async fn destroy(&self, _policy: &Policy, _sink: Arc<dyn RecordSink>) -> EnforceResult<()> {
213        Ok(())
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220    use keel_policy::profile_workspace;
221    use std::path::Path;
222
223    #[test]
224    fn workspace_write_rules() {
225        let p = profile_workspace(Path::new("/tmp/proj")).unwrap();
226        assert!(soft_fs_allowed(&p, Path::new("/tmp/proj/a.rs"), true));
227        assert!(soft_fs_allowed(&p, Path::new("/etc/passwd"), false)); // default_read
228        assert!(!soft_fs_allowed(&p, Path::new("/etc/passwd"), true));
229    }
230
231    #[test]
232    fn deny_wins() {
233        let p = Policy::builder("/tmp/proj")
234            .default_read(true)
235            .read_write("/tmp/proj")
236            .deny("/tmp/proj/secrets")
237            .build()
238            .unwrap();
239        assert!(!soft_fs_allowed(&p, Path::new("/tmp/proj/secrets/key"), false));
240        assert!(soft_fs_allowed(&p, Path::new("/tmp/proj/src"), true));
241    }
242
243    #[test]
244    fn relative_paths_resolve_to_workspace() {
245        let p = profile_workspace(Path::new("/tmp/proj")).unwrap();
246        assert!(soft_fs_allowed(&p, Path::new("README.md"), true));
247        assert!(soft_fs_allowed(&p, Path::new("src/main.rs"), true));
248    }
249}