rawether 0.2.0

Raw layer-2 Ethernet I/O: AF_PACKET with zero-copy rings, hardware receive and transmit timestamps, SO_TXTIME and classic BPF on Linux; BPF devices on macOS and FreeBSD.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! Raw layer-2 Ethernet I/O.
//!
//! Open a [`Socket`] on a named interface, choose which frames reach it, and send and receive
//! whole Ethernet frames — with the kernel features that make that fast and precise:
//!
//! | | Linux (AF_PACKET) | macOS, FreeBSD (BPF) |
//! |---|---|---|
//! | EtherType filter, tagged or not; custom classic BPF | ✓ in kernel | ✓ in kernel |
//! | Multicast membership, all-multicast, promiscuous | ✓ | ✓ (all-multicast via promiscuous) |
//! | Receive ring (TPACKET_V3), zero-copy | ✓, `recvmsg` fallback | read buffer |
//! | Receive timestamps | hardware or software, labelled | software |
//! | Stripped VLAN tags put back | ✓ | not needed |
//! | Batched send | `sendmmsg` | loop |
//! | Launch-time send (`SO_TXTIME`), `SO_PRIORITY`, qdisc bypass | ✓ | — |
//! | Drop counters | ✓ | ✓ |
//! | Pollable fd, non-blocking, timed receive | ✓ | ✓ |
//!
//! Other platforms compile, and [`Socket::open`] returns [`std::io::ErrorKind::Unsupported`].
//!
//! ```no_run
//! use std::time::Duration;
//!
//! # fn main() -> std::io::Result<()> {
//! // LLDP and PTP frames, VLAN-tagged or not, with timestamps.
//! use rawether::EtherType;
//! let mut sock = rawether::Config::new("eth0").ethertypes([EtherType::LLDP, EtherType::PTP]).open()?;
//! while let Some(p) = sock.recv(Some(Duration::from_secs(1)))? {
//!     let Some(f) = p.frame() else { continue }; // shorter than a header: skip, never panic
//!     println!("{} sent {} at {:?}", f.source(), f.ethertype(), p.timestamp());
//! }
//! # Ok(()) }
//! ```
//!
//! Receiving hands out a [`Packet`] that borrows the socket's ring or buffer until the next
//! receive, so a steady-state loop never allocates.
//!
//! # Frames
//!
//! [`Packet::frame`] (or [`Frame::new`] on any byte slice) reads the Ethernet header: addresses,
//! up to two VLAN tags, the EtherType and the payload, without index arithmetic and without
//! panicking on a short frame. [`FrameBuilder`] writes a frame into a buffer you reuse, padded
//! to the Ethernet minimum, and [`Frame::reply`] answers a received one:
//!
//! ```no_run
//! # fn f(sock: &mut rawether::Socket) -> std::io::Result<()> {
//! let me = sock.mac_address();
//! let mut buf = Vec::with_capacity(1518);
//! loop {
//!     let Some(p) = sock.recv(None)? else { continue };
//!     let Some(reply) = p.frame().and_then(|f| f.reply(me)) else { continue };
//!     reply.write(&mut buf, b"pong"); // the builder holds no borrow of the packet
//!     sock.send(&buf)?;
//! }
//! # }
//! ```
//!
//! # Privileges
//!
//! Opening a socket needs `CAP_NET_RAW` on Linux and read/write access to `/dev/bpf*` on macOS
//! and FreeBSD. Grant the capability to the binary (`setcap cap_net_raw+ep`) rather than running
//! as root, and call [`drop_capabilities`] once every socket is open: the sockets keep working,
//! and the code that parses untrusted frames no longer holds the privilege.
//!
//! # Security
//!
//! The [threat model](threat_model) states what rawether defends against (the ring shared with
//! the kernel, hostile frame shapes, the privilege, descriptor leaks, silent drops), what it
//! trusts, and the test that guards each claim. Report a vulnerability privately through
//! [GitHub's private vulnerability reporting](https://github.com/hupe1980/rawether/security/advisories/new).
//!
//! More guides, including launch-time transmission, hardware timestamps and event-loop
//! integration, are on the [rawether website](https://hupe1980.github.io/rawether/).

#![deny(unsafe_op_in_unsafe_fn)]

