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
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
//! Magic-byte protocol recognizers for the protocols flowscope
//! ships parsers for + the handful of widely-deployed text /
//! framed protocols beyond.
//!
//! Each signature has the shape:
//!
//! ```rust,ignore
//! fn http_request(bytes: &[u8]) -> SignatureMatch;
//! ```
//!
//! and returns one of [`SignatureMatch::Match`] /
//! [`SignatureMatch::NoMatch`] / [`SignatureMatch::NeedMoreData`].
//! Pure functions, no state, no allocation — suitable for
//! hot-path dispatch.
//!
//! Each signature is intentionally strict — multiple
//! discriminator bytes per protocol, false-positive resistant.
//! Wireshark-style: "use strict signatures with multiple
//! confirmation bytes."
//!
//! New in 0.10.0 (plan 113 sub-A).
//!
//! ```
//! use flowscope::detect::signatures::{http_request, SignatureMatch};
//!
//! assert_eq!(http_request(b"GET / HTTP/1.1\r\n"), SignatureMatch::Match);
//! assert_eq!(http_request(b"GET "), SignatureMatch::NeedMoreData);
//! assert_eq!(http_request(b"XYZ"), SignatureMatch::NoMatch);
//! ```

/// Result of a signature evaluation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SignatureMatch {
    /// Bytes definitively match this protocol.
    Match,
    /// Bytes definitively do not match.
    NoMatch,
    /// Not enough bytes to decide — re-check with more. Bytes
    /// seen so far are a valid prefix of a match.
    NeedMoreData,
}

/// Signature function type — `fn(&[u8]) -> SignatureMatch`.
pub type SignatureFn = fn(&[u8]) -> SignatureMatch;

const HTTP_METHODS: &[&[u8]] = &[
    b"GET ",
    b"POST ",
    b"HEAD ",
    b"PUT ",
    b"DELETE ",
    b"OPTIONS ",
    b"PATCH ",
    b"TRACE ",
    b"CONNECT ",
];

/// HTTP/1.x request: method + path + `HTTP/1.` within first 256 B.
pub fn http_request(bytes: &[u8]) -> SignatureMatch {
    if bytes.is_empty() {
        return SignatureMatch::NeedMoreData;
    }
    // If we have at least the longest method header, check whether
    // we start with one. Otherwise, we may still be a valid prefix.
    let prefix_compatible = HTTP_METHODS.iter().any(|m| {
        if bytes.len() >= m.len() {
            bytes.starts_with(m)
        } else {
            m.starts_with(bytes)
        }
    });
    if !prefix_compatible {
        return SignatureMatch::NoMatch;
    }
    // Need at least "GET / HTTP/1.0\r\n" worth of bytes to confirm.
    if bytes.len() < 16 {
        return SignatureMatch::NeedMoreData;
    }
    if !HTTP_METHODS.iter().any(|m| bytes.starts_with(m)) {
        return SignatureMatch::NoMatch;
    }
    let scan_limit = bytes.len().min(256);
    if bytes[..scan_limit].windows(7).any(|w| w == b"HTTP/1.") {
        SignatureMatch::Match
    } else {
        SignatureMatch::NeedMoreData
    }
}

/// HTTP/1.x response: starts with `HTTP/1.` + space + 3-digit code.
pub fn http_response(bytes: &[u8]) -> SignatureMatch {
    if bytes.is_empty() {
        return SignatureMatch::NeedMoreData;
    }
    if bytes.len() < b"HTTP/1.0 200 ".len() {
        if b"HTTP/1.".starts_with(bytes) || bytes.starts_with(b"HTTP/1.") {
            return SignatureMatch::NeedMoreData;
        }
        return SignatureMatch::NoMatch;
    }
    if !bytes.starts_with(b"HTTP/1.") {
        return SignatureMatch::NoMatch;
    }
    if bytes[8] != b' ' {
        return SignatureMatch::NoMatch;
    }
    if !bytes[9..12].iter().all(|c| c.is_ascii_digit()) {
        return SignatureMatch::NoMatch;
    }
    SignatureMatch::Match
}

