Skip to main content

sandlock_core/
policy.rs

1use std::collections::HashMap;
2use std::path::PathBuf;
3use std::time::SystemTime;
4
5use serde::{Deserialize, Serialize};
6
7use crate::error::PolicyError;
8
9/// A byte size value.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
11pub struct ByteSize(pub u64);
12
13impl ByteSize {
14    pub fn bytes(n: u64) -> Self {
15        ByteSize(n)
16    }
17
18    pub fn kib(n: u64) -> Self {
19        ByteSize(n * 1024)
20    }
21
22    pub fn mib(n: u64) -> Self {
23        ByteSize(n * 1024 * 1024)
24    }
25
26    pub fn gib(n: u64) -> Self {
27        ByteSize(n * 1024 * 1024 * 1024)
28    }
29
30    pub fn parse(s: &str) -> Result<Self, PolicyError> {
31        let s = s.trim();
32        if s.is_empty() {
33            return Err(PolicyError::Invalid("empty byte size string".into()));
34        }
35
36        // Check for suffix
37        let last = s.chars().last().unwrap();
38        if last.is_ascii_alphabetic() {
39            let (num_str, suffix) = s.split_at(s.len() - 1);
40            let n: u64 = num_str
41                .trim()
42                .parse()
43                .map_err(|_| PolicyError::Invalid(format!("invalid byte size: {}", s)))?;
44            match suffix.to_ascii_uppercase().as_str() {
45                "K" => Ok(ByteSize::kib(n)),
46                "M" => Ok(ByteSize::mib(n)),
47                "G" => Ok(ByteSize::gib(n)),
48                other => Err(PolicyError::Invalid(format!("unknown byte size suffix: {}", other))),
49            }
50        } else {
51            let n: u64 = s
52                .parse()
53                .map_err(|_| PolicyError::Invalid(format!("invalid byte size: {}", s)))?;
54            Ok(ByteSize(n))
55        }
56    }
57}
58
59/// Filesystem isolation mode.
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
61pub enum FsIsolation {
62    #[default]
63    None,
64    OverlayFs,
65    BranchFs,
66}
67
68/// Action to take on branch exit.
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
70pub enum BranchAction {
71    #[default]
72    Commit,
73    Abort,
74    Keep,
75}
76
77/// Sandbox policy configuration.
78#[derive(Clone, Serialize, Deserialize)]
79pub struct Policy {
80    // Filesystem access
81    pub fs_writable: Vec<PathBuf>,
82    pub fs_readable: Vec<PathBuf>,
83    pub fs_denied: Vec<PathBuf>,
84
85    // Syscall filtering
86    pub deny_syscalls: Option<Vec<String>>,
87    pub allow_syscalls: Option<Vec<String>>,
88
89    // Network
90    pub net_allow_hosts: Vec<String>,
91    pub net_bind: Vec<u16>,
92    pub net_connect: Vec<u16>,
93    pub no_raw_sockets: bool,
94    pub no_udp: bool,
95
96    // Namespace isolation
97    pub isolate_ipc: bool,
98    pub isolate_signals: bool,
99    pub isolate_pids: bool,
100
101    // Resource limits
102    pub max_memory: Option<ByteSize>,
103    pub max_processes: u32,
104    pub max_open_files: Option<u32>,
105    pub max_cpu: Option<u8>,
106
107    // Reproducibility
108    pub random_seed: Option<u64>,
109    pub time_start: Option<SystemTime>,
110    pub no_randomize_memory: bool,
111    pub no_huge_pages: bool,
112    pub deterministic_dirs: bool,
113    pub hostname: Option<String>,
114
115    // Filesystem branch
116    pub fs_isolation: FsIsolation,
117    pub workdir: Option<PathBuf>,
118    pub fs_storage: Option<PathBuf>,
119    pub max_disk: Option<ByteSize>,
120    pub on_exit: BranchAction,
121    pub on_error: BranchAction,
122
123    // Environment
124    pub chroot: Option<PathBuf>,
125    pub clean_env: bool,
126    pub env: HashMap<String, String>,
127    pub close_fds: bool,
128
129    // Devices
130    pub gpu_devices: Option<Vec<u32>>,
131
132    // CPU
133    pub cpu_cores: Option<Vec<u32>>,
134    pub num_cpus: Option<u32>,
135    pub port_remap: bool,
136
137    // Mode flags
138    pub privileged: bool,
139
140    // Dynamic policy callback
141    #[serde(skip)]
142    pub policy_fn: Option<crate::policy_fn::PolicyCallback>,
143}
144
145impl std::fmt::Debug for Policy {
146    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147        f.debug_struct("Policy")
148            .field("fs_readable", &self.fs_readable)
149            .field("fs_writable", &self.fs_writable)
150            .field("max_memory", &self.max_memory)
151            .field("max_processes", &self.max_processes)
152            .field("policy_fn", &self.policy_fn.as_ref().map(|_| "<callback>"))
153            .finish_non_exhaustive()
154    }
155}
156
157impl Policy {
158    pub fn builder() -> PolicyBuilder {
159        PolicyBuilder::default()
160    }
161}
162
163/// Fluent builder for `Policy`.
164#[derive(Default)]
165pub struct PolicyBuilder {
166    fs_writable: Vec<PathBuf>,
167    fs_readable: Vec<PathBuf>,
168    fs_denied: Vec<PathBuf>,
169
170    deny_syscalls: Option<Vec<String>>,
171    allow_syscalls: Option<Vec<String>>,
172
173    net_allow_hosts: Vec<String>,
174    net_bind: Vec<u16>,
175    net_connect: Vec<u16>,
176    no_raw_sockets: Option<bool>,
177    no_udp: bool,
178
179    isolate_ipc: bool,
180    isolate_signals: bool,
181    isolate_pids: bool,
182
183    max_memory: Option<ByteSize>,
184    max_processes: Option<u32>,
185    max_open_files: Option<u32>,
186    max_cpu: Option<u8>,
187
188    random_seed: Option<u64>,
189    time_start: Option<SystemTime>,
190    no_randomize_memory: bool,
191    no_huge_pages: bool,
192    deterministic_dirs: bool,
193    hostname: Option<String>,
194
195    fs_isolation: Option<FsIsolation>,
196    workdir: Option<PathBuf>,
197    fs_storage: Option<PathBuf>,
198    max_disk: Option<ByteSize>,
199    on_exit: Option<BranchAction>,
200    on_error: Option<BranchAction>,
201
202    chroot: Option<PathBuf>,
203    clean_env: bool,
204    env: HashMap<String, String>,
205    close_fds: Option<bool>,
206
207    gpu_devices: Option<Vec<u32>>,
208
209    cpu_cores: Option<Vec<u32>>,
210    num_cpus: Option<u32>,
211    port_remap: bool,
212
213    privileged: bool,
214    policy_fn: Option<crate::policy_fn::PolicyCallback>,
215}
216
217impl PolicyBuilder {
218    pub fn fs_write(mut self, path: impl Into<PathBuf>) -> Self {
219        self.fs_writable.push(path.into());
220        self
221    }
222
223    pub fn fs_read(mut self, path: impl Into<PathBuf>) -> Self {
224        self.fs_readable.push(path.into());
225        self
226    }
227
228    pub fn fs_deny(mut self, path: impl Into<PathBuf>) -> Self {
229        self.fs_denied.push(path.into());
230        self
231    }
232
233    pub fn deny_syscalls(mut self, calls: Vec<String>) -> Self {
234        self.deny_syscalls = Some(calls);
235        self
236    }
237
238    pub fn allow_syscalls(mut self, calls: Vec<String>) -> Self {
239        self.allow_syscalls = Some(calls);
240        self
241    }
242
243    pub fn net_allow_host(mut self, host: impl Into<String>) -> Self {
244        self.net_allow_hosts.push(host.into());
245        self
246    }
247
248    pub fn net_bind_port(mut self, port: u16) -> Self {
249        self.net_bind.push(port);
250        self
251    }
252
253    pub fn net_connect_port(mut self, port: u16) -> Self {
254        self.net_connect.push(port);
255        self
256    }
257
258    pub fn no_raw_sockets(mut self, v: bool) -> Self {
259        self.no_raw_sockets = Some(v);
260        self
261    }
262
263    pub fn no_udp(mut self, v: bool) -> Self {
264        self.no_udp = v;
265        self
266    }
267
268    pub fn isolate_ipc(mut self, v: bool) -> Self {
269        self.isolate_ipc = v;
270        self
271    }
272
273    pub fn isolate_signals(mut self, v: bool) -> Self {
274        self.isolate_signals = v;
275        self
276    }
277
278    pub fn isolate_pids(mut self, v: bool) -> Self {
279        self.isolate_pids = v;
280        self
281    }
282
283    pub fn max_memory(mut self, size: ByteSize) -> Self {
284        self.max_memory = Some(size);
285        self
286    }
287
288    pub fn max_processes(mut self, n: u32) -> Self {
289        self.max_processes = Some(n);
290        self
291    }
292
293    pub fn max_open_files(mut self, n: u32) -> Self {
294        self.max_open_files = Some(n);
295        self
296    }
297
298    pub fn max_cpu(mut self, pct: u8) -> Self {
299        self.max_cpu = Some(pct);
300        self
301    }
302
303    pub fn random_seed(mut self, seed: u64) -> Self {
304        self.random_seed = Some(seed);
305        self
306    }
307
308    pub fn time_start(mut self, t: SystemTime) -> Self {
309        self.time_start = Some(t);
310        self
311    }
312
313    pub fn no_randomize_memory(mut self, v: bool) -> Self {
314        self.no_randomize_memory = v;
315        self
316    }
317
318    pub fn no_huge_pages(mut self, v: bool) -> Self {
319        self.no_huge_pages = v;
320        self
321    }
322
323    pub fn deterministic_dirs(mut self, v: bool) -> Self {
324        self.deterministic_dirs = v;
325        self
326    }
327
328    pub fn hostname(mut self, name: impl Into<String>) -> Self {
329        self.hostname = Some(name.into());
330        self
331    }
332
333    pub fn fs_isolation(mut self, iso: FsIsolation) -> Self {
334        self.fs_isolation = Some(iso);
335        self
336    }
337
338    pub fn workdir(mut self, path: impl Into<PathBuf>) -> Self {
339        self.workdir = Some(path.into());
340        self
341    }
342
343    pub fn fs_storage(mut self, path: impl Into<PathBuf>) -> Self {
344        self.fs_storage = Some(path.into());
345        self
346    }
347
348    pub fn max_disk(mut self, size: ByteSize) -> Self {
349        self.max_disk = Some(size);
350        self
351    }
352
353    pub fn on_exit(mut self, action: BranchAction) -> Self {
354        self.on_exit = Some(action);
355        self
356    }
357
358    pub fn on_error(mut self, action: BranchAction) -> Self {
359        self.on_error = Some(action);
360        self
361    }
362
363    pub fn chroot(mut self, path: impl Into<PathBuf>) -> Self {
364        self.chroot = Some(path.into());
365        self
366    }
367
368    pub fn clean_env(mut self, v: bool) -> Self {
369        self.clean_env = v;
370        self
371    }
372
373    pub fn env_var(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
374        self.env.insert(key.into(), value.into());
375        self
376    }
377
378    pub fn close_fds(mut self, v: bool) -> Self {
379        self.close_fds = Some(v);
380        self
381    }
382
383    pub fn gpu_devices(mut self, devices: Vec<u32>) -> Self {
384        self.gpu_devices = Some(devices);
385        self
386    }
387
388    pub fn cpu_cores(mut self, cores: Vec<u32>) -> Self {
389        self.cpu_cores = Some(cores);
390        self
391    }
392
393    pub fn num_cpus(mut self, n: u32) -> Self {
394        self.num_cpus = Some(n);
395        self
396    }
397
398    pub fn port_remap(mut self, v: bool) -> Self {
399        self.port_remap = v;
400        self
401    }
402
403    pub fn policy_fn(
404        mut self,
405        f: impl Fn(crate::policy_fn::SyscallEvent, &mut crate::policy_fn::PolicyContext) -> crate::policy_fn::Verdict + Send + Sync + 'static,
406    ) -> Self {
407        self.policy_fn = Some(std::sync::Arc::new(f));
408        self
409    }
410
411    pub fn privileged(mut self, v: bool) -> Self {
412        self.privileged = v;
413        self
414    }
415
416    pub fn build(self) -> Result<Policy, PolicyError> {
417        // Validate: deny_syscalls and allow_syscalls are mutually exclusive
418        if self.deny_syscalls.is_some() && self.allow_syscalls.is_some() {
419            return Err(PolicyError::MutuallyExclusiveSyscalls);
420        }
421
422        // Validate: max_cpu must be 1-100
423        if let Some(cpu) = self.max_cpu {
424            if cpu == 0 || cpu > 100 {
425                return Err(PolicyError::InvalidCpuPercent(cpu));
426            }
427        }
428
429        // Validate: fs_isolation != None requires workdir
430        let fs_isolation = self.fs_isolation.unwrap_or_default();
431        if fs_isolation != FsIsolation::None && self.workdir.is_none() {
432            return Err(PolicyError::FsIsolationRequiresWorkdir);
433        }
434
435        Ok(Policy {
436            fs_writable: self.fs_writable,
437            fs_readable: self.fs_readable,
438            fs_denied: self.fs_denied,
439            deny_syscalls: self.deny_syscalls,
440            allow_syscalls: self.allow_syscalls,
441            net_allow_hosts: self.net_allow_hosts,
442            net_bind: self.net_bind,
443            net_connect: self.net_connect,
444            no_raw_sockets: self.no_raw_sockets.unwrap_or(true),
445            no_udp: self.no_udp,
446            isolate_ipc: self.isolate_ipc,
447            isolate_signals: self.isolate_signals,
448            isolate_pids: self.isolate_pids,
449            max_memory: self.max_memory,
450            max_processes: self.max_processes.unwrap_or(64),
451            max_open_files: self.max_open_files,
452            max_cpu: self.max_cpu,
453            random_seed: self.random_seed,
454            time_start: self.time_start,
455            no_randomize_memory: self.no_randomize_memory,
456            no_huge_pages: self.no_huge_pages,
457            deterministic_dirs: self.deterministic_dirs,
458            hostname: self.hostname,
459            fs_isolation,
460            workdir: self.workdir,
461            fs_storage: self.fs_storage,
462            max_disk: self.max_disk,
463            on_exit: self.on_exit.unwrap_or_default(),
464            on_error: self.on_error.unwrap_or_default(),
465            chroot: self.chroot,
466            clean_env: self.clean_env,
467            env: self.env,
468            close_fds: self.close_fds.unwrap_or(true),
469            gpu_devices: self.gpu_devices,
470            cpu_cores: self.cpu_cores,
471            num_cpus: self.num_cpus,
472            port_remap: self.port_remap,
473            privileged: self.privileged,
474            policy_fn: self.policy_fn,
475        })
476    }
477}