refine tls:rota.subject() -> Result<String, Error>

This commit is contained in:
nworbnhoj 2024-02-28 05:24:57 +10:00
parent 8ed22b8257
commit faece9783e
2 changed files with 90 additions and 66 deletions

View file

@ -136,37 +136,42 @@ impl Tls {
/// ///
/// * `ta` - a trusted trust-anchor /// * `ta` - a trusted trust-anchor
pub fn save_ta(&self, ta: &OwnedTrustAnchor) -> Result<(), Error> { pub fn save_ta(&self, ta: &OwnedTrustAnchor) -> Result<(), Error> {
let key = ta.pddb_key(); match ta.pddb_key() {
match self.pddb.get(TLS_TRUSTED_DICT, &key, None, true, true, Some(ota::MAX_OTA_BYTES), None::<fn()>) Ok(key) => {
{ // log::warn!("AAA {:?}", ta);
Ok(mut pddb_key) => { match self.pddb.get(TLS_TRUSTED_DICT, &key, None, true, true, Some(ota::MAX_OTA_BYTES), None::<fn()>)
let mut buf = Vec::<u8>::new(); {
// reserve 2 bytes to hold a u16 (see below) Ok(mut pddb_key) => {
let reserved = 2; let mut buf = Vec::<u8>::new();
buf.push(0u8); // reserve 2 bytes to hold a u16 (see below)
buf.push(0u8); let reserved = 2;
buf.push(0u8);
buf.push(0u8);
// serialize the trust-anchor // serialize the trust-anchor
let mut serializer = WriteSerializer::with_pos(buf, reserved); let mut serializer = WriteSerializer::with_pos(buf, reserved);
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);
}
}
} }
Err(e) => log::warn!("failed to create {}:{}\n{}", TLS_TRUSTED_DICT, key, e),
} }
} }
Err(e) => log::warn!("failed to create {}:{}\n{}", TLS_TRUSTED_DICT, key, e), Err(e) => log::warn!("failed to get pddb_key {e}"),
} }
Ok(()) Ok(())
} }
@ -250,14 +255,21 @@ impl Tls {
/// 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 = OwnedTrustAnchor::from(x509); let ta = OwnedTrustAnchor::from(x509);
let key = ta.pddb_key(); match ta.pddb_key() {
match self.pddb.get(TLS_TRUSTED_DICT, &key, None, false, false, None, None::<fn()>) { Ok(key) => {
Ok(_) => { match self.pddb.get(TLS_TRUSTED_DICT, &key, None, false, false, None, None::<fn()>) {
log::info!("trusted: {key}"); Ok(_) => {
true log::info!("trusted: {key}");
true
}
Err(_) => {
log::info!("UNtrusted: {key}");
false
}
}
} }
Err(_) => { Err(e) => {
log::info!("UNtrusted: {key}"); log::warn!("failed to get pddb_key: {e}");
false false
} }
} }

View file

@ -3,6 +3,7 @@ use rkyv::{Archive, Deserialize, Serialize};
use rustls::pki_types::{Der, TrustAnchor}; use rustls::pki_types::{Der, TrustAnchor};
use std::cmp::min; use std::cmp::min;
use std::fmt; use std::fmt;
use std::io::{Error, ErrorKind};
use x509_parser::prelude::{FromDer, X509Certificate}; use x509_parser::prelude::{FromDer, X509Certificate};
pub const MAX_OTA_BYTES: usize = 1028; pub const MAX_OTA_BYTES: usize = 1028;
@ -27,55 +28,66 @@ impl OwnedTrustAnchor {
} }
} }
pub fn pddb_key(&self) -> String { pub fn pddb_key(&self) -> Result<String, Error> {
let subject = self.subject(); match self.subject() {
let begin = match subject.find("CN=") { Ok(subject) => {
Some(begin) => Some(begin), let begin = match subject.find("CN=") {
None => subject.find("OU="), 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]
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;
Ok(pddb_key[..min(pddb_key.len(), KEY_NAME_LEN - 1)].to_string())
} }
None => { Err(e) => {
log::warn!("Subject missing CN= & OU= :{}", &subject); log::warn!("failed to construct pddb_key: {e}");
&subject Err(Error::from(ErrorKind::InvalidData))
} }
} }
.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()
} }
// decoded subject // decoded subject
pub fn subject(&self) -> String { pub fn subject(&self) -> Result<String, Error> {
match x509_parser::x509::X509Name::from_der(&self.subject) { match x509_parser::x509::X509Name::from_der(&self.subject) {
Ok((_, decoded)) => decoded.to_string(), Ok((_, decoded)) => Ok(decoded.to_string()),
Err(e) => { Err(e) => {
log::warn!("{:?}", e); log::warn!("failed to decode Subject: {:?}", e);
"der decode failed".to_string() Err(Error::from(ErrorKind::InvalidData))
} }
} }
} }
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)
}
} }
impl fmt::Display for OwnedTrustAnchor { impl fmt::Display for OwnedTrustAnchor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.subject()) write!(f, "{}", self.subject().unwrap_or("Subject error".to_string()))
} }
} }