forge
Explore
Log in

Don't you dare go Hollow

wifi_lab

Clone
★ 0

0 watching0 forksRust2.1 MiBb265998Tahinli1 month ago27 commits

rawsock.rs268 lines, 9.1 KiBHistoryRawDownload
1//! Raw layer-2 socket — the only module in the crate allowed to use `unsafe`.
2//!
3//! AF_PACKET/SOCK_RAW with ETH_P_ALL, bound to a single interface via
4//! sockaddr_ll. In monitor mode delivered frames are radiotap + 802.11;
5//! transmitted frames must already carry the radiotap INJECT_HDR prefix.
6
7use std::ffi::CString;
8use std::io;
9use std::mem::size_of;
10
11/// Receive buffer size covering any real 802.11 frame: the largest A-MSDU
12/// aggregate tops out at 11454 octets (802.11-2020 §9.3.2.1 max MPDU) and a
13/// monitor-mode radiotap header is at most a few hundred bytes; 16 KiB
14/// leaves generous headroom.
15pub const RECV_BUFSZ: usize = 16384;
16
17/// Outcome of [`RawSocket::recv_msg`]: bytes copied into the caller's
18/// buffer plus the frame's true on-wire length, so truncation is visible
19/// instead of silent.
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub struct RecvMsg {
22 /// Bytes actually written into the caller's buffer.
23 pub len: usize,
24 /// Full frame length as reported by the kernel (MSG_TRUNC).
25 pub orig_len: usize,
26}
27
28impl RecvMsg {
29 /// True when the frame didn't fit the buffer and `len` bytes are a
30 /// prefix of a longer packet.
31 pub fn truncated(&self) -> bool {
32 self.orig_len > self.len
33 }
34}
35
36pub struct RawSocket {
37 fd: i32,
38 #[allow(dead_code)]
39 ifindex: i32,
40}
41
42impl RawSocket {
43 /// AF_PACKET SOCK_RAW ETH_P_ALL bound to ifname. Requires CAP_NET_RAW.
44 pub fn open(ifname: &str) -> io::Result<Self> {
45 let cname = CString::new(ifname)
46 .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "ifname contains NUL"))?;
47 // SAFETY: plain libc calls on stack-allocated data; fd/checks below.
48 unsafe {
49 let ifindex = libc::if_nametoindex(cname.as_ptr());
50 if ifindex == 0 {
51 return Err(io::Error::new(
52 io::ErrorKind::NotFound,
53 format!("no such interface: {ifname}"),
54 ));
55 }
56 let fd = libc::socket(
57 libc::AF_PACKET,
58 libc::SOCK_RAW | libc::SOCK_CLOEXEC,
59 (libc::ETH_P_ALL as u16).to_be() as i32,
60 );
61 if fd < 0 {
62 return Err(io::Error::last_os_error());
63 }
64 let sll = libc::sockaddr_ll {
65 sll_family: libc::AF_PACKET as u16,
66 sll_protocol: (libc::ETH_P_ALL as u16).to_be(),
67 sll_ifindex: ifindex as i32,
68 sll_hatype: 0,
69 sll_pkttype: 0,
70 sll_halen: 0,
71 sll_addr: [0; 8],
72 };
73 if libc::bind(
74 fd,
75 &sll as *const libc::sockaddr_ll as *const libc::sockaddr,
76 size_of::<libc::sockaddr_ll>() as libc::socklen_t,
77 ) < 0
78 {
79 let err = io::Error::last_os_error();
80 libc::close(fd);
81 return Err(err);
82 }
83 Ok(RawSocket {
84 fd,
85 ifindex: ifindex as i32,
86 })
87 }
88 }
89
90 /// Truncation-aware receive: passes MSG_TRUNC on a packet socket, so
91 /// the kernel reports the frame's true length even when it exceeds
92 /// `buf`. The caller MUST check [`RecvMsg::truncated`] and drop the
93 /// prefix (or enlarge the buffer) — the buffer then holds only the
94 /// first `len` bytes of a longer frame.
95 pub fn recv_msg(&self, buf: &mut [u8]) -> io::Result<RecvMsg> {
96 loop {
97 // SAFETY: fd is a live socket owned by self; buf is valid for
98 // buf.len() writable bytes.
99 let n =
100 unsafe { libc::recv(self.fd, buf.as_mut_ptr().cast(), buf.len(), libc::MSG_TRUNC) };
101 if n >= 0 {
102 let orig_len = n as usize;
103 return Ok(RecvMsg {
104 len: orig_len.min(buf.len()),
105 orig_len,
106 });
107 }
108 let err = io::Error::last_os_error();
109 if err.kind() != io::ErrorKind::Interrupted {
110 return Err(err);
111 }
112 }
113 }
114
115 /// Transmit a frame prefixed with radiotap INJECT_HDR (len includes it).
116 pub fn send(&self, frame_with_radiotap: &[u8]) -> io::Result<usize> {
117 loop {
118 // SAFETY: fd is a live socket; slice is valid readable memory.
119 let n = unsafe {
120 libc::send(
121 self.fd,
122 frame_with_radiotap.as_ptr().cast(),
123 frame_with_radiotap.len(),
124 0,
125 )
126 };
127 if n >= 0 {
128 return Ok(n as usize);
129 }
130 let err = io::Error::last_os_error();
131 if err.kind() != io::ErrorKind::Interrupted {
132 return Err(err);
133 }
134 }
135 }
136
137 /// Receive timeout toggle for poll-style loops. 0 disables the timeout.
138 pub fn set_timeout(&self, ms: u32) -> io::Result<()> {
139 let tv = libc::timeval {
140 tv_sec: (ms / 1000) as libc::time_t,
141 tv_usec: ((ms % 1000) * 1000) as libc::suseconds_t,
142 };
143 // SAFETY: fd is a live socket; tv outlives the call.
144 let rc = unsafe {
145 libc::setsockopt(
146 self.fd,
147 libc::SOL_SOCKET,
148 libc::SO_RCVTIMEO,
149 &tv as *const libc::timeval as *const libc::c_void,
150 size_of::<libc::timeval>() as libc::socklen_t,
151 )
152 };
153 if rc < 0 {
154 return Err(io::Error::last_os_error());
155 }
156 Ok(())
157 }
158}
159
160impl Drop for RawSocket {
161 fn drop(&mut self) {
162 // SAFETY: fd came from socket() and is closed exactly once here.
163 unsafe {
164 libc::close(self.fd);
165 }
166 }
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172
173 /// Without root/CAP_NET_RAW this returns EPERM; with it, loopback opens
174 /// fine. Both outcomes are acceptable — the point is no panic and that a
175 /// successful open accepts a timeout.
176 #[test]
177 fn open_loopback_best_effort() {
178 match RawSocket::open("lo") {
179 Ok(sock) => {
180 assert!(sock.set_timeout(100).is_ok());
181 }
182 Err(e) => {
183 let k = e.kind();
184 assert!(matches!(
185 k,
186 io::ErrorKind::PermissionDenied
187 | io::ErrorKind::NotFound
188 | io::ErrorKind::Other
189 ));
190 }
191 }
192 }
193
194 #[test]
195 fn bogus_iface_is_an_error_not_a_panic() {
196 let res = RawSocket::open("no_such_iface_zz");
197 assert!(res.is_err());
198 }
199
200 /// MSG_TRUNC reporting semantics: a frame longer than the buffer shows
201 /// len == buf.len() < orig_len; anything else is complete.
202 #[test]
203 fn recv_msg_truncation_flag() {
204 let m = RecvMsg {
205 len: 100,
206 orig_len: 200,
207 };
208 assert!(m.truncated());
209 let m = RecvMsg {
210 len: 200,
211 orig_len: 200,
212 };
213 assert!(!m.truncated());
214 let m = RecvMsg {
215 len: 100,
216 orig_len: 100,
217 };
218 assert!(!m.truncated());
219 }
220
221 /// Live MSG_TRUNC round-trip: send a big UDP datagram over loopback via
222 /// an AF_PACKET socket and confirm recv_msg reports the full length
223 /// while delivering only a prefix. Skipped silently without
224 /// CAP_NET_RAW (same posture as `open_loopback_best_effort`).
225 #[test]
226 fn recv_msg_reports_full_length_on_truncation() {
227 let Ok(sock) = RawSocket::open("lo") else {
228 return; // no CAP_NET_RAW in the test sandbox
229 };
230 // UDP needs root for raw sends on lo through AF_PACKET? No — we
231 // send an ordinary UDP datagram; the packet socket sees it twice
232 // (outgoing + incoming) with the full L2/L3/L4 framing.
233 let udp = match std::net::UdpSocket::bind("127.0.0.1:0") {
234 Ok(s) => s,
235 Err(_) => return,
236 };
237 if udp.connect("127.0.0.1:9").is_err() {
238 return;
239 }
240 let payload = vec![0xabu8; 6000]; // fits loopback MTU (65536)
241 if udp.send(&payload).is_err() {
242 return;
243 }
244 sock.set_timeout(500).expect("set_timeout");
245 let mut tiny = [0u8; 128];
246 // Read until an over-long packet arrives: the datagram shows up as
247 // outgoing + incoming copies, both >128 bytes. Small stray traffic
248 // (ARP, ICMP errors) is skipped.
249 for _ in 0..8 {
250 match sock.recv_msg(&mut tiny) {
251 Ok(m) if m.truncated() => {
252 assert_eq!(m.len, tiny.len());
253 assert!(m.orig_len > tiny.len());
254 return;
255 }
256 Ok(_) => continue, // short frame — not ours, keep looking
257 Err(e)
258 if e.kind() == io::ErrorKind::WouldBlock
259 || e.kind() == io::ErrorKind::TimedOut =>
260 {
261 break;
262 }
263 Err(_) => continue,
264 }
265 }
266 panic!("no over-long packet observed on loopback packet socket");
267 }
268}