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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
// 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

//! A report that exercises every corner of the exported document.
//!
//! Export tests need a report containing each shape the schema can produce: a
//! fully described host and a bare one, a port with a certificate and one
//! without, a strategy that failed, a scanner that filed counters, a script value
//! JSON cannot represent. Driving a real scan produces none of that reliably, and
//! building it inline would leave every test covering a slightly different
//! document.
//!
//! It is built once, here, so anything a test asserts about the output traces to
//! a value set below.

use std::net::{IpAddr, Ipv4Addr};
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use crate::config::{IdleScan, ZondConfig};
use crate::evasion::EvasionProfile;
use crate::model::capture::CaptureCounts;
use crate::model::confidence::Confidence;
use crate::model::exclusion::Exclusions;
use crate::model::finding::{
    DetectionClass, DetectionId, Excerpt, Finding, Reference, Severity, Version,
};
use crate::model::host::{
    EvidenceSource, Filtering, HardwareDescription, HardwareInfo, Hop, Host, HostStatus,
    IpProtocolState, NetworkRole, OsFingerprint, StatusProtocol, StatusReason,
};
use crate::model::ip::scoped::Zone;
use crate::model::ip::set::IpSet;
use crate::model::mac::MacAddr;
use crate::model::port::{
    CertificateInfo, Discovery, Port, PortState, Protocol, ScanResponse, Security, Service,
};
use crate::model::tls::{
    CipherSuite, Interruption, TlsSupport, TlsVersion, UnfinishedVersion, VersionSupport,
};
use crate::protocols::tcp::flags;
use crate::report::ScannerKind;
use crate::report::WindowSummary;
use crate::report::{
    Attachment, AttachmentSource, BUCKET_BOUNDS_MS, ProbeStats, ScanKind, ScanReport, StopReason,
    TargetScope,
};
use crate::scanner::recorder::PhaseRecorder;
use crate::scanner::session::ScanSession;
use crate::system::privilege::Privilege;

/// An address on the fixture's network.
fn ip(last: u8) -> IpAddr {
    IpAddr::V4(Ipv4Addr::new(203, 0, 113, last))
}

/// The gateway: everything the schema can say about a host, said about one.
fn router() -> Host {
    let mut host = Host::new(ip(1));
    host.set_hostname(Some("router.local".to_string()));
    host.set_status(HostStatus::Up);
    host.add_reason(StatusReason::new(StatusProtocol::Arp, "reply from gateway"));
    // Every sender a reason can name besides the host itself: a middlebox the
    // report names, and one whose address the scan's exclusions withheld.
    host.add_reason(
        StatusReason::new(
            StatusProtocol::IcmpUnreachable,
            "unreachable, from the path",
        )
        .from_source(IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1))),
    );
    let mut withheld = StatusReason::new(StatusProtocol::IcmpUnreachable, "unreachable");
    withheld.source = EvidenceSource::Withheld;
    host.add_reason(withheld);
    host.record_mac(MacAddr::new(0x2c, 0xcf, 0x67, 0x00, 0x00, 0x01));

    let mut os = OsFingerprint::new("Linux", 95)
        .with_family("Unix-like")
        // Both axes at once, the case a fixture is most likely to leave out.
        .with_device("Printer")
        .with_generation("5.15.0")
        // Shaped like what the stack fingerprinter renders, so the document
        // exercises a populated evidence line rather than a null.
        .with_evidence("syn-ack hops>=64 opts=M,S,T,N,W win=65160=45x1448 ws=7 mss=1460");
    os.add_cpe("cpe:/o:linux:linux_kernel:5.15.0");
    host.set_os(os);

    host.add_rtt(Duration::from_micros(1_200));
    host.add_rtt(Duration::from_micros(1_800));
    host.add_rtt(Duration::from_micros(3_000));

    // Every shape a path can hold: a measured hop, a router that would not
    // identify itself, a hop inherited from another host's trace, and a router
    // whose address the scan's exclusions withheld. Recorded out of order for
    // the same reason the ports below are.
    host.record_hop(Hop::withheld(4));
    host.record_hop(Hop::answered(
        3,
        IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1)),
        Some(Duration::from_micros(4_100)),
    ));
    host.record_hop(Hop::silent(2));
    host.record_hop(
        Hop::answered(1, IpAddr::V4(Ipv4Addr::new(203, 0, 113, 254)), None).as_inferred(),
    );

    // Added out of ascending order, so the document's ordering guarantee is
    // being tested rather than inherited from how the fixture was written.
    host.add_port(https_port());
    host.add_port(ssh_port());
    host.add_port(Port::new(80, Protocol::Tcp, PortState::Open));

    // The characterise pass drew every filtering conclusion for this host, so
    // the exported document carries them and the schema is held to each.
    host.add_filtering(Filtering::InlineMiddlebox);
    host.add_filtering(Filtering::StatefulFilter);
    host.add_filtering(Filtering::PortTrustingAcl);
    host.add_filtering(Filtering::StatelessFilter);

    // One of each verdict, so a document carrying this fixture exercises every
    // state the schema accepts rather than whichever one a live scan happened to
    // reach.
    host.record_ip_protocol(1, IpProtocolState::Open);
    host.record_ip_protocol(47, IpProtocolState::Closed);
    host.record_ip_protocol(50, IpProtocolState::Filtered);
    host.record_ip_protocol(89, IpProtocolState::OpenFiltered);
    host.record_ip_protocol(103, IpProtocolState::Unasked);

    host
}

