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,14 +102,15 @@ 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();
match ServerName::try_from(target.to_owned()) {
Ok(server_name) => {
let mut conn =
rustls::ClientConnection::new(Arc::new(config), server_name).unwrap();
let mut tls = rustls::Stream::new(&mut conn, &mut sock); let mut tls = rustls::Stream::new(&mut conn, &mut sock);
log::info!("create http headers and write to server"); log::info!("create http headers and write to server");
let msg = format!( let msg = format!(
@ -124,7 +126,12 @@ pub fn shellchat<'a>(mut tokens: impl Iterator<Item = &'a str>) -> Result<Option
match tls.read_to_end(&mut plaintext) { match tls.read_to_end(&mut plaintext) {
Ok(n) => { Ok(n) => {
log::info!("tls received {} bytes", n); log::info!("tls received {} bytes", n);
write!(ret, "{} {}\n", t!("tls.test_success_bytes", locales::LANG), n) write!(
ret,
"{} {}\n",
t!("tls.test_success_bytes", locales::LANG),
n
)
.ok(); .ok();
log::info!("{}", from_utf8(&plaintext).unwrap_or("utf-error")); log::info!("{}", from_utf8(&plaintext).unwrap_or("utf-error"));
} }
@ -140,6 +147,12 @@ pub fn shellchat<'a>(mut tokens: impl Iterator<Item = &'a str>) -> Result<Option
} }
}; };
} }
Err(e) => {
log::warn!("failed to convert target into a valid ServerName: {e}");
write!(ret, "{e}\n").ok();
}
}
}
Err(e) => { Err(e) => {
log::warn!("failed to connect tcp: {e}"); log::warn!("failed to connect tcp: {e}");
write!(ret, "{e}\n").ok(); write!(ret, "{e}\n").ok();

View file

@ -414,14 +414,19 @@ 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))
}
}
}
} }
// https://stackoverflow.com/questions/57029974/how-to-split-string-into-chunks-in-rust-to-insert-spaces // https://stackoverflow.com/questions/57029974/how-to-split-string-into-chunks-in-rust-to-insert-spaces

View file

@ -14,14 +14,15 @@ 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");
match ServerName::try_from(dns_name.to_owned()) {
Ok(server_name) => {
loop { loop {
// refresh rustls client config with current root_store // refresh rustls client config with current root_store
let tls = Tls::new(); let tls = Tls::new();
let config = rustls::ClientConfig::builder() let config = rustls::ClientConfig::builder()
.with_safe_defaults()
.with_root_certificates(tls.root_store()) .with_root_certificates(tls.root_store())
.with_no_client_auth(); .with_no_client_auth();
match rustls::ClientConnection::new(Arc::new(config), dns_name.try_into().unwrap()) { match rustls::ClientConnection::new(Arc::new(config), server_name.clone()) {
Ok(mut connection) => { Ok(mut connection) => {
log::info!("tls handshake started"); log::info!("tls handshake started");
match connection.complete_io(&mut io) { match connection.complete_io(&mut io) {
@ -36,6 +37,7 @@ impl ureq::TlsConnector for TlsConnector {
if let Some(rustls_error) = inner.downcast_ref::<rustls::Error>() { if let Some(rustls_error) = inner.downcast_ref::<rustls::Error>() {
if let rustls::Error::InvalidCertificate(_) = rustls_error { if let rustls::Error::InvalidCertificate(_) = rustls_error {
if let Ok(certs) = tls.probe(dns_name) { if let Ok(certs) = tls.probe(dns_name) {
if let Some(certs) = certs {
if certs.len() > 0 { if certs.len() > 0 {
log::info!("try again with new trusted certs"); log::info!("try again with new trusted certs");
continue; continue;
@ -44,6 +46,7 @@ impl ureq::TlsConnector for TlsConnector {
} }
} }
} }
}
// non certificate chain errors // non certificate chain errors
log::warn!("{e}"); log::warn!("{e}");
break; break;
@ -53,12 +56,14 @@ impl ureq::TlsConnector for TlsConnector {
// errors generated early in the tls handshake // errors generated early in the tls handshake
Err(rustls::Error::InvalidCertificate(_)) => { Err(rustls::Error::InvalidCertificate(_)) => {
if let Ok(certs) = tls.probe(dns_name) { if let Ok(certs) = tls.probe(dns_name) {
if let Some(certs) = certs {
if certs.len() > 0 { if certs.len() > 0 {
log::info!("try again with new trusted certs"); log::info!("try again with new trusted certs");
continue; continue;
} }
} }
} }
}
// non certificate chain errors // non certificate chain errors
Err(e) => { Err(e) => {
log::warn!("{e}"); log::warn!("{e}");
@ -68,7 +73,20 @@ impl ureq::TlsConnector for TlsConnector {
} }
log::warn!("failed to establish tls connection"); log::warn!("failed to establish tls connection");
// this would be better as a ureq:Error::Transport but they are hard to build // 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())) Err(ureq::Error::Status(
526,
Response::new(526, "tls", "untrusted certificate chain").unwrap(),
))
}
Err(e) => {
log::warn!("failed to convert dns_name into a valid server name: {e}");
Err(ureq::Error::Status(
400,
Response::new(526, "http", "failed to convert dns_name into a valid server name")
.unwrap(),
))
}
}
} }
} }