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
pub fn save_ta(&self, ta: &OwnedTrustAnchor) -> Result<(), Error> {
let key = ta.pddb_key();
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);
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()>)
{
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();
// 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();
bytes[0] = pos_bytes[0];
bytes[1] = pos_bytes[1];
match pddb_key.write(&bytes) {
Ok(len) => {
self.pddb.sync().ok();
log::info!("Wrote {} bytes to {}:{}", len, TLS_TRUSTED_DICT, key);
}
Err(e) => {
log::warn!("Error writing {}:{}: {:?}", TLS_TRUSTED_DICT, key, e);
// 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();
bytes[0] = pos_bytes[0];
bytes[1] = pos_bytes[1];
match pddb_key.write(&bytes) {
Ok(len) => {
self.pddb.sync().ok();
log::info!("Wrote {} bytes to {}:{}", len, TLS_TRUSTED_DICT, key);
}
Err(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(())
}
@ -250,14 +255,21 @@ 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);
let key = ta.pddb_key();
match self.pddb.get(TLS_TRUSTED_DICT, &key, None, false, false, None, None::<fn()>) {
Ok(_) => {
log::info!("trusted: {key}");
true
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(_) => {
log::info!("UNtrusted: {key}");
Err(e) => {
log::warn!("failed to get pddb_key: {e}");
false
}
}

View file

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