Skip to main content

platform/sandbox/
fence.rs

1//! The process-level fence table: what this process serves its clients on, which no
2//! confined command may reach. Backends read it when they write a policy.
3
4use std::net::SocketAddr;
5use std::path::{Path, PathBuf};
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::sync::RwLock;
8
9/// What this process serves its clients on, one entry per live [`Fence`].
10static SERVED: RwLock<Vec<(u64, Served)>> = RwLock::new(Vec::new());
11
12static NEXT_FENCE: AtomicU64 = AtomicU64::new(0);
13
14#[cfg_attr(not(feature = "sandbox"), allow(dead_code))]
15enum Served {
16    Socket(PathBuf),
17    Port(SocketAddr),
18    Secret(PathBuf),
19}
20
21/// One listener's or one file's place in what no confined command may reach,
22/// until it is dropped. Held as long as what it fences: a port or a path
23/// outlives the listener or file that had it, and whatever is there next is
24/// not this process's to fence.
25#[must_use = "the fence comes down when this is dropped"]
26pub struct Fence(u64);
27
28impl Drop for Fence {
29    fn drop(&mut self) {
30        let mut served = SERVED.write().unwrap_or_else(|e| e.into_inner());
31        served.retain(|(id, _)| *id != self.0);
32    }
33}
34
35fn fence(entry: Served) -> Fence {
36    let id = NEXT_FENCE.fetch_add(1, Ordering::Relaxed);
37    let mut served = SERVED.write().unwrap_or_else(|e| e.into_inner());
38    served.push((id, entry));
39    Fence(id)
40}
41
42/// No command this process confines may connect to the unix socket at
43/// `path` while the returned fence is held. For a daemon's own listener,
44/// wherever `--socket` put it: a command connected to it would be its host.
45pub fn fence_socket(path: &Path) -> Fence {
46    fence(Served::Socket(
47        path.canonicalize().unwrap_or_else(|_| path.to_path_buf()),
48    ))
49}
50
51/// [`fence_socket`] for a TCP listener. Only the macOS backend can refuse a
52/// port; bwrap can cut the network only as a whole, and the egress relay
53/// refuses to forward to one.
54pub fn fence_port(addr: SocketAddr) -> Fence {
55    fence(Served::Port(addr))
56}
57
58/// No command this process confines may read the file at `path` while the
59/// returned fence is held, whatever `sandbox.allow_read` says. For a
60/// credential the daemon writes for its own clients, such as the unix
61/// socket's token.
62pub fn fence_secret(path: &Path) -> Fence {
63    fence(Served::Secret(
64        path.canonicalize().unwrap_or_else(|_| path.to_path_buf()),
65    ))
66}
67
68#[cfg(feature = "sandbox")]
69fn fenced<T: Ord>(pick: impl Fn(&Served) -> Option<T>) -> Vec<T> {
70    let served = SERVED.read().unwrap_or_else(|e| e.into_inner());
71    let mut found: Vec<T> = served.iter().filter_map(|(_, s)| pick(s)).collect();
72    found.sort();
73    found.dedup();
74    found
75}
76
77/// The fenced secrets that are still there.
78#[cfg(all(feature = "sandbox", any(target_os = "macos", target_os = "linux")))]
79pub(super) fn fenced_secrets() -> Vec<PathBuf> {
80    fenced(|s| match s {
81        Served::Secret(p) if p.exists() => Some(p.clone()),
82        _ => None,
83    })
84}
85
86/// The fenced sockets that are still there.
87#[cfg(all(feature = "sandbox", any(target_os = "macos", target_os = "linux")))]
88pub(super) fn fenced_sockets() -> Vec<PathBuf> {
89    fenced(|s| match s {
90        Served::Socket(p) if is_socket(p) => Some(p.clone()),
91        _ => None,
92    })
93}
94
95#[cfg(all(feature = "sandbox", any(target_os = "macos", target_os = "linux")))]
96pub(super) fn fenced_ports() -> Vec<SocketAddr> {
97    fenced(|s| match s {
98        Served::Port(addr) => Some(*addr),
99        _ => None,
100    })
101}
102
103#[cfg(all(feature = "sandbox", any(target_os = "macos", target_os = "linux")))]
104pub(super) fn is_socket(path: &Path) -> bool {
105    use std::os::unix::fs::FileTypeExt;
106    path.symlink_metadata()
107        .is_ok_and(|m| m.file_type().is_socket())
108}