zond-engine 0.14.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
// 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

//! # Raw Transport-Layer Sockets (Send Path)
//!
//! Wraps `pnet`'s raw transport-layer (Layer 4) sockets for *sending* probes,
//! so async scanning code never touches the blocking socket API directly.
//!
//! This module deliberately opens no receiver. Receiving TCP/UDP over a raw
//! socket works on Linux but is silently dead on macOS/BSD, whose kernels
//! never deliver those protocols to raw sockets - so replies are captured at
//! the link layer via [`crate::transport::capture`] instead, and every scanner
//! pairs this send-only handle with that capture through
//! [`crate::transport::probe::ProbeTransport`].
//!
//! A raw socket is bound to one address family: an IPv4 socket can neither
//! send to nor receive from an IPv6 destination, and vice versa. TCP scanning
//! needs both, since targets can be either, so [`open_sender`] opens one
//! socket per address family for [`TransportType::TcpLayer4`].
//! [`TransportType::UdpLayer4`], [`TransportType::SctpLayer4`] and
//! [`TransportType::IcmpLayer4`] open both, and the ICMP one is
//! is the only way this crate can put an ICMP message on the wire for a host it
//! cannot reach at the link layer: the echo builders in
//! [`crate::protocols::icmp`] emit whole Ethernet frames and so need a
//! neighbour.

use std::net::{IpAddr, Ipv6Addr, SocketAddrV6};
use std::sync::{Arc, Mutex};

use pnet_packet::{
    Packet,
    ip::{IpNextHeaderProtocol, IpNextHeaderProtocols},
};
use pnet_transport::{
    self as transport, TransportChannelType, TransportProtocol, TransportReceiver, TransportSender,
};

const TRANSPORT_BUFFER_SIZE: usize = 4096;
const CHANNEL_TYPE_UDP_V4: TransportChannelType =
    TransportChannelType::Layer4(TransportProtocol::Ipv4(IpNextHeaderProtocols::Udp));
const CHANNEL_TYPE_UDP_V6: TransportChannelType =
    TransportChannelType::Layer4(TransportProtocol::Ipv6(IpNextHeaderProtocols::Udp));
const CHANNEL_TYPE_TCP_V4: TransportChannelType =
    TransportChannelType::Layer4(TransportProtocol::Ipv4(IpNextHeaderProtocols::Tcp));
const CHANNEL_TYPE_TCP_V6: TransportChannelType =
    TransportChannelType::Layer4(TransportProtocol::Ipv6(IpNextHeaderProtocols::Tcp));
const CHANNEL_TYPE_ICMP_V4: TransportChannelType =
    TransportChannelType::Layer4(TransportProtocol::Ipv4(IpNextHeaderProtocols::Icmp));
const CHANNEL_TYPE_ICMP_V6: TransportChannelType =
    TransportChannelType::Layer4(TransportProtocol::Ipv6(IpNextHeaderProtocols::Icmpv6));
const CHANNEL_TYPE_SCTP_V4: TransportChannelType =
    TransportChannelType::Layer4(TransportProtocol::Ipv4(IpNextHeaderProtocols::Sctp));
const CHANNEL_TYPE_SCTP_V6: TransportChannelType =
    TransportChannelType::Layer4(TransportProtocol::Ipv6(IpNextHeaderProtocols::Sctp));

