format libs/tls

This commit is contained in:
bunnie 2024-01-14 19:13:54 +08:00
parent 84590c58fc
commit c43fd370ee
5 changed files with 67 additions and 193 deletions

View file

@ -1,19 +1,19 @@
use crate::Tls;
use locales::t;
#[cfg(feature = "rootCA")]
use modals::Modals;
use std::convert::TryInto; use std::convert::TryInto;
use std::io::Read; use std::io::Read;
use std::io::Write; use std::io::Write;
use std::net::TcpStream; use std::net::TcpStream;
use std::str::from_utf8; use std::str::from_utf8;
use std::sync::Arc; use std::sync::Arc;
use locales::t;
#[cfg(feature = "rootCA")]
use modals::Modals;
#[cfg(feature = "rootCA")] #[cfg(feature = "rootCA")]
use xous_names::XousNames; use xous_names::XousNames;
pub fn shellchat<'a>( use crate::Tls;
mut tokens: impl Iterator<Item = &'a str>,
) -> Result<Option<String>, xous::Error> { pub fn shellchat<'a>(mut tokens: impl Iterator<Item = &'a str>) -> Result<Option<String>, xous::Error> {
use core::fmt::Write; use core::fmt::Write;
let mut ret = String::new(); let mut ret = String::new();
match tokens.next() { match tokens.next() {
@ -81,15 +81,8 @@ pub fn shellchat<'a>(
}; };
let tls = Tls::new(); let tls = Tls::new();
match tls.inspect(target) { match tls.inspect(target) {
Ok(count) => { Ok(count) => write!(ret, "{} {}", count, t!("tls.inspect_done", locales::LANG)).ok(),
write!(ret, "{} {}", count, t!("tls.inspect_done", locales::LANG)).ok() Err(_) => write!(ret, "{} {target}", t!("tls.inspect_fail_servername", locales::LANG)).ok(),
}
Err(_) => write!(
ret,
"{} {target}",
t!("tls.inspect_fail_servername", locales::LANG)
)
.ok(),
}; };
log::set_max_level(log::LevelFilter::Info); log::set_max_level(log::LevelFilter::Info);
} }
@ -109,8 +102,7 @@ pub fn shellchat<'a>(
}; };
log::info!("point TLS to {}", target); log::info!("point TLS to {}", target);
let mut conn = let mut conn =
rustls::ClientConnection::new(Arc::new(config), target.try_into().unwrap()) rustls::ClientConnection::new(Arc::new(config), target.try_into().unwrap()).unwrap();
.unwrap();
log::info!("connect TCPstream to {}", target); log::info!("connect TCPstream to {}", target);
match TcpStream::connect((target, 443)) { match TcpStream::connect((target, 443)) {
@ -119,7 +111,10 @@ pub fn shellchat<'a>(
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); 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!("GET / HTTP/1.1\r\nHost: {}\r\nConnection: close\r\nAccept-Encoding: identity\r\n\r\n", target); 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()) { match tls.write_all(msg.as_bytes()) {
Ok(()) => { Ok(()) => {
log::info!("tls accepted GET"); log::info!("tls accepted GET");
@ -129,13 +124,8 @@ pub fn shellchat<'a>(
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!( write!(ret, "{} {}\n", t!("tls.test_success_bytes", locales::LANG), n)
ret, .ok();
"{} {}\n",
t!("tls.test_success_bytes", locales::LANG),
n
)
.ok();
log::info!("{}", from_utf8(&plaintext).unwrap_or("utf-error")); log::info!("{}", from_utf8(&plaintext).unwrap_or("utf-error"));
} }
Err(e) => { Err(e) => {
@ -160,28 +150,13 @@ pub fn shellchat<'a>(
} }
None | _ => { None | _ => {
write!(ret, "{}\n", t!("tls.cmd", locales::LANG)).ok(); write!(ret, "{}\n", t!("tls.cmd", locales::LANG)).ok();
write!( write!(ret, "\tdeleteall\t{}\n", t!("tls.deleteall_cmd", locales::LANG)).ok();
ret,
"\tdeleteall\t{}\n",
t!("tls.deleteall_cmd", locales::LANG)
)
.ok();
write!(ret, "\thelp\n").ok(); write!(ret, "\thelp\n").ok();
write!(ret, "\tlist\t{}\n", t!("tls.list_cmd", locales::LANG)).ok(); write!(ret, "\tlist\t{}\n", t!("tls.list_cmd", locales::LANG)).ok();
#[cfg(feature = "rootCA")] #[cfg(feature = "rootCA")]
write!(ret, "\tmozilla\t{}\n", t!("tls.mozilla_cmd", locales::LANG)).ok(); write!(ret, "\tmozilla\t{}\n", t!("tls.mozilla_cmd", locales::LANG)).ok();
write!( write!(ret, "\tinspect <host>\t{}\n", t!("tls.inspect_cmd", locales::LANG)).ok();
ret, write!(ret, "\ttest <host>\t{}\n", t!("tls.test_cmd", locales::LANG)).ok();
"\tinspect <host>\t{}\n",
t!("tls.inspect_cmd", locales::LANG)
)
.ok();
write!(
ret,
"\ttest <host>\t{}\n",
t!("tls.test_cmd", locales::LANG)
)
.ok();
} }
} }
Ok(Some(ret)) Ok(Some(ret))

