zond-engine 0.12.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
488
489
490
491
492
493
494
495
// 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

//! # Fingerprinting Domain Model
//!
//! The vocabulary every detector in the fingerprinting subsystem speaks.
//!
//! A detector's job is to turn raw response data into [`Evidence`]: an
//! independent, provenance-tagged observation about what a port is running. A
//! regex banner match, a parsed TLS certificate, and an HTTP header scrape all
//! produce the same `Evidence`, so they compose without knowing about one
//! another. [`ServiceVerdict`] is how a set of evidence is reconciled into a
//! single answer, retaining the evidence it was drawn from for explainability.
//!
//! These types are deliberately independent of *how* evidence is produced, so
//! adding a new kind of detector never changes them.

use crate::model::port::Service;

/// How much trust to place in a single piece of [`Evidence`].
///
/// Ordered weakest-to-strongest, so evidence can be compared and ranked
/// directly.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
pub enum Confidence {
    /// A guess from context alone, e.g. the registered name for a port number
    /// with no probing performed.
    #[default]
    Heuristic,
    /// A plausible but non-authoritative signal.
    Weak,
    /// A signature matched, but the match is generic (no product/version).
    Probable,
    /// A specific signature matched, yielding product and/or version detail.
    Strong,
    /// Effectively certain: the service self-identified unambiguously.
    Certain,
}

impl Confidence {
    /// Projects onto the `0..=100` confidence scale used by [`Service`].
    pub fn as_score(self) -> u8 {
        match self {
            Confidence::Heuristic => 0,
            Confidence::Weak => 40,
            Confidence::Probable => 70,
            Confidence::Strong => 90,
            Confidence::Certain => 100,
        }
    }
}

/// Which detector produced a piece of [`Evidence`].
///
/// Retained on every observation for provenance, resolver tie-breaking, and
/// per-analyzer metrics. New analyzers add a variant here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SourceId {
    /// The registered name for the port number, with no probing.
    PortHeuristic,
    /// A regex signature matched a banner or active-probe response.
    BannerRegex,
    /// A TLS certificate was captured and parsed from the port.
    TlsCert,
    /// A structured parse of an HTTP response's headers.
    HttpHeaders,
    /// An SSH protocol exchange (version banner + `KEXINIT` algorithm lists).
    Ssh,
    // Future analyzers: Jarm, Snmp, Favicon, ...
}

/// A transport the observed traffic was carried *inside*.
///
/// When an analyzer identifies a protocol from data read through a tunnel, the
/// verdict records it here so the label can reflect both facts (e.g. `ssl/http`)
/// while `Evidence::service` stays the bare protocol for downstream use.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tunnel {
    /// A completed TLS handshake — the payload was decrypted before analysis.
    Tls,
}

impl Tunnel {
    /// The scheme prefix this tunnel contributes to a service label.
    fn scheme(self) -> &'static str {
        match self {
            Tunnel::Tls => "ssl",
        }
    }
}

/// One independent observation about what a port is running.
///
/// Every descriptive field is optional: a detector reports only what it
/// actually learned. The resolver merges fields across evidence, so a TLS
/// analyzer supplying `product` and a banner analyzer supplying `version` combine
/// into one verdict.
/// Comparable but not [`Eq`]: [`os`](Self::os) carries a confidence, which is a
/// float, and a value nobody can write down exactly is not one two observations
/// should be claimed to share.
#[derive(Debug, Clone, PartialEq)]
pub struct Evidence {
    pub service: Option<String>,
    pub product: Option<String>,
    pub version: Option<String>,
    pub vendor: Option<String>,
    /// Supplementary detail that is not the product itself: an environment hint
    /// or a *secondary* technology (an HTTP `X-Powered-By` value like `PHP/8.2`,
    /// an SSH `protocol 2.0`). Kept separate from `product` precisely so it can
    /// never displace the primary product in the resolver.
    pub extrainfo: Option<String>,
    /// A CPE identifier, when known. Kept as a string until a typed CPE model
    /// lands; forward-compatible with structured parsing later.
    pub cpe: Option<String>,
    /// The transport this observation was read through, if any. Set when the
    /// data was decrypted from a tunnel (e.g. banner matched inside TLS).
    pub tunnel: Option<Tunnel>,
    /// Whether this match is corroborated by the port it was found on — i.e. the
    /// signature was one registered for this port, not one found only by global
    /// content search. A port-confirmed match carries a stronger prior (the
    /// service was *expected* here), so the resolver ranks it above a
    /// global-only match of equal confidence. Analyzers that do not consult the
    /// port-signature index leave it `false`.
    pub port_confirmed: bool,
    pub confidence: Confidence,
    pub source: SourceId,
    /// What this observation said about the *machine*, as distinct from the
    /// service.
    ///
    /// Carried alongside rather than folded into the fields above because it
    /// answers a different question and is resolved by different rules. A banner
    /// identifies a service directly; that it also implies an operating system is
    /// a second, weaker inference — a container names the image it was built
    /// from, not the kernel it runs on. `ServiceVerdict` retains its whole
    /// evidence set, so this reaches a caller without the resolver having to
    /// rank it.
    pub os: Option<crate::fingerprint::os::OsEvidence>,
}