/// Which transport-layer protocol, and address family coverage, to open a capture for.
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub enum TransportType {
    /// Raw TCP segments, over both IPv4 and IPv6 where available.
    TcpLayer4,
    /// Raw UDP datagrams, over IPv4 only.
    UdpLayer4,
    /// Raw ICMP messages, over both IPv4 and IPv6 where available.
    ///
    /// The two families are different protocols rather than one protocol over two
    /// address sizes: ICMP is next-header 1 and ICMPv6 is 58, they number their
    /// message types differently, and ICMPv6 checksums cover a pseudo-header
    /// while ICMPv4 checksums cover the message alone. A caller therefore builds
    /// a different message per family, and this opens a socket for each.
    ///
    /// This is the only path by which this crate can send an ICMP message to a
    /// host that is not on the local segment. The echo builders in
    /// [`protocols::icmp`] produce whole Ethernet frames, which need a
    /// destination hardware address and so only reach an on-link neighbour.
    ///
    /// [`protocols::icmp`]: crate::protocols::icmp
    IcmpLayer4,
    /// Raw SCTP packets, over both IPv4 and IPv6 where available.
    ///
    /// The socket carries the packet and nothing more: an SCTP checksum is a
    /// CRC32c over the packet alone, so unlike TCP and UDP there is no
    /// pseudo-header for the kernel or the builder to agree about, and the same
    /// bytes go out over either family.
    ///
    /// Opening it needs no SCTP stack in the kernel, only the privilege every
    /// raw socket needs. A host that cannot itself hold an association can still
    /// send an INIT and read what comes back, which is the whole of what a scan
    /// does with one.
    SctpLayer4,
    /// Datagrams of one arbitrary IP protocol, over both families where
    /// available.
    ///
    /// The four above name a protocol this crate speaks; this one carries a
    /// number and speaks nothing. It is what an
    /// [IP protocol scan](crate::scanner::strategy::protocols) sends: a header
    /// under a chosen next-header value, to find out whether the host's stack
    /// takes delivery of it at all.
    ///
    /// One socket per number, because the kernel derives a Layer-4 socket's
    /// next-header value from the socket rather than from the packet. A pass
    /// asking about a dozen protocols opens a dozen, which is the price of not
    /// writing the IP header by hand; a header this crate wrote would have to be
    /// routed by this crate as well, and the reason the raw path exists is that
    /// the kernel does that better.
    IpProtocol(u8),
}

/// Routes an outgoing packet to whichever underlying raw socket matches its
/// destination's address family.
///
/// A [`TransportType::UdpLayer4`] handle only ever has an IPv4 sender, so
/// sending to an IPv6 destination through it fails with a clear error rather
/// than silently doing nothing.
pub struct TransportSenderHandle {
    v4: Option<Arc<Mutex<Socket>>>,
    v6: Option<Arc<Mutex<Socket>>>,
}

/// One raw socket, and the hop limit currently set on it.
///
/// The two travel under one lock because they have to be changed together: a
/// hop limit is socket state, not packet state, so setting it and sending are
/// one operation and a second thread must not send in between.
struct Socket {
    sender: TransportSender,
    /// What `IP_TTL` (or `IPV6_UNICAST_HOPS`) was last set to on this socket,
    /// or `None` before anything set it.
    ///
    /// Tracked so that a scan sending millions of probes at one hop limit pays
    /// for one `setsockopt` rather than one per probe. It starts as `None`
    /// rather than as this engine's default, so the first send states the value
    /// explicitly instead of trusting a kernel default that is only usually 64. A
    /// host tuned otherwise would send probes that expire early, and an expired
    /// probe is indistinguishable from a host that did not answer.
    hop_limit: Option<u8>,
}

impl Socket {
    fn new(sender: TransportSender) -> Arc<Mutex<Self>> {
        Arc::new(Mutex::new(Self {
            sender,
            hop_limit: None,
        }))
    }
}

