Skip to main content

raw_ether/
broker.rs

1//! Raw sockets from a helper, so the program using them holds no
2//! capability. On Linux a raw Ethernet socket takes CAP_NET_RAW only to be
3//! created; once open it works for whoever holds it. A program holding the
4//! capability itself runs as one other programs may not look into: the
5//! desktop portals refuse it file dialogs and screen sharing, and
6//! debuggers and crash reports pass it by. So an app ships a tiny helper
7//! of its own, the one file granted the capability, whose `main` calls
8//! [`serve`]; the app starts it with [`Broker::start`] and [`install`]s
9//! it, and every raw socket this crate opens comes from it from then on.
10//!
11//! The helper takes requests on its standard input, a Unix socket the app
12//! keeps the other end of: one octet, the kind of socket. It answers each
13//! with four octets, zero or the error number, and on success the new
14//! socket's descriptor beside them. It makes nothing but packet sockets,
15//! and stops when the app closes its end. A helper granted CAP_NET_ADMIN
16//! as well makes [`Kind::Launch`] sockets, whose frames a card sends at
17//! their times; one without answers EPERM for them.
18
19#![allow(unsafe_code)]
20
21use std::io::{self, Read};
22use std::mem::{size_of, zeroed};
23use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
24use std::os::unix::net::UnixStream;
25use std::path::{Path, PathBuf};
26use std::process::{Child, Command, Stdio};
27use std::sync::{Mutex, OnceLock, PoisonError};
28
29/// A kind of packet socket.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31#[non_exhaustive]
32pub enum Kind {
33    /// Frames' payloads, the link-layer header taken off and put on.
34    Datagram = 1,
35    /// Whole frames, header and all.
36    Raw = 2,
37    /// Whole frames, each sent at the launch time it carries on CLOCK_TAI
38    /// (SO_TXTIME), for the ETF queue discipline to hand to a card that
39    /// sends it at that time, and the frames ETF drops reported on the
40    /// socket's error queue. A departure time on CLOCK_TAI takes
41    /// CAP_NET_ADMIN as well as CAP_NET_RAW: a helper without it answers
42    /// EPERM, as one older than this kind answers EINVAL, and the app
43    /// takes a [`Kind::Raw`] socket instead. The drops come on the error
44    /// queue as SO_EE_ORIGIN_TXTIME, so an app also taking transmit time
45    /// stamps on it tells the two apart by origin. A launch time with no
46    /// ETF on the frame's queue is ignored, and the frame sent at once.
47    Launch = 3,
48}
49
50impl Kind {
51    fn from_octet(octet: u8) -> Option<Self> {
52        match octet {
53            1 => Some(Self::Datagram),
54            2 => Some(Self::Raw),
55            3 => Some(Self::Launch),
56            _ => None,
57        }
58    }
59
60    fn socket_type(self) -> libc::c_int {
61        match self {
62            Self::Datagram => libc::SOCK_DGRAM,
63            Self::Raw | Self::Launch => libc::SOCK_RAW,
64        }
65    }
66}
67
68/// A packet socket of `kind` for no protocol, made here: it takes
69/// CAP_NET_RAW, and CAP_NET_ADMIN too for [`Kind::Launch`]. The helper
70/// answers with the error number alone, so each stays the system's.
71fn make(kind: Kind) -> io::Result<OwnedFd> {
72    let fd = packet_socket(kind)?;
73    if kind == Kind::Launch {
74        launch_on_tai(&fd)?;
75    }
76    Ok(fd)
77}
78
79/// A packet socket of `kind`'s type for no protocol: it takes CAP_NET_RAW.
80fn packet_socket(kind: Kind) -> io::Result<OwnedFd> {
81    // SAFETY: plain system call with integer arguments.
82    let raw = unsafe { libc::socket(libc::AF_PACKET, kind.socket_type() | libc::SOCK_CLOEXEC, 0) };
83    if raw < 0 {
84        return Err(io::Error::last_os_error());
85    }
86    // SAFETY: `raw` is a socket this function just opened and owns.
87    Ok(unsafe { OwnedFd::from_raw_fd(raw) })
88}
89
90/// Has `fd`'s frames carry launch times: on CLOCK_TAI, ETF's clock,
91/// without deadline mode, as a frame should leave at its time and not
92/// before, and each frame dropped reported. It takes CAP_NET_ADMIN.
93fn launch_on_tai(fd: &OwnedFd) -> io::Result<()> {
94    let timing = libc::sock_txtime {
95        clockid: libc::CLOCK_TAI,
96        flags: libc::SOF_TXTIME_REPORT_ERRORS,
97    };
98    // SAFETY: `timing` lives through the call, and the length passed is
99    // its size.
100    let set = unsafe {
101        libc::setsockopt(
102            fd.as_raw_fd(),
103            libc::SOL_SOCKET,
104            libc::SO_TXTIME,
105            (&raw const timing).cast(),
106            size_of::<libc::sock_txtime>() as libc::socklen_t,
107        )
108    };
109    if set < 0 {
110        return Err(io::Error::last_os_error());
111    }
112    Ok(())
113}
114
115/// The error for a [`Kind::Launch`] socket refused for want of
116/// CAP_NET_ADMIN, naming the program that needs it.
117fn launch_capability(program: Option<&Path>) -> io::Error {
118    let grant = match program {
119        Some(program) => format!(
120            "; grant it with: sudo setcap cap_net_raw,cap_net_admin+ep {}",
121            program.display()
122        ),
123        None => String::new(),
124    };
125    io::Error::new(
126        io::ErrorKind::PermissionDenied,
127        format!("launch times on CLOCK_TAI need CAP_NET_ADMIN as well as CAP_NET_RAW{grant}"),
128    )
129}
130
131/// The helper started and installed, and where it is, once there is one.
132struct Installed {
133    broker: Mutex<Broker>,
134    program: PathBuf,
135}
136
137static INSTALLED: OnceLock<Installed> = OnceLock::new();
138
139/// The helper [`use_helper`] found last, started or not, for the error to
140/// name.
141static FOUND: Mutex<Option<PathBuf>> = Mutex::new(None);
142
143/// A packet socket of `kind`: from the helper when one is installed, else
144/// made here. The error for one CAP_NET_RAW is missing for carries
145/// [`crate::Blocked::RawCapability`]; a [`Kind::Launch`] one refused for
146/// want of CAP_NET_ADMIN is PermissionDenied, naming that capability. For
147/// crates on this one opening sockets of their own, as avb-net does for
148/// AVTP streams.
149pub fn open(kind: Kind) -> io::Result<OwnedFd> {
150    let result = match INSTALLED.get() {
151        Some(installed) => {
152            let made = installed
153                .broker
154                .lock()
155                .unwrap_or_else(PoisonError::into_inner)
156                .socket(kind);
157            match made {
158                // The helper made a socket as it started, so it holds
159                // CAP_NET_RAW: EPERM for a Launch one is CAP_NET_ADMIN.
160                Err(error) if kind == Kind::Launch && error.raw_os_error() == Some(libc::EPERM) => {
161                    return Err(launch_capability(Some(&installed.program)));
162                }
163                made => made,
164            }
165        }
166        None => match packet_socket(kind) {
167            Ok(fd) if kind == Kind::Launch => match launch_on_tai(&fd) {
168                Ok(()) => Ok(fd),
169                Err(error) if error.raw_os_error() == Some(libc::EPERM) => {
170                    let program = std::env::current_exe().ok();
171                    return Err(launch_capability(program.as_deref()));
172                }
173                Err(error) => Err(error),
174            },
175            made => made,
176        },
177    };
178    result.map_err(|error| match error.raw_os_error() {
179        Some(libc::EPERM | libc::EACCES) => crate::socket::raw_capability(),
180        _ => error,
181    })
182}
183
184/// The program that must hold CAP_NET_RAW for raw sockets to open: the
185/// installed helper, or the one found that could not start, else this
186/// one. An app names it in the command it offers to grant the capability.
187pub fn needs_capability() -> Option<PathBuf> {
188    INSTALLED
189        .get()
190        .map(|installed| installed.program.clone())
191        .or_else(|| FOUND.lock().unwrap_or_else(PoisonError::into_inner).clone())
192        .or_else(|| std::env::current_exe().ok())
193}
194
195/// Has every raw socket this crate opens from now on come from `broker`.
196/// Only the first broker installed is kept; a later one is dropped, its
197/// helper stopping.
198pub fn install(broker: Broker) {
199    let program = broker.program.clone();
200    let _ = INSTALLED.set(Installed {
201        broker: Mutex::new(broker),
202        program,
203    });
204}
205
206/// Whether a helper is installed.
207pub fn installed() -> bool {
208    INSTALLED.get().is_some()
209}
210
211/// Starts and installs the app's helper, `name`, once: found beside the
212/// running program, or beside the folder it is in, as for an example, or
213/// in one of `folders`, where packages put it. Later calls do nothing
214/// once one is installed, and try again after one failed, as after the
215/// helper is granted the capability.
216pub fn use_helper(name: &str, folders: &[&Path]) -> io::Result<()> {
217    static STARTING: Mutex<()> = Mutex::new(());
218    let _one_at_a_time = STARTING.lock().unwrap_or_else(PoisonError::into_inner);
219    if installed() {
220        return Ok(());
221    }
222    let program = find(name, folders).ok_or_else(|| {
223        io::Error::new(
224            io::ErrorKind::NotFound,
225            format!("the raw Ethernet helper, {name}, is not installed beside this program"),
226        )
227    })?;
228    *FOUND.lock().unwrap_or_else(PoisonError::into_inner) = Some(program.clone());
229    install(Broker::start(&program)?);
230    Ok(())
231}
232
233/// Where the helper `name` is, as [`use_helper`] looks for it.
234fn find(name: &str, folders: &[&Path]) -> Option<PathBuf> {
235    let beside = std::env::current_exe()
236        .ok()
237        .and_then(|program| program.parent().map(Path::to_path_buf));
238    let mut places = Vec::new();
239    if let Some(folder) = beside {
240        places.push(folder.join(name));
241        if let Some(parent) = folder.parent() {
242            places.push(parent.join(name));
243        }
244    }
245    places.extend(folders.iter().map(|folder| folder.join(name)));
246    places.into_iter().find(|place| place.is_file())
247}
248
249/// A running helper, and the socket to it. Dropping it stops the helper.
250pub struct Broker {
251    stream: UnixStream,
252    child: Child,
253    program: PathBuf,
254}
255
256impl Broker {
257    /// Starts the helper at `program` and asks it for a first socket, so a
258    /// helper that lacks the capability is found out here: the error then
259    /// carries [`crate::Blocked::RawCapability`], naming the helper.
260    pub fn start(program: &Path) -> io::Result<Self> {
261        let (ours, theirs) = UnixStream::pair()?;
262        let child = Command::new(program)
263            .stdin(Stdio::from(OwnedFd::from(theirs)))
264            .stdout(Stdio::null())
265            .spawn()?;
266        let mut broker = Self {
267            stream: ours,
268            child,
269            program: program.to_owned(),
270        };
271        match broker.socket(Kind::Datagram) {
272            Ok(_) => Ok(broker),
273            Err(error) if matches!(error.raw_os_error(), Some(libc::EPERM | libc::EACCES)) => {
274                let program = program.display();
275                Err(io::Error::new(
276                    io::ErrorKind::PermissionDenied,
277                    format!(
278                        "raw Ethernet needs CAP_NET_RAW on the helper; grant it with: sudo \
279                         setcap cap_net_raw+ep {program}"
280                    ),
281                ))
282            }
283            Err(error) => Err(error),
284        }
285    }
286
287    /// Asks the helper for a socket of `kind`.
288    fn socket(&mut self, kind: Kind) -> io::Result<OwnedFd> {
289        use std::io::Write;
290        self.stream.write_all(&[kind as u8])?;
291        let (status, fd) = receive(self.stream.as_raw_fd())?;
292        match (status, fd) {
293            (0, Some(fd)) => Ok(fd),
294            (0, None) => Err(io::Error::other("the helper sent no socket")),
295            (errno, _) => Err(io::Error::from_raw_os_error(errno)),
296        }
297    }
298}
299
300impl Drop for Broker {
301    fn drop(&mut self) {
302        // Closing our end ends the helper's requests.
303        let _ = self.stream.shutdown(std::net::Shutdown::Both);
304        let _ = self.child.wait();
305    }
306}
307
308/// The room a message with one descriptor beside it takes.
309fn control_room() -> usize {
310    // SAFETY: CMSG_SPACE only computes a length.
311    unsafe { libc::CMSG_SPACE(size_of::<RawFd>() as u32) as usize }
312}
313
314/// Sends `status`, and `fd` beside it when there is one.
315fn send(socket: RawFd, status: i32, fd: Option<RawFd>) -> io::Result<()> {
316    let mut data = status.to_ne_bytes();
317    let mut iov = libc::iovec {
318        iov_base: data.as_mut_ptr().cast(),
319        iov_len: data.len(),
320    };
321    let mut control = vec![0u8; control_room()];
322    // SAFETY: msghdr is plain data, valid when zeroed.
323    let mut message: libc::msghdr = unsafe { zeroed() };
324    message.msg_iov = &raw mut iov;
325    message.msg_iovlen = 1;
326    if let Some(fd) = fd {
327        message.msg_control = control.as_mut_ptr().cast();
328        message.msg_controllen = control.len() as _;
329        // SAFETY: the control buffer has room for one header and one
330        // descriptor, as CMSG_SPACE said, and lives through the call.
331        unsafe {
332            let header = libc::CMSG_FIRSTHDR(&raw const message);
333            (*header).cmsg_level = libc::SOL_SOCKET;
334            (*header).cmsg_type = libc::SCM_RIGHTS;
335            (*header).cmsg_len = libc::CMSG_LEN(size_of::<RawFd>() as u32) as _;
336            libc::CMSG_DATA(header).cast::<RawFd>().write_unaligned(fd);
337        }
338    }
339    // SAFETY: `message` points at buffers that live through the call.
340    if unsafe { libc::sendmsg(socket, &raw const message, 0) } < 0 {
341        return Err(io::Error::last_os_error());
342    }
343    Ok(())
344}
345
346/// Receives a status, and the descriptor beside it if any, close on exec.
347fn receive(socket: RawFd) -> io::Result<(i32, Option<OwnedFd>)> {
348    let mut data = [0u8; 4];
349    let mut iov = libc::iovec {
350        iov_base: data.as_mut_ptr().cast(),
351        iov_len: data.len(),
352    };
353    let mut control = vec![0u8; control_room()];
354    // SAFETY: msghdr is plain data, valid when zeroed.
355    let mut message: libc::msghdr = unsafe { zeroed() };
356    message.msg_iov = &raw mut iov;
357    message.msg_iovlen = 1;
358    message.msg_control = control.as_mut_ptr().cast();
359    message.msg_controllen = control.len() as _;
360    // SAFETY: `message` points at buffers that live through the call.
361    let read = unsafe { libc::recvmsg(socket, &raw mut message, libc::MSG_CMSG_CLOEXEC) };
362    if read < 0 {
363        return Err(io::Error::last_os_error());
364    }
365    if read as usize != data.len() {
366        return Err(io::Error::new(
367            io::ErrorKind::UnexpectedEof,
368            "the helper stopped",
369        ));
370    }
371    let mut fd = None;
372    // SAFETY: the kernel filled the control buffer and set its length;
373    // the macros walk the headers within it.
374    unsafe {
375        let mut header = libc::CMSG_FIRSTHDR(&raw const message);
376        while !header.is_null() {
377            if (*header).cmsg_level == libc::SOL_SOCKET && (*header).cmsg_type == libc::SCM_RIGHTS {
378                let raw = libc::CMSG_DATA(header).cast::<RawFd>().read_unaligned();
379                fd = Some(OwnedFd::from_raw_fd(raw));
380            }
381            header = libc::CMSG_NXTHDR(&raw const message, header);
382        }
383    }
384    Ok((i32::from_ne_bytes(data), fd))
385}
386
387/// The helper's whole program: answers the requests on its standard
388/// input until the app closes it. Returns the exit code.
389pub fn serve() -> i32 {
390    let input = 0;
391    // A Unix socket the app started us with, or nothing to serve.
392    let mut kind: libc::c_int = 0;
393    let mut length = size_of::<libc::c_int>() as libc::socklen_t;
394    // SAFETY: `kind` and `length` live through the call and fit it.
395    let is_socket = unsafe {
396        libc::getsockopt(
397            input,
398            libc::SOL_SOCKET,
399            libc::SO_TYPE,
400            (&raw mut kind).cast(),
401            &raw mut length,
402        )
403    } == 0;
404    if !is_socket {
405        eprintln!("this helper opens raw Ethernet sockets for the app that starts it");
406        return 2;
407    }
408    // SAFETY: standard input is ours for the life of the program.
409    let mut requests = unsafe { UnixStream::from_raw_fd(input) };
410    let mut octet = [0u8];
411    loop {
412        match requests.read(&mut octet) {
413            Ok(0) | Err(_) => return 0,
414            Ok(_) => {}
415        }
416        let made = Kind::from_octet(octet[0])
417            .ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))
418            .and_then(make);
419        let sent = match &made {
420            Ok(fd) => send(requests.as_raw_fd(), 0, Some(fd.as_raw_fd())),
421            Err(error) => send(
422                requests.as_raw_fd(),
423                error.raw_os_error().unwrap_or(libc::EIO),
424                None,
425            ),
426        };
427        // Ours closes once sent: the app holds its own copy.
428        drop(made);
429        if sent.is_err() {
430            return 0;
431        }
432    }
433}
434
435#[cfg(test)]
436mod tests {
437    use super::*;
438
439    /// A descriptor and a status go across a socket pair as the helper
440    /// sends them, the descriptor arriving as one of the receiver's own.
441    #[test]
442    fn a_descriptor_crosses() {
443        let (helper, app) = UnixStream::pair().unwrap();
444        let (left, mut right) = UnixStream::pair().unwrap();
445        send(helper.as_raw_fd(), 0, Some(left.as_raw_fd())).unwrap();
446        let (status, fd) = receive(app.as_raw_fd()).unwrap();
447        assert_eq!(status, 0);
448        let mut received = UnixStream::from(fd.expect("a descriptor"));
449        use std::io::Write;
450        received.write_all(b"hi").unwrap();
451        let mut heard = [0u8; 2];
452        right.read_exact(&mut heard).unwrap();
453        assert_eq!(&heard, b"hi");
454        // An error goes alone.
455        send(helper.as_raw_fd(), libc::EPERM, None).unwrap();
456        let (status, fd) = receive(app.as_raw_fd()).unwrap();
457        assert_eq!(status, libc::EPERM);
458        assert!(fd.is_none());
459    }
460
461    #[test]
462    fn only_packet_sockets_are_asked_for() {
463        assert_eq!(Kind::from_octet(1), Some(Kind::Datagram));
464        assert_eq!(Kind::from_octet(2), Some(Kind::Raw));
465        assert_eq!(Kind::from_octet(3), Some(Kind::Launch));
466        assert_eq!(Kind::from_octet(4), None);
467        for kind in [Kind::Datagram, Kind::Raw, Kind::Launch] {
468            assert_eq!(Kind::from_octet(kind as u8), Some(kind));
469        }
470    }
471
472    #[test]
473    fn a_launch_socket_refused_names_cap_net_admin() {
474        let error = launch_capability(Some(Path::new("/usr/lib/app/helper")));
475        assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
476        // No error number, so open() does not take it for CAP_NET_RAW.
477        assert_eq!(error.raw_os_error(), None);
478        let text = error.to_string();
479        assert!(text.contains("CAP_NET_ADMIN"), "{text}");
480        assert!(
481            text.ends_with("setcap cap_net_raw,cap_net_admin+ep /usr/lib/app/helper"),
482            "{text}"
483        );
484        assert!(!launch_capability(None).to_string().contains("setcap"));
485    }
486}