use crate::fingerprint::ja4_hash::sha256_first_12;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransportProto {
Tcp,
Quic,
Dtls,
}
impl TransportProto {
#[must_use]
pub const fn ja4_char(self) -> char {
match self {
Self::Tcp => 't',
Self::Quic => 'q',
Self::Dtls => 'd',
}
}
}
const GREASE_VALUES: &[u16] = &[
0x0a0a, 0x1a1a, 0x2a2a, 0x3a3a, 0x4a4a, 0x5a5a, 0x6a6a, 0x7a7a, 0x8a8a, 0x9a9a, 0xaaaa, 0xbaba,
0xcaca, 0xdada, 0xeaea, 0xfafa,
];
fn is_grease(value: u16) -> bool {
GREASE_VALUES.contains(&value)
}
fn tls_version_char(version: u16) -> &'static str {
match version {
0x0304 => "13",
0x0303 => "12",
0x0302 => "11",
0x0301 => "10",
0x0300 => "s3",
0x0200 => "s2",
0xfeff => "d1",
0xfefd => "d2",
0xfefc => "d3",
_ => "00",
}
}
fn effective_tls_version(legacy: u16, supported_versions: &[u16]) -> u16 {
supported_versions
.iter()
.copied()
.find(|version| !is_grease(*version))
.unwrap_or(legacy)
}
fn alpn_part(alpn: &[String]) -> String {
match 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'
}
};
format!(
"{}{}",
safe(*bytes.first().unwrap_or(&0)),
safe(*bytes.last().unwrap_or(&0))
)
}
_ => "00".to_string(),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServerHelloFields {
pub version: u16,
pub supported_versions: Vec<u16>,
pub cipher: u16,
pub extensions: Vec<u16>,
pub alpn: Vec<String>,
pub proto: TransportProto,
}
impl ServerHelloFields {
#[must_use]
pub fn effective_tls_version(&self) -> u16 {
effective_tls_version(self.version, &self.supported_versions)
}
}
#[must_use]
pub fn compute_ja4s(fields: &ServerHelloFields) -> String {
let version = tls_version_char(fields.effective_tls_version());
let ext_count = format!("{:02}", fields.extensions.len().min(99));
let alpn = alpn_part(&fields.alpn);
let part_a = format!(
"{}{}{}{}",
fields.proto.ja4_char(),
version,
ext_count,
alpn
);
let cipher = format!("{:04x}", fields.cipher);
let ext_hash = if fields.extensions.is_empty() {
"000000000000".to_string()
} else {
let mut sorted = fields.extensions.clone();
sorted.sort_unstable();
let input = sorted
.iter()
.map(|extension| format!("{extension:04x}"))
.collect::<Vec<_>>()
.join(",");
sha256_first_12(&input)
};
format!("{part_a}_{cipher}_{ext_hash}")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LatencySide {
Client,
Server,
}
impl LatencySide {
#[must_use]
fn ja4_char(self) -> char {
match self {
Self::Client => 'C',
Self::Server => 'S',
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LatencySample {
pub side: LatencySide,
pub latency_us: u64,
pub ttl: u8,
}
#[must_use]
pub fn compute_ja4l(sample: &LatencySample) -> String {
format!(
"JA4L-{}={}_{}",
sample.side.ja4_char(),
sample.latency_us,
sample.ttl
)
}
#[must_use]
pub fn light_distance_miles(latency_us: u64, propagation_factor: f64) -> f64 {
const SPEED_OF_LIGHT_MILES_PER_US: f64 = 0.128;
(latency_us as f64 * SPEED_OF_LIGHT_MILES_PER_US) / propagation_factor
}
#[must_use]
pub fn light_distance_km(latency_us: u64, propagation_factor: f64) -> f64 {
const SPEED_OF_LIGHT_KM_PER_US: f64 = 0.206;
(latency_us as f64 * SPEED_OF_LIGHT_KM_PER_US) / propagation_factor
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TcpHandshakeRole {
Syn,
SynAck,
Ack,
}
#[must_use]
pub fn compute_ja4l_from_tcp_handshake(
role: TcpHandshakeRole,
latency_us: u64,
ttl: u8,
) -> Option<String> {
let sample = match role {
TcpHandshakeRole::Syn => return None,
TcpHandshakeRole::SynAck => LatencySample {
side: LatencySide::Server,
latency_us: latency_us.max(1),
ttl,
},
TcpHandshakeRole::Ack => LatencySample {
side: LatencySide::Client,
latency_us: latency_us.max(1),
ttl,
},
};
Some(compute_ja4l(&sample))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OidParseError {
oid: String,
}
impl std::fmt::Display for OidParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "invalid OID dotted string: {}", self.oid)
}
}
impl std::error::Error for OidParseError {}
pub fn oid_to_hex(oid: &str) -> Result<String, OidParseError> {
let parts: Vec<u32> = oid
.split('.')
.map(|part| {
part.parse::<u32>().map_err(|_| OidParseError {
oid: oid.to_string(),
})
})
.collect::<Result<_, _>>()?;
if parts.len() < 2 {
return Err(OidParseError {
oid: oid.to_string(),
});
}
let mut bytes: Vec<u32> = Vec::with_capacity(parts.len());
bytes.push(parts[0] * 40 + parts[1]);
for &part in &parts[2..] {
if part < 0x80 {
bytes.push(part);
} else {
let mut value = part;
let mut vlq = Vec::new();
vlq.push(value & 0x7f);
value >>= 7;
while value > 0 {
vlq.push((value & 0x7f) | 0x80);
value >>= 7;
}
vlq.reverse();
bytes.extend(vlq);
}
}
Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CertificateFields {
pub issuer_rdns: Vec<String>,
pub subject_rdns: Vec<String>,
pub extensions: Vec<String>,
}
fn hash_rdn_list(values: &[String]) -> String {
if values.is_empty() {
return "000000000000".to_string();
}
sha256_first_12(&values.join(","))
}
#[must_use]
pub fn compute_ja4x(fields: &CertificateFields) -> String {
format!(
"{}_{}_{}",
hash_rdn_list(&fields.issuer_rdns),
hash_rdn_list(&fields.subject_rdns),
hash_rdn_list(&fields.extensions)
)
}
#[cfg(test)]
#[path = "ja4_family/tests.rs"]
mod tests;