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::Write;
use std::net::TcpStream;
@ -101,44 +102,56 @@ pub fn shellchat<'a>(mut tokens: impl Iterator<Item = &'a str>) -> Result<Option
None => "bunnyfoo.com",
};
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);
match TcpStream::connect((target, 443)) {
Ok(mut sock) => {
log::info!("tcp connected");
write!(ret, "{}", t!("tls.test_success_tcp", locales::LANG)).ok();
let mut tls = rustls::Stream::new(&mut conn, &mut sock);
log::info!("create http headers and write to server");
let msg = format!(
"GET / HTTP/1.1\r\nHost: {}\r\nConnection: close\r\nAccept-Encoding: identity\r\n\r\n",
target
);
match tls.write_all(msg.as_bytes()) {
Ok(()) => {
log::info!("tls accepted GET");
write!(ret, "{}", t!("tls.test_success_get", locales::LANG)).ok();
let mut plaintext = Vec::new();
log::info!("read TLS response");
match tls.read_to_end(&mut plaintext) {
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"));
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);
log::info!("create http headers and write to server");
let msg = format!(
"GET / HTTP/1.1\r\nHost: {}\r\nConnection: close\r\nAccept-Encoding: identity\r\n\r\n",
target
);
match tls.write_all(msg.as_bytes()) {
Ok(()) => {
log::info!("tls accepted GET");
write!(ret, "{}", t!("tls.test_success_get", locales::LANG)).ok();
let mut plaintext = Vec::new();
log::info!("read TLS response");
match tls.read_to_end(&mut plaintext) {
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) => {
log::warn!("failed to read tls response: {e}");
log::warn!("failed to GET on tls connection: {e}");
write!(ret, "{e}\n").ok();
}
};
}
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();
}
};
}
}
Err(e) => {
log::warn!("failed to connect tcp: {e}");

View file

@ -414,12 +414,17 @@ impl Tls {
host: &str,
sock: TcpStream,
) -> Result<rustls::StreamOwned<ClientConnection, TcpStream>, Error> {
match rustls::ClientConnection::new(
Arc::new(self.client_config()),
host.try_into().expect("failed url host_str"),
) {
Ok(conn) => Ok(rustls::StreamOwned::new(conn, sock)),
Err(_) => Err(Error::new(ErrorKind::Other, "failed to configure client connection")),
match host.to_owned().try_into() {
Ok(server_name) => {
match rustls::ClientConnection::new(Arc::new(self.client_config()), server_name) {
Ok(conn) => Ok(rustls::StreamOwned::new(conn, sock)),
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 {
fn connect(&self, dns_name: &str, mut io: Box<dyn ReadWrite>) -> Result<Box<dyn ReadWrite>, ureq::Error> {
log::info!("Commencing tls connection setup");
loop {
// refresh rustls client config with current root_store
let tls = Tls::new();
let config = rustls::ClientConfig::builder()
.with_safe_defaults()
.with_root_certificates(tls.root_store())
.with_no_client_auth();
match rustls::ClientConnection::new(Arc::new(config), dns_name.try_into().unwrap()) {
Ok(mut connection) => {
log::info!("tls handshake started");
match connection.complete_io(&mut io) {
Ok(_) => {
if connection.peer_certificates().is_some() {
return Ok(Box::new(TlsStream(StreamOwned::new(connection, io))));
}
}
// errors generated late in the tls handshake
Err(e) => {
if let Some(inner) = e.get_ref() {
if let Some(rustls_error) = inner.downcast_ref::<rustls::Error>() {
if let rustls::Error::InvalidCertificate(_) = rustls_error {
if let Ok(certs) = tls.probe(dns_name) {
if certs.len() > 0 {
log::info!("try again with new trusted certs");
continue;
match ServerName::try_from(dns_name.to_owned()) {
Ok(server_name) => {
loop {
// refresh rustls client config with current root_store
let tls = Tls::new();
let config = rustls::ClientConfig::builder()
.with_root_certificates(tls.root_store())
.with_no_client_auth();
match rustls::ClientConnection::new(Arc::new(config), server_name.clone()) {
Ok(mut connection) => {
log::info!("tls handshake started");
match connection.complete_io(&mut io) {
Ok(_) => {
if connection.peer_certificates().is_some() {
return Ok(Box::new(TlsStream(StreamOwned::new(connection, io))));
}
}
// errors generated late in the tls handshake
Err(e) => {
if let Some(inner) = e.get_ref() {
if let Some(rustls_error) = inner.downcast_ref::<rustls::Error>() {
if let rustls::Error::InvalidCertificate(_) = rustls_error {
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
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}");
break;
}
}
}
// errors generated early in the tls handshake
Err(rustls::Error::InvalidCertificate(_)) => {
if let Ok(certs) = tls.probe(dns_name) {
if certs.len() > 0 {
log::info!("try again with new trusted certs");
continue;
}
}
}
// non certificate chain errors
Err(e) => {
log::warn!("{e}");
break;
}
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(),
))
}
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(),
))
}
}
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()))
}
}