/// A port carrying a service identification, discovery telemetry, and script
/// output including a value JSON cannot express.
fn ssh_port() -> Port {
    let service = Service::new("ssh", 100)
        .with_product("OpenSSH")
        .with_vendor("OpenBSD")
        .with_version("8.9p1")
        .with_cpe("cpe:/a:openbsd:openssh:8.9p1");

    let discovery = Discovery::new(ScanResponse::TcpSynAck)
        .with_rtt(Duration::from_micros(1_450))
        .with_ttl(64)
        .with_source_ip(ip(50));

    Port::new(22, Protocol::Tcp, PortState::Open)
        .with_service(service)
        .with_discovery(discovery)
}

/// A port carrying a certificate, whose subject names a machine.
fn https_port() -> Port {
    let certificate = CertificateInfo::new(
        "router.local",
        "Local CA",
        std::time::UNIX_EPOCH + Duration::from_secs(1_767_225_600),
        std::time::UNIX_EPOCH + Duration::from_secs(1_798_761_600),
        "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
    )
    .with_sans([Arc::from("www.router.local")])
    .with_public_key("ECDSA", 256);

    let security = Security::new()
        .with_tls_version("TLSv1.3")
        .with_cipher_suite("TLS_AES_256_GCM_SHA384")
        .with_alpn("h2")
        .with_alpn("http/1.1")
        .with_certificate(certificate)
        .with_support(accepted());

    Port::new(443, Protocol::Tcp, PortState::Open).with_security(security)
}

/// What an enumeration found this endpoint accepts.
///
/// The shape the document has to be able to say, rather than a plausible
/// server: a withdrawn version beside a current one, a suite with nothing wrong
/// with it beside one that is simply broken, a number the engine could not
/// name, and walks that did not finish for each of the reasons one can end. A fixture that only held a well-configured server would leave every
/// interesting field of the block untested.
fn accepted() -> TlsSupport {
    let suite = |code: u16| CipherSuite::from_code(code).expect("a suite in the registry");

    TlsSupport::new()
        .accepting(VersionSupport::new(
            TlsVersion::Tls10,
            // Insecure and weak together, so the grading reaches the document.
            vec![suite(0x000A), suite(0x002F)],
            Vec::new(),
        ))
        .accepting(VersionSupport::new(
            TlsVersion::Tls12,
            vec![suite(0xC030), suite(0x009C)],
            // A suite this build does not carry, which a reader still has to be
            // told about.
            vec![0xFF01],
        ))
        .accepting(VersionSupport::new(
            TlsVersion::Tls13,
            vec![suite(0x1302)],
            Vec::new(),
        ))
        // A version the endpoint stopped answering about before saying
        // anything, which is neither accepted nor refused.
        .leaving_unfinished(UnfinishedVersion::new(
            TlsVersion::Tls11,
            Interruption::Unanswered,
        ))
        // And one whose suites above are a floor, because the scan stopped
        // asking part way through.
        .leaving_unfinished(UnfinishedVersion::new(
            TlsVersion::Tls12,
            Interruption::Stopped,
        ))
}