/// TLS ClientHello: handshake record type 0x16 + valid record
/// version + ClientHello message type 0x01.
pub fn tls_client_hello(bytes: &[u8]) -> SignatureMatch {
    if bytes.is_empty() {
        return SignatureMatch::NeedMoreData;
    }
    if bytes[0] != 0x16 {
        return SignatureMatch::NoMatch;
    }
    if bytes.len() < 6 {
        return SignatureMatch::NeedMoreData;
    }
    let version = u16::from_be_bytes([bytes[1], bytes[2]]);
    if !(0x0301..=0x0303).contains(&version) {
        return SignatureMatch::NoMatch;
    }
    if bytes[5] != 0x01 {
        return SignatureMatch::NoMatch;
    }
    SignatureMatch::Match
}

/// TLS ServerHello: 0x16 handshake type + version + ServerHello
/// message type 0x02.
pub fn tls_server_hello(bytes: &[u8]) -> SignatureMatch {
    if bytes.is_empty() {
        return SignatureMatch::NeedMoreData;
    }
    if bytes[0] != 0x16 {
        return SignatureMatch::NoMatch;
    }
    if bytes.len() < 6 {
        return SignatureMatch::NeedMoreData;
    }
    let version = u16::from_be_bytes([bytes[1], bytes[2]]);
    if !(0x0301..=0x0303).contains(&version) {
        return SignatureMatch::NoMatch;
    }
    if bytes[5] != 0x02 {
        return SignatureMatch::NoMatch;
    }
    SignatureMatch::Match
}

/// SSH banner: `SSH-N.M-…`.
pub fn ssh_banner(bytes: &[u8]) -> SignatureMatch {
    if bytes.is_empty() {
        return SignatureMatch::NeedMoreData;
    }
    if bytes.len() < 4 {
        if !b"SSH-".starts_with(bytes) {
            return SignatureMatch::NoMatch;
        }
        return SignatureMatch::NeedMoreData;
    }
    if !bytes.starts_with(b"SSH-") {
        return SignatureMatch::NoMatch;
    }
    if bytes.len() < 8 {
        return SignatureMatch::NeedMoreData;
    }
    if !(bytes[4].is_ascii_digit() && bytes[5] == b'.') {
        return SignatureMatch::NoMatch;
    }
    SignatureMatch::Match
}

/// DNS message: 12-byte header with QDCOUNT > 0 and reasonable
/// flags.
pub fn dns_message(bytes: &[u8]) -> SignatureMatch {
    if bytes.len() < 12 {
        return SignatureMatch::NeedMoreData;
    }
    // Flags byte 2 has opcode in bits 3-6 (mask 0x78). Opcodes
    // 0 (QUERY), 1 (IQUERY), 2 (STATUS), 4 (NOTIFY), 5 (UPDATE) are
    // valid; everything else is invalid.
    let opcode = (bytes[2] >> 3) & 0x0f;
    if !matches!(opcode, 0 | 1 | 2 | 4 | 5) {
        return SignatureMatch::NoMatch;
    }
    let qdcount = u16::from_be_bytes([bytes[4], bytes[5]]);
    if qdcount == 0 || qdcount > 16 {
        return SignatureMatch::NoMatch;
    }
    SignatureMatch::Match
}

/// SMTP banner: `220 ` (greeting) or `220-` (multi-line).
pub fn smtp_banner(bytes: &[u8]) -> SignatureMatch {
    if bytes.is_empty() {
        return SignatureMatch::NeedMoreData;
    }
    if bytes.len() < 4 {
        if b"220 ".starts_with(bytes) || b"220-".starts_with(bytes) {
            return SignatureMatch::NeedMoreData;
        }
        return SignatureMatch::NoMatch;
    }
    if bytes.starts_with(b"220 ") || bytes.starts_with(b"220-") {
        SignatureMatch::Match
    } else {
        SignatureMatch::NoMatch
    }
}

/// FTP banner: `220 ` / `220-` (control channel greeting).
pub fn ftp_banner(bytes: &[u8]) -> SignatureMatch {
    smtp_banner(bytes)
}

