rustnet-core 0.6.0

Network analysis library: packet parsing, protocol types, deep packet inspection, link-layer parsers, connection merging, and DNS/GeoIP/OUI lookups: the reusable core of rustnet
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
use crate::network::dpi::tls_common::{
    self, TlsParseOptions, is_partial_sni, parse_sni_extension, parse_sni_header,
};
use crate::network::types::{CryptoFrameReassembler, TlsInfo};
use log::debug;

use super::salvage::{try_parse_unencrypted_crypto_frames, try_reconstruct_sni_from_fragments};

/// Check if SNI is complete (not partial)
fn is_complete_sni(sni: &Option<String>) -> bool {
    match sni {
        Some(s) => !is_partial_sni(s),
        None => false,
    }
}

/// Try to extract TLS info from contiguous reassembled data
fn try_extract_from_contiguous(reassembled: &[u8], allow_partial: bool) -> Option<TlsInfo> {
    debug!(
        "QUIC: Attempting to parse {} bytes of contiguous crypto data (allow_partial={})",
        reassembled.len(),
        allow_partial
    );

    let tls_info = parse_partial_tls_handshake(reassembled, allow_partial)?;

    if tls_info.sni.is_none() && tls_info.alpn.is_empty() {
        return None;
    }

    let sni_is_complete = is_complete_sni(&tls_info.sni);
    debug!(
        "QUIC: Found TLS info from contiguous data (complete={})",
        sni_is_complete
    );
    Some(tls_info)
}

/// Try to parse individual fragments with proper TLS headers
fn try_extract_from_fragments(
    reassembler: &CryptoFrameReassembler,
    allow_partial: bool,
) -> Option<TlsInfo> {
    debug!("QUIC: Trying to parse individual crypto fragments with proper TLS headers");

    for (offset, fragment_data) in reassembler.get_fragments() {
        debug!(
            "QUIC: Trying fragment at offset {} with {} bytes",
            offset,
            fragment_data.len()
        );

        // Only try to parse fragments that look like they contain complete TLS structures
        // Check if fragment starts with TLS handshake header (0x01 for ClientHello)
        if fragment_data.len() >= 4
            && fragment_data[0] == 0x01
            && let Some(tls_info) = parse_partial_tls_handshake(fragment_data, allow_partial)
            && (tls_info.sni.is_some() || !tls_info.alpn.is_empty())
        {
            let sni_is_complete = is_complete_sni(&tls_info.sni);
            debug!(
                "QUIC: Found TLS info from individual fragment at offset {} (complete={})",
                offset, sni_is_complete
            );
            return Some(tls_info);
        }

        // Also try direct TLS pattern matching, but only for fragments that look like TLS records
        if fragment_data.len() >= 6
            && fragment_data[0] == 0x16
            && let Some(tls_info) = try_parse_unencrypted_crypto_frames(fragment_data)
            && (tls_info.sni.is_some() || !tls_info.alpn.is_empty())
        {
            let sni_is_complete = is_complete_sni(&tls_info.sni);
            debug!(
                "QUIC: Found TLS info from pattern matching in fragment at offset {} (complete={})",
                offset, sni_is_complete
            );
            return Some(tls_info);
        }

        debug!(
            "QUIC: Skipping fragment at offset {} - doesn't start with TLS header",
            offset
        );
    }

    None
}

/// Try greedy SNI extraction from all fragments and contiguous data
fn try_extract_greedy_from_reassembler(
    reassembler: &CryptoFrameReassembler,
    contiguous: Option<&[u8]>,
    allow_partial: bool,
) -> Option<TlsInfo> {
    debug!("QUIC: Attempting greedy SNI extraction as final fallback");

    for (_, fragment_data) in reassembler.get_fragments() {
        if let Some(sni) =
            scan_for_sni_extension(fragment_data, allow_partial, SniScanStrictness::Lenient)
        {
            debug!("QUIC: Greedy extraction succeeded from fragment");
            return Some(TlsInfo::with_sni(sni));
        }
    }

    // Also try on contiguous data if available
    if let Some(contiguous) = contiguous
        && let Some(sni) =
            scan_for_sni_extension(contiguous, allow_partial, SniScanStrictness::Lenient)
    {
        debug!("QUIC: Greedy extraction succeeded from contiguous data");
        return Some(TlsInfo::with_sni(sni));
    }

    None
}