impl Evidence {
    /// Begins an evidence record from `source` at `confidence`, with no fields
    /// populated yet.
    pub fn new(source: SourceId, confidence: Confidence) -> Self {
        Self {
            service: None,
            product: None,
            version: None,
            vendor: None,
            extrainfo: None,
            cpe: None,
            tunnel: None,
            port_confirmed: false,
            os: None,
            confidence,
            source,
        }
    }

    pub fn with_service(mut self, service: impl Into<String>) -> Self {
        self.service = Some(service.into());
        self
    }

    pub fn with_product(mut self, product: impl Into<String>) -> Self {
        self.product = Some(product.into());
        self
    }

    pub fn with_version(mut self, version: impl Into<String>) -> Self {
        self.version = Some(version.into());
        self
    }

    pub fn with_vendor(mut self, vendor: impl Into<String>) -> Self {
        self.vendor = Some(vendor.into());
        self
    }

    pub fn with_extrainfo(mut self, extrainfo: impl Into<String>) -> Self {
        self.extrainfo = Some(extrainfo.into());
        self
    }

    /// Records the tunnel this observation was read through.
    pub fn with_tunnel(mut self, tunnel: Tunnel) -> Self {
        self.tunnel = Some(tunnel);
        self
    }
}

/// The reconciled answer for a port, plus the full evidence it was drawn from.
///
/// Keeping every contributing [`Evidence`] (not just the winner) is deliberate:
/// provenance is a product feature — it makes results explainable and
/// signatures tunable.
/// Comparable but not [`Eq`], for the reason [`Evidence`] is not: the
/// observations it retains carry a confidence, and a float is not something two
/// verdicts should be claimed to share exactly.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ServiceVerdict {
    pub service: Option<String>,
    pub product: Option<String>,
    pub version: Option<String>,
    pub vendor: Option<String>,
    pub extrainfo: Option<String>,
    pub cpe: Option<String>,
    /// The tunnel the winning `service` was observed through, if any. Drives the
    /// `ssl/…` label in [`ServiceVerdict::to_service`].
    pub tunnel: Option<Tunnel>,
    pub confidence: Confidence,
    pub evidence: Vec<Evidence>,
}

impl ServiceVerdict {
    /// Reconciles independent observations into one verdict.
    ///
    /// Evidence is ranked strongest-first; each field is filled from the
    /// highest-confidence observation that carries it, so different analyzers
    /// can contribute different fields. Ties preserve insertion order, keeping
    /// the result deterministic. The full evidence set is retained.
    pub fn resolve(mut evidence: Vec<Evidence>) -> Self {
        // Rank strongest-first. Confidence dominates: a genuinely stronger
        // identification is never buried by port context. Within one confidence
        // level, a port-confirmed match (its signature was registered for this
        // port) outranks a global-only one — a coincidental cross-protocol
        // banner match (the classic bare-`220` FTP-vs-SMTP ambiguity) loses to
        // the service actually expected on the port. The sort is stable, so a
        // full tie keeps the order produced and stays independent of analyzer
        // scheduling.
        evidence.sort_by(|a, b| {
            b.confidence
                .cmp(&a.confidence)
                .then(b.port_confirmed.cmp(&a.port_confirmed))
        });

        let mut verdict = ServiceVerdict {
            confidence: evidence
                .first()
                .map(|e| e.confidence)
                .unwrap_or(Confidence::Heuristic),
            ..Default::default()
        };

        for ev in &evidence {
            // The tunnel travels with the service field: whichever evidence
            // first supplies the service also decides how it is labelled.
            if verdict.service.is_none() && ev.service.is_some() {
                verdict.tunnel = ev.tunnel;
            }
            fill(&mut verdict.service, &ev.service);
            fill(&mut verdict.version, &ev.version);
            fill(&mut verdict.vendor, &ev.vendor);
            fill(&mut verdict.extrainfo, &ev.extrainfo);
            fill(&mut verdict.cpe, &ev.cpe);
        }

        // Product needs more than "first that carries it". A product that merely
        // echoes the service ("http" for service http) is what a *generic* match
        // emits — the `generic_http` signature, the matcher's product-defaults-
        // to-service fallback, a protocol baseline. It conveys no product, so it
        // must not bury a real name ("cloudflare", bare "nginx") that a more
        // specific analyzer supplied at the *same* confidence. Prefer the
        // highest-confidence product that names something beyond the service;
        // fall back to the echo only when nothing more specific exists.
        verdict.product = evidence
            .iter()
            .filter_map(|ev| ev.product.as_deref())
            .find(|product| Some(*product) != verdict.service.as_deref())
            .or_else(|| evidence.iter().find_map(|ev| ev.product.as_deref()))
            .map(str::to_string);

        verdict.evidence = evidence;
        verdict
    }