pub mod bpf;
#[cfg(any(target_os = "macos", target_os = "freebsd", test, fuzzing))]
mod bpf_record;
mod config;
mod ethertype;
pub mod frame;
#[cfg(any(target_os = "linux", test))]
mod hwtstamp;
mod packet;
#[cfg(any(target_os = "linux", test, fuzzing))]
mod ring;
mod sys;
pub mod threat_model;
#[cfg(any(target_os = "linux", test, fuzzing))]
mod vlan;

use std::io;
use std::time::Duration;

pub use config::{Clock, Config, Filter, FrameRingConfig, RingConfig, RxMode, Timestamping, TxTime};
pub use ethertype::EtherType;
pub use frame::{Frame, FrameBuilder, TagKind, VlanTag};
pub use packet::{
    MacAddr, Packet, RxPath, Stats, Timestamp, TimestampInfo, TimestampSource, TxErrors, TxTimestamp,
};

/// An open raw socket on one interface.
#[derive(Debug)]
pub struct Socket {
    inner: sys::Inner,
}

impl Socket {
    /// Open a socket as `config` describes.
    ///
    /// The filter is in place before the socket is bound, so no frame it rejects is ever
    /// queued.
    pub fn open(config: &Config) -> io::Result<Socket> {
        config.validate()?;
        let program = config.program()?;
        Ok(Socket { inner: sys::Inner::open(config, program.as_ref())? })
    }

    /// The interface's name.
    pub fn interface(&self) -> &str {
        self.inner.interface()
    }

    /// The interface's index.
    pub fn index(&self) -> u32 {
        self.inner.index()
    }

    /// The interface's hardware address — the source address of frames this host sends.
    pub fn mac_address(&self) -> MacAddr {
        self.inner.mac()
    }

    /// How received frames reach user space.
    pub fn rx_path(&self) -> RxPath {
        self.inner.rx_path()
    }

    /// Wait for the next frame for at most `timeout` (`None`: indefinitely). `Ok(None)` when the
    /// time ran out, or at once on a non-blocking socket with nothing waiting.
    ///
    /// The packet borrows the socket, so its memory cannot be handed back to the kernel while it
    /// is in use (threat model T-02, SR-002):
    ///
    /// ```compile_fail
    /// # fn f(sock: &mut rawether::Socket) -> std::io::Result<()> {
    /// let first = sock.recv(None)?;
    /// let second = sock.recv(None)?; // error: `sock` is still borrowed by `first`
    /// drop(first);
    /// # Ok(()) }
    /// ```
    pub fn recv(&mut self, timeout: Option<Duration>) -> io::Result<Option<Packet<'_>>> {
        self.inner.recv(timeout)
    }

    /// The next frame if one is already waiting.
    pub fn try_recv(&mut self) -> io::Result<Option<Packet<'_>>> {
        self.inner.recv(Some(Duration::ZERO))
    }

    /// Send one frame: destination MAC first, at least 14 octets, no frame check sequence.
    pub fn send(&self, frame: &[u8]) -> io::Result<()> {
        check_frame(frame)?;
        self.inner.send(frame)
    }

    /// Send one frame to leave at `launch_ns` nanoseconds on the configured launch-time clock
    /// ([`Config::tx_time`]; read the clock with [`clock_now`]).
    pub fn send_at(&self, frame: &[u8], launch_ns: u64) -> io::Result<()> {
        check_frame(frame)?;
        self.inner.send_at(frame, launch_ns)
    }

    /// Send several frames with as few system calls as the platform allows. Returns how many
    /// were sent, which is all of them unless an error interrupted the batch.
    pub fn send_batch(&mut self, frames: &[&[u8]]) -> io::Result<usize> {
        for f in frames {
            check_frame(f)?;
        }
        self.inner.send_batch(frames)
    }

    /// Frames received and dropped since the socket was opened.
    pub fn stats(&mut self) -> io::Result<Stats> {
        self.inner.stats()
    }

    /// Launch-time frames the kernel dropped since the last call, by reason (Linux, with
    /// [`TxTime::report_errors`]). Always zero elsewhere.
    pub fn tx_errors(&mut self) -> io::Result<TxErrors> {
        self.inner.tx_errors()
    }

    /// The transmit timestamps this socket delivers: [`Timestamping::Off`] unless
    /// [`Config::tx_timestamping`] asked for them; a request for hardware stamps that the NIC
    /// cannot honour delivers [`Timestamping::Software`].
    pub fn tx_timestamping(&self) -> Timestamping {
        self.inner.tx_timestamping()
    }

    /// The identifier the next frame sent gets; a batch gets consecutive ones (wrapping). On
    /// Linux 6.13 and later identifiers are exact; before, the kernel numbers frames itself and
    /// a send it refuses after numbering (a qdisc drop) shifts later identifiers by one.
    pub fn next_tx_id(&self) -> u32 {
        self.inner.next_tx_id()
    }

    /// The next transmit timestamp, waiting for at most `timeout` (`None`: indefinitely; at once
    /// on a non-blocking socket). Timestamps may arrive out of order; match them by
    /// [`TxTimestamp::id`]. Fails with `InvalidInput` unless [`Config::tx_timestamping`] is on.
    ///
    /// ```no_run
    /// use std::time::Duration;
    /// use rawether::{Config, Timestamping};
    ///
    /// # fn main() -> std::io::Result<()> {
    /// # let frame = [0u8; 60];
    /// let mut sock = Config::new("eth0").tx_timestamping(Timestamping::Hardware).open()?;
    /// let id = sock.next_tx_id();
    /// sock.send(&frame)?;
    /// if let Some(t) = sock.tx_timestamp(Some(Duration::from_millis(10)))? {
    ///     assert_eq!(t.id, id);
    ///     println!("left at {:?} ({:?})", t.timestamp.as_nanos(), t.timestamp.source);
    /// }
    /// # Ok(()) }
    /// ```
    pub fn tx_timestamp(&mut self, timeout: Option<Duration>) -> io::Result<Option<TxTimestamp>> {
        self.inner.tx_timestamp(timeout)
    }

    /// What this socket's interface can timestamp, and its PTP hardware clock: see
    /// [`timestamp_info`].
    pub fn timestamp_info(&self) -> io::Result<TimestampInfo> {
        timestamp_info(self.interface())
    }

    /// The timestamps this socket delivers. [`Timestamping::Hardware`] when the NIC stamps
    /// received frames; a request for hardware timestamps that the NIC cannot honour delivers
    /// [`Timestamping::Software`]. Each frame's [`Timestamp::source`] says which clock stamped
    /// it.
    pub fn timestamping(&self) -> Timestamping {
        self.inner.timestamping()
    }

    /// Switch non-blocking mode.
    pub fn set_nonblocking(&mut self, on: bool) -> io::Result<()> {
        self.inner.set_nonblocking(on)
    }
}

