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

//! # JSON export
//!
//! Writes a report as a single JSON document in the schema defined by
//! [`schema`](super::schema).
//!
//! This is the canonical format. Everything the engine records is in it,
//! nothing is summarized away, and the other formats are lossy views of the
//! same data. When a question arises about what a report contains, the answer
//! is whatever this writes.

use std::io::Write;

use crate::export::schema::ReportDto;
use crate::export::{ExportError, ExportOptions, Exporter, write};
use crate::report::ScanReport;

/// The format name carried in a [`ExportError::Render`].
const FORMAT: &str = "json";

/// Writes a report as one JSON document.
///
/// ```no_run
/// use std::fs::File;
/// use zond_engine::report::ScanReport;
/// use zond_engine::export::{ExportOptions, Exporter, JsonExporter, Redaction};
///
/// # fn example(report: &ScanReport) -> Result<(), Box<dyn std::error::Error>> {
/// let options = ExportOptions::new().with_redaction(Redaction::Standard);
/// let mut file = File::create("scan.json")?;
///
/// JsonExporter::new(options).export(report, &mut file)?;
/// # Ok(())
/// # }
/// ```
#[must_use]
#[derive(Debug, Clone)]
pub struct JsonExporter {
    options: ExportOptions,
    pretty: bool,
}

/// Written out rather than derived: a derived one reads `pretty` as `false` and
/// hands back a compact exporter, which is not what [`JsonExporter::new`] gives.
impl Default for JsonExporter {
    fn default() -> Self {
        Self::new(ExportOptions::default())
    }
}

impl JsonExporter {
    /// An exporter that writes indented JSON.
    ///
    /// Indented is the default because the usual destination is a file somebody
    /// will open, and because a report that diffs line by line is worth more
    /// than one that saves bytes. The engine sorts hosts, ports and every set it
    /// exports for the same reason.
    pub fn new(options: ExportOptions) -> Self {
        Self {
            options,
            pretty: true,
        }
    }

    /// Switches to single-line output.
    ///
    /// For a pipe rather than a file: an HTTP body, a message queue, anything
    /// that is going to be parsed and never read.
    pub fn compact(mut self) -> Self {
        self.pretty = false;
        self
    }

    /// Switches back to indented output.
    pub fn pretty(mut self) -> Self {
        self.pretty = true;
        self
    }

    /// The options in force.
    pub fn options(&self) -> &ExportOptions {
        &self.options
    }
}