    /// Whether the verdict names nothing identifiable.
    pub fn is_empty(&self) -> bool {
        self.service.is_none() && self.product.is_none()
    }

    /// Projects the verdict onto the crate's [`Service`] model, if it names
    /// anything. Returns `None` for an empty verdict.
    ///
    /// A tunnelled service is labelled `<scheme>/<name>` (e.g. `ssl/http`),
    /// keeping both observed facts visible — the protocol *and* that it was
    /// carried inside TLS — without renaming the bare protocol. An untunnelled
    /// service, or the tunnel's own `ssl` verdict, is labelled plainly.
    pub fn to_service(&self) -> Option<Service> {
        let name = self.service.clone().or_else(|| self.product.clone())?;
        let name = match self.tunnel {
            Some(tunnel) => format!("{}/{name}", tunnel.scheme()),
            None => name,
        };
        let mut service = Service::new(name, self.confidence.as_score());
        if let Some(product) = &self.product {
            service = service.with_product(product.clone());
        }
        if let Some(vendor) = &self.vendor {
            service = service.with_vendor(vendor.clone());
        }
        if let Some(version) = &self.version {
            service = service.with_version(version.clone());
        }
        if let Some(extrainfo) = &self.extrainfo {
            service = service.with_extrainfo(extrainfo.clone());
        }
        Some(service)
    }
}

