flowscope 0.22.0

Passive flow & session tracking for packet capture (runtime-free, cross-platform)
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
//! Parser tests using hand-crafted synthetic TLS records.
//!
//! Drives the `SessionParser` API (`TlsParser::feed_initiator`
//! / `feed_responder`) and collects emitted `TlsMessage`
//! variants.

use flowscope::{
    SessionParser, Timestamp,
    tls::{TlsAlert, TlsClientHello, TlsMessage, TlsParser, TlsServerHello, TlsVersion},
};

#[derive(Default)]
struct Captured {
    client_hellos: Vec<TlsClientHello>,
    server_hellos: Vec<TlsServerHello>,
    alerts: Vec<TlsAlert>,
    #[cfg(feature = "tls-fingerprints")]
    ja3s: Vec<(String, String)>,
}

impl Captured {
    fn ingest(&mut self, msgs: Vec<TlsMessage>) {
        for m in msgs {
            match m {
                TlsMessage::ClientHello(ch) => self.client_hellos.push(*ch),
                TlsMessage::ServerHello(sh) => self.server_hellos.push(*sh),
                TlsMessage::Alert(a) => self.alerts.push(a),
                #[cfg(feature = "tls-fingerprints")]
                TlsMessage::Ja3 { hash, canonical } => self.ja3s.push((hash, canonical)),
                #[cfg(feature = "tls-fingerprints")]
                TlsMessage::Ja4 { .. } => {}
                #[cfg(feature = "ja4plus")]
                TlsMessage::Ja4s { .. } => {}
                TlsMessage::Certificate { .. } => {}
                _ => {}
            }
        }
    }
}

// ── synthetic TLS record builders ──────────────────────────────

fn record(content_type: u8, version: u16, payload: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(5 + payload.len());
    out.push(content_type);
    out.extend_from_slice(&version.to_be_bytes());
    out.extend_from_slice(&(payload.len() as u16).to_be_bytes());
    out.extend_from_slice(payload);
    out
}

fn handshake(msg_type: u8, body: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(4 + body.len());
    out.push(msg_type);
    let len = body.len() as u32;
    out.push((len >> 16) as u8);
    out.push((len >> 8) as u8);
    out.push(len as u8);
    out.extend_from_slice(body);
    out
}

fn client_hello_with_sni(host: &str) -> Vec<u8> {
    let mut body = Vec::new();
    body.extend_from_slice(&0x0303u16.to_be_bytes());
    body.extend_from_slice(&[0u8; 32]);
    body.push(0);
    body.extend_from_slice(&2u16.to_be_bytes());
    body.extend_from_slice(&0x1301u16.to_be_bytes());
    body.push(1);
    body.push(0);

    let mut exts = Vec::new();
    let host_bytes = host.as_bytes();
    let mut sni_data = Vec::new();
    let server_name_list_len = (3 + host_bytes.len()) as u16;
    sni_data.extend_from_slice(&server_name_list_len.to_be_bytes());
    sni_data.push(0);
    sni_data.extend_from_slice(&(host_bytes.len() as u16).to_be_bytes());
    sni_data.extend_from_slice(host_bytes);
    exts.extend_from_slice(&0u16.to_be_bytes());
    exts.extend_from_slice(&(sni_data.len() as u16).to_be_bytes());
    exts.extend_from_slice(&sni_data);

    let alpn_list = b"\x02h2";
    let mut alpn_data = Vec::new();
    alpn_data.extend_from_slice(&(alpn_list.len() as u16).to_be_bytes());
    alpn_data.extend_from_slice(alpn_list);
    exts.extend_from_slice(&16u16.to_be_bytes());
    exts.extend_from_slice(&(alpn_data.len() as u16).to_be_bytes());
    exts.extend_from_slice(&alpn_data);

    body.extend_from_slice(&(exts.len() as u16).to_be_bytes());
    body.extend_from_slice(&exts);

    let hs = handshake(1, &body);
    record(22, 0x0303, &hs)
}