/// Try to extract TLS information from reassembled fragments
///
/// The `allow_partial` parameter controls whether partial SNI extraction is allowed:
/// - `false`: Only return complete SNI (used during initial packet parsing)
/// - `true`: Return partial SNI as fallback (used during merge/re-extraction)
///
/// Tries the cache first, then the extraction strategies below in order of
/// preference, stopping at the first that yields an SNI.
pub fn try_extract_tls_from_reassembler(
    reassembler: &mut CryptoFrameReassembler,
    allow_partial: bool,
) -> Option<TlsInfo> {
    if reassembler.extraction_finished() {
        return reassembler.get_cached_tls_info().cloned();
    }

    let contiguous = reassembler.get_contiguous_data();
    if let Some(data) = &contiguous
        && data.len() >= 4
        && data[0] == 0x01
    {
        let handshake_end = 4 + u32::from_be_bytes([0, data[1], data[2], data[3]]) as usize;
        // A complete SNI can precede ALPN and supported_versions. Only stop
        // when the declared ClientHello is assembled, or the bounded
        // inspection window has been filled for an oversized ClientHello.
        let inspected_end = handshake_end.min(CryptoFrameReassembler::MAX_BUFFER_SIZE);
        if data.len() >= inspected_end {
            let tls_info = if handshake_end <= CryptoFrameReassembler::MAX_BUFFER_SIZE {
                parse_partial_tls_handshake(&data[..inspected_end], allow_partial)
            } else {
                extract_provisional_tls(reassembler, contiguous.as_deref(), allow_partial)
            };
            reassembler.finish_extraction(tls_info.clone());
            return tls_info;
        }
    }

    extract_provisional_tls(reassembler, contiguous.as_deref(), allow_partial)
}

fn extract_provisional_tls(
    reassembler: &CryptoFrameReassembler,
    contiguous: Option<&[u8]>,
    allow_partial: bool,
) -> Option<TlsInfo> {
    if let Some(tls_info) = contiguous
        .and_then(|data| try_extract_from_contiguous(data, allow_partial))
        .or_else(|| try_extract_from_fragments(reassembler, allow_partial))
    {
        // Provisional metadata must not discard bytes needed by later
        // fragments, even when this fragment contains the entire SNI.
        return Some(tls_info);
    }

    // Fragment reconstruction needs a reasonable amount of data.
    let total_fragment_size: usize = reassembler.get_fragments().map(|(_, v)| v.len()).sum();
    if total_fragment_size >= 100 {
        debug!(
            "QUIC: Have {} total bytes in fragments, attempting reconstruction",
            total_fragment_size
        );
        if let Some(sni) = try_reconstruct_sni_from_fragments(reassembler)
            && (allow_partial || !is_partial_sni(&sni))
        {
            let sni_is_complete = !is_partial_sni(&sni);
            let tls_info = TlsInfo::with_sni(sni);
            debug!(
                "QUIC: Reconstructed SNI from fragmented data (complete={})",
                sni_is_complete
            );
            return Some(tls_info);
        }
    } else {
        debug!(
            "QUIC: Only {} total bytes in fragments, not enough for reliable SNI extraction",
            total_fragment_size
        );
    }

    // Greedy fallback.
    if let Some(tls_info) =
        try_extract_greedy_from_reassembler(reassembler, contiguous, allow_partial)
    {
        return Some(tls_info);
    }

    debug!("QUIC: No TLS info could be extracted from reassembler");
    None
}

/// Parse a TLS handshake from reassembled data
pub(super) fn parse_partial_tls_handshake(data: &[u8], allow_partial: bool) -> Option<TlsInfo> {
    let mut info = TlsInfo::new();
    if !tls_common::parse_handshake(data, &mut info, TlsParseOptions::quic(allow_partial)) {
        return None;
    }

    debug!(
        "QUIC: Parsed TLS info - SNI={:?}, ALPN={:?}, version={:?}",
        info.sni, info.alpn, info.version
    );

    if info.sni.is_some() || !info.alpn.is_empty() || info.version.is_some() {
        Some(info)
    } else {
        debug!("QUIC: No useful TLS info extracted");
        None
    }
}

/// Validation strictness applied to SNI extension candidates found by raw byte scanning
#[derive(Clone, Copy)]
pub(super) enum SniScanStrictness {
    /// Accept any candidate whose server name list fits within the extension length
    Lenient,
    /// Require a plausible server name list length, tolerating truncated extension data
    Moderate,
    /// Require the full extension to be present with exactly consistent header lengths
    Strict,
}

