1#![allow(missing_docs)]
15#![allow(clippy::extra_unused_lifetimes)]
16#![allow(clippy::enum_variant_names)]
17#![allow(clippy::struct_field_names)]
18#![allow(clippy::vec_init_then_push)]
19#![allow(clippy::useless_vec)]
20
21use sha2::{Digest, Sha256};
22
23pub enum Protocol {
24 Tls = 0,
25 Quic = 1,
26 Dtls = 2,
27}
28
29pub enum Sni {
30 Domain,
31 Ip,
32}
33
34fn alpn_char(b: u8) -> String {
36 if b.is_ascii_alphanumeric() {
37 (b as char).to_string()
38 } else {
39 format!("{b:02x}")
40 }
41}
42
43fn alpn_first_last(protocol: &[u8]) -> (String, String) {
46 let first = protocol
47 .first()
48 .map_or_else(|| "0".to_string(), |&b| alpn_char(b));
49 let last = if protocol.len() > 1 {
50 protocol
51 .last()
52 .map_or_else(|| "0".to_string(), |&b| alpn_char(b))
53 } else {
54 "0".to_string()
55 };
56 (first, last)
57}
58
59fn protocol_marker(_is_quic: bool) -> char {
61 't' }
63
64fn hash12(input: &str) -> String {
66 let hash = Sha256::digest(input.as_bytes());
67 hex::encode(&hash[..6])
68}
69
70fn format_id_list(ids: &[u16]) -> String {
72 use std::fmt::Write;
73 let mut result = String::new();
74 for (i, id) in ids.iter().enumerate() {
75 if i > 0 {
76 result.push(',');
77 }
78 let _ = write!(result, "{id:04x}");
79 }
80 result
81}
82
83#[allow(dead_code)]
84pub struct Ja4 {
85 pub ja4: String,
86 record_type: u8,
87 protocol_version: u16,
88 record_len: u16,
89 handshake_message_type: u8,
90 handshake_message_len: u32,
91 client_version: u16,
92 client_random: [u8; 32],
93 session_id: Vec<u8>,
94 cipher_suites: Vec<u16>,
95 compression_methods: Vec<u8>,
96 extensions: Vec<Extension>,
97 protocol: Protocol,
98}
99
100#[derive(Debug)]
101pub enum Error {
102 InvalidClientHelloRecordType,
103 InvalidClientHelloLength,
104 InvalidClientHelloRecordLength,
105 InvalidClientHelloHandshakeMessageType,
106 InvalidClientHelloHandshakeMessageLength,
107 InvalidClientHelloClientRandom,
108 InvalidEcPointFormatsExtensionBufferLength,
109 InvalidEcPointFormatsExtensionLength,
110 InvalidAlpnExtensionBufferLength,
111 InvalidAlpnExtensionLength,
112 InvalidSupportedGroupsExtensionBufferLength,
113 InvalidSupportedGroupsExtensionLength,
114 InvalidSignatureAlgorithmsExtensionBufferLength,
115 InvalidSignatureAlgorithmsExtensionLength,
116 InvalidServerNameExtensionBufferLength,
117 InvalidServerNameExtensionLength,
118 InvalidServerNameExtensionName,
119}
120
121const RECORD_HEADER_LENGTH: usize = 5;
122const HANDSHAKE_HEADER_LENGTH: usize = 4;
123const HANDSHAKE_RECORD_TYPE: u8 = 0x16;
124const HANDSHAKE_MESSAGE_TYPE: u8 = 0x01;
125
126impl Default for Ja4 {
127 fn default() -> Self {
128 Self {
129 ja4: String::new(),
130 record_type: 0,
131 protocol_version: 0,
132 record_len: 0,
133 handshake_message_type: 0,
134 handshake_message_len: 0,
135 client_version: 0,
136 client_random: [0; 32],
137 session_id: Vec::new(),
138 cipher_suites: Vec::new(),
139 compression_methods: Vec::new(),
140 extensions: Vec::new(),
141 protocol: Protocol::Tls,
142 }
143 }
144}
145
146impl Ja4 {
147 pub fn from_client_hello(mut data: &[u8]) -> Result<Self, Error> {
148 let protocol = Protocol::Tls; if data.len() < RECORD_HEADER_LENGTH + HANDSHAKE_HEADER_LENGTH {
158 return Err(Error::InvalidClientHelloLength);
159 }
160
161 let record_type = data[0];
162 if record_type != HANDSHAKE_RECORD_TYPE {
163 return Err(Error::InvalidClientHelloRecordType);
164 }
165 let protocol_version = u16::from_be_bytes([data[1], data[2]]);
166 let record_len = u16::from_be_bytes([data[3], data[4]]);
167 data = &data[RECORD_HEADER_LENGTH..];
168
169 if data.len() < record_len as usize {
170 return Err(Error::InvalidClientHelloRecordLength);
171 }
172
173 let handshake_message_type = data[0];
174 if handshake_message_type != HANDSHAKE_MESSAGE_TYPE {
175 return Err(Error::InvalidClientHelloHandshakeMessageType);
176 }
177 let handshake_message_len = u32::from_be_bytes([0, data[1], data[2], data[3]]);
178 data = &data[HANDSHAKE_HEADER_LENGTH..];
179
180 if data.len() < handshake_message_len as usize {
181 return Err(Error::InvalidClientHelloHandshakeMessageLength);
182 }
183
184 if data.len() < 2 + 32 + 1 {
187 return Err(Error::InvalidClientHelloLength);
188 }
189
190 let mut client_version = u16::from_be_bytes([data[0], data[1]]);
191 data = &data[2..];
192
193 let client_random: [u8; 32] = data[0..32]
194 .try_into()
195 .map_err(|_| Error::InvalidClientHelloClientRandom)?;
196 data = &data[32..];
197
198 let session_id_len = data[0] as usize;
199 data = &data[1..];
200
201 if data.len() < session_id_len {
202 return Err(Error::InvalidClientHelloLength);
203 }
204 let session_id: Vec<u8> = data[0..session_id_len].to_vec();
205 data = &data[session_id_len..];
206
207 if data.len() < 2 {
208 return Err(Error::InvalidClientHelloLength);
209 }
210 let cipher_suites_len = u16::from_be_bytes([data[0], data[1]]) as usize;
211 data = &data[2..];
212
213 if data.len() < cipher_suites_len {
214 return Err(Error::InvalidClientHelloLength);
215 }
216 if !cipher_suites_len.is_multiple_of(2) {
219 return Err(Error::InvalidClientHelloLength);
220 }
221
222 let mut cipher_suites = Vec::new();
224 for i in (0..cipher_suites_len).step_by(2) {
225 if i + 1 >= data.len() {
226 return Err(Error::InvalidClientHelloLength);
227 }
228 let cipher_suite = u16::from_be_bytes([data[i], data[i + 1]]);
229 cipher_suites.push(cipher_suite);
230 }
231 data = &data[cipher_suites_len..];
232
233 if data.is_empty() {
234 return Err(Error::InvalidClientHelloLength);
235 }
236 let compression_methods_len = data[0] as usize;
237 data = &data[1..];
238
239 if data.len() < compression_methods_len {
240 return Err(Error::InvalidClientHelloLength);
241 }
242 let compression_methods: Vec<u8> = data[0..compression_methods_len].to_vec();
243 data = &data[compression_methods_len..];
244
245 if data.len() < 2 {
246 return Err(Error::InvalidClientHelloLength);
247 }
248 let extensions_len = u16::from_be_bytes([data[0], data[1]]) as usize;
249 data = &data[2..];
250
251 if data.len() < extensions_len {
252 return Err(Error::InvalidClientHelloLength);
253 }
254 let mut extensions_bytes: &[u8] = &data[0..extensions_len];
255
256 let mut signature_algorithm_ids: Vec<u16> = Vec::new();
257 let mut supported_group_ids: Vec<u16> = Vec::new();
258 let mut protocols: Vec<&[u8]> = Vec::new();
259 let mut ec_point_formats: Vec<u8> = Vec::new();
260
261 let mut extensions: Vec<Extension> = Vec::new();
262 while !extensions_bytes.is_empty() {
263 let extension_id = u16::from_be_bytes([extensions_bytes[0], extensions_bytes[1]]);
264 extensions_bytes = &extensions_bytes[2..];
265
266 let extension_len = u16::from_be_bytes([extensions_bytes[0], extensions_bytes[1]]);
267 extensions_bytes = &extensions_bytes[2..];
268 let extension_bytes: &[u8] = &extensions_bytes[..extension_len as usize];
269 extensions_bytes = &extensions_bytes[extension_len as usize..];
270 extensions.push(Extension {
271 id: extension_id,
272 len: extension_len,
273 });
274
275 match extension_id {
276 id if id == TlsExtensionId::SupportedVersions as u16 => {
277 if let Ok(versions) = Self::parse_supported_versions_extension(extension_bytes)
281 {
282 if let Some(&best) = versions.iter().filter(|&&v| !Self::is_grease(v)).max()
283 {
284 client_version = best;
285 }
286 }
287 }
288 id if id == TlsExtensionId::SignatureAlgorithms as u16 => {
289 let parsed_signature_algorithm_ids =
290 Self::parse_signature_algorithms_extension(extension_bytes)?;
291 signature_algorithm_ids.extend(parsed_signature_algorithm_ids);
292 }
293 id if id == TlsExtensionId::SupportedGroups as u16 => {
294 let extension_supported_groups =
295 Self::parse_supported_groups_extension(extension_bytes)?;
296 supported_group_ids.extend(extension_supported_groups);
297 }
298 id if id == TlsExtensionId::ApplicationLayerProtocolNegotiation as u16 => {
299 let extension_alpn_protocols = Self::parse_alpn_extension(extension_bytes)?;
300 protocols.extend(extension_alpn_protocols);
301 }
302 id if id == TlsExtensionId::EcPointFormats as u16 => {
303 let parsed_ec_point_formats =
304 Self::parse_ec_point_formats_extension(extension_bytes)?;
305 ec_point_formats.extend(parsed_ec_point_formats);
306 }
307 _ => {
308 continue;
309 }
310 }
311 }
312
313 let ja4_protocol = protocol_marker(false); let ja4_tls_version = match TlsProtocolVersion::from_u16(client_version) {
316 TlsProtocolVersion::TLSv1_0 => "10",
317 TlsProtocolVersion::TLSv1_1 => "11",
318 TlsProtocolVersion::TLSv1_2 => "12",
319 TlsProtocolVersion::TLSv1_3 => "13",
320 _ => "00",
321 };
322 let ja4_sni = if extensions
326 .iter()
327 .any(|e| e.id == TlsExtensionId::ServerName as u16)
328 {
329 'd'
330 } else {
331 'i'
332 };
333
334 let (alpn_first, alpn_last) = if protocols.is_empty() {
336 ("0".to_string(), "0".to_string())
337 } else {
338 alpn_first_last(protocols[0])
339 };
340
341 let nr_ciphers = 99.min(
343 cipher_suites
344 .iter()
345 .filter(|&&c| !Self::is_grease(c))
346 .count(),
347 );
348 let nr_exts = 99.min(extensions.iter().filter(|e| !Self::is_grease(e.id)).count());
349
350 let first_chunk = format!(
352 "{}{}{}{}{}{}{}",
353 ja4_protocol,
354 ja4_tls_version,
355 ja4_sni,
356 format_args!("{:02}", nr_ciphers),
357 format_args!("{:02}", nr_exts),
358 alpn_first,
359 alpn_last
360 );
361
362 let cipher_string = {
364 let mut ciphers: Vec<u16> = cipher_suites
365 .iter()
366 .copied()
367 .filter(|c| !Self::is_grease(*c))
368 .collect();
369 ciphers.sort_unstable();
370 format_id_list(&ciphers)
371 };
372 let ja4_cipher_hash = hash12(&cipher_string);
373
374 let extension_string = {
376 let mut ext_ids: Vec<u16> = extensions
377 .iter()
378 .map(|e| e.id)
379 .filter(|id| !Self::is_grease(*id) && *id != 0x0000 && *id != 0x0010)
380 .collect();
381 ext_ids.sort_unstable();
382 format_id_list(&ext_ids)
383 };
384
385 let sig_alg_string = {
387 let sig_algs: Vec<u16> = signature_algorithm_ids
388 .iter()
389 .copied()
390 .filter(|id| !Self::is_grease(*id))
391 .collect();
392 format_id_list(&sig_algs)
393 };
394
395 let ja4_exts_hash = if sig_alg_string.is_empty() {
397 hash12(&extension_string)
398 } else {
399 let exts_sigs = format!("{extension_string}_{sig_alg_string}");
400 hash12(&exts_sigs)
401 };
402
403 let ja4 = format!("{first_chunk}_{ja4_cipher_hash}_{ja4_exts_hash}");
404
405 Ok(Ja4 {
406 ja4,
407 record_type,
408 protocol_version,
409 record_len,
410 handshake_message_type,
411 handshake_message_len,
412 client_version,
413 client_random,
414 session_id,
415 cipher_suites,
416 compression_methods,
417 extensions,
418 protocol,
419 })
420 }
421
422 pub fn parse_supported_versions_extension(mut buffer: &[u8]) -> Result<Vec<u16>, Error> {
425 if buffer.is_empty() {
426 return Ok(Vec::new());
427 }
428 let list_len = buffer[0] as usize;
429 buffer = &buffer[1..];
430 if buffer.len() < list_len {
431 return Ok(Vec::new());
432 }
433 buffer = &buffer[..list_len];
434 let mut versions = Vec::new();
435 while buffer.len() >= 2 {
436 let v = u16::from_be_bytes([buffer[0], buffer[1]]);
437 buffer = &buffer[2..];
438 versions.push(v);
439 }
440 Ok(versions)
441 }
442
443 pub fn parse_ec_point_formats_extension(buffer: &[u8]) -> Result<&[u8], Error> {
444 if buffer.is_empty() {
445 return Err(Error::InvalidEcPointFormatsExtensionBufferLength);
446 }
447
448 let len = buffer[0];
449 let buffer = &buffer[1..];
450
451 if buffer.len() != len as usize {
452 return Err(Error::InvalidEcPointFormatsExtensionLength);
453 }
454
455 Ok(buffer)
457 }
458
459 pub fn parse_alpn_extension<'a>(mut buffer: &[u8]) -> Result<Vec<&[u8]>, Error> {
460 if buffer.len() < 2 {
461 return Err(Error::InvalidAlpnExtensionBufferLength);
462 }
463
464 let len = u16::from_be_bytes([buffer[0], buffer[1]]);
465 buffer = &buffer[2..];
466
467 if buffer.len() != len as usize {
468 return Err(Error::InvalidAlpnExtensionLength);
469 }
470
471 let mut protocols: Vec<&[u8]> = Vec::new();
472 while !buffer.is_empty() {
473 let protocol_len = u8::from_be_bytes([buffer[0]]);
474 buffer = &buffer[1..];
475 let protocol = &buffer[0..protocol_len as usize];
476 buffer = &buffer[protocol_len as usize..];
477 protocols.push(protocol);
478 }
479
480 Ok(protocols)
481 }
482
483 pub fn parse_supported_groups_extension<'a>(mut buffer: &[u8]) -> Result<Vec<u16>, Error> {
484 if buffer.len() < 2 {
485 return Err(Error::InvalidSupportedGroupsExtensionBufferLength);
486 }
487
488 let len = u16::from_be_bytes([buffer[0], buffer[1]]);
489 buffer = &buffer[2..];
490
491 if buffer.len() != len as usize {
492 return Err(Error::InvalidSupportedGroupsExtensionLength);
493 }
494 let mut supported_group_ids = Vec::new();
495 while !buffer.is_empty() {
496 let supported_group_id = u16::from_be_bytes([buffer[0], buffer[1]]);
497 buffer = &buffer[2..];
498 if Self::is_grease(supported_group_id) {
499 continue;
500 }
501 supported_group_ids.push(supported_group_id);
502 }
503
504 Ok(supported_group_ids)
505 }
506
507 pub fn parse_signature_algorithms_extension<'a>(mut buffer: &[u8]) -> Result<Vec<u16>, Error> {
508 if buffer.len() < 2 {
509 return Err(Error::InvalidSignatureAlgorithmsExtensionBufferLength);
510 }
511
512 let len = u16::from_be_bytes([buffer[0], buffer[1]]);
513 buffer = &buffer[2..];
514
515 if buffer.len() != len as usize {
516 return Err(Error::InvalidSignatureAlgorithmsExtensionLength);
517 }
518
519 let mut signature_algorithm_ids = Vec::new();
520 while !buffer.is_empty() {
521 let signature_algorithm_id = u16::from_be_bytes([buffer[0], buffer[1]]);
522 buffer = &buffer[2..];
523 if Self::is_grease(signature_algorithm_id) {
524 continue;
525 }
526 signature_algorithm_ids.push(signature_algorithm_id);
527 }
528
529 Ok(signature_algorithm_ids)
530 }
531
532 pub fn parse_server_name_extension<'a>(mut buffer: &[u8]) -> Result<Vec<String>, Error> {
533 if buffer.len() < 2 {
534 return Err(Error::InvalidServerNameExtensionBufferLength);
535 }
536
537 let len = u16::from_be_bytes([buffer[0], buffer[1]]);
538 buffer = &buffer[2..];
539
540 if buffer.len() != len as usize {
541 return Err(Error::InvalidServerNameExtensionLength);
542 }
543
544 let mut names: Vec<String> = Vec::new();
545
546 while !buffer.is_empty() {
547 let name_type = buffer[0];
548 buffer = &buffer[1..];
549 let name_len = u16::from_be_bytes([buffer[0], buffer[1]]);
550 buffer = &buffer[2..];
551
552 if buffer.len() < name_len as usize {
553 return Err(Error::InvalidServerNameExtensionLength);
554 }
555
556 let name: &[u8] = &buffer[0..name_len as usize];
557 buffer = &buffer[name_len as usize..];
558
559 if name_type == 0 {
561 let name_str = String::from_utf8(name.to_vec())
562 .map_err(|_| Error::InvalidServerNameExtensionName)?;
563 names.push(name_str);
564 }
565 }
566
567 Ok(names)
568 }
569
570 #[must_use]
572 pub fn is_grease(id: u16) -> bool {
573 id & 0x0F0F == 0x0A0A && id >> 8 == id & 0xFF
577 }
578}
579
580#[allow(dead_code)]
581struct ExtensionAlpn<'a> {
582 protocols: &'a [&'a [u8]],
583}
584
585#[allow(dead_code)]
586struct ExtensionServerName<'a> {
587 names: &'a [String],
588}
589
590#[derive(PartialEq, Eq, Ord, PartialOrd)]
591struct Extension {
592 id: u16,
593 len: u16,
594}
595
596pub enum TlsProtocolVersion {
597 TLSv1_0 = 0x0301,
598 TLSv1_1 = 0x0302,
599 TLSv1_2 = 0x0303,
600 TLSv1_3 = 0x0304,
601 Unknown = 0x0000,
602}
603
604impl TlsProtocolVersion {
605 #[must_use]
606 pub fn from_u16(value: u16) -> Self {
607 match value {
608 0x0301 => Self::TLSv1_0,
609 0x0302 => Self::TLSv1_1,
610 0x0303 => Self::TLSv1_2,
611 0x0304 => Self::TLSv1_3,
612 _ => Self::Unknown,
613 }
614 }
615
616 #[must_use]
617 pub fn to_u16(&self) -> u16 {
618 match self {
619 Self::TLSv1_0 => 0x0301,
620 Self::TLSv1_1 => 0x0302,
621 Self::TLSv1_2 => 0x0303,
622 Self::TLSv1_3 => 0x0304,
623 Self::Unknown => 0x0000,
624 }
625 }
626}
627
628#[derive(Debug, Clone, Copy, PartialEq, Eq)]
629#[repr(u16)]
630pub enum TlsExtensionId {
631 ServerName = 0,
632 MaxFragmentLength = 1,
633 ClientCertificateUrl = 2,
634 TrustedCaKeys = 3,
635 TruncatedHmac = 4,
636 StatusRequest = 5,
637 UserMapping = 6,
638 ClientAuthz = 7,
639 ServerAuthz = 8,
640 CertType = 9,
641 SupportedGroups = 10,
642 EcPointFormats = 11,
643 Srp = 12,
644 SignatureAlgorithms = 13,
645 UseSrtp = 14,
646 Heartbeat = 15,
647 ApplicationLayerProtocolNegotiation = 16,
648 StatusRequestV2 = 17,
649 SignedCertificateTimestamp = 18,
650 ClientCertificateType = 19,
651 ServerCertificateType = 20,
652 Padding = 21,
653 EncryptThenMac = 22,
654 ExtendedMasterSecret = 23,
655 TokenBinding = 24,
656 CachedInfo = 25,
657 TlsLts = 26,
658 CompressCertificate = 27,
659 RecordSizeLimit = 28,
660 DelegatedCredentials = 34,
661 SessionTicket = 35,
662 Tlmsp = 36,
663 TlmspProxying = 37,
664 TlmspDelegate = 38,
665 SupportedEktCiphers = 39,
666 PreSharedKeyLegacy = 40,
667 PreSharedKey = 41,
668 EarlyData = 42,
669 SupportedVersions = 0x002B,
670 Cookie = 44,
671 PskKeyExchangeModes = 45,
672 PskKeyExchangeModesLegacy = 46,
673 CertificateAuthorities = 47,
674 OidFilters = 48,
675 PostHandshakeAuth = 49,
676 SignatureAlgorithmsCert = 50,
677 KeyShare = 51,
678 ConnectionId = 52,
679 ConnectionIdDtls = 53,
680 ExternalIdHash = 93,
681 ExternalSessionId = 94,
682 PwdProtect = 30,
683 PwdClear = 31,
684 PasswordSalt = 32,
685 TicketPinning = 33,
686 RenegotiationInfo = 65281,
687 EncryptedClientHello = 65037,
688 ChannelId = 30031,
689}
690
691#[cfg(test)]
692#[allow(clippy::unwrap_used, clippy::expect_used)]
693mod tests {
694 use super::*;
695
696 #[test]
697 fn test_alpn_char_alphanumeric() {
698 assert_eq!(alpn_char(b'h'), "h");
699 assert_eq!(alpn_char(b'2'), "2");
700 assert_eq!(alpn_char(b'A'), "A");
701 assert_eq!(alpn_char(b'z'), "z");
702 }
703
704 #[test]
705 fn test_alpn_char_non_alphanumeric() {
706 assert_eq!(alpn_char(b'/'), "2f");
708 assert_eq!(alpn_char(0xAD), "ad");
709 assert_eq!(alpn_char(0x00), "00");
710 }
711
712 #[test]
713 fn test_alpn_first_last() {
714 assert_eq!(alpn_first_last(b"h2"), ("h".to_string(), "2".to_string()));
715 assert_eq!(alpn_first_last(b"h"), ("h".to_string(), "0".to_string()));
717 assert_eq!(alpn_first_last(b""), ("0".to_string(), "0".to_string()));
719 assert_eq!(
721 alpn_first_last(b"http/1.1"),
722 ("h".to_string(), "1".to_string())
723 );
724 assert_eq!(
726 alpn_first_last(&[0xAD, b'x']),
727 ("ad".to_string(), "x".to_string())
728 );
729 }
730
731 #[test]
732 fn test_protocol_marker() {
733 assert_eq!(protocol_marker(false), 't');
734 assert_eq!(protocol_marker(true), 't'); }
736
737 #[test]
738 fn test_hash12() {
739 let input = "test_input";
740 let hash = hash12(input);
741
742 assert_eq!(hash.len(), 12);
744 assert!(hash.chars().all(|c| c.is_ascii_hexdigit()));
745
746 let hash2 = hash12(input);
748 assert_eq!(hash, hash2);
749
750 let hash3 = hash12("different_input");
752 assert_ne!(hash, hash3);
753 }
754
755 #[test]
756 fn test_is_grease() {
757 assert!(Ja4::is_grease(0x0a0a));
759 assert!(Ja4::is_grease(0x1a1a));
760 assert!(Ja4::is_grease(0x2a2a));
761 assert!(Ja4::is_grease(0x3a3a));
762 assert!(Ja4::is_grease(0x4a4a));
763 assert!(Ja4::is_grease(0x5a5a));
764 assert!(Ja4::is_grease(0x6a6a));
765 assert!(Ja4::is_grease(0x7a7a));
766 assert!(Ja4::is_grease(0x8a8a));
767 assert!(Ja4::is_grease(0x9a9a));
768 assert!(Ja4::is_grease(0xaaaa));
769 assert!(Ja4::is_grease(0xbaba));
770 assert!(Ja4::is_grease(0xcaca));
771 assert!(Ja4::is_grease(0xdada));
772 assert!(Ja4::is_grease(0xeaea));
773 assert!(Ja4::is_grease(0xfafa));
774
775 assert!(!Ja4::is_grease(0x1301)); assert!(!Ja4::is_grease(0xc02f)); assert!(!Ja4::is_grease(0x0000)); assert!(!Ja4::is_grease(0x002b)); assert!(!Ja4::is_grease(0x0a1a));
784 assert!(!Ja4::is_grease(0x1a0a));
785 assert!(!Ja4::is_grease(0x2a3a));
786 }
787
788 #[test]
789 fn test_ja4_format() {
790 let ja4_example = "t13d1516h2_8daaf6152771_e5627efa2ab1";
795
796 assert!(ja4_example.starts_with('t'));
798
799 assert_eq!(ja4_example.split('_').count(), 3);
801
802 let parts: Vec<&str> = ja4_example.split('_').collect();
804 assert_eq!(parts[0].len(), 10); assert_eq!(parts[1].len(), 12); assert_eq!(parts[2].len(), 12); assert!(parts[1].chars().all(|c| c.is_ascii_hexdigit()));
810 assert!(parts[2].chars().all(|c| c.is_ascii_hexdigit()));
811 }
812
813 #[test]
814 fn test_ja4_fingerprint_consistency() {
815 let cipher_string = "1301,1302,1303,c02b,c02f";
817 let hash1 = hash12(cipher_string);
818 let hash2 = hash12(cipher_string);
819
820 assert_eq!(hash1, hash2);
821 }
822
823 #[test]
824 fn test_extension_filtering() {
825 let extensions = vec![
827 Extension { id: 0x0000, len: 0 }, Extension { id: 0x000a, len: 0 }, Extension { id: 0x0010, len: 0 }, Extension { id: 0x002b, len: 0 }, ];
832
833 let filtered: Vec<u16> = extensions
834 .iter()
835 .map(|e| e.id)
836 .filter(|id| !Ja4::is_grease(*id) && *id != 0x0000 && *id != 0x0010)
837 .collect();
838
839 assert_eq!(filtered.len(), 2);
840 assert!(!filtered.contains(&0x0000));
841 assert!(!filtered.contains(&0x0010));
842 assert!(filtered.contains(&0x000a));
843 assert!(filtered.contains(&0x002b));
844 }
845
846 #[test]
847 fn test_ja4_default() {
848 let ja4 = Ja4::default();
849 assert_eq!(ja4.ja4, "");
850 assert_eq!(ja4.client_version, 0);
851 assert_eq!(ja4.cipher_suites.len(), 0);
852 assert_eq!(ja4.extensions.len(), 0);
853 }
854
855 fn build_client_hello(
861 tls_version: u16,
862 cipher_suites: &[u16],
863 extensions: &[(u16, &[u8])],
864 ) -> Vec<u8> {
865 let mut body = Vec::new();
866
867 body.extend_from_slice(&tls_version.to_be_bytes());
869
870 body.extend_from_slice(&[0xAA; 32]);
872
873 body.push(0);
875
876 let cs_len = (cipher_suites.len() * 2) as u16;
878 body.extend_from_slice(&cs_len.to_be_bytes());
879 for cs in cipher_suites {
880 body.extend_from_slice(&cs.to_be_bytes());
881 }
882
883 body.push(1);
885 body.push(0);
886
887 let mut ext_buf = Vec::new();
889 for (id, data) in extensions {
890 ext_buf.extend_from_slice(&id.to_be_bytes());
891 ext_buf.extend_from_slice(&(data.len() as u16).to_be_bytes());
892 ext_buf.extend_from_slice(data);
893 }
894 body.extend_from_slice(&(ext_buf.len() as u16).to_be_bytes());
895 body.extend_from_slice(&ext_buf);
896
897 let hs_len = body.len() as u32;
899 let mut handshake = Vec::new();
900 handshake.push(HANDSHAKE_MESSAGE_TYPE); handshake.push((hs_len >> 16) as u8);
902 handshake.push((hs_len >> 8) as u8);
903 handshake.push(hs_len as u8);
904 handshake.extend_from_slice(&body);
905
906 let rec_len = handshake.len() as u16;
908 let mut record = Vec::new();
909 record.push(HANDSHAKE_RECORD_TYPE); record.extend_from_slice(&0x0301u16.to_be_bytes()); record.extend_from_slice(&rec_len.to_be_bytes());
912 record.extend_from_slice(&handshake);
913
914 record
915 }
916
917 fn build_sni_extension(hostname: &str) -> Vec<u8> {
919 let name = hostname.as_bytes();
920 let mut buf = Vec::new();
921 let list_len = (1 + 2 + name.len()) as u16;
923 buf.extend_from_slice(&list_len.to_be_bytes());
924 buf.push(0);
926 buf.extend_from_slice(&(name.len() as u16).to_be_bytes());
928 buf.extend_from_slice(name);
929 buf
930 }
931
932 fn build_alpn_extension(protocols: &[&str]) -> Vec<u8> {
934 let mut proto_buf = Vec::new();
935 for p in protocols {
936 proto_buf.push(p.len() as u8);
937 proto_buf.extend_from_slice(p.as_bytes());
938 }
939 let mut buf = Vec::new();
940 buf.extend_from_slice(&(proto_buf.len() as u16).to_be_bytes());
941 buf.extend_from_slice(&proto_buf);
942 buf
943 }
944
945 fn build_supported_versions_extension() -> Vec<u8> {
947 vec![
949 2, 0x03, 0x04, ]
952 }
953
954 fn build_sig_algs_extension(algs: &[u16]) -> Vec<u8> {
956 let mut buf = Vec::new();
957 let len = (algs.len() * 2) as u16;
958 buf.extend_from_slice(&len.to_be_bytes());
959 for alg in algs {
960 buf.extend_from_slice(&alg.to_be_bytes());
961 }
962 buf
963 }
964
965 #[test]
968 fn test_rejects_too_short_input() {
969 assert!(matches!(
971 Ja4::from_client_hello(&[0x16, 0x03, 0x01]),
972 Err(Error::InvalidClientHelloLength)
973 ));
974 }
975
976 #[test]
977 fn test_rejects_non_handshake_record_type() {
978 let mut record = build_client_hello(0x0303, &[0x1301], &[]);
979 record[0] = 0x17; assert!(matches!(
981 Ja4::from_client_hello(&record),
982 Err(Error::InvalidClientHelloRecordType)
983 ));
984 }
985
986 #[test]
987 fn test_rejects_non_client_hello_handshake_type() {
988 let mut record = build_client_hello(0x0303, &[0x1301], &[]);
989 record[5] = 0x02; assert!(matches!(
991 Ja4::from_client_hello(&record),
992 Err(Error::InvalidClientHelloHandshakeMessageType)
993 ));
994 }
995
996 #[test]
997 fn test_rejects_odd_cipher_suites_length() {
998 let mut record = build_client_hello(0x0303, &[0x1301], &[]);
1001 record[44] = 0;
1004 record[45] = 3;
1005 assert!(matches!(
1006 Ja4::from_client_hello(&record),
1007 Err(Error::InvalidClientHelloLength)
1008 ));
1009 }
1010
1011 #[test]
1012 fn test_rejects_truncated_record() {
1013 let record = build_client_hello(0x0303, &[0x1301], &[]);
1014 let truncated = &record[..record.len() - 10];
1016 assert!(Ja4::from_client_hello(truncated).is_err());
1017 }
1018
1019 #[test]
1022 fn test_parses_tls12_no_extensions() {
1023 let ciphers: Vec<u16> = vec![0xc02f, 0xc030, 0x009e];
1024 let record = build_client_hello(0x0303, &ciphers, &[]);
1025 let ja4 = Ja4::from_client_hello(&record).expect("should parse");
1026
1027 assert_eq!(ja4.record_type, HANDSHAKE_RECORD_TYPE);
1028 assert_eq!(ja4.handshake_message_type, HANDSHAKE_MESSAGE_TYPE);
1029 assert_eq!(ja4.client_version, 0x0303);
1030 assert_eq!(ja4.cipher_suites, ciphers);
1031 assert_eq!(ja4.compression_methods, vec![0]);
1032 assert!(ja4.extensions.is_empty());
1033 }
1034
1035 #[test]
1036 fn test_parses_tls13_with_supported_versions() {
1037 let ciphers = vec![0x1301, 0x1302];
1038 let sv_ext = build_supported_versions_extension();
1039 let record = build_client_hello(
1040 0x0303, &ciphers,
1042 &[(TlsExtensionId::SupportedVersions as u16, &sv_ext)],
1043 );
1044 let ja4 = Ja4::from_client_hello(&record).expect("should parse");
1045
1046 assert_eq!(ja4.client_version, 0x0304);
1048 assert!(ja4.ja4.starts_with("t13"));
1050 }
1051
1052 #[test]
1053 fn test_sni_sets_d_flag() {
1054 let sni = build_sni_extension("example.com");
1055 let record = build_client_hello(
1056 0x0303,
1057 &[0xc02f],
1058 &[(TlsExtensionId::ServerName as u16, &sni)],
1059 );
1060 let ja4 = Ja4::from_client_hello(&record).expect("should parse");
1061
1062 let parts: Vec<&str> = ja4.ja4.split('_').collect();
1064 assert_eq!(parts[0].chars().nth(3), Some('d'));
1065 }
1066
1067 #[test]
1068 fn test_no_sni_sets_i_flag() {
1069 let record = build_client_hello(0x0303, &[0xc02f], &[]);
1070 let ja4 = Ja4::from_client_hello(&record).expect("should parse");
1071
1072 let parts: Vec<&str> = ja4.ja4.split('_').collect();
1074 assert_eq!(parts[0].chars().nth(3), Some('i'));
1075 }
1076
1077 #[test]
1078 fn test_empty_sni_extension_sets_d_flag() {
1079 let record = build_client_hello(
1082 0x0303,
1083 &[0xc02f],
1084 &[(TlsExtensionId::ServerName as u16, &[])],
1085 );
1086 let ja4 = Ja4::from_client_hello(&record).expect("should parse");
1087 let parts: Vec<&str> = ja4.ja4.split('_').collect();
1088 assert_eq!(parts[0].chars().nth(3), Some('d'));
1089 }
1090
1091 #[test]
1092 fn test_alpn_characters_in_fingerprint() {
1093 let alpn = build_alpn_extension(&["h2"]);
1094 let record = build_client_hello(
1095 0x0303,
1096 &[0xc02f],
1097 &[(
1098 TlsExtensionId::ApplicationLayerProtocolNegotiation as u16,
1099 &alpn,
1100 )],
1101 );
1102 let ja4 = Ja4::from_client_hello(&record).expect("should parse");
1103
1104 let first_chunk = ja4.ja4.split('_').next().unwrap();
1106 assert_eq!(first_chunk.chars().nth(8), Some('h'));
1107 assert_eq!(first_chunk.chars().nth(9), Some('2'));
1108 }
1109
1110 #[test]
1111 fn test_no_alpn_uses_zeros() {
1112 let record = build_client_hello(0x0303, &[0xc02f], &[]);
1113 let ja4 = Ja4::from_client_hello(&record).expect("should parse");
1114
1115 let first_chunk = ja4.ja4.split('_').next().unwrap();
1116 assert_eq!(first_chunk.chars().nth(8), Some('0'));
1117 assert_eq!(first_chunk.chars().nth(9), Some('0'));
1118 }
1119
1120 #[test]
1121 fn test_cipher_and_extension_counts() {
1122 let ciphers = vec![0x1301, 0x1302, 0x1303, 0xc02b, 0xc02f];
1123 let sni = build_sni_extension("example.com");
1124 let alpn = build_alpn_extension(&["h2", "http/1.1"]);
1125 let sig_algs = build_sig_algs_extension(&[0x0403, 0x0804]);
1126 let record = build_client_hello(
1127 0x0303,
1128 &ciphers,
1129 &[
1130 (TlsExtensionId::ServerName as u16, &sni),
1131 (
1132 TlsExtensionId::ApplicationLayerProtocolNegotiation as u16,
1133 &alpn,
1134 ),
1135 (TlsExtensionId::SignatureAlgorithms as u16, &sig_algs),
1136 ],
1137 );
1138 let ja4 = Ja4::from_client_hello(&record).expect("should parse");
1139
1140 let first_chunk = ja4.ja4.split('_').next().unwrap();
1141 assert_eq!(&first_chunk[4..6], "05");
1143 assert_eq!(&first_chunk[6..8], "03");
1144 }
1145
1146 #[test]
1147 fn test_grease_ciphers_filtered_from_hash() {
1148 let with_grease = vec![0x0a0a, 0x1301, 0x1302];
1151 let without_grease = vec![0x1301, 0x1302];
1152
1153 let record_with = build_client_hello(0x0303, &with_grease, &[]);
1154 let record_without = build_client_hello(0x0303, &without_grease, &[]);
1155
1156 let ja4_with = Ja4::from_client_hello(&record_with).expect("should parse");
1157 let ja4_without = Ja4::from_client_hello(&record_without).expect("should parse");
1158
1159 let hash_with = ja4_with.ja4.split('_').nth(1).unwrap();
1161 let hash_without = ja4_without.ja4.split('_').nth(1).unwrap();
1162 assert_eq!(hash_with, hash_without);
1163 }
1164
1165 #[test]
1166 fn test_sni_and_alpn_extensions_excluded_from_ext_hash() {
1167 let sni = build_sni_extension("example.com");
1170 let alpn = build_alpn_extension(&["h2"]);
1171 let sig_algs = build_sig_algs_extension(&[0x0403]);
1172
1173 let record_with_sni_alpn = build_client_hello(
1174 0x0303,
1175 &[0x1301],
1176 &[
1177 (TlsExtensionId::ServerName as u16, &sni),
1178 (
1179 TlsExtensionId::ApplicationLayerProtocolNegotiation as u16,
1180 &alpn,
1181 ),
1182 (TlsExtensionId::SignatureAlgorithms as u16, &sig_algs),
1183 ],
1184 );
1185 let record_only_sig = build_client_hello(
1186 0x0303,
1187 &[0x1301],
1188 &[(TlsExtensionId::SignatureAlgorithms as u16, &sig_algs)],
1189 );
1190
1191 let ja4_with = Ja4::from_client_hello(&record_with_sni_alpn).expect("should parse");
1192 let ja4_without = Ja4::from_client_hello(&record_only_sig).expect("should parse");
1193
1194 let ext_hash_with = ja4_with.ja4.split('_').nth(2).unwrap();
1195 let ext_hash_without = ja4_without.ja4.split('_').nth(2).unwrap();
1196 assert_eq!(ext_hash_with, ext_hash_without);
1197 }
1198
1199 #[test]
1200 fn test_ja4_output_format() {
1201 let sni = build_sni_extension("example.com");
1202 let alpn = build_alpn_extension(&["h2"]);
1203 let record = build_client_hello(
1204 0x0303,
1205 &[0x1301, 0xc02f],
1206 &[
1207 (TlsExtensionId::ServerName as u16, &sni),
1208 (
1209 TlsExtensionId::ApplicationLayerProtocolNegotiation as u16,
1210 &alpn,
1211 ),
1212 ],
1213 );
1214 let ja4 = Ja4::from_client_hello(&record).expect("should parse");
1215
1216 let parts: Vec<&str> = ja4.ja4.split('_').collect();
1217 assert_eq!(
1218 parts.len(),
1219 3,
1220 "JA4 should have 3 underscore-separated parts"
1221 );
1222 assert_eq!(parts[0].len(), 10, "first chunk should be 10 chars");
1223 assert_eq!(parts[1].len(), 12, "cipher hash should be 12 hex chars");
1224 assert_eq!(parts[2].len(), 12, "extension hash should be 12 hex chars");
1225 assert!(parts[1].chars().all(|c| c.is_ascii_hexdigit()));
1226 assert!(parts[2].chars().all(|c| c.is_ascii_hexdigit()));
1227 }
1228
1229 #[test]
1230 fn test_deterministic_output() {
1231 let record = build_client_hello(0x0303, &[0x1301, 0x1302, 0xc02f], &[]);
1232 let ja4a = Ja4::from_client_hello(&record).expect("should parse");
1233 let ja4b = Ja4::from_client_hello(&record).expect("should parse");
1234 assert_eq!(ja4a.ja4, ja4b.ja4, "same input must produce same JA4");
1235 }
1236
1237 #[test]
1238 fn test_full_realistic_client_hello() {
1239 let sni = build_sni_extension("www.example.com");
1243 let alpn = build_alpn_extension(&["h2", "http/1.1"]);
1244 let sig_algs = build_sig_algs_extension(&[
1245 0x0403, 0x0804, 0x0401, ]);
1249 let sv_ext = build_supported_versions_extension();
1250
1251 let ciphers = vec![
1252 0x4a4a, 0x1301, 0x1302, 0x1303, 0xc02b, 0xc02f, ];
1259
1260 let record = build_client_hello(
1261 0x0303,
1262 &ciphers,
1263 &[
1264 (TlsExtensionId::ServerName as u16, &sni),
1265 (TlsExtensionId::SupportedVersions as u16, &sv_ext),
1266 (
1267 TlsExtensionId::ApplicationLayerProtocolNegotiation as u16,
1268 &alpn,
1269 ),
1270 (TlsExtensionId::SignatureAlgorithms as u16, &sig_algs),
1271 ],
1272 );
1273
1274 let ja4 = Ja4::from_client_hello(&record).expect("should parse realistic ClientHello");
1275
1276 let parts: Vec<&str> = ja4.ja4.split('_').collect();
1277 assert_eq!(parts.len(), 3);
1278
1279 assert_eq!(&parts[0][0..4], "t13d");
1281
1282 assert_eq!(&parts[0][4..6], "05");
1284
1285 assert_eq!(&parts[0][6..8], "04");
1287
1288 assert_eq!(&parts[0][8..10], "h2");
1290
1291 assert_eq!(parts[1].len(), 12);
1293 assert_eq!(parts[2].len(), 12);
1294
1295 assert_eq!(ja4.client_version, 0x0304); assert_eq!(ja4.cipher_suites, ciphers);
1298 assert_eq!(ja4.extensions.len(), 4);
1299 }
1300
1301 #[test]
1302 fn test_supported_versions_tls12_only() {
1303 let sv_ext = vec![
1305 2, 0x03, 0x03, ];
1308 let record = build_client_hello(
1309 0x0303,
1310 &[0x1301],
1311 &[(TlsExtensionId::SupportedVersions as u16, &sv_ext)],
1312 );
1313 let ja4 = Ja4::from_client_hello(&record).expect("should parse");
1314 assert!(ja4.ja4.starts_with("t12"), "expected t12, got {}", ja4.ja4);
1315 }
1316
1317 #[test]
1318 fn test_parse_supported_versions_extension() {
1319 let data = vec![4, 0x03, 0x04, 0x03, 0x03]; let versions = Ja4::parse_supported_versions_extension(&data).unwrap();
1322 assert_eq!(versions, vec![0x0304, 0x0303]);
1323
1324 let data2 = vec![4, 0x0a, 0x0a, 0x03, 0x04];
1326 let versions2 = Ja4::parse_supported_versions_extension(&data2).unwrap();
1327 assert_eq!(versions2, vec![0x0a0a, 0x0304]);
1328 let best: Option<u16> = versions2
1330 .iter()
1331 .copied()
1332 .filter(|&v| !Ja4::is_grease(v))
1333 .max();
1334 assert_eq!(best, Some(0x0304));
1335 }
1336}