resolve tls ownership issues

This commit is contained in:
nworbnhoj 2024-02-25 05:23:57 +10:00
parent 39f3b782fa
commit 2d744f1267
3 changed files with 110 additions and 74 deletions

View file

@ -1,4 +1,5 @@
use std::convert::TryInto; use rustls::pki_types::ServerName;
use std::convert::TryFrom;
use std::io::Read; use std::io::Read;
use std::io::Write; use std::io::Write;
use std::net::TcpStream; use std::net::TcpStream;
@ -101,44 +102,56 @@ pub fn shellchat<'a>(mut tokens: impl Iterator<Item = &'a str>) -> Result<Option
None => "bunnyfoo.com", None => "bunnyfoo.com",
}; };
log::info!("point TLS to {}", target); log::info!("point TLS to {}", target);
let mut conn =
rustls::ClientConnection::new(Arc::new(config), target.try_into().unwrap()).unwrap();
log::info!("connect TCPstream to {}", target); log::info!("connect TCPstream to {}", target);
match TcpStream::connect((target, 443)) { match TcpStream::connect((target, 443)) {
Ok(mut sock) => { Ok(mut sock) => {
log::info!("tcp connected"); log::info!("tcp connected");
write!(ret, "{}", t!("tls.test_success_tcp", locales::LANG)).ok(); write!(ret, "{}", t!("tls.test_success_tcp", locales::LANG)).ok();
let mut tls = rustls::Stream::new(&mut conn, &mut sock); match ServerName::try_from(target.to_owned()) {
log::info!("create http headers and write to server"); Ok(server_name) => {
let msg = format!( let mut conn =
"GET / HTTP/1.1\r\nHost: {}\r\nConnection: close\r\nAccept-Encoding: identity\r\n\r\n", rustls::ClientConnection::new(Arc::new(config), server_name).unwrap();
target let mut tls = rustls::Stream::new(&mut conn, &mut sock);
); log::info!("create http headers and write to server");
match tls.write_all(msg.as_bytes()) { let msg = format!(
Ok(()) => { "GET / HTTP/1.1\r\nHost: {}\r\nConnection: close\r\nAccept-Encoding: identity\r\n\r\n",
log::info!("tls accepted GET"); target
write!(ret, "{}", t!("tls.test_success_get", locales::LANG)).ok(); );
let mut plaintext = Vec::new(); match tls.write_all(msg.as_bytes()) {
log::info!("read TLS response"); Ok(()) => {
match tls.read_to_end(&mut plaintext) { log::info!("tls accepted GET");
Ok(n) => { write!(ret, "{}", t!("tls.test_success_get", locales::LANG)).ok();
log::info!("tls received {} bytes", n); let mut plaintext = Vec::new();
write!(ret, "{} {}\n", t!("tls.test_success_bytes", locales::LANG), n) log::info!("read TLS response");
.ok(); match tls.read_to_end(&mut plaintext) {
log::info!("{}", from_utf8(&plaintext).unwrap_or("utf-error")); Ok(n) => {
log::info!("tls received {} bytes", n);
write!(
ret,
"{} {}\n",
t!("tls.test_success_bytes", locales::LANG),
n
)
.ok();
log::info!("{}", from_utf8(&plaintext).unwrap_or("utf-error"));
}
Err(e) => {
log::warn!("failed to read tls response: {e}");
write!(ret, "{e}\n").ok();
}
};
} }
Err(e) => { Err(e) => {
log::warn!("failed to read tls response: {e}"); log::warn!("failed to GET on tls connection: {e}");
write!(ret, "{e}\n").ok(); write!(ret, "{e}\n").ok();
} }
}; };
} }
Err(e) => { Err(e) => {
log::warn!("failed to GET on tls connection: {e}"); log::warn!("failed to convert target into a valid ServerName: {e}");
write!(ret, "{e}\n").ok(); write!(ret, "{e}\n").ok();
} }
}; }
} }
Err(e) => { Err(e) => {
log::warn!("failed to connect tcp: {e}"); log::warn!("failed to connect tcp: {e}");

View file

@ -414,12 +414,17 @@ impl Tls {
host: &str, host: &str,
sock: TcpStream, sock: TcpStream,
) -> Result<rustls::StreamOwned<ClientConnection, TcpStream>, Error> { ) -> Result<rustls::StreamOwned<ClientConnection, TcpStream>, Error> {
match rustls::ClientConnection::new( match host.to_owned().try_into() {
Arc::new(self.client_config()), Ok(server_name) => {
host.try_into().expect("failed url host_str"), match rustls::ClientConnection::new(Arc::new(self.client_config()), server_name) {
) { Ok(conn) => Ok(rustls::StreamOwned::new(conn, sock)),
Ok(conn) => Ok(rustls::StreamOwned::new(conn, sock)), Err(_) => Err(Error::new(ErrorKind::Other, "failed to configure client connection")),
Err(_) => Err(Error::new(ErrorKind::Other, "failed to configure client connection")), }
}
Err(e) => {
log::warn!("failed to create sever_name from {host}: {e}");
Err(Error::from(ErrorKind::InvalidInput))
}
} }
} }
} }

View file

@ -14,61 +14,79 @@ pub struct TlsConnector {}
impl ureq::TlsConnector for TlsConnector { impl ureq::TlsConnector for TlsConnector {
fn connect(&self, dns_name: &str, mut io: Box<dyn ReadWrite>) -> Result<Box<dyn ReadWrite>, ureq::Error> { fn connect(&self, dns_name: &str, mut io: Box<dyn ReadWrite>) -> Result<Box<dyn ReadWrite>, ureq::Error> {
log::info!("Commencing tls connection setup"); log::info!("Commencing tls connection setup");
loop { match ServerName::try_from(dns_name.to_owned()) {
// refresh rustls client config with current root_store Ok(server_name) => {
let tls = Tls::new(); loop {
let config = rustls::ClientConfig::builder() // refresh rustls client config with current root_store
.with_safe_defaults() let tls = Tls::new();
.with_root_certificates(tls.root_store()) let config = rustls::ClientConfig::builder()
.with_no_client_auth(); .with_root_certificates(tls.root_store())
match rustls::ClientConnection::new(Arc::new(config), dns_name.try_into().unwrap()) { .with_no_client_auth();
Ok(mut connection) => { match rustls::ClientConnection::new(Arc::new(config), server_name.clone()) {
log::info!("tls handshake started"); Ok(mut connection) => {
match connection.complete_io(&mut io) { log::info!("tls handshake started");
Ok(_) => { match connection.complete_io(&mut io) {
if connection.peer_certificates().is_some() { Ok(_) => {
return Ok(Box::new(TlsStream(StreamOwned::new(connection, io)))); if connection.peer_certificates().is_some() {
} return Ok(Box::new(TlsStream(StreamOwned::new(connection, io))));
} }
// errors generated late in the tls handshake }
Err(e) => { // errors generated late in the tls handshake
if let Some(inner) = e.get_ref() { Err(e) => {
if let Some(rustls_error) = inner.downcast_ref::<rustls::Error>() { if let Some(inner) = e.get_ref() {
if let rustls::Error::InvalidCertificate(_) = rustls_error { if let Some(rustls_error) = inner.downcast_ref::<rustls::Error>() {
if let Ok(certs) = tls.probe(dns_name) { if let rustls::Error::InvalidCertificate(_) = rustls_error {
if certs.len() > 0 { if let Ok(certs) = tls.probe(dns_name) {
log::info!("try again with new trusted certs"); if let Some(certs) = certs {
continue; if certs.len() > 0 {
log::info!("try again with new trusted certs");
continue;
}
}
}
} }
} }
} }
// non certificate chain errors
log::warn!("{e}");
break;
} }
} }
// non certificate chain errors }
// errors generated early in the tls handshake
Err(rustls::Error::InvalidCertificate(_)) => {
if let Ok(certs) = tls.probe(dns_name) {
if let Some(certs) = certs {
if certs.len() > 0 {
log::info!("try again with new trusted certs");
continue;
}
}
}
}
// non certificate chain errors
Err(e) => {
log::warn!("{e}"); log::warn!("{e}");
break; break;
} }
} }
} }
// errors generated early in the tls handshake log::warn!("failed to establish tls connection");
Err(rustls::Error::InvalidCertificate(_)) => { // this would be better as a ureq:Error::Transport but they are hard to build
if let Ok(certs) = tls.probe(dns_name) { Err(ureq::Error::Status(
if certs.len() > 0 { 526,
log::info!("try again with new trusted certs"); Response::new(526, "tls", "untrusted certificate chain").unwrap(),
continue; ))
} }
} Err(e) => {
} log::warn!("failed to convert dns_name into a valid server name: {e}");
// non certificate chain errors Err(ureq::Error::Status(
Err(e) => { 400,
log::warn!("{e}"); Response::new(526, "http", "failed to convert dns_name into a valid server name")
break; .unwrap(),
} ))
} }
} }
log::warn!("failed to establish tls connection");
// this would be better as a ureq:Error::Transport but they are hard to build
Err(ureq::Error::Status(526, Response::new(526, "tls", "untrusted certificate chain").unwrap()))
} }
} }