zond-engine 0.6.0

A lightweight, fast, and highly concurrent networking backend for packet crafting, protocol fingerprinting, and host discovery.
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
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
// If a copy of the MPL was not distributed with this file, You can obtain one at
// https://mozilla.org/MPL/2.0/.

//! # Host Model
//!
//! This module defines the [`Host`] entity, which represents a single network
//! equipment or device.
//!
//! The `Host` model is architected as an **aggregate of findings**. It is
//! specifically designed to be enriched over multiple asynchronous scanning
//! stages, leveraging high-performance merging logic to collate reachability,
//! hardware, OS, and service discovery data into a single forensic record.

use crate::core::models::port::Port;
use std::{
    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
    net::IpAddr,
    time::SystemTime,
};

pub mod hardware;
pub mod os;
pub mod status;
pub mod telemetry;

pub use hardware::HardwareInfo;
pub use os::OsFingerprint;
pub use status::{HostStatus, StatusProtocol, StatusReason};
pub use telemetry::HostTelemetry;

/// The absolute maximum number of open ports to record per host.
///
/// This serves as a security boundary against network "tarpits" (devices that
/// report every possible port as open), which could otherwise trigger an
/// Out-Of-Memory (OOM) crash in the scanner.
pub const MAX_PORTS_PER_HOST: usize = 1000;

/// Specialized network roles identified during host discovery.
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub enum NetworkRole {
    /// Identifies the default gateway for a local subnet.
    Gateway,
    /// Identifies a host providing DHCP services.
    DHCP,
    /// Identifies a host providing DNS services.
    DNS,
    /// Identifies a host that has triggered defensive limits (e.g., reporting
    /// an impossible number of open ports).
    Tarpit,
}

/// A comprehensive identity and state record for a network-reachable host.
///
/// A `Host` is the primary unit of work for the Zond scanner. It holds
/// multi-homed IP data, forensic hardware IDs, and a history of network
/// performance metrics.
///
/// Large metadata blocks (like [`OsFingerprint`]) are stored in Boxes to
/// minimize the overall stack size of the `Host` struct.
#[derive(Debug, Clone)]
pub struct Host {
    /// The primary IP address used to target or identify this host.
    primary_ip: IpAddr,

    /// All known IP addresses for this host (multi-homed support).
    ips: BTreeSet<IpAddr>,

    /// The resolved hostname (FQDN or local network name).
    hostname: Option<String>,

    /// The current reachability status.
    status: HostStatus,

    /// Aggregated evidence explaining the current reachability status.
    reasons: HashSet<StatusReason>,

    /// Identified operating system metadata.
    os: Option<Box<OsFingerprint>>,

    /// physical hardware (MAC) and vendor information.
    hardware: Option<HardwareInfo>,

    /// Network performance and path telemetry.
    telemetry: HostTelemetry,

    /// Inferred roles based on network location or discovered services.
    network_roles: HashSet<NetworkRole>,

    /// Extensible map for scan script results (e.g., Nmap NSE output).
    scripts: Option<HashMap<String, String>>,

    /// The timestamp of the first discovery event for this host.
    first_seen: SystemTime,

    /// The timestamp of the most recent discovery or update event.
    last_seen: SystemTime,

    /// Internal map for sorted port discovery. Limited by [`MAX_PORTS_PER_HOST`].
    ports: BTreeMap<u16, Port>,
}

impl Host {
    /// Creates a new `Host` centered around a primary IP address.
    ///
    /// The initial status is always [`HostStatus::Unknown`].
    pub fn new(primary_ip: IpAddr) -> Self {
        let mut ips = BTreeSet::new();
        ips.insert(primary_ip);
        let now = SystemTime::now();

        Self {
            primary_ip,
            ips,
            hostname: None,
            status: HostStatus::Unknown,
            reasons: HashSet::new(),
            os: None,
            hardware: None,
            telemetry: HostTelemetry::default(),
            network_roles: HashSet::new(),
            scripts: None,
            first_seen: now,
            last_seen: now,
            ports: BTreeMap::new(),
        }
    }

    /// Returns the primary IP address for this host.
    pub fn primary_ip(&self) -> IpAddr {
        self.primary_ip
    }

    /// Returns all known IP addresses for this host.
    pub fn ips(&self) -> &BTreeSet<IpAddr> {
        &self.ips
    }

    /// Returns the resolved hostname, if any.
    pub fn hostname(&self) -> Option<&str> {
        self.hostname.as_deref()
    }

    /// Returns the current reachability status.
    pub fn status(&self) -> HostStatus {
        self.status
    }

    /// Returns all aggregated evidence for the current status.
    pub fn reasons(&self) -> &HashSet<StatusReason> {
        &self.reasons
    }

    /// Returns the identified operating system, if any.
    pub fn os(&self) -> Option<&OsFingerprint> {
        self.os.as_deref()
    }

    /// Returns physical hardware information, if any.
    pub fn hardware(&self) -> Option<&HardwareInfo> {
        self.hardware.as_ref()
    }

    /// Returns network performance and path telemetry.
    pub fn telemetry(&self) -> &HostTelemetry {
        &self.telemetry
    }