/// Why a raw socket could not be opened, or a write through one failed.
///
/// Every variant here is an answer from the operating system rather than a
/// mistake in what was asked, [`NoSocket`](Self::NoSocket) aside. That matters
/// for what a caller does next: a scan meeting [`Open`](Self::Open) has no raw
/// path at all and falls back, and one meeting [`Send`](Self::Send) has a
/// transport that works and a destination that did not.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum RawSocketError {
    /// A raw socket could not be opened.
    ///
    /// Almost always a privilege refusal. `CAP_NET_RAW` on Linux, root
    /// elsewhere; see [`can_send_raw`](crate::system::privilege::can_send_raw),
    /// which asks this question by asking for the socket.
    #[error("a raw socket could not be opened: {source}")]
    Open {
        /// What the operating system said.
        #[source]
        source: std::io::Error,
    },

    /// No socket is open for the address family a destination named.
    ///
    /// A handle opens what it can, and a host with IPv6 raw sockets disabled
    /// gets an IPv4-only one rather than nothing. This is what a v6 destination
    /// then meets, and it is a narrower transport rather than a broken one.
    #[error(
        "no open raw socket for {destination}, whose address family this handle does not carry"
    )]
    NoSocket {
        /// The destination that had nowhere to go.
        destination: IpAddr,
    },

    /// The hop limit could not be set on the socket.
    #[error("a hop limit of {hop_limit} could not be set: {source}")]
    HopLimit {
        /// The hop limit that was asked for.
        hop_limit: u8,
        /// What the operating system said.
        #[source]
        source: std::io::Error,
    },

    /// The packet could not be written.
    #[error("sending to {destination} failed: {source}")]
    Send {
        /// Where it was going.
        destination: IpAddr,
        /// What the operating system said.
        #[source]
        source: std::io::Error,
    },

    /// The socket's lock was poisoned by another thread's panic.
    ///
    /// One socket is shared across a scan's senders, so a panic while it was
    /// held leaves it unusable rather than merely unlocked. Named rather than
    /// unwrapped, because this happened in the caller's process and taking it
    /// down twice helps nobody.
    #[error("the raw socket lock was poisoned by another thread's panic")]
    Poisoned,
}

impl TransportSenderHandle {
    /// Sends `packet` to `destination`, expiring after `hop_limit` routers.
    ///
    /// The hop limit is applied to the socket rather than written into the
    /// packet, because a Layer-4 socket has the kernel build the IP header and
    /// there is no header here to write it into. That makes it *sticky*, which
    /// is why the value in force is tracked alongside the socket: what a caller
    /// asks for is what goes out, whatever the previous send asked for.
    /// `zone` is the interface a link-local destination is valid on. A
    /// `SocketAddrV6` carrying a zero scope id is not deliverable to `fe80::1`
    /// however close the neighbour is, and `pnet`'s own send builds one, so a
    /// scoped destination takes a `sendto` of its own instead.
    pub fn send_to<T: Packet>(
        &self,
        packet: T,
        destination: IpAddr,
        zone: Option<u32>,
        hop_limit: u8,
    ) -> Result<usize, RawSocketError> {
        let socket = match destination {
            IpAddr::V4(_) => self.v4.as_ref(),
            IpAddr::V6(_) => self.v6.as_ref(),
        }
        .ok_or(RawSocketError::NoSocket { destination })?;

        let mut socket = socket.lock().map_err(|_| RawSocketError::Poisoned)?;

        if socket.hop_limit != Some(hop_limit) {
            socket
                .sender
                .set_ttl(hop_limit)
                .map_err(|source| RawSocketError::HopLimit { hop_limit, source })?;
            socket.hop_limit = Some(hop_limit);
        }

        match (destination, zone) {
            (IpAddr::V6(v6), Some(zone)) => {
                send_scoped(socket.sender.socket.fd, packet.packet(), v6, 0, zone)
            }
            _ => socket.sender.send_to(packet, destination),
        }
        .map_err(|source| RawSocketError::Send {
            destination,
            source,
        })
    }
}