/// IRC message: starts with `NICK`, `USER`, `PASS`, or `:server`
/// prefix.
pub fn irc_message(bytes: &[u8]) -> SignatureMatch {
    if bytes.is_empty() {
        return SignatureMatch::NeedMoreData;
    }
    const STARTS: &[&[u8]] = &[b"NICK ", b"USER ", b"PASS ", b":"];
    let compatible = STARTS.iter().any(|s| {
        if bytes.len() >= s.len() {
            bytes.starts_with(s)
        } else {
            s.starts_with(bytes)
        }
    });
    if !compatible {
        return SignatureMatch::NoMatch;
    }
    if bytes.len() < 5 {
        return SignatureMatch::NeedMoreData;
    }
    if STARTS.iter().any(|s| bytes.starts_with(s)) {
        SignatureMatch::Match
    } else {
        SignatureMatch::NoMatch
    }
}

/// Redis RESP: starts with `+`, `-`, `:`, `$`, or `*`. Strict —
/// reject empty or non-RESP first byte.
pub fn redis_resp(bytes: &[u8]) -> SignatureMatch {
    if bytes.is_empty() {
        return SignatureMatch::NeedMoreData;
    }
    if matches!(bytes[0], b'+' | b'-' | b':' | b'$' | b'*') {
        if bytes.len() < 4 {
            // Need a CRLF or close to it to commit.
            return SignatureMatch::NeedMoreData;
        }
        // For the framing types ($ *), the next bytes should
        // describe a length: digits + optionally `-`.
        if matches!(bytes[0], b'$' | b'*') && !bytes[1].is_ascii_digit() && bytes[1] != b'-' {
            return SignatureMatch::NoMatch;
        }
        return SignatureMatch::Match;
    }
    SignatureMatch::NoMatch
}

/// MQTT CONNECT: first byte 0x10 (CONNECT control packet) and
/// protocol name `MQTT` or `MQIsdp` in the variable header.
pub fn mqtt_connect(bytes: &[u8]) -> SignatureMatch {
    if bytes.is_empty() {
        return SignatureMatch::NeedMoreData;
    }
    // First byte: 0x10 (CONNECT, flags zero).
    if bytes[0] != 0x10 {
        return SignatureMatch::NoMatch;
    }
    // Need: 1B type + 1-4B remaining length + 2B name len + 4-6B name.
    if bytes.len() < 12 {
        return SignatureMatch::NeedMoreData;
    }
    // Scan for "MQTT" or "MQIsdp" within first 20 bytes.
    let scan_limit = bytes.len().min(20);
    let has_mqtt = bytes[..scan_limit].windows(4).any(|w| w == b"MQTT");
    let has_legacy = bytes[..scan_limit].windows(6).any(|w| w == b"MQIsdp");
    if has_mqtt || has_legacy {
        SignatureMatch::Match
    } else {
        SignatureMatch::NoMatch
    }
}

/// Postgres startup message: first 4 bytes encode the message
/// length (≥ 8 ≤ 10_000), next 4 bytes encode protocol version
/// 3.0 = 0x00030000.
pub fn postgres_startup(bytes: &[u8]) -> SignatureMatch {
    if bytes.len() < 8 {
        return SignatureMatch::NeedMoreData;
    }
    let len = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
    if !(8..=10_000).contains(&len) {
        return SignatureMatch::NoMatch;
    }
    let version = u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
    // Protocol 3.0 (most common) or SSLRequest (80877103).
    if version == 0x0003_0000 || version == 80877103 {
        SignatureMatch::Match
    } else {
        SignatureMatch::NoMatch
    }
}

