mod hash;
pub(crate) use hash::{md5_string, sha256_first_12};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientHelloFields {
pub version: u16,
pub cipher_suites: Vec<u16>,
pub extensions: Vec<u16>,
pub supported_groups: Vec<u16>,
pub ec_point_formats: Vec<u8>,
pub alpn: Vec<String>,
pub signature_algorithms: Vec<u16>,
}
impl ClientHelloFields {
#[must_use]
pub fn with_alpn(mut self, alpn: Vec<String>) -> Self {
self.alpn = alpn;
self
}
#[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,
];
#[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
)
}
#[must_use]
pub fn compute_ja3_hash(fields: &ClientHelloFields) -> String {
let canonical = compute_ja3(fields);
md5_string(&canonical)
}
#[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}")
}
#[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(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JA3VerificationOutcome {
Match {
canonical: String,
},
Drift {
actual: String,
expected: String,
},
}
impl JA3VerificationOutcome {
#[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}");
}
}
}