Debian Codegraph @

crt/s2n/bindings/rust-examples/client-hello-config-resolution/src/bin/async_load_server.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 s2n_tls::{
5 callbacks::{ClientHelloCallback, ConfigResolver, ConnectionFuture},
6 security::{Policy, DEFAULT_TLS13},
7 };
8 use s2n_tls_tokio::TlsAcceptor;
9 use std::{error::Error, pin::Pin};
10 use tokio::{io::AsyncWriteExt, net::*, try_join};
11
12 const PORT: u16 = 1738;
13
14 #[derive(Clone)]
15 pub struct AsyncAnimalConfigResolver {
16 // the directory that contains the relevant certs
17 cert_directory: String,
18 }
19
20 impl AsyncAnimalConfigResolver {
21 fn new(cert_directory: String) -> Self {
22 AsyncAnimalConfigResolver { cert_directory }
23 }
24 }
25
26 impl ClientHelloCallback for AsyncAnimalConfigResolver {
27 fn on_client_hello(
28 &self,
29 connection: &mut s2n_tls::connection::Connection,
30 ) -> Result<Option<Pin<Box<dyn ConnectionFuture>>>, s2n_tls::error::Error> {
31 let sni = match connection.server_name() {
32 Some(sni) => sni,
33 None => {
34 println!("connection contained no SNI");
35 return Err(s2n_tls::error::Error::application("no sni".into()));
36 }
37 };
38
39 // simple, limited logic to parse "animal" from "www.animal.com".
40 let mut tokens = sni.split('.');
41 tokens.next(); // "www"
42 let animal = match tokens.next() {
43 Some(animal) => animal.to_owned(), // "animal"
44 None => {
45 println!("unable to parse sni");
46 return Err(s2n_tls::error::Error::application(
47 format!("unable to parse sni: {}", sni).into(),
48 ));
49 }
50 };
51
52 let config_future = server_config(animal, self.cert_directory.clone());
53 let config_resolver = ConfigResolver::new(config_future);
54 connection.server_name_extension_used();
55 Ok(Some(Box::pin(config_resolver)))
56 }
57 }
58
59 // This method will lookup the appropriate certificates and read them from disk
60 // in an async manner which won't block the tokio task.
61 //
62 // Note that this method takes `String` instead of `&str` like the synchronous
63 // version in server.rs. ConfigResolver requires a future that is `'static`.
64 async fn server_config(
65 animal: String,
66 cert_directory: String,
67 ) -> Result<s2n_tls::config::Config, s2n_tls::error::Error> {
68 println!("asynchronously setting connection config associated with {animal}");
69
70 let cert_path = format!("{}/{}-chain.pem", cert_directory, animal);
71 let key_path = format!("{}/{}-key.pem", cert_directory, animal);
72 // we asynchronously read the cert chain and key from disk
73 let (cert, key) = try_join!(tokio::fs::read(cert_path), tokio::fs::read(key_path))
74 // we map any IO errors to the s2n-tls Error type, as required by the ConfigResolver bounds.
75 .map_err(|io_error| s2n_tls::error::Error::application(Box::new(io_error)))?;
76
77 let mut config = s2n_tls::config::Builder::new();
78 // we can set different policies for different configs. "20190214" doesn't
79 // support TLS 1.3, so any customer requesting www.wombat.com won't be able
80 // to negotiate TLS 1.3
81 let security_policy = match animal.as_str() {
82 "wombat" => Policy::from_version("20190214")?,
83 _ => DEFAULT_TLS13,
84 };
85 config.set_security_policy(&security_policy)?;
86 config.load_pem(&cert, &key)?;
87 config.build()
88 }
89
90 #[tokio::main]
91 async fn main() -> Result<(), Box<dyn Error>> {
92 let cert_directory = format!("{}/certs", env!("CARGO_MANIFEST_DIR"));
93 let resolver = AsyncAnimalConfigResolver::new(cert_directory);
94 let mut initial_config = s2n_tls::config::Builder::new();
95 initial_config.set_client_hello_callback(resolver)?;
96
97 let server = TlsAcceptor::new(initial_config.build()?);
98
99 let listener = TcpListener::bind(&format!("0.0.0.0:{PORT}")).await?;
100 loop {
101 let server = server.clone();
102 let (stream, _) = listener.accept().await?;
103 tokio::spawn(async move {
104 // handshake with the client
105 let handshake = server.accept(stream).await;
106 let mut tls = match handshake {
107 Ok(tls) => tls,
108 Err(e) => {
109 println!("error during handshake: {:?}", e);
110 return Ok(());
111 }
112 };
113
114 let connection = tls.as_ref();
115 let offered_sni = connection.server_name().unwrap();
116 let _ = tls
117 .write(format!("Hello, you are speaking to {offered_sni}").as_bytes())
118 .await?;
119 tls.shutdown().await?;
120 Ok::<(), Box<dyn Error + Send + Sync>>(())
121 });
122 }
123 }