/// A host that answered nothing but is known to be there.
fn filtered_host() -> Host {
    let mut host = Host::new(ip(2));
    host.set_status(HostStatus::Filtered);
    host.add_reason(StatusReason::basic(StatusProtocol::TcpSyn));
    host.add_port(Port::new(445, Protocol::Tcp, PortState::Filtered));
    host
}

/// A host with nothing on it, so the document is held to a fixed shape when
/// there is nothing to put in it.
fn bare_host() -> Host {
    let mut host = Host::new(ip(9));
    host.set_status(HostStatus::Down);
    host
}

/// The counters a routed sweep that ran out of time would file.
fn probe_stats() -> ProbeStats {
    let mut found_at = [0u64; BUCKET_BOUNDS_MS.len() + 1];
    found_at[0] = 4;
    found_at[3] = 3;
    found_at[BUCKET_BOUNDS_MS.len()] = 2;

    ProbeStats {
        // A paced scanner, cut back twice and still short of its ceiling: what
        // a consumer reads to tell this fixture's silence from a firewall.
        window: Some(WindowSummary {
            capacity: 48,
            peak: 256,
            reductions: 2,
            adaptive: true,
            at_floor: false,
        }),
        scanner: ScannerKind::Routed,
        targets: 256,
        stop_reason: StopReason::DeadlineExpired,
        elapsed: Duration::from_millis(412),
        sends_attempted: 512,
        sends_failed: 0,
        sends_witnessed: 0,
        segments_seen: 271,
        segments_off_target: 3,
        replies_without_rtt: 2,
        hosts_found: 9,
        answered_on: [7, 2, 0, 0, 0, 0],
        answered_unattributed: 0,
        first_reply: Some(Duration::from_micros(900)),
        last_reply: Some(Duration::from_millis(405)),
        found_at,
        capture: Some(CaptureCounts {
            received: 271,
            dropped: 0,
            if_dropped: 0,
            stopped_early: 0,
        }),
    }
}

