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
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
// 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

//! # The on-disk form of a capability tape
//!
//! A [`CapTape`] written down as data a journal can hold, so a scan's recorded runs
//! survive to be replayed later. This is the compute tier's parallel to the model's
//! record layer: the tape itself stays free of `serde`, and this module is the one
//! place its wire shape and the names of its errors are defined. A record is built
//! from a tape through [`From`] and read back through
//! [`rebuild`](CapTapeRecord::rebuild).
//!
//! ## How the pieces are written
//!
//! Bytes become lowercase hex, the encoding the engine already uses for a content
//! hash: compact enough, identical across two runs so a journal stays comparable
//! with itself, and needing no dependency. Each exchange records either its reply
//! or its error, never both, so a run that branched on a refusal replays that branch
//! from the file. Following the model records, a value that will not parse reads
//! back as the least it could mean rather than failing the whole tape: an
//! undecodable byte string reads empty, and an unknown error kind reads as a reset.

use std::net::IpAddr;

use serde::{Deserialize, Serialize};

use super::capability::CapError;
use super::replay::{CapTape, ResolveExchange, SpeakExchange};
use crate::record::DetectionIdRecord;

/// One detection run, as the journal holds it: which detection ran over which
/// subject, and the tape of what it read. This is the line the journal writes per
/// run, so a recorded scan can be replayed offline, detection by detection.
///
/// A versioned record, read back from a journal, never built by hand:
/// `#[non_exhaustive]`, so a field a later format adds is not a breaking change for
/// a caller reading one.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DetectionRunRecord {
    /// The address the detection ran against.
    pub host: String,
    /// The name a target reached that address by, where it named a host: what
    /// a module read as `ctx.hostname`, kept so a replay reads it too.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub host_name: Option<String>,
    /// The port it ran over.
    pub port: u16,
    /// The transport, by wire name.
    pub protocol: String,
    /// Which detection ran, to which version, from which bytes.
    pub detection: DetectionIdRecord,
    /// The responses the scan had already gathered and handed the detection, which
    /// a passive detection reads instead of speaking. Kept so a replay feeds the
    /// same input.
    #[serde(default)]
    pub responses: Vec<String>,
    /// What it read from its capabilities, kept for replay.
    pub tape: CapTapeRecord,
}

/// The runs over one port that read the same responses, as one line of a
/// journal: the port and its responses once, then each run's detection and
/// tape.
///
/// Every passive detection that matches a port's service reads everything the
/// scan gathered there, a dozen of them for any HTTP port, and a response runs
/// to kilobytes. Written with each run, a port's responses would fill the file
/// once per detection that read them. [`DetectionRunRecord`] stays the shape a
/// run is read back in; this is only how the file holds a batch of them.
///
/// An engine that writes a run to a line reads this as a line it cannot parse,
/// and refuses the file rather than replaying a passive run on no input.
#[cfg(feature = "journal-format")]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct PortRunsRecord {
    host: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    host_name: Option<String>,
    port: u16,
    protocol: String,
    responses: Vec<String>,
    runs: Vec<PortRunRecord>,
}

/// One run of a [`PortRunsRecord`]: what ran, and what it read from its
/// capabilities.
#[cfg(feature = "journal-format")]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct PortRunRecord {
    detection: DetectionIdRecord,
    tape: CapTapeRecord,
}

#[cfg(feature = "journal-format")]
impl PortRunsRecord {
    /// `runs` as the lines a journal writes them in: one for each port and
    /// set of responses, in the order each first appears, holding its runs in
    /// the order given.
    pub(crate) fn grouping(runs: &[DetectionRunRecord]) -> Vec<Self> {
        let mut lines: Vec<Self> = Vec::new();
        for run in runs {
            let line = lines.iter_mut().find(|line| {
                (
                    line.port,
                    &line.host,
                    &line.host_name,
                    &line.protocol,
                    &line.responses,
                ) == (
                    run.port,
                    &run.host,
                    &run.host_name,
                    &run.protocol,
                    &run.responses,
                )
            });
            let run_record = PortRunRecord {
                detection: run.detection.clone(),
                tape: run.tape.clone(),
            };
            match line {
                Some(line) => line.runs.push(run_record),
                None => lines.push(Self {
                    host: run.host.clone(),
                    host_name: run.host_name.clone(),
                    port: run.port,
                    protocol: run.protocol.clone(),
                    responses: run.responses.clone(),
                    runs: vec![run_record],
                }),
            }
        }
        lines
    }
}

