Debian Codegraph @

crt/s2n/bindings/rust/extended/s2n-tls/src/cert_chain.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 crate::error::{Error, ErrorType, Fallible};
5 use s2n_tls_sys::*;
6 use std::{
7 any::Any,
8 ffi::c_void,
9 marker::PhantomData,
10 ptr::{self, NonNull},
11 sync::Arc,
12 };
13
14 /// Internal wrapper type used for a convenient drop implementation.
15 ///
16 /// [CertificateChain] is internally reference counted. The reference counted `T`
17 /// must have a drop implementation.
18 #[derive(Debug)]
19 pub(crate) struct CertificateChainHandle<'a> {
20 pub(crate) cert: NonNull<s2n_cert_chain_and_key>,
21 is_owned: bool,
22 _lifetime: PhantomData<&'a s2n_cert_chain_and_key>,
23 }
24
25 // # Safety
26 //
27 // s2n_cert_chain_and_key objects can be sent across threads.
28 unsafe impl Send for CertificateChainHandle<'_> {}
29 unsafe impl Sync for CertificateChainHandle<'_> {}
30
31 impl CertificateChainHandle<'_> {
32 /// Allocate an uninitialized CertificateChainHandle.
33 ///
34 /// Corresponds to [`s2n_cert_chain_and_key_new`].
35 pub(crate) fn allocate() -> Result<CertificateChainHandle<'static>, crate::error::Error> {
36 crate::init::init();
37 Ok(CertificateChainHandle {
38 cert: unsafe { s2n_cert_chain_and_key_new().into_result() }?,
39 is_owned: true,
40 _lifetime: PhantomData,
41 })
42 }
43
44 fn from_reference(cert: NonNull<s2n_cert_chain_and_key>) -> Self {
45 Self {
46 cert,
47 is_owned: false,
48 _lifetime: PhantomData,
49 }
50 }
51
52 /// Corresponds to [`s2n_cert_chain_and_key_get_ctx`].
53 fn context_mut(&mut self) -> Option<&mut Context> {
54 let context = unsafe { s2n_cert_chain_and_key_get_ctx(self.cert.as_ptr()) };
55 if context.is_null() {
56 None
57 } else {
58 Some(unsafe { &mut *(context as *mut Context) })
59 }
60 }
61
62 /// Corresponds to [`s2n_cert_chain_and_key_get_ctx`].
63 fn context(&self) -> Option<&Context> {
64 let context = unsafe { s2n_cert_chain_and_key_get_ctx(self.cert.as_ptr()) };
65 if context.is_null() {
66 None
67 } else {
68 Some(unsafe { &*(context as *const Context) })
69 }
70 }
71 }
72
73 impl Drop for CertificateChainHandle<'_> {
74 /// Corresponds to [`s2n_cert_chain_and_key_free`].
75 fn drop(&mut self) {
76 if self.is_owned {
77 if let Some(internal_context) = self.context_mut() {
78 drop(unsafe { Box::from_raw(internal_context) });
79 }
80 // ignore failures since there's not much we can do about it
81 unsafe {
82 // null the cert chain context out of an abundance of caution
83 let _ = s2n_cert_chain_and_key_set_ctx(self.cert.as_ptr(), std::ptr::null_mut())
84 .into_result();
85
86 let _ = s2n_cert_chain_and_key_free(self.cert.as_ptr()).into_result();
87 }
88 }
89 }
90 }
91
92 /// An internal container to hold the customer supplied application context.
93 ///
94 /// We can't directly store the application context on the `s2n_cert_chain_and_key`,
95 /// because `*mut dyn Any` is a fat pointer (16 bytes) and can not be stored as
96 /// a c_void (8 bytes).
97 struct Context {
98 application_context: Box<dyn Any + Send + Sync>,
99 }
100
101 #[derive(Debug)]
102 pub struct Builder {
103 cert_handle: CertificateChainHandle<'static>,
104 }
105
106 impl Builder {
107 pub fn new() -> Result<Self, Error> {
108 Ok(Self {
109 cert_handle: CertificateChainHandle::allocate()?,
110 })
111 }
112
113 /// Corresponds to [`s2n_cert_chain_and_key_load_pem_bytes`]
114 ///
115 /// This can be used with [crate::config::Builder::load_chain] to share a
116 /// single cert across multiple configs.
117 pub fn load_pem(&mut self, chain: &[u8], key: &[u8]) -> Result<&mut Self, Error> {
118 unsafe {
119 // SAFETY: manual audit of load_pem_bytes shows that `chain_pem` and
120 // `private_key_pem` are not modified.
121 // https://github.com/aws/s2n-tls/issues/4140
122 s2n_cert_chain_and_key_load_pem_bytes(
123 self.cert_handle.cert.as_ptr(),
124 chain.as_ptr() as *mut _,
125 chain.len() as u32,
126 key.as_ptr() as *mut _,
127 key.len() as u32,
128 )
129 .into_result()
130 }?;
131
132 Ok(self)
133 }
134
135 /// Corresponds to [`s2n_cert_chain_and_key_load_public_pem_bytes`].
136 ///
137 /// This method is only used when performing private-key offloading. For standard
138 /// use-cases see [CertificateChain::from_pem].
139 pub fn load_public_pem(&mut self, chain: &[u8]) -> Result<&mut Self, Error> {
140 unsafe {
141 // SAFETY: manual audit of load_public_pem_bytes shows that `chain_pem`
142 // is not modified
143 // https://github.com/aws/s2n-tls/issues/4140
144 s2n_cert_chain_and_key_load_public_pem_bytes(
145 self.cert_handle.cert.as_ptr(),
146 chain.as_ptr() as *mut _,
147 chain.len() as u32,
148 )
149 .into_result()
150 }?;
151
152 Ok(self)
153 }
154
155 /// Corresponds to [`s2n_cert_chain_and_key_set_ocsp_data`].
156 pub fn set_ocsp_data(&mut self, data: &[u8]) -> Result<&mut Self, Error> {
157 unsafe {
158 s2n_cert_chain_and_key_set_ocsp_data(
159 self.cert_handle.cert.as_ptr(),
160 data.as_ptr(),
161 data.len() as u32,
162 )
163 .into_result()
164 }?;
165 Ok(self)
166 }
167
168 /// Associates an arbitrary application context with the CertificateChain to
169 /// be later retrieved via [`CertificateChain::application_context()`].
170 ///
171 /// This API will override an existing application context set on the Builder.
172 ///
173 /// Corresponds to [`s2n_cert_chain_and_key_set_ctx`].
174 pub fn set_application_context<T: Send + Sync + 'static>(
175 &mut self,
176 app_context: T,
177 ) -> Result<&mut Self, Error> {
178 match self.cert_handle.context_mut() {
179 Some(_) => Err(Error::bindings(
180 ErrorType::UsageError,
181 "cert builder error",
182 "set_application_context can only be called once",
183 )),
184 None => {
185 let app_context = Box::new(app_context);
186 let internal_context = Box::new(Context {
187 application_context: app_context,
188 });
189 unsafe {
190 s2n_cert_chain_and_key_set_ctx(
191 self.cert_handle.cert.as_ptr(),
192 Box::into_raw(internal_context) as *mut c_void,
193 )
194 .into_result()
195 }?;
196 Ok(self)
197 }
198 }
199 }
200
201 /// Return an immutable, internally-reference counted CertificateChain.
202 pub fn build(self) -> Result<CertificateChain<'static>, Error> {
203 // This method is currently infallible, but returning a result allows
204 // us to add validation in the future.
205 Ok(CertificateChain::from_allocated(self.cert_handle))
206 }
207 }
208
209 /// A CertificateChain represents a chain of X.509 certificates.
210 ///
211 /// Certificate chains are internally reference counted and are cheaply clone-able.
212 //
213 // SAFETY: it is important that no CertificateChain methods operate on mutable
214 // references. Because CertificateChains can be shared across threads, it is not
215 // safe to mutate CertificateChains.
216 #[derive(Clone)]
217 pub struct CertificateChain<'a> {
218 cert_handle: Arc<CertificateChainHandle<'a>>,
219 }
220
221 impl CertificateChain<'_> {
222 /// Construct a CertificateChain from an allocated [CertificateChainHandle].
223 pub(crate) fn from_allocated(
224 handle: CertificateChainHandle<'static>,
225 ) -> CertificateChain<'static> {
226 CertificateChain {
227 cert_handle: Arc::new(handle),
228 }
229 }
230
231 /// This is used to create a CertificateChain "reference" backed by memory
232 /// on some external struct, where the external struct has some lifetime `'a`.
233 pub(crate) unsafe fn from_ptr_reference<'a>(
234 ptr: NonNull<s2n_cert_chain_and_key>,
235 ) -> CertificateChain<'a> {
236 let handle = Arc::new(CertificateChainHandle::from_reference(ptr));
237
238 CertificateChain {
239 cert_handle: handle,
240 }
241 }
242
243 pub fn iter(&self) -> CertificateChainIter<'_> {
244 CertificateChainIter {
245 idx: 0,
246 // Cache the length as it's O(n) to compute it, the chain is stored as a linked list.
247 // It shouldn't change while we have access to the iterator.
248 len: self.len(),
249 chain: self,
250 }
251 }
252
253 /// Retrieves a reference to the application context associated with the
254 /// CertificateChain.
255 ///
256 /// If an application context hasn't been set on the CertificateChain or if
257 /// the set application context isn't of type `T`, `None` will be returned.
258 ///
259 /// To set a context on the connection, use [`Builder::set_application_context()`].
260 ///
261 /// Corresponds to [`s2n_cert_chain_and_key_get_ctx`].
262 pub fn application_context<T: Send + Sync + 'static>(&self) -> Option<&T> {
263 if let Some(internal_context) = self.cert_handle.context() {
264 internal_context.application_context.downcast_ref()
265 } else {
266 None
267 }
268 }
269
270 /// Return the length of this certificate chain.
271 ///
272 /// Note that the underlying API currently traverses a linked list, so this is a relatively
273 /// expensive API to call.
274 ///
275 /// Corresponds to [`s2n_cert_chain_get_length`].
276 pub fn len(&self) -> usize {
277 let mut length: u32 = 0;
278 let res = unsafe { s2n_cert_chain_get_length(self.as_ptr(), &mut length).into_result() };
279 if res.is_err() {
280 // Errors should only happen on empty chains (we guarantee that `ptr` is a valid chain).
281 return 0;
282 }
283 // u32 should always fit into usize on the platforms we support.
284 length.try_into().unwrap()
285 }
286
287 /// Check if the certificate chain has any certificates.
288 ///
289 /// Note that the underlying API currently traverses a linked list, so this is a relatively
290 /// expensive API to call.
291 pub fn is_empty(&self) -> bool {
292 self.len() == 0
293 }
294
295 pub(crate) fn as_ptr(&self) -> *const s2n_cert_chain_and_key {
296 self.cert_handle.cert.as_ptr() as *const _
297 }
298 }
299
300 pub struct CertificateChainIter<'a> {
301 idx: u32,
302 len: usize,
303 chain: &'a CertificateChain<'a>,
304 }
305
306 impl<'a> Iterator for CertificateChainIter<'a> {
307 type Item = Result<Certificate<'a>, Error>;
308
309 /// Corresponds to [`s2n_cert_chain_get_cert`].
310 fn next(&mut self) -> Option<Self::Item> {
311 let idx = self.idx;
312 // u32 fits into usize on platforms we support.
313 if usize::try_from(idx).unwrap() >= self.len {
314 return None;
315 }
316 self.idx += 1;
317 let mut out = ptr::null_mut();
318 unsafe {
319 if let Err(e) =
320 s2n_cert_chain_get_cert(self.chain.as_ptr(), &mut out, idx).into_result()
321 {
322 return Some(Err(e));
323 }
324 }
325 let out = match NonNull::new(out) {
326 Some(out) => out,
327 None => return Some(Err(Error::INVALID_INPUT)),
328 };
329 Some(Ok(Certificate {
330 chain: PhantomData,
331 certificate: out,
332 }))
333 }
334 }
335
336 pub struct Certificate<'a> {
337 // The chain owns the memory for this certificate.
338 chain: PhantomData<&'a CertificateChain<'a>>,
339
340 certificate: NonNull<s2n_cert>,
341 }
342
343 impl Certificate<'_> {
344 /// Corresponds to [`s2n_cert_get_der`].
345 pub fn der(&self) -> Result<&[u8], Error> {
346 unsafe {
347 let mut buffer = ptr::null();
348 let mut length = 0;
349 s2n_cert_get_der(self.certificate.as_ptr(), &mut buffer, &mut length).into_result()?;
350 let length = usize::try_from(length).map_err(|_| Error::INVALID_INPUT)?;
351
352 Ok(std::slice::from_raw_parts(buffer, length))
353 }
354 }
355 }
356
357 // # Safety
358 //
359 // Certificates just reference data in the chain, so share the Send-ness of the chain.
360 unsafe impl Send for Certificate<'_> {}
361
362 #[cfg(test)]
363 mod tests {
364 use crate::{
365 config,
366 error::{Error as S2NError, ErrorSource, ErrorType},
367 security::DEFAULT_TLS13,
368 testing::{
369 config_builder, CertKeyPair, InsecureAcceptAllCertificatesHandler, SniTestCerts,
370 TestPair,
371 },
372 };
373
374 use super::*;
375
376 /// Create a test pair using SNI certs
377 /// * `certs`: takes references to already created cert chains. This is useful
378 /// to assert on expected reference counts.
379 /// * `types`: Used to find the CA paths for the client configs
380 fn sni_test_pair(
381 certs: Vec<CertificateChain<'static>>,
382 defaults: Option<Vec<CertificateChain<'static>>>,
383 types: &[SniTestCerts],
384 ) -> Result<TestPair, crate::error::Error> {
385 let mut server_config = config::Builder::new();
386 server_config
387 .with_system_certs(false)?
388 .set_security_policy(&DEFAULT_TLS13)?;
389 for cert in certs.into_iter() {
390 server_config.load_chain(cert)?;
391 }
392 if let Some(defaults) = defaults {
393 server_config.set_default_chains(defaults)?;
394 }
395
396 let mut client_config = config::Builder::new();
397 client_config
398 .with_system_certs(false)?
399 .set_security_policy(&DEFAULT_TLS13)?
400 .set_verify_host_callback(InsecureAcceptAllCertificatesHandler {})?;
401 for t in types {
402 client_config.trust_pem(t.get().cert())?;
403 }
404 Ok(TestPair::from_configs(
405 &client_config.build()?,
406 &server_config.build()?,
407 ))
408 }
409
410 /// This is a useful (but inefficient) test utility to check if CertificateChain
411 /// structs are equal. It does this by comparing the serialized `der` representation.
412 fn cert_chains_are_equal(this: &CertificateChain<'_>, that: &CertificateChain<'_>) -> bool {
413 let this: Vec<Vec<u8>> = this
414 .iter()
415 .map(|cert| cert.unwrap().der().unwrap().to_owned())
416 .collect();
417 let that: Vec<Vec<u8>> = that
418 .iter()
419 .map(|cert| cert.unwrap().der().unwrap().to_owned())
420 .collect();
421 this == that
422 }
423
424 #[test]
425 fn reference_count_increment() -> Result<(), crate::error::Error> {
426 let cert = SniTestCerts::AlligatorRsa.get().into_certificate_chain();
427 assert_eq!(Arc::strong_count(&cert.cert_handle), 1);
428
429 {
430 let mut server = config::Builder::new();
431 server.load_chain(cert.clone())?;
432
433 // after being added, the reference count should have increased
434 assert_eq!(Arc::strong_count(&cert.cert_handle), 2);
435 }
436
437 // after the config goes out of scope and is dropped, the ref count should
438 // decrement
439 assert_eq!(Arc::strong_count(&cert.cert_handle), 1);
440 Ok(())
441 }
442
443 #[test]
444 fn cert_is_dropped() {
445 let weak_ref = {
446 let cert = SniTestCerts::AlligatorEcdsa.get().into_certificate_chain();
447 assert_eq!(Arc::strong_count(&cert.cert_handle), 1);
448 Arc::downgrade(&cert.cert_handle)
449 };
450 assert_eq!(weak_ref.strong_count(), 0);
451 assert!(weak_ref.upgrade().is_none());
452 }
453
454 // a cert can be successfully shared across multiple configs
455 #[test]
456 fn shared_certs() -> Result<(), crate::error::Error> {
457 let test_key_pair = SniTestCerts::AlligatorRsa.get();
458 let cert = test_key_pair.into_certificate_chain();
459
460 let mut test_pair_1 =
461 sni_test_pair(vec![cert.clone()], None, &[SniTestCerts::AlligatorRsa])?;
462 let mut test_pair_2 =
463 sni_test_pair(vec![cert.clone()], None, &[SniTestCerts::AlligatorRsa])?;
464
465 assert_eq!(Arc::strong_count(&cert.cert_handle), 3);
466
467 assert!(test_pair_1.handshake().is_ok());
468 assert!(test_pair_2.handshake().is_ok());
469
470 assert_eq!(Arc::strong_count(&cert.cert_handle), 3);
471
472 drop(test_pair_1);
473 assert_eq!(Arc::strong_count(&cert.cert_handle), 2);
474 drop(test_pair_2);
475 assert_eq!(Arc::strong_count(&cert.cert_handle), 1);
476 Ok(())
477 }
478
479 #[test]
480 fn too_many_certs_in_default() -> Result<(), crate::error::Error> {
481 // 5 certs in the maximum allowed, 6 should error.
482 const FAILING_NUMBER: usize = 6;
483 let certs = vec![SniTestCerts::AlligatorRsa.get().into_certificate_chain(); FAILING_NUMBER];
484 assert_eq!(Arc::strong_count(&certs[0].cert_handle), FAILING_NUMBER);
485
486 let mut config = config::Builder::new();
487 let err = config.set_default_chains(certs.clone()).err().unwrap();
488 assert_eq!(err.kind(), ErrorType::UsageError);
489 assert_eq!(err.source(), ErrorSource::Bindings);
490
491 // The config should not hold a reference when the error was detected
492 // in the bindings
493 assert_eq!(Arc::strong_count(&certs[0].cert_handle), FAILING_NUMBER);
494
495 Ok(())
496 }
497
498 #[test]
499 fn default_selection() -> Result<(), crate::error::Error> {
500 let alligator_cert = SniTestCerts::AlligatorRsa.get().into_certificate_chain();
501 let beaver_cert = SniTestCerts::BeaverRsa.get().into_certificate_chain();
502
503 // when no default is explicitly set, the first loaded cert is the default
504 {
505 let mut test_pair = sni_test_pair(
506 vec![alligator_cert.clone(), beaver_cert.clone()],
507 None,
508 &[SniTestCerts::AlligatorRsa, SniTestCerts::BeaverRsa],
509 )?;
510
511 assert!(test_pair.handshake().is_ok());
512
513 assert!(cert_chains_are_equal(
514 &alligator_cert,
515 &test_pair.client.peer_cert_chain().unwrap()
516 ));
517
518 assert_eq!(Arc::strong_count(&alligator_cert.cert_handle), 2);
519 assert_eq!(Arc::strong_count(&beaver_cert.cert_handle), 2);
520 }
521
522 // set an explicit default
523 {
524 let mut test_pair = sni_test_pair(
525 vec![alligator_cert.clone(), beaver_cert.clone()],
526 Some(vec![beaver_cert.clone()]),
527 &[SniTestCerts::AlligatorRsa, SniTestCerts::BeaverRsa],
528 )?;
529
530 assert!(test_pair.handshake().is_ok());
531
532 assert!(cert_chains_are_equal(
533 &beaver_cert,
534 &test_pair.client.peer_cert_chain().unwrap()
535 ));
536
537 assert_eq!(Arc::strong_count(&alligator_cert.cert_handle), 2);
538 // beaver has an additional reference because it was used in multiple
539 // calls
540 assert_eq!(Arc::strong_count(&beaver_cert.cert_handle), 3);
541 }
542
543 // set a default without adding it to the store
544 {
545 let mut test_pair = sni_test_pair(
546 vec![alligator_cert.clone()],
547 Some(vec![beaver_cert.clone()]),
548 &[SniTestCerts::AlligatorRsa, SniTestCerts::BeaverRsa],
549 )?;
550
551 assert!(test_pair.handshake().is_ok());
552
553 assert!(cert_chains_are_equal(
554 &beaver_cert,
555 &test_pair.client.peer_cert_chain().unwrap()
556 ));
557
558 assert_eq!(Arc::strong_count(&alligator_cert.cert_handle), 2);
559 assert_eq!(Arc::strong_count(&beaver_cert.cert_handle), 2);
560 }
561
562 Ok(())
563 }
564
565 #[test]
566 fn cert_ownership_error() -> Result<(), crate::error::Error> {
567 let application_owned_cert = SniTestCerts::AlligatorRsa.get().into_certificate_chain();
568 let cert_for_lib = SniTestCerts::BeaverRsa.get();
569
570 let mut config = config::Builder::new();
571
572 // library owned certs can not be used with application owned certs
573 config.load_chain(application_owned_cert)?;
574 let err = config
575 .load_pem(cert_for_lib.cert(), cert_for_lib.key())
576 .err()
577 .unwrap();
578
579 assert_eq!(err.kind(), ErrorType::UsageError);
580 assert_eq!(err.name(), "S2N_ERR_CERT_OWNERSHIP");
581
582 Ok(())
583 }
584
585 // ensure the certificates are send and sync
586 #[test]
587 fn certificate_send_sync_test() {
588 fn assert_send_sync<T: 'static + Send + Sync>() {}
589 assert_send_sync::<CertificateChain<'static>>();
590 }
591
592 /// sanity check for basic cert chain context interactions
593 #[test]
594 fn application_context_workflow() -> Result<(), S2NError> {
595 let context: Arc<u64> = Arc::new(0xC0FFEE);
596 let handle = Arc::clone(&context);
597 assert_eq!(Arc::strong_count(&handle), 2);
598
599 let default = CertKeyPair::default();
600 let mut chain = Builder::new()?;
601 chain.load_pem(default.cert(), default.key())?;
602 chain.set_application_context(context)?;
603 let chain = chain.build()?;
604
605 let invalid_type_get = chain.application_context::<u64>();
606 assert!(invalid_type_get.is_none());
607
608 let retrieved_context = chain.application_context::<Arc<u64>>().unwrap();
609 assert_eq!(*retrieved_context.as_ref(), 0xC0FFEE);
610 assert_eq!(Arc::strong_count(&handle), 2);
611 drop(chain);
612 assert_eq!(Arc::strong_count(&handle), 1);
613 Ok(())
614 }
615
616 /// When an application context is overridden, it should be error.
617 #[test]
618 fn application_context_override() -> Result<(), S2NError> {
619 let initial: Arc<u64> = Arc::new(0xC0FFEE);
620 let overridden: Arc<[u8; 6]> = Arc::new(*b"coffee");
621
622 let mut builder = Builder::new()?;
623 builder.set_application_context(initial)?;
624 let err = builder.set_application_context(overridden).unwrap_err();
625 assert_eq!(err.kind(), ErrorType::UsageError);
626
627 Ok(())
628 }
629
630 /// An application context should be retrievable from a selected cert after
631 /// the handshake.
632 #[test]
633 fn application_context_from_selected_cert() -> Result<(), S2NError> {
634 let default = CertKeyPair::default();
635 let mut chain = Builder::new()?;
636 chain.load_pem(default.cert(), default.key())?;
637 chain.set_application_context(0xC0FFEE_u64)?;
638
639 let mut server_config = config::Builder::new();
640 server_config.load_chain(chain.build()?)?;
641
642 let client_config = config_builder(&crate::security::DEFAULT).unwrap();
643
644 let mut test_pair =
645 TestPair::from_configs(&client_config.build()?, &server_config.build()?);
646 test_pair.handshake()?;
647
648 let selected_cert = test_pair.server.selected_cert().unwrap();
649 let context = selected_cert.application_context::<u64>();
650 assert_eq!(context, Some(&0xC0FFEE_u64));
651
652 Ok(())
653 }
654 }