rscap 0.3.2

Cross-platform packet capture and transmission utilities
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
// SPDX-License-Identifier: MIT OR Apache-2.0
//
// Copyright (c) 2024 Nathaniel Bennett <me[at]nathanielbennett[dotcom]>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Link-layer address structures.
//!
//! Link-layer addresses may take different byte formats depending on the link-layer protocol in use.
//! To account for this, link-layer addresses are strongly coupled to protocol by defining distinct
//! address types for each link-layer protocol available. A generalized type of all of these possible
//! protocols is additionally made available as [`L2AddrAny`].

use std::fmt::{Debug, Display};
use std::str::FromStr;
use std::{array, io};

use crate::Interface;

use pkts_common::Buffer;

/// A link-layer protocol identifier.
///
/// This value corresponds directly to `libc::ETH_P_*` protocol specifier values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum L2Protocol {
    All,
    Ip,
    Other(u16),
}

impl From<u16> for L2Protocol {
    #[inline]
    fn from(value: u16) -> Self {
        match value as i32 {
            libc::ETH_P_ALL => L2Protocol::All,
            libc::ETH_P_IP => L2Protocol::Ip,
            _ => L2Protocol::Other(value),
        }
    }
}

impl From<L2Protocol> for u16 {
    #[inline]
    fn from(value: L2Protocol) -> Self {
        match value {
            L2Protocol::All => libc::ETH_P_ALL as u16,
            L2Protocol::Ip => libc::ETH_P_IP as u16,
            L2Protocol::Other(val) => val,
        }
    }
}

/// Defines a generic link-layer address.
pub trait L2Addr: TryFrom<libc::sockaddr_ll> {
    /// The link-layer protocol associated with the address type.
    fn protocol(&self) -> L2Protocol;

    /// The interface packets are sent to or received from.
    fn interface(&self) -> Interface;

    /// Set the interface the packet is sent to or received from.
    ///
    /// This will only change the interface for the `L2Addr`, not for any socket the address was
    /// retrieved from. To change the interface of a socket, use `bind()`.
    fn set_interface(&mut self, iface: Interface);

    /// Constructs a [`sockaddr_ll`](libc::sockaddr_ll) struct from the given address.
    fn to_sockaddr(&self) -> io::Result<libc::sockaddr_ll>;
}

/// An error in converting the format of an address.
///
/// This type encompasses errors in parsing either a `sockaddr_*` type or a string into an address.
#[derive(Debug)]
pub struct AddrConversionError {
    reason: &'static str,
}

impl AddrConversionError {
    fn new(reason: &'static str) -> Self {
        Self { reason }
    }

    /// Returns a string describing the nature of the conversion error.
    #[inline]
    pub fn as_str(&self) -> &str {
        self.reason
    }
}

/// A MAC (Media Access Control) address.
pub struct MacAddr {
    addr: [u8; 6],
}

impl From<[u8; 6]> for MacAddr {
    #[inline]
    fn from(value: [u8; 6]) -> Self {
        Self { addr: value }
    }
}

impl From<MacAddr> for [u8; 6] {
    #[inline]
    fn from(value: MacAddr) -> Self {
        value.addr
    }
}

impl Debug for MacAddr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MacAddress")
            .field(
                "addr",
                &format!(
                    "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}",
                    self.addr[0],
                    self.addr[1],
                    self.addr[2],
                    self.addr[3],
                    self.addr[4],
                    self.addr[5]
                ),
            )
            .finish()
    }
}

impl Display for MacAddr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}",
            self.addr[0], self.addr[1], self.addr[2], self.addr[3], self.addr[4], self.addr[5]
        )
    }
}

impl FromStr for MacAddr {
    type Err = AddrConversionError; // TODO: change to MacAddrParseError?

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut addr = [0u8; 6];
        let mut addr_idx = 0;