/// Try to match an SNI extension at position `i` in raw scan data
///
/// SNI extension structure:
/// - 0x00 0x00 - extension type (SNI)
/// - 2 bytes - extension length
/// - 2 bytes - server name list length
/// - 0x00 - name type (hostname)
/// - 2 bytes - hostname length
/// - N bytes - hostname
pub(super) fn match_sni_extension_at(
    data: &[u8],
    i: usize,
    allow_partial: bool,
    strictness: SniScanStrictness,
) -> Option<String> {
    let min_tail = match strictness {
        SniScanStrictness::Lenient => 9,
        SniScanStrictness::Moderate => 10,
        SniScanStrictness::Strict => 20,
    };
    if i + min_tail >= data.len() {
        return None;
    }

    // Look for SNI extension type marker
    if data[i] != 0x00 || data[i + 1] != 0x00 {
        return None;
    }

    // Sanity check extension length (5-300 bytes is reasonable for SNI)
    let ext_len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
    if !(5..=300).contains(&ext_len) {
        return None;
    }

    let ext_data = match strictness {
        SniScanStrictness::Lenient => &data[i + 4..],
        SniScanStrictness::Moderate => {
            if i + 4 + ext_len <= data.len() {
                &data[i + 4..i + 4 + ext_len]
            } else {
                &data[i + 4..]
            }
        }
        SniScanStrictness::Strict => {
            if i + 4 + ext_len > data.len() {
                return None;
            }
            &data[i + 4..i + 4 + ext_len]
        }
    };

    let header = parse_sni_header(ext_data)?;
    let list_len = header.list_len as usize;

    let header_plausible = match strictness {
        SniScanStrictness::Lenient => list_len <= ext_len,
        SniScanStrictness::Moderate => (3..=256).contains(&list_len),
        SniScanStrictness::Strict => {
            (3..=256).contains(&list_len) && list_len == header.name_len as usize + 3
        }
    };
    if !header_plausible {
        return None;
    }

    parse_sni_extension(ext_data, allow_partial)
}