/// A line of a journal's detection runs, in either shape it has been written
/// in.
///
/// Untagged: a port's line is told apart by its runs, and a line naming a
/// single run is read as one.
#[cfg(feature = "journal-format")]
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(untagged)]
pub(crate) enum DetectionLine {
    /// A port's runs, sharing its responses.
    Port(PortRunsRecord),
    /// One run, carrying its own copy of what it read.
    Run(DetectionRunRecord),
}

#[cfg(feature = "journal-format")]
impl DetectionLine {
    /// The runs this line holds, each with the responses it read.
    pub(crate) fn into_runs(self) -> Vec<DetectionRunRecord> {
        match self {
            Self::Run(run) => vec![run],
            Self::Port(line) => line
                .runs
                .into_iter()
                .map(|run| DetectionRunRecord {
                    host: line.host.clone(),
                    host_name: line.host_name.clone(),
                    port: line.port,
                    protocol: line.protocol.clone(),
                    detection: run.detection,
                    responses: line.responses.clone(),
                    tape: run.tape,
                })
                .collect(),
        }
    }
}

/// A capability tape, as a file holds it.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CapTapeRecord {
    /// Each recorded `speak`, in call order.
    #[serde(default)]
    pub speaks: Vec<SpeakExchangeRecord>,
    /// Each recorded `resolve`, in call order.
    #[serde(default)]
    pub resolves: Vec<ResolveExchangeRecord>,
    /// Each `now` tick, in call order, as milliseconds on the run's clock.
    #[serde(default)]
    pub nows: Vec<u64>,
}

/// One recorded `speak`: the bytes sent, and either the reply or the error.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpeakExchangeRecord {
    /// The bytes the module sent, as hex.
    pub sent: String,
    /// The reply as hex, present when the exchange succeeded.
    #[serde(default)]
    pub reply: Option<String>,
    /// The error, present when it failed.
    #[serde(default)]
    pub error: Option<CapErrorRecord>,
}

/// One recorded `resolve`: the name asked, and either the addresses or the error.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResolveExchangeRecord {
    /// The name the module asked to resolve.
    pub name: String,
    /// The addresses returned, as strings, present when resolution succeeded.
    #[serde(default)]
    pub addresses: Vec<String>,
    /// The error, present when it failed.
    #[serde(default)]
    pub error: Option<CapErrorRecord>,
}

/// A capability error, by wire name, with the reason a denial carries.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CapErrorRecord {
    /// The error kind, by wire name.
    pub kind: String,
    /// Why, for a denial. Absent for every other kind.
    #[serde(default)]
    pub reason: Option<String>,
}

impl From<&CapTape> for CapTapeRecord {
    fn from(tape: &CapTape) -> Self {
        Self {
            speaks: tape.speaks.iter().map(SpeakExchangeRecord::from).collect(),
            resolves: tape
                .resolves
                .iter()
                .map(ResolveExchangeRecord::from)
                .collect(),
            nows: tape.nows.clone(),
        }
    }
}

impl CapTapeRecord {
    /// Rebuilds the tape this record holds.
    pub fn rebuild(&self) -> CapTape {
        CapTape {
            speaks: self
                .speaks
                .iter()
                .map(SpeakExchangeRecord::rebuild)
                .collect(),
            resolves: self
                .resolves
                .iter()
                .map(ResolveExchangeRecord::rebuild)
                .collect(),
            nows: self.nows.clone(),
        }
    }
}

impl From<&SpeakExchange> for SpeakExchangeRecord {
    fn from(exchange: &SpeakExchange) -> Self {
        let (reply, error) = match &exchange.reply {
            Ok(bytes) => (Some(to_hex(bytes)), None),
            Err(error) => (None, Some(CapErrorRecord::from(error))),
        };
        Self {
            sent: to_hex(&exchange.sent),
            reply,
            error,
        }
    }
}

impl SpeakExchangeRecord {
    fn rebuild(&self) -> SpeakExchange {
        let reply = match &self.error {
            Some(error) => Err(error.rebuild()),
            None => Ok(from_hex(self.reply.as_deref().unwrap_or(""))),
        };
        SpeakExchange {
            sent: from_hex(&self.sent),
            reply,
        }
    }
}

impl From<&ResolveExchange> for ResolveExchangeRecord {
    fn from(exchange: &ResolveExchange) -> Self {
        let (addresses, error) = match &exchange.result {
            Ok(addresses) => (addresses.iter().map(IpAddr::to_string).collect(), None),
            Err(error) => (Vec::new(), Some(CapErrorRecord::from(error))),
        };
        Self {
            name: exchange.name.clone(),
            addresses,
            error,
        }
    }
}