/// A ClientHello carrying SNI + a post-quantum `key_share`
/// (X25519MLKEM768, group 0x11ec) with a ~1.2 KiB dummy key — the
/// shape that pushes a real Chrome/Firefox ClientHello past one
/// TCP segment. Total record lands around 1.3 KiB.
fn client_hello_with_pq_keyshare(host: &str) -> Vec<u8> {
    let mut body = Vec::new();
    body.extend_from_slice(&0x0303u16.to_be_bytes());
    body.extend_from_slice(&[0u8; 32]);
    body.push(0);
    body.extend_from_slice(&2u16.to_be_bytes());
    body.extend_from_slice(&0x1301u16.to_be_bytes());
    body.push(1);
    body.push(0);

    let mut exts = Vec::new();
    // SNI.
    let host_bytes = host.as_bytes();
    let mut sni_data = Vec::new();
    sni_data.extend_from_slice(&((3 + host_bytes.len()) as u16).to_be_bytes());
    sni_data.push(0);
    sni_data.extend_from_slice(&(host_bytes.len() as u16).to_be_bytes());
    sni_data.extend_from_slice(host_bytes);
    exts.extend_from_slice(&0u16.to_be_bytes());
    exts.extend_from_slice(&(sni_data.len() as u16).to_be_bytes());
    exts.extend_from_slice(&sni_data);

    // key_share (51): one entry, group X25519MLKEM768 (0x11ec),
    // ~1216-byte key exchange value.
    let ke = vec![0xABu8; 1216];
    let mut entry = Vec::new();
    entry.extend_from_slice(&0x11ecu16.to_be_bytes());
    entry.extend_from_slice(&(ke.len() as u16).to_be_bytes());
    entry.extend_from_slice(&ke);
    let mut ks_data = Vec::new();
    ks_data.extend_from_slice(&(entry.len() as u16).to_be_bytes()); // client_shares len
    ks_data.extend_from_slice(&entry);
    exts.extend_from_slice(&51u16.to_be_bytes());
    exts.extend_from_slice(&(ks_data.len() as u16).to_be_bytes());
    exts.extend_from_slice(&ks_data);

    body.extend_from_slice(&(exts.len() as u16).to_be_bytes());
    body.extend_from_slice(&exts);

    let hs = handshake(1, &body);
    record(22, 0x0303, &hs)
}

fn client_hello_with_ech(host: &str, config_id: u8) -> Vec<u8> {
    let mut body = Vec::new();
    body.extend_from_slice(&0x0303u16.to_be_bytes());
    body.extend_from_slice(&[0u8; 32]);
    body.push(0);
    body.extend_from_slice(&2u16.to_be_bytes());
    body.extend_from_slice(&0x1301u16.to_be_bytes());
    body.push(1);
    body.push(0);

    let mut exts = Vec::new();
    // SNI (outer / cover)
    let host_bytes = host.as_bytes();
    let mut sni_data = Vec::new();
    let server_name_list_len = (3 + host_bytes.len()) as u16;
    sni_data.extend_from_slice(&server_name_list_len.to_be_bytes());
    sni_data.push(0);
    sni_data.extend_from_slice(&(host_bytes.len() as u16).to_be_bytes());
    sni_data.extend_from_slice(host_bytes);
    exts.extend_from_slice(&0u16.to_be_bytes());
    exts.extend_from_slice(&(sni_data.len() as u16).to_be_bytes());
    exts.extend_from_slice(&sni_data);

    // ECH (extension type 0xfe0d, outer form).
    // Body layout (RFC draft §5.1):
    //   1B  ECHClientHelloType (0 = outer)
    //   1B  HPKE config_id
    //   2B  HPKE KDF
    //   2B  HPKE AEAD
    //   2B  enc.len + enc bytes (use 0 bytes for the smoke test)
    //   2B  payload.len + payload bytes
    let mut ech_body = Vec::new();
    ech_body.push(0); // outer
    ech_body.push(config_id);
    ech_body.extend_from_slice(&0x0001u16.to_be_bytes()); // KDF
    ech_body.extend_from_slice(&0x0001u16.to_be_bytes()); // AEAD
    ech_body.extend_from_slice(&0u16.to_be_bytes()); // enc.len
    ech_body.extend_from_slice(&0u16.to_be_bytes()); // payload.len
    exts.extend_from_slice(&0xfe0du16.to_be_bytes());
    exts.extend_from_slice(&(ech_body.len() as u16).to_be_bytes());
    exts.extend_from_slice(&ech_body);

    body.extend_from_slice(&(exts.len() as u16).to_be_bytes());
    body.extend_from_slice(&exts);

    let hs = handshake(1, &body);
    record(22, 0x0303, &hs)
}

fn server_hello() -> Vec<u8> {
    let mut body = Vec::new();
    body.extend_from_slice(&0x0303u16.to_be_bytes());
    body.extend_from_slice(&[0u8; 32]);
    body.push(0);
    body.extend_from_slice(&0x1301u16.to_be_bytes());
    body.push(0);
    body.extend_from_slice(&0u16.to_be_bytes());
    let hs = handshake(2, &body);
    record(22, 0x0303, &hs)
}

