guise 0.1.2

Canonical browser fingerprint bundles, human-behavior timing, and TLS profile re-exports for the Santh fleet
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
//! JA3 and JA4 fingerprint computation for captured TLS ClientHello fields.
//!
//! The functions here are pure transforms over already-extracted handshake
//! fields. They do not open sockets, parse packets, or emit TLS handshakes.

mod hash;

pub(crate) use hash::{md5_string, sha256_first_12};

/// One TLS ClientHello, broken into the fields used by JA3 and JA4.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientHelloFields {
    /// TLS legacy protocol version encoded in the ClientHello.
    pub version: u16,
    /// Cipher suites offered by the client, in client-preferred order.
    pub cipher_suites: Vec<u16>,
    /// Extension type ids offered by the client, in wire order.
    pub extensions: Vec<u16>,
    /// Supported elliptic-curve groups.
    pub supported_groups: Vec<u16>,
    /// EC point formats.
    pub ec_point_formats: Vec<u8>,
    /// ALPN protocols, in client-preferred order.
    pub alpn: Vec<String>,
    /// Signature algorithm ids, in client-offered order.
    pub signature_algorithms: Vec<u16>,
}

impl ClientHelloFields {
    /// Return a copy of this ClientHello shape with `alpn` populated.
    #[must_use]
    pub fn with_alpn(mut self, alpn: Vec<String>) -> Self {
        self.alpn = alpn;
        self
    }

    /// Return a copy of this ClientHello shape with `algs` populated.
    #[must_use]
    pub fn with_signature_algorithms(mut self, algs: Vec<u16>) -> Self {
        self.signature_algorithms = algs;
        self
    }
}

const GREASE_VALUES: [u16; 16] = [
    0x0a0a, 0x1a1a, 0x2a2a, 0x3a3a, 0x4a4a, 0x5a5a, 0x6a6a, 0x7a7a, 0x8a8a, 0x9a9a, 0xaaaa, 0xbaba,
    0xcaca, 0xdada, 0xeaea, 0xfafa,
];

/// Compute the canonical JA3 string from ClientHello fields.
///
/// JA3 uses `version,cipher_suites,extensions,supported_groups,ec_point_formats`
/// with dash-joined numeric lists. GREASE values are stripped from all `u16`
/// lists before rendering.
#[must_use]
pub fn compute_ja3(fields: &ClientHelloFields) -> String {
    let cipher = join_u16_dash(&fields.cipher_suites);
    let ext = join_u16_dash(&fields.extensions);
    let groups = join_u16_dash(&fields.supported_groups);
    let formats = join_u8_dash(&fields.ec_point_formats);
    format!(
        "{},{},{},{},{}",
        fields.version, cipher, ext, groups, formats
    )
}

/// Compute the MD5 hash of the canonical JA3 string.
#[must_use]
pub fn compute_ja3_hash(fields: &ClientHelloFields) -> String {
    let canonical = compute_ja3(fields);
    md5_string(&canonical)
}

