zond-engine 0.16.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
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
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! # The Host's Own Neighbour Table
//!
//! The cheapest source of addresses a scanner has, and the one the engine spent
//! its whole life ignoring.
//!
//! The operating system has been performing neighbour discovery all along. Every
//! address it has spoken to on a local segment recently is sitting in its
//! neighbour cache, already resolved to a MAC, obtained for no packets and no
//! waiting. On the segment this was written against, that table names twelve
//! devices over IPv6, against thirteen in the ARP table, and fourteen of its
//! addresses are global or unique-local ones the engine could not otherwise
//! learn at all, because the only IPv6 probe it sends is sourced from a
//! link-local address and so draws only link-local answers.
//!
//! ## Why this matters more for IPv6 than for IPv4
//!
//! An IPv4 segment can be swept: a `/24` is 256 ARP requests. An IPv6 segment
//! cannot, a `/64` holds 2^64 addresses, and the one probe that does reach a
//! whole IPv6 segment, the all-nodes echo, is optional to answer. A neighbor
//! solicitation is *not* optional, but it can only be aimed at an address
//! somebody already has.
//!
//! This is where those addresses come from. The table supplies candidates and
//! solicitation confirms them, which is the only combination that finds a host
//! that both ignores multicast echo and has never been named by a user.
//!
//! ## What it is not
//!
//! Not a census. The table holds neighbours *this host* has had reason to talk
//! to recently, so it is biased toward whatever this machine uses and says
//! nothing about the rest of the segment. Entries also go stale: an address in
//! the table is one that answered once, not one that is answering now. Both are
//! reasons to treat an entry as a lead to be confirmed rather than as a
//! discovered host: nothing here writes to the store.

use std::net::IpAddr;

use crate::model::mac::MacAddr;

/// One entry from the host's neighbour cache.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Neighbor {
    /// The neighbour's address.
    pub ip: IpAddr,
    /// Its link-layer address, when the entry is resolved.
    ///
    /// The crate's own [`MacAddr`] rather than the
    /// one belonging to whichever library read the table, on the reasoning
    /// [`Link`](crate::system::interface::Link) gives: a consumer should not
    /// have to know which crate this came from, any more than they have to know
    /// which syscall did. A library's own type here would put a pre-1.0 foreign
    /// type in the public API of the module making that argument.
    ///
    /// `None` for an entry the operating system created but has not completed:
    /// an address it is currently asking about. Those are still worth having:
    /// something on this host had a reason to look the address up, which is
    /// evidence it exists even though the neighbour has not answered yet.
    pub mac: Option<MacAddr>,
    /// The interface the entry belongs to, as a scope id.
    ///
    /// Required rather than incidental for IPv6: a link-local address from this
    /// table is meaningless without it, exactly as it is everywhere else in the
    /// engine. See [`ScopedIp`](crate::model::ip::scoped::ScopedIp).
    pub interface_index: u32,
}

/// Every IPv6 neighbour this host currently knows of.
///
/// Empty rather than an error when the table cannot be read: a scan that cannot
/// consult this source is a scan with fewer leads, not a failed one, and every
/// address it would have supplied is still reachable by the probes that do not
/// depend on it.
pub fn ipv6_neighbors() -> Vec<Neighbor> {
    platform::ipv6_neighbors()
}

// ══════════════════════════════════════════════════════════════════════════════
// macOS and BSD
// ══════════════════════════════════════════════════════════════════════════════

/// On BSD-derived systems the IPv6 neighbour cache *is* the routing table: each
/// entry is a host route carrying the `RTF_LLINFO` flag, whose gateway is a
/// link-layer address rather than another IP. That is precisely what `ndp -an`
/// reads, and it is reached through `sysctl` rather than through a socket.
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))]
mod platform {
    use std::mem;
    use std::net::{IpAddr, Ipv6Addr};

    use crate::model::mac::MacAddr;
    use libc::{
        AF_INET6, AF_LINK, CTL_NET, NET_RT_FLAGS, PF_ROUTE, RTA_DST, RTA_GATEWAY, RTF_LLINFO,
        c_int, c_void, rt_msghdr, size_t, sockaddr, sockaddr_dl, sockaddr_in6,
    };