/// A one-phase discovery report over three hosts, a failed strategy and one
/// instrumented scanner.
pub(crate) fn report() -> ScanReport {
    // Built with a spent per-host budget so that asking about one host below
    // files it, and the document carries the list a phase writes when it leaves
    // a host early.
    let (_session, ctx) = ScanSession::builder()
        .host_timeout(Some(Duration::ZERO))
        .build();

    let mut targets = IpSet::new();
    targets.insert_range("203.0.113.0/24".parse().expect("a valid range"));

    // Half the range withheld by policy, so the exported scope carries an
    // exclusion that overlapped rather than one that did nothing. Every host
    // below sits in the half that was kept.
    let mut excluded = IpSet::new();
    excluded.insert_range("203.0.113.128/25".parse().expect("a valid range"));

    // This phase evaded something, so the document carries an evasion record
    // and every writer is held to what one looks like. The port-scan phase
    // below keeps the defaults, giving the fixture one of each.
    let config = ZondConfig {
        evasion: EvasionProfile::default()
            .with_source_port(53)
            .with_ttl(40)
            .with_padding(24)
            .with_bad_tcp_checksum(true)
            .with_spoof_mac(MacAddr::new(0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x01))
            .with_fragment(28)
            .with_decoys(vec![
                "192.0.2.61".parse().expect("a valid decoy address"),
                "192.0.2.62".parse().expect("a valid decoy address"),
            ])
            .with_flags(flags::SYN | flags::FIN),
        // For the schema rather than for plausibility: a phase carries the
        // idle-scan record beside the evasion one.
        idle_scan: Some(IdleScan {
            zombie: "192.0.2.9".parse().expect("a valid zombie address"),
            zombie_port: Some(113),
        }),
        // Both wall-clock bounds, so the settings block carries a value in each
        // rather than a pair of nulls no writer is held to.
        host_timeout: Some(Duration::from_secs(300)),
        scan_timeout: Some(Duration::from_secs(3600)),
        // The technique nobody would reach for first, so the document carries a
        // value the writer had to look up rather than the one it would emit for
        // a default it never read.
        sctp_technique: crate::model::technique::SctpScanTechnique::CookieEcho,
        ..Default::default()
    };

    let recorder = PhaseRecorder::start(
        ScanKind::Discovery,
        Privilege::Raw,
        TargetScope::from_ip_set(&mut targets, &Exclusions::new(excluded)),
        &config,
    );

    ctx.record_failure(ScannerKind::Local, "raw socket unavailable".to_string());
    ctx.record_probe_stats(probe_stats());
    // A sweep covers the link it ran on as well as the addresses it was handed.
    // Without one, every test of that field compares two empty lists.
    ctx.record_sweep(Zone::new(3, "en0"));

    // A managed switch's announcement, so the document carries an attachment.
    // Recorded through the context rather than assembled into the phase, so the
    // path a real announcement takes is the path under test.
    ctx.record_attachment(
        Attachment::new(
            Zone::new(3, "en0"),
            AttachmentSource::Lldp,
            SystemTime::UNIX_EPOCH + Duration::from_secs(1_772_000_000),
        )
        .with_device_mac(MacAddr::new(0x00, 0x1B, 0x2C, 0x3D, 0x4E, 0x5F))
        .with_device_name("core-sw-02")
        .with_port("GigabitEthernet1/0/14")
        .with_native_vlan(40)
        .with_management_address(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 2))),
    );

    // A host the phase gave up on, filed the way a strategy files one: by
    // asking whether its budget is spent. `bare_host` is the one left early,
    // which is why it carries so little.
    assert!(
        ctx.host_expired(ip(9)),
        "the fixture's budget is spent before it is asked"
    );

    // Loopback, which a raw sweep reaches by connect whatever its privilege, so
    // the document carries the list a reader tells connect evidence from raw
    // evidence by. A range as well as a single address, since a tunnel's own
    // subnet arrives whole.
    let mut connected = IpSet::new();
    connected.insert(IpAddr::V4(Ipv4Addr::LOCALHOST));
    connected.insert_range("198.51.100.0/30".parse().expect("a valid range"));
    ctx.record_reached_by_connect(&connected);

    for host in [router(), filtered_host(), bare_host()] {
        ctx.store.insert(host.scoped_ip(), host);
    }

    // Correlation is its own step rather than something `finish` does on the
    // way past, so a fixture wanting a vulnerability finding has to ask.
    for mut entry in ctx.store.iter_mut() {
        crate::cve::correlate(entry.value_mut());
    }

    recorder.finish(&ctx)
}

// ---------------------------------------------------------------------------
// A network, and the same network later
// ---------------------------------------------------------------------------

/// The moment the earlier of the two comparison scans ran.
const BASELINE_AT: Duration = Duration::from_secs(1_780_000_000);

/// A day, for placing the fixtures apart.
const DAY: Duration = Duration::from_secs(86_400);

/// The port set both comparison scans walked, on every address.
const COMPARED_PORTS: &str = "22,80,443,8080,8443";

/// Two scans of one network, thirty-five days apart, differing in one of every
/// way a comparison can report.
///
/// Built for a schema rather than for plausibility: a host gone, a host arrived,
/// a port opened, a port shut, a service moved a version, a certificate rotated,
/// a certificate nobody touched crossing its expiry threshold, an operating
/// system reidentified and a name resolved differently. A comparison of the two
/// carries at least one change of nearly every kind, so a test can assert the
/// whole document.
///
/// Both phases are port scans that state which ports they walked. A discovery
/// sweep walks none, and against one of those every endpoint change reads as
/// ground nobody covered, which exercises the coverage rules instead.
///
/// Times are fixed rather than taken from the clock. A certificate crossing a
/// threshold between two scans is only expressible if the two are a known
/// distance apart.
pub(crate) fn compared() -> (ScanReport, ScanReport) {
    (
        compared_phase(0, before_hosts()),
        compared_phase(35, after_hosts()),
    )
}

