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

View file

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

View file

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

View file

@ -1,10 +1,11 @@
// A mirror of rustls::OwnedTrustAnchor
use der::{Encode, Header, Reader, Tag};
use rkyv::{Archive, Deserialize, Serialize};
use std::cmp::min;
use std::convert::TryInto;
use std::io::{Error, ErrorKind};
use der::{Encode, Header, Reader, Tag};
use rkyv::{Archive, Deserialize, Serialize};
use x509_parser::prelude::{FromDer, X509Certificate};
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];
match header.encode_to_slice(&mut buff) {
Ok(der) => Ok([der, naked].concat()),
Err(_) => Err(Error::new(
ErrorKind::InvalidData,
"der parse failed: encode",
)),
Err(_) => Err(Error::new(ErrorKind::InvalidData, "der parse failed: encode")),
}
}
Err(_) => Err(Error::new(
ErrorKind::InvalidData,
"der parse failed: header",
)),
Err(_) => Err(Error::new(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(len) => match TryInto::<usize>::try_into(len) {
Ok(len) => Ok(der[len..].to_vec()),
Err(_) => Err(Error::new(
ErrorKind::InvalidData,
"der decode failed: into",
)),
Err(_) => Err(Error::new(ErrorKind::InvalidData, "der decode failed: into")),
},
Err(_) => Err(Error::new(
ErrorKind::InvalidData,
"der decode failed: length",
)),
Err(_) => Err(Error::new(ErrorKind::InvalidData, "der decode failed: length")),
},
Err(_) => Err(Error::new(
ErrorKind::InvalidData,
"der decode failed: header",
)),
Err(_) => Err(Error::new(ErrorKind::InvalidData, "der decode failed: header")),
},
Err(_) => Err(Error::new(
ErrorKind::InvalidData,
"der decode failed: reader",
)),
Err(_) => Err(Error::new(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 rustls::{ClientConnection, StreamOwned};
use ureq::{ReadWrite, Response};
use crate::Tls;
pub struct TlsConnector {}
/// 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
/// to perhaps trust one of the certificates in the chain - then try again.
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");
loop {
// refresh rustls client config with current root_store
@ -70,10 +68,7 @@ impl ureq::TlsConnector for TlsConnector {
}
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(ureq::Error::Status(526, Response::new(526, "tls", "untrusted certificate chain").unwrap()))
}
}
@ -83,35 +78,23 @@ pub struct TlsStream(StreamOwned<ClientConnection, Box<dyn ReadWrite>>);
impl TlsStream {
/// Returns a shared reference to the inner stream.
pub fn get_ref(&self) -> &Box<dyn ReadWrite> {
self.0.get_ref()
}
pub fn get_ref(&self) -> &Box<dyn ReadWrite> { self.0.get_ref() }
/// Returns a mutable reference to the inner stream.
pub fn get_mut(&mut self) -> &mut Box<dyn ReadWrite> {
self.0.get_mut()
}
pub fn get_mut(&mut self) -> &mut Box<dyn ReadWrite> { self.0.get_mut() }
}
impl io::Read for TlsStream {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
Ok(self.0.read(buf)?)
}
fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> { Ok(self.0.read(buf)?) }
}
impl io::Write for TlsStream {
fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> {
Ok(self.0.write(buf)?)
}
fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> { Ok(self.0.write(buf)?) }
fn flush(&mut self) -> Result<(), std::io::Error> {
Ok(self.0.flush()?)
}
fn flush(&mut self) -> Result<(), std::io::Error> { Ok(self.0.flush()?) }
}
// required for the return type in TlsConnect::connect()
impl ReadWrite for TlsStream {
fn socket(&self) -> Option<&TcpStream> {
self.get_ref().socket()
}
fn socket(&self) -> Option<&TcpStream> { self.get_ref().socket() }
}