    use super::Neighbor;
    use crate::warn;

    /// Socket addresses in a routing message are padded to a four-byte boundary,
    /// and a zero-length one still occupies that much.
    const SA_ALIGN: usize = mem::size_of::<u32>();

    /// A sockaddr's length rounded up to the alignment the routing socket pads
    /// each one to.
    fn roundup(len: usize) -> usize {
        if len == 0 {
            SA_ALIGN
        } else {
            (len + (SA_ALIGN - 1)) & !(SA_ALIGN - 1)
        }
    }

    /// The neighbour table as the BSD routing socket reports it.
    ///
    /// A `sysctl` walk over `NET_RT_FLAGS`, which hands back a run of routing
    /// messages that have to be stepped through by their own length fields.
    pub(super) fn ipv6_neighbors() -> Vec<Neighbor> {
        let mut mib: [c_int; 6] = [
            CTL_NET,
            PF_ROUTE,
            0,
            AF_INET6,
            NET_RT_FLAGS,
            RTF_LLINFO as c_int,
        ];

        let buffer = match dump(&mut mib) {
            Ok(buffer) => buffer,
            Err(e) => {
                warn!(
                    verbosity = 1,
                    "could not read the IPv6 neighbour table: {e}"
                );
                return Vec::new();
            }
        };

        parse(&buffer)
    }

    /// Reads a sysctl of unknown size: ask for the length, allocate, read.
    ///
    /// The two calls race against a table that changes between them, so a short
    /// read is retried once with the length the kernel reported the second time.
    /// A table that keeps growing faster than it can be read is reported rather
    /// than looped on.
    fn dump(mib: &mut [c_int]) -> std::io::Result<Vec<u8>> {
        for _ in 0..2 {
            let mut len: size_t = 0;
            // SAFETY: `mib` is a valid slice of the length passed alongside it,
            // and a null `oldp` with a non-null `oldlenp` is the documented way
            // to ask only for the size.
            let sized = unsafe {
                libc::sysctl(
                    mib.as_mut_ptr(),
                    mib.len() as u32,
                    std::ptr::null_mut(),
                    &mut len,
                    std::ptr::null_mut(),
                    0,
                )
            };
            if sized < 0 {
                return Err(std::io::Error::last_os_error());
            }
            if len == 0 {
                return Ok(Vec::new());
            }

            let mut buffer = vec![0u8; len];
            // SAFETY: `buffer` is `len` bytes and `len` is passed by pointer, so
            // the kernel writes no more than was allocated and reports how much
            // it used.
            let read = unsafe {
                libc::sysctl(
                    mib.as_mut_ptr(),
                    mib.len() as u32,
                    buffer.as_mut_ptr() as *mut c_void,
                    &mut len,
                    std::ptr::null_mut(),
                    0,
                )
            };
            if read < 0 {
                let err = std::io::Error::last_os_error();
                // The table grew between the two calls; ask again.
                if err.raw_os_error() == Some(libc::ENOMEM) {
                    continue;
                }
                return Err(err);
            }

            buffer.truncate(len);
            return Ok(buffer);
        }

        Err(std::io::Error::other(
            "the neighbour table kept growing while it was being read",
        ))
    }