/// Fills `slot` from `value` only if `slot` is empty and `value` is present.
fn fill(slot: &mut Option<String>, value: &Option<String>) {
    if slot.is_none()
        && let Some(v) = value
    {
        *slot = Some(v.clone());
    }
}

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

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

    fn ev(conf: Confidence) -> Evidence {
        Evidence::new(SourceId::BannerRegex, conf)
    }

    #[test]
    fn confidence_is_ordered() {
        assert!(Confidence::Certain > Confidence::Strong);
        assert!(Confidence::Strong > Confidence::Probable);
        assert!(Confidence::Probable > Confidence::Heuristic);
    }

    #[test]
    fn resolve_prefers_strongest_evidence_per_field() {
        let weak = ev(Confidence::Weak)
            .with_service("http")
            .with_product("generic");
        let strong = ev(Confidence::Strong)
            .with_service("http")
            .with_product("nginx");
        let verdict = ServiceVerdict::resolve(vec![weak, strong]);

        assert_eq!(verdict.product.as_deref(), Some("nginx"));
        assert_eq!(verdict.confidence, Confidence::Strong);
        assert_eq!(verdict.evidence.len(), 2);
    }

    #[test]
    fn informative_product_beats_a_service_echo_at_equal_confidence() {
        // A generic match names product == service ("http"); a specific analyzer
        // names the real server ("cloudflare"). Both Probable. Even with the
        // generic one first (as `generic_http` sorts ahead of later analyzers),
        // the real name must win the product slot.
        let generic = ev(Confidence::Probable)
            .with_service("http")
            .with_product("http");
        let specific = ev(Confidence::Probable)
            .with_service("http")
            .with_product("cloudflare");
        let verdict = ServiceVerdict::resolve(vec![generic, specific]);

        assert_eq!(verdict.service.as_deref(), Some("http"));
        assert_eq!(verdict.product.as_deref(), Some("cloudflare"));
    }

    #[test]
    fn service_echo_product_is_kept_when_nothing_more_specific_exists() {
        // With no informative product available, the echo is still surfaced
        // rather than dropping the product entirely.
        let verdict = ServiceVerdict::resolve(vec![
            ev(Confidence::Probable)
                .with_service("http")
                .with_product("http"),
        ]);
        assert_eq!(verdict.product.as_deref(), Some("http"));
    }

    #[test]
    fn port_confirmed_match_wins_the_service_at_equal_confidence() {
        // Insertion order puts the global match first, so without the
        // port-confirmation tie-break the stable sort would keep "smtp". The
        // port-confirmed "ftp" — the service actually expected on this port —
        // must win. This is the bare-`220` FTP-vs-SMTP residue.
        let global_smtp = ev(Confidence::Probable).with_service("smtp");
        let mut port_ftp = ev(Confidence::Probable).with_service("ftp");
        port_ftp.port_confirmed = true;

        let verdict = ServiceVerdict::resolve(vec![global_smtp, port_ftp]);
        assert_eq!(verdict.service.as_deref(), Some("ftp"));
    }

    #[test]
    fn confidence_still_dominates_port_confirmation() {
        // A weak port-confirmed match must not bury a genuinely stronger global
        // identification — confidence is the primary key, port-confirmation only
        // breaks ties within a level.
        let mut weak_port = ev(Confidence::Probable).with_service("ftp");
        weak_port.port_confirmed = true;
        let strong_global = ev(Confidence::Strong)
            .with_service("smtp")
            .with_product("Postfix");

        let verdict = ServiceVerdict::resolve(vec![weak_port, strong_global]);
        assert_eq!(verdict.service.as_deref(), Some("smtp"));
    }

    #[test]
    fn resolve_merges_fields_across_evidence() {
        let a = ev(Confidence::Strong)
            .with_service("https")
            .with_product("nginx");
        let b = ev(Confidence::Probable).with_version("1.25.3");
        let verdict = ServiceVerdict::resolve(vec![a, b]);

        assert_eq!(verdict.product.as_deref(), Some("nginx"));
        assert_eq!(verdict.version.as_deref(), Some("1.25.3"));
    }

    #[test]
    fn empty_verdict_maps_to_no_service() {
        assert!(ServiceVerdict::resolve(Vec::new()).to_service().is_none());
    }

    #[test]
    fn tunnel_prefixes_the_service_label_and_travels_with_service() {
        let tunnelled = ev(Confidence::Strong)
            .with_service("http")
            .with_product("nginx")
            .with_tunnel(Tunnel::Tls);
        let verdict = ServiceVerdict::resolve(vec![tunnelled]);
        assert_eq!(verdict.service.as_deref(), Some("http")); // bare on the verdict
        assert_eq!(verdict.tunnel, Some(Tunnel::Tls));
        assert_eq!(verdict.to_service().unwrap().name(), "ssl/http"); // composed label

        // Without a tunnel the label is plain.
        let plain = ev(Confidence::Strong).with_service("http");
        let verdict = ServiceVerdict::resolve(vec![plain]);
        assert_eq!(verdict.tunnel, None);
        assert_eq!(verdict.to_service().unwrap().name(), "http");
    }

    #[test]
    fn vendor_and_extrainfo_resolve_and_reach_the_service() {
        // Different analyzers contribute different attribution: a Server match
        // names product+vendor, an X-Powered-By match adds a secondary tech.
        // Both must survive resolution and land on the projected Service.
        let server = ev(Confidence::Strong)
            .with_service("http")
            .with_product("Apache")
            .with_vendor("Apache Software Foundation");
        let powered_by = ev(Confidence::Probable)
            .with_service("http")
            .with_extrainfo("PHP/8.2.1");
        let verdict = ServiceVerdict::resolve(vec![server, powered_by]);

        assert_eq!(
            verdict.vendor.as_deref(),
            Some("Apache Software Foundation")
        );
        assert_eq!(verdict.extrainfo.as_deref(), Some("PHP/8.2.1"));

        let service = verdict.to_service().expect("names a service");
        assert_eq!(service.product(), Some("Apache"));
        assert_eq!(service.vendor(), Some("Apache Software Foundation"));
        assert_eq!(service.extrainfo(), Some("PHP/8.2.1"));
    }

    #[test]
    fn verdict_projects_onto_service_model() {
        let verdict = ServiceVerdict::resolve(vec![
            ev(Confidence::Strong)
                .with_service("ssh")
                .with_product("OpenSSH")
                .with_version("9.6"),
        ]);
        let service = verdict.to_service().expect("names a service");
        assert_eq!(service.confidence(), Confidence::Strong.as_score());
    }
}