impl Exporter for JsonExporter {
    fn export(&self, report: &ScanReport, out: &mut dyn Write) -> Result<(), ExportError> {
        let document = ReportDto::new(report, &self.options);

        let written = if self.pretty {
            serde_json::to_writer_pretty(&mut *out, &document)
        } else {
            serde_json::to_writer(&mut *out, &document)
        };
        written.map_err(|error| write::render_error(FORMAT, error))?;

        // A POSIX text file ends in a newline, and appending after one that
        // does not would join two documents on a line.
        out.write_all(b"\n")?;
        Ok(())
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::export::Redaction;
    use crate::export::fixture;
    use serde_json::Value;

    fn export(exporter: &JsonExporter, report: &ScanReport) -> Value {
        let mut bytes = Vec::new();
        exporter
            .export(report, &mut bytes)
            .expect("export succeeds");

        assert_eq!(
            bytes.last(),
            Some(&b'\n'),
            "a written report must end in a newline"
        );
        serde_json::from_slice(&bytes).expect("the output parses as JSON")
    }

    fn exported(report: &ScanReport) -> Value {
        export(&JsonExporter::new(ExportOptions::new()), report)
    }

    /// The two halves of `engine` name the same build, whoever produced the
    /// findings.
    ///
    /// With `name` fixed at this engine's and `version` taken from the report's
    /// own attribution, exporting a report read out of nmap's XML would write
    /// `zond-engine` paired with `nmap 7.94`, a build that never existed. What
    /// produced the findings is `produced_by`.
    #[test]
    fn the_engine_object_names_the_build_that_wrote_the_document() {
        let foreign =
            ScanReport::recorded("nmap 7.94", fixture::report().phases().to_vec(), Vec::new());
        let document = exported(&foreign);

        assert_eq!(document["engine"]["name"], "zond-engine");
        assert_eq!(
            document["engine"]["version"],
            crate::report::ENGINE_VERSION,
            "the version beside a fixed name has to be that name's"
        );
        assert_eq!(document["produced_by"], "nmap 7.94");
    }

    /// **The document says what the report as a whole left open, beside the
    /// flag that reads it.** A resumed job carries the stopped sitting's phase,
    /// whose own lists still name the host its budget cut short and the targets
    /// its walk never reached, beside the sitting that finished both. `partial`
    /// reads the report and says nothing is open; a consumer reading the
    /// phases would have to know the rule that closes one account with
    /// another to agree with it, so the report's own reading is written out.
    #[test]
    fn the_document_names_what_the_report_left_open_across_its_sittings() {
        use crate::report::{PhaseParts, ScanPhase};

        let stopped = fixture::report();
        let document = exported(&stopped);
        assert_eq!(document["timed_out"], serde_json::json!(["203.0.113.9"]));
        assert_eq!(document["unreached"], "1024");

        let first = &stopped.phases()[0];
        let finished = ScanPhase::from_parts(PhaseParts {
            open: false,
            attachments: Vec::new(),
            kind: first.kind(),
            started_at: first.started_at(),
            elapsed: first.elapsed(),
            privilege: first.privilege(),
            targets: first.targets().clone(),
            settings: first.settings().clone(),
            failures: Vec::new(),
            refusals: Vec::new(),
            unroutable: first.unroutable().to_vec(),
            refused_by_route: first.refused_by_route().to_vec(),
            timed_out: Vec::new(),
            icmp_rate_limited: Vec::new(),
            reached_by_connect: Vec::new(),
            undecided: Vec::new(),
            liveness_skipped: first.liveness_skipped(),
            silent: Vec::new(),
            stopped: None,
            passes_cut: Vec::new(),
            unreached: 0,
            unheard_probes: 0,
            probes: Vec::new(),
            origin: None,
        });
        let mut resumed = stopped.clone();
        resumed.merge(ScanReport::new(finished, []));
        let document = exported(&resumed);

        assert_eq!(
            document["phases"][0]["timed_out"],
            serde_json::json!(["203.0.113.9"]),
            "the stopped sitting's record stands"
        );
        assert!(
            document.get("timed_out").is_none(),
            "{}",
            document["timed_out"]
        );
        assert!(
            document.get("unreached").is_none(),
            "{}",
            document["unreached"]
        );
        assert!(
            document.get("undecided").is_none(),
            "{}",
            document["undecided"]
        );
        assert_eq!(document["partial"], resumed.is_partial());
    }

    /// The header is the part a consumer reads before it decides whether it can
    /// read the rest, so every field in it has to be there.
    #[test]
    fn the_document_identifies_itself() {
        let document = exported(&fixture::report());

        assert_eq!(document["schema_version"], 1);
        assert_eq!(document["engine"]["name"], "zond-engine");
        assert_eq!(document["engine"]["version"], crate::report::ENGINE_VERSION);
        assert_eq!(
            document["produced_by"],
            crate::export::fixture::report().engine_version()
        );
        assert!(
            document["generated_at"]
                .as_str()
                .expect("a generation timestamp")
                .ends_with('Z')
        );
        assert_eq!(document["partial"], true);
    }

    /// Counts in the summary are derived from the hosts, so the two views of the
    /// same scan cannot be allowed to disagree.
    #[test]
    fn the_summary_agrees_with_the_hosts_it_summarizes() {
        let document = exported(&fixture::report());

        let hosts = document["hosts"].as_array().expect("a host array");
        let open_ports = hosts
            .iter()
            .flat_map(|host| host["ports"].as_array().expect("a port array"))
            .filter(|port| port["state"] == "open")
            .count();

        assert_eq!(document["summary"]["hosts_total"], hosts.len());
        assert_eq!(document["summary"]["ports_open"], open_ports);
        assert_eq!(document["summary"]["hosts_alive"], 2);
        assert_eq!(document["summary"]["services_identified"], 1);
    }

    /// Hosts sort by address and ports by number, so two scans of the same
    /// network produce documents that diff cleanly.
    #[test]
    fn output_is_ordered_for_diffing() {
        let document = exported(&fixture::report());
        let hosts = document["hosts"].as_array().expect("a host array");

        let addresses: Vec<&str> = hosts
            .iter()
            .map(|host| host["primary_ip"].as_str().expect("an address"))
            .collect();
        assert_eq!(addresses, vec!["203.0.113.1", "203.0.113.2", "203.0.113.9"]);

        let ports: Vec<u64> = hosts[0]["ports"]
            .as_array()
            .expect("a port array")
            .iter()
            .map(|port| port["port"].as_u64().expect("a port number"))
            .collect();
        assert_eq!(ports, vec![22, 80, 443]);
    }

    /// Two exports of one report must be byte-identical apart from the stamp
    /// that says when they were written. Anything else moving means an
    /// unordered collection reached the output.
    #[test]
    fn two_exports_of_one_report_differ_only_in_their_timestamp() {
        let report = fixture::report();
        let exporter = JsonExporter::new(ExportOptions::new());

        let mut first = Vec::new();
        let mut second = Vec::new();
        exporter.export(&report, &mut first).expect("first export");
        exporter
            .export(&report, &mut second)
            .expect("second export");

        let strip = |bytes: &[u8]| {
            String::from_utf8(bytes.to_vec())
                .expect("utf-8")
                .lines()
                .filter(|line| !line.contains("\"generated_at\""))
                .collect::<Vec<_>>()
                .join("\n")
        };

        assert_eq!(strip(&first), strip(&second));
    }

    /// The whole point of the redaction policy: what leaves the process is
    /// masked, and what stays behind is not touched.
    #[test]
    fn redaction_masks_names_and_hardware_without_losing_the_hosts() {
        let report = fixture::report();

        let plain = exported(&report);
        let masked = export(
            &JsonExporter::new(ExportOptions::new().with_redaction(Redaction::Standard)),
            &report,
        );

        assert_eq!(plain["hosts"][0]["hostname"], "router.local");
        assert_eq!(masked["hosts"][0]["hostname"], "roXXXXXal");

        // A name the host gave for itself is masked on the terms its hostname
        // is, the domain as well as the machine, and keeps what says what it
        // is: the kind and the protocol name no one.
        assert_eq!(plain["hosts"][0]["names"][0]["name"], "gw01.corp.example");
        assert_eq!(masked["hosts"][0]["names"][0]["name"], "gwXXXXXle");
        assert_eq!(masked["hosts"][0]["names"][0]["kind"], "host");
        assert_eq!(masked["hosts"][0]["names"][0]["source"], "ldap");
        let domains = masked["hosts"][0]["names"].to_string();
        assert!(!domains.contains("corp"), "a domain survived: {domains}");

        assert_eq!(plain["hosts"][0]["hardware"]["mac"], "2c:cf:67:00:00:01");
        assert_eq!(masked["hosts"][0]["hardware"]["mac"], "2c:cf:67:XX:XX:XX");

        // The vendor comes from the OUI, which masking preserves, so hiding it
        // would cost information without buying privacy.
        assert_eq!(
            plain["hosts"][0]["hardware"]["vendor"],
            masked["hosts"][0]["hardware"]["vendor"]
        );

        // Addresses are untouched: a report whose hosts all mask to the same
        // string is not a report.
        assert_eq!(
            plain["hosts"][0]["primary_ip"],
            masked["hosts"][0]["primary_ip"]
        );
        assert_ne!(
            masked["hosts"][0]["primary_ip"],
            masked["hosts"][1]["primary_ip"]
        );

        // A certificate names machines and people too.
        assert_eq!(
            masked["hosts"][0]["ports"][2]["security"]["certificate"]["common_name"],
            "roXXXXXal"
        );

        // The scan's own redaction setting is a record of how the scan ran, not
        // of how it was exported, and must not move when the export policy does.
        assert_eq!(
            plain["phases"][0]["settings"]["redact"],
            masked["phases"][0]["settings"]["redact"]
        );
    }

    /// A field that has no value is present and null; a list with nothing in it
    /// is present and empty. A consumer never has to tell absent from empty.
    #[test]
    fn absent_values_are_present_and_null() {
        let document = exported(&fixture::report());
        let bare = &document["hosts"][2];

        assert!(bare["hostname"].is_null());
        assert!(bare["os"].is_null());
        assert!(bare["hardware"].is_null());
        assert!(bare["telemetry"]["rtt_median_us"].is_null());
        assert!(bare["ports"].as_array().expect("a port array").is_empty());
        assert!(
            bare["reasons"]
                .as_array()
                .expect("a reason array")
                .is_empty()
        );
    }

    /// Instrumentation is what bounds how far a host list can be trusted, so it
    /// has to arrive self-describing: a histogram whose bucket bounds live only
    /// in this crate's source is not a document anyone else can read.
    #[test]
    fn probe_instrumentation_carries_its_own_units() {
        let document = exported(&fixture::report());
        let stats = &document["phases"][0]["probe_stats"][0];

        assert_eq!(stats["scanner"], "routed");
        assert_eq!(stats["stop_reason"], "deadline_expired");
        assert_eq!(stats["complete"], false);
        assert_eq!(stats["targets"], "256");

        let attempts = stats["answered_on"].as_array().expect("an attempt array");
        assert_eq!(attempts[0]["attempt"], 1);
        assert_eq!(attempts[0]["count"], 7);
        assert_eq!(attempts[0]["or_later"], false);
        assert_eq!(
            attempts.last().expect("a final attempt bucket")["or_later"],
            true
        );

        let buckets = stats["found_at"].as_array().expect("a bucket array");
        assert_eq!(buckets[0]["le_ms"], 1);
        assert_eq!(
            buckets.last().expect("a final bucket")["le_ms"],
            Value::Null,
            "the open-ended bucket must say so rather than name a bound"
        );

        assert_eq!(stats["capture"]["dropped"], 0);
    }

    /// A failed strategy is the difference between an empty network and a scan
    /// that never ran, and it is the one thing a consumer must not miss.
    #[test]
    fn a_failed_strategy_reaches_the_document() {
        let document = exported(&fixture::report());
        let failures = document["phases"][0]["failures"]
            .as_array()
            .expect("a failure array");

        assert_eq!(failures.len(), 2);
        assert_eq!(failures[0]["scanner"], "local");
        assert_eq!(failures[0]["reason"], "raw socket unavailable");
        assert!(
            failures[0]["at"]
                .as_str()
                .expect("a timestamp")
                .ends_with('Z')
        );
    }

    /// Work a limit cut short is marked so in the document, and a failure is
    /// not, so a consumer can tell a fault to look for from a limit to raise.
    /// Left out where false, so a failure reads as every document before the
    /// marker wrote one.
    #[test]
    fn work_a_limit_cut_short_is_marked_apart_from_a_failure() {
        let document = exported(&fixture::report());
        let failures = document["phases"][0]["failures"]
            .as_array()
            .expect("a failure array");

        assert_eq!(failures[0]["scanner"], "local");
        assert!(failures[0].get("cut_short").is_none(), "{}", failures[0]);
        assert_eq!(failures[1]["scanner"], "connect");
        assert_eq!(failures[1]["cut_short"], true);
    }

    /// The two ways of building one of these have to produce the same exporter.
    ///
    /// A derived `Default` reads `pretty` as `false`, so
    /// `JsonExporter::default()` would write the compact document while
    /// `JsonExporter::new(ExportOptions::default())` writes the indented one that
    /// `new` documents as the default. Compared as bytes, because the difference
    /// is only whitespace and a test that parses the output first is blind to
    /// it.
    #[test]
    fn the_default_exporter_is_the_one_new_builds() {
        let report = fixture::report();

        // Without the stamp, which is the one field that moves between two
        // exports of one report.
        let render = |exporter: &JsonExporter| {
            let mut bytes = Vec::new();
            exporter.export(&report, &mut bytes).expect("exports");
            String::from_utf8(bytes)
                .expect("utf-8")
                .lines()
                .filter(|line| !line.contains("\"generated_at\""))
                .collect::<Vec<_>>()
                .join("\n")
        };

        let built = render(&JsonExporter::new(ExportOptions::new()));
        assert_eq!(render(&JsonExporter::default()), built);
        assert!(
            built.contains("\n  "),
            "the documented default is indented output"
        );
    }

    /// Compact output is the same document, not a smaller one.
    #[test]
    fn compact_output_carries_the_same_document() {
        let report = fixture::report();

        let indented = exported(&report);
        let compact = export(&JsonExporter::new(ExportOptions::new()).compact(), &report);

        let mut indented = indented;
        let mut compact = compact;
        indented["generated_at"] = Value::Null;
        compact["generated_at"] = Value::Null;

        assert_eq!(indented, compact);
    }

    /// The engine writes into whatever it is handed, and a destination that
    /// fails part way through has to surface as a failed export rather than a
    /// truncated file reported as a success.
    #[test]
    fn a_failing_destination_surfaces_as_an_error() {
        struct Full;

        impl Write for Full {
            fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
                Err(std::io::Error::new(
                    std::io::ErrorKind::StorageFull,
                    "no space left on device",
                ))
            }

            fn flush(&mut self) -> std::io::Result<()> {
                Ok(())
            }
        }

        let error = JsonExporter::new(ExportOptions::new())
            .export(&fixture::report(), &mut Full)
            .expect_err("a full disk fails the export");

        assert!(matches!(error, ExportError::Io(_)), "got {error:?}");
    }
}