/// One side of [`compared`]: a port-scan phase `days` after the baseline,
/// stating the ports it walked.
fn compared_phase(days: u64, hosts: Vec<Host>) -> ScanReport {
    use crate::model::port::PortSet;
    use crate::model::target::{TargetMap, TargetSet};
    use crate::report::{PhaseParts, ScanPhase, ScanSettings};

    let mut targets = TargetMap::new();
    let mut addresses = IpSet::new();
    addresses.insert_range("203.0.113.0/25".parse().expect("a valid range"));
    targets.add_unit(TargetSet::new(
        addresses,
        PortSet::try_from(COMPARED_PORTS).expect("a valid port set"),
    ));

    let phase = ScanPhase::from_parts(PhaseParts {
        // No attachment: where the measuring machine was plugged in has
        // nothing to do with what changed between the two scans.
        attachments: Vec::new(),
        kind: ScanKind::PortScan,
        started_at: std::time::UNIX_EPOCH + BASELINE_AT + DAY * days as u32,
        elapsed: Duration::from_secs(12),
        privilege: Some(Privilege::Raw),
        targets: TargetScope::from_target_map(&mut targets, &Exclusions::none()),
        settings: ScanSettings::from(&ZondConfig::default()),
        failures: Vec::new(),
        refusals: Vec::new(),
        unroutable: Vec::new(),
        timed_out: Vec::new(),
        reached_by_connect: Vec::new(),
        probes: Vec::new(),
        origin: None,
    });

    ScanReport::recorded(crate::report::ENGINE_VERSION, vec![phase], hosts)
}

/// A certificate, by the two things that make one distinguishable.
fn certificate(fingerprint: &str, issuer: &str, ends: Duration) -> Security {
    Security::new()
        .with_tls_version("TLSv1.3")
        .with_cipher_suite("TLS_AES_256_GCM_SHA384")
        .with_certificate(CertificateInfo::new(
            "www.example.test",
            issuer,
            std::time::UNIX_EPOCH + BASELINE_AT - DAY * 90,
            std::time::UNIX_EPOCH + ends,
            fingerprint,
        ))
}

/// The gateway, whose every field moves between the two scans.
fn compared_router(later: bool) -> Host {
    let mut host = Host::new(ip(1));
    host.set_status(HostStatus::Up);
    host.add_reason(StatusReason::new(StatusProtocol::Arp, "reply from gateway"));
    host.record_mac(MacAddr::new(0x2c, 0xcf, 0x67, 0x00, 0x00, 0x01));
    host.set_hostname(Some(
        if later {
            "gateway.local"
        } else {
            "router.local"
        }
        .to_string(),
    ));
    host.set_os(
        OsFingerprint::new("Linux", 95)
            .with_family("Unix-like")
            .with_generation(if later { "6.1.0" } else { "5.15.0" }),
    );

    // A finding the later scan draws and the baseline did not, so the comparison
    // carries `finding_appeared`.
    if later {
        host.add_finding(
            Finding::new(
                DetectionId::new("kev", Version::new(1, 0, 0), "seed")
                    .expect("a valid detection id"),
                "Known exploited vulnerability in the management interface",
                Severity::High,
                Confidence::Strong,
                DetectionClass::Passive,
            )
            .expect("a titled finding"),
        );
    }

    // One claim both scans make, graded higher by the later one, so the document
    // carries `finding_reassessed` as well.
    host.add_finding(
        Finding::new(
            DetectionId::new("tls-audit", Version::new(1, 0, 0), "seed")
                .expect("a valid detection id"),
            "Management interface accepts a deprecated TLS version",
            if later {
                Severity::High
            } else {
                Severity::Medium
            },
            Confidence::Strong,
            DetectionClass::Passive,
        )
        .expect("a titled finding"),
    );

    // A service that moved a version.
    host.add_port(
        Port::new(22, Protocol::Tcp, PortState::Open).with_service(
            Service::new("ssh", 100)
                .with_product("OpenSSH")
                .with_version(if later { "9.6p1" } else { "8.9p1" }),
        ),
    );

    // A port that shut.
    host.add_port(Port::new(
        80,
        Protocol::Tcp,
        if later {
            PortState::Closed
        } else {
            PortState::Open
        },
    ));

    // A certificate replaced by a different one.
    host.add_port(
        Port::new(443, Protocol::Tcp, PortState::Open).with_security(if later {
            certificate(
                "bbbb2b0b822cd15d6c15b0f00a089f86d081884c7d659a2feaa0c55ad015",
                "Public CA",
                BASELINE_AT + DAY * 400,
            )
        } else {
            certificate(
                "aaaa884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
                "Local CA",
                BASELINE_AT + DAY * 200,
            )
        }),
    );

    // A port that opened.
    if later {
        host.add_port(
            Port::new(8080, Protocol::Tcp, PortState::Open).with_service(
                Service::new("http-alt", 90)
                    .with_product("Caddy")
                    .with_version("2.7.6"),
            ),
        );
    }

    host
}

