Answer#
A TLS server needs a certificate chain (its own certificate, then any intermediates) and the matching private key. In production the certificate comes from a certificate authority, for example through the ACME protocol, and the key is a secret like any other. For tests you can generate a certificate in memory.
The program below runs the whole TLS handshake between a client and a server that exchange bytes through memory, so it needs no network and no files. The client trusts exactly the generated certificate.
use rustls::{crypto::ring, ClientConfig, ClientConnection, RootCertStore, ServerConfig, ServerConnection};
use rustls_pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName};
use std::sync::Arc;
/// Run a TLS handshake between a client and a server that talk through memory, not a network.
fn handshake(client: Arc<ClientConfig>, server: Arc<ServerConfig>, name: &'static str) -> Result<String, String> {
let mut c = ClientConnection::new(client, ServerName::try_from(name).unwrap()).map_err(|e| e.to_string())?;
let mut s = ServerConnection::new(server).map_err(|e| e.to_string())?;
for _ in 0..10 {
let mut buf = Vec::new();
c.write_tls(&mut buf).unwrap();
s.read_tls(&mut buf.as_slice()).unwrap();
s.process_new_packets().map_err(|e| e.to_string())?;
buf.clear();
s.write_tls(&mut buf).unwrap();
c.read_tls(&mut buf.as_slice()).unwrap();
c.process_new_packets().map_err(|e| e.to_string())?;
if !c.is_handshaking() && !s.is_handshaking() {
return Ok(format!("{:?}", c.protocol_version().unwrap()));
}
}
Err("no result".into())
}
fn main() {
let provider = Arc::new(ring::default_provider());
// A throw-away certificate for "localhost", made in memory for this demonstration.
let cert = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
let cert_der: CertificateDer<'static> = cert.cert.der().clone();
let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(cert.key_pair.serialize_der()));
let server = ServerConfig::builder_with_provider(provider.clone())
.with_safe_default_protocol_versions().unwrap()
.with_no_client_auth()
.with_single_cert(vec![cert_der.clone()], key).unwrap();
// The client trusts exactly this certificate, and still checks the name.
let mut roots = RootCertStore::empty();
roots.add(cert_der).unwrap();
let client = ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions().unwrap()
.with_root_certificates(roots)
.with_no_client_auth();
let (client, server) = (Arc::new(client), Arc::new(server));
println!("localhost: {:?}", handshake(client.clone(), server.clone(), "localhost"));
println!("other.test: {:?}", handshake(client, server, "other.test"));
}localhost: Ok("TLSv1_3")
other.test: Err("invalid peer certificate: certificate not valid for name \"other.test\"; certificate is only valid for DnsName(\"localhost\")")The first line shows that TLS 1.3 was negotiated for localhost. The second shows that the client still checks the name: the certificate is only valid for localhost, so a connection for other.test fails.
[dependencies]
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
rustls-pki-types = "1"
rcgen = "0.13"How to do it#
- Load the certificate chain and key from files that only the service account can read (for example with the
rustls-pemfilecrate), or from your certificate manager. - Build
ServerConfigwith the safe default protocol versions andwith_single_cert. - Wrap each accepted TCP stream in a
ServerConnection, or usetokio-rustlsfor async servers. - Reload the certificate before it expires; automate renewal.
- Redirect plain HTTP to HTTPS and send the
Strict-Transport-Securityheader once HTTPS works everywhere.
Common mistakes#
- Shipping a generated test certificate or key in the repository. Keep test keys apart from production keys.
- Serving the leaf certificate without the intermediates, which breaks some clients.
- Letting the private key file be readable by other users.
Related questions#
Do I need client certificates?#
Only for mutual TLS between services. Use with_client_cert_verifier on the server for that; ordinary web servers do not use it.
How do I serve HTTPS from a web framework?#
Frameworks that support rustls take a ServerConfig or a pair of file paths. Read the documentation of the framework version you use; the configuration shown here is what they build for you.
Sources#
- rustls documentation,
ServerConfig: https://docs.rs/rustls/0.23.46/rustls/server/struct.ServerConfig.html rcgendocumentation: https://docs.rs/rcgen/0.13.2/rcgen/- Mozilla Server Side TLS guidelines: https://wiki.mozilla.org/Security/Server_Side_TLS