    /// Returns inferred roles based on network location or discovered services.
    pub fn network_roles(&self) -> &HashSet<NetworkRole> {
        &self.network_roles
    }

    /// Returns the map of scan script results.
    pub fn scripts(&self) -> Option<&HashMap<String, String>> {
        self.scripts.as_ref()
    }

    /// Returns the timestamp of the first discovery event.
    pub fn first_seen(&self) -> SystemTime {
        self.first_seen
    }

    /// Returns the timestamp of the most recent discovery or update event.
    pub fn last_seen(&self) -> SystemTime {
        self.last_seen
    }

    /// Updates the primary IP, ensures it exists in the `ips` set,
    /// and bumps the `last_seen` timestamp.
    pub fn set_primary_ip(&mut self, ip: IpAddr) {
        self.primary_ip = ip;
        self.ips.insert(ip);
        self.last_seen = SystemTime::now();
    }

    /// Adds a new IP address to the host's record and bumps `last_seen`.
    /// Returns `true` if the IP was newly added.
    pub fn add_ip(&mut self, ip: IpAddr) -> bool {
        let is_new = self.ips.insert(ip);
        self.last_seen = SystemTime::now();
        is_new
    }

    /// Adds multiple IP addresses to the host's record and bumps `last_seen`.
    pub fn extend_ips(&mut self, ips: impl IntoIterator<Item = IpAddr>) {
        self.ips.extend(ips);
        self.last_seen = SystemTime::now();
    }

    /// Sets the host's hostname and bumps `last_seen`.
    pub fn set_hostname(&mut self, hostname: Option<String>) {
        self.hostname = hostname;
        self.last_seen = SystemTime::now();
    }

    /// Updates the reachability status and bumps `last_seen`.
    pub fn set_status(&mut self, status: HostStatus) {
        self.status = status;
        self.last_seen = SystemTime::now();
    }

    /// Adds a status reason and bumps `last_seen`.
    pub fn add_reason(&mut self, reason: StatusReason) {
        self.reasons.insert(reason);
        self.last_seen = SystemTime::now();
    }

    /// Sets the OS fingerprint and bumps `last_seen`.
    pub fn set_os(&mut self, os: OsFingerprint) {
        self.os = Some(Box::new(os));
        self.last_seen = SystemTime::now();
    }

    /// Sets the hardware info and bumps `last_seen`.
    pub fn set_hardware(&mut self, hardware: HardwareInfo) {
        self.hardware = Some(hardware);
        self.last_seen = SystemTime::now();
    }

    /// Builder method to set the hardware MAC and return Self.
    pub fn with_mac(mut self, mac: crate::core::models::mac::MacAddr) -> Self {
        self.set_hardware(HardwareInfo::new(mac));
        self
    }

    /// Adds a single RTT measurement and bumps `last_seen`.
    pub fn add_rtt(&mut self, rtt: std::time::Duration) {
        self.telemetry.add_rtt(rtt);
        self.last_seen = SystemTime::now();
    }

    /// Builder method to add a single RTT measurement and return Self.
    pub fn with_rtt(mut self, rtt: std::time::Duration) -> Self {
        self.add_rtt(rtt);
        self
    }

    /// Adds multiple RTT measurements and bumps `last_seen`.
    pub fn set_rtts(&mut self, rtts: impl IntoIterator<Item = std::time::Duration>) {
        for rtt in rtts {
            self.telemetry.add_rtt(rtt);
        }
        self.last_seen = SystemTime::now();
    }

    /// Adds a network role and bumps `last_seen`.
    pub fn add_network_role(&mut self, role: NetworkRole) {
        self.network_roles.insert(role);
        self.last_seen = SystemTime::now();
    }

    /// Adds or updates a script result and bumps `last_seen`.
    pub fn add_script_result(&mut self, key: String, value: String) {
        self.scripts
            .get_or_insert_with(HashMap::new)
            .insert(key, value);
        self.last_seen = SystemTime::now();
    }

    /// Returns the minimum recorded RTT.
    pub fn min_rtt(&self) -> Option<std::time::Duration> {
        self.telemetry.min_rtt()
    }

    /// Returns the maximum recorded RTT.
    pub fn max_rtt(&self) -> Option<std::time::Duration> {
        self.telemetry.max_rtt()
    }

    /// Returns the average recorded RTT.
    pub fn average_rtt(&self) -> Option<std::time::Duration> {
        self.telemetry.average_rtt()
    }

    /// Returns the most recent MAC address, if hardware info is available.
    pub fn mac(&self) -> Option<crate::core::models::mac::MacAddr> {
        self.hardware.as_ref().and_then(|h| h.most_recent_mac())
    }

    /// Returns the hardware vendor, if hardware info is available.
    pub fn vendor(&self) -> Option<&str> {
        self.hardware
            .as_ref()
            .and_then(|h| h.vendor.as_ref())
            .map(|v| &**v)
    }

    /// Returns `true` if this host is confirmed to be on the network
    /// (either fully responding or filtered).
    pub fn is_alive(&self) -> bool {
        self.status.is_alive()
    }