        if let Some(delim @ (b':' | b'-')) = s.as_bytes().get(2) {
            // Hexadecimal separated by colons (XX:XX:XX:XX:XX:XX) or dashes (XX-XX-XX-XX-XX-XX)

            if s.bytes().len() != 17 {
                return Err(AddrConversionError::new("invalid length MAC address"));
            }

            for (idx, mut b) in s.bytes().enumerate() {
                let mod3_idx = idx % 3;
                if (mod3_idx) == 2 {
                    if b != *delim {
                        return Err(AddrConversionError::new(
                            "invalid character in MAC address: expected colon/dash",
                        ));
                    }
                    addr_idx += 1;
                } else {
                    b = match b {
                        b'0'..=b'9' => b - b'0',
                        b'a'..=b'f' => 10 + (b - b'a'),
                        b'A'..=b'F' => 10 + (b - b'A'),
                        _ => {
                            return Err(AddrConversionError::new(
                                "invalid character in MAC address: expected hexadecimal value",
                            ))
                        }
                    };

                    if mod3_idx == 0 {
                        b <<= 4;
                    }

                    addr[addr_idx] |= b;
                }
            }
        } else if let Some(b'.') = s.as_bytes().get(4) {
            // Hexadecimal separated by dots (XXXX.XXXX.XXXX)

            if s.bytes().len() != 14 {
                return Err(AddrConversionError::new("invalid length MAC address"));
            }

            for (idx, mut b) in s.bytes().enumerate() {
                let mod5_idx = idx % 5;
                if (mod5_idx) == 4 {
                    if b != b'.' {
                        return Err(AddrConversionError::new("invalid character in MAC address: expected '.' after four hexadecimal values"));
                    }
                } else {
                    b = match b {
                        b'0'..=b'9' => b - b'0',
                        b'a'..=b'f' => 10 + (b - b'a'),
                        b'A'..=b'F' => 10 + (b - b'A'),
                        _ => {
                            return Err(AddrConversionError::new(
                                "invalid character in MAC address: expected hexadecimal value",
                            ))
                        }
                    };

                    if mod5_idx & 0b1 == 0 {
                        // Evens, i.e. every first hex value in a byte
                        addr[addr_idx] = b << 4;
                    } else {
                        // Odds, i.e. every 2nd hex value
                        addr[addr_idx] |= b;
                        addr_idx += 1;
                    }
                }
            }
        } else {
            // Unseparated hexadecimal (XXXXXXXXXXXX)

            if s.bytes().len() != 12 {
                return Err(AddrConversionError::new("invalid length MAC address"));
            }

            for (idx, mut b) in s.bytes().enumerate() {
                b = match b {
                    b'0'..=b'9' => b - b'0',
                    b'a'..=b'f' => 10 + (b - b'a'),
                    b'A'..=b'F' => 10 + (b - b'A'),
                    _ => {
                        return Err(AddrConversionError::new(
                            "invalid character in MAC address: expected hexadecimal value",
                        ))
                    }
                };

                let even_bit = (idx & 0b1) == 0;

                if even_bit {
                    // Evens, i.e. every first hex value in a byte
                    addr[addr_idx] = b << 4;
                } else {
                    // Odds, i.e. every 2nd hex value
                    addr[addr_idx] |= b;
                    addr_idx += 1;
                }
            }
        }

        Ok(Self { addr })
    }
}

// TODO: ETH_P_IP and similar only capture incoming traffic. You need
// ETH_P_ALL to capture outgoing traffic.

/// A link-layer address corresponding to the `ETH_P_ALL` protocol.
pub struct L2AddrAll {
    iface: Interface,
}

impl L2AddrAll {
    #[inline]
    pub fn interface(&self) -> Interface {
        self.iface
    }
}

/// A link-layer address corresponding to the `ETH_P_IP` protocol.
pub struct L2AddrIp {
    addr: MacAddr,
    iface: Interface,
}

impl TryFrom<libc::sockaddr_ll> for L2AddrIp {
    type Error = io::Error;

    #[inline]
    fn try_from(value: libc::sockaddr_ll) -> Result<Self, Self::Error> {
        if value.sll_family != libc::AF_PACKET as u16 {
            return Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "unrecognized address family (not AF_PACKET)",
            ));
        }

        if value.sll_protocol != libc::ETH_P_IP as u16 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "sockaddr link-layer protocol did not match type (expected {}, was {})",
                    libc::ETH_P_IP as u16,
                    value.sll_protocol
                ),
            ));
        }

        if value.sll_halen != 6 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "invalid sockaddr link-layer address length",
            ));
        }

        let addr: [u8; 6] = array::from_fn(|i| value.sll_addr[i]);

        Ok(L2AddrIp {
            addr: MacAddr { addr },
            iface: Interface::from_index(value.sll_ifindex as u32)?,
        })
    }
}

impl L2Addr for L2AddrIp {
    #[inline]
    fn protocol(&self) -> L2Protocol {
        L2Protocol::Ip
    }

