tls tidy-up

This commit is contained in:
nworbnhoj 2024-02-29 06:22:38 +10:00
parent 6d24f1af41
commit b217c1546e
3 changed files with 93 additions and 39 deletions

View file

@ -9,6 +9,9 @@ use std::sync::Arc;
use webpki::ring as webpki_algs;
use xous_names::XousNames;
/// The entire purpose of the StifledCertificateVerification is to gain access to
/// the certificate-chain-of-trust offered by a host by stifling CertificateError::UnknownIssuer
///
#[derive(Debug)]
pub struct StifledCertificateVerification {
pub roots: RootCertStore,
@ -16,9 +19,19 @@ pub struct StifledCertificateVerification {
}
impl StifledCertificateVerification {
/// rustls includes a sanity check early in the process, to ensure that the RootCertStore
/// contains at least one root certificate before going to the trouble of asking the host
/// to offer its certificate chain of trust. Trouble is, xous/tls wants to probe the host
/// to see what is offered up before deciding if we trust it.
///
/// The somewhat hacky work-around is to add a single bogus TrustAnchor to RootCertStore,
/// and neither the bogus TrustAnchor or the RootCertStore exist beyond the lifetime of
/// this StifledCertificateVerification.
///
pub fn new() -> Self {
let mut root_cert_store = rustls::RootCertStore::empty();
// rustls::ServerCertVerifierBuilder::build() returns a
// rustls::ServerCertVerifierBuilder::build() returns a
// `CertVerifierBuilderError` if no trust anchors have been provided.
let single_bogus_ta_to_avoid_error_on_empty_roots = TrustAnchor {
subject: Der::from_slice(b"bogus subject"),
@ -59,7 +72,10 @@ impl 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))
}
@ -82,7 +98,7 @@ impl ServerCertVerifier for StifledCertificateVerification {
}
Err(e) => Err(e),
}
},
}
Err(e) => {
log::warn!("failed to build WebPkiServerVerifier: {e}");
Err(Error::General("failed to build WebPkiServerVerifier".to_string()))
@ -116,6 +132,7 @@ impl ServerCertVerifier for StifledCertificateVerification {
/// Vendor in the sadly private rustls::crypto::ring::SUPPORTED_SIG_ALGS
/// A `WebPkiSupportedAlgorithms` value that reflects webpki's capabilities when
/// compiled against *ring*.
///
static SUPPORTED_SIG_ALGS: WebPkiSupportedAlgorithms = WebPkiSupportedAlgorithms {
all: &[
webpki_algs::ECDSA_P256_SHA256,

View file

@ -3,11 +3,6 @@ mod danger;
pub mod ota;
pub mod xtls;
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 ota::OwnedTrustAnchor;
@ -18,6 +13,10 @@ use rkyv::{
};
use rustls::pki_types::{CertificateDer, TrustAnchor};
use rustls::{ClientConfig, ClientConnection, RootCertStore};
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::{parse_x509_certificate, FromDer, X509Certificate};
use xous_names::XousNames;
@ -43,10 +42,10 @@ impl Tls {
/// # Returns
///
/// a count of trusted certificates
///
pub fn trust_modal(&self, certificates: Vec<CertificateDer>) -> usize {
let xns = XousNames::new().unwrap();
let modals = Modals::new(&xns).unwrap();
let certificates: Vec<(&[u8], X509Certificate)> = certificates
.iter()
.map(|cert| X509Certificate::from_der(cert))
@ -54,7 +53,6 @@ impl Tls {
.map(|result| result.unwrap())
.filter(|(_fingerprint, x509)| x509.is_ca())
.collect();
let chain: Vec<String> = certificates
.iter()
.map(|(fingerprint, x509)| {
@ -96,6 +94,7 @@ 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(),
@ -105,10 +104,6 @@ impl Tls {
Ok(_) => {
log::info!("Deleted {}\n", TLS_TRUSTED_DICT);
self.pddb.sync().or_else(|e| Ok::<(), Error>(log::warn!("{e}"))).ok();
// match self.pddb.sync() {
// Err(e) => log::warn!("{e}"),
// _ => (),
// }
}
Err(e) => log::warn!("failed to delete {}: {:?}", TLS_TRUSTED_DICT, e),
}
@ -120,6 +115,7 @@ 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(_) => {
@ -136,24 +132,29 @@ impl Tls {
/// # Arguments
///
/// * `ta` - a trusted trust-anchor
///
pub fn save_ta(&self, ta: &OwnedTrustAnchor) -> Result<(), Error> {
match ta.pddb_key() {
Ok(key) => {
// log::warn!("AAA {:?}", ta);
match self.pddb.get(TLS_TRUSTED_DICT, &key, None, true, true, Some(ota::MAX_OTA_BYTES), None::<fn()>)
{
match self.pddb.get(
TLS_TRUSTED_DICT,
&key,
None,
true,
true,
Some(ota::MAX_OTA_BYTES),
None::<fn()>,
) {
Ok(mut pddb_key) => {
let mut buf = Vec::<u8>::new();
// reserve 2 bytes to hold a u16 (see below)
let reserved = 2;
buf.push(0u8);
buf.push(0u8);
// serialize the trust-anchor
let mut serializer = WriteSerializer::with_pos(buf, reserved);
let pos = serializer.serialize_value(ta).unwrap();
let mut bytes = serializer.into_inner();
// copy pop u16 into the first 2 bytes to enable the rkyv archive to be deserialised
let pos: u16 = u16::try_from(pos).expect("data > u16");
let pos_bytes = pos.to_be_bytes();
@ -182,6 +183,7 @@ impl Tls {
/// # Arguments
///
/// * `key` - pddb key holding the trust-anchor
///
pub fn get_ota(&self, key: &str) -> Option<OwnedTrustAnchor> {
match self.pddb.get(TLS_TRUSTED_DICT, key, None, false, false, None, None::<fn()>) {
Ok(mut pddb_key) => {
@ -211,7 +213,12 @@ impl Tls {
}
}
/// Returns a Vec of all trusted trust-anchors
/// Returns a Vec of all trusted (saved) OwnedTrustAnchors
///
/// # Returns
///
/// a Vec of OwnedTrustAnchor.
///
pub fn trusted(&self) -> Vec<OwnedTrustAnchor> {
match self.pddb.list_keys(TLS_TRUSTED_DICT, None) {
Ok(list) => list
@ -235,6 +242,7 @@ impl Tls {
/// # Returns
///
/// true if the certificate is saved in the TLS_TRUSTED_DICT in the pddb
///
pub fn is_trusted_cert(&self, cert: CertificateDer) -> bool {
match parse_x509_certificate(cert.as_ref()) {
Ok(result) => self.is_trusted_x509(&result.1),
@ -255,28 +263,38 @@ impl Tls {
///
/// 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 = OwnedTrustAnchor::from(x509);
match ta.pddb_key() {
Ok(key) => {
match self.pddb.get(TLS_TRUSTED_DICT, &key, None, false, false, None, None::<fn()>) {
Ok(_) => {
log::info!("trusted: {key}");
true
}
Err(_) => {
log::info!("UNtrusted: {key}");
false
match OwnedTrustAnchor::from_x509(x509) {
Ok(ta) => match ta.pddb_key() {
Ok(key) => {
match self.pddb.get(TLS_TRUSTED_DICT, &key, None, false, false, None, None::<fn()>) {
Ok(_) => {
log::info!("trusted: {key}");
true
}
Err(_) => {
log::info!("UNtrusted: {key}");
false
}
}
}
}
Err(e) => {
log::warn!("failed to get pddb_key: {e}");
false
}
},
Err(e) => {
log::warn!("failed to get pddb_key: {e}");
log::warn!("failed construct OwnedTrustAnchor from x509: {e}");
false
}
}
}
/// Returns a RootCertStore containing all trusted trust-anchors
/// Returns a RootCertStore containing all trusted (saved) TrustAnchors
///
/// # Returns
///
/// a RootCertStore suitable for rustls
///
pub fn root_store(&self) -> RootCertStore {
let mut root_store = RootCertStore::empty();
let trusted = match self.pddb.list_keys(TLS_TRUSTED_DICT, None) {
@ -295,7 +313,7 @@ impl Tls {
root_store
}
/// Probes the host and returns the TLS chain of trust
/// Probes the host and returns the TLS chain of trust for a host
///
/// Establishes a tls connection to the host, extracts the
/// certificates offered and immediately closes the connection.
@ -369,6 +387,7 @@ 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) => {
@ -427,6 +446,7 @@ impl Tls {
/// # Returns
///
/// an owned rusttls stream on the tcp-stream provided
///
pub fn stream_owned(
&self,
host: &str,

View file

@ -7,9 +7,12 @@ use std::convert::TryInto;
use std::fmt;
use std::io::{Error, ErrorKind};
use x509_parser::prelude::{FromDer, X509Certificate};
use x509_parser::x509::X509Name;
pub const MAX_OTA_BYTES: usize = 1028;
/// Note that the subject, spki & name_constraints fields are all DER encoded,
/// but WITHOUT the DER header, in keeping with webpki-roots.
#[derive(Archive, Serialize, Deserialize)]
pub struct OwnedTrustAnchor {
pub subject: Vec<u8>,
@ -30,6 +33,18 @@ impl OwnedTrustAnchor {
}
}
/// Creates a OwnedTrustAnchor from an x509 Certificate
///
/// The Der headers are removed from each of the fields during the conversion.
///
/// # Arguments
///
/// * `x509` - a X509Certificate to create the OwnedTrustAnchor
///
/// # Returns
///
/// An OwnedTrustAnchor based on the supplied X509Certificate
///
pub fn from_x509(x509: &X509Certificate) -> Result<Self, Error> {
match (
rm_der_header(x509.subject().as_raw()),
@ -38,6 +53,7 @@ impl OwnedTrustAnchor {
) {
(Ok(subject), Ok(spki), Ok(name_constraints)) => match name_constraints {
// Ignore name_constrains for now TODO
// The problem is that it is hard to get access to the raw &[u8] form of name_constraints
Some(_) => Ok(Self::from_subject_spki_name_constraints(subject, spki, None::<&[u8]>)),
None => Ok(Self::from_subject_spki_name_constraints(subject, spki, None::<&[u8]>)),
},
@ -63,7 +79,6 @@ impl OwnedTrustAnchor {
Some(begin) => Some(begin),
None => subject.find("OU="),
};
let mut pddb_key = match begin {
Some(mut begin) => {
begin += 3;
@ -79,11 +94,9 @@ impl OwnedTrustAnchor {
}
}
.to_string();
// grab a few arbitrary bytes from spki so pddb_key is deterministic & unique
let k = &self.spki;
pddb_key.push_str(&format!(" {:X}{:X}{:X}{:X}", k[6], k[7], k[8], k[9]));
// mirror of pddb::KEY_NAME_LEN
// u64: vaddr/len/resvd, u32: flags, age = 95
// would this be better as a pddb pub?
@ -100,7 +113,7 @@ impl OwnedTrustAnchor {
// decoded subject
pub fn subject(&self) -> Result<String, Error> {
match add_der_header(Tag::Sequence, &self.subject) {
Ok(subject) => match x509_parser::x509::X509Name::from_der(&subject) {
Ok(subject) => match X509Name::from_der(&subject) {
Ok((_, decoded)) => Ok(decoded.to_string()),
Err(e) => {
log::warn!("failed to decode Subject: {:?}", e);
@ -113,6 +126,8 @@ impl OwnedTrustAnchor {
}
}
}
}
impl fmt::Debug for OwnedTrustAnchor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}\nDer{:?}", self.subject().unwrap_or("Subject error".to_string()), self.spki)
@ -142,6 +157,8 @@ impl<'a> Into<TrustAnchor<'a>> for OwnedTrustAnchor {
subject_public_key_info: Der::from(self.spki),
name_constraints: self.name_constraints.map_or(None, |nc| Some(Der::from(nc))),
}
}
}
/// Add a DER header to a DER encoded [u8]
fn add_der_header(tag: Tag, naked: &Vec<u8>) -> Result<Vec<u8>, Error> {