use tor_bytes::Reader;
use tor_checkable::{ExternallySigned, timed::TimerangeBound};
use tor_llcrypto as ll;
use digest::Digest;
use crate::{CertType, ExpiryHours};
mod encode;
pub use encode::EncodedRsaCrosscert;
#[must_use]
pub struct RsaCrosscert {
subject_key: ll::pk::ed25519::Ed25519Identity,
exp_hours: ExpiryHours,
digest: [u8; 32],
signature: Vec<u8>,
}
const PREFIX: &[u8] = b"Tor TLS RSA/Ed25519 cross-certificate";
fn compute_digest(c: &[u8]) -> [u8; 32] {
let mut d = ll::d::Sha256::new();
d.update(PREFIX);
d.update(c);
d.finalize().into()
}
impl RsaCrosscert {
pub fn expiry(&self) -> std::time::SystemTime {
self.exp_hours.into()
}
pub fn digest(&self) -> &[u8; 32] {
&self.digest
}
pub fn subject_key_matches(&self, other: &ll::pk::ed25519::Ed25519Identity) -> bool {
other == &self.subject_key
}
pub fn cert_type(&self) -> CertType {
CertType::RSA_ID_V_IDENTITY
}
pub fn decode(bytes: &[u8]) -> tor_bytes::Result<UncheckedRsaCrosscert> {
let mut r = Reader::from_slice(bytes);
let signed_portion = r.peek(36)?; let subject_key = r.extract()?;
let exp_hours = r.extract()?;
let siglen = r.take_u8()?;
let signature = r.take(siglen as usize)?.into();
let digest = compute_digest(signed_portion);
let cc = RsaCrosscert {
subject_key,
exp_hours,
digest,
signature,
};
Ok(UncheckedRsaCrosscert(cc))
}
}
pub struct UncheckedRsaCrosscert(RsaCrosscert);
impl ExternallySigned<TimerangeBound<RsaCrosscert>> for UncheckedRsaCrosscert {
type Key = ll::pk::rsa::PublicKey;
type KeyHint = ();
type Error = tor_bytes::Error;
fn key_is_correct(&self, _k: &Self::Key) -> Result<(), Self::KeyHint> {
Ok(())
}
fn is_well_signed(&self, k: &Self::Key) -> Result<(), Self::Error> {
k.verify(&self.0.digest[..], &self.0.signature[..])
.map_err(|_| {
tor_bytes::Error::InvalidMessage(
"Invalid signature on RSA->Ed identity crosscert".into(),
)
})?;
Ok(())
}
fn dangerously_assume_wellsigned(self) -> TimerangeBound<RsaCrosscert> {
let expiration = self.0.expiry();
TimerangeBound::new(self.0, ..expiration)
}
}