    #[inline]
    fn interface(&self) -> Interface {
        self.iface
    }

    #[inline]
    fn set_interface(&mut self, iface: Interface) {
        self.iface = iface;
    }

    fn to_sockaddr(&self) -> io::Result<libc::sockaddr_ll> {
        let sll_addr = array::from_fn(|i| *self.addr.addr.get(i).unwrap_or(&0));

        Ok(libc::sockaddr_ll {
            sll_family: libc::AF_PACKET as u16,
            sll_protocol: libc::ETH_P_IP as u16,
            sll_ifindex: self.iface.index()? as i32,
            sll_hatype: 0,
            sll_pkttype: 0,
            sll_halen: 6,
            sll_addr,
        })
    }
}

/// A type encompassing any Link-Layer address.
pub enum L2AddrAny {
    /// A link-layer address containing an Internet Protocol packet.
    Ip(L2AddrIp),
    /// Some other link-layer address type that does not have an explicit type defined.
    Other(L2AddrUnspec),
}

impl TryFrom<libc::sockaddr_ll> for L2AddrAny {
    type Error = io::Error;

    #[inline]
    fn try_from(value: libc::sockaddr_ll) -> Result<Self, Self::Error> {
        Ok(match value.sll_protocol as i32 {
            libc::ETH_P_IP => Self::Ip(L2AddrIp::try_from(value)?),
            _ => Self::Other(L2AddrUnspec::try_from(value)?),
        })
    }
}

impl L2Addr for L2AddrAny {
    #[inline]
    fn protocol(&self) -> L2Protocol {
        match self {
            L2AddrAny::Ip(addr_ip) => addr_ip.protocol(),
            L2AddrAny::Other(addr_other) => addr_other.protocol(),
        }
    }

    #[inline]
    fn interface(&self) -> Interface {
        match self {
            L2AddrAny::Ip(addr_ip) => addr_ip.interface(),
            L2AddrAny::Other(addr_other) => addr_other.interface(),
        }
    }

    #[inline]
    fn set_interface(&mut self, iface: Interface) {
        match self {
            L2AddrAny::Ip(addr_ip) => addr_ip.set_interface(iface),
            L2AddrAny::Other(addr_other) => addr_other.set_interface(iface),
        }
    }

    #[inline]
    fn to_sockaddr(&self) -> io::Result<libc::sockaddr_ll> {
        match self {
            L2AddrAny::Ip(addr_ip) => addr_ip.to_sockaddr(),
            L2AddrAny::Other(addr_other) => addr_other.to_sockaddr(),
        }
    }
}

/// An unspecified link-layer address.
pub struct L2AddrUnspec {
    addr: Buffer<u8, 8>,
    iface: Interface,
    protocol: L2Protocol,
}

impl TryFrom<libc::sockaddr_ll> for L2AddrUnspec {
    type Error = io::Error;

    fn try_from(value: libc::sockaddr_ll) -> Result<Self, Self::Error> {
        if value.sll_family != libc::AF_PACKET as u16 {
            return Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "unrecognized address family (not AF_PACKET)",
            ));
        }

        let mut addr = Buffer::new();
        match value.sll_addr.get(..value.sll_halen as usize) {
            None => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "invalid sockaddr link-layer address length",
                ))
            }
            Some(s) => addr.append(s),
        }

        Ok(L2AddrUnspec {
            addr,
            iface: Interface::from_index(value.sll_ifindex as u32)?,
            protocol: value.sll_protocol.into(),
        })
    }
}

impl L2Addr for L2AddrUnspec {
    #[inline]
    fn protocol(&self) -> L2Protocol {
        self.protocol
    }

    #[inline]
    fn interface(&self) -> Interface {
        self.iface
    }

    #[inline]
    fn set_interface(&mut self, iface: Interface) {
        self.iface = iface;
    }

    fn to_sockaddr(&self) -> io::Result<libc::sockaddr_ll> {
        let sll_addr = array::from_fn(|i| *self.addr.as_slice().get(i).unwrap_or(&0));

        Ok(libc::sockaddr_ll {
            sll_family: libc::AF_PACKET as u16,
            sll_protocol: libc::ETH_P_IP as u16,
            sll_ifindex: self.iface.index()? as i32,
            sll_hatype: 0,
            sll_pkttype: 0,
            sll_halen: 6,
            sll_addr,
        })
    }
}