Debian Codegraph @

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

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 //! Certificate Authorities handling as part of CertificateRequests.
5 //!
6 //! This is an unstable s2n API.
7
8 use s2n_tls_sys::*;
9
10 use crate::{
11 callbacks::with_context,
12 config,
13 connection::Connection,
14 enums::CallbackResult,
15 error::{Error, Fallible},
16 };
17 use std::{marker::PhantomData, ptr::NonNull};
18
19 /// A CertificateRequest message.
20 ///
21 /// This is provided via [`CertificateRequestCallback::on_certificate_request`].
22 pub struct CertificateRequest<'a> {
23 request: NonNull<s2n_certificate_request>,
24 conn: &'a mut Connection,
25 }
26
27 /// A list of DER-encoded X.509 distinguished names sent by the server.
28 ///
29 /// Note that s2n-tls does not validate the contents of the names, consider them untrusted input.
30 pub struct CertificateAuthorities<'a>(
31 Option<NonNull<s2n_certificate_authority_list>>,
32 PhantomData<&'a mut ()>,
33 );
34
35 #[derive(Default)]
36 pub(crate) struct CertRequestState {
37 chain: Option<crate::cert_chain::CertificateChain<'static>>,
38 }
39
40 impl CertificateRequest<'_> {
41 /// Get the list of certificate_authorities provided by the server for this request.
42 ///
43 /// This returns a reference to the internal state of the CertificateRequest: the iterator is
44 /// not reset on each call to this method.
45 ///
46 /// Corresponds to [`s2n_certificate_request_get_ca_list`].
47 pub fn certificate_authorities(&mut self) -> CertificateAuthorities<'_> {
48 // SAFETY: Accessor function, with returned object bound to the appropraite lifetime.
49 unsafe {
50 let list = NonNull::new(s2n_certificate_request_get_ca_list(self.request.as_ptr()));
51 CertificateAuthorities(list, PhantomData)
52 }
53 }
54
55 /// Get the connection this request arrived on.
56 pub fn connection(&mut self) -> &mut Connection {
57 self.conn
58 }
59
60 /// Set the certificate chain to reply with to this request.
61 ///
62 /// Corresponds to [`s2n_certificate_request_set_certificate`].
63 pub fn set_certificate(
64 &mut self,
65 cert_chain: crate::cert_chain::CertificateChain<'static>,
66 ) -> Result<(), Error> {
67 let ptr = cert_chain.as_ptr();
68 self.conn.cert_request_state().chain = Some(cert_chain);
69
70 // SAFETY: We've stashed the certificate chain provided into the Connection's context, so
71 // it's going to outlive any access to it.
72 //
73 // Only the last call to set_certificate has any effect in s2n-tls, so we don't need to
74 // keep a vec of the chains.
75 unsafe {
76 s2n_certificate_request_set_certificate(self.request.as_ptr(), ptr as *mut _)
77 .into_result()?;
78 }
79
80 Ok(())
81 }
82 }
83
84 impl<'a> CertificateAuthorities<'a> {
85 /// Reset the iterator to the start.
86 ///
87 /// Corresponds to [`s2n_certificate_authority_list_reread`].
88 pub fn reset(&mut self) -> Result<(), Error> {
89 if let Some(this) = self.0.as_ref().map(|v| v.as_ptr()) {
90 // SAFETY: Calling with non-null, valid pointer to a list.
91 unsafe {
92 s2n_certificate_authority_list_reread(this).into_result()?;
93 }
94 }
95
96 Ok(())
97 }
98 }
99
100 pub struct CertificateAuthority<'a>(&'a [u8]);
101
102 impl<'a> CertificateAuthority<'a> {
103 /// Note that s2n-tls does not validate the contents of the names, consider them untrusted input.
104 pub fn der(&self) -> &[u8] {
105 self.0
106 }
107 }
108
109 impl<'a> Iterator for CertificateAuthorities<'a> {
110 type Item = Result<CertificateAuthority<'a>, Error>;
111
112 /// Corresponds to:
113 /// - [`s2n_certificate_authority_list_has_next`]
114 /// - [`s2n_certificate_authority_list_next`]
115 fn next(&mut self) -> Option<Self::Item> {
116 let mut ptr = std::ptr::null_mut::<u8>();
117 let mut length: u16 = 0;
118
119 if let Some(this) = self.0.as_ref().map(|v| v.as_ptr()) {
120 // SAFETY: Calling with non-null, valid pointer to a list.
121 unsafe {
122 if !s2n_certificate_authority_list_has_next(this) {
123 return None;
124 }
125 }
126
127 // SAFETY: Calling with non-null, valid pointer to a list.
128 //
129 // The `ptr` and `length` are returned to users with the appropriate lifetime.
130 unsafe {
131 if let Err(e) =
132 s2n_certificate_authority_list_next(this, &mut ptr, &mut length).into_result()
133 {
134 return Some(Err(e));
135 }
136 }
137 }
138
139 if ptr.is_null() {
140 // Should be unreachable, but avoiding relying on that being true.
141 return Some(Err(crate::error::Error::INVALID_INPUT));
142 }
143
144 // Avoid questions about whether s2n's zero-length return had a valid pointer from Rust's
145 // perspective (i.e., well-aligned).
146 if length == 0 {
147 return Some(Ok(CertificateAuthority(&[])));
148 }
149
150 // SAFETY: The slice provided by s2n lives for the certificate request ('a),
151 // and is guaranteed to be initialized by s2n. It's also immutable.
152 Some(Ok(CertificateAuthority(unsafe {
153 std::slice::from_raw_parts(ptr, usize::from(length))
154 })))
155 }
156 }
157
158 /// Callback for the CertificateRequest message.
159 pub trait CertificateRequestCallback: 'static + Send + Sync {
160 /// A callback that triggers when the client receives a CertificateRequest message
161 /// from the server, providing an opportunity to override the default certificate on the
162 /// Config.
163 fn on_certificate_request(&self, request: &mut CertificateRequest) -> Result<(), Error>;
164 }
165
166 impl config::Builder {
167 /// Sets a method to be called when the client receives CertificateRequest message.
168 ///
169 /// Corresponds to [`s2n_config_set_cert_request_callback`].
170 pub fn set_certificate_request_callback<T: 'static + CertificateRequestCallback>(
171 &mut self,
172 handler: T,
173 ) -> Result<&mut Self, Error> {
174 unsafe extern "C" fn cert_request_callback(
175 conn_ptr: *mut s2n_connection,
176 _context: *mut libc::c_void,
177 request: *mut s2n_certificate_request,
178 ) -> libc::c_int {
179 let request = match NonNull::new(request) {
180 Some(r) => r,
181 None => return CallbackResult::Failure.into(),
182 };
183
184 with_context(conn_ptr, |conn, context| {
185 let callback = context.cert_authorities.as_ref();
186 if let Some(callback) = callback {
187 let mut req = CertificateRequest { request, conn };
188 match callback.on_certificate_request(&mut req) {
189 Ok(()) => return CallbackResult::Success.into(),
190 // FIXME: How do we propagate the specific err?
191 Err(_err) => return CallbackResult::Failure.into(),
192 }
193 }
194 CallbackResult::Success.into()
195 })
196 }
197
198 let handler = Box::new(handler);
199 let context = unsafe {
200 // SAFETY: usage of context_mut is safe in the builder, because while
201 // it is being built, the Builder is the only reference to the config.
202 self.config.context_mut()
203 };
204 context.cert_authorities = Some(handler);
205 unsafe {
206 s2n_config_set_cert_request_callback(
207 self.as_mut_ptr(),
208 Some(cert_request_callback),
209 std::ptr::null_mut(),
210 )
211 .into_result()?;
212 }
213 Ok(self)
214 }
215 }
216
217 #[cfg(test)]
218 mod tests {
219 use crate::{
220 cert_chain::CertificateChain,
221 enums::ClientAuthType,
222 security,
223 testing::{config_builder, CertKeyPair, TestPair},
224 };
225 use std::{
226 collections::HashMap,
227 sync::{Arc, Mutex},
228 };
229
230 struct SetCallback {
231 certificate: CertificateChain<'static>,
232 }
233
234 impl super::CertificateRequestCallback for SetCallback {
235 fn on_certificate_request(
236 &self,
237 request: &mut super::CertificateRequest,
238 ) -> Result<(), super::Error> {
239 request.set_certificate(self.certificate.clone())?;
240 Ok(())
241 }
242 }
243
244 struct ExtractCallback {
245 certificate: CertificateChain<'static>,
246 cas: Arc<Mutex<Vec<Vec<u8>>>>,
247 }
248
249 impl super::CertificateRequestCallback for ExtractCallback {
250 fn on_certificate_request(
251 &self,
252 request: &mut super::CertificateRequest,
253 ) -> Result<(), super::Error> {
254 let mut cas = self.cas.lock().unwrap();
255
256 cas.clear();
257
258 for ca in request.certificate_authorities() {
259 cas.push(ca?.der().to_owned());
260 }
261
262 request.certificate_authorities().reset()?;
263
264 for (idx, ca) in request.certificate_authorities().enumerate() {
265 assert_eq!(cas[idx], ca?.der());
266 }
267
268 request.set_certificate(self.certificate.clone())?;
269 Ok(())
270 }
271 }
272
273 #[test]
274 fn basic() -> Result<(), Box<dyn std::error::Error>> {
275 let keypair = CertKeyPair::default();
276 let config = {
277 let mut config = config_builder(&security::DEFAULT_TLS13)?;
278 config.set_client_auth_type(ClientAuthType::Required)?;
279 config.trust_pem(keypair.cert())?;
280 config.set_certificate_request_callback(SetCallback {
281 certificate: keypair.into_certificate_chain(),
282 })?;
283 config.build()?
284 };
285
286 let mut pair = TestPair::from_config(&config);
287
288 // None before handshake...
289 assert!(pair.server.selected_cert().is_none());
290 assert!(pair.client.selected_cert().is_none());
291
292 pair.handshake()?;
293
294 for conn in [&pair.server, &pair.client] {
295 let chain = conn.selected_cert().unwrap();
296 assert_eq!(chain.len(), 1);
297 for cert in chain.iter() {
298 let cert = cert?;
299 let cert = cert.der()?;
300 assert!(!cert.is_empty());
301 }
302 }
303
304 // Same config is used for both and we are doing mTLS, so both should select the same
305 // certificate.
306 assert_eq!(
307 pair.server
308 .selected_cert()
309 .unwrap()
310 .iter()
311 .next()
312 .unwrap()?
313 .der()?,
314 pair.client
315 .selected_cert()
316 .unwrap()
317 .iter()
318 .next()
319 .unwrap()?
320 .der()?
321 );
322
323 Ok(())
324 }
325
326 #[test]
327 fn change_cert() -> Result<(), Box<dyn std::error::Error>> {
328 let keypair = CertKeyPair::from_path("rsa_4096_sha384_client_", "cert", "key", "cert");
329 let config = {
330 let mut config = config_builder(&security::DEFAULT_TLS13)?;
331 config.set_client_auth_type(ClientAuthType::Required)?;
332 config.trust_pem(keypair.cert())?;
333 config.set_certificate_request_callback(SetCallback {
334 certificate: keypair.into_certificate_chain(),
335 })?;
336 config.build()?
337 };
338
339 let mut pair = TestPair::from_config(&config);
340
341 // None before handshake...
342 assert!(pair.server.selected_cert().is_none());
343 assert!(pair.client.selected_cert().is_none());
344
345 pair.handshake()?;
346
347 for conn in [&pair.server, &pair.client] {
348 let chain = conn.selected_cert().unwrap();
349 assert_eq!(chain.len(), 1);
350 for cert in chain.iter() {
351 let cert = cert?;
352 let cert = cert.der()?;
353 assert!(!cert.is_empty());
354 }
355 }
356
357 // Server selected the default cert
358 assert_eq!(
359 pair.server
360 .selected_cert()
361 .unwrap()
362 .iter()
363 .next()
364 .unwrap()?
365 .der()?,
366 CertKeyPair::default()
367 .into_certificate_chain()
368 .iter()
369 .next()
370 .unwrap()?
371 .der()?
372 );
373
374 // Client selected the custom cert
375 assert_eq!(
376 pair.client
377 .selected_cert()
378 .unwrap()
379 .iter()
380 .next()
381 .unwrap()?
382 .der()?,
383 keypair
384 .into_certificate_chain()
385 .iter()
386 .next()
387 .unwrap()?
388 .der()?
389 );
390
391 Ok(())
392 }
393
394 #[test]
395 fn ca_list_empty() -> Result<(), Box<dyn std::error::Error>> {
396 let keypair = CertKeyPair::default();
397 let cas = Arc::new(Mutex::new(vec![]));
398 let config = {
399 let mut config = config_builder(&security::DEFAULT_TLS13)?;
400 config.set_client_auth_type(ClientAuthType::Required)?;
401 config.set_certificate_request_callback(ExtractCallback {
402 certificate: keypair.into_certificate_chain(),
403 cas: cas.clone(),
404 })?;
405 config.build()?
406 };
407
408 let mut pair = TestPair::from_config(&config);
409
410 // None before handshake...
411 assert!(pair.server.selected_cert().is_none());
412 assert!(pair.client.selected_cert().is_none());
413
414 pair.handshake()?;
415
416 let cas = cas.lock().unwrap();
417
418 // No CAs are sent by default.
419 assert_eq!(cas.len(), 0);
420
421 Ok(())
422 }
423
424 #[test]
425 fn ca_list() -> Result<(), Box<dyn std::error::Error>> {
426 let keypair = CertKeyPair::default();
427 let cas = Arc::new(Mutex::new(vec![]));
428 let config = {
429 let mut config = config_builder(&security::DEFAULT_TLS13)?;
430 config.set_client_auth_type(ClientAuthType::Required)?;
431 config.set_certificate_authorities_from_trust_store()?;
432 config.set_certificate_request_callback(ExtractCallback {
433 certificate: keypair.into_certificate_chain(),
434 cas: cas.clone(),
435 })?;
436 config.with_system_certs(false)?;
437 config.build()?
438 };
439
440 let mut pair = TestPair::from_config(&config);
441
442 // None before handshake...
443 assert!(pair.server.selected_cert().is_none());
444 assert!(pair.client.selected_cert().is_none());
445
446 pair.handshake()?;
447
448 let cas = cas.lock().unwrap();
449
450 assert_eq!(cas.len(), 1);
451 let ca = cas.iter().next().unwrap();
452 let decoded = openssl::x509::X509Name::from_der(ca)?;
453 let expected =
454 openssl::x509::X509Name::load_client_ca_file(CertKeyPair::default().cert_path())?;
455 assert_eq!(
456 decoded.try_cmp(expected.get(0).unwrap())?,
457 std::cmp::Ordering::Equal
458 );
459
460 Ok(())
461 }
462
463 #[derive(Clone)]
464 struct Pick(Arc<Mutex<HashMap<&'static str, crate::config::Config>>>);
465
466 impl crate::callbacks::ClientHelloCallback for Pick {
467 fn on_client_hello(
468 &self,
469 connection: &mut crate::connection::Connection,
470 ) -> crate::callbacks::ConnectionFutureResult {
471 // This uses SNI, but in principle it could select from multiple options in a way
472 // unknown to the client.
473 let name = connection.server_name().unwrap();
474
475 let this = self.0.lock().unwrap();
476 let config = this.get(name).expect(name).clone();
477
478 connection.set_config(config)?;
479
480 connection.server_name_extension_used();
481
482 Ok(None)
483 }
484 }
485
486 struct DynamicSelect;
487
488 impl super::CertificateRequestCallback for DynamicSelect {
489 fn on_certificate_request(
490 &self,
491 request: &mut super::CertificateRequest,
492 ) -> Result<(), super::Error> {
493 let a = CertKeyPair::from_path("rsa_4096_sha256_client_", "cert", "key", "cert");
494 let b = CertKeyPair::from_path("rsa_4096_sha384_client_", "cert", "key", "cert");
495
496 let reply = match request.certificate_authorities().count() {
497 1 => a,
498 2 => b,
499 _ => unreachable!(),
500 };
501
502 request.set_certificate(reply.into_certificate_chain())?;
503
504 Ok(())
505 }
506 }
507
508 #[test]
509 fn dynamic_pick() -> Result<(), Box<dyn std::error::Error>> {
510 let a = CertKeyPair::from_path("rsa_4096_sha256_client_", "cert", "key", "cert");
511 let b = CertKeyPair::from_path("rsa_4096_sha384_client_", "cert", "key", "cert");
512 let c = CertKeyPair::from_path("rsa_4096_sha512_client_", "cert", "key", "cert");
513
514 let mut map = HashMap::new();
515 map.insert("a.example.com", {
516 let mut config = config_builder(&security::DEFAULT_TLS13)?;
517 config.set_client_auth_type(ClientAuthType::Required)?;
518
519 config.wipe_trust_store()?;
520 config.trust_pem(a.cert())?;
521 config.set_certificate_authorities_from_trust_store()?;
522
523 config.build()?
524 });
525 map.insert("b.example.com", {
526 let mut config = config_builder(&security::DEFAULT_TLS13)?;
527 config.set_client_auth_type(ClientAuthType::Required)?;
528
529 config.wipe_trust_store()?;
530 // indicate we're the 2nd one by trusting two certificates.
531 // this is a hack but we don't have a nice way to create distinct subjects (what
532 // s2n sends) so this is best we can easily do.
533 config.trust_pem(b.cert())?;
534 config.trust_pem(c.cert())?;
535 config.set_certificate_authorities_from_trust_store()?;
536
537 config.build()?
538 });
539 let pick = Pick(Arc::new(Mutex::new(map)));
540 let server_config = {
541 let mut config = config_builder(&security::DEFAULT_TLS13)?;
542 config.set_client_auth_type(ClientAuthType::Required)?;
543 config.set_client_hello_callback(pick.clone())?;
544 config.build()?
545 };
546
547 let client_config = {
548 let mut config = config_builder(&security::DEFAULT_TLS13)?;
549 config.set_client_auth_type(ClientAuthType::Required)?;
550 config.set_certificate_request_callback(DynamicSelect)?;
551 config.build()?
552 };
553
554 let mut pair = TestPair::from_configs(&client_config, &server_config);
555
556 pair.client.set_server_name("a.example.com")?;
557 pair.server
558 .set_waker(Some(futures_test::task::noop_waker_ref()))?;
559 pair.handshake()?;
560
561 // Client selected the custom cert (a)
562 assert_eq!(
563 pair.client
564 .selected_cert()
565 .unwrap()
566 .iter()
567 .next()
568 .unwrap()?
569 .der()?,
570 a.into_certificate_chain().iter().next().unwrap()?.der()?
571 );
572
573 let mut pair = TestPair::from_configs(&client_config, &server_config);
574
575 pair.client.set_server_name("b.example.com")?;
576 pair.server
577 .set_waker(Some(futures_test::task::noop_waker_ref()))?;
578 pair.handshake()?;
579
580 // Client selected the custom cert (b)
581 assert_eq!(
582 pair.client
583 .selected_cert()
584 .unwrap()
585 .iter()
586 .next()
587 .unwrap()?
588 .der()?,
589 b.into_certificate_chain().iter().next().unwrap()?.der()?
590 );
591
592 // Note that the same Client config is used in both of the above connections, so this is
593 // proof that we can select different client certificates depending on server-provided CAs
594 // in the CertificateRequest callback.
595
596 Ok(())
597 }
598 }