/// Writes `bytes` to a destination that names the interface it is valid on.
///
/// The one thing `pnet`'s send cannot express. It builds its destination from an
/// `IpAddr` alone, which leaves `sin6_scope_id` zero, and a link-local address
/// with no scope id names no segment: the kernel refuses it rather than guessing
/// which of the host's `fe80::/64`s was meant.
///
/// `port` is zero for a raw socket, which reads the port from the segment it is
/// handed and none from the address it is sent to. It is a parameter because a
/// datagram socket does read one, and refuses a zero, which is how this is
/// exercised without the privilege a raw socket needs.
#[cfg(unix)]
fn send_scoped(
    fd: std::os::fd::RawFd,
    bytes: &[u8],
    destination: Ipv6Addr,
    port: u16,
    zone: u32,
) -> std::io::Result<usize> {
    let address = socket2::SockAddr::from(SocketAddrV6::new(destination, port, 0, zone));

    // SAFETY: the socket outlives the call, `bytes` is a live slice for its
    // length, and the address and its length come from the same `SockAddr`.
    let written = unsafe {
        libc::sendto(
            fd,
            bytes.as_ptr().cast(),
            bytes.len(),
            0,
            address.as_ptr().cast(),
            address.len(),
        )
    };

    match written {
        -1 => Err(std::io::Error::last_os_error()),
        written => Ok(written as usize),
    }
}

/// Refuses a scoped send on a platform with no `sendto` to reach for.
///
/// Windows blocks raw TCP sends outright, so the scan that would arrive here
/// has already fallen back to a connected socket, which carries its own scope
/// id.
#[cfg(not(unix))]
fn send_scoped(
    _fd: std::os::windows::io::RawSocket,
    _bytes: &[u8],
    _destination: Ipv6Addr,
    _port: u16,
    _zone: u32,
) -> std::io::Result<usize> {
    Err(std::io::Error::new(
        std::io::ErrorKind::Unsupported,
        "a scoped raw send is not built on this platform",
    ))
}

/// Opens only the outgoing half of a raw transport capture: the raw
/// socket(s) needed to *send* segments, with no receiver threads.
///
/// Sending over a raw Layer-4 socket works on every supported OS - it's only
/// *receiving* TCP/UDP this way that BSD-derived kernels refuse - so the
/// [`RawIpSender`](crate::transport::probe::RawIpSender) pairs this send-only
/// handle with a `libpcap` capture for replies instead of the (silently dead
/// on macOS) raw-socket receiver.
pub fn open_sender(transport_type: TransportType) -> Result<TransportSenderHandle, RawSocketError> {
    match transport_type {
        TransportType::TcpLayer4 => {
            let (v4_tx, _v4_rx) = open_channel(CHANNEL_TYPE_TCP_V4)?;
            // IPv6 raw sockets aren't available on every host; TCP scanning
            // still works over IPv4 alone, so a failure here isn't fatal.
            let v6 = open_channel(CHANNEL_TYPE_TCP_V6)
                .ok()
                .map(|(v6_tx, _v6_rx)| Socket::new(v6_tx));
            Ok(TransportSenderHandle {
                v4: Some(Socket::new(v4_tx)),
                v6,
            })
        }
        TransportType::UdpLayer4 => {
            let (v4_tx, _v4_rx) = open_channel(CHANNEL_TYPE_UDP_V4)?;
            // As for TCP: a host without IPv6 raw sockets still scans UDP over
            // IPv4, so a failure here narrows the transport rather than ending
            // it.
            let v6 = open_channel(CHANNEL_TYPE_UDP_V6)
                .ok()
                .map(|(v6_tx, _v6_rx)| Socket::new(v6_tx));
            Ok(TransportSenderHandle {
                v4: Some(Socket::new(v4_tx)),
                v6,
            })
        }
        TransportType::SctpLayer4 => {
            let (v4_tx, _v4_rx) = open_channel(CHANNEL_TYPE_SCTP_V4)?;
            // As for TCP: a host without IPv6 raw sockets still scans SCTP over
            // IPv4, so a failure here narrows the transport rather than ending
            // it.
            let v6 = open_channel(CHANNEL_TYPE_SCTP_V6)
                .ok()
                .map(|(v6_tx, _v6_rx)| Socket::new(v6_tx));
            Ok(TransportSenderHandle {
                v4: Some(Socket::new(v4_tx)),
                v6,
            })
        }
        TransportType::IpProtocol(number) => {
            let protocol = IpNextHeaderProtocol(number);
            let (v4_tx, _v4_rx) = open_channel(TransportChannelType::Layer4(
                TransportProtocol::Ipv4(protocol),
            ))?;
            // As for TCP: a host without IPv6 raw sockets still probes over
            // IPv4, and a kernel that refuses one protocol's socket outright
            // narrows the pass rather than ending it.
            let v6 = open_channel(TransportChannelType::Layer4(TransportProtocol::Ipv6(
                protocol,
            )))
            .ok()
            .map(|(v6_tx, _v6_rx)| Socket::new(v6_tx));
            Ok(TransportSenderHandle {
                v4: Some(Socket::new(v4_tx)),
                v6,
            })
        }
        TransportType::IcmpLayer4 => {
            let (v4_tx, _v4_rx) = open_channel(CHANNEL_TYPE_ICMP_V4)?;
            // Same reasoning as TCP: a host without IPv6 raw sockets can still
            // be probed over IPv4, so a failure here is a narrower transport
            // rather than no transport.
            let v6 = open_channel(CHANNEL_TYPE_ICMP_V6)
                .ok()
                .map(|(v6_tx, _v6_rx)| Socket::new(v6_tx));
            Ok(TransportSenderHandle {
                v4: Some(Socket::new(v4_tx)),
                v6,
            })
        }
    }
}