/// Compute a JA4 string for a TCP TLS ClientHello.
///
/// The implementation follows FoxIO JA4 shape:
/// `<proto><ver><sni><nciphers><nexts><alpn>_<cipherhash12>_<exthash12>`.
/// Cipher and extension hash inputs are GREASE-stripped, hex-rendered, and
/// sorted as required by the JA4 spec. Signature algorithms are appended to the
/// extension hash input in client-offered order.
#[must_use]
pub fn compute_ja4(fields: &ClientHelloFields) -> String {
    let tls_version = match fields.version {
        769 => "10",
        770 => "11",
        771 => "12",
        772 => "13",
        _ => "00",
    };

    let alpn_field = match fields.alpn.first() {
        Some(value) if !value.is_empty() => {
            let bytes = value.as_bytes();
            let safe = |byte: u8| -> char {
                let candidate = byte as char;
                if candidate.is_ascii_alphanumeric() {
                    candidate
                } else {
                    '0'
                }
            };
            let first = safe(bytes.first().copied().unwrap_or(b'0'));
            let last = safe(bytes.last().copied().unwrap_or(b'0'));
            format!("{first}{last}")
        }
        _ => "00".to_string(),
    };

    let cipher_filtered: Vec<u16> = fields
        .cipher_suites
        .iter()
        .copied()
        .filter(|cipher| !is_grease(*cipher))
        .collect();
    let ext_filtered: Vec<u16> = fields
        .extensions
        .iter()
        .copied()
        .filter(|extension| !is_grease(*extension))
        .filter(|extension| *extension != 0x0000 && *extension != 0x0010)
        .collect();
    let cipher_count = format!("{:02}", cipher_filtered.len().min(99));
    let ext_count = format!("{:02}", ext_filtered.len().min(99));

    let mut sorted_ciphers = cipher_filtered.clone();
    sorted_ciphers.sort_unstable();
    let cipher_hash_input = sorted_ciphers
        .iter()
        .map(|cipher| format!("{cipher:04x}"))
        .collect::<Vec<_>>()
        .join(",");
    let cipher_hash = sha256_first_12(&cipher_hash_input);

    let mut sorted_exts = ext_filtered.clone();
    sorted_exts.sort_unstable();
    let ext_hex = sorted_exts
        .iter()
        .map(|extension| format!("{extension:04x}"))
        .collect::<Vec<_>>()
        .join(",");
    let sigalg_hex = fields
        .signature_algorithms
        .iter()
        .map(|algorithm| format!("{algorithm:04x}"))
        .collect::<Vec<_>>()
        .join(",");
    let ext_hash_input = if sigalg_hex.is_empty() {
        ext_hex
    } else {
        format!("{ext_hex}_{sigalg_hex}")
    };
    let ext_hash = sha256_first_12(&ext_hash_input);

    let sni = "d";

    format!("t{tls_version}{sni}{cipher_count}{ext_count}{alpn_field}_{cipher_hash}_{ext_hash}")
}

/// Verify a captured ClientHello against a target JA3 string.
#[must_use]
pub fn verify_against_target(
    actual: &ClientHelloFields,
    target_ja3: &str,
) -> JA3VerificationOutcome {
    let actual_ja3 = compute_ja3(actual);
    if actual_ja3 == target_ja3 {
        JA3VerificationOutcome::Match {
            canonical: actual_ja3,
        }
    } else {
        JA3VerificationOutcome::Drift {
            actual: actual_ja3,
            expected: target_ja3.to_string(),
        }
    }
}

/// Result of comparing an actual ClientHello against a target JA3.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JA3VerificationOutcome {
    /// The actual ClientHello rendered to the expected canonical JA3 string.
    Match {
        /// Actual canonical JA3 string.
        canonical: String,
    },
    /// The actual ClientHello rendered to a different canonical JA3 string.
    Drift {
        /// Actual canonical JA3 string.
        actual: String,
        /// Expected canonical JA3 string.
        expected: String,
    },
}

impl JA3VerificationOutcome {
    /// Return true when this comparison is a match.
    #[must_use]
    pub fn is_match(&self) -> bool {
        matches!(self, JA3VerificationOutcome::Match { .. })
    }
}

fn join_u16_dash(values: &[u16]) -> String {
    values
        .iter()
        .copied()
        .filter(|value| !is_grease(*value))
        .map(|value| value.to_string())
        .collect::<Vec<_>>()
        .join("-")
}

fn join_u8_dash(values: &[u8]) -> String {
    values
        .iter()
        .map(|value| value.to_string())
        .collect::<Vec<_>>()
        .join("-")
}