View file

@ -38,22 +38,15 @@ impl rustls::client::ServerCertVerifier for StifledCertificateVerification {
CertificateError::UnknownIssuer => Ok(ServerCertVerified::assertion()), CertificateError::UnknownIssuer => Ok(ServerCertVerified::assertion()),
CertificateError::NotValidYet => { CertificateError::NotValidYet => {
modals modals
.show_notification( .show_notification(t!("tls.probe_help_not_valid_yet", locales::LANG), None)
t!("tls.probe_help_not_valid_yet", locales::LANG),
None,
)
.expect("modal failed"); .expect("modal failed");
Err(Error::InvalidCertificate(e)) Err(Error::InvalidCertificate(e))
} }
_ => { _ => {
modals modals
.show_notification( .show_notification(
format!( format!("{}\n{:?}", t!("tls.probe_invalid_certificate", locales::LANG), e)
"{}\n{:?}", .as_str(),
t!("tls.probe_invalid_certificate", locales::LANG),
e
)
.as_str(),
None, None,
) )
.expect("modal failed"); .expect("modal failed");

View file

@ -3,7 +3,11 @@ mod danger;
pub mod rota; pub mod rota;
pub mod xtls; pub mod xtls;
use crate::rota::RustlsOwnedTrustAnchor; use std::convert::{Into, TryFrom, TryInto};
use std::io::{Error, ErrorKind, Read, Write};
use std::net::TcpStream;
use std::sync::Arc;
use locales::t; use locales::t;
use modals::Modals; use modals::Modals;
use rkyv::{ use rkyv::{
@ -13,13 +17,11 @@ use rkyv::{
}; };
use rustls::{Certificate, ClientConfig, ClientConnection, RootCertStore}; use rustls::{Certificate, ClientConfig, ClientConnection, RootCertStore};
use sha2::Digest; use sha2::Digest;
use std::convert::{Into, TryFrom, TryInto};
use std::io::{Error, ErrorKind, Read, Write};
use std::net::TcpStream;
use std::sync::Arc;
use x509_parser::prelude::{FromDer, X509Certificate}; use x509_parser::prelude::{FromDer, X509Certificate};
use xous_names::XousNames; use xous_names::XousNames;
use crate::rota::RustlsOwnedTrustAnchor;
/// PDDB Dict for tls trusted certificates keys /// PDDB Dict for tls trusted certificates keys
const TLS_TRUSTED_DICT: &str = "tls.trusted"; const TLS_TRUSTED_DICT: &str = "tls.trusted";
@ -28,11 +30,7 @@ pub struct Tls {
} }
impl Tls { impl Tls {
pub fn new() -> Tls { pub fn new() -> Tls { Tls { pddb: pddb::Pddb::new() } }
Tls {
pddb: pddb::Pddb::new(),
}
}
/// Presents a modal to the user to select trusted tls certificates /// Presents a modal to the user to select trusted tls certificates
/// and saves the selected certificates to the pddb /// and saves the selected certificates to the pddb
@ -44,7 +42,6 @@ impl Tls {
/// # Returns /// # Returns
/// ///
/// a count of trusted certificates /// a count of trusted certificates
///
pub fn trust_modal(&self, certificates: Vec<Certificate>) -> usize { pub fn trust_modal(&self, certificates: Vec<Certificate>) -> usize {
let xns = XousNames::new().unwrap(); let xns = XousNames::new().unwrap();
let modals = Modals::new(&xns).unwrap(); let modals = Modals::new(&xns).unwrap();
@ -54,10 +51,7 @@ impl Tls {
.map(|cert| { .map(|cert| {
let mut hasher = sha2::Sha256::new(); let mut hasher = sha2::Sha256::new();
hasher.update(&cert); hasher.update(&cert);
( (format!("{:X}", hasher.finalize()), X509Certificate::from_der(cert.as_ref()))
format!("{:X}", hasher.finalize()),
X509Certificate::from_der(cert.as_ref()),
)
}) })
.filter(|(_fingerprint, result)| result.is_ok()) .filter(|(_fingerprint, result)| result.is_ok())
.map(|(fingerprint, result)| (fingerprint, result.unwrap().1)) .map(|(fingerprint, result)| (fingerprint, result.unwrap().1))
@ -69,14 +63,10 @@ impl Tls {
.map(|(fingerprint, x509)| format!("🏛 {}\n{}", &x509.subject(), open_hex(fingerprint),)) .map(|(fingerprint, x509)| format!("🏛 {}\n{}", &x509.subject(), open_hex(fingerprint),))
.collect(); .collect();
let chain: Vec<&str> = chain.iter().map(AsRef::as_ref).collect(); let chain: Vec<&str> = chain.iter().map(AsRef::as_ref).collect();
modals modals.add_list(chain).expect("couldn't build checkbox list");
.add_list(chain)
.expect("couldn't build checkbox list");
match modals.get_checkbox(t!("tls.check_trust_prompt", locales::LANG)) { match modals.get_checkbox(t!("tls.check_trust_prompt", locales::LANG)) {
Ok(trusted) => { Ok(trusted) => {
trusted trusted.iter().for_each(|cert| log::info!("trusts {}", cert));
.iter()
.for_each(|cert| log::info!("trusts {}", cert));
modals modals
.get_check_index() .get_check_index()
.unwrap() .unwrap()
@ -108,7 +98,6 @@ impl Tls {
/// # Returns /// # Returns
/// ///
/// the number of trust-anchors deleted /// the number of trust-anchors deleted
///
pub fn del_all_rota(&self) -> Result<usize, Error> { pub fn del_all_rota(&self) -> Result<usize, Error> {
let count = match self.pddb.list_keys(TLS_TRUSTED_DICT, None) { let count = match self.pddb.list_keys(TLS_TRUSTED_DICT, None) {
Ok(list) => list.len(), Ok(list) => list.len(),
@ -117,10 +106,7 @@ impl Tls {
match self.pddb.delete_dict(TLS_TRUSTED_DICT, None) { match self.pddb.delete_dict(TLS_TRUSTED_DICT, None) {
Ok(_) => { Ok(_) => {
log::info!("Deleted {}\n", TLS_TRUSTED_DICT); log::info!("Deleted {}\n", TLS_TRUSTED_DICT);
self.pddb self.pddb.sync().or_else(|e| Ok::<(), Error>(log::warn!("{e}"))).ok();
.sync()
.or_else(|e| Ok::<(), Error>(log::warn!("{e}")))
.ok();
// match self.pddb.sync() { // match self.pddb.sync() {
// Err(e) => log::warn!("{e}"), // Err(e) => log::warn!("{e}"),
// _ => (), // _ => (),
@ -136,15 +122,11 @@ impl Tls {
/// # Arguments /// # Arguments
/// ///
/// * `key` - the pddb-key containing the unwanted trust-anchor /// * `key` - the pddb-key containing the unwanted trust-anchor
///
pub fn del_rota(&self, key: &str) -> Result<(), Error> { pub fn del_rota(&self, key: &str) -> Result<(), Error> {
match self.pddb.delete_key(TLS_TRUSTED_DICT, key, None) { match self.pddb.delete_key(TLS_TRUSTED_DICT, key, None) {
Ok(_) => { Ok(_) => {
log::info!("Deleted {}:{}\n", TLS_TRUSTED_DICT, key); log::info!("Deleted {}:{}\n", TLS_TRUSTED_DICT, key);
self.pddb self.pddb.sync().or_else(|e| Ok::<(), Error>(log::warn!("{e}"))).ok();
.sync()
.or_else(|e| Ok::<(), Error>(log::warn!("{e}")))
.ok();
} }
Err(e) => log::warn!("failed to delete {}:{}: {:?}", TLS_TRUSTED_DICT, key, e), Err(e) => log::warn!("failed to delete {}:{}: {:?}", TLS_TRUSTED_DICT, key, e),
} }
@ -156,7 +138,6 @@ impl Tls {
/// # Arguments /// # Arguments
/// ///
/// * `ta` - a trusted trust-anchor /// * `ta` - a trusted trust-anchor
///
pub fn save_rota(&self, ta: &RustlsOwnedTrustAnchor) -> Result<(), Error> { pub fn save_rota(&self, ta: &RustlsOwnedTrustAnchor) -> Result<(), Error> {
let key = ta.pddb_key(); let key = ta.pddb_key();
match self.pddb.get( match self.pddb.get(
@ -205,17 +186,8 @@ impl Tls {
/// # Arguments /// # Arguments
/// ///
/// * `key` - pddb key holding the trust-anchor /// * `key` - pddb key holding the trust-anchor
///
pub fn get_rota(&self, key: &str) -> Option<RustlsOwnedTrustAnchor> { pub fn get_rota(&self, key: &str) -> Option<RustlsOwnedTrustAnchor> {
match self.pddb.get( match self.pddb.get(TLS_TRUSTED_DICT, key, None, false, false, None, None::<fn()>) {
TLS_TRUSTED_DICT,
key,
None,
false,
false,
None,
None::<fn()>,
) {
Ok(mut pddb_key) => { Ok(mut pddb_key) => {
let mut bytes = [0u8; rota::MAX_ROTA_BYTES]; let mut bytes = [0u8; rota::MAX_ROTA_BYTES];
match pddb_key.read(&mut bytes) { match pddb_key.read(&mut bytes) {
@ -224,8 +196,7 @@ impl Tls {
let pos: u16 = u16::from_be_bytes([bytes[0], bytes[1]]); let pos: u16 = u16::from_be_bytes([bytes[0], bytes[1]]);
let pos: usize = pos.into(); let pos: usize = pos.into();
// deserialize the trust-anchor // deserialize the trust-anchor
let archive = let archive = unsafe { rkyv::archived_value::<RustlsOwnedTrustAnchor>(&bytes, pos) };
unsafe { rkyv::archived_value::<RustlsOwnedTrustAnchor>(&bytes, pos) };
let ta = archive.deserialize(&mut AllocDeserializer {}).ok(); let ta = archive.deserialize(&mut AllocDeserializer {}).ok();
log::info!("get trust anchor {}", key); log::info!("get trust anchor {}", key);
log::trace!("get trust anchor'{}' = '{:?}'", key, &ta); log::trace!("get trust anchor'{}' = '{:?}'", key, &ta);
@ -245,7 +216,6 @@ impl Tls {
} }
/// Returns a Vec of all trusted trust-anchors /// Returns a Vec of all trusted trust-anchors
///
pub fn trusted(&self) -> Vec<RustlsOwnedTrustAnchor> { pub fn trusted(&self) -> Vec<RustlsOwnedTrustAnchor> {
match self.pddb.list_keys(TLS_TRUSTED_DICT, None) { match self.pddb.list_keys(TLS_TRUSTED_DICT, None) {
Ok(list) => list Ok(list) => list
@ -269,7 +239,6 @@ impl Tls {
/// # Returns /// # Returns
/// ///
/// true if the certificate is saved in the TLS_TRUSTED_DICT in the pddb /// true if the certificate is saved in the TLS_TRUSTED_DICT in the pddb
///
pub fn is_trusted_cert(&self, cert: Certificate) -> bool { pub fn is_trusted_cert(&self, cert: Certificate) -> bool {
match X509Certificate::from_der(cert.as_ref()) { match X509Certificate::from_der(cert.as_ref()) {
Ok(result) => self.is_trusted_x509(&result.1), Ok(result) => self.is_trusted_x509(&result.1),
@ -289,19 +258,10 @@ impl Tls {
/// # Returns /// # Returns
/// ///
/// true if the certificate is saved in the TLS_TRUSTED_DICT in the pddb /// true if the certificate is saved in the TLS_TRUSTED_DICT in the pddb
///
pub fn is_trusted_x509(&self, x509: &X509Certificate) -> bool { pub fn is_trusted_x509(&self, x509: &X509Certificate) -> bool {
let ta = RustlsOwnedTrustAnchor::from(x509); let ta = RustlsOwnedTrustAnchor::from(x509);
let key = ta.pddb_key(); let key = ta.pddb_key();
match self.pddb.get( match self.pddb.get(TLS_TRUSTED_DICT, &key, None, false, false, None, None::<fn()>) {
TLS_TRUSTED_DICT,
&key,
None,
false,
false,
None,
None::<fn()>,
) {
Ok(_) => { Ok(_) => {
log::info!("trusted: {key}"); log::info!("trusted: {key}");
true true
@ -314,7 +274,6 @@ impl Tls {
} }
/// Returns a RootCertStore containing all trusted trust-anchors /// Returns a RootCertStore containing all trusted trust-anchors
///
pub fn root_store(&self) -> RootCertStore { pub fn root_store(&self) -> RootCertStore {
let mut root_store = RootCertStore::empty(); let mut root_store = RootCertStore::empty();
match self.pddb.list_keys(TLS_TRUSTED_DICT, None) { match self.pddb.list_keys(TLS_TRUSTED_DICT, None) {
@ -348,23 +307,20 @@ impl Tls {
/// # Returns /// # Returns
/// ///
/// The TLS chain of trust for the host /// The TLS chain of trust for the host
///
pub fn probe(&self, host: &str) -> Result<Vec<Certificate>, Error> { pub fn probe(&self, host: &str) -> Result<Vec<Certificate>, Error> {
log::info!("starting TLS probe"); log::info!("starting TLS probe");
// Attempt to open the tls connection with an empty root_store // Attempt to open the tls connection with an empty root_store
let root_store = rustls::RootCertStore::empty(); let root_store = rustls::RootCertStore::empty();
// Stifle the default rustls certificate verification's complaint about an // Stifle the default rustls certificate verification's complaint about an
// unknown/untrusted CA root certificate so that we get to see the certificate chain // unknown/untrusted CA root certificate so that we get to see the certificate chain
let stifled_verifier = let stifled_verifier = Arc::new(danger::StifledCertificateVerification { roots: root_store });
Arc::new(danger::StifledCertificateVerification { roots: root_store });
let config = rustls::ClientConfig::builder() let config = rustls::ClientConfig::builder()
.with_safe_defaults() .with_safe_defaults()
.with_custom_certificate_verifier(stifled_verifier) .with_custom_certificate_verifier(stifled_verifier)
.with_no_client_auth(); .with_no_client_auth();
match host.try_into() { match host.try_into() {
Ok(server_name) => { Ok(server_name) => {
let mut conn = let mut conn = rustls::ClientConnection::new(Arc::new(config), server_name).unwrap();
rustls::ClientConnection::new(Arc::new(config), server_name).unwrap();
log::info!("connect TCPstream to {}", host); log::info!("connect TCPstream to {}", host);
match TcpStream::connect((host, 443)) { match TcpStream::connect((host, 443)) {
Ok(mut sock) => { Ok(mut sock) => {
@ -403,7 +359,6 @@ impl Tls {
/// # Returns /// # Returns
/// ///
/// the number of trusted Certificates offered by the host /// the number of trusted Certificates offered by the host
///
pub fn inspect(&self, host: &str) -> Result<usize, Error> { pub fn inspect(&self, host: &str) -> Result<usize, Error> {
match self.probe(host) { match self.probe(host) {
Ok(certs) => Ok(self.trust_modal(certs)), Ok(certs) => Ok(self.trust_modal(certs)),
@ -428,18 +383,12 @@ impl Tls {
/// # Returns /// # Returns
/// ///
/// true if the user trusts at least one of the Certificates offered by the host. /// true if the user trusts at least one of the Certificates offered by the host.
///
pub fn accessible(&self, host: &str, inspect: bool) -> bool { pub fn accessible(&self, host: &str, inspect: bool) -> bool {
match self.probe(host) { match self.probe(host) {
Ok(certs) => { Ok(certs) => match certs.iter().find(|&cert| self.is_trusted_cert(cert.clone())) {
match certs Some(_) => true,
.iter() None => inspect && (self.trust_modal(certs) > 0),
.find(|&cert| self.is_trusted_cert(cert.clone())) },
{
Some(_) => true,
None => inspect && (self.trust_modal(certs) > 0),
}
}
Err(e) => { Err(e) => {
log::warn!("failed to probe {host}: {e}"); log::warn!("failed to probe {host}: {e}");
false false
@ -474,10 +423,7 @@ impl Tls {
host.try_into().expect("failed url host_str"), host.try_into().expect("failed url host_str"),
) { ) {
Ok(conn) => Ok(rustls::StreamOwned::new(conn, sock)), Ok(conn) => Ok(rustls::StreamOwned::new(conn, sock)),
Err(_) => Err(Error::new( Err(_) => Err(Error::new(ErrorKind::Other, "failed to configure client connection")),
ErrorKind::Other,
"failed to configure client connection",
)),
} }
} }
} }
@ -488,13 +434,7 @@ fn open_hex(text: &str) -> String {
text.chars() text.chars()
.enumerate() .enumerate()
.flat_map(|(i, c)| { .flat_map(|(i, c)| {
if i != 0 && i % 2 == 0 { if i != 0 && i % 2 == 0 { Some(' ') } else { None }.into_iter().chain(std::iter::once(c))
Some(' ')
} else {
None
}
.into_iter()
.chain(std::iter::once(c))
}) })
.collect::<String>() .collect::<String>()
} }

View file

@ -1,10 +1,11 @@
// A mirror of rustls::OwnedTrustAnchor // A mirror of rustls::OwnedTrustAnchor
use der::{Encode, Header, Reader, Tag};
use rkyv::{Archive, Deserialize, Serialize};
use std::cmp::min; use std::cmp::min;
use std::convert::TryInto; use std::convert::TryInto;
use std::io::{Error, ErrorKind}; use std::io::{Error, ErrorKind};
use der::{Encode, Header, Reader, Tag};
use rkyv::{Archive, Deserialize, Serialize};
use x509_parser::prelude::{FromDer, X509Certificate}; use x509_parser::prelude::{FromDer, X509Certificate};
pub const MAX_ROTA_BYTES: usize = 1028; pub const MAX_ROTA_BYTES: usize = 1028;
@ -143,16 +144,10 @@ fn add_der_header(tag: Tag, naked: &Vec<u8>) -> Result<Vec<u8>, Error> {
let mut buff: [u8; 32] = [0u8; 32]; let mut buff: [u8; 32] = [0u8; 32];
match header.encode_to_slice(&mut buff) { match header.encode_to_slice(&mut buff) {
Ok(der) => Ok([der, naked].concat()), Ok(der) => Ok([der, naked].concat()),
Err(_) => Err(Error::new( Err(_) => Err(Error::new(ErrorKind::InvalidData, "der parse failed: encode")),
ErrorKind::InvalidData,
"der parse failed: encode",
)),
} }
} }
Err(_) => Err(Error::new( Err(_) => Err(Error::new(ErrorKind::InvalidData, "der parse failed: header")),
ErrorKind::InvalidData,
"der parse failed: header",
)),
} }
} }
@ -163,25 +158,13 @@ fn rm_der_header(der: &[u8]) -> Result<Vec<u8>, Error> {
Ok(header) => match header.encoded_len() { Ok(header) => match header.encoded_len() {
Ok(len) => match TryInto::<usize>::try_into(len) { Ok(len) => match TryInto::<usize>::try_into(len) {
Ok(len) => Ok(der[len..].to_vec()), Ok(len) => Ok(der[len..].to_vec()),
Err(_) => Err(Error::new( Err(_) => Err(Error::new(ErrorKind::InvalidData, "der decode failed: into")),
ErrorKind::InvalidData,
"der decode failed: into",
)),
}, },
Err(_) => Err(Error::new( Err(_) => Err(Error::new(ErrorKind::InvalidData, "der decode failed: length")),
ErrorKind::InvalidData,
"der decode failed: length",
)),
}, },
Err(_) => Err(Error::new( Err(_) => Err(Error::new(ErrorKind::InvalidData, "der decode failed: header")),
ErrorKind::InvalidData,
"der decode failed: header",
)),
}, },
Err(_) => Err(Error::new( Err(_) => Err(Error::new(ErrorKind::InvalidData, "der decode failed: reader")),
ErrorKind::InvalidData,
"der decode failed: reader",
)),
} }
} }

View file

@ -1,8 +1,10 @@
use crate::Tls;
use rustls::{ClientConnection, StreamOwned};
use std::{convert::TryInto, fmt::Debug, io, net::TcpStream, result::Result, sync::Arc}; use std::{convert::TryInto, fmt::Debug, io, net::TcpStream, result::Result, sync::Arc};
use rustls::{ClientConnection, StreamOwned};
use ureq::{ReadWrite, Response}; use ureq::{ReadWrite, Response};
use crate::Tls;
pub struct TlsConnector {} pub struct TlsConnector {}
/// Set up tls with rustls::ClientConnection, /// Set up tls with rustls::ClientConnection,
@ -10,11 +12,7 @@ pub struct TlsConnector {}
/// probe the host for the untrusted certificate chain and prompt the user /// probe the host for the untrusted certificate chain and prompt the user
/// to perhaps trust one of the certificates in the chain - then try again. /// to perhaps trust one of the certificates in the chain - then try again.
impl ureq::TlsConnector for TlsConnector { impl ureq::TlsConnector for TlsConnector {
fn connect( fn connect(&self, dns_name: &str, mut io: Box<dyn ReadWrite>) -> Result<Box<dyn ReadWrite>, ureq::Error> {
&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 { loop {
// refresh rustls client config with current root_store // refresh rustls client config with current root_store
@ -70,10 +68,7 @@ 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( Err(ureq::Error::Status(526, Response::new(526, "tls", "untrusted certificate chain").unwrap()))
526,
Response::new(526, "tls", "untrusted certificate chain").unwrap(),
))
} }
} }
@ -83,35 +78,23 @@ pub struct TlsStream(StreamOwned<ClientConnection, Box<dyn ReadWrite>>);
impl TlsStream { impl TlsStream {
/// Returns a shared reference to the inner stream. /// Returns a shared reference to the inner stream.
pub fn get_ref(&self) -> &Box<dyn ReadWrite> { pub fn get_ref(&self) -> &Box<dyn ReadWrite> { self.0.get_ref() }
self.0.get_ref()
}
/// Returns a mutable reference to the inner stream. /// Returns a mutable reference to the inner stream.
pub fn get_mut(&mut self) -> &mut Box<dyn ReadWrite> { pub fn get_mut(&mut self) -> &mut Box<dyn ReadWrite> { self.0.get_mut() }
self.0.get_mut()
}
} }
impl io::Read for TlsStream { impl io::Read for TlsStream {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> { fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> { Ok(self.0.read(buf)?) }
Ok(self.0.read(buf)?)
}
} }
impl io::Write for TlsStream { impl io::Write for TlsStream {
fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> { fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> { Ok(self.0.write(buf)?) }
Ok(self.0.write(buf)?)
}
fn flush(&mut self) -> Result<(), std::io::Error> { fn flush(&mut self) -> Result<(), std::io::Error> { Ok(self.0.flush()?) }
Ok(self.0.flush()?)
}
} }
// required for the return type in TlsConnect::connect() // required for the return type in TlsConnect::connect()
impl ReadWrite for TlsStream { impl ReadWrite for TlsStream {
fn socket(&self) -> Option<&TcpStream> { fn socket(&self) -> Option<&TcpStream> { self.get_ref().socket() }
self.get_ref().socket()
}
} }