请求host不匹配时重新生成证书

This commit is contained in:
2026-11-01 12:39:44 +08:00
parent 5b0cf965bd
commit 0f3a225516
6 changed files with 237 additions and 180 deletions
+40
View File
@@ -0,0 +1,40 @@
use crate::cert::{check_cert_included, sign};
use crate::info;
use rustls_pemfile::{certs, private_key};
use std::io::BufReader;
use std::sync::Arc;
pub fn build_tls_acceptor(target_hosts: Vec<String>) -> Arc<rustls::ServerConfig> {
let is_included_built_in = check_cert_included(target_hosts.iter().map(|s| s.as_str()));
let (cert_chain, key) = if is_included_built_in {
let fullchain = include_bytes!(concat!(env!("OUT_DIR"), "/fullchain.pem"));
let leaf_key = include_bytes!(concat!(env!("OUT_DIR"), "/leaf.key"));
let cert_chain = certs(&mut BufReader::new(&fullchain[..]))
.collect::<Result<Vec<_>, _>>()
.unwrap();
let key = private_key(&mut BufReader::new(&leaf_key[..]))
.unwrap()
.unwrap();
(cert_chain, key)
} else {
info!("Target hosts not match built-in cert, generating new cert");
let target = target_hosts.iter().map(|s| s.as_str()).collect::<Vec<_>>();
let (fullchain, leaf_key) = sign(target.iter());
let cert_chain = certs(&mut BufReader::new(fullchain.as_bytes()))
.collect::<Result<Vec<_>, _>>()
.unwrap();
let key = private_key(&mut BufReader::new(leaf_key.as_bytes()))
.unwrap()
.unwrap();
(cert_chain, key)
};
let mut config = rustls::ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(cert_chain, key)
.unwrap();
config.alpn_protocols = vec![b"http/1.1".to_vec()];
Arc::new(config)
}