Skip to main content

zond_engine/system/
privilege.rs

1// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
2//
3// This file is part of Zond Engine, licensed under the GNU Affero General
4// Public License, version 3 or later. See the LICENSE file for details, or
5// <https://www.gnu.org/licenses/agpl-3.0.html>.
6//
7// SPDX-License-Identifier: AGPL-3.0-or-later
8
9//! # What this process is allowed to send
10//!
11//! Raw sockets, packet capture and ARP injection need rights an ordinary process
12//! does not have. This module answers whether the current one holds them, so a
13//! caller can pick a privileged strategy or fall back to an unprivileged one.
14//!
15//! [`can_send_raw`] and [`can_inject_frames`] ask whether this process can put a
16//! packet of its own on the wire, through a raw socket or through the link-layer
17//! handle libpcap opens. [`Privilege`] is what those answers mean for a scan; a
18//! journal records it and refuses to continue a scan of one kind as the other.
19//!
20//! The two routes differ on macOS. Raw sockets belong to root, while the BPF
21//! devices libpcap opens are often given to a group (Wireshark's ChmodBPF does
22//! this). A process in that group can send every frame a scan needs without being
23//! able to open a raw socket.
24//!
25//! [`is_elevated`] asks whether this process is root or holds an elevated token.
26//! Its one caller is [`journal::paths`](crate::journal::paths), deciding whose
27//! home a journal written under `sudo` belongs in. Do not use it to decide how to
28//! scan: Linux gates raw sockets on `CAP_NET_RAW`, which a binary given `setcap
29//! cap_net_raw+ep` holds without being root.
30
31/// Which kind of probe a scan could send, as its privileges decide.
32///
33/// The same finding means different things under the two, so anything that
34/// records what a scan did records this beside it. A raw scan chooses its own
35/// packets and reads the answers off the wire; a connect scan can only ask the
36/// local stack to complete a handshake, and what it does not get back is weaker
37/// evidence about the target.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum Privilege {
40    /// The scan sent the packets it chose: ARP and ICMPv6 on the local
41    /// segment, raw TCP and UDP beyond it, through a raw socket or a link-layer
42    /// handle (the packets are the same either way).
43    ///
44    /// The scan set its own flags, so a port that answered and a port that did
45    /// not are distinct findings about the target.
46    Raw,
47    /// Neither route was open, so the scan fell back to ordinary TCP connect
48    /// attempts.
49    ///
50    /// A result recorded under this saw less and was more visible to the
51    /// target. Only a completed handshake proves anything, so the states a raw
52    /// technique distinguishes collapse, and silence on a port may come from the
53    /// local stack.
54    Connect,
55}
56
57impl Privilege {
58    /// What this process holds, as [`can_send_raw`] and [`can_inject_frames`]
59    /// report it. Either route is enough for [`Raw`](Self::Raw).
60    #[must_use]
61    pub fn current() -> Self {
62        if can_send_raw() || can_inject_frames() {
63            Self::Raw
64        } else {
65            Self::Connect
66        }
67    }
68
69    /// Whether raw sockets were held, for formats that record this as a boolean
70    /// (a journal's manifest).
71    #[must_use]
72    pub fn is_raw(self) -> bool {
73        matches!(self, Self::Raw)
74    }
75
76    /// The inverse of [`is_raw`](Self::is_raw), for the formats that write this
77    /// as a boolean: the journal's manifest and the published report schema.
78    pub fn from_raw(raw: bool) -> Self {
79        if raw { Self::Raw } else { Self::Connect }
80    }
81}
82
83/// Whether this process can open a raw socket, asked by opening one.
84///
85/// Linux gates raw sockets on `CAP_NET_RAW`, so a binary carrying the capability
86/// answers `true` here and `false` to [`is_elevated`]; macOS grants them to root
87/// alone.
88///
89/// Costs one socket, opened and closed. Not cached, so a process that drops its
90/// privileges mid-run gets the new answer.
91#[must_use]
92pub fn can_send_raw() -> bool {
93    imp::can_send_raw()
94}
95
96/// Whether this process can open a link-layer handle and inject frames.
97///
98/// A scan that cannot open a raw socket can still build its own Ethernet frames
99/// and send them; macOS prefers this path and Windows has no other.
100///
101/// Frames cannot reach a destination with no Ethernet in front of it, so
102/// tunnel-only addresses still need a raw socket, as does loopback everywhere but
103/// macOS.
104#[must_use]
105pub fn can_inject_frames() -> bool {
106    imp::can_inject_frames()
107}
108
109/// Whether this process is root, or holds an elevated token on Windows.
110///
111/// This is about *who* the process is, for deciding whose home a journal belongs
112/// in. Use [`can_send_raw`] to decide how to scan.
113#[must_use]
114pub fn is_elevated() -> bool {
115    imp::is_elevated()
116}
117
118#[cfg(unix)]
119mod imp {
120    pub fn is_elevated() -> bool {
121        // SAFETY: `geteuid` takes no arguments, dereferences nothing, and is
122        // specified as always succeeding.
123        unsafe { libc::geteuid() == 0 }
124    }
125
126    /// How many `/dev/bpf` devices to try before giving up.
127    ///
128    /// They share an owner and a mode, so the first one that exists answers for
129    /// all of them. A low-numbered device can be missing on a host that clones
130    /// them on demand.
131    #[cfg(target_os = "macos")]
132    const BPF_DEVICES_TO_TRY: u8 = 4;
133
134    /// Asks the BPF devices the same question libpcap's open will.
135    ///
136    /// `EBUSY` means permitted (whoever holds the device passed the same
137    /// permission check) and `EACCES` means not.
138    #[cfg(target_os = "macos")]
139    pub fn can_inject_frames() -> bool {
140        (0..BPF_DEVICES_TO_TRY).any(|n| {
141            match std::fs::OpenOptions::new()
142                .read(true)
143                .write(true)
144                .open(format!("/dev/bpf{n}"))
145            {
146                Ok(_) => true,
147                Err(error) => error.kind() == std::io::ErrorKind::ResourceBusy,
148            }
149        })
150    }
151
152    /// Everywhere else the two routes are one permission.
153    ///
154    /// The packet socket libpcap opens on Linux is gated on the same
155    /// `CAP_NET_RAW` as the raw socket.
156    #[cfg(not(target_os = "macos"))]
157    pub fn can_inject_frames() -> bool {
158        can_send_raw()
159    }
160
161    pub fn can_send_raw() -> bool {
162        // The exact socket the raw TCP paths open.
163        //
164        // SAFETY: `socket` takes three integers, dereferences nothing, and
165        // returns a descriptor or -1.
166        let fd = unsafe { libc::socket(libc::AF_INET, libc::SOCK_RAW, libc::IPPROTO_TCP) };
167        if fd < 0 {
168            return false;
169        }
170
171        // SAFETY: `fd` was just opened by the call above and is not used again.
172        unsafe { libc::close(fd) };
173        true
174    }
175}
176
177#[cfg(windows)]
178mod imp {
179    use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
180    use windows_sys::Win32::Security::{
181        GetTokenInformation, TOKEN_ELEVATION, TOKEN_QUERY, TokenElevation,
182    };
183    use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
184
185    pub fn is_elevated() -> bool {
186        let mut token: HANDLE = std::ptr::null_mut();
187
188        // SAFETY: `GetCurrentProcess` returns a pseudo-handle needing no cleanup,
189        // and `token` is a valid out-pointer left untouched on failure.
190        if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
191            return false;
192        }
193
194        let mut elevation = TOKEN_ELEVATION { TokenIsElevated: 0 };
195        let mut returned = 0u32;
196
197        // SAFETY: `token` is a live handle opened with TOKEN_QUERY, and the
198        // buffer matches the size and layout expected for `TokenElevation`.
199        let ok = unsafe {
200            GetTokenInformation(
201                token,
202                TokenElevation,
203                (&raw mut elevation).cast(),
204                size_of::<TOKEN_ELEVATION>() as u32,
205                &mut returned,
206            )
207        } != 0;
208
209        // SAFETY: `token` was opened successfully above and is not used again.
210        unsafe { CloseHandle(token) };
211
212        ok && elevation.TokenIsElevated != 0
213    }
214
215    /// Windows has no capability to hold short of elevation, so the two
216    /// questions have one answer here.
217    pub fn can_send_raw() -> bool {
218        is_elevated()
219    }
220
221    /// Follows elevation, even where Npcap lets non-administrators capture, so an
222    /// unelevated run takes the connect path on every Windows machine.
223    pub fn can_inject_frames() -> bool {
224        is_elevated()
225    }
226}
227
228#[cfg(not(any(unix, windows)))]
229mod imp {
230    pub fn is_elevated() -> bool {
231        false
232    }
233
234    pub fn can_send_raw() -> bool {
235        false
236    }
237
238    pub fn can_inject_frames() -> bool {
239        false
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246
247    /// Root must see both `true`; a non-root run may still hold the capability.
248    #[test]
249    fn being_root_answers_both_questions_the_same_way() {
250        if is_elevated() {
251            assert!(can_send_raw(), "root is granted a raw socket");
252            assert_eq!(Privilege::current(), Privilege::Raw);
253        } else {
254            assert_eq!(
255                Privilege::current(),
256                Privilege::from_raw(can_send_raw() || can_inject_frames()),
257                "the distinction is made in one place"
258            );
259        }
260    }
261
262    /// A raw socket implies the link-layer handle everywhere the two are one
263    /// permission, and on macOS because root may open anything. The converse
264    /// does not hold.
265    #[test]
266    fn a_raw_socket_implies_frame_injection() {
267        if can_send_raw() {
268            assert!(can_inject_frames());
269        }
270    }
271
272    /// Either route answering yes is enough to scan with chosen packets.
273    #[test]
274    fn either_route_is_privilege_enough() {
275        if can_inject_frames() {
276            assert_eq!(Privilege::current(), Privilege::Raw);
277        }
278    }
279
280    /// The answer must not depend on how often it is asked.
281    #[test]
282    fn asking_repeatedly_gives_one_answer() {
283        let first = can_send_raw();
284        for _ in 0..64 {
285            assert_eq!(can_send_raw(), first);
286        }
287    }
288}