    /// Returns an iterator over all discovered ports in sorted order.
    pub fn ports(&self) -> impl Iterator<Item = &Port> {
        self.ports.values()
    }

    /// Returns the total number of recorded ports for this host.
    pub fn port_count(&self) -> usize {
        self.ports.len()
    }

    /// Ingests a new port finding.
    ///
    /// If the port is already known, it is merged with the existing record.
    /// If the total port count exceeds [`MAX_PORTS_PER_HOST`], the port is ignored
    /// and the host is assigned the [`NetworkRole::Tarpit`] role.
    pub fn add_port(&mut self, new_port: Port) {
        if self.ports.len() >= MAX_PORTS_PER_HOST && !self.ports.contains_key(&new_port.number()) {
            self.network_roles.insert(NetworkRole::Tarpit);
            return;
        }

        self.ports
            .entry(new_port.number())
            .and_modify(|p| p.merge(new_port.clone()))
            .or_insert(new_port);

        self.last_seen = SystemTime::now();
    }

    /// Merges architectural findings from another `Host` record.
    ///
    /// This is the core aggregation method of the library, used to combine
    /// results from multiple asynchronous scan stages into a single truth.
    ///
    /// - Status is promoted based on semantic ordering.
    /// - Telemetry and OS data are merged using their respective logic.
    /// - Port caps are enforced during aggregation.
    pub fn merge(&mut self, other: Host) {
        self.ips.extend(other.ips);
        if self.hostname.is_none() {
            self.hostname = other.hostname;
        }

        if other.status > self.status {
            self.status = other.status;
        }
        self.reasons.extend(other.reasons);

        if let Some(other_os) = other.os {
            if let Some(ref mut self_os) = self.os {
                self_os.merge(*other_os);
            } else {
                self.os = Some(other_os);
            }
        }

        if let Some(other_hw) = other.hardware {
            if let Some(ref mut self_hw) = self.hardware {
                self_hw.merge(other_hw);
            } else {
                self.hardware = Some(other_hw);
            }
        }

        self.telemetry.merge(other.telemetry);
        self.network_roles.extend(other.network_roles);

        if let Some(other_scripts) = other.scripts {
            let self_scripts = self.scripts.get_or_insert_with(HashMap::new);
            self_scripts.extend(other_scripts);
        }

        for (_, port) in other.ports {
            self.add_port(port);
        }

        if other.first_seen < self.first_seen {
            self.first_seen = other.first_seen;
        }
        if other.last_seen > self.last_seen {
            self.last_seen = other.last_seen;
        }
    }
}

impl std::fmt::Display for Host {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} ({})", self.primary_ip, self.status)?;
        if let Some(ref os) = self.os {
            write!(f, " - {}", os)?;
        }
        if self.network_roles.contains(&NetworkRole::Tarpit) {
            write!(f, " [TARPIT]")?;
        } else {
            write!(f, " [{}]", self.telemetry)?;
        }
        Ok(())
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::models::port::{Port, PortState, Protocol};
    use std::net::Ipv4Addr;

    static IP_ADDR: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 168, 0, 100));

    #[test]
    fn host_primary_ip_invariant() {
        let mut host = Host::new(IP_ADDR);
        let fresh_ip = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 5));
        host.set_primary_ip(fresh_ip);

        assert_eq!(host.primary_ip(), fresh_ip);
        assert!(host.ips().contains(&fresh_ip));
    }

    #[test]
    fn tarpit_boundary_test() {
        let mut host = Host::new(IP_ADDR);
        for i in 0..MAX_PORTS_PER_HOST {
            host.add_port(Port::new(i as u16, Protocol::Tcp, PortState::Open));
        }
        assert!(!host.network_roles.contains(&NetworkRole::Tarpit));

        host.add_port(Port::new(9999, Protocol::Tcp, PortState::Open));
        assert!(host.network_roles.contains(&NetworkRole::Tarpit));
        assert_eq!(host.port_count(), MAX_PORTS_PER_HOST);
    }

    #[test]
    fn host_merge_promotes_status() {
        let mut h1 = Host::new(IP_ADDR);
        h1.set_status(HostStatus::Down);

        let mut h2 = Host::new(IP_ADDR);
        h2.set_status(HostStatus::Filtered);

        h1.merge(h2);
        assert_eq!(h1.status(), HostStatus::Filtered);
    }

    #[test]
    fn merge_tarpit_collision_test() {
        let mut h1 = Host::new(IP_ADDR);
        for i in 0..600 {
            h1.add_port(Port::new(i, Protocol::Tcp, PortState::Open));
        }

        let mut h2 = Host::new(IP_ADDR);
        // Ports 500-1100. 100 overlap (0-indexed 500-599), 500 new ones.
        // Total should hit cap at 1000.
        for i in 500..1100 {
            h2.add_port(Port::new(i, Protocol::Tcp, PortState::Open));
        }

        h1.merge(h2);
        assert_eq!(h1.port_count(), MAX_PORTS_PER_HOST);
        assert!(h1.network_roles.contains(&NetworkRole::Tarpit));
    }
}