1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3#![allow(renamed_and_removed_lints)] #![allow(unknown_lints)] #![warn(missing_docs)]
7#![warn(noop_method_call)]
8#![warn(unreachable_pub)]
9#![warn(clippy::all)]
10#![deny(clippy::await_holding_lock)]
11#![deny(clippy::cargo_common_metadata)]
12#![deny(clippy::cast_lossless)]
13#![deny(clippy::checked_conversions)]
14#![allow(clippy::cognitive_complexity)] #![deny(clippy::debug_assert_with_mut_call)]
16#![deny(clippy::exhaustive_enums)]
17#![deny(clippy::exhaustive_structs)]
18#![deny(clippy::expl_impl_clone_on_copy)]
19#![deny(clippy::fallible_impl_from)]
20#![deny(clippy::implicit_clone)]
21#![deny(clippy::large_stack_arrays)]
22#![warn(clippy::manual_ok_or)]
23#![deny(clippy::missing_docs_in_private_items)]
24#![warn(clippy::needless_borrow)]
25#![warn(clippy::needless_pass_by_value)]
26#![warn(clippy::option_option)]
27#![warn(clippy::or_fun_call)]
28#![deny(clippy::print_stderr)]
29#![deny(clippy::print_stdout)]
30#![warn(clippy::rc_buffer)]
31#![deny(clippy::ref_option_ref)]
32#![warn(clippy::semicolon_if_nothing_returned)]
33#![warn(clippy::trait_duplication_in_bounds)]
34#![deny(clippy::unchecked_time_subtraction)]
35#![deny(clippy::unnecessary_wraps)]
36#![warn(clippy::unseparated_literal_suffix)]
37#![deny(clippy::unwrap_used)]
38#![deny(clippy::mod_module_files)]
39#![allow(clippy::let_unit_value)] #![allow(clippy::uninlined_format_args)]
41#![allow(clippy::significant_drop_in_scrutinee)] #![allow(clippy::result_large_err)] #![allow(clippy::needless_raw_string_hashes)] #![allow(clippy::needless_lifetimes)] #![allow(mismatched_lifetime_syntaxes)] #![allow(clippy::collapsible_if)] #![deny(clippy::unused_async)]
48#![deny(clippy::string_slice)] #![allow(recursion_depth_exceeding_limit)] #![warn(unnameable_types)]
54
55mod err;
56pub mod rsa;
57
58#[cfg(feature = "x509")]
59pub use tor_cert_x509 as x509;
60
61use caret::caret_int;
62use tor_bytes::{Error as BytesError, Result as BytesResult};
63use tor_bytes::{Readable, Reader, Writeable, Writer};
64use tor_checkable::{TimeRange, TimeRangeBound};
65use tor_llcrypto::pk::*;
66
67use web_time_compat as time;
68
69pub use err::CertError;
70
71mod encode;
72pub use encode::{EncodedCert, EncodedEd25519Cert};
73pub use err::CertEncodeError;
74
75type CertResult<T> = std::result::Result<T, CertError>;
77
78caret_int! {
79 pub struct CertType(u8) {
90 TLS_LINK_X509 = 0x01,
92 RSA_ID_X509 = 0x02,
94 LINK_AUTH_X509 = 0x03,
97
98 IDENTITY_V_SIGNING = 0x04,
100
101 SIGNING_V_TLS_CERT = 0x05,
103
104 SIGNING_V_LINK_AUTH = 0x06,
106
107 RSA_ID_V_IDENTITY = 0x07,
110
111 HS_BLINDED_ID_V_SIGNING = 0x08,
115
116 HS_IP_V_SIGNING = 0x09,
131
132 NTOR_CC_IDENTITY = 0x0A,
135
136 HS_IP_CC_SIGNING = 0x0B,
145
146 FAMILY_V_IDENTITY = 0x0C,
149 }
150}
151
152caret_int! {
153 pub struct ExtType(u8) {
155 SIGNED_WITH_ED25519_KEY = 0x04,
159 }
160}
161
162caret_int! {
163 pub struct KeyType(u8) {
165 ED25519_KEY = 0x01,
167 SHA256_OF_RSA = 0x02,
169 SHA256_OF_X509 = 0x03,
171 }
172}
173
174#[derive(Debug, Clone, PartialEq, Eq, derive_builder::Builder)]
177#[builder(build_fn(skip))]
178pub struct Ed25519Cert {
179 #[builder(setter(custom))]
181 exp_hours: ExpiryHours,
182 cert_type: CertType,
184 cert_key: CertifiedKey,
186 #[allow(unused)] #[builder(setter(custom))]
189 extensions: Vec<CertExt>,
190 #[builder(setter(custom))]
196 signed_with: Option<ed25519::Ed25519Identity>,
197}
198
199#[derive(Debug, Clone, PartialEq, Eq, derive_more::From)]
201#[non_exhaustive]
202pub enum CertifiedKey {
203 Ed25519(ed25519::Ed25519Identity),
205 #[from(skip)]
207 RsaSha256Digest([u8; 32]),
208 #[from(skip)]
210 X509Sha256Digest([u8; 32]),
211 #[from(skip)]
213 Unrecognized(UnrecognizedKey),
214}
215
216#[derive(Debug, Clone, PartialEq, Eq)]
218pub struct UnrecognizedKey {
219 key_type: KeyType,
221 key_digest: [u8; 32],
223}
224
225impl CertifiedKey {
226 pub fn key_type(&self) -> KeyType {
228 match self {
229 CertifiedKey::Ed25519(_) => KeyType::ED25519_KEY,
230 CertifiedKey::RsaSha256Digest(_) => KeyType::SHA256_OF_RSA,
231 CertifiedKey::X509Sha256Digest(_) => KeyType::SHA256_OF_X509,
232
233 CertifiedKey::Unrecognized(u) => u.key_type,
234 }
235 }
236 pub fn as_bytes(&self) -> &[u8] {
239 match self {
240 CertifiedKey::Ed25519(k) => k.as_bytes(),
241 CertifiedKey::RsaSha256Digest(k) => &k[..],
242 CertifiedKey::X509Sha256Digest(k) => &k[..],
243 CertifiedKey::Unrecognized(u) => &u.key_digest[..],
244 }
245 }
246 pub fn as_ed25519(&self) -> Option<&ed25519::Ed25519Identity> {
249 match self {
250 CertifiedKey::Ed25519(k) => Some(k),
251 _ => None,
252 }
253 }
254 fn from_reader(key_type: KeyType, r: &mut Reader<'_>) -> BytesResult<Self> {
257 Ok(match key_type {
258 KeyType::ED25519_KEY => CertifiedKey::Ed25519(r.extract()?),
259 KeyType::SHA256_OF_RSA => CertifiedKey::RsaSha256Digest(r.extract()?),
260 KeyType::SHA256_OF_X509 => CertifiedKey::X509Sha256Digest(r.extract()?),
261 _ => CertifiedKey::Unrecognized(UnrecognizedKey {
262 key_type,
263 key_digest: r.extract()?,
264 }),
265 })
266 }
267}
268
269#[derive(Debug, Clone, PartialEq, Eq)]
271enum CertExt {
272 SignedWithEd25519(SignedWithEd25519Ext),
274 Unrecognized(UnrecognizedExt),
276}
277
278#[derive(Debug, Clone, PartialEq, Eq)]
280#[allow(unused)]
281struct UnrecognizedExt {
282 affects_validation: bool,
285 ext_type: ExtType,
287 body: Vec<u8>,
289}
290
291impl CertExt {
292 fn ext_id(&self) -> ExtType {
294 match self {
295 CertExt::SignedWithEd25519(_) => ExtType::SIGNED_WITH_ED25519_KEY,
296 CertExt::Unrecognized(u) => u.ext_type,
297 }
298 }
299}
300
301#[derive(Debug, Clone, PartialEq, Eq)]
303struct SignedWithEd25519Ext {
304 pk: ed25519::Ed25519Identity,
306}
307
308impl Readable for CertExt {
309 fn take_from(b: &mut Reader<'_>) -> BytesResult<Self> {
310 let len = b.take_u16()?;
311 let ext_type: ExtType = b.take_u8()?.into();
312 let flags = b.take_u8()?;
313 let body = b.take(len as usize)?;
314
315 Ok(match ext_type {
316 ExtType::SIGNED_WITH_ED25519_KEY => CertExt::SignedWithEd25519(SignedWithEd25519Ext {
317 pk: ed25519::Ed25519Identity::from_bytes(body).ok_or_else(|| {
318 BytesError::InvalidMessage("wrong length on Ed25519 key".into())
319 })?,
320 }),
321 _ => {
322 if (flags & 1) != 0 {
323 return Err(BytesError::InvalidMessage(
324 "unrecognized certificate extension, with 'affects_validation' flag set."
325 .into(),
326 ));
327 }
328 CertExt::Unrecognized(UnrecognizedExt {
329 affects_validation: false,
330 ext_type,
331 body: body.into(),
332 })
333 }
334 })
335 }
336}
337
338impl Writeable for KeyUnknownCert {
339 fn write_onto<B: Writer + ?Sized>(&self, b: &mut B) -> Result<(), tor_bytes::EncodeError> {
340 self.cert.write_onto(b)
341 }
342}
343
344impl Readable for KeyUnknownCert {
345 fn take_from(r: &mut Reader<'_>) -> BytesResult<KeyUnknownCert> {
346 let b = r.take_rest();
347 Ed25519Cert::decode(b)
348 }
349}
350
351impl Ed25519Cert {
352 pub fn decode(cert: &[u8]) -> BytesResult<KeyUnknownCert> {
361 let mut r = Reader::from_slice(cert);
362 let v = r.take_u8()?;
363 if v != 1 {
364 return Err(BytesError::InvalidMessage(
367 "Unrecognized certificate version".into(),
368 ));
369 }
370 let cert_type = r.take_u8()?.into();
371 let exp_hours = r.extract()?;
372 let mut cert_key_type = r.take_u8()?.into();
373
374 if cert_type == CertType::SIGNING_V_TLS_CERT && cert_key_type == KeyType::ED25519_KEY {
378 cert_key_type = KeyType::SHA256_OF_X509;
379 }
380
381 let cert_key = CertifiedKey::from_reader(cert_key_type, &mut r)?;
382 let n_exts = r.take_u8()?;
383 let mut extensions = Vec::new();
384 for _ in 0..n_exts {
385 let e: CertExt = r.extract()?;
386 extensions.push(e);
387 }
388
389 let sig_offset = r.consumed();
390 let signature: ed25519::Signature = r.extract()?;
391 r.should_be_exhausted()?;
392 let keyext = extensions
395 .iter()
396 .find(|e| e.ext_id() == ExtType::SIGNED_WITH_ED25519_KEY);
397
398 let included_pkey = match keyext {
399 Some(CertExt::SignedWithEd25519(s)) => Some(s.pk),
400 _ => None,
401 };
402
403 Ok(KeyUnknownCert {
404 cert: UncheckedCert {
405 cert: Ed25519Cert {
406 exp_hours,
407 cert_type,
408 cert_key,
409 extensions,
410
411 signed_with: included_pkey,
412 },
413 text: cert[0..sig_offset].into(),
414 signature,
415 },
416 })
417 }
418
419 pub fn expiry(&self) -> std::time::SystemTime {
421 self.exp_hours.into()
422 }
423
424 pub fn is_expired_at(&self, when: std::time::SystemTime) -> bool {
428 when > self.expiry()
429 }
430
431 pub fn subject_key(&self) -> &CertifiedKey {
434 &self.cert_key
435 }
436
437 pub fn signing_key(&self) -> Option<&ed25519::Ed25519Identity> {
439 self.signed_with.as_ref()
440 }
441
442 pub fn cert_type(&self) -> CertType {
444 self.cert_type
445 }
446}
447
448#[derive(Clone, Debug, PartialEq, Eq)]
457pub struct KeyUnknownCert {
458 cert: UncheckedCert,
460}
461
462impl KeyUnknownCert {
463 pub fn peek_cert_type(&self) -> CertType {
465 self.cert.cert.cert_type
466 }
467 pub fn peek_subject_key(&self) -> &CertifiedKey {
469 &self.cert.cert.cert_key
470 }
471
472 #[deprecated(
480 since = "0.7.1",
481 note = "Use should_have_signing_key or should_be_signed_with instead."
482 )]
483 pub fn check_key(self, pkey: Option<&ed25519::Ed25519Identity>) -> CertResult<UncheckedCert> {
484 match pkey {
485 Some(wanted) => self.should_be_signed_with(wanted),
486 None => self.should_have_signing_key(),
487 }
488 }
489
490 pub fn should_have_signing_key(self) -> CertResult<UncheckedCert> {
497 let real_key = match &self.cert.cert.signed_with {
498 Some(a) => *a,
499 None => return Err(CertError::MissingPubKey),
500 };
501
502 Ok(UncheckedCert {
503 cert: Ed25519Cert {
504 signed_with: Some(real_key),
505 ..self.cert.cert
506 },
507 ..self.cert
508 })
509 }
510
511 pub fn should_be_signed_with(
517 self,
518 pkey: &ed25519::Ed25519Identity,
519 ) -> CertResult<UncheckedCert> {
520 let real_key = match &self.cert.cert.signed_with {
521 Some(a) if a == pkey => *pkey,
522 None => *pkey,
523 Some(_) => return Err(CertError::KeyMismatch),
524 };
525
526 Ok(UncheckedCert {
527 cert: Ed25519Cert {
528 signed_with: Some(real_key),
529 ..self.cert.cert
530 },
531 ..self.cert
532 })
533 }
534}
535
536#[derive(Debug, Clone, PartialEq, Eq)]
539pub struct UncheckedCert {
540 cert: Ed25519Cert,
543
544 text: Vec<u8>,
549
550 signature: ed25519::Signature,
552}
553
554#[derive(Debug, Clone, PartialEq, Eq)]
557pub struct SigCheckedCert {
558 cert: Ed25519Cert,
560}
561
562impl UncheckedCert {
563 pub fn dangerously_split(
566 self,
567 ) -> CertResult<(SigCheckedCert, ed25519::ValidatableEd25519Signature)> {
568 use tor_checkable::SelfSigned;
569 let signing_key = self.cert.signed_with.ok_or(CertError::MissingPubKey)?;
570 let signing_key = signing_key
571 .try_into()
572 .map_err(|_| CertError::BadSignature)?;
573 let signature =
574 ed25519::ValidatableEd25519Signature::new(signing_key, self.signature, &self.text[..]);
575 Ok((self.dangerously_assume_wellsigned(), signature))
576 }
577
578 pub fn peek_subject_key(&self) -> &CertifiedKey {
580 &self.cert.cert_key
581 }
582 pub fn peek_signing_key(&self) -> &ed25519::Ed25519Identity {
584 self.cert
585 .signed_with
586 .as_ref()
587 .expect("Made an UncheckedCert without a signing key")
588 }
589}
590
591impl Writeable for UncheckedCert {
592 fn write_onto<B: Writer + ?Sized>(&self, b: &mut B) -> Result<(), tor_bytes::EncodeError> {
599 self.text.write_onto(b)?;
605 self.signature.write_onto(b)?;
606 Ok(())
607 }
608}
609
610impl tor_checkable::SelfSigned<SigCheckedCert> for UncheckedCert {
611 type Error = CertError;
612
613 fn is_well_signed(&self) -> CertResult<()> {
614 let pubkey = &self.cert.signed_with.ok_or(CertError::MissingPubKey)?;
615 let pubkey: ed25519::PublicKey = pubkey.try_into().map_err(|_| CertError::BadSignature)?;
616
617 pubkey
618 .verify(&self.text[..], &self.signature)
619 .map_err(|_| CertError::BadSignature)?;
620
621 Ok(())
622 }
623
624 fn dangerously_assume_wellsigned(self) -> SigCheckedCert {
625 SigCheckedCert { cert: self.cert }
626 }
627}
628
629impl tor_checkable::TimeBound for Ed25519Cert {
630 type Inner = Ed25519Cert;
631
632 fn bounds(&self) -> TimeRange {
633 TimeRangeBound::new((), ..=self.expiry())
634 }
635
636 fn dangerously_assume_timely(self) -> Ed25519Cert {
637 self
638 }
639}
640
641impl tor_checkable::TimeBound for SigCheckedCert {
642 type Inner = Ed25519Cert;
643
644 fn bounds(&self) -> TimeRange {
645 self.cert.bounds()
646 }
647
648 fn dangerously_assume_timely(self) -> Ed25519Cert {
649 self.cert.dangerously_assume_timely()
650 }
651}
652
653#[derive(Debug, Clone, Copy, PartialEq, Eq)]
655struct ExpiryHours(u32);
656
657const SEC_PER_HOUR: u64 = 3600;
659
660impl From<ExpiryHours> for time::SystemTime {
661 fn from(value: ExpiryHours) -> Self {
662 let d = std::time::Duration::from_secs(u64::from(value.0) * SEC_PER_HOUR);
664 std::time::SystemTime::UNIX_EPOCH + d
665 }
666}
667
668impl ExpiryHours {
669 fn try_from_systemtime_ceil(expiry: time::SystemTime) -> Result<Self, CertEncodeError> {
671 let d = expiry
672 .duration_since(time::SystemTime::UNIX_EPOCH)
673 .map_err(|_| CertEncodeError::InvalidExpiration)?;
674 let sec_ceil = d.as_secs() + if d.subsec_nanos() > 0 { 1 } else { 0 };
675 let hours = sec_ceil
676 .div_ceil(SEC_PER_HOUR)
677 .try_into()
678 .map_err(|_| CertEncodeError::InvalidExpiration)?;
679 Ok(ExpiryHours(hours))
680 }
681
682 const fn max() -> Self {
684 ExpiryHours(u32::MAX)
685 }
686}
687
688impl Readable for ExpiryHours {
689 fn take_from(b: &mut Reader<'_>) -> BytesResult<Self> {
690 Ok(ExpiryHours(b.take_u32()?))
691 }
692}
693
694impl tor_bytes::Writeable for ExpiryHours {
695 fn write_onto<B: tor_bytes::Writer + ?Sized>(&self, b: &mut B) -> tor_bytes::EncodeResult<()> {
696 b.write_u32(self.0);
697 Ok(())
698 }
699}
700
701#[cfg(test)]
702mod test {
703 #![allow(clippy::bool_assert_comparison)]
705 #![allow(clippy::clone_on_copy)]
706 #![allow(clippy::dbg_macro)]
707 #![allow(clippy::mixed_attributes_style)]
708 #![allow(clippy::print_stderr)]
709 #![allow(clippy::print_stdout)]
710 #![allow(clippy::single_char_pattern)]
711 #![allow(clippy::unwrap_used)]
712 #![allow(clippy::unchecked_time_subtraction)]
713 #![allow(clippy::useless_vec)]
714 #![allow(clippy::needless_pass_by_value)]
715 #![allow(clippy::string_slice)] use super::*;
718 use hex_literal::hex;
719 use web_time_compat::SystemTimeExt;
720
721 #[test]
722 fn parse_unrecognized_ext() -> BytesResult<()> {
723 let b = hex!("0009 99 10 657874656e73696f6e");
725 let mut r = Reader::from_slice(&b);
726 let e: CertExt = r.extract()?;
727 r.should_be_exhausted()?;
728
729 assert_eq!(e.ext_id(), 0x99.into());
730
731 let b = hex!("0009 99 11 657874656e73696f6e");
734 let mut r = Reader::from_slice(&b);
735 let e: Result<CertExt, BytesError> = r.extract();
736 assert!(e.is_err());
737 assert_eq!(
738 e.err().unwrap(),
739 BytesError::InvalidMessage(
740 "unrecognized certificate extension, with 'affects_validation' flag set.".into()
741 )
742 );
743
744 Ok(())
745 }
746
747 #[test]
748 fn certified_key() -> BytesResult<()> {
749 let b =
750 hex!("4c27616d6f757220756e6974206365757820717527656e636861c3ae6e616974206c6520666572");
751 let mut r = Reader::from_slice(&b);
752
753 let ck = CertifiedKey::from_reader(KeyType::SHA256_OF_RSA, &mut r)?;
754 assert_eq!(ck.as_bytes(), &b[..32]);
755 assert_eq!(ck.key_type(), KeyType::SHA256_OF_RSA);
756 assert_eq!(r.remaining(), 7);
757
758 let mut r = Reader::from_slice(&b);
759 let ck = CertifiedKey::from_reader(42.into(), &mut r)?;
760 assert_eq!(ck.as_bytes(), &b[..32]);
761 assert_eq!(ck.key_type(), 42.into());
762 assert_eq!(r.remaining(), 7);
763
764 Ok(())
765 }
766
767 #[test]
768 fn expiry_hours_ceil() {
769 use std::time::{Duration, SystemTime};
770
771 let now = SystemTime::get();
772 let mut exp = now + Duration::from_secs(24 * 60 * 60);
773 for _ in 0..=3600 {
774 let eh = ExpiryHours::try_from_systemtime_ceil(exp).unwrap();
775 assert!(SystemTime::from(eh) >= exp);
776 assert!(SystemTime::from(eh) < exp + Duration::from_secs(SEC_PER_HOUR));
777
778 exp += Duration::from_secs(1);
779 }
780 }
781}