/// A host presenting the same certificate in both scans, which falls inside the
/// expiry threshold somewhere between them.
fn compared_expiring() -> Host {
    let mut host = Host::new(ip(4));
    host.set_status(HostStatus::Up);
    host.add_port(
        Port::new(8443, Protocol::Tcp, PortState::Open)
            // Sixty days of life at the baseline and twenty-five at the later
            // scan: outside a thirty-day threshold and then inside it, with
            // nothing about the certificate having moved.
            .with_security(certificate(
                "cccc7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
                "Local CA",
                BASELINE_AT + DAY * 60,
            )),
    );
    host
}

/// What the earlier scan found.
fn before_hosts() -> Vec<Host> {
    let mut gone = Host::new(ip(9));
    gone.set_status(HostStatus::Up);

    vec![compared_router(false), compared_expiring(), gone]
}

/// What the later scan found: the gateway changed, the expiring host untouched,
/// one host gone and one arrived.
fn after_hosts() -> Vec<Host> {
    let mut arrived = Host::new(ip(7));
    arrived.set_status(HostStatus::Up);
    arrived.add_reason(StatusReason::new(StatusProtocol::IcmpEcho, "echo reply"));
    arrived.add_port(Port::new(22, Protocol::Tcp, PortState::Open));

    vec![compared_router(true), compared_expiring(), arrived]
}

// ---------------------------------------------------------------------------
// The hostile report
// ---------------------------------------------------------------------------

/// The string every attacker-controlled field of [`hostile`] is set to.
///
/// A scanned host chooses its own banner, its own certificate subject and its
/// own script output, and all three end up in a document somebody opens. This
/// carries one payload per format the engine writes: markup and quotes for HTML
/// and XML, a leading `=` for a spreadsheet, and a right-to-left override, which
/// reverses the text after it so one address can be made to read as another.
///
/// One string rather than one per field, so a test asserting it never survives
/// intact does not have to know which field it came from and covers fields
/// nobody has written yet.
pub(crate) const HOSTILE: &str = "=<script>alert(\"x\")</script>&'\u{202e}";

/// A host on the hostile fixture's network.
/// A finding whose every describable string is hostile, including a `url`
/// reference, the one reference kind carrying attacker-controlled text.
fn hostile_finding() -> Finding {
    Finding::new(
        DetectionId::new(HOSTILE, Version::new(1, 0, 0), HOSTILE).unwrap(),
        HOSTILE,
        Severity::Critical,
        Confidence::Certain,
        DetectionClass::Exploit,
    )
    .unwrap()
    .with_excerpt(Excerpt::new(HOSTILE))
    .with_reference(Reference::url(HOSTILE))
    .with_remediation(HOSTILE)
}

fn hostile_host() -> Host {
    let mut host = Host::new(ip(3));
    host.set_hostname(Some(HOSTILE.to_string()));
    host.set_status(HostStatus::Up);
    host.add_reason(StatusReason::new(StatusProtocol::Arp, HOSTILE));
    host.set_hardware(hostile_hardware());
    // The one role anything assigns, so the corpus still exercises a non-empty
    // `roles` array through every exporter.
    host.add_network_role(NetworkRole::Tarpit);

    let mut os = OsFingerprint::new(HOSTILE, 90)
        .with_family(HOSTILE)
        .with_device(HOSTILE)
        .with_generation(HOSTILE)
        .with_kernel(HOSTILE)
        .with_arch(HOSTILE)
        .with_evidence(HOSTILE);
    os.add_cpe(HOSTILE);
    host.set_os(os);
    host.add_rtt(Duration::from_micros(1_000));

    host.add_finding(hostile_finding());
    host.add_port(hostile_port());
    host
}