/// Curated `(parser_kind, signature)` table.
///
/// `parser_kind` strings align with the [`ParserKind`](crate::ParserKind)
/// slug vocabulary where applicable so signature matches dispatch
/// back to the existing parsers.
pub fn registry() -> impl Iterator<Item = (&'static str, SignatureFn)> {
    [
        ("http", http_request as SignatureFn),
        ("tls", tls_client_hello as SignatureFn),
        ("dns-udp", dns_message as SignatureFn),
        ("ssh", ssh_banner as SignatureFn),
        ("smtp", smtp_banner as SignatureFn),
        ("ftp", ftp_banner as SignatureFn),
        ("irc", irc_message as SignatureFn),
        ("redis-resp", redis_resp as SignatureFn),
        ("mqtt", mqtt_connect as SignatureFn),
        ("postgres", postgres_startup as SignatureFn),
    ]
    .into_iter()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn assert_table(sig: SignatureFn, examples: &[(&[u8], SignatureMatch)]) {
        for (bytes, expected) in examples {
            assert_eq!(
                sig(bytes),
                *expected,
                "{} expected {:?}",
                String::from_utf8_lossy(bytes),
                expected,
            );
        }
    }

    #[test]
    fn http_request_signature() {
        assert_table(
            http_request,
            &[
                (b"GET / HTTP/1.1\r\n", SignatureMatch::Match),
                (b"POST /a HTTP/1.0\r\n", SignatureMatch::Match),
                (b"GET ", SignatureMatch::NeedMoreData),
                (b"GE", SignatureMatch::NeedMoreData),
                (b"XYZ", SignatureMatch::NoMatch),
                (&[0x16, 0x03, 0x01], SignatureMatch::NoMatch),
                (b"GET /index.html ", SignatureMatch::NeedMoreData),
            ],
        );
    }

    #[test]
    fn http_response_signature() {
        assert_table(
            http_response,
            &[
                (b"HTTP/1.1 200 OK\r\n", SignatureMatch::Match),
                (b"HTTP/1.0 404 Not Found\r\n", SignatureMatch::Match),
                (b"HTTP/1.", SignatureMatch::NeedMoreData),
                (b"GET / HTTP/1.1", SignatureMatch::NoMatch),
            ],
        );
    }

    #[test]
    fn tls_client_hello_signature() {
        assert_table(
            tls_client_hello,
            &[
                (&[0x16, 0x03, 0x01, 0x00, 0x42, 0x01], SignatureMatch::Match),
                (&[0x16, 0x03, 0x03, 0x00, 0x42, 0x01], SignatureMatch::Match),
                (
                    &[0x16, 0x03, 0x04, 0x00, 0x42, 0x01],
                    SignatureMatch::NoMatch,
                ),
                (
                    &[0x17, 0x03, 0x01, 0x00, 0x42, 0x01],
                    SignatureMatch::NoMatch,
                ),
                (&[0x16, 0x03], SignatureMatch::NeedMoreData),
                (b"GET / HTTP/1.1", SignatureMatch::NoMatch),
            ],
        );
    }

    #[test]
    fn tls_server_hello_signature() {
        assert_table(
            tls_server_hello,
            &[(&[0x16, 0x03, 0x03, 0x00, 0x42, 0x02], SignatureMatch::Match)],
        );
        // ClientHello bytes are rejected.
        assert_eq!(
            tls_server_hello(&[0x16, 0x03, 0x03, 0x00, 0x42, 0x01]),
            SignatureMatch::NoMatch
        );
    }

    #[test]
    fn ssh_banner_signature() {
        assert_table(
            ssh_banner,
            &[
                (b"SSH-2.0-OpenSSH_8.0\r\n", SignatureMatch::Match),
                (b"SSH-1.99-foo", SignatureMatch::Match),
                (b"SSH-", SignatureMatch::NeedMoreData),
                (b"SS", SignatureMatch::NeedMoreData),
                (b"FOO", SignatureMatch::NoMatch),
            ],
        );
    }

    #[test]
    fn dns_message_signature() {
        // Header: id=1234, flags=0x0100 (recursion desired), qdcount=1, ancount=0, nscount=0, arcount=0.
        let bytes = [
            0x04, 0xd2, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        assert_eq!(dns_message(&bytes), SignatureMatch::Match);
        // Too short.
        assert_eq!(dns_message(&bytes[..8]), SignatureMatch::NeedMoreData);
        // Bad opcode (15 = invalid).
        let mut bad = bytes;
        bad[2] = 0x78; // opcode = 15
        assert_eq!(dns_message(&bad), SignatureMatch::NoMatch);
    }

    #[test]
    fn smtp_banner_signature() {
        assert_table(
            smtp_banner,
            &[
                (b"220 smtp.example.com ESMTP\r\n", SignatureMatch::Match),
                (b"220-multi\r\n", SignatureMatch::Match),
                (b"220", SignatureMatch::NeedMoreData),
                (b"HELO foo", SignatureMatch::NoMatch),
            ],
        );
    }

    #[test]
    fn irc_message_signature() {
        assert_table(
            irc_message,
            &[
                (b"NICK foo\r\n", SignatureMatch::Match),
                (b"USER me\r\n", SignatureMatch::Match),
                (b":server PING\r\n", SignatureMatch::Match),
                (b"NICK", SignatureMatch::NeedMoreData),
                (b"XXX", SignatureMatch::NoMatch),
            ],
        );
    }

    #[test]
    fn redis_resp_signature() {
        assert_table(
            redis_resp,
            &[
                (b"+OK\r\n", SignatureMatch::Match),
                (b"-ERR foo\r\n", SignatureMatch::Match),
                (b":1234\r\n", SignatureMatch::Match),
                (b"$5\r\nhello\r\n", SignatureMatch::Match),
                (b"*3\r\n", SignatureMatch::Match),
                (b"$X\r\n", SignatureMatch::NoMatch),
                (b"+", SignatureMatch::NeedMoreData),
                (b"X", SignatureMatch::NoMatch),
            ],
        );
    }

    #[test]
    fn mqtt_connect_signature() {
        // 0x10 + remaining length 14 + 4-byte name "MQTT".
        let bytes = [
            0x10, 0x0E, 0x00, 0x04, b'M', b'Q', b'T', b'T', 0x04, 0x02, 0x00, 0x3C, 0x00, 0x00,
        ];
        assert_eq!(mqtt_connect(&bytes), SignatureMatch::Match);
        // Non-CONNECT type byte.
        assert_eq!(mqtt_connect(&[0x20, 0x0E][..]), SignatureMatch::NoMatch);
        // Too short.
        assert_eq!(mqtt_connect(&[0x10][..]), SignatureMatch::NeedMoreData);
    }

    #[test]
    fn postgres_startup_signature() {
        // Length 16 + version 3.0 + dummy 8 bytes user.
        let mut bytes = vec![];
        bytes.extend_from_slice(&16u32.to_be_bytes());
        bytes.extend_from_slice(&0x0003_0000u32.to_be_bytes());
        bytes.extend_from_slice(b"user");
        assert_eq!(postgres_startup(&bytes), SignatureMatch::Match);
        // SSLRequest.
        let ssl = {
            let mut v = vec![];
            v.extend_from_slice(&8u32.to_be_bytes());
            v.extend_from_slice(&80877103u32.to_be_bytes());
            v
        };
        assert_eq!(postgres_startup(&ssl), SignatureMatch::Match);
        // Bad length.
        let bad = vec![0u8; 8];
        assert_eq!(postgres_startup(&bad), SignatureMatch::NoMatch);
    }

    #[test]
    fn registry_lists_ten_signatures() {
        let count = registry().count();
        assert_eq!(count, 10);
    }

    #[test]
    fn splitting_invariance_http_request() {
        let bytes = b"GET /index.html HTTP/1.1\r\nHost: example.com\r\n\r\n";
        for end in 1..=bytes.len() {
            let prefix = &bytes[..end];
            let result = http_request(prefix);
            assert_ne!(
                result,
                SignatureMatch::NoMatch,
                "prefix len {end} returned NoMatch unexpectedly: {prefix:?}",
            );
        }
    }

    #[test]
    fn splitting_invariance_tls_client_hello() {
        let bytes = [0x16, 0x03, 0x03, 0x00, 0x42, 0x01, 0x00, 0x00, 0x42];
        for end in 1..=bytes.len() {
            let prefix = &bytes[..end];
            let result = tls_client_hello(prefix);
            assert_ne!(
                result,
                SignatureMatch::NoMatch,
                "prefix len {end} returned NoMatch unexpectedly",
            );
        }
    }
}