Debian Codegraph @

crt/s2n/bindings/rust-examples/client-hello-config-resolution/src/bin/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, ConnectionFuture},
6 security::{Policy, DEFAULT_TLS13},
7 };
8 use s2n_tls_tokio::TlsAcceptor;
9 use std::{collections::HashMap, error::Error, pin::Pin};
10 use tokio::{io::AsyncWriteExt, net::*};
11
12 const PORT: u16 = 1738;
13
14 /// Used by the server to resolve the appropriate config
15 pub struct AnimalConfigResolver {
16 // this stores the mapping from sni -> config
17 configs: HashMap<String, s2n_tls::config::Config>,
18 }
19
20 impl Default for AnimalConfigResolver {
21 fn default() -> Self {
22 let mut configs = HashMap::new();
23 configs.insert("www.wombat.com".to_owned(), server_config("wombat"));
24 configs.insert("www.kangaroo.com".to_owned(), server_config("kangaroo"));
25 Self { configs }
26 }
27 }
28
29 // Servers that wish to do config resolution in an async manner should consider
30 // using the ConfigResolver: https://docs.rs/s2n-tls/latest/s2n_tls/callbacks/struct.ConfigResolver.html#
31 // This is useful if servers need to read from disk or make network calls as part
32 // of the configuration, and want to avoid blocking the tokio task while doing so.
33 // An example of this implementation is contained in the "async_load_server".
34 impl ClientHelloCallback for AnimalConfigResolver {
35 fn on_client_hello(
36 &self,
37 connection: &mut s2n_tls::connection::Connection,
38 ) -> Result<Option<Pin<Box<dyn ConnectionFuture>>>, s2n_tls::error::Error> {
39 let sni = match connection.server_name() {
40 Some(sni) => sni,
41 None => {
42 println!("connection contained no SNI");
43 return Err(s2n_tls::error::Error::application("no sni".into()));
44 }
45 };
46 let config_ref = match self.configs.get(sni) {
47 Some(c) => c,
48 None => {
49 println!("unknown sni: {sni}");
50 return Err(s2n_tls::error::Error::application("unknown sni".into()));
51 }
52 };
53 println!("setting connection config associated with {sni}");
54 let config = config_ref.clone();
55 connection.set_config(config).unwrap();
56 // Inform s2n-tls that the server name was used in configuration so that
57 // the appropriate extension is sent back to the peer.
58 // From RFC 6066, section 3
59 // > A server that receives a client hello containing the "server_name"
60 // > extension MAY use the information contained in the extension to guide
61 // > its selection of an appropriate certificate to return to the client,
62 // > and/or other aspects of security policy. In this event, the server
63 // > SHALL include an extension of type "server_name" in the (extended)
64 // > server hello. The "extension_data" field of this extension SHALL be
65 // > empty.
66 // https://datatracker.ietf.org/doc/html/rfc6066#section-3
67 connection.server_name_extension_used();
68 // Ok -> the function completed successfully
69 // None -> s2n-tls doesn't need to poll this to completion
70 Ok(None)
71 }
72 }
73
74 fn server_config(animal: &str) -> s2n_tls::config::Config {
75 let cert_path = format!(
76 "{}/../certs/{}-chain.pem",
77 env!("CARGO_MANIFEST_DIR"),
78 animal
79 );
80 let key_path = format!("{}/../certs/{}-key.pem", env!("CARGO_MANIFEST_DIR"), animal);
81 let cert = std::fs::read(cert_path).unwrap();
82 let key = std::fs::read(key_path).unwrap();
83 let mut config = s2n_tls::config::Builder::new();
84
85 // we can set different policies for different configs. "20190214" doesn't
86 // support TLS 1.3, so any customer requesting www.wombat.com won't be able
87 // to negotiate TLS 1.3
88 let security_policy = match animal {
89 "wombat" => Policy::from_version("20190214").unwrap(),
90 _ => DEFAULT_TLS13,
91 };
92 config.set_security_policy(&security_policy).unwrap();
93 config.load_pem(&cert, &key).unwrap();
94 config.build().unwrap()
95 }
96
97 #[tokio::main]
98 async fn main() -> Result<(), Box<dyn Error>> {
99 let resolver = AnimalConfigResolver::default();
100
101 // this is the initial config that "receives" the connection. Since we error
102 // out on an unrecognized SNI, the only important setting on this config is
103 // the client hello callback that sets the config used for the rest of the
104 // connection.
105 let mut initial_config = s2n_tls::config::Builder::new();
106 initial_config.set_client_hello_callback(resolver)?;
107
108 let server = TlsAcceptor::new(initial_config.build()?);
109
110 let listener = TcpListener::bind(&format!("0.0.0.0:{PORT}")).await?;
111 loop {
112 let server = server.clone();
113 let (stream, _) = listener.accept().await?;
114 tokio::spawn(async move {
115 // handshake with the client
116 let handshake = server.accept(stream).await;
117 let mut tls = match handshake {
118 Ok(tls) => tls,
119 Err(e) => {
120 println!("error during handshake: {:?}", e);
121 return Ok(());
122 }
123 };
124
125 let connection = tls.as_ref();
126 let offered_sni = connection.server_name().unwrap();
127 let _ = tls
128 .write(format!("Hello, you are speaking to {offered_sni}").as_bytes())
129 .await?;
130 tls.shutdown().await?;
131 Ok::<(), Box<dyn Error + Send + Sync>>(())
132 });
133 }
134 }