fn is_grease(value: u16) -> bool {
    GREASE_VALUES.contains(&value)
}

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

    fn chrome_130_fields() -> ClientHelloFields {
        ClientHelloFields {
            version: 771,
            cipher_suites: vec![
                4865, 4866, 4867, 49195, 49199, 49196, 49200, 52393, 52392, 49171, 49172, 156, 157,
                47, 53,
            ],
            extensions: vec![
                0, 23, 65281, 10, 11, 35, 16, 5, 13, 18, 51, 45, 43, 27, 17513, 21,
            ],
            supported_groups: vec![29, 23, 24],
            ec_point_formats: vec![0],
            alpn: vec!["h2".to_string(), "http/1.1".to_string()],
            signature_algorithms: vec![0x0403, 0x0804, 0x0401],
        }
    }

    #[test]
    fn compute_ja3_returns_canonical_format() {
        let fields = chrome_130_fields();
        let ja3 = compute_ja3(&fields);
        let parts: Vec<&str> = ja3.split(',').collect();
        assert_eq!(parts.len(), 5);
        assert_eq!(parts[0], "771");
        assert!(parts[1].contains("4865"));
        assert!(parts[2].contains("65281"));
        assert!(parts[3].contains("29"));
        assert_eq!(parts[4], "0");
    }

    #[test]
    fn compute_ja3_strips_grease_values() {
        let mut fields = chrome_130_fields();
        fields.cipher_suites.insert(0, 0x0a0a);
        fields.cipher_suites.push(0x1a1a);
        fields.extensions.insert(0, 0x2a2a);
        let ja3 = compute_ja3(&fields);
        assert!(!ja3.contains("0a0a"), "GREASE 0a0a should be stripped");
        assert!(!ja3.contains("2a2a"), "GREASE 2a2a should be stripped");
        assert!(
            !ja3.contains("2570"),
            "GREASE 0x0a0a decimal form should be stripped"
        );
    }

    #[test]
    fn compute_ja3_hash_is_md5_of_canonical() {
        let fields = ClientHelloFields {
            version: 771,
            cipher_suites: vec![],
            extensions: vec![],
            supported_groups: vec![],
            ec_point_formats: vec![],
            alpn: vec![],
            signature_algorithms: vec![],
        };
        let canonical = compute_ja3(&fields);
        assert_eq!(canonical, "771,,,,");
        let via_path = compute_ja3_hash(&fields);
        let via_oracle = md5_string(&canonical);
        assert_eq!(via_path, via_oracle);
        assert_eq!(via_path.len(), 32);
        assert!(via_path.chars().all(|char| char.is_ascii_hexdigit()));
    }

    #[test]
    fn ja3_hash_changes_when_cipher_order_changes() {
        let first = ClientHelloFields {
            version: 771,
            cipher_suites: vec![4865, 4866],
            extensions: vec![0],
            supported_groups: vec![29],
            ec_point_formats: vec![0],
            alpn: vec![],
            signature_algorithms: vec![],
        };
        let second = ClientHelloFields {
            version: 771,
            cipher_suites: vec![4866, 4865],
            extensions: vec![0],
            supported_groups: vec![29],
            ec_point_formats: vec![0],
            alpn: vec![],
            signature_algorithms: vec![],
        };
        assert_ne!(compute_ja3_hash(&first), compute_ja3_hash(&second));
    }

    #[test]
    fn verify_against_target_returns_match_when_canonical_string_equals() {
        let fields = chrome_130_fields();
        let target = compute_ja3(&fields);
        let outcome = verify_against_target(&fields, &target);
        assert!(outcome.is_match());
    }

    #[test]
    fn verify_against_target_returns_drift_with_both_strings() {
        let fields = chrome_130_fields();
        let outcome = verify_against_target(&fields, "771,4865,,,0");
        match outcome {
            JA3VerificationOutcome::Drift { actual, expected } => {
                assert_eq!(expected, "771,4865,,,0");
                assert!(actual.starts_with("771,"));
            }
            JA3VerificationOutcome::Match { .. } => panic!("expected Drift"),
        }
    }

    #[test]
    fn ja4_format_starts_with_t12_for_legacy_tls_version_771() {
        let fields = chrome_130_fields();
        let ja4 = compute_ja4(&fields);
        assert!(
            ja4.starts_with("t12d"),
            "JA4 must start with t12d, got {ja4}"
        );
    }

    #[test]
    fn ja4_filters_grease_from_cipher_count() {
        let mut fields = chrome_130_fields();
        let baseline = compute_ja4(&fields);
        fields.cipher_suites.insert(0, 0x0a0a);
        fields.cipher_suites.push(0x1a1a);
        let with_grease = compute_ja4(&fields);
        assert_eq!(baseline, with_grease);
    }

    #[test]
    fn is_grease_recognises_all_sixteen_grease_values() {
        for value in GREASE_VALUES {
            assert!(is_grease(value));
        }
        assert!(!is_grease(4865));
        assert!(!is_grease(0));
        assert!(!is_grease(0x0a0b));
    }

    #[test]
    fn md5_string_matches_known_oracle_for_empty_input() {
        assert_eq!(md5_string(""), "d41d8cd98f00b204e9800998ecf8427e");
    }

    #[test]
    fn md5_string_matches_known_oracle_for_short_input() {
        assert_eq!(md5_string("a"), "0cc175b9c0f1b6a831c399e269772661");
        assert_eq!(md5_string("abc"), "900150983cd24fb0d6963f7d28e17f72");
        assert_eq!(
            md5_string("message digest"),
            "f96b697d7cb7938d525a2f31aaf161d0"
        );
    }

    proptest::proptest! {
        #[test]
        fn compute_ja3_never_panics(
            version in proptest::prelude::any::<u16>(),
            ciphers in proptest::collection::vec(proptest::prelude::any::<u16>(), 0..40),
            extensions in proptest::collection::vec(proptest::prelude::any::<u16>(), 0..40),
            groups in proptest::collection::vec(proptest::prelude::any::<u16>(), 0..20),
            point_formats in proptest::collection::vec(proptest::prelude::any::<u8>(), 0..6),
        ) {
            let fields = ClientHelloFields {
                version,
                cipher_suites: ciphers,
                extensions,
                supported_groups: groups,
                ec_point_formats: point_formats,
                alpn: vec![],
                signature_algorithms: vec![],
            };
            let canonical = compute_ja3(&fields);
            let hash = compute_ja3_hash(&fields);
            proptest::prop_assert_eq!(hash.len(), 32);
            proptest::prop_assert!(hash.chars().all(|char| char.is_ascii_hexdigit()));
            proptest::prop_assert_eq!(canonical.split(',').count(), 5);
        }

        #[test]
        fn compute_ja4_never_panics(
            version in proptest::prelude::any::<u16>(),
            ciphers in proptest::collection::vec(proptest::prelude::any::<u16>(), 0..40),
            extensions in proptest::collection::vec(proptest::prelude::any::<u16>(), 0..40),
            sigalgs in proptest::collection::vec(proptest::prelude::any::<u16>(), 0..16),
            alpn_strs in proptest::collection::vec("[a-zA-Z0-9./_-]{0,16}", 0..4),
        ) {
            let fields = ClientHelloFields {
                version,
                cipher_suites: ciphers,
                extensions,
                supported_groups: vec![],
                ec_point_formats: vec![],
                alpn: alpn_strs,
                signature_algorithms: sigalgs,
            };
            let ja4 = compute_ja4(&fields);
            proptest::prop_assert!(ja4.starts_with('t'),
                "JA4 must start with transport char 't': {ja4}");
            proptest::prop_assert_eq!(ja4.matches('_').count(), 2);
        }

        #[test]
        fn ja4_unknown_version_does_not_collide_with_tls13(
            ciphers in proptest::collection::vec(proptest::prelude::any::<u16>(), 0..20),
        ) {
            let fields = ClientHelloFields {
                version: 0xABCD,
                cipher_suites: ciphers,
                extensions: vec![],
                supported_groups: vec![],
                ec_point_formats: vec![],
                alpn: vec![],
                signature_algorithms: vec![],
            };
            let ja4 = compute_ja4(&fields);
            proptest::prop_assert!(ja4.starts_with("t00"),
                "unknown TLS version must emit t00 sentinel: {ja4}");
        }
    }
}