/// Opens one raw transport channel, naming this crate's error rather than
/// letting `pnet`'s reach a caller.
fn open_channel(
    channel_type: TransportChannelType,
) -> Result<(TransportSender, TransportReceiver), RawSocketError> {
    transport::transport_channel(TRANSPORT_BUFFER_SIZE, channel_type)
        .map_err(|source| RawSocketError::Open { source })
}

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

#[cfg(all(test, unix))]
mod tests {
    use super::*;
    use std::net::UdpSocket;
    use std::os::fd::AsRawFd;

    /// A datagram addressed to a link-local neighbour, sent through the scoped
    /// path on an ordinary UDP socket.
    ///
    /// The raw socket this exists for needs privilege to open, and the syscall
    /// underneath is the same one either way: what is being checked is that the
    /// destination reaches the kernel with its scope id on it. Sent to this
    /// host's own link-local address, so nothing leaves the machine.
    ///
    /// Skipped on a host holding no link-local address, which is a host that
    /// could not answer the question.
    /// Nothing listens here, and a discard port keeps the datagram from
    /// reaching anything that does.
    const DISCARD: u16 = 9;

    #[test]
    fn a_scoped_send_reaches_the_kernel_with_its_interface_on_it() {
        // A real broadcast interface, lowest index first, so the pick is stable.
        let mut links: Vec<_> = crate::system::interface::interfaces()
            .into_iter()
            .filter(|link| link.is_up() && !link.is_loopback() && !link.is_point_to_point())
            .collect();
        links.sort_by_key(crate::system::interface::Link::index);
        let Some((address, zone)) = links.iter().find_map(|link| {
            link.addresses()
                .iter()
                .map(|held| held.address())
                .find_map(|address| match address {
                    IpAddr::V6(v6) if v6.is_unicast_link_local() => Some((v6, link.index())),
                    _ => None,
                })
        }) else {
            return;
        };

        // Only the positive is asserted. Whether the kernel *rejects* a
        // zero-scope send to a link-local is its own call and is not portable:
        // a host with one such interface infers the scope and accepts it, as the
        // GitHub Linux runners do.
        let socket = UdpSocket::bind("[::]:0").expect("an unprivileged socket");
        let sent = send_scoped(socket.as_raw_fd(), b"zond", address, DISCARD, zone);
        assert!(
            sent.is_ok(),
            "a scoped destination is deliverable: {}",
            sent.unwrap_err()
        );
    }
}