    /// Walks the routing messages in `buffer`, yielding one neighbour per entry.
    ///
    /// Every length here comes from the kernel and is bounds-checked anyway. The
    /// buffer is trusted, but a message claiming to be longer than what remains
    /// would walk off the end, and a zero-length one would loop forever.
    fn parse(buffer: &[u8]) -> Vec<Neighbor> {
        let mut neighbors = Vec::new();
        let mut offset = 0usize;

        while offset + mem::size_of::<rt_msghdr>() <= buffer.len() {
            // SAFETY: the bounds check above guarantees a whole header is
            // present, and `rt_msghdr` is a plain repr(C) struct.
            let header: rt_msghdr =
                unsafe { std::ptr::read_unaligned(buffer[offset..].as_ptr() as *const rt_msghdr) };

            // A message has to be at least a header, and no longer than what
            // remains. The lower bound was `!= 0`, which is the same thing only
            // if a message can never be shorter than the struct being read out
            // of it — and `rtm_msglen` is the kernel's number while
            // `size_of::<rt_msghdr>()` is whatever `libc` was compiled to
            // believe. A routing socket carries several message types with
            // headers of different sizes, so the two can disagree, and the slice
            // below then ran from the header's end back to a smaller offset and
            // panicked. Bounding by the header size subsumes the zero case.
            let message_len = header.rtm_msglen as usize;
            if message_len < mem::size_of::<rt_msghdr>() || offset + message_len > buffer.len() {
                break;
            }

            if let Some(neighbor) = entry(
                &buffer[offset + mem::size_of::<rt_msghdr>()..offset + message_len],
                header.rtm_addrs,
                header.rtm_index as u32,
            ) {
                neighbors.push(neighbor);
            }

            offset += message_len;
        }

        neighbors
    }

    /// Reads one message's address block: a sequence of `sockaddr`s, present or
    /// absent according to the bits in `addrs`, in a fixed order.
    ///
    /// The destination is the neighbour's address and the gateway is its
    /// link-layer address. Anything else in the block is skipped by its own
    /// length, which is why the whole sequence has to be walked even to read
    /// only two of them.
    fn entry(mut block: &[u8], addrs: c_int, interface_index: u32) -> Option<Neighbor> {
        let mut ip: Option<IpAddr> = None;
        let mut mac: Option<MacAddr> = None;

        for bit in 0..8 {
            let flag = 1 << bit;
            if addrs & flag == 0 {
                continue;
            }
            if block.len() < mem::size_of::<sockaddr>() {
                break;
            }

            // SAFETY: a whole `sockaddr` is present per the check above; its
            // `sa_len` then says how much of the block this one occupies.
            let sa: sockaddr =
                unsafe { std::ptr::read_unaligned(block.as_ptr() as *const sockaddr) };
            let sa_len = roundup(sa.sa_len as usize);
            if sa_len == 0 || sa_len > block.len() {
                break;
            }

            match (flag, c_int::from(sa.sa_family)) {
                (RTA_DST, AF_INET6) => ip = read_ipv6(&block[..sa_len]),
                (RTA_GATEWAY, AF_LINK) => mac = read_mac(&block[..sa_len]),
                _ => {}
            }

            block = &block[sa_len..];
        }

        ip.map(|ip| Neighbor {
            ip,
            mac,
            interface_index,
        })
    }

    fn read_ipv6(bytes: &[u8]) -> Option<IpAddr> {
        if bytes.len() < mem::size_of::<sockaddr_in6>() {
            return None;
        }
        // SAFETY: the length check guarantees a whole `sockaddr_in6`.
        let sin6: sockaddr_in6 =
            unsafe { std::ptr::read_unaligned(bytes.as_ptr() as *const sockaddr_in6) };
        let mut octets = sin6.sin6_addr.s6_addr;

        // BSD stores a link-local address's scope in bytes 2 and 3 of the
        // address itself rather than in the `sin6_scope_id` field, which is a
        // representation no other part of the engine uses and which would
        // otherwise be reported as part of the address. The interface is carried
        // separately, so the embedded copy is cleared.
        if octets[0] == 0xfe && (octets[1] & 0xc0) == 0x80 {
            octets[2] = 0;
            octets[3] = 0;
        }

        Some(IpAddr::V6(Ipv6Addr::from(octets)))
    }