fn alert_record(level: u8, desc: u8) -> Vec<u8> {
    record(21, 0x0303, &[level, desc])
}

// ── tests ──────────────────────────────────────────────────────

fn feed_init(parser: &mut TlsParser, captured: &mut Captured, bytes: &[u8]) {
    let mut out = Vec::new();
    parser.feed_initiator(bytes, Timestamp::default(), &mut out);
    captured.ingest(out);
}

fn feed_resp(parser: &mut TlsParser, captured: &mut Captured, bytes: &[u8]) {
    let mut out = Vec::new();
    parser.feed_responder(bytes, Timestamp::default(), &mut out);
    captured.ingest(out);
}

#[test]
fn ech_extension_marks_present_and_captures_config_id() {
    let mut parser = TlsParser::default();
    let mut captured = Captured::default();
    let bytes = client_hello_with_ech("cover.example.com", 7);
    feed_init(&mut parser, &mut captured, &bytes);
    assert_eq!(captured.client_hellos.len(), 1);
    let ch = &captured.client_hellos[0];
    assert!(ch.ech_present, "ECH extension should be detected");
    assert_eq!(ch.ech_config_id, Some(7));
    assert!(
        ch.sni_is_outer,
        "when ECH is present, the parsed SNI is the outer cover"
    );
    // SNI carries the outer cover (it's still the SNI extension
    // bytes; passive observers can't see the inner SNI).
    assert_eq!(ch.sni.as_deref(), Some("cover.example.com"));
}

#[test]
fn non_ech_client_hello_leaves_fields_default() {
    let mut parser = TlsParser::default();
    let mut captured = Captured::default();
    let bytes = client_hello_with_sni("example.com");
    feed_init(&mut parser, &mut captured, &bytes);
    let ch = &captured.client_hellos[0];
    assert!(!ch.ech_present);
    assert!(ch.ech_config_id.is_none());
    assert!(!ch.sni_is_outer);
}

#[test]
fn parses_client_hello_with_sni() {
    let mut parser = TlsParser::default();
    let mut captured = Captured::default();
    let bytes = client_hello_with_sni("example.com");
    feed_init(&mut parser, &mut captured, &bytes);
    assert_eq!(captured.client_hellos.len(), 1);
    assert_eq!(
        captured.client_hellos[0].sni.as_deref(),
        Some("example.com")
    );
    assert_eq!(captured.client_hellos[0].alpn, vec!["h2".to_string()]);
    assert_eq!(captured.client_hellos[0].cipher_suites, vec![0x1301]);
}

#[test]
fn parses_server_hello() {
    let mut parser = TlsParser::default();
    let mut captured = Captured::default();
    let bytes = server_hello();
    feed_resp(&mut parser, &mut captured, &bytes);
    assert_eq!(captured.server_hellos.len(), 1);
    assert_eq!(captured.server_hellos[0].cipher_suite, 0x1301);
    assert_eq!(captured.server_hellos[0].legacy_version, TlsVersion::Tls1_2);
}

#[test]
fn parses_alert() {
    let mut parser = TlsParser::default();
    let mut captured = Captured::default();
    let bytes = alert_record(2, 40);
    feed_init(&mut parser, &mut captured, &bytes);
    assert_eq!(captured.alerts.len(), 1);
    assert_eq!(captured.alerts[0].description, 40);
}

#[test]
fn record_split_across_segments() {
    let mut parser = TlsParser::default();
    let mut captured = Captured::default();
    let bytes = client_hello_with_sni("example.com");
    let mid = bytes.len() / 2;
    feed_init(&mut parser, &mut captured, &bytes[..mid]);
    assert!(
        captured.client_hellos.is_empty(),
        "should wait for full record"
    );
    feed_init(&mut parser, &mut captured, &bytes[mid..]);
    assert_eq!(captured.client_hellos.len(), 1);
    assert_eq!(
        captured.client_hellos[0].sni.as_deref(),
        Some("example.com")
    );
}

#[test]
fn large_pq_client_hello_reassembles_across_tcp_segments() {
    // Issue #135: a post-quantum ClientHello (~1.3 KiB) split across
    // several small TCP segments must still yield SNI + the PQ signal.
    let mut parser = TlsParser::default();
    let mut captured = Captured::default();
    let bytes = client_hello_with_pq_keyshare("pq.example.com");
    assert!(bytes.len() > 1200, "fixture should exceed one segment");

    // Feed in 400-byte TCP segments — none complete the record alone.
    for chunk in bytes.chunks(400) {
        feed_init(&mut parser, &mut captured, chunk);
    }
    assert_eq!(captured.client_hellos.len(), 1, "reassembled one CH");
    let ch = &captured.client_hellos[0];
    assert_eq!(ch.sni.as_deref(), Some("pq.example.com"));
    assert!(ch.pq_key_share, "X25519MLKEM768 key share detected");
    assert!(ch.key_share_groups.contains(&0x11ec));
    assert!(flowscope::tls::is_pq_hybrid_group(0x11ec));
}