impl ResolveExchangeRecord {
    fn rebuild(&self) -> ResolveExchange {
        let result = match &self.error {
            Some(error) => Err(error.rebuild()),
            None => Ok(self
                .addresses
                .iter()
                .filter_map(|address| address.parse().ok())
                .collect()),
        };
        ResolveExchange {
            name: self.name.clone(),
            result,
        }
    }
}

impl From<&CapError> for CapErrorRecord {
    fn from(error: &CapError) -> Self {
        Self {
            kind: cap_error_kind_name(error).to_owned(),
            reason: match error {
                CapError::Denied(reason) => Some(reason.clone()),
                _ => None,
            },
        }
    }
}

impl CapErrorRecord {
    fn rebuild(&self) -> CapError {
        cap_error(&self.kind, self.reason.as_deref())
    }
}

/// The wire name of a capability error.
fn cap_error_kind_name(error: &CapError) -> &'static str {
    match error {
        CapError::ByteBudgetExhausted => "byte-budget-exhausted",
        CapError::ConnectionBudgetExhausted => "connection-budget-exhausted",
        CapError::Denied(_) => "denied",
        CapError::OutOfDescriptors => "out-of-descriptors",
        CapError::TimedOut => "timed-out",
        CapError::ConnectionRefused => "connection-refused",
        CapError::Reset => "reset",
    }
}

/// The capability error a wire name and its reason name. An unknown kind reads as a
/// reset, the most generic failure, rather than dropping the exchange.
fn cap_error(kind: &str, reason: Option<&str>) -> CapError {
    match kind {
        "byte-budget-exhausted" => CapError::ByteBudgetExhausted,
        "connection-budget-exhausted" => CapError::ConnectionBudgetExhausted,
        "denied" => CapError::Denied(reason.unwrap_or_default().to_owned()),
        "out-of-descriptors" => CapError::OutOfDescriptors,
        "timed-out" => CapError::TimedOut,
        "connection-refused" => CapError::ConnectionRefused,
        _ => CapError::Reset,
    }
}

/// Bytes as lowercase hex, the engine's content-hash convention.
fn to_hex(bytes: &[u8]) -> String {
    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}