/// A hardware record whose every describable string is hostile, beside the
/// address it was seen under.
///
/// Every field is a service's to state, and a rule fills a `hw.cpe23` template
/// from the banner's own captures, so none of them is safe to leave clean. All
/// seven are set rather than the ones a name-based check notices: `vendor`,
/// `product`, `family` and `version` share their names with a service's fields,
/// so the conformance check would read them as covered either way.
fn hostile_hardware() -> HardwareInfo {
    let mut hardware = HardwareInfo::new(MacAddr::new(0xde, 0xad, 0xbe, 0xef, 0x00, 0x01));
    hardware.merge(
        HardwareInfo::described(HardwareDescription {
            vendor: Some(HOSTILE),
            product: Some(HOSTILE),
            family: Some(HOSTILE),
            cpe23: Some(HOSTILE),
            model: Some(HOSTILE),
            version: Some(HOSTILE),
            serial_number: Some(HOSTILE),
        })
        .expect("a description naming every field names something"),
    );
    hardware
}

/// A port whose every describable string is hostile.
fn hostile_port() -> Port {
    let service = Service::new(HOSTILE, 100)
        .with_product(HOSTILE)
        .with_vendor(HOSTILE)
        .with_version(HOSTILE)
        .with_extrainfo(HOSTILE)
        .with_cpe(HOSTILE);

    let certificate = CertificateInfo::new(
        HOSTILE,
        HOSTILE,
        std::time::UNIX_EPOCH + Duration::from_secs(1_767_225_600),
        std::time::UNIX_EPOCH + Duration::from_secs(1_798_761_600),
        HOSTILE,
    )
    .with_sans([Arc::from(HOSTILE)])
    .with_public_key(HOSTILE, 256);

    let security = Security::new()
        .with_tls_version(HOSTILE)
        .with_cipher_suite(HOSTILE)
        .with_alpn(HOSTILE)
        .with_certificate(certificate);

    let mut port = Port::new(8443, Protocol::Tcp, PortState::Open)
        .with_service(service)
        .with_security(security)
        .with_discovery(Discovery::new(ScanResponse::TcpSynAck).with_source_ip(ip(50)));
    port.add_finding(hostile_finding());
    port
}

/// A report whose every attacker-controlled string is [`HOSTILE`].
///
/// The same shape as [`report`], so a writer that handles one handles the other.
/// It answers the question the per-field tests cannot: not whether the escaper
/// works, but whether every field goes through it.
pub(crate) fn hostile() -> ScanReport {
    let (_session, ctx) = ScanSession::new();

    let mut targets = IpSet::new();
    targets.insert_range("203.0.113.0/24".parse().expect("a valid range"));

    let recorder = PhaseRecorder::start(
        ScanKind::Discovery,
        Privilege::Raw,
        TargetScope::from_ip_set(&mut targets, &Exclusions::none()),
        &ZondConfig::default(),
    );

    ctx.record_failure(ScannerKind::Local, HOSTILE.to_string());
    // A neighbour's own account of itself, which is the most attacker-chosen
    // data a report carries: LLDP and CDP are unauthenticated by design, so
    // every string here was written by whoever is on the segment. It reaches
    // the HTML page's own table and the nmap document, and without this line no
    // escaping test would see one.
    ctx.record_attachment(
        crate::report::Attachment::new(
            crate::model::ip::scoped::Zone::new(1, HOSTILE),
            crate::report::AttachmentSource::Lldp,
            std::time::UNIX_EPOCH + Duration::from_secs(1_767_225_600),
        )
        .with_device_name(HOSTILE)
        .with_device_mac(MacAddr::new(0xde, 0xad, 0xbe, 0xef, 0x00, 0x02))
        .with_port(HOSTILE)
        .with_native_vlan(42)
        .with_management_address(ip(9)),
    );
    ctx.record_probe_stats(probe_stats());
    ctx.store.insert(
        crate::model::ip::scoped::ScopedIp::unscoped(ip(3)),
        hostile_host(),
    );

    recorder.finish(&ctx)
}