#[test]
fn classical_client_hello_is_not_flagged_pq() {
    let mut parser = TlsParser::default();
    let mut captured = Captured::default();
    feed_init(
        &mut parser,
        &mut captured,
        &client_hello_with_sni("classic.example"),
    );
    assert_eq!(captured.client_hellos.len(), 1);
    assert!(!captured.client_hellos[0].pq_key_share);
}

#[test]
fn change_cipher_spec_stops_parsing() {
    let mut parser = TlsParser::default();
    let mut captured = Captured::default();
    let mut combined = Vec::new();
    combined.extend_from_slice(&server_hello());
    combined.extend_from_slice(&record(20, 0x0303, &[0x01])); // ChangeCipherSpec
    combined.extend_from_slice(&server_hello());
    feed_resp(&mut parser, &mut captured, &combined);
    // Only the first ServerHello parses; the second is past CCS.
    assert_eq!(captured.server_hellos.len(), 1);
}

#[test]
fn malformed_doesnt_panic() {
    let mut parser = TlsParser::default();
    let mut captured = Captured::default();
    let mut bad = vec![22u8, 0x03, 0x03, 0x00, 0x10];
    bad.extend_from_slice(&[0xff; 16]);
    feed_init(&mut parser, &mut captured, &bad);
    // Should not panic; the parser enters Desynced state.
}

#[cfg(feature = "tls-fingerprints")]
#[test]
fn ja3_fires_when_enabled() {
    use flowscope::tls::TlsConfig;
    let mut cfg = TlsConfig::default();
    cfg.ja3 = true;
    let mut parser = TlsParser::with_config(cfg);
    let mut captured = Captured::default();
    let bytes = client_hello_with_sni("example.com");
    feed_init(&mut parser, &mut captured, &bytes);
    assert_eq!(captured.ja3s.len(), 1);
    assert!(!captured.ja3s[0].0.is_empty(), "expected non-empty hash");
}

#[cfg(feature = "tls-fingerprints")]
#[test]
fn ja4_fires_when_enabled() {
    use flowscope::tls::TlsConfig;
    let mut cfg = TlsConfig::default();
    cfg.ja4 = true;
    let mut parser = TlsParser::with_config(cfg);
    let captured = std::cell::RefCell::new(Vec::new());
    let mut out = Vec::new();
    parser.feed_initiator(
        &client_hello_with_sni("example.com"),
        Timestamp::default(),
        &mut out,
    );
    for msg in out {
        if let TlsMessage::Ja4 { fingerprint } = msg {
            captured.borrow_mut().push(fingerprint);
        }
    }
    assert_eq!(captured.borrow().len(), 1);
    assert!(captured.borrow()[0].starts_with('t'));
}

#[cfg(feature = "tls-fingerprints")]
#[test]
fn standalone_ja3_matches_message_hash_and_facade_reexports() {
    use flowscope::tls::TlsConfig;
    // Capture both the ClientHello and the parser-emitted JA3 so we
    // can prove the standalone fn (issue #136) yields the same hash.
    let mut cfg = TlsConfig::default();
    cfg.ja3 = true;
    let mut parser = TlsParser::with_config(cfg);
    let mut captured = Captured::default();
    feed_init(
        &mut parser,
        &mut captured,
        &client_hello_with_sni("example.com"),
    );
    let ch = captured.client_hellos.first().expect("client hello");
    let (msg_hash, _canonical) = captured.ja3s.first().cloned().expect("ja3 message");

    // Standalone fns (both the `tls::` home and the `fingerprint::`
    // facade re-export) agree with the message-emitted hash.
    assert_eq!(flowscope::tls::ja3_fingerprint(ch), msg_hash);
    assert_eq!(flowscope::fingerprint::ja3_fingerprint(ch), msg_hash);
    assert!(!flowscope::tls::ja3_canonical(ch).is_empty());

    // JA4 facade re-export matches the `tls::` fn and is transport 't'.
    let ja4_home = flowscope::tls::ja4_fingerprint(ch);
    assert_eq!(flowscope::fingerprint::ja4_fingerprint(ch), ja4_home);
    assert!(ja4_home.starts_with('t'));
}