/// Scan raw data for an SNI extension pattern
/// This works even when full ClientHello parsing fails due to incomplete data
///
/// The `allow_partial` parameter controls whether partial SNI extraction is allowed:
/// - `false`: Only return complete SNI
/// - `true`: Return partial SNI as fallback when full hostname is truncated
pub(super) fn scan_for_sni_extension(
    data: &[u8],
    allow_partial: bool,
    strictness: SniScanStrictness,
) -> Option<String> {
    (0..data.len()).find_map(|i| match_sni_extension_at(data, i, allow_partial, strictness))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::network::dpi::tls_common::test_fixtures::build_sni_extension;

    #[test]
    fn full_client_hello_releases_bytes_only_after_late_metadata_is_parsed() {
        use crate::network::dpi::tls_common::test_fixtures::{RFC9001_CLIENT_HELLO, from_hex};
        use crate::network::types::TlsVersion;
        let hello = from_hex(RFC9001_CLIENT_HELLO);
        let split = hello
            .windows(11)
            .position(|bytes| bytes == b"example.com")
            .unwrap()
            + 11;
        let mut reassembler = CryptoFrameReassembler::new();
        reassembler
            .add_fragment(0, hello[..split].to_vec())
            .unwrap();
        let provisional = try_extract_tls_from_reassembler(&mut reassembler, false).unwrap();
        assert_eq!(provisional.sni.as_deref(), Some("example.com"));
        assert!(provisional.alpn.is_empty());
        assert!(!reassembler.extraction_finished());
        reassembler
            .add_fragment(split as u64, hello[split..].to_vec())
            .unwrap();
        let complete = try_extract_tls_from_reassembler(&mut reassembler, false).unwrap();
        assert_eq!(complete.sni.as_deref(), Some("example.com"));
        assert_eq!(complete.alpn, vec!["alpn"]);
        assert_eq!(complete.version, Some(TlsVersion::Tls13));
        assert!(reassembler.extraction_finished());
        assert!(reassembler.get_fragments().next().is_none());
        reassembler.add_fragment(0, hello).unwrap();
        assert!(reassembler.get_fragments().next().is_none());
        assert_eq!(
            try_extract_tls_from_reassembler(&mut reassembler, false)
                .unwrap()
                .alpn,
            vec!["alpn"]
        );
    }

    #[test]
    fn client_hello_without_sni_finishes_and_releases_bytes() {
        use crate::network::dpi::tls_common::test_fixtures::build_client_hello;
        let hello = build_client_hello(&[0, 16, 0, 5, 0, 3, 2, b'h', b'3']);
        let mut reassembler = CryptoFrameReassembler::new();
        reassembler.add_fragment(0, hello).unwrap();
        let info = try_extract_tls_from_reassembler(&mut reassembler, false).unwrap();
        assert!(info.sni.is_none());
        assert_eq!(info.alpn, vec!["h3"]);
        assert!(reassembler.extraction_finished());
        assert!(reassembler.get_fragments().next().is_none());
    }

    #[test]
    fn oversized_client_hello_stops_at_the_inspection_window() {
        use crate::network::dpi::tls_common::test_fixtures::build_client_hello;
        let mut hello = build_client_hello(&build_sni_extension("example.com"));
        hello[1..4].copy_from_slice(&[1, 0, 1]);
        hello.resize(CryptoFrameReassembler::MAX_BUFFER_SIZE + 10, 0);
        let mut reassembler = CryptoFrameReassembler::new();
        reassembler.add_fragment(0, hello).unwrap();
        let info = try_extract_tls_from_reassembler(&mut reassembler, false).unwrap();
        assert_eq!(info.sni.as_deref(), Some("example.com"));
        assert!(reassembler.extraction_finished());
        assert!(reassembler.get_fragments().next().is_none());
    }

    #[test]
    fn partial_salvage_is_not_cached_as_complete() {
        let mut fragment = build_sni_extension("example.com");
        fragment.truncate(fragment.len() - 3);
        let mut reassembler = CryptoFrameReassembler::new();
        reassembler.add_fragment(10, fragment).unwrap();
        assert!(try_extract_tls_from_reassembler(&mut reassembler, false).is_none());
        let partial = try_extract_tls_from_reassembler(&mut reassembler, true).unwrap();
        assert_eq!(partial.sni.as_deref(), Some("example.[PARTIAL]"));
        assert!(!reassembler.extraction_finished());
        assert!(reassembler.get_cached_tls_info().is_none());
        assert!(reassembler.get_fragments().next().is_some());
    }

    #[test]
    fn test_greedy_sni_extraction_complete() {
        let sni_ext = build_sni_extension("www.example.com");
        // allow_partial doesn't matter when full hostname is available
        let result = scan_for_sni_extension(&sni_ext, false, SniScanStrictness::Lenient);
        assert_eq!(result, Some("www.example.com".to_string()));
    }

    #[test]
    fn test_greedy_sni_extraction_with_prefix() {
        // Add some random bytes before the SNI extension
        let mut data = vec![0x01, 0x02, 0x03, 0x04, 0x05];
        data.extend(build_sni_extension("api.google.com"));
        let result = scan_for_sni_extension(&data, false, SniScanStrictness::Lenient);
        assert_eq!(result, Some("api.google.com".to_string()));
    }

    #[test]
    fn test_greedy_sni_extraction_partial() {
        // Build partial SNI extension (hostname truncated)
        // With fragmented QUIC packets, we need to extract partial SNI
        let mut data = Vec::new();
        data.push(0x00); // ext type
        data.push(0x00);
        data.extend_from_slice(&20u16.to_be_bytes()); // ext_len (full would be 20)
        data.extend_from_slice(&18u16.to_be_bytes()); // list_len
        data.push(0x00); // name type
        data.extend_from_slice(&15u16.to_be_bytes()); // name_len (15 chars)
        data.extend_from_slice(b"www.examp"); // only 9 chars provided

        // With allow_partial=false, returns None
        let result = scan_for_sni_extension(&data, false, SniScanStrictness::Lenient);
        assert_eq!(result, None);

        // With allow_partial=true, returns partial SNI
        let result = scan_for_sni_extension(&data, true, SniScanStrictness::Lenient);
        assert_eq!(result, Some("www.examp[PARTIAL]".to_string()));
    }

    #[test]
    fn test_greedy_extraction_ignores_invalid_patterns() {
        // Data with 0x00 0x00 but invalid SNI structure
        let data = vec![0x00, 0x00, 0x00, 0x01, 0x00]; // ext_len = 1 (too short)
        let result = scan_for_sni_extension(&data, true, SniScanStrictness::Lenient);
        assert_eq!(result, None);
    }

    #[test]
    fn test_greedy_extraction_multiple_zeros() {
        // Data with multiple 0x00 0x00 sequences, only one valid
        let mut data = vec![0x00, 0x00, 0x00, 0x02, 0xFF]; // Invalid SNI
        data.extend(build_sni_extension("valid.example.com"));
        let result = scan_for_sni_extension(&data, false, SniScanStrictness::Lenient);
        assert_eq!(result, Some("valid.example.com".to_string()));
    }
}