#[cfg(unix)]
impl std::os::fd::AsFd for Socket {
    fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
        self.inner.as_fd()
    }
}

#[cfg(unix)]
impl std::os::fd::AsRawFd for Socket {
    fn as_raw_fd(&self) -> std::os::fd::RawFd {
        self.inner.as_fd().as_raw_fd()
    }
}

/// Give up the privilege that opening a socket needed, for the whole process, keeping every
/// socket already open.
///
/// On Linux this clears the calling thread's effective, permitted, inheritable and ambient
/// capability sets, removes every capability from the bounding set where the process may
/// (with `CAP_SETPCAP`), and sets `no_new_privs`, so no later `exec` regains privilege. Open
/// sockets keep working: the kernel checks `CAP_NET_RAW` only when one is created.
///
/// Capabilities are per thread. If any other thread of the process still holds one afterwards,
/// or that cannot be checked (no `/proc`), this returns an error rather than leaving a thread
/// privileged: call it after opening the sockets and before spawning threads. In an async
/// program, that means before building a multi-threaded runtime:
///
/// ```no_run
/// fn main() -> std::io::Result<()> {
///     let sock = rawether::Config::new("eth0").ethertypes([rawether::EtherType::PTP]).open()?;
///     rawether::drop_capabilities()?; // still the only thread
///     // ...then build the runtime (or spawn threads) and move `sock` into it.
///     # drop(sock);
///     Ok(())
/// }
/// ```
///
/// On macOS and FreeBSD the privilege is access to `/dev/bpf*`, which an open descriptor
/// already holds, and this does nothing. A process running as root keeps its user id: drop
/// that separately.
pub fn drop_capabilities() -> io::Result<()> {
    sys::drop_capabilities()
}

/// What `interface` can timestamp, and which PTP hardware clock (`/dev/ptp<index>`) its
/// hardware stamps come from. Needs no privilege. On macOS and FreeBSD, BPF stamps received
/// frames in software and there is no hardware clock.
///
/// ```no_run
/// # fn main() -> std::io::Result<()> {
/// let info = rawether::timestamp_info("eth0")?;
/// if let Some(phc) = info.phc_path() {
///     println!("hardware stamps on {}", phc.display());
/// }
/// # Ok(()) }
/// ```
pub fn timestamp_info(interface: &str) -> io::Result<TimestampInfo> {
    sys::timestamp_info(interface)
}

