Debian Codegraph @

crt/s2n/bindings/rust/extended/s2n-tls/src/fingerprint.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 //! Methods to fingerprint ClientHellos.
5 //!
6 //! See [the C API documentation](https://github.com/aws/s2n-tls/blob/main/api/unstable/fingerprint.h).
7
8 use crate::{
9 client_hello::ClientHello,
10 error::{Error, Fallible},
11 ffi::*,
12 };
13
14 use core::ptr::NonNull;
15
16 #[non_exhaustive]
17 #[derive(Copy, Clone)]
18 pub enum FingerprintType {
19 JA3,
20 JA4,
21 }
22
23 impl From<FingerprintType> for s2n_tls_sys::s2n_fingerprint_type::Type {
24 fn from(value: FingerprintType) -> Self {
25 match value {
26 FingerprintType::JA3 => s2n_tls_sys::s2n_fingerprint_type::FINGERPRINT_JA3,
27 FingerprintType::JA4 => s2n_tls_sys::s2n_fingerprint_type::FINGERPRINT_JA4,
28 }
29 }
30 }
31
32 /// A fingerprint operation.
33 pub struct Fingerprint<'a>(&'a mut Builder);
34
35 impl Fingerprint<'_> {
36 /// Size of the fingerprint hash.
37 ///
38 /// Corresponds to [`s2n_fingerprint_get_hash_size`].
39 pub fn hash_size(&self) -> Result<usize, Error> {
40 self.0.hash_size()
41 }
42
43 /// Calculate the fingerprint hash string.
44 ///
45 /// Corresponds to [`s2n_fingerprint_get_hash`].
46 pub fn hash(&mut self) -> Result<&str, Error> {
47 if self.0.hash.is_empty() {
48 let mut output_size = 0;
49 unsafe {
50 s2n_fingerprint_get_hash(
51 self.0.ptr.as_ptr(),
52 self.0.hash.capacity() as u32,
53 self.0.hash.as_mut_ptr(),
54 &mut output_size,
55 )
56 .into_result()?;
57
58 self.0.hash.as_mut_vec().set_len(output_size as usize);
59 }
60 }
61 Ok(&self.0.hash)
62 }
63
64 /// Size of the raw fingerprint string.
65 ///
66 /// Corresponds to [`s2n_fingerprint_get_raw_size`].
67 ///
68 /// The size of the raw fingerprint string can't be known without calculating
69 /// the fingerprint for a given ClientHello, so either [Fingerprint::hash()]
70 /// or [Fingerprint::raw()] must be called before this method.
71 pub fn raw_size(&self) -> Result<usize, Error> {
72 let mut raw_size = 0;
73 unsafe { s2n_fingerprint_get_raw_size(self.0.ptr.as_ptr(), &mut raw_size).into_result() }?;
74 Ok(raw_size as usize)
75 }
76
77 /// Calculate the raw fingerprint string.
78 ///
79 /// Corresponds to [`s2n_fingerprint_get_raw`].
80 ///
81 /// The size of the raw fingerprint string can't be known without calculating
82 /// the fingerprint for a given ClientHello. Before calling this method, you
83 /// must either:
84 ///
85 /// 1. Call [`Builder::set_raw_size()`] to set a fixed maximum size.
86 /// If that maximum is insufficient, then this method will fail.
87 ///
88 /// ```no_run
89 /// use s2n_tls::client_hello::ClientHello;
90 /// use s2n_tls::fingerprint::{Fingerprint, FingerprintType};
91 ///
92 /// let client_hello_bytes = [ 0, 1, 2, 3, 4, 5 ];
93 /// let client_hello = ClientHello::parse_client_hello(&client_hello_bytes)?;
94 ///
95 /// let mut builder = Fingerprint::builder(FingerprintType::JA3)?;
96 /// builder.set_raw_size(1000)?;
97 /// let mut fingerprint = builder.build(&client_hello)?;
98 /// let raw = fingerprint.raw()?;
99 ///
100 /// # Ok::<(), std::io::Error>(())
101 /// ```
102 ///
103 /// 2. Call [`Fingerprint::hash()`] to calculate the exact fingerprint size.
104 /// This method will then ensure sufficient space is available to calculate
105 /// the raw string.
106 ///
107 /// ```no_run
108 /// use s2n_tls::client_hello::ClientHello;
109 /// use s2n_tls::fingerprint::{Fingerprint, FingerprintType};
110 ///
111 /// let client_hello_bytes = [ 0, 1, 2, 3, 4, 5 ];
112 /// let client_hello = ClientHello::parse_client_hello(&client_hello_bytes)?;
113 ///
114 /// let mut builder = Fingerprint::builder(FingerprintType::JA3)?;
115 /// let mut fingerprint = builder.build(&client_hello)?;
116 /// let hash = fingerprint.hash()?;
117 /// let raw = fingerprint.raw()?;
118 ///
119 /// # Ok::<(), std::io::Error>(())
120 /// ```
121 pub fn raw(&mut self) -> Result<&str, Error> {
122 if self.0.raw.is_empty() {
123 if self.0.raw_size.is_none() {
124 self.0.raw.reserve_exact(self.raw_size()?);
125 };
126
127 let mut output_size = 0;
128 unsafe {
129 s2n_fingerprint_get_raw(
130 self.0.ptr.as_ptr(),
131 self.0.raw.capacity() as u32,
132 self.0.raw.as_mut_ptr(),
133 &mut output_size,
134 )
135 .into_result()?;
136
137 self.0.raw.as_mut_vec().set_len(output_size as usize);
138 };
139 }
140 Ok(&self.0.raw)
141 }
142
143 pub fn builder(method: FingerprintType) -> Result<Builder, Error> {
144 Builder::new(method)
145 }
146 }
147
148 impl Drop for Fingerprint<'_> {
149 /// Resets the underlying [Builder] for the next fingerprint.
150 ///
151 /// Corresponds to [`s2n_fingerprint_wipe`].
152 fn drop(&mut self) {
153 unsafe {
154 s2n_fingerprint_wipe(self.0.ptr.as_ptr())
155 .into_result()
156 .unwrap()
157 };
158 self.0.hash.clear();
159 self.0.raw.clear();
160 }
161 }
162
163 /// Builder that can be reused for multiple fingerprints.
164 ///
165 /// The `Builder` can build a new [Fingerprint] as soon as the old [Fingerprint]
166 /// goes out of scope. The [Fingerprint] implementation of [`Self::drop()`] ensures that this
167 /// is safe by resetting the underlying C structure.
168 ///
169 /// See the below example:
170 /// ```no_run
171 /// use s2n_tls::client_hello::ClientHello;
172 /// use s2n_tls::fingerprint::{Fingerprint, FingerprintType};
173 ///
174 /// let mut builder = Fingerprint::builder(FingerprintType::JA3)?;
175 /// let client_hello_bytes = [ 0, 1, 2, 3, 4, 5 ];
176 ///
177 /// for _ in 1..10 {
178 /// let client_hello = ClientHello::parse_client_hello(&client_hello_bytes)?;
179 /// let mut fingerprint = builder.build(&client_hello)?;
180 /// let hash = fingerprint.hash()?;
181 /// }
182 /// # Ok::<(), std::io::Error>(())
183 /// ```
184 ///
185 /// Multiple Fingerprints constructed from the same Builder can't exist simultaneously.
186 /// The below example fails to compile:
187 /// ```compile_fail,E0499
188 /// use s2n_tls::client_hello::ClientHello;
189 /// use s2n_tls::fingerprint::{Fingerprint, FingerprintType};
190 ///
191 /// let mut builder = Fingerprint::builder(FingerprintType::JA3)?;
192 ///
193 /// let client_hello_bytes = [ 0, 1, 2, 3, 4, 5 ];
194 /// let client_hello_1 = ClientHello::parse_client_hello(&client_hello_bytes)?;
195 /// let client_hello_2 = ClientHello::parse_client_hello(&client_hello_bytes)?;
196 ///
197 /// let mut fingerprint_1 = builder.build(&client_hello_1)?;
198 /// let mut fingerprint_2 = builder.build(&client_hello_2)?;
199 ///
200 /// # Ok::<(), std::io::Error>(())
201 /// ```
202 pub struct Builder {
203 ptr: NonNull<s2n_fingerprint>,
204 hash: String,
205 raw: String,
206 raw_size: Option<usize>,
207 }
208
209 impl Builder {
210 /// Creates a reusable [Builder].
211 ///
212 /// Corresponds to [`s2n_fingerprint_new`].
213 pub fn new(method: FingerprintType) -> Result<Self, Error> {
214 crate::init::init();
215 let ptr = unsafe { s2n_fingerprint_new(method.into()).into_result() }?;
216 let hash = String::with_capacity(Self::ptr_hash_size(&ptr)?);
217 let raw = String::new();
218 Ok(Builder {
219 ptr,
220 hash,
221 raw,
222 raw_size: None,
223 })
224 }
225
226 // Static version of hash_size, required to allocate enough memory in Builder::new()
227 fn ptr_hash_size(ptr: &NonNull<s2n_fingerprint>) -> Result<usize, Error> {
228 let mut hash_size = 0;
229 unsafe { s2n_fingerprint_get_hash_size(ptr.as_ptr(), &mut hash_size).into_result() }?;
230 Ok(hash_size as usize)
231 }
232
233 /// Size of the fingerprint hash.
234 ///
235 /// Corresponds to [`s2n_fingerprint_get_hash_size`].
236 pub fn hash_size(&self) -> Result<usize, Error> {
237 Self::ptr_hash_size(&self.ptr)
238 }
239
240 /// Set the maximum size of the raw fingerprint string.
241 ///
242 /// If the size is not set via this method, then [`Fingerprint::hash()`]
243 /// must be called to calculate the size before [`Fingerprint::raw_size()`]
244 /// or [`Fingerprint::raw()`] can be called.
245 ///
246 /// While the size of the fingerprint hash is fixed, the size of the raw string
247 /// varies based on the size and contents of the ClientHello. Setting a fixed
248 /// size prevents allocating an excessive amount of memory, but can lead to
249 /// failures when calculating unexpectedly large fingerprints.
250 pub fn set_raw_size(&mut self, size: usize) -> Result<&mut Self, Error> {
251 self.raw_size = Some(size);
252 self.raw.reserve_exact(size);
253 Ok(self)
254 }
255
256 /// Creates a fingerprint operation for a given [ClientHello].
257 ///
258 /// Corresponds to [`s2n_fingerprint_set_client_hello`].
259 ///
260 /// The ClientHello must outlive the Fingerprint. The following code is expected to
261 /// fail compilation due to the ClientHello `ch` dropping out of scope before `fingerprint`.
262 /// ```compile_fail,E0597
263 /// # use s2n_tls::{client_hello::ClientHello, fingerprint::{Fingerprint, FingerprintType}};
264 /// # let mut builder = Fingerprint::builder(FingerprintType::JA3).unwrap();
265 /// let fingerprint = {
266 /// let ch = ClientHello::parse_client_hello(&[0; 6]).unwrap();
267 /// builder.build(&ch)
268 /// };
269 /// ```
270 pub fn build<'a>(
271 &'a mut self,
272 client_hello: &'a ClientHello,
273 ) -> Result<Fingerprint<'a>, Error> {
274 unsafe {
275 s2n_fingerprint_set_client_hello(self.ptr.as_ptr(), client_hello.deref_mut_ptr())
276 .into_result()
277 }?;
278 Ok(Fingerprint(self))
279 }
280 }
281
282 impl Drop for Builder {
283 /// Frees the memory associated with this [Builder].
284 ///
285 /// Corresponds to [`s2n_fingerprint_free`].
286 fn drop(&mut self) {
287 let mut ptr: *mut s2n_fingerprint = unsafe { self.ptr.as_mut() };
288 unsafe {
289 let _ = s2n_fingerprint_free(std::ptr::addr_of_mut!(ptr));
290 }
291 }
292 }
293
294 // Legacy versions of the fingerprinting methods
295 const MD5_HASH_SIZE: u32 = 16;
296 impl ClientHello {
297 /// `fingerprint_hash` calculates the hash, and also returns the size
298 /// required for the full fingerprint string. The return value can be used
299 /// to construct a string of appropriate capacity to call
300 /// `fingerprint_string`. `output` will be extended if necessary to store
301 /// the full hash.
302 ///
303 /// ```no_run
304 /// use s2n_tls::client_hello::{ClientHello, FingerprintType};
305 /// use s2n_tls::connection::Connection;
306 /// use s2n_tls::enums::Mode;
307 ///
308 /// let mut conn = Connection::new(Mode::Server);
309 /// // handshake happens
310 /// let mut client_hello: &ClientHello = conn.client_hello().unwrap();
311 /// let mut hash = Vec::new();
312 /// let string_size = client_hello.fingerprint_hash(FingerprintType::JA3, &mut hash).unwrap();
313 /// // hash has been resized so that it can store the fingerprint hash
314 ///
315 /// let mut string = String::with_capacity(string_size as usize);
316 /// // string will not be resized, and the method will fail with
317 /// // ErrorType::UsageError if the string doesn't have enough capacity
318 /// client_hello.fingerprint_string(FingerprintType::JA3, &mut string).unwrap();
319 /// ```
320 ///
321 /// Corresponds to [`s2n_client_hello_get_fingerprint_hash`].
322 #[deprecated = "Users should prefer the Fingerprint::hash() method"]
323 pub fn fingerprint_hash(
324 &self,
325 hash: FingerprintType,
326 output: &mut Vec<u8>,
327 ) -> Result<u32, Error> {
328 let mut hash_size: u32 = 0;
329 let mut str_size: u32 = 0;
330 // make sure the vec has sufficient space for the hash
331 if output.capacity() < MD5_HASH_SIZE as usize {
332 output.reserve_exact(MD5_HASH_SIZE as usize - output.len());
333 }
334 unsafe {
335 s2n_client_hello_get_fingerprint_hash(
336 self.deref_mut_ptr(),
337 hash.into(),
338 MD5_HASH_SIZE,
339 output.as_mut_ptr(),
340 &mut hash_size,
341 &mut str_size,
342 )
343 .into_result()?;
344 // SAFETY: we wrote to the raw vec (using the mut pointer), and need
345 // to update the state of the vec to reflect the changes we made.
346 output.set_len(hash_size as usize);
347 };
348 Ok(str_size)
349 }
350
351 /// `fingerprint_string` will try to calculate the fingerprint and store the
352 /// resulting string in `output`. If `output` does not have sufficient
353 /// capacity an Error of `ErrorType::UsageError` will be returned.
354 ///
355 /// Corresponds to [`s2n_client_hello_get_fingerprint_string`].
356 #[deprecated = "Users should prefer the Fingerprint::raw() method"]
357 pub fn fingerprint_string(
358 &self,
359 hash: FingerprintType,
360 output: &mut String,
361 ) -> Result<(), Error> {
362 let mut output_size = 0;
363 unsafe {
364 s2n_tls_sys::s2n_client_hello_get_fingerprint_string(
365 self.deref_mut_ptr(),
366 hash.into(),
367 output.capacity() as u32,
368 output.as_mut_ptr(),
369 &mut output_size,
370 )
371 .into_result()?;
372 // SAFETY: update internal state of string to match the data written
373 // into it.
374 output.as_mut_vec().set_len(output_size as usize);
375 };
376 Ok(())
377 }
378 }
379
380 #[cfg(test)]
381 mod tests {
382 use super::*;
383 use crate::{
384 error::ErrorType,
385 security,
386 security::Policy,
387 testing::{build_config, TestPair},
388 };
389 use std::{collections::HashSet, error::Error};
390
391 const CLIENT_HELLO_BYTES: &[u8] = &[
392 0x01, 0x00, 0x00, 0xEC, 0x03, 0x03, 0x90, 0xe8, 0xcc, 0xee, 0xe5, 0x70, 0xa2, 0xa1, 0x2f,
393 0x6b, 0x69, 0xd2, 0x66, 0x96, 0x0f, 0xcf, 0x20, 0xd5, 0x32, 0x6e, 0xc4, 0xb2, 0x8c, 0xc7,
394 0xbd, 0x0a, 0x06, 0xc2, 0xa5, 0x14, 0xfc, 0x34, 0x20, 0xaf, 0x72, 0xbf, 0x39, 0x99, 0xfb,
395 0x20, 0x70, 0xc3, 0x10, 0x83, 0x0c, 0xee, 0xfb, 0xfa, 0x72, 0xcc, 0x5d, 0xa8, 0x99, 0xb4,
396 0xc5, 0x53, 0xd6, 0x3d, 0xa0, 0x53, 0x7a, 0x5c, 0xbc, 0xf5, 0x0b, 0x00, 0x1e, 0xc0, 0x2b,
397 0xc0, 0x2f, 0xcc, 0xa9, 0xcc, 0xa8, 0xc0, 0x2c, 0xc0, 0x30, 0xc0, 0x0a, 0xc0, 0x09, 0xc0,
398 0x13, 0xc0, 0x14, 0x00, 0x33, 0x00, 0x39, 0x00, 0x2f, 0x00, 0x35, 0x00, 0x0a, 0x01, 0x00,
399 0x00, 0x85, 0x00, 0x00, 0x00, 0x23, 0x00, 0x21, 0x00, 0x00, 0x1e, 0x69, 0x6e, 0x63, 0x6f,
400 0x6d, 0x69, 0x6e, 0x67, 0x2e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e,
401 0x6d, 0x6f, 0x7a, 0x69, 0x6c, 0x6c, 0x61, 0x2e, 0x6f, 0x72, 0x67, 0x00, 0x17, 0x00, 0x00,
402 0xff, 0x01, 0x00, 0x01, 0x00, 0x00, 0x0a, 0x00, 0x0a, 0x00, 0x08, 0x00, 0x1d, 0x00, 0x17,
403 0x00, 0x18, 0x00, 0x19, 0x00, 0x0b, 0x00, 0x02, 0x01, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00,
404 0x10, 0x00, 0x0e, 0x00, 0x0c, 0x02, 0x68, 0x32, 0x08, 0x68, 0x74, 0x74, 0x70, 0x2f, 0x31,
405 0x2e, 0x31, 0x00, 0x05, 0x00, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x18,
406 0x00, 0x16, 0x04, 0x03, 0x05, 0x03, 0x06, 0x03, 0x08, 0x04, 0x08, 0x05, 0x08, 0x06, 0x04,
407 0x01, 0x05, 0x01, 0x06, 0x01, 0x02, 0x03, 0x02, 0x01, 0x00, 0x1c, 0x00, 0x02, 0x40, 0x00,
408 ];
409 const JA3_FULL_STRING: &str = "771,49195-49199-52393-52392-49196-49200-\
410 49162-49161-49171-49172-51-57-47-53-10,0-\
411 23-65281-10-11-35-16-5-13-28,29-23-24-25,0";
412 const JA3_HASH: &str = "839bbe3ed07fed922ded5aaf714d6842";
413
414 fn simple_handshake() -> Result<TestPair, Box<dyn Error>> {
415 let config = build_config(&security::DEFAULT)?;
416 let mut pair = TestPair::from_config(&config);
417 pair.handshake()?;
418 Ok(pair)
419 }
420
421 #[test]
422 fn connection_fingerprint() -> Result<(), Box<dyn Error>> {
423 let pair = simple_handshake()?;
424 let client_hello = pair.server.client_hello()?;
425
426 let mut builder = Fingerprint::builder(FingerprintType::JA3)?;
427 let mut fingerprint = builder.build(client_hello)?;
428
429 let hash_size = fingerprint.hash_size()?;
430 let hash = fingerprint.hash()?;
431 assert_eq!(hash.len(), hash_size);
432 hex::decode(hash)?;
433
434 let raw_size = fingerprint.raw_size()?;
435 let raw = fingerprint.raw()?;
436 assert_eq!(raw.len(), raw_size);
437
438 Ok(())
439 }
440
441 #[test]
442 fn known_value() -> Result<(), Box<dyn Error>> {
443 let client_hello = ClientHello::parse_client_hello(CLIENT_HELLO_BYTES)?;
444
445 let mut builder = Fingerprint::builder(FingerprintType::JA3)?;
446 let mut fingerprint = builder.build(&client_hello)?;
447
448 let hash_size = fingerprint.hash_size()?;
449 let hash = fingerprint.hash()?;
450 assert_eq!(hash.len(), hash_size);
451 assert_eq!(hash, JA3_HASH);
452
453 let raw_size = fingerprint.raw_size()?;
454 let raw = fingerprint.raw()?;
455 assert_eq!(raw.len(), raw_size);
456 assert_eq!(raw, JA3_FULL_STRING);
457
458 Ok(())
459 }
460
461 #[test]
462 fn multiple_fingerprints() -> Result<(), Box<dyn Error>> {
463 let mut builder = Fingerprint::builder(FingerprintType::JA3)?;
464
465 for _ in 1..10 {
466 let client_hello = ClientHello::parse_client_hello(CLIENT_HELLO_BYTES)?;
467 let mut fingerprint = builder.build(&client_hello)?;
468
469 let hash = fingerprint.hash()?;
470 assert_eq!(hash, JA3_HASH);
471 }
472
473 Ok(())
474 }
475
476 #[test]
477 fn multiple_fingerprints_reset() -> Result<(), Box<dyn Error>> {
478 let mut builder = Fingerprint::builder(FingerprintType::JA3)?;
479 let client_hello = ClientHello::parse_client_hello(CLIENT_HELLO_BYTES)?;
480
481 {
482 let mut fingerprint = builder.build(&client_hello)?;
483
484 // Before hash is called, there is no raw size
485 fingerprint
486 .raw_size()
487 .expect_err("Raw size unexpectedly set");
488
489 // After hash is called, there is a raw size
490 fingerprint.hash()?;
491 fingerprint.raw_size()?;
492 }
493
494 // Build another fingerprint with the same builder
495 let client_hello = ClientHello::parse_client_hello(CLIENT_HELLO_BYTES)?;
496 let fingerprint = builder.build(&client_hello)?;
497
498 // If the fingerprint state was properly reset, there is no raw size again
499 fingerprint
500 .raw_size()
501 .expect_err("Fingerprint state not reset");
502
503 Ok(())
504 }
505
506 #[test]
507 fn multiple_connection_fingerprints() -> Result<(), Box<dyn Error>> {
508 let mut builder = Fingerprint::builder(FingerprintType::JA3)?;
509 // Use a good variety of security policies
510 let configs = [
511 build_config(&Policy::from_version("20240501")?)?,
512 build_config(&Policy::from_version("20240502")?)?,
513 build_config(&Policy::from_version("20240503")?)?,
514 build_config(&Policy::from_version("test_all")?)?,
515 ];
516 let mut fingerprints: Vec<String> = Vec::new();
517
518 let handshake_count = configs.len() * 5;
519 for i in 0..handshake_count {
520 let i = i % configs.len();
521
522 let config = &configs[i];
523 let mut pair = TestPair::from_config(config);
524 pair.handshake()?;
525
526 let client_hello = pair.server.client_hello()?;
527 let mut fingerprint = builder.build(client_hello)?;
528
529 let hash = fingerprint.hash()?;
530 hex::decode(hash)?;
531
532 // Verify that the same config produces the same fingerprint
533 if let Some(previous) = fingerprints.get(i) {
534 assert_eq!(previous.as_str(), hash);
535 } else {
536 fingerprints.push(hash.to_string());
537 }
538 }
539 assert_eq!(configs.len(), fingerprints.len());
540
541 // Verify that we actually tested different unique fingerprints
542 let unique: HashSet<&String> = HashSet::from_iter(fingerprints.iter());
543 assert_eq!(unique.len(), fingerprints.len());
544
545 Ok(())
546 }
547
548 #[test]
549 fn raw_sufficient_memory() -> Result<(), Box<dyn Error>> {
550 let client_hello = ClientHello::parse_client_hello(CLIENT_HELLO_BYTES)?;
551
552 let mut builder = Fingerprint::builder(FingerprintType::JA3)?;
553 builder.set_raw_size(JA3_FULL_STRING.len())?;
554
555 let mut fingerprint = builder.build(&client_hello)?;
556 let raw = fingerprint.raw()?;
557 assert_eq!(raw, JA3_FULL_STRING);
558
559 Ok(())
560 }
561
562 #[test]
563 fn raw_insufficient_memory() -> Result<(), Box<dyn Error>> {
564 let client_hello = ClientHello::parse_client_hello(CLIENT_HELLO_BYTES)?;
565
566 let mut builder = Fingerprint::builder(FingerprintType::JA3)?;
567 builder.set_raw_size(JA3_FULL_STRING.len() - 1)?;
568
569 let mut fingerprint = builder.build(&client_hello)?;
570 let error = fingerprint
571 .raw()
572 .expect_err("Calculated raw string despite insufficient memory");
573 assert_eq!(error.kind(), ErrorType::UsageError);
574 assert_eq!(error.name(), "S2N_ERR_INSUFFICIENT_MEM_SIZE");
575
576 Ok(())
577 }
578
579 #[test]
580 fn hash_does_not_allocate_memory() -> Result<(), Box<dyn Error>> {
581 let client_hello = ClientHello::parse_client_hello(CLIENT_HELLO_BYTES)?;
582
583 let mut builder = Fingerprint::builder(FingerprintType::JA3)?;
584
585 for _ in 0..10 {
586 let snapshot = checkers::with(|| {
587 let mut fingerprint = builder.build(&client_hello).unwrap();
588 fingerprint.hash().unwrap();
589 });
590 assert!(snapshot.events.is_empty());
591 }
592
593 Ok(())
594 }
595
596 #[test]
597 fn raw_may_allocate_memory() -> Result<(), Box<dyn Error>> {
598 let client_hello = ClientHello::parse_client_hello(CLIENT_HELLO_BYTES)?;
599
600 let mut builder = Fingerprint::builder(FingerprintType::JA3)?;
601
602 let minimum_size = JA3_FULL_STRING.len();
603 let large_size = minimum_size + 100;
604
605 // If we want to allocate the known value of the raw string,
606 // then that allocation must happen when raw() is called rather than
607 // when the fingerprint is built.
608 let snapshot = checkers::with(|| {
609 let mut fingerprint = builder.build(&client_hello).unwrap();
610 // Calculating the hash is necessary to calculate the raw_size,
611 // But the hash_does_not_allocate_memory test proves this does not
612 // allocate any memory.
613 fingerprint.hash().unwrap();
614
615 fingerprint.raw().unwrap();
616 });
617 // Expect a single allocation to allocate the raw string
618 assert_eq!(snapshot.events.allocs(), 1);
619 assert_eq!(snapshot.events.reallocs(), 0);
620 assert_eq!(snapshot.events.frees(), 0);
621 assert_eq!(snapshot.events.max_memory_used().unwrap(), minimum_size);
622
623 // Snapshots must be cumulative to accurately track total allocations,
624 // so keep track of the current snapshot.
625 let mut full_snapshot = snapshot;
626
627 // Expect that repeating either the build or the calculation does not
628 // lead to any new allocations.
629 let snapshot = checkers::with(|| {
630 for _ in 0..10 {
631 let mut fingerprint = builder.build(&client_hello).unwrap();
632 // Calculating the hash is necessary to calculate the raw_size,
633 // But the hash_does_not_allocate_memory test proves this does not
634 // allocate any memory.
635 fingerprint.hash().unwrap();
636
637 for _ in 0..10 {
638 fingerprint.raw().unwrap();
639 }
640 }
641 });
642 assert!(snapshot.events.is_empty());
643
644 // If we set a larger raw size on the builder,
645 // then the raw string is reallocated.
646 let snapshot = checkers::with(|| {
647 builder.set_raw_size(large_size).unwrap();
648 });
649 assert_eq!(snapshot.events.allocs(), 0);
650 assert_eq!(snapshot.events.reallocs(), 1);
651 assert_eq!(snapshot.events.frees(), 0);
652
653 // Snapshots must be cumulative to accurately track total allocations,
654 // so add the new snapshot events.
655 for event in snapshot.events.as_slice() {
656 full_snapshot.events.push(event.clone());
657 }
658 // The new total memory should be the larger size we set on the builder.
659 assert_eq!(full_snapshot.events.max_memory_used().unwrap(), large_size);
660
661 // If the raw size was set on the builder, then the raw string is not
662 // allocated when raw() is called.
663 let snapshot = checkers::with(|| {
664 let mut fingerprint = builder.build(&client_hello).unwrap();
665 fingerprint.raw().unwrap();
666 });
667 assert!(snapshot.events.is_empty());
668
669 // If we set a smaller raw size on the builder,
670 // then the raw string is not reallocated.
671 let snapshot = checkers::with(|| {
672 builder.set_raw_size(minimum_size).unwrap();
673 });
674 assert!(snapshot.events.is_empty());
675
676 // Recalculating the raw string does not reallocate the raw string
677 let snapshot = checkers::with(|| {
678 for _ in 0..10 {
679 let mut fingerprint = builder.build(&client_hello).unwrap();
680 fingerprint.raw().unwrap();
681 }
682 });
683 assert!(snapshot.events.is_empty());
684
685 Ok(())
686 }
687
688 #[test]
689 #[allow(deprecated)]
690 fn legacy_connection_fingerprint() -> Result<(), Box<dyn Error>> {
691 let pair = simple_handshake()?;
692 let client_hello = pair.server.client_hello()?;
693
694 let mut hash = Vec::with_capacity(MD5_HASH_SIZE.try_into()?);
695 let str_size = client_hello.fingerprint_hash(FingerprintType::JA3, &mut hash)?;
696 assert_eq!(hash.len(), MD5_HASH_SIZE.try_into()?);
697
698 let mut full_str = String::with_capacity(str_size.try_into()?);
699 client_hello.fingerprint_string(FingerprintType::JA3, &mut full_str)?;
700 assert_eq!(full_str.len(), str_size.try_into()?);
701
702 Ok(())
703 }
704
705 #[test]
706 #[allow(deprecated)]
707 fn legacy_known_value() -> Result<(), Box<dyn Error>> {
708 let client_hello = ClientHello::parse_client_hello(CLIENT_HELLO_BYTES)?;
709
710 let mut hash = Vec::with_capacity(MD5_HASH_SIZE.try_into()?);
711 let str_size = client_hello.fingerprint_hash(FingerprintType::JA3, &mut hash)?;
712 assert_eq!(hash.len(), MD5_HASH_SIZE.try_into()?);
713 assert_eq!(hash, hex::decode(JA3_HASH)?);
714
715 let mut full_str = String::with_capacity(str_size.try_into()?);
716 client_hello.fingerprint_string(FingerprintType::JA3, &mut full_str)?;
717 assert_eq!(full_str.len(), str_size.try_into()?);
718 assert_eq!(full_str, JA3_FULL_STRING);
719
720 Ok(())
721 }
722
723 #[test]
724 #[allow(deprecated)]
725 fn legacy_hash_output_resizing() -> Result<(), Box<dyn Error>> {
726 let client_hello = ClientHello::parse_client_hello(CLIENT_HELLO_BYTES)?;
727 let hash_capacities = vec![0, MD5_HASH_SIZE, 1_000];
728 for initial_size in hash_capacities {
729 let mut hash = Vec::with_capacity(initial_size.try_into()?);
730 client_hello.fingerprint_hash(FingerprintType::JA3, &mut hash)?;
731 assert_eq!(hash.len(), MD5_HASH_SIZE.try_into()?);
732 }
733 Ok(())
734 }
735
736 #[test]
737 #[allow(deprecated)]
738 fn legacy_string_output_too_small() -> Result<(), Box<dyn Error>> {
739 let client_hello = ClientHello::parse_client_hello(CLIENT_HELLO_BYTES)?;
740 let mut fingerprint_string = String::with_capacity(JA3_FULL_STRING.len() - 1);
741 let fingerprint_err = client_hello
742 .fingerprint_string(FingerprintType::JA3, &mut fingerprint_string)
743 .unwrap_err();
744 assert_eq!(fingerprint_err.kind(), ErrorType::UsageError);
745 assert_eq!(fingerprint_err.name(), "S2N_ERR_INSUFFICIENT_MEM_SIZE");
746 Ok(())
747 }
748 }