Skip to main content

rustnet_sandbox/
lib.rs

1//! Post-initialization sandboxing and privilege dropping for rustnet.
2//!
3//! One [`apply_sandbox`] entry point with a platform backend behind it:
4//!
5//! - **Linux**: `PR_SET_NO_NEW_PRIVS`, capability drops (CAP_NET_RAW,
6//!   CAP_BPF, CAP_PERFMON), the root uid drop, and Landlock
7//!   filesystem/network/scope restrictions (behind the `landlock` feature).
8//! - **macOS**: the root uid drop, then a Seatbelt profile restricting outbound
9//!   network, credential reads, and writes under user home directories
10//!   (behind the `macos-sandbox` feature).
11//! - **Windows**: dangerous token privileges removed and a job object that
12//!   blocks child process creation.
13//! - **FreeBSD**: the root uid drop (Capsicum is planned).
14//!
15//! # Application order contract
16//!
17//! Sandboxing is a *post-initialization* step. Callers must apply it only
18//! after every privileged operation is done, in this order:
19//!
20//! 1. Open capture handles (raw sockets, BPF/PKTAP devices, Npcap): the
21//!    descriptors stay valid across the sandbox and uid drop.
22//! 2. Load eBPF programs (needs CAP_BPF/CAP_PERFMON, which the sandbox
23//!    drops).
24//! 3. Securely open output files (logs, PCAP exports) and, when dropping root,
25//!    hand ownership to the drop target ([`privdrop::chown_to_target`]). Retain
26//!    these descriptors for writing after the drop instead of reopening paths
27//!    or granting pathname write exceptions.
28//! 4. Call [`apply_sandbox`] on the **main thread**.
29//! 5. Only then spawn worker threads that should inherit the restrictions:
30//!    Landlock domains and capability sets are per-thread state that new
31//!    threads inherit from their spawner; threads started before step 4 keep
32//!    the unrestricted state.
33//!
34//! Long-lived workers should not start before the sandbox. Capture handles and
35//! eBPF maps opened during initialization remain usable through their existing
36//! descriptors after capability and identity reduction. Workers created after
37//! step 4 inherit the reduced capability set and sandbox restrictions.
38
39use std::path::PathBuf;
40
41#[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
42pub mod privdrop;
43
44#[cfg(target_os = "freebsd")]
45mod freebsd;
46#[cfg(target_os = "linux")]
47mod linux;
48#[cfg(target_os = "macos")]
49mod macos;
50#[cfg(target_os = "windows")]
51mod windows;
52
53#[cfg(all(target_os = "linux", feature = "landlock"))]
54pub use linux::capabilities;
55
56/// Sandbox enforcement mode
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
58pub enum SandboxMode {
59    /// Permit unavailable optional sandbox layers, but require a requested UID drop.
60    #[default]
61    BestEffort,
62    /// Require full sandbox enforcement or fail
63    Strict,
64    /// Disable sandboxing entirely
65    Disabled,
66}
67
68/// A requested root UID/GID transition failed.
69///
70/// Callers must not continue startup after this error, even in best-effort mode:
71/// the process may still be root or have only partially changed its identity.
72#[derive(Debug)]
73pub struct PrivilegeDropError;
74
75impl std::fmt::Display for PrivilegeDropError {
76    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        formatter.write_str("required root UID/GID drop failed")
78    }
79}
80
81impl std::error::Error for PrivilegeDropError {}
82
83impl SandboxMode {
84    /// Map the `--no-sandbox` / `--sandbox-strict` CLI flags to a mode.
85    pub fn from_flags(no_sandbox: bool, strict: bool) -> Self {
86        if no_sandbox {
87            SandboxMode::Disabled
88        } else if strict {
89            SandboxMode::Strict
90        } else {
91            SandboxMode::BestEffort
92        }
93    }
94}
95
96/// Status of sandbox application
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
98pub enum SandboxStatus {
99    /// Sandbox fully enforced (all requested restrictions applied)
100    FullyEnforced,
101    /// Sandbox partially enforced (some features unavailable)
102    PartiallyEnforced,
103    /// Sandbox not applied (disabled, or platform support missing)
104    #[default]
105    NotApplied,
106    /// Applying the sandbox failed (only set by callers on an `Err` from
107    /// [`apply_sandbox`]; the backends themselves never return it)
108    Error,
109}
110
111impl SandboxStatus {
112    /// Short human-readable label for status displays.
113    pub fn label(&self) -> &'static str {
114        match self {
115            SandboxStatus::FullyEnforced => "Fully enforced",
116            SandboxStatus::PartiallyEnforced => "Partially enforced",
117            SandboxStatus::NotApplied => "Not applied",
118            SandboxStatus::Error => "Error",
119        }
120    }
121}
122
123/// Configuration for the sandbox
124///
125/// One cross-platform shape; each backend reads what applies to it. Windows
126/// reads only `mode`; FreeBSD reads `mode` and `drop_uid`.
127#[derive(Debug, Clone, Default)]
128pub struct SandboxConfig {
129    /// Sandbox enforcement mode
130    pub mode: SandboxMode,
131    /// Block TCP bind/connect (Linux) or outbound TCP/UDP (macOS).
132    /// Recommended for passive monitors.
133    pub block_network: bool,
134    /// Paths that need read access after sandboxing (e.g., GeoIP databases)
135    pub read_paths: Vec<PathBuf>,
136    /// When running as root: the identity to drop to after initialization
137    /// (`None` = not root, or drop disabled via `--no-uid-drop`)
138    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
139    pub drop_uid: Option<privdrop::DropTarget>,
140}
141
142/// Result of sandbox application
143///
144/// One struct for every platform: the cross-platform fields always exist
145/// (and stay `false` where a platform has no such restriction), the
146/// platform-specific details are cfg-gated. This is both the enforcement
147/// report and the UI/status shape, so a new field automatically reaches
148/// every consumer.
149#[derive(Debug, Clone, Default)]
150pub struct SandboxReport {
151    /// Overall status
152    pub status: SandboxStatus,
153    /// Human-readable message
154    pub message: String,
155    /// Whether filesystem restrictions are active (Landlock / Seatbelt)
156    pub fs_restricted: bool,
157    /// Whether network restrictions are active (Landlock TCP restrictions /
158    /// Seatbelt outbound restrictions)
159    pub net_restricted: bool,
160    /// Whether the root uid/gid were dropped (Linux/macOS/FreeBSD)
161    pub uid_dropped: bool,
162    /// Whether CAP_NET_RAW was dropped
163    #[cfg(target_os = "linux")]
164    pub cap_net_raw_dropped: bool,
165    /// Whether CAP_BPF/CAP_PERFMON were dropped
166    #[cfg(target_os = "linux")]
167    pub ebpf_caps_dropped: bool,
168    /// Whether Landlock scope restrictions (abstract UNIX sockets + signals)
169    /// are applied
170    #[cfg(target_os = "linux")]
171    pub scope_restricted: bool,
172    /// Whether Landlock is available on this kernel
173    #[cfg(target_os = "linux")]
174    pub landlock_available: bool,
175    /// Effective Landlock ABI negotiated with the kernel (e.g. `Some(6)`),
176    /// or `None` when Landlock is unavailable / not enforced
177    #[cfg(target_os = "linux")]
178    pub landlock_abi: Option<u8>,
179    /// Whether PR_SET_NO_NEW_PRIVS is set (applied even with `--no-sandbox`)
180    #[cfg(target_os = "linux")]
181    pub no_new_privs: bool,
182    /// Whether the Seatbelt profile was applied
183    #[cfg(target_os = "macos")]
184    pub seatbelt_applied: bool,
185    /// Whether dangerous privileges were removed
186    #[cfg(target_os = "windows")]
187    pub privileges_removed: bool,
188    /// Number of privileges removed
189    #[cfg(target_os = "windows")]
190    pub privileges_removed_count: u32,
191    /// Whether the job object was applied
192    #[cfg(target_os = "windows")]
193    pub job_object_applied: bool,
194}
195
196impl SandboxReport {
197    /// Report for a failed [`apply_sandbox`] call (non-strict callers).
198    pub fn from_error(error: &anyhow::Error) -> Self {
199        Self {
200            status: SandboxStatus::Error,
201            message: error.to_string(),
202            ..Self::default()
203        }
204    }
205
206    /// Report for a backend whose only enforcement was the root uid drop
207    /// (no platform sandbox available or compiled in): partially enforced
208    /// when the drop happened, not applied otherwise.
209    #[cfg(any(target_os = "macos", target_os = "freebsd"))]
210    pub(crate) fn uid_drop_only(banner: &str, outcome: &UidDropOutcome) -> Self {
211        Self {
212            status: if outcome.dropped {
213                SandboxStatus::PartiallyEnforced
214            } else {
215                SandboxStatus::NotApplied
216            },
217            message: outcome.message_after(banner),
218            uid_dropped: outcome.dropped,
219            ..Self::default()
220        }
221    }
222}
223
224/// Outcome of the root uid drop step shared by the Linux, macOS and FreeBSD
225/// backends (see [`drop_root_step`]).
226#[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
227pub(crate) struct UidDropOutcome {
228    /// Whether the root uid/gid were dropped.
229    pub(crate) dropped: bool,
230    /// Human-readable summary of the successful step;
231    /// `None` when no drop was requested.
232    pub(crate) message: Option<String>,
233}
234
235#[cfg(any(target_os = "macos", target_os = "freebsd"))]
236impl UidDropOutcome {
237    /// `banner`, followed by the step summary as a `; `-separated suffix when
238    /// a drop was attempted. (Linux folds the summary into its own message
239    /// list instead.)
240    pub(crate) fn message_after(&self, banner: &str) -> String {
241        match &self.message {
242            Some(message) => format!("{}; {}", banner, message),
243            None => banner.to_string(),
244        }
245    }
246}
247
248/// Drop the root uid/gid when `config.drop_uid` is set.
249///
250/// Capture fds opened during initialization remain valid across the drop.
251/// `attribution_note` names the platform's process-attribution fallback that
252/// is limited to the target user's processes afterwards; it is appended to
253/// the success log line. A failed requested drop returns [`PrivilegeDropError`]
254/// in every enforcing mode and must stop startup before worker creation.
255#[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
256pub(crate) fn drop_root_step(
257    config: &SandboxConfig,
258    attribution_note: &str,
259) -> anyhow::Result<UidDropOutcome> {
260    let Some(target) = config.drop_uid else {
261        return Ok(UidDropOutcome {
262            dropped: false,
263            message: None,
264        });
265    };
266    privdrop::drop_to(target).map_err(|error| error.context(PrivilegeDropError))?;
267    // The target uid/gid are reported through the outcome message
268    // (shown in the Overview Security panel) rather than logged here.
269    log::info!("Dropped root privileges (verified); {}", attribution_note);
270    Ok(UidDropOutcome {
271        dropped: true,
272        message: Some(format!(
273            "root dropped to uid {} gid {}",
274            target.uid, target.gid
275        )),
276    })
277}
278
279/// Apply the sandbox with the given configuration.
280///
281/// See the crate docs for the required application order. Returns
282/// `Ok(SandboxReport)` with details about what was applied; in
283/// [`SandboxMode::Strict`], returns `Err` if enforcement cannot be achieved.
284/// A failed requested UID/GID drop is always fatal and returns
285/// [`PrivilegeDropError`], including in [`SandboxMode::BestEffort`].
286pub fn apply_sandbox(config: &SandboxConfig) -> anyhow::Result<SandboxReport> {
287    apply_sandbox_with_policy(config, false)
288}
289
290/// Apply the sandbox with its narrow platform DNS exception enabled.
291///
292/// This separate entry point preserves the stable [`SandboxConfig`] shape and
293/// makes the process-wide network exception explicit at the call site.
294pub fn apply_sandbox_allowing_dns(config: &SandboxConfig) -> anyhow::Result<SandboxReport> {
295    apply_sandbox_with_policy(config, true)
296}
297
298fn apply_sandbox_with_policy(
299    config: &SandboxConfig,
300    allow_dns_resolution: bool,
301) -> anyhow::Result<SandboxReport> {
302    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
303    let _ = allow_dns_resolution;
304    #[cfg(target_os = "linux")]
305    return linux::apply(config, allow_dns_resolution);
306    #[cfg(target_os = "macos")]
307    return macos::apply(config, allow_dns_resolution);
308    #[cfg(target_os = "windows")]
309    return windows::apply(config);
310    #[cfg(target_os = "freebsd")]
311    return freebsd::apply(config);
312    #[cfg(not(any(
313        target_os = "linux",
314        target_os = "macos",
315        target_os = "windows",
316        target_os = "freebsd"
317    )))]
318    {
319        log::warn!("Sandboxing not implemented for this platform");
320        let _ = (config, allow_dns_resolution);
321        Ok(SandboxReport {
322            message: "Sandboxing not implemented for this platform".to_string(),
323            ..SandboxReport::default()
324        })
325    }
326}
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331
332    #[test]
333    fn test_mode_from_flags() {
334        assert_eq!(
335            SandboxMode::from_flags(false, false),
336            SandboxMode::BestEffort
337        );
338        assert_eq!(SandboxMode::from_flags(false, true), SandboxMode::Strict);
339        assert_eq!(SandboxMode::from_flags(true, false), SandboxMode::Disabled);
340    }
341
342    #[test]
343    fn test_report_from_error_defaults_everything_off() {
344        let report = SandboxReport::from_error(&anyhow::anyhow!("boom"));
345        assert_eq!(report.status, SandboxStatus::Error);
346        assert_eq!(report.message, "boom");
347        assert!(!report.fs_restricted);
348        assert!(!report.net_restricted);
349        assert!(!report.uid_dropped);
350    }
351
352    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
353    #[test]
354    fn requested_uid_drop_failure_is_fatal_in_every_enforcing_mode() {
355        for mode in [SandboxMode::BestEffort, SandboxMode::Strict] {
356            let config = SandboxConfig {
357                mode,
358                // Invalid targets fail before any identity-changing syscall.
359                drop_uid: Some(privdrop::DropTarget { uid: 0, gid: 0 }),
360                ..SandboxConfig::default()
361            };
362            let error = drop_root_step(&config, "test attribution")
363                .err()
364                .expect("a requested identity drop must fail closed");
365            assert!(error.is::<PrivilegeDropError>());
366            assert!(format!("{error:#}").contains("refusing to 'drop' to uid 0 / gid 0"));
367        }
368    }
369
370    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
371    #[test]
372    fn absent_uid_drop_target_preserves_explicit_opt_out() {
373        for mode in [SandboxMode::BestEffort, SandboxMode::Strict] {
374            let config = SandboxConfig {
375                mode,
376                drop_uid: None,
377                ..SandboxConfig::default()
378            };
379            let outcome = drop_root_step(&config, "test attribution").unwrap();
380            assert!(!outcome.dropped);
381            assert!(outcome.message.is_none());
382        }
383    }
384
385    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))]
386    #[test]
387    fn disabled_sandbox_does_not_attempt_uid_drop() {
388        let report = apply_sandbox(&SandboxConfig {
389            mode: SandboxMode::Disabled,
390            // This would fail if the disabled backend attempted the drop.
391            drop_uid: Some(privdrop::DropTarget { uid: 0, gid: 0 }),
392            ..SandboxConfig::default()
393        })
394        .unwrap();
395        assert!(!report.uid_dropped);
396        assert_eq!(report.status, SandboxStatus::NotApplied);
397    }
398}