    fn read_mac(bytes: &[u8]) -> Option<MacAddr> {
        if bytes.len() < mem::size_of::<sockaddr_dl>() {
            return None;
        }
        // SAFETY: the length check guarantees a whole `sockaddr_dl`.
        let sdl: sockaddr_dl =
            unsafe { std::ptr::read_unaligned(bytes.as_ptr() as *const sockaddr_dl) };

        // The address lives inside a variable-length trailer after the interface
        // name, and is only a MAC when it is six bytes long.
        const ETHER_ADDR_LEN: usize = 6;
        if sdl.sdl_alen as usize != ETHER_ADDR_LEN {
            return None;
        }

        let start = sdl.sdl_nlen as usize;
        let data = &sdl.sdl_data;
        let end = start + ETHER_ADDR_LEN;
        if end > data.len() {
            return None;
        }

        let octets: Vec<u8> = data[start..end].iter().map(|b| *b as u8).collect();
        Some(MacAddr::new(
            octets[0], octets[1], octets[2], octets[3], octets[4], octets[5],
        ))
    }

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

        /// One routing message, with the fields the walk reads set and the rest
        /// zeroed, as the kernel would hand it over.
        fn message(msglen: u16, addrs: c_int, index: u16) -> Vec<u8> {
            // SAFETY: `rt_msghdr` is a plain `repr(C)` struct of integers, so a
            // zeroed one is a valid value, and the copy below reads exactly the
            // bytes it occupies.
            let mut header: rt_msghdr = unsafe { mem::zeroed() };
            header.rtm_msglen = msglen;
            header.rtm_addrs = addrs;
            header.rtm_index = index;

            let size = mem::size_of::<rt_msghdr>();
            let mut bytes = vec![0u8; size];
            unsafe {
                std::ptr::copy_nonoverlapping(
                    (&raw const header) as *const u8,
                    bytes.as_mut_ptr(),
                    size,
                );
            }
            bytes
        }

        /// **A message shorter than the header it is read through ends the
        /// walk.**
        ///
        /// A guard refusing only a length of zero and a length past the end of
        /// the buffer panics here: the slice handed to `entry` runs from
        /// `offset + size_of::<rt_msghdr>()` to `offset + message_len`, which is
        /// backwards for every length between the two. `rtm_msglen` is the
        /// kernel's and the struct size is the binding's, so they can disagree
        /// on a platform whose layout has moved or a dump carrying a message
        /// type this does not expect.
        #[test]
        fn a_message_shorter_than_its_header_ends_the_walk() {
            let header = mem::size_of::<rt_msghdr>();

            for msglen in [0usize, 1, 4, 64, header - 1] {
                let mut buffer = message(msglen as u16, RTA_DST | RTA_GATEWAY, 1);
                buffer.resize(header + 64, 0xAA);

                assert!(
                    parse(&buffer).is_empty(),
                    "a message declaring {msglen} bytes must yield nothing"
                );
            }

            // And the first length that is not short is read rather than
            // refused, so the bound is the header's size and not something
            // larger.
            let mut buffer = message(header as u16, RTA_DST | RTA_GATEWAY, 1);
            buffer.resize(header + 64, 0);
            let _ = parse(&buffer);
        }

        /// The walk terminates and reads nothing out of bounds whatever the
        /// buffer, which is the property the trust model leans on: the bytes
        /// come from the kernel, and are bounds-checked anyway.
        #[test]
        fn the_walk_survives_any_buffer() {
            let mut state = 0x2545_F491_4F6C_DD1Du64;
            let mut next = || {
                state ^= state << 13;
                state ^= state >> 7;
                state ^= state << 17;
                state
            };

            for _ in 0..20_000 {
                let len = (next() % 512) as usize;
                let buffer: Vec<u8> = (0..len).map(|_| (next() & 0xFF) as u8).collect();
                let _ = parse(&buffer);
            }

            // And the same over buffers shaped like real messages, where the
            // length field is plausible enough to be acted on.
            for _ in 0..20_000 {
                let mut buffer = message((next() % 70_000) as u16, (next() % 256) as c_int, 1);
                let extra = (next() % 128) as usize;
                buffer.extend((0..extra).map(|_| (next() & 0xFF) as u8));
                let _ = parse(&buffer);
            }
        }