/// Bytes from lowercase hex. A malformed string, an odd length, or a non-hex or
/// non-ASCII byte reads back empty rather than failing, since a machine wrote it
/// and a corrupt tape is a degraded replay, not a crash. Indexing is over bytes,
/// not chars, so a multi-byte character cannot land a slice mid-character.
fn from_hex(hex: &str) -> Vec<u8> {
    let hex = hex.as_bytes();
    if !hex.len().is_multiple_of(2) {
        return Vec::new();
    }
    (0..hex.len())
        .step_by(2)
        .map(|start| {
            let hi = (hex[start] as char).to_digit(16)?;
            let lo = (hex[start + 1] as char).to_digit(16)?;
            Some((hi * 16 + lo) as u8)
        })
        .collect::<Option<Vec<u8>>>()
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::detect::compute::{
        Budget, CapError, ComputeRuntime, Grant, LiveCapabilities, ModuleBody,
        RecordedCapabilities, RecordingCapabilities, RhaiRuntime,
    };
    use crate::fingerprint::PortContext;
    use crate::model::finding::{DetectionClass, DetectionId, Version};
    use crate::model::port::Protocol;
    use crate::testing::loopback::from_this_process;
    use std::io::{Read, Write};
    use std::net::TcpListener;
    use std::thread;
    use std::time::Duration;

    fn budget() -> Budget {
        Budget {
            fuel: 1_000_000,
            deadline: Duration::from_secs(2),
            max_memory: 65_536,
            max_bytes: 8_192,
            max_connections: 4,
        }
    }

    fn grant() -> Grant {
        Grant {
            detection: DetectionId::new("record-test", Version::new(1, 0, 0), "hash").unwrap(),
            class: DetectionClass::ActiveBenign,
            budget: budget(),
            speak: true,
            resolve: false,
        }
    }

    fn ctx(port: u16) -> PortContext {
        PortContext {
            port,
            protocol: Protocol::Tcp,
            addr: None,
            tunnel: None,
            speaks_http: false,
            detection: crate::config::ServiceDetection::default(),
            host_name: None,
        }
    }

    #[test]
    fn a_tape_survives_json_and_still_replays_identically() {
        // The whole persistence guarantee: capture a live run, write the tape to
        // JSON and read it back, and the replay from that JSON reproduces the live
        // findings exactly. This is what the journal will do.
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        thread::spawn(move || {
            if let Some(mut sock) = from_this_process(&listener).next() {
                let mut probe = [0u8; 64];
                let _ = sock.read(&mut probe);
                // A reply with a non-ASCII byte, so a lossy encoding would corrupt it.
                let _ = sock.write_all(&[0x52, 0x45, 0x44, 0x49, 0x53, 0xff]);
            }
        });

        let source = r#"
            fn analyze(ctx, responses) {
                let reply = speak(blob(4, 0x41));
                [ #{
                    severity: "medium",
                    summary: "answered " + reply.len() + " bytes at " + now(),
                } ]
            }
        "#;

        let runtime = RhaiRuntime::new();
        let module = runtime
            .load(&ModuleBody::Rhai(source.to_string()))
            .expect("the module compiles");

        // Capture a live run.
        let mut recording =
            RecordingCapabilities::new(LiveCapabilities::new(addr, Protocol::Tcp, None, &budget()));
        let mut instance = runtime
            .instantiate(&module, &grant())
            .expect("instantiates");
        let live = runtime
            .run(&mut instance, &ctx(addr.port()), &[], &mut recording)
            .expect("a clean live run");
        let tape = recording.into_tape();

        // Round-trip the tape through JSON, as a journal writes and reads it.
        let json = serde_json::to_string(&CapTapeRecord::from(&tape)).expect("serializes");
        let restored = serde_json::from_str::<CapTapeRecord>(&json)
            .expect("deserializes")
            .rebuild();
        assert_eq!(
            restored, tape,
            "the tape did not survive the JSON round-trip"
        );

        // Replay from the restored tape and compare to the live findings.
        let mut caps = RecordedCapabilities::from_tape(restored);
        let mut instance = runtime
            .instantiate(&module, &grant())
            .expect("instantiates");
        let replayed = runtime
            .run(&mut instance, &ctx(addr.port()), &[], &mut caps)
            .expect("a clean replay");

        assert_eq!(
            live, replayed,
            "the findings did not survive the journal round-trip"
        );
    }

    /// The name a run's module read as `ctx.hostname` survives the journal's
    /// line, so a replay reads what the live run did, and a line written
    /// without one reads as a run on an address named by itself.
    #[test]
    fn a_runs_host_name_survives_the_journal_line() {
        let detection = DetectionId::new("d", Version::new(1, 0, 0), "h").expect("an id");
        let run = |host_name: Option<&str>| DetectionRunRecord {
            host: "192.0.2.1".to_string(),
            host_name: host_name.map(str::to_string),
            port: 443,
            protocol: "tcp".to_string(),
            detection: DetectionIdRecord::from(&detection),
            responses: Vec::new(),
            tape: CapTapeRecord::from(&CapTape::default()),
        };
        let runs = vec![run(Some("box.example")), run(None)];

        let read: Vec<DetectionRunRecord> = PortRunsRecord::grouping(&runs)
            .into_iter()
            .map(|line| serde_json::to_string(&line).expect("serializes"))
            .flat_map(|json| {
                serde_json::from_str::<DetectionLine>(&json)
                    .expect("deserializes")
                    .into_runs()
            })
            .collect();
        assert_eq!(read, runs);

        let unnamed = serde_json::to_string(&run(None)).expect("serializes");
        assert!(!unnamed.contains("host_name"), "{unnamed}");
    }

    #[test]
    fn every_error_kind_is_named_and_read_back() {
        // A name that does not parse back to its own variant would silently rewrite a
        // recorded error on read, turning a refusal into something else.
        let errors = [
            CapError::ByteBudgetExhausted,
            CapError::ConnectionBudgetExhausted,
            CapError::Denied("out of scope".to_string()),
            CapError::OutOfDescriptors,
            CapError::TimedOut,
            CapError::ConnectionRefused,
            CapError::Reset,
        ];
        for error in errors {
            let rebuilt = CapErrorRecord::from(&error).rebuild();
            assert_eq!(
                rebuilt, error,
                "an error kind did not survive its wire name"
            );
        }
    }

    #[test]
    fn a_tape_with_non_ascii_hex_reads_back_empty_rather_than_panicking() {
        // A journal a local attacker plants can hold any string in a hex field. An
        // even byte length of multi-byte characters once passed the length guard
        // and then sliced a `&str` mid-character, aborting the read of the file.
        let record = CapTapeRecord {
            speaks: vec![SpeakExchangeRecord {
                sent: "€€".to_string(),
                reply: Some(" zz not hex".to_string()),
                error: None,
            }],
            resolves: Vec::new(),
            nows: Vec::new(),
        };

        let tape = record.rebuild();
        assert_eq!(tape.speaks.len(), 1);
        assert_eq!(tape.speaks[0].sent, Vec::<u8>::new());
        assert_eq!(tape.speaks[0].reply, Ok(Vec::new()));
    }
}