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.
16
17#![allow(unsafe_code)]
18
19use std::io::{self, Read};
20use std::mem::{size_of, zeroed};
21use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
22use std::os::unix::net::UnixStream;
23use std::path::{Path, PathBuf};
24use std::process::{Child, Command, Stdio};
25use std::sync::{Mutex, OnceLock, PoisonError};
26
27/// A kind of packet socket.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum Kind {
30    /// Frames' payloads, the link-layer header taken off and put on.
31    Datagram = 1,
32    /// Whole frames, header and all.
33    Raw = 2,
34}
35
36impl Kind {
37    fn from_octet(octet: u8) -> Option<Self> {
38        match octet {
39            1 => Some(Self::Datagram),
40            2 => Some(Self::Raw),
41            _ => None,
42        }
43    }
44
45    fn socket_type(self) -> libc::c_int {
46        match self {
47            Self::Datagram => libc::SOCK_DGRAM,
48            Self::Raw => libc::SOCK_RAW,
49        }
50    }
51}
52
53/// A packet socket of `kind` for no protocol, made here: it takes
54/// CAP_NET_RAW.
55fn make(kind: Kind) -> io::Result<OwnedFd> {
56    // SAFETY: plain system call with integer arguments.
57    let raw = unsafe { libc::socket(libc::AF_PACKET, kind.socket_type() | libc::SOCK_CLOEXEC, 0) };
58    if raw < 0 {
59        return Err(io::Error::last_os_error());
60    }
61    // SAFETY: `raw` is a socket this function just opened and owns.
62    Ok(unsafe { OwnedFd::from_raw_fd(raw) })
63}
64
65/// The helper started and installed, and where it is, once there is one.
66struct Installed {
67    broker: Mutex<Broker>,
68    program: PathBuf,
69}
70
71static INSTALLED: OnceLock<Installed> = OnceLock::new();
72
73/// The helper [`use_helper`] found last, started or not, for the error to
74/// name.
75static FOUND: Mutex<Option<PathBuf>> = Mutex::new(None);
76
77/// A packet socket of `kind`: from the helper when one is installed, else
78/// made here. The error for one the capability is missing for carries
79/// [`crate::Blocked::RawCapability`]. For crates on this one opening
80/// sockets of their own, as avb-net does for AVTP streams.
81pub fn open(kind: Kind) -> io::Result<OwnedFd> {
82    let result = match INSTALLED.get() {
83        Some(installed) => installed
84            .broker
85            .lock()
86            .unwrap_or_else(PoisonError::into_inner)
87            .socket(kind),
88        None => make(kind),
89    };
90    result.map_err(|error| match error.raw_os_error() {
91        Some(libc::EPERM | libc::EACCES) => crate::socket::raw_capability(),
92        _ => error,
93    })
94}
95
96/// The program that must hold CAP_NET_RAW for raw sockets to open: the
97/// installed helper, or the one found that could not start, else this
98/// one. An app names it in the command it offers to grant the capability.
99pub fn needs_capability() -> Option<PathBuf> {
100    INSTALLED
101        .get()
102        .map(|installed| installed.program.clone())
103        .or_else(|| FOUND.lock().unwrap_or_else(PoisonError::into_inner).clone())
104        .or_else(|| std::env::current_exe().ok())
105}
106
107/// Has every raw socket this crate opens from now on come from `broker`.
108/// Only the first broker installed is kept; a later one is dropped, its
109/// helper stopping.
110pub fn install(broker: Broker) {
111    let program = broker.program.clone();
112    let _ = INSTALLED.set(Installed {
113        broker: Mutex::new(broker),
114        program,
115    });
116}
117
118/// Whether a helper is installed.
119pub fn installed() -> bool {
120    INSTALLED.get().is_some()
121}
122
123/// Starts and installs the app's helper, `name`, once: found beside the
124/// running program, or beside the folder it is in, as for an example, or
125/// in one of `folders`, where packages put it. Later calls do nothing
126/// once one is installed, and try again after one failed, as after the
127/// helper is granted the capability.
128pub fn use_helper(name: &str, folders: &[&Path]) -> io::Result<()> {
129    static STARTING: Mutex<()> = Mutex::new(());
130    let _one_at_a_time = STARTING.lock().unwrap_or_else(PoisonError::into_inner);
131    if installed() {
132        return Ok(());
133    }
134    let program = find(name, folders).ok_or_else(|| {
135        io::Error::new(
136            io::ErrorKind::NotFound,
137            format!("the raw Ethernet helper, {name}, is not installed beside this program"),
138        )
139    })?;
140    *FOUND.lock().unwrap_or_else(PoisonError::into_inner) = Some(program.clone());
141    install(Broker::start(&program)?);
142    Ok(())
143}
144
145/// Where the helper `name` is, as [`use_helper`] looks for it.
146fn find(name: &str, folders: &[&Path]) -> Option<PathBuf> {
147    let beside = std::env::current_exe()
148        .ok()
149        .and_then(|program| program.parent().map(Path::to_path_buf));
150    let mut places = Vec::new();
151    if let Some(folder) = beside {
152        places.push(folder.join(name));
153        if let Some(parent) = folder.parent() {
154            places.push(parent.join(name));
155        }
156    }
157    places.extend(folders.iter().map(|folder| folder.join(name)));
158    places.into_iter().find(|place| place.is_file())
159}
160
161/// A running helper, and the socket to it. Dropping it stops the helper.
162pub struct Broker {
163    stream: UnixStream,
164    child: Child,
165    program: PathBuf,
166}
167
168impl Broker {
169    /// Starts the helper at `program` and asks it for a first socket, so a
170    /// helper that lacks the capability is found out here: the error then
171    /// carries [`crate::Blocked::RawCapability`], naming the helper.
172    pub fn start(program: &Path) -> io::Result<Self> {
173        let (ours, theirs) = UnixStream::pair()?;
174        let child = Command::new(program)
175            .stdin(Stdio::from(OwnedFd::from(theirs)))
176            .stdout(Stdio::null())
177            .spawn()?;
178        let mut broker = Self {
179            stream: ours,
180            child,
181            program: program.to_owned(),
182        };
183        match broker.socket(Kind::Datagram) {
184            Ok(_) => Ok(broker),
185            Err(error) if matches!(error.raw_os_error(), Some(libc::EPERM | libc::EACCES)) => {
186                let program = program.display();
187                Err(io::Error::new(
188                    io::ErrorKind::PermissionDenied,
189                    format!(
190                        "raw Ethernet needs CAP_NET_RAW on the helper; grant it with: sudo \
191                         setcap cap_net_raw+ep {program}"
192                    ),
193                ))
194            }
195            Err(error) => Err(error),
196        }
197    }
198
199    /// Asks the helper for a socket of `kind`.
200    fn socket(&mut self, kind: Kind) -> io::Result<OwnedFd> {
201        use std::io::Write;
202        self.stream.write_all(&[kind as u8])?;
203        let (status, fd) = receive(self.stream.as_raw_fd())?;
204        match (status, fd) {
205            (0, Some(fd)) => Ok(fd),
206            (0, None) => Err(io::Error::other("the helper sent no socket")),
207            (errno, _) => Err(io::Error::from_raw_os_error(errno)),
208        }
209    }
210}
211
212impl Drop for Broker {
213    fn drop(&mut self) {
214        // Closing our end ends the helper's requests.
215        let _ = self.stream.shutdown(std::net::Shutdown::Both);
216        let _ = self.child.wait();
217    }
218}
219
220/// The room a message with one descriptor beside it takes.
221fn control_room() -> usize {
222    // SAFETY: CMSG_SPACE only computes a length.
223    unsafe { libc::CMSG_SPACE(size_of::<RawFd>() as u32) as usize }
224}
225
226/// Sends `status`, and `fd` beside it when there is one.
227fn send(socket: RawFd, status: i32, fd: Option<RawFd>) -> io::Result<()> {
228    let mut data = status.to_ne_bytes();
229    let mut iov = libc::iovec {
230        iov_base: data.as_mut_ptr().cast(),
231        iov_len: data.len(),
232    };
233    let mut control = vec![0u8; control_room()];
234    // SAFETY: msghdr is plain data, valid when zeroed.
235    let mut message: libc::msghdr = unsafe { zeroed() };
236    message.msg_iov = &raw mut iov;
237    message.msg_iovlen = 1;
238    if let Some(fd) = fd {
239        message.msg_control = control.as_mut_ptr().cast();
240        message.msg_controllen = control.len() as _;
241        // SAFETY: the control buffer has room for one header and one
242        // descriptor, as CMSG_SPACE said, and lives through the call.
243        unsafe {
244            let header = libc::CMSG_FIRSTHDR(&raw const message);
245            (*header).cmsg_level = libc::SOL_SOCKET;
246            (*header).cmsg_type = libc::SCM_RIGHTS;
247            (*header).cmsg_len = libc::CMSG_LEN(size_of::<RawFd>() as u32) as _;
248            libc::CMSG_DATA(header).cast::<RawFd>().write_unaligned(fd);
249        }
250    }
251    // SAFETY: `message` points at buffers that live through the call.
252    if unsafe { libc::sendmsg(socket, &raw const message, 0) } < 0 {
253        return Err(io::Error::last_os_error());
254    }
255    Ok(())
256}
257
258/// Receives a status, and the descriptor beside it if any, close on exec.
259fn receive(socket: RawFd) -> io::Result<(i32, Option<OwnedFd>)> {
260    let mut data = [0u8; 4];
261    let mut iov = libc::iovec {
262        iov_base: data.as_mut_ptr().cast(),
263        iov_len: data.len(),
264    };
265    let mut control = vec![0u8; control_room()];
266    // SAFETY: msghdr is plain data, valid when zeroed.
267    let mut message: libc::msghdr = unsafe { zeroed() };
268    message.msg_iov = &raw mut iov;
269    message.msg_iovlen = 1;
270    message.msg_control = control.as_mut_ptr().cast();
271    message.msg_controllen = control.len() as _;
272    // SAFETY: `message` points at buffers that live through the call.
273    let read = unsafe { libc::recvmsg(socket, &raw mut message, libc::MSG_CMSG_CLOEXEC) };
274    if read < 0 {
275        return Err(io::Error::last_os_error());
276    }
277    if read as usize != data.len() {
278        return Err(io::Error::new(
279            io::ErrorKind::UnexpectedEof,
280            "the helper stopped",
281        ));
282    }
283    let mut fd = None;
284    // SAFETY: the kernel filled the control buffer and set its length;
285    // the macros walk the headers within it.
286    unsafe {
287        let mut header = libc::CMSG_FIRSTHDR(&raw const message);
288        while !header.is_null() {
289            if (*header).cmsg_level == libc::SOL_SOCKET && (*header).cmsg_type == libc::SCM_RIGHTS {
290                let raw = libc::CMSG_DATA(header).cast::<RawFd>().read_unaligned();
291                fd = Some(OwnedFd::from_raw_fd(raw));
292            }
293            header = libc::CMSG_NXTHDR(&raw const message, header);
294        }
295    }
296    Ok((i32::from_ne_bytes(data), fd))
297}
298
299/// The helper's whole program: answers the requests on its standard
300/// input until the app closes it. Returns the exit code.
301pub fn serve() -> i32 {
302    let input = 0;
303    // A Unix socket the app started us with, or nothing to serve.
304    let mut kind: libc::c_int = 0;
305    let mut length = size_of::<libc::c_int>() as libc::socklen_t;
306    // SAFETY: `kind` and `length` live through the call and fit it.
307    let is_socket = unsafe {
308        libc::getsockopt(
309            input,
310            libc::SOL_SOCKET,
311            libc::SO_TYPE,
312            (&raw mut kind).cast(),
313            &raw mut length,
314        )
315    } == 0;
316    if !is_socket {
317        eprintln!("this helper opens raw Ethernet sockets for the app that starts it");
318        return 2;
319    }
320    // SAFETY: standard input is ours for the life of the program.
321    let mut requests = unsafe { UnixStream::from_raw_fd(input) };
322    let mut octet = [0u8];
323    loop {
324        match requests.read(&mut octet) {
325            Ok(0) | Err(_) => return 0,
326            Ok(_) => {}
327        }
328        let made = Kind::from_octet(octet[0])
329            .ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))
330            .and_then(make);
331        let sent = match &made {
332            Ok(fd) => send(requests.as_raw_fd(), 0, Some(fd.as_raw_fd())),
333            Err(error) => send(
334                requests.as_raw_fd(),
335                error.raw_os_error().unwrap_or(libc::EIO),
336                None,
337            ),
338        };
339        // Ours closes once sent: the app holds its own copy.
340        drop(made);
341        if sent.is_err() {
342            return 0;
343        }
344    }
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350
351    /// A descriptor and a status go across a socket pair as the helper
352    /// sends them, the descriptor arriving as one of the receiver's own.
353    #[test]
354    fn a_descriptor_crosses() {
355        let (helper, app) = UnixStream::pair().unwrap();
356        let (left, mut right) = UnixStream::pair().unwrap();
357        send(helper.as_raw_fd(), 0, Some(left.as_raw_fd())).unwrap();
358        let (status, fd) = receive(app.as_raw_fd()).unwrap();
359        assert_eq!(status, 0);
360        let mut received = UnixStream::from(fd.expect("a descriptor"));
361        use std::io::Write;
362        received.write_all(b"hi").unwrap();
363        let mut heard = [0u8; 2];
364        right.read_exact(&mut heard).unwrap();
365        assert_eq!(&heard, b"hi");
366        // An error goes alone.
367        send(helper.as_raw_fd(), libc::EPERM, None).unwrap();
368        let (status, fd) = receive(app.as_raw_fd()).unwrap();
369        assert_eq!(status, libc::EPERM);
370        assert!(fd.is_none());
371    }
372
373    #[test]
374    fn only_packet_sockets_are_asked_for() {
375        assert_eq!(Kind::from_octet(1), Some(Kind::Datagram));
376        assert_eq!(Kind::from_octet(2), Some(Kind::Raw));
377        assert_eq!(Kind::from_octet(3), None);
378    }
379}