271 lines
9.7 KiB
Rust
271 lines
9.7 KiB
Rust
use openssl::{
|
|
asn1::Asn1Time,
|
|
bn::{BigNum, MsbOption},
|
|
ec::{EcGroup, EcKey},
|
|
hash::MessageDigest,
|
|
nid::Nid,
|
|
pkey::{PKey, Private},
|
|
ssl::{SslAcceptor, SslMethod, SslVerifyMode},
|
|
x509::{
|
|
X509, X509NameBuilder,
|
|
extension::{BasicConstraints, ExtendedKeyUsage, KeyUsage, SubjectAlternativeName},
|
|
},
|
|
};
|
|
use std::{
|
|
io::{Read, Write},
|
|
net::{SocketAddr, TcpListener},
|
|
sync::{
|
|
Arc,
|
|
atomic::{AtomicBool, Ordering},
|
|
},
|
|
thread,
|
|
time::Duration,
|
|
};
|
|
pub fn key() -> PKey<Private> {
|
|
let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
|
|
PKey::from_ec_key(EcKey::generate(&group).unwrap()).unwrap()
|
|
}
|
|
pub struct Pki {
|
|
pub ca: X509,
|
|
pub ca_key: PKey<Private>,
|
|
}
|
|
impl Pki {
|
|
pub fn new() -> Self {
|
|
let ca_key = key();
|
|
let mut name = X509NameBuilder::new().unwrap();
|
|
name.append_entry_by_text("CN", "Ephemeral transport test CA")
|
|
.unwrap();
|
|
let name = name.build();
|
|
let mut b = X509::builder().unwrap();
|
|
b.set_version(2).unwrap();
|
|
let mut serial = BigNum::new().unwrap();
|
|
serial.rand(128, MsbOption::MAYBE_ZERO, false).unwrap();
|
|
b.set_serial_number(&serial.to_asn1_integer().unwrap())
|
|
.unwrap();
|
|
b.set_subject_name(&name).unwrap();
|
|
b.set_issuer_name(&name).unwrap();
|
|
b.set_pubkey(&ca_key).unwrap();
|
|
let now = chrono::Utc::now().timestamp();
|
|
b.set_not_before(&Asn1Time::from_unix(now - 60 * 86400).unwrap())
|
|
.unwrap();
|
|
b.set_not_after(&Asn1Time::from_unix(now + 365 * 86400).unwrap())
|
|
.unwrap();
|
|
b.append_extension(BasicConstraints::new().critical().ca().build().unwrap())
|
|
.unwrap();
|
|
b.append_extension(
|
|
KeyUsage::new()
|
|
.critical()
|
|
.key_cert_sign()
|
|
.crl_sign()
|
|
.build()
|
|
.unwrap(),
|
|
)
|
|
.unwrap();
|
|
b.sign(&ca_key, MessageDigest::sha256()).unwrap();
|
|
Self {
|
|
ca: b.build(),
|
|
ca_key,
|
|
}
|
|
}
|
|
pub fn issue(
|
|
&self,
|
|
public: &openssl::pkey::PKeyRef<impl openssl::pkey::HasPublic>,
|
|
cn: &str,
|
|
server: bool,
|
|
from: i64,
|
|
until: i64,
|
|
) -> X509 {
|
|
let mut name = X509NameBuilder::new().unwrap();
|
|
name.append_entry_by_text("CN", cn).unwrap();
|
|
let mut b = X509::builder().unwrap();
|
|
b.set_version(2).unwrap();
|
|
let mut serial = BigNum::new().unwrap();
|
|
serial.rand(128, MsbOption::MAYBE_ZERO, false).unwrap();
|
|
b.set_serial_number(&serial.to_asn1_integer().unwrap())
|
|
.unwrap();
|
|
b.set_subject_name(&name.build()).unwrap();
|
|
b.set_issuer_name(self.ca.subject_name()).unwrap();
|
|
b.set_pubkey(public).unwrap();
|
|
b.set_not_before(&Asn1Time::from_unix(from).unwrap())
|
|
.unwrap();
|
|
b.set_not_after(&Asn1Time::from_unix(until).unwrap())
|
|
.unwrap();
|
|
b.append_extension(BasicConstraints::new().critical().build().unwrap())
|
|
.unwrap();
|
|
b.append_extension(
|
|
KeyUsage::new()
|
|
.critical()
|
|
.digital_signature()
|
|
.build()
|
|
.unwrap(),
|
|
)
|
|
.unwrap();
|
|
let mut eku = ExtendedKeyUsage::new();
|
|
if server {
|
|
eku.server_auth();
|
|
} else {
|
|
eku.client_auth();
|
|
}
|
|
b.append_extension(eku.build().unwrap()).unwrap();
|
|
if server {
|
|
let san = SubjectAlternativeName::new()
|
|
.dns(cn)
|
|
.build(&b.x509v3_context(Some(&self.ca), None))
|
|
.unwrap();
|
|
b.append_extension(san).unwrap();
|
|
}
|
|
b.sign(&self.ca_key, MessageDigest::sha256()).unwrap();
|
|
b.build()
|
|
}
|
|
}
|
|
pub struct Request {
|
|
pub path: String,
|
|
pub body: Vec<u8>,
|
|
pub content_type: String,
|
|
}
|
|
pub struct Response {
|
|
pub status: u16,
|
|
pub media: &'static str,
|
|
pub body: Vec<u8>,
|
|
}
|
|
impl Response {
|
|
pub fn protobuf(body: Vec<u8>) -> Self {
|
|
Self {
|
|
status: 200,
|
|
media: "application/x-protobuf",
|
|
body,
|
|
}
|
|
}
|
|
}
|
|
pub struct Server {
|
|
pub address: SocketAddr,
|
|
stop: Arc<AtomicBool>,
|
|
worker: Option<thread::JoinHandle<()>>,
|
|
}
|
|
impl Server {
|
|
pub fn start(
|
|
pki: &Pki,
|
|
dns: &str,
|
|
handler: impl Fn(Request) -> Option<Response> + Send + 'static,
|
|
) -> Self {
|
|
let server_key = key();
|
|
let now = chrono::Utc::now().timestamp();
|
|
let cert = pki.issue(&server_key, dns, true, now - 60, now + 86400);
|
|
let mut tls = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
|
|
// OpenSSL requires a session-id context when verifying client certificates,
|
|
// including when a reconnect offers a previous session. Cache/ticket
|
|
// disabling alone does not satisfy ssl_get_prev_session on OpenSSL 1.1.1.
|
|
tls.set_session_id_context(b"agent-transport-test").unwrap();
|
|
tls.set_private_key(&server_key).unwrap();
|
|
tls.set_certificate(&cert).unwrap();
|
|
tls.cert_store_mut().add_cert(pki.ca.clone()).unwrap();
|
|
tls.set_verify(SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT);
|
|
let tls = tls.build();
|
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
|
let address = listener.local_addr().unwrap();
|
|
listener.set_nonblocking(true).unwrap();
|
|
let stop = Arc::new(AtomicBool::new(false));
|
|
let stopped = stop.clone();
|
|
let worker = thread::spawn(move || {
|
|
while !stopped.load(Ordering::SeqCst) {
|
|
let stream = match listener.accept() {
|
|
Ok((stream, _)) => stream,
|
|
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
|
|
thread::sleep(Duration::from_millis(5));
|
|
continue;
|
|
}
|
|
Err(_) => break,
|
|
};
|
|
stream
|
|
.set_read_timeout(Some(Duration::from_secs(3)))
|
|
.unwrap();
|
|
stream
|
|
.set_write_timeout(Some(Duration::from_secs(3)))
|
|
.unwrap();
|
|
let mut stream = match tls.accept(stream) {
|
|
Ok(stream) => stream,
|
|
Err(openssl::ssl::HandshakeError::Failure(stream)) => {
|
|
let error = stream.error();
|
|
eprintln!("TEST_TLS_ACCEPT code={:?}", error.code());
|
|
if let Some(stack) = error.ssl_error() {
|
|
for frame in stack.errors() {
|
|
// Static library metadata only: never print error data,
|
|
// peer names, certificates, keys or request contents.
|
|
eprintln!(
|
|
"TEST_TLS_FRAME code={} library={:?} function={:?} reason={:?}",
|
|
frame.code(),
|
|
frame.library(),
|
|
frame.function(),
|
|
frame.reason()
|
|
);
|
|
}
|
|
}
|
|
continue;
|
|
}
|
|
Err(_) => {
|
|
eprintln!("TEST_TLS_ACCEPT setup_or_would_block");
|
|
continue;
|
|
}
|
|
};
|
|
let mut header = Vec::new();
|
|
while !header.ends_with(b"\r\n\r\n") && header.len() < 16384 {
|
|
let mut byte = [0];
|
|
if stream.read_exact(&mut byte).is_err() {
|
|
break;
|
|
}
|
|
header.push(byte[0]);
|
|
}
|
|
let header = String::from_utf8_lossy(&header);
|
|
let path = header
|
|
.split_whitespace()
|
|
.nth(1)
|
|
.unwrap_or_default()
|
|
.to_owned();
|
|
let mut length = 0;
|
|
let mut content_type = String::new();
|
|
for line in header.lines().skip(1) {
|
|
if let Some((name, value)) = line.split_once(':') {
|
|
if name.eq_ignore_ascii_case("content-length") {
|
|
length = value.trim().parse::<usize>().unwrap();
|
|
}
|
|
if name.eq_ignore_ascii_case("content-type") {
|
|
content_type = value.trim().into();
|
|
}
|
|
}
|
|
}
|
|
assert!(length <= 1024 * 1024);
|
|
let mut body = vec![0; length];
|
|
if stream.read_exact(&mut body).is_err() {
|
|
continue;
|
|
}
|
|
if let Some(response) = handler(Request {
|
|
path,
|
|
body,
|
|
content_type,
|
|
}) {
|
|
let header = format!(
|
|
"HTTP/1.1 {} Test\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
|
response.status,
|
|
response.media,
|
|
response.body.len()
|
|
);
|
|
let _ = stream.write_all(header.as_bytes());
|
|
let _ = stream.write_all(&response.body);
|
|
let _ = stream.flush();
|
|
}
|
|
}
|
|
});
|
|
Self {
|
|
address,
|
|
stop,
|
|
worker: Some(worker),
|
|
}
|
|
}
|
|
}
|
|
impl Drop for Server {
|
|
fn drop(&mut self) {
|
|
self.stop.store(true, Ordering::SeqCst);
|
|
self.worker.take().unwrap().join().unwrap();
|
|
}
|
|
}
|