        /// A sockaddr block that lies about its own length is stepped over or
        /// ends the block, and never reads a neighbour's bytes as an address.
        #[test]
        fn a_sockaddr_that_lies_about_its_length_yields_nothing() {
            let header = mem::size_of::<rt_msghdr>();

            for sa_len in [0u8, 1, 3, 255] {
                let total = header + 32;
                let mut buffer = message(total as u16, RTA_DST | RTA_GATEWAY, 1);
                buffer.resize(total, 0);
                buffer[header] = sa_len;
                buffer[header + 1] = AF_INET6 as u8;

                assert!(
                    parse(&buffer).is_empty(),
                    "sa_len {sa_len} named no address"
                );
            }
        }

        /// The interface-name length inside a link-layer sockaddr is where the
        /// MAC is read from, and it is a stranger's number in the same sense as
        /// the rest.
        #[test]
        fn a_link_address_naming_a_long_interface_yields_no_mac() {
            let header = mem::size_of::<rt_msghdr>();
            let total = header + mem::size_of::<sockaddr_dl>() + 8;

            let mut buffer = message(total as u16, RTA_GATEWAY, 1);
            buffer.resize(total, 0);
            buffer[header] = mem::size_of::<sockaddr_dl>() as u8;
            buffer[header + 1] = AF_LINK as u8;
            buffer[header + 5] = 255; // sdl_nlen, past the end of sdl_data
            buffer[header + 6] = 6; // sdl_alen, a plausible MAC length

            assert!(parse(&buffer).is_empty());
        }
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// Everywhere else
// ══════════════════════════════════════════════════════════════════════════════

/// Platforms whose neighbour table this does not read yet.
///
/// Reported once rather than silently returning nothing, because an empty table
/// and an unread one lead to the same host count and mean entirely different
/// things: the distinction this whole engine is built to preserve.
///
/// Linux keeps its table behind netlink (`RTM_GETNEIGH`) and Windows behind
/// `GetIpNetTable2`; both are a self-contained piece of work against an
/// interface neither shares with the other.
#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "freebsd")))]
mod platform {
    use super::Neighbor;
    use crate::warn;

    /// Nothing, on a platform whose neighbour table this engine cannot read.
    ///
    /// Empty rather than an error, for the reason the public function gives: a
    /// scan that cannot read the table is a scan with one fewer source of
    /// candidate addresses, not a scan that failed.
    pub(super) fn ipv6_neighbors() -> Vec<Neighbor> {
        warn!(
            verbosity = 1,
            "reading the IPv6 neighbour table is not implemented on this platform; \
             discovery will not use it as a source of candidate addresses"
        );
        Vec::new()
    }
}

// ╔════════════════════════════════════════════╗
// ║ ████████╗███████╗███████╗████████╗███████╗ ║
// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
// ║    ██║   ███████╗███████║   ██║   ███████║ ║
// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
// ╚════════════════════════════════════════════╝

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

    /// Reading the table must not panic, whatever the host looks like, and must
    /// answer with something usable rather than an error a caller has to handle.
    ///
    /// Deliberately not an assertion about *contents*: a machine with no IPv6
    /// neighbours is a perfectly ordinary machine, and a test demanding some
    /// would fail in CI for a reason having nothing to do with this code.
    #[test]
    fn reading_the_table_is_infallible() {
        let neighbors = ipv6_neighbors();

        for neighbor in &neighbors {
            assert!(
                neighbor.ip.is_ipv6(),
                "the IPv6 table yielded {}",
                neighbor.ip
            );
        }
    }

    /// Every entry the table yields has to be something a probe can be aimed at.
    ///
    /// A link-local address without its interface is the one shape this must
    /// never produce, since it is exactly what the rest of the engine refuses to
    /// act on.
    #[test]
    fn every_link_local_entry_names_its_interface() {
        for neighbor in ipv6_neighbors() {
            let IpAddr::V6(v6) = neighbor.ip else {
                continue;
            };
            if v6.is_unicast_link_local() {
                assert_ne!(
                    neighbor.interface_index, 0,
                    "{v6} came back with no interface, so nothing could probe it"
                );
            }
        }
    }
}