implement tls::rota::pddb_key

This commit is contained in:
nworbnhoj 2023-07-03 16:49:59 +10:00
parent a4de987eb8
commit ffb573f5dc
3 changed files with 90 additions and 72 deletions

View file

@ -28,26 +28,21 @@ pub fn shellchat<'a>(
// save/trust all Root CA's in webpki-roots en-masse // save/trust all Root CA's in webpki-roots en-masse
#[cfg(feature = "rootCA")] #[cfg(feature = "rootCA")]
Some("mozilla") => { Some("mozilla") => {
let rotas: Vec<(String, crate::RustlsOwnedTrustAnchor)> = let rotas: Vec<crate::RustlsOwnedTrustAnchor> = webpki_roots::TLS_SERVER_ROOTS
webpki_roots::TLS_SERVER_ROOTS .0
.0 .iter()
.iter() .map(|ta| {
.map(|ta| { crate::RustlsOwnedTrustAnchor::from_subject_spki_name_constraints(
let rota = ta.subject,
crate::RustlsOwnedTrustAnchor::from_subject_spki_name_constraints( ta.spki,
ta.subject, ta.name_constraints,
ta.spki, )
ta.name_constraints, })
); .collect();
let key = rota.subject();
(key, rota)
})
.collect();
let mut count = 0; let mut count = 0;
let tls = Tls::new(); let tls = Tls::new();
for (key, rota) in rotas { for rota in rotas {
tls.save_cert(&key, &rota) tls.save_cert(&rota).unwrap_or_else(|e| log::warn!("{e}"));
.unwrap_or_else(|e| log::warn!("{e}"));
count += 1; count += 1;
} }
write!(ret, "trusted {count} certificates").ok(); write!(ret, "trusted {count} certificates").ok();

View file

@ -13,8 +13,8 @@ use rkyv::{
use rustls::{Certificate, RootCertStore}; use rustls::{Certificate, RootCertStore};
use sha2::Digest; use sha2::Digest;
use std::convert::{Into, TryFrom}; use std::convert::{Into, TryFrom};
use std::io::{Error, ErrorKind, Read, Write}; use std::io::{Error, Read, Write};
use x509_parser::prelude::{oid_registry, FromDer, X509Certificate}; use x509_parser::prelude::{FromDer, X509Certificate};
use xous_names::XousNames; use xous_names::XousNames;
/// PDDB Dict for tls trusted certificates keys /// PDDB Dict for tls trusted certificates keys
@ -72,19 +72,13 @@ impl Tls {
.unwrap() .unwrap()
.iter() .iter()
.map(|i| &certificates[*i].1) .map(|i| &certificates[*i].1)
.map(|x509| { .map(|x509| RustlsOwnedTrustAnchor::from(x509))
let subject = &x509 .for_each(|rota| {
.subject() self.save_cert(&rota).unwrap_or_else(|e| {
.to_string_with_registry(oid_registry())
.unwrap();
(subject.to_owned(), RustlsOwnedTrustAnchor::from(x509))
})
.for_each(|(key, val)| {
self.save_cert(&key, &val).unwrap_or_else(|e| {
log::warn!("failed to save cert: {e}"); log::warn!("failed to save cert: {e}");
modals modals
.show_notification( .show_notification(
format!("failed to save:\n{}\n{e}", &val.subject()).as_str(), format!("failed to save:\n{}\n{e}", &rota.subject()).as_str(),
None, None,
) )
.expect("modal failed"); .expect("modal failed");
@ -139,53 +133,49 @@ impl Tls {
} }
// saves a tls trust-anchor to the pddb // saves a tls trust-anchor to the pddb
pub fn save_cert(&self, key: &str, ta: &RustlsOwnedTrustAnchor) -> Result<(), Error> { pub fn save_cert(&self, ta: &RustlsOwnedTrustAnchor) -> Result<(), Error> {
if key.starts_with("__") { // let xns = XousNames::new().unwrap();
Err(Error::new( // let modals = Modals::new(&xns).unwrap();
ErrorKind::PermissionDenied, let key = ta.pddb_key();
"may not set a variable beginning with __ ", match self.pddb.get(
)) TLS_TRUSTED_DICT,
} else { &key,
match self.pddb.get( None,
TLS_TRUSTED_DICT, true,
key, true,
None, Some(rota::MAX_ROTA_BYTES),
true, None::<fn()>,
true, ) {
Some(rota::MAX_ROTA_BYTES), Ok(mut pddb_key) => {
None::<fn()>, let mut buf = Vec::<u8>::new();
) { // reserve 2 bytes to hold a u16 (see below)
Ok(mut pddb_key) => { buf.push(0u8);
let mut buf = Vec::<u8>::new(); buf.push(0u8);
// reserve 2 bytes to hold a u16 (see below)
buf.push(0u8);
buf.push(0u8);
// serialize the trust-anchor // serialize the trust-anchor
let mut serializer = WriteSerializer::new(buf); let mut serializer = WriteSerializer::new(buf);
let pos = serializer.serialize_value(ta).unwrap(); let pos = serializer.serialize_value(ta).unwrap();
let mut bytes = serializer.into_inner(); let mut bytes = serializer.into_inner();
// copy pop u16 into the first 2 bytes to enable the rkyv archive to be deserialised // 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: u16 = u16::try_from(pos).expect("data > u16");
let pos_bytes = pos.to_be_bytes(); let pos_bytes = pos.to_be_bytes();
bytes[0] = pos_bytes[0]; bytes[0] = pos_bytes[0];
bytes[1] = pos_bytes[1]; bytes[1] = pos_bytes[1];
match pddb_key.write(&bytes) { match pddb_key.write(&bytes) {
Ok(len) => { Ok(len) => {
self.pddb.sync().ok(); self.pddb.sync().ok();
log::info!("Wrote {} bytes to {}:{}", len, TLS_TRUSTED_DICT, key); log::info!("Wrote {} bytes to {}:{}", len, TLS_TRUSTED_DICT, key);
} }
Err(e) => { Err(e) => {
log::warn!("Error writing {}:{}: {:?}", TLS_TRUSTED_DICT, key, e); log::warn!("Error writing {}:{}: {:?}", TLS_TRUSTED_DICT, key, e);
}
} }
} }
_ => log::warn!("failed to create {}:{}", TLS_TRUSTED_DICT, key),
} }
Ok(()) Err(e) => log::warn!("failed to create {}:{}\n{}", TLS_TRUSTED_DICT, key, e),
} }
Ok(())
} }

View file

@ -2,8 +2,7 @@
use der::{Encode, Header, Reader, Tag}; use der::{Encode, Header, Reader, Tag};
use rkyv::{Archive, Deserialize, Serialize}; use rkyv::{Archive, Deserialize, Serialize};
use sha2::Digest; use std::cmp::min;
use std::convert::TryInto; use std::convert::TryInto;
use std::fmt; use std::fmt;
use std::io::{Error, ErrorKind}; use std::io::{Error, ErrorKind};
@ -50,6 +49,40 @@ impl RustlsOwnedTrustAnchor {
} }
} }
} }
pub fn pddb_key(&self) -> String {
let subject = &self.subject();
let begin = match subject.find("CN=") {
Some(begin) => Some(begin),
None => subject.find("OU="),
};
let mut pddb_key = match begin {
Some(mut begin) => {
begin += 3;
let end = match subject[begin..].find(",") {
Some(e) => begin + e,
None => subject.len(),
};
&subject[begin..end]
}
None => {
log::warn!("Subject missing CN= & OU= :{}", &subject);
&subject
}
}
.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?
const KEY_NAME_LEN: usize = 127 - 8 - 8 - 8 - 4 - 4;
pddb_key[..min(pddb_key.len(), KEY_NAME_LEN - 1)].to_string()
}
} }
impl<'a> From<&X509Certificate<'a>> for RustlsOwnedTrustAnchor { impl<'a> From<&X509Certificate<'a>> for RustlsOwnedTrustAnchor {