/// Read `clock` — for computing launch times.
pub fn clock_now(clock: Clock) -> io::Result<Duration> {
    sys::clock_now(clock)
}

fn check_frame(frame: &[u8]) -> io::Result<()> {
    if frame.len() < 14 {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("a frame of {} octets has no Ethernet header", frame.len()),
        ));
    }
    Ok(())
}

/// Entry points into the internal parsers for the fuzz targets in `fuzz/`. Not part of the API.
#[cfg(fuzzing)]
#[doc(hidden)]
pub mod fuzzing {
    /// Walk one TPACKET_V3 block as the receive ring does, re-inserting stripped tags.
    pub fn ring_walk(block: &mut [u8]) {
        let Some(mut cur) = crate::ring::Cursor::start(block) else { return };
        let mut found = Vec::new();
        while let Some((at, meta)) = cur.next(block) {
            assert!(at + meta.mac + meta.snaplen <= block.len());
            found.push((at + meta.mac, meta.snaplen, meta.stripped_vlan()));
        }
        for (start, len, tag) in found {
            if let (Some((tpid, tci)), Some(lo)) = (tag, start.checked_sub(4))
                && let Some(region) = block.get_mut(lo..start + len)
            {
                let _ = crate::vlan::reinsert(region, 4, len, tpid, tci);
            }
        }
    }

    /// Read a per-frame ring slot as the frame ring does.
    pub fn frame_slot(slot: &[u8]) {
        if let Some(m) = crate::ring::FrameMeta::read_v2(slot) {
            assert!(m.mac + m.snaplen <= slot.len());
        }
    }

    /// Parse a BPF read buffer with both platforms' layouts.
    pub fn bpf_records(buf: &[u8]) {
        for layout in [crate::bpf_record::Layout::MACOS, crate::bpf_record::Layout::FREEBSD_LP64] {
            let mut pos = 0;
            while let Some(r) = crate::bpf_record::next(buf, &mut pos, layout) {
                assert!(r.start + r.caplen <= buf.len());
            }
        }
    }

    /// Re-insert a tag into `buf` at `start` with `len`, as the plain path does.
    pub fn vlan_reinsert(buf: &mut [u8], start: usize, len: usize, tpid: u16, tci: u16) {
        let before = buf.to_vec();
        match crate::vlan::reinsert(buf, start, len, tpid, tci) {
            Some((s, l)) => assert!(s + l <= buf.len()),
            None => assert_eq!(buf, &before[..], "a refused re-insertion leaves the buffer alone"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[cfg_attr(miri, ignore)] // system calls
    fn opening_a_missing_interface_or_on_an_unsupported_platform_fails_cleanly() {
        let e = Socket::open(&Config::new("no-such-if0")).expect_err("no interface");
        assert!(
            matches!(
                e.kind(),
                io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied | io::ErrorKind::Unsupported
            ),
            "{e:?}"
        );
    }

    /// On macOS a BPF device on the loopback interface opens with access to `/dev/bpf*`, and
    /// without it fails naming what is missing.
    #[cfg(target_os = "macos")]
    #[test]
    #[cfg_attr(miri, ignore)] // system calls
    fn the_loopback_interface_opens_or_says_what_access_is_missing() {
        match Socket::open(&Config::new("lo0")) {
            Ok(s) => assert_eq!(s.rx_path(), RxPath::Bpf),
            Err(e) => {
                assert_eq!(e.kind(), io::ErrorKind::PermissionDenied, "{e}");
                assert!(e.to_string().contains("/dev/bpf"), "{e}");
            }
        }
    }

    /// Threat model T-07 (SR-007).
    #[test]
    fn the_default_configuration_is_neither_promiscuous_nor_all_multicast() {
        let c = Config::new("eth0");
        assert!(!c.promiscuous && !c.all_multicast);
    }

    #[test]
    fn a_frame_without_a_header_is_refused_before_any_system_call() {
        assert_eq!(check_frame(&[0; 13]).expect_err("short").kind(), io::ErrorKind::InvalidInput);
        assert!(check_frame(&[0; 14]).is_ok());
    }
}