mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-16 08:38:26 +00:00
rename RustlsOwnedTrustAnchor to OwnedTrustAnchor and update for rustls v22.2
This commit is contained in:
parent
fa24528226
commit
ad01b7de6c
3 changed files with 137 additions and 224 deletions
|
|
@ -1,6 +1,6 @@
|
|||
pub mod cmd;
|
||||
mod danger;
|
||||
pub mod rota;
|
||||
pub mod ota;
|
||||
pub mod xtls;
|
||||
|
||||
use std::convert::{Into, TryFrom, TryInto};
|
||||
|
|
@ -15,14 +15,13 @@ use rkyv::{
|
|||
ser::{serializers::WriteSerializer, Serializer},
|
||||
Deserialize,
|
||||
};
|
||||
use ota::OwnedTrustAnchor;
|
||||
use rustls::{ClientConfig, ClientConnection, RootCertStore};
|
||||
use rustls::pki_types::CertificateDer;
|
||||
use sha2::Digest;
|
||||
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";
|
||||
|
||||
|
|
@ -71,15 +70,12 @@ impl Tls {
|
|||
.unwrap()
|
||||
.iter()
|
||||
.map(|i| &certificates[*i].1)
|
||||
.map(|x509| RustlsOwnedTrustAnchor::from(x509))
|
||||
.for_each(|rota| {
|
||||
self.save_rota(&rota).unwrap_or_else(|e| {
|
||||
.map(|x509| OwnedTrustAnchor::from(x509))
|
||||
.for_each(|ta| {
|
||||
self.save_ta(&ta).unwrap_or_else(|e| {
|
||||
log::warn!("failed to save cert: {e}");
|
||||
modals
|
||||
.show_notification(
|
||||
format!("failed to save:\n{}\n{e}", &rota.subject()).as_str(),
|
||||
None,
|
||||
)
|
||||
.show_notification(format!("failed to save:\n{:?}\n{e}", &ta).as_str(), None)
|
||||
.expect("modal failed");
|
||||
});
|
||||
});
|
||||
|
|
@ -137,17 +133,10 @@ impl Tls {
|
|||
/// # Arguments
|
||||
///
|
||||
/// * `ta` - a trusted trust-anchor
|
||||
pub fn save_rota(&self, ta: &RustlsOwnedTrustAnchor) -> Result<(), Error> {
|
||||
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(rota::MAX_ROTA_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)
|
||||
|
|
@ -185,17 +174,17 @@ impl Tls {
|
|||
/// # Arguments
|
||||
///
|
||||
/// * `key` - pddb key holding the trust-anchor
|
||||
pub fn get_rota(&self, key: &str) -> Option<RustlsOwnedTrustAnchor> {
|
||||
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) => {
|
||||
let mut bytes = [0u8; rota::MAX_ROTA_BYTES];
|
||||
let mut bytes = [0u8; ota::MAX_OTA_BYTES];
|
||||
match pddb_key.read(&mut bytes) {
|
||||
Ok(_) => {
|
||||
// extract pos u16 from the first 2 bytes
|
||||
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::<OwnedTrustAnchor>(&bytes, pos) };
|
||||
let ta = archive.deserialize(&mut AllocDeserializer {}).ok();
|
||||
log::info!("get trust anchor {}", key);
|
||||
log::trace!("get trust anchor'{}' = '{:?}'", key, &ta);
|
||||
|
|
@ -215,16 +204,16 @@ impl Tls {
|
|||
}
|
||||
|
||||
/// Returns a Vec of all trusted trust-anchors
|
||||
pub fn trusted(&self) -> Vec<RustlsOwnedTrustAnchor> {
|
||||
pub fn trusted(&self) -> Vec<OwnedTrustAnchor> {
|
||||
match self.pddb.list_keys(TLS_TRUSTED_DICT, None) {
|
||||
Ok(list) => list
|
||||
.iter()
|
||||
.map(|key| self.get_rota(&key))
|
||||
.filter_map(|rota| rota)
|
||||
.collect::<Vec<RustlsOwnedTrustAnchor>>(),
|
||||
.map(|key| self.get_ota(&key))
|
||||
.filter_map(|ota| ota)
|
||||
.collect::<Vec<OwnedTrustAnchor>>(),
|
||||
Err(e) => {
|
||||
log::warn!("failed to get iter over trusted: {e}");
|
||||
Vec::<RustlsOwnedTrustAnchor>::new()
|
||||
Vec::<OwnedTrustAnchor>::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -258,7 +247,7 @@ 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 = RustlsOwnedTrustAnchor::from(x509);
|
||||
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(_) => {
|
||||
|
|
@ -275,17 +264,19 @@ 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) {
|
||||
Ok(list) => {
|
||||
let rota = list
|
||||
.iter()
|
||||
.map(|key| self.get_rota(&key))
|
||||
.filter_map(|rota| rota)
|
||||
.map(|t| Into::<rustls::OwnedTrustAnchor>::into(t));
|
||||
root_store.add_trust_anchors(rota);
|
||||
let trusted = match self.pddb.list_keys(TLS_TRUSTED_DICT, None) {
|
||||
Ok(list) => list
|
||||
.iter()
|
||||
.map(|key| self.get_ota(&key))
|
||||
.filter_map(|ota| ota)
|
||||
.map(|ota| ota.into())
|
||||
.collect::<Vec<TrustAnchor>>(),
|
||||
Err(e) => {
|
||||
log::warn!("failed to get iter over trusted: {e}");
|
||||
Vec::<TrustAnchor>::new()
|
||||
}
|
||||
Err(e) => log::warn!("failed to get iter over trusted: {e}"),
|
||||
}
|
||||
};
|
||||
root_store.extend(trusted);
|
||||
root_store
|
||||
}
|
||||
|
||||
|
|
|
|||
107
libs/tls/src/ota.rs
Normal file
107
libs/tls/src/ota.rs
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
// A rkyv serialisable intermediatory for a TrustAnchor
|
||||
use rkyv::{Archive, Deserialize, Serialize};
|
||||
use rustls::pki_types::{Der, TrustAnchor};
|
||||
use std::cmp::min;
|
||||
use std::fmt;
|
||||
use x509_parser::prelude::X509Certificate;
|
||||
|
||||
pub const MAX_OTA_BYTES: usize = 1028;
|
||||
|
||||
#[derive(Archive, Serialize, Deserialize, Debug)]
|
||||
pub struct OwnedTrustAnchor {
|
||||
pub subject: Vec<u8>,
|
||||
pub spki: Vec<u8>,
|
||||
pub name_constraints: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl OwnedTrustAnchor {
|
||||
pub fn from_subject_spki_name_constraints(
|
||||
subject: impl Into<Vec<u8>>,
|
||||
spki: impl Into<Vec<u8>>,
|
||||
name_constraints: Option<impl Into<Vec<u8>>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
subject: subject.into(),
|
||||
spki: spki.into(),
|
||||
name_constraints: name_constraints.map(|x| x.into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pddb_key(&self) -> String {
|
||||
let subject = match std::str::from_utf8(&self.subject) {
|
||||
Ok(subject) => subject,
|
||||
Err(e) => "",
|
||||
};
|
||||
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 fmt::Display for OwnedTrustAnchor {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", std::str::from_utf8(&self.subject).unwrap_or("failed convert from_utf8"))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<TrustAnchor<'a>> for OwnedTrustAnchor {
|
||||
fn from(ta: TrustAnchor) -> Self {
|
||||
Self::from_subject_spki_name_constraints(
|
||||
ta.subject.as_ref().to_owned(),
|
||||
ta.subject_public_key_info.as_ref().to_owned(),
|
||||
ta.name_constraints.map(|nc| nc.as_ref().to_owned()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<&X509Certificate<'a>> for OwnedTrustAnchor {
|
||||
fn from(x509: &X509Certificate) -> Self {
|
||||
Self::from_subject_spki_name_constraints(
|
||||
x509.subject().as_raw(),
|
||||
x509.public_key().raw,
|
||||
None::<&[u8]>, // ignore name constraints for now TODO
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Into<TrustAnchor<'a>> for OwnedTrustAnchor {
|
||||
fn into(self) -> TrustAnchor<'a> {
|
||||
TrustAnchor {
|
||||
subject: Der::from_slice(self.subject.as_slice()),
|
||||
subject_public_key_info: Der::from_slice(self.spki.as_slice()),
|
||||
name_constraints: if self.name_constraints.is_some() {
|
||||
Some(Der::from_slice(self.name_constraints.as_deref().unwrap()))
|
||||
} else {
|
||||
None
|
||||
},
|
||||
}
|
||||
.to_owned()
|
||||
}
|
||||
}
|
||||
|
|
@ -1,185 +0,0 @@
|
|||
// A mirror of rustls::OwnedTrustAnchor
|
||||
|
||||
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;
|
||||
|
||||
/// A close mirror of rustls::OwnedTrustAnchor - but with extras
|
||||
/// Note that the subject, spki & name_constraints fields are
|
||||
/// DER encoded but WITHOUT the DER header.
|
||||
#[derive(Archive, Serialize, Deserialize, Debug)]
|
||||
pub struct RustlsOwnedTrustAnchor {
|
||||
pub subject: Vec<u8>,
|
||||
pub spki: Vec<u8>,
|
||||
pub name_constraints: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl RustlsOwnedTrustAnchor {
|
||||
pub fn from_subject_spki_name_constraints(
|
||||
subject: impl Into<Vec<u8>>,
|
||||
spki: impl Into<Vec<u8>>,
|
||||
name_constraints: Option<impl Into<Vec<u8>>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
subject: subject.into(),
|
||||
spki: spki.into(),
|
||||
name_constraints: name_constraints.map(|x| x.into()),
|
||||
}
|
||||
}
|
||||
|
||||
// decoded subject
|
||||
pub fn subject(&self) -> String {
|
||||
match add_der_header(Tag::Sequence, &self.subject) {
|
||||
Ok(der) => match x509_parser::x509::X509Name::from_der(&der) {
|
||||
Ok((_, decoded)) => decoded.to_string(),
|
||||
Err(e) => {
|
||||
log::warn!("{:?}", e);
|
||||
"der decode failed".to_string()
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
log::warn!("{:?}", e.into_inner().unwrap());
|
||||
"der decode failed".to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// decoded public key
|
||||
// see https://docs.rs/x509-parser/0.15.0/src/x509_parser/x509.rs.html#260-274
|
||||
#[allow(unreachable_code)]
|
||||
pub fn public_key(&self) -> Result<Vec<u8>, Error> {
|
||||
match add_der_header(Tag::Sequence, &self.spki) {
|
||||
Ok(der) => match x509_parser::x509::SubjectPublicKeyInfo::from_der(&der) {
|
||||
Ok((_, spki)) => Ok(spki.subject_public_key.data.to_vec()),
|
||||
Err(e) => {
|
||||
log::warn!("{:?}", e);
|
||||
Err(Error::new(ErrorKind::InvalidData, "failed spki der decode"))
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
log::warn!("{:?}", e.into_inner().unwrap());
|
||||
Err(Error::new(ErrorKind::InvalidData, "failed spki der header"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
fn from(x509: &X509Certificate) -> Self {
|
||||
// Remove the DER headers in keeping with rustls::OwnersTrustAnchor
|
||||
RustlsOwnedTrustAnchor {
|
||||
subject: match rm_der_header(x509.subject().as_raw()) {
|
||||
Ok(naked_der) => naked_der,
|
||||
Err(e) => {
|
||||
log::warn!("{e}");
|
||||
b"der decode failed".to_vec()
|
||||
}
|
||||
},
|
||||
spki: match rm_der_header(x509.public_key().raw) {
|
||||
Ok(naked_der) => naked_der,
|
||||
Err(e) => {
|
||||
log::warn!("{e}");
|
||||
b"der decode failed".to_vec()
|
||||
}
|
||||
},
|
||||
name_constraints: match x509.name_constraints() {
|
||||
Ok(Some(_)) => {
|
||||
log::warn!("Name Constraints ignored");
|
||||
None
|
||||
}
|
||||
Ok(None) => None,
|
||||
Err(e) => {
|
||||
log::warn!("{e}");
|
||||
None
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a DER header to a DER encoded [u8]
|
||||
fn add_der_header(tag: Tag, naked: &Vec<u8>) -> Result<Vec<u8>, Error> {
|
||||
match Header::new(tag, naked.len()) {
|
||||
Ok(header) => {
|
||||
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: header")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a DER header from a DER encoded [u8]
|
||||
fn rm_der_header(der: &[u8]) -> Result<Vec<u8>, Error> {
|
||||
match der::SliceReader::new(der) {
|
||||
Ok(reader) => match reader.peek_header() {
|
||||
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: length")),
|
||||
},
|
||||
Err(_) => Err(Error::new(ErrorKind::InvalidData, "der decode failed: header")),
|
||||
},
|
||||
Err(_) => Err(Error::new(ErrorKind::InvalidData, "der decode failed: reader")),
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<&rustls::pki_types::TrustAnchor<'a>> for RustlsOwnedTrustAnchor {
|
||||
fn from(ta: &rustls::pki_types::TrustAnchor) -> Self {
|
||||
Self::from_subject_spki_name_constraints(ta.subject, ta.spki, ta.name_constraints)
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<rustls::OwnedTrustAnchor> for RustlsOwnedTrustAnchor {
|
||||
fn into(self) -> rustls::OwnedTrustAnchor {
|
||||
rustls::OwnedTrustAnchor::from_subject_spki_name_constraints(
|
||||
self.subject,
|
||||
self.spki,
|
||||
self.name_constraints,
|
||||
)
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue