Debian Codegraph @

crt/s2n/bindings/rust/standard/s2n-tls-metrics-subscriber/src/record.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 use std::{
5 sync::atomic::{AtomicU64, Ordering},
6 time::SystemTime,
7 };
8
9 use s2n_tls_metrics_schema::{
10 record::FrozenHandshakeRecord,
11 static_lists::{
12 Alert, CERT_KEY_COUNT, CERT_SIG_COUNT, CIPHER_COUNT, CertKeyType, CertSignatureAlgorithm,
13 Cipher, DEFINED_ALERTS_COUNT, GROUP_COUNT, Group, PROTOCOL_COUNT, SIGNATURE_COUNT,
14 Signature, Version,
15 },
16 };
17
18 use crate::{
19 bounded_set::BoundedStringSet,
20 compatibility::{Cnsa1, Cnsa2, Fips20251201, General20251201, TlsProfile},
21 counter::Counter,
22 detector::SyntheticTrafficDetector,
23 parsing::{self, ClientHelloSupportedParameters},
24 };
25
26 fn protocol_version_to_iana(v: s2n_tls::enums::Version) -> Option<Version> {
27 let iana = match v {
28 s2n_tls::enums::Version::SSLV3 => 0x0300u16,
29 s2n_tls::enums::Version::TLS10 => 0x0301,
30 s2n_tls::enums::Version::TLS11 => 0x0302,
31 s2n_tls::enums::Version::TLS12 => 0x0303,
32 s2n_tls::enums::Version::TLS13 => 0x0304,
33 _ => return None,
34 };
35 Some(Version(s2n_codec::zerocopy::U16::new(iana)))
36 }
37
38 /// The HandshakeRecordInProgress stores the in-flight counters for handshake
39 /// information - e.g. negotiated parameters.
40 #[derive(Debug)]
41 pub(crate) struct HandshakeRecordInProgress {
42 /// This is used to send a frozen version back to the Aggregator, after which
43 /// point it can be exported. This is only used in the drop impl.
44 exporter: std::sync::mpsc::Sender<FrozenHandshakeRecord>,
45
46 security_policies: BoundedStringSet,
47
48 /// the total number of handshakes that this record represents.
49 handshake_success_count: AtomicU64,
50
51 /// the total number of failed handshakes
52 handshake_failure_count: AtomicU64,
53 alerts: Counter<DEFINED_ALERTS_COUNT, Alert>,
54
55 negotiated_protocols: Counter<PROTOCOL_COUNT, Version>,
56 negotiated_ciphers: Counter<CIPHER_COUNT, Cipher>,
57 negotiated_groups: Counter<GROUP_COUNT, Group>,
58 negotiated_signatures: Counter<SIGNATURE_COUNT, Signature>,
59
60 // we do not attempt to detect supported parameters for SSLv2 formatted client
61 // hellos
62 sslv2_client_hello: AtomicU64,
63 supported_protocols: Counter<PROTOCOL_COUNT, Version>,
64 supported_ciphers: Counter<CIPHER_COUNT, Cipher>,
65 supported_groups: Counter<GROUP_COUNT, Group>,
66 supported_signatures: Counter<SIGNATURE_COUNT, Signature>,
67
68 // chain counters will increment for both the ICA and the CA
69 server_leaf_cert_key: Counter<CERT_KEY_COUNT, CertKeyType>,
70 server_leaf_cert_sig: Counter<CERT_SIG_COUNT, CertSignatureAlgorithm>,
71 server_chain_cert_key: Counter<CERT_KEY_COUNT, CertKeyType>,
72 server_chain_cert_sig: Counter<CERT_SIG_COUNT, CertSignatureAlgorithm>,
73 client_leaf_cert_key: Counter<CERT_KEY_COUNT, CertKeyType>,
74 client_leaf_cert_sig: Counter<CERT_SIG_COUNT, CertSignatureAlgorithm>,
75 client_chain_cert_key: Counter<CERT_KEY_COUNT, CertKeyType>,
76 client_chain_cert_sig: Counter<CERT_SIG_COUNT, CertSignatureAlgorithm>,
77 /// indicates a parsing error in the metrics subscriber der codec
78 server_cert_parsing_failure: AtomicU64,
79 client_cert_parsing_failure: AtomicU64,
80
81 compatibility_general20251201: AtomicU64,
82 compatibility_fips20251201: AtomicU64,
83 compatibility_cnsa1: AtomicU64,
84 compatibility_cnsa2: AtomicU64,
85
86 /// sum of handshake duration, including network latency and waiting
87 ///
88 /// To get the average, divide this by handshake_success_count.
89 handshake_duration_us: AtomicU64,
90 /// sum of handshake compute
91 ///
92 /// To get the average, divide this by handshake_success_count.
93 handshake_compute_us: AtomicU64,
94
95 /// Number of handshakes flagged by the configured
96 /// [`SyntheticTrafficDetector`]. Synthetic handshakes are excluded from
97 /// every other counter on this record (including `handshake_success_count`).
98 synthetic_traffic_count: AtomicU64,
99 }
100
101 impl HandshakeRecordInProgress {
102 pub fn new(exporter: std::sync::mpsc::Sender<FrozenHandshakeRecord>) -> Self {
103 Self {
104 security_policies: Default::default(),
105 handshake_success_count: Default::default(),
106 handshake_failure_count: Default::default(),
107 alerts: Counter::new(),
108
109 negotiated_groups: Counter::new(),
110 negotiated_ciphers: Counter::new(),
111 negotiated_protocols: Counter::new(),
112 negotiated_signatures: Counter::new(),
113
114 sslv2_client_hello: Default::default(),
115 supported_groups: Counter::new(),
116 supported_ciphers: Counter::new(),
117 supported_protocols: Counter::new(),
118 supported_signatures: Counter::new(),
119
120 server_leaf_cert_key: Counter::new(),
121 server_leaf_cert_sig: Counter::new(),
122 server_chain_cert_key: Counter::new(),
123 server_chain_cert_sig: Counter::new(),
124 client_leaf_cert_key: Counter::new(),
125 client_leaf_cert_sig: Counter::new(),
126 client_chain_cert_key: Counter::new(),
127 client_chain_cert_sig: Counter::new(),
128 server_cert_parsing_failure: Default::default(),
129 client_cert_parsing_failure: Default::default(),
130
131 compatibility_general20251201: AtomicU64::default(),
132 compatibility_fips20251201: AtomicU64::default(),
133 compatibility_cnsa1: AtomicU64::default(),
134 compatibility_cnsa2: AtomicU64::default(),
135
136 handshake_duration_us: Default::default(),
137 handshake_compute_us: Default::default(),
138 synthetic_traffic_count: Default::default(),
139 exporter,
140 }
141 }
142
143 pub fn update(
144 &self,
145 conn: &s2n_tls::connection::Connection,
146 event: &s2n_tls::events::HandshakeEvent,
147 detector: Option<&dyn SyntheticTrafficDetector>,
148 ) -> Result<(), Box<dyn std::error::Error>> {
149 // client_hello is only available on the server side of the connection
150 let client_hello = if conn.mode() == s2n_tls::enums::Mode::Server {
151 Some(conn.client_hello()?)
152 } else {
153 None
154 };
155
156 // Run the detector first, on every handshake (including SSLv2).
157 // Synthetic handshakes contribute ONLY to `synthetic_traffic_count`;
158 // every other counter (including `handshake_success_count`) reflects real
159 // traffic only, so consumers can read each metric directly without
160 // post-processing.
161 if let Some(detector) = detector {
162 if let Some(client_hello) = client_hello {
163 if detector.is_synthetic(client_hello) {
164 self.synthetic_traffic_count.fetch_add(1, Ordering::Relaxed);
165 return Ok(());
166 }
167 }
168 }
169
170 let success = match event.result() {
171 s2n_tls::events::HandshakeResult::Failure(_) => {
172 self.handshake_failure_count.fetch_add(1, Ordering::Relaxed);
173 let alert = conn.alert().map(Alert);
174 if let Some(alert) = alert {
175 self.alerts.increment(&alert);
176 }
177 return Ok(());
178 }
179 s2n_tls::events::HandshakeResult::Success(s) => {
180 self.handshake_success_count.fetch_add(1, Ordering::Relaxed);
181 s
182 }
183 };
184
185 self.security_policies.record(event.security_policy_label());
186
187 if let Some(client_hello) = client_hello {
188 if conn.client_hello_is_sslv2()? {
189 self.sslv2_client_hello.fetch_add(1, Ordering::Relaxed);
190 } else {
191 let supported_parameter = ClientHelloSupportedParameters::new(client_hello)?;
192
193 supported_parameter
194 .supported_versions()
195 .iter()
196 .for_each(|version| self.supported_protocols.increment(version));
197
198 supported_parameter
199 .supported_ciphers()
200 .iter()
201 .for_each(|cipher| self.supported_ciphers.increment(cipher));
202
203 supported_parameter
204 .supported_groups()
205 .iter()
206 .flat_map(|groups| groups.iter())
207 .for_each(|group| self.supported_groups.increment(group));
208
209 supported_parameter
210 .supported_signatures()
211 .iter()
212 .flat_map(|sigs| sigs.iter())
213 .for_each(|signature| self.supported_signatures.increment(signature));
214
215 if General20251201::supported(&supported_parameter) {
216 self.compatibility_general20251201
217 .fetch_add(1, Ordering::Relaxed);
218 }
219 if Fips20251201::supported(&supported_parameter) {
220 self.compatibility_fips20251201
221 .fetch_add(1, Ordering::Relaxed);
222 }
223 if Cnsa1::supported(&supported_parameter) {
224 self.compatibility_cnsa1.fetch_add(1, Ordering::Relaxed);
225 }
226 if Cnsa2::supported(&supported_parameter) {
227 self.compatibility_cnsa2.fetch_add(1, Ordering::Relaxed);
228 }
229 }
230 }
231
232 // populate cert metrics
233 {
234 fn record_chain_metrics<'a>(
235 mut certs: impl Iterator<
236 Item = Result<s2n_tls::cert_chain::Certificate<'a>, s2n_tls::error::Error>,
237 >,
238 leaf_key: &Counter<CERT_KEY_COUNT, CertKeyType>,
239 leaf_sig: &Counter<CERT_SIG_COUNT, CertSignatureAlgorithm>,
240 chain_key: &Counter<CERT_KEY_COUNT, CertKeyType>,
241 chain_sig: &Counter<CERT_SIG_COUNT, CertSignatureAlgorithm>,
242 parse_failures: &AtomicU64,
243 ) {
244 if let Some(Ok(cert)) = certs.next() {
245 if let Ok(der) = cert.der() {
246 match parsing::cert::parse(der) {
247 Ok(c) => {
248 leaf_key.increment(&c.key_type);
249 leaf_sig.increment(&c.signature);
250 }
251 Err(_) => {
252 parse_failures.fetch_add(1, Ordering::Relaxed);
253 }
254 }
255 }
256 }
257 for cert in certs.flatten() {
258 if let Ok(der) = cert.der() {
259 match parsing::cert::parse(der) {
260 Ok(c) => {
261 chain_key.increment(&c.key_type);
262 chain_sig.increment(&c.signature);
263 }
264 Err(_) => {
265 parse_failures.fetch_add(1, Ordering::Relaxed);
266 }
267 }
268 }
269 }
270 }
271
272 // selected_cert() is the local cert; peer_cert_chain() is the remote cert.
273 // Map to server/client labels based on connection mode.
274 let (server_cert, client_cert) = match conn.mode() {
275 s2n_tls::enums::Mode::Server => (conn.selected_cert(), conn.peer_cert_chain().ok()),
276 s2n_tls::enums::Mode::Client => (conn.peer_cert_chain().ok(), conn.selected_cert()),
277 };
278
279 if let Some(cert) = server_cert {
280 record_chain_metrics(
281 cert.iter(),
282 &self.server_leaf_cert_key,
283 &self.server_leaf_cert_sig,
284 &self.server_chain_cert_key,
285 &self.server_chain_cert_sig,
286 &self.server_cert_parsing_failure,
287 );
288 }
289
290 if let Some(cert) = client_cert {
291 record_chain_metrics(
292 cert.iter(),
293 &self.client_leaf_cert_key,
294 &self.client_leaf_cert_sig,
295 &self.client_chain_cert_key,
296 &self.client_chain_cert_sig,
297 &self.client_cert_parsing_failure,
298 );
299 }
300 }
301
302 // populate negotiation parameters
303 {
304 if let Some(version) = protocol_version_to_iana(success.protocol_version()) {
305 self.negotiated_protocols.increment(&version);
306 }
307
308 if let Some(cipher) = Cipher::from_openssl_name(success.cipher()) {
309 self.negotiated_ciphers.increment(&cipher);
310 }
311
312 if let Some(group) = success.group().and_then(|g| g.parse().ok()) {
313 self.negotiated_groups.increment(&group);
314 }
315
316 if let Some(sig) = conn.signature_scheme().and_then(|s| s.parse().ok()) {
317 self.negotiated_signatures.increment(&sig);
318 }
319 }
320
321 // accuracy: as long as the handshake took less than 500,000 years
322 // this cast will not truncate. We prefer truncation/less accurate metrics
323 // over a panic.
324 self.handshake_compute_us.fetch_add(
325 event.synchronous_time().as_micros() as u64,
326 Ordering::Relaxed,
327 );
328 self.handshake_duration_us
329 .fetch_add(event.duration().as_micros() as u64, Ordering::Relaxed);
330
331 Ok(())
332 }
333
334 /// make a copy of this record to be exported.
335 ///
336 /// ### A Note On Ordering Correctness
337 ///
338 /// It is important that this function observes the results of all the `fetch_add`
339 /// operations on other threads.
340 ///
341 /// Simple Intuition: This function takes a `&mut`. Therefore the rust compiler
342 /// enforces that there are no other references to this memory and there isn't
343 /// anything to actually synchronize. So a Relaxed load is fine.
344 fn finish(&mut self) -> FrozenHandshakeRecord {
345 FrozenHandshakeRecord {
346 freeze_time: SystemTime::now(),
347 handshake_success_count: self.handshake_success_count.load(Ordering::Relaxed),
348 handshake_failure_count: self.handshake_failure_count.load(Ordering::Relaxed),
349 alerts: self.alerts.freeze(),
350 negotiated_protocols: self.negotiated_protocols.freeze(),
351 negotiated_ciphers: self.negotiated_ciphers.freeze(),
352 negotiated_groups: self.negotiated_groups.freeze(),
353 negotiated_signatures: self.negotiated_signatures.freeze(),
354
355 sslv2_client_hello: self.sslv2_client_hello.load(Ordering::Relaxed),
356 supported_protocols: self.supported_protocols.freeze(),
357 supported_ciphers: self.supported_ciphers.freeze(),
358 supported_groups: self.supported_groups.freeze(),
359 supported_signatures: self.supported_signatures.freeze(),
360
361 server_leaf_cert_key: self.server_leaf_cert_key.freeze(),
362 server_leaf_cert_sig: self.server_leaf_cert_sig.freeze(),
363 server_chain_cert_key: self.server_chain_cert_key.freeze(),
364 server_chain_cert_sig: self.server_chain_cert_sig.freeze(),
365 client_leaf_cert_key: self.client_leaf_cert_key.freeze(),
366 client_leaf_cert_sig: self.client_leaf_cert_sig.freeze(),
367 client_chain_cert_key: self.client_chain_cert_key.freeze(),
368 client_chain_cert_sig: self.client_chain_cert_sig.freeze(),
369 server_cert_parsing_failure: self.server_cert_parsing_failure.load(Ordering::Relaxed),
370 client_cert_parsing_failure: self.client_cert_parsing_failure.load(Ordering::Relaxed),
371
372 compatibility_general20251201: self
373 .compatibility_general20251201
374 .load(Ordering::Relaxed),
375 compatibility_fips20251201: self.compatibility_fips20251201.load(Ordering::Relaxed),
376 compatibility_cnsa1: self.compatibility_cnsa1.load(Ordering::Relaxed),
377 compatibility_cnsa2: self.compatibility_cnsa2.load(Ordering::Relaxed),
378
379 handshake_duration_us: self.handshake_duration_us.load(Ordering::Relaxed),
380 handshake_compute_us: self.handshake_compute_us.load(Ordering::Relaxed),
381 synthetic_traffic_count: self.synthetic_traffic_count.load(Ordering::Relaxed),
382 security_policies: self.security_policies.freeze(),
383 }
384 }
385 }
386
387 impl Drop for HandshakeRecordInProgress {
388 fn drop(&mut self) {
389 let frozen = self.finish();
390 // no available way to report error
391 let _ = self.exporter.send(frozen);
392 }
393 }
394
395 #[cfg(test)]
396 mod tests {
397 use crate::test_utils::{ARBITRARY_POLICY_1, TestEndpoint};
398 use s2n_tls_metrics_schema::{
399 counter::FrozenCounter,
400 static_lists::{Cipher, FiniteCounter},
401 };
402
403 use super::*;
404
405 #[test]
406 fn record_contents_negotiated_parameters() {
407 let endpoint = TestEndpoint::new();
408
409 let result = endpoint.client_handshake(&ARBITRARY_POLICY_1);
410 endpoint.subscriber.finish_record();
411 let records = endpoint.sink.records.lock().unwrap();
412 let record = &records[0].as_schema().handshake;
413
414 assert_eq!(record.handshake_success_count, 1);
415 assert_eq!(
416 record
417 .negotiated_ciphers
418 .iter_non_zero()
419 .map(|(_, _, c)| c)
420 .sum::<u64>(),
421 1
422 );
423 assert_eq!(
424 record
425 .negotiated_groups
426 .iter_non_zero()
427 .map(|(_, _, c)| c)
428 .sum::<u64>(),
429 1
430 );
431 assert_eq!(
432 record
433 .negotiated_signatures
434 .iter_non_zero()
435 .map(|(_, _, c)| c)
436 .sum::<u64>(),
437 1
438 );
439 assert_eq!(
440 record
441 .negotiated_protocols
442 .iter_non_zero()
443 .map(|(_, _, c)| c)
444 .sum::<u64>(),
445 1
446 );
447
448 let expected_version_element =
449 protocol_version_to_iana(result.client.actual_protocol_version().unwrap()).unwrap();
450 let slot = expected_version_element.slot_from_key().unwrap();
451 assert_eq!(record.negotiated_protocols.slots()[slot], 1);
452
453 let expected_cipher = result.client.cipher_suite().unwrap().to_owned();
454 let expected_cipher_element = Cipher::from_openssl_name(expected_cipher.as_str()).unwrap();
455 let slot = expected_cipher_element.slot_from_key().unwrap();
456 assert_eq!(record.negotiated_ciphers.slots()[slot], 1);
457
458 let expected_group = result
459 .client
460 .selected_key_exchange_group()
461 .unwrap()
462 .to_owned();
463 let expected_group_element: Group = expected_group.parse().unwrap();
464 let slot = expected_group_element.slot_from_key().unwrap();
465 assert_eq!(record.negotiated_groups.slots()[slot], 1);
466
467 let expected_sig = result.client.signature_scheme().unwrap().to_owned();
468 let expected_sig_element: Signature = expected_sig.parse().unwrap();
469 let slot = expected_sig_element.slot_from_key().unwrap();
470 assert_eq!(record.negotiated_signatures.slots()[slot], 1);
471 }
472
473 #[test]
474 fn record_contents_supported_parameters() {
475 const EXPECTED_VERSIONS: &[&str] = &["TLSv1_3", "TLSv1_2"];
476 const EXPECTED_CIPHERS: &[&str] = &[
477 "TLS_AES_256_GCM_SHA384",
478 "TLS_AES_128_GCM_SHA256",
479 "TLS_CHACHA20_POLY1305_SHA256",
480 "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
481 "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
482 "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384",
483 "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
484 "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
485 "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
486 "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
487 "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",
488 "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
489 "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
490 ];
491 const EXPECTED_GROUPS: &[&str] = &["secp256r1", "secp384r1", "secp521r1", "x25519"];
492 const EXPECTED_SIGS: &[&str] = &[
493 "ecdsa_sha256",
494 "ecdsa_sha384",
495 "ecdsa_sha512",
496 "rsa_pkcs1_sha256",
497 "rsa_pkcs1_sha384",
498 "rsa_pkcs1_sha512",
499 "rsa_pss_rsae_sha256",
500 "rsa_pss_rsae_sha384",
501 "rsa_pss_rsae_sha512",
502 "rsa_pss_pss_sha256",
503 "rsa_pss_pss_sha384",
504 "rsa_pss_pss_sha512",
505 ];
506
507 let endpoint = TestEndpoint::new();
508
509 let _ = endpoint.client_handshake(&ARBITRARY_POLICY_1);
510 endpoint.subscriber.finish_record();
511 let records = endpoint.sink.records.lock().unwrap();
512 let record = &records[0].as_schema().handshake;
513
514 fn assert_supported_matches<const N: usize, T>(
515 counter: &FrozenCounter<N, T>,
516 expected: &[&str],
517 ) where
518 T: FiniteCounter<N> + std::fmt::Display + std::str::FromStr<Err = ()>,
519 {
520 let expected_slots: Vec<usize> = expected
521 .iter()
522 .map(|description| {
523 description
524 .parse::<T>()
525 .unwrap_or_else(|()| panic!("unknown description {description}"))
526 .slot_from_key()
527 .unwrap()
528 })
529 .collect();
530
531 for (slot, &count) in counter.slots().iter().enumerate() {
532 let name = T::key_from_slot(slot).unwrap();
533 if expected_slots.contains(&slot) {
534 assert_eq!(count, 1, "{name} count is {count}, not one");
535 } else {
536 assert_eq!(count, 0, "{name} count is {count}, not zero");
537 }
538 }
539 }
540
541 assert_supported_matches(&record.supported_protocols, EXPECTED_VERSIONS);
542 assert_supported_matches(&record.supported_ciphers, EXPECTED_CIPHERS);
543 assert_supported_matches(&record.supported_groups, EXPECTED_GROUPS);
544 assert_supported_matches(&record.supported_signatures, EXPECTED_SIGS);
545 }
546
547 #[test]
548 fn multiple_records() {
549 let endpoint = TestEndpoint::new();
550
551 endpoint.client_handshake(&ARBITRARY_POLICY_1);
552 endpoint.client_handshake(&ARBITRARY_POLICY_1);
553 endpoint.client_handshake(&ARBITRARY_POLICY_1);
554
555 endpoint.subscriber.finish_record();
556 let records = endpoint.sink.records.lock().unwrap();
557 let record = &records[0].as_schema().handshake;
558
559 assert_eq!(record.handshake_success_count, 3);
560 assert_eq!(
561 record
562 .negotiated_ciphers
563 .iter_non_zero()
564 .map(|(_, _, c)| c)
565 .sum::<u64>(),
566 3
567 );
568 assert_eq!(
569 record
570 .negotiated_groups
571 .iter_non_zero()
572 .map(|(_, _, c)| c)
573 .sum::<u64>(),
574 3
575 );
576 assert_eq!(
577 record
578 .negotiated_signatures
579 .iter_non_zero()
580 .map(|(_, _, c)| c)
581 .sum::<u64>(),
582 3
583 );
584 assert_eq!(
585 record
586 .negotiated_protocols
587 .iter_non_zero()
588 .map(|(_, _, c)| c)
589 .sum::<u64>(),
590 3
591 );
592 }
593
594 /// A record with no handshakes should be entirely empty/default.
595 #[test]
596 fn empty_record() {
597 let endpoint = TestEndpoint::new();
598
599 endpoint.subscriber.finish_record();
600 let records = endpoint.sink.records.lock().unwrap();
601 let mut record = records[0].as_schema().handshake.clone();
602
603 // ignore the freeze time, since that "default" value is set to the Unix Epoch.
604 record.freeze_time = SystemTime::UNIX_EPOCH;
605 assert_eq!(record, FrozenHandshakeRecord::default());
606 }
607
608 /// ARBITRARY_POLICY_1 (20240503 / default_tls13) should be compatible with
609 /// General, Fips, and Cnsa1 profiles, but not CNSA2 (which requires MLKEM1024
610 /// and mldsa87).
611 #[test]
612 fn record_contents_compatibility_metrics() {
613 let endpoint = TestEndpoint::new();
614
615 endpoint.client_handshake(&ARBITRARY_POLICY_1);
616 endpoint.subscriber.finish_record();
617 let records = endpoint.sink.records.lock().unwrap();
618 let record = &records[0].as_schema().handshake;
619
620 assert_eq!(record.compatibility_general20251201, 1);
621 assert_eq!(record.compatibility_fips20251201, 1);
622 assert_eq!(record.compatibility_cnsa1, 1);
623 assert_eq!(record.compatibility_cnsa2, 0);
624 }
625
626 #[test]
627 fn record_contents_security_policies() {
628 use s2n_tls::security::Policy;
629 use s2n_tls_metrics_schema::bounded_set::FrozenBoundedStringSet;
630 use std::ffi::CStr;
631
632 // a single handshake -> a single security policy
633 {
634 let endpoint = TestEndpoint::new();
635 endpoint.client_handshake(&ARBITRARY_POLICY_1);
636 endpoint.subscriber.finish_record();
637 let records = endpoint.sink.records.lock().unwrap();
638 let policies = &records[0].as_schema().handshake.security_policies;
639 match policies {
640 FrozenBoundedStringSet::Entries(set) => {
641 assert_eq!(set.len(), 1);
642 assert!(set.contains("default_tls13"));
643 }
644 FrozenBoundedStringSet::TooMany => panic!("expected Entries"),
645 }
646 }
647
648 // multiple handshakes shifting between two policies -> two policies recorded
649 {
650 let endpoint = TestEndpoint::new();
651 endpoint.client_handshake(&ARBITRARY_POLICY_1);
652
653 let policy_b = Policy::from_version("20240501").unwrap();
654 let client_config = s2n_tls::testing::build_config(&ARBITRARY_POLICY_1).unwrap();
655 let mut pair =
656 s2n_tls::testing::TestPair::from_configs(&client_config, &endpoint.server_config);
657 pair.server.set_security_policy(&policy_b).unwrap();
658 pair.handshake().unwrap();
659
660 endpoint.subscriber.finish_record();
661 let records = endpoint.sink.records.lock().unwrap();
662 let policies = &records[0].as_schema().handshake.security_policies;
663 match policies {
664 FrozenBoundedStringSet::Entries(set) => {
665 assert_eq!(set.len(), 2);
666 }
667 FrozenBoundedStringSet::TooMany => panic!("expected Entries"),
668 }
669 }
670
671 // more than 10 security policies -> TOO_MANY is recorded
672 {
673 let endpoint = TestEndpoint::new();
674 let client_config = s2n_tls::testing::build_config(&ARBITRARY_POLICY_1).unwrap();
675
676 let policies: Vec<Policy> = {
677 let mut seen = std::collections::HashSet::new();
678 let mut result = Vec::new();
679 for entry in s2n_tls_sys_internal::security_policy_table() {
680 // we need unique security policies (e.g. unique security policy
681 // pointers)
682 if !seen.insert(entry.security_policy as usize) {
683 continue;
684 }
685 let name = unsafe { CStr::from_ptr(entry.version) }.to_str().unwrap();
686 result.push(Policy::from_version(name).unwrap());
687 if result.len() > BoundedStringSet::MAX_STORAGE {
688 break;
689 }
690 }
691 result
692 };
693 assert_eq!(policies.len(), BoundedStringSet::MAX_STORAGE + 1);
694
695 for policy in &policies {
696 let mut pair = s2n_tls::testing::TestPair::from_configs(
697 &client_config,
698 &endpoint.server_config,
699 );
700 pair.server.set_security_policy(policy).unwrap();
701 pair.handshake().unwrap();
702 }
703
704 endpoint.subscriber.finish_record();
705 let records = endpoint.sink.records.lock().unwrap();
706 assert_eq!(
707 records[0].as_schema().handshake.security_policies,
708 FrozenBoundedStringSet::TooMany
709 );
710 }
711 }
712
713 /// Make sure that the compute time is less than the overall handshake time.
714 ///
715 /// Additionally, make sure that three handshakes takes longer than one handshake.
716 /// This provides some confidence that we are correctly e.g. adding amounts
717 #[test]
718 fn timers() {
719 let endpoint = TestEndpoint::new();
720
721 endpoint.client_handshake(&ARBITRARY_POLICY_1);
722 endpoint.subscriber.finish_record();
723 let records = endpoint.sink.records.lock().unwrap();
724 let single_handshake = &records[0].as_schema().handshake;
725
726 assert!(single_handshake.handshake_compute_us <= single_handshake.handshake_duration_us);
727 drop(records);
728
729 endpoint.client_handshake(&ARBITRARY_POLICY_1);
730 endpoint.client_handshake(&ARBITRARY_POLICY_1);
731 endpoint.client_handshake(&ARBITRARY_POLICY_1);
732 endpoint.subscriber.finish_record();
733 let records = endpoint.sink.records.lock().unwrap();
734 let single_handshake = &records[0].as_schema().handshake;
735 let multiple_handshakes = &records[1].as_schema().handshake;
736
737 assert!(
738 multiple_handshakes.handshake_compute_us <= multiple_handshakes.handshake_duration_us
739 );
740
741 assert!(single_handshake.handshake_compute_us < multiple_handshakes.handshake_compute_us);
742 assert!(single_handshake.handshake_duration_us < multiple_handshakes.handshake_duration_us);
743 }
744
745 /// Helper: performs an mTLS handshake using distinct cert types for server
746 /// (RSA 4096 / SHA384) and client (ECDSA P384 / SHA384) so the test can
747 /// distinguish which cert ended up in which record field.
748 mod mtls_helper {
749 use crate::{AggregatedMetricsSubscriber, Attribution, test_utils::VecSink};
750 use s2n_tls::{
751 enums::ClientAuthType,
752 security::DEFAULT_TLS13,
753 testing::{CertKeyPair, TestPair},
754 };
755
756 pub(super) struct MtlsEndpoint {
757 pub subscriber: AggregatedMetricsSubscriber<VecSink>,
758 pub sink: VecSink,
759 pub client_config: s2n_tls::config::Config,
760 pub server_config: s2n_tls::config::Config,
761 }
762
763 /// Server cert: RSA 4096 / SHA384
764 fn server_keypair() -> CertKeyPair {
765 CertKeyPair::from_path(
766 "permutations/rsae_pkcs_4096_sha384/",
767 "server-chain",
768 "server-key",
769 "ca-cert",
770 )
771 }
772
773 /// Client cert: ECDSA P384 / SHA384
774 fn client_keypair() -> CertKeyPair {
775 CertKeyPair::from_path(
776 "permutations/ec_ecdsa_p384_sha384/",
777 "client-cert",
778 "client-key",
779 "ca-cert",
780 )
781 }
782
783 /// Build an mTLS endpoint with the subscriber on the server side.
784 pub(super) fn server_endpoint() -> MtlsEndpoint {
785 let sink = VecSink::new();
786 let attribution = Attribution {
787 service: "test".to_owned(),
788 resource: "test".to_owned(),
789 component: "test".to_owned(),
790 };
791 let subscriber = AggregatedMetricsSubscriber::new(sink.clone(), attribution);
792
793 let server_keypair = server_keypair();
794 let client_keypair = client_keypair();
795
796 let server_config = {
797 let mut c = s2n_tls::config::Builder::new();
798 c.set_security_policy(&DEFAULT_TLS13)
799 .unwrap()
800 .load_pem(server_keypair.cert(), server_keypair.key())
801 .unwrap()
802 .trust_pem(client_keypair.ca_cert())
803 .unwrap()
804 .set_client_auth_type(ClientAuthType::Required)
805 .unwrap()
806 .set_event_subscriber(subscriber.clone())
807 .unwrap();
808 c.build().unwrap()
809 };
810
811 let client_config = {
812 let mut c = s2n_tls::config::Builder::new();
813 c.set_security_policy(&DEFAULT_TLS13)
814 .unwrap()
815 .load_pem(client_keypair.cert(), client_keypair.key())
816 .unwrap()
817 .trust_pem(server_keypair.ca_cert())
818 .unwrap()
819 .with_system_certs(false)
820 .unwrap();
821 c.build().unwrap()
822 };
823
824 MtlsEndpoint {
825 subscriber,
826 sink,
827 client_config,
828 server_config,
829 }
830 }
831
832 /// Build an mTLS endpoint with the subscriber on the client side.
833 pub(super) fn client_endpoint() -> MtlsEndpoint {
834 let sink = VecSink::new();
835 let attribution = Attribution {
836 service: "test".to_owned(),
837 resource: "test".to_owned(),
838 component: "test".to_owned(),
839 };
840 let subscriber = AggregatedMetricsSubscriber::new(sink.clone(), attribution);
841
842 let server_keypair = server_keypair();
843 let client_keypair = client_keypair();
844
845 let server_config = {
846 let mut c = s2n_tls::config::Builder::new();
847 c.set_security_policy(&DEFAULT_TLS13)
848 .unwrap()
849 .load_pem(server_keypair.cert(), server_keypair.key())
850 .unwrap()
851 .trust_pem(client_keypair.ca_cert())
852 .unwrap()
853 .set_client_auth_type(ClientAuthType::Required)
854 .unwrap();
855 c.build().unwrap()
856 };
857
858 let client_config = {
859 let mut c = s2n_tls::config::Builder::new();
860 c.set_security_policy(&DEFAULT_TLS13)
861 .unwrap()
862 .load_pem(client_keypair.cert(), client_keypair.key())
863 .unwrap()
864 .trust_pem(server_keypair.ca_cert())
865 .unwrap()
866 .with_system_certs(false)
867 .unwrap()
868 .set_event_subscriber(subscriber.clone())
869 .unwrap();
870 c.build().unwrap()
871 };
872
873 MtlsEndpoint {
874 subscriber,
875 sink,
876 client_config,
877 server_config,
878 }
879 }
880
881 impl MtlsEndpoint {
882 pub fn handshake(&self) {
883 let mut pair = TestPair::from_configs(&self.client_config, &self.server_config);
884 pair.client.set_server_name("localhost").unwrap();
885 pair.handshake().unwrap();
886 }
887 }
888 }
889
890 /// When the subscriber is on the server, `selected_cert` (server's own RSA cert)
891 /// should be recorded as server, and `peer_cert_chain` (client's ECDSA cert)
892 /// should be recorded as client.
893 #[test]
894 fn mtls_server_cert_attribution() {
895 let endpoint = mtls_helper::server_endpoint();
896 endpoint.handshake();
897 endpoint.subscriber.finish_record();
898
899 let records = endpoint.sink.records.lock().unwrap();
900 let record = &records[0].as_schema().handshake;
901
902 // Sanity check: a cipher was negotiated
903 assert_eq!(record.negotiated_ciphers.total(), 1);
904
905 // Server's own cert is RSA 4096 (leaf + 2 chain certs)
906 assert_eq!(record.server_leaf_cert_key.get(&CertKeyType::Rsa4096), 1);
907 assert_eq!(
908 record
909 .server_leaf_cert_sig
910 .get(&CertSignatureAlgorithm::RsaPkcsSha384),
911 1
912 );
913 assert_eq!(record.server_chain_cert_key.get(&CertKeyType::Rsa4096), 2);
914 assert_eq!(
915 record
916 .server_chain_cert_sig
917 .get(&CertSignatureAlgorithm::RsaPkcsSha384),
918 2
919 );
920
921 // Client's cert is ECDSA P384 (leaf + CA chain cert)
922 assert_eq!(record.client_leaf_cert_key.get(&CertKeyType::Secp384r1), 1);
923 assert_eq!(
924 record
925 .client_leaf_cert_sig
926 .get(&CertSignatureAlgorithm::EcdsaSha384),
927 1
928 );
929 assert_eq!(record.client_chain_cert_key.get(&CertKeyType::Secp384r1), 1);
930 assert_eq!(
931 record
932 .client_chain_cert_sig
933 .get(&CertSignatureAlgorithm::EcdsaSha384),
934 1
935 );
936
937 // No RSA in client fields, no ECDSA in server fields
938 assert_eq!(record.client_leaf_cert_key.get(&CertKeyType::Rsa4096), 0);
939 assert_eq!(record.server_leaf_cert_key.get(&CertKeyType::Secp384r1), 0);
940 }
941
942 /// When the subscriber is on the client, `selected_cert` (client's own ECDSA cert)
943 /// should be recorded as client, and `peer_cert_chain` (server's RSA cert)
944 /// should be recorded as server.
945 #[test]
946 fn mtls_client_cert_attribution() {
947 let endpoint = mtls_helper::client_endpoint();
948 endpoint.handshake();
949 endpoint.subscriber.finish_record();
950
951 let records = endpoint.sink.records.lock().unwrap();
952 let record = &records[0].as_schema().handshake;
953
954 // Sanity check: a cipher was negotiated
955 assert_eq!(record.negotiated_ciphers.total(), 1);
956
957 // Server's cert (peer) is RSA 4096 (leaf + 2 chain certs)
958 assert_eq!(record.server_leaf_cert_key.get(&CertKeyType::Rsa4096), 1);
959 assert_eq!(
960 record
961 .server_leaf_cert_sig
962 .get(&CertSignatureAlgorithm::RsaPkcsSha384),
963 1
964 );
965 assert_eq!(record.server_chain_cert_key.get(&CertKeyType::Rsa4096), 2);
966 assert_eq!(
967 record
968 .server_chain_cert_sig
969 .get(&CertSignatureAlgorithm::RsaPkcsSha384),
970 2
971 );
972
973 // Client's own cert is ECDSA P384 (leaf only, selected_cert has no chain)
974 assert_eq!(record.client_leaf_cert_key.get(&CertKeyType::Secp384r1), 1);
975 assert_eq!(
976 record
977 .client_leaf_cert_sig
978 .get(&CertSignatureAlgorithm::EcdsaSha384),
979 1
980 );
981 assert_eq!(record.client_chain_cert_key.total(), 0);
982 assert_eq!(record.client_chain_cert_sig.total(), 0);
983
984 // No RSA in client fields, no ECDSA in server fields
985 assert_eq!(record.client_leaf_cert_key.get(&CertKeyType::Rsa4096), 0);
986 assert_eq!(record.server_leaf_cert_key.get(&CertKeyType::Secp384r1), 0);
987 }
988 }