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)] mod err;
53pub mod rsa;
54
55#[cfg(feature = "x509")]
56pub use tor_cert_x509 as x509;
57
58use caret::caret_int;
59use tor_bytes::{Error as BytesError, Result as BytesResult};
60use tor_bytes::{Readable, Reader, Writeable, Writer};
61use tor_checkable::{TimeRange, TimeRangeBound};
62use tor_llcrypto::pk::*;
63
64use web_time_compat as time;
65
66pub use err::CertError;
67
68mod encode;
69pub use encode::{EncodedCert, EncodedEd25519Cert};
70pub use err::CertEncodeError;
71
72type CertResult<T> = std::result::Result<T, CertError>;
74
75caret_int! {
76 pub struct CertType(u8) {
87 TLS_LINK_X509 = 0x01,
89 RSA_ID_X509 = 0x02,
91 LINK_AUTH_X509 = 0x03,
94
95 IDENTITY_V_SIGNING = 0x04,
97
98 SIGNING_V_TLS_CERT = 0x05,
100
101 SIGNING_V_LINK_AUTH = 0x06,
103
104 RSA_ID_V_IDENTITY = 0x07,
107
108 HS_BLINDED_ID_V_SIGNING = 0x08,
112
113 HS_IP_V_SIGNING = 0x09,
128
129 NTOR_CC_IDENTITY = 0x0A,
132
133 HS_IP_CC_SIGNING = 0x0B,
142
143 FAMILY_V_IDENTITY = 0x0C,
146 }
147}
148
149caret_int! {
150 pub struct ExtType(u8) {
152 SIGNED_WITH_ED25519_KEY = 0x04,
156 }
157}
158
159caret_int! {
160 pub struct KeyType(u8) {
162 ED25519_KEY = 0x01,
164 SHA256_OF_RSA = 0x02,
166 SHA256_OF_X509 = 0x03,
168 }
169}
170
171#[derive(Debug, Clone, PartialEq, Eq, derive_builder::Builder)]
174#[builder(build_fn(skip))]
175pub struct Ed25519Cert {
176 #[builder(setter(custom))]
178 exp_hours: ExpiryHours,
179 cert_type: CertType,
181 cert_key: CertifiedKey,
183 #[allow(unused)] #[builder(setter(custom))]
186 extensions: Vec<CertExt>,
187 #[builder(setter(custom))]
193 signed_with: Option<ed25519::Ed25519Identity>,
194}
195
196#[derive(Debug, Clone, PartialEq, Eq, derive_more::From)]
198#[non_exhaustive]
199pub enum CertifiedKey {
200 Ed25519(ed25519::Ed25519Identity),
202 #[from(skip)]
204 RsaSha256Digest([u8; 32]),
205 #[from(skip)]
207 X509Sha256Digest([u8; 32]),
208 #[from(skip)]
210 Unrecognized(UnrecognizedKey),
211}
212
213#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct UnrecognizedKey {
216 key_type: KeyType,
218 key_digest: [u8; 32],
220}
221
222impl CertifiedKey {
223 pub fn key_type(&self) -> KeyType {
225 match self {
226 CertifiedKey::Ed25519(_) => KeyType::ED25519_KEY,
227 CertifiedKey::RsaSha256Digest(_) => KeyType::SHA256_OF_RSA,
228 CertifiedKey::X509Sha256Digest(_) => KeyType::SHA256_OF_X509,
229
230 CertifiedKey::Unrecognized(u) => u.key_type,
231 }
232 }
233 pub fn as_bytes(&self) -> &[u8] {
236 match self {
237 CertifiedKey::Ed25519(k) => k.as_bytes(),
238 CertifiedKey::RsaSha256Digest(k) => &k[..],
239 CertifiedKey::X509Sha256Digest(k) => &k[..],
240 CertifiedKey::Unrecognized(u) => &u.key_digest[..],
241 }
242 }
243 pub fn as_ed25519(&self) -> Option<&ed25519::Ed25519Identity> {
246 match self {
247 CertifiedKey::Ed25519(k) => Some(k),
248 _ => None,
249 }
250 }
251 fn from_reader(key_type: KeyType, r: &mut Reader<'_>) -> BytesResult<Self> {
254 Ok(match key_type {
255 KeyType::ED25519_KEY => CertifiedKey::Ed25519(r.extract()?),
256 KeyType::SHA256_OF_RSA => CertifiedKey::RsaSha256Digest(r.extract()?),
257 KeyType::SHA256_OF_X509 => CertifiedKey::X509Sha256Digest(r.extract()?),
258 _ => CertifiedKey::Unrecognized(UnrecognizedKey {
259 key_type,
260 key_digest: r.extract()?,
261 }),
262 })
263 }
264}
265
266#[derive(Debug, Clone, PartialEq, Eq)]
268enum CertExt {
269 SignedWithEd25519(SignedWithEd25519Ext),
271 Unrecognized(UnrecognizedExt),
273}
274
275#[derive(Debug, Clone, PartialEq, Eq)]
277#[allow(unused)]
278struct UnrecognizedExt {
279 affects_validation: bool,
282 ext_type: ExtType,
284 body: Vec<u8>,
286}
287
288impl CertExt {
289 fn ext_id(&self) -> ExtType {
291 match self {
292 CertExt::SignedWithEd25519(_) => ExtType::SIGNED_WITH_ED25519_KEY,
293 CertExt::Unrecognized(u) => u.ext_type,
294 }
295 }
296}
297
298#[derive(Debug, Clone, PartialEq, Eq)]
300struct SignedWithEd25519Ext {
301 pk: ed25519::Ed25519Identity,
303}
304
305impl Readable for CertExt {
306 fn take_from(b: &mut Reader<'_>) -> BytesResult<Self> {
307 let len = b.take_u16()?;
308 let ext_type: ExtType = b.take_u8()?.into();
309 let flags = b.take_u8()?;
310 let body = b.take(len as usize)?;
311
312 Ok(match ext_type {
313 ExtType::SIGNED_WITH_ED25519_KEY => CertExt::SignedWithEd25519(SignedWithEd25519Ext {
314 pk: ed25519::Ed25519Identity::from_bytes(body).ok_or_else(|| {
315 BytesError::InvalidMessage("wrong length on Ed25519 key".into())
316 })?,
317 }),
318 _ => {
319 if (flags & 1) != 0 {
320 return Err(BytesError::InvalidMessage(
321 "unrecognized certificate extension, with 'affects_validation' flag set."
322 .into(),
323 ));
324 }
325 CertExt::Unrecognized(UnrecognizedExt {
326 affects_validation: false,
327 ext_type,
328 body: body.into(),
329 })
330 }
331 })
332 }
333}
334
335impl Writeable for KeyUnknownCert {
336 fn write_onto<B: Writer + ?Sized>(&self, b: &mut B) -> Result<(), tor_bytes::EncodeError> {
337 self.cert.write_onto(b)
338 }
339}
340
341impl Readable for KeyUnknownCert {
342 fn take_from(r: &mut Reader<'_>) -> BytesResult<KeyUnknownCert> {
343 let b = r.take_rest();
344 Ed25519Cert::decode(b)
345 }
346}
347
348impl Ed25519Cert {
349 pub fn decode(cert: &[u8]) -> BytesResult<KeyUnknownCert> {
358 let mut r = Reader::from_slice(cert);
359 let v = r.take_u8()?;
360 if v != 1 {
361 return Err(BytesError::InvalidMessage(
364 "Unrecognized certificate version".into(),
365 ));
366 }
367 let cert_type = r.take_u8()?.into();
368 let exp_hours = r.extract()?;
369 let mut cert_key_type = r.take_u8()?.into();
370
371 if cert_type == CertType::SIGNING_V_TLS_CERT && cert_key_type == KeyType::ED25519_KEY {
375 cert_key_type = KeyType::SHA256_OF_X509;
376 }
377
378 let cert_key = CertifiedKey::from_reader(cert_key_type, &mut r)?;
379 let n_exts = r.take_u8()?;
380 let mut extensions = Vec::new();
381 for _ in 0..n_exts {
382 let e: CertExt = r.extract()?;
383 extensions.push(e);
384 }
385
386 let sig_offset = r.consumed();
387 let signature: ed25519::Signature = r.extract()?;
388 r.should_be_exhausted()?;
389 let keyext = extensions
392 .iter()
393 .find(|e| e.ext_id() == ExtType::SIGNED_WITH_ED25519_KEY);
394
395 let included_pkey = match keyext {
396 Some(CertExt::SignedWithEd25519(s)) => Some(s.pk),
397 _ => None,
398 };
399
400 Ok(KeyUnknownCert {
401 cert: UncheckedCert {
402 cert: Ed25519Cert {
403 exp_hours,
404 cert_type,
405 cert_key,
406 extensions,
407
408 signed_with: included_pkey,
409 },
410 text: cert[0..sig_offset].into(),
411 signature,
412 },
413 })
414 }
415
416 pub fn expiry(&self) -> std::time::SystemTime {
418 self.exp_hours.into()
419 }
420
421 pub fn is_expired_at(&self, when: std::time::SystemTime) -> bool {
425 when > self.expiry()
426 }
427
428 pub fn subject_key(&self) -> &CertifiedKey {
431 &self.cert_key
432 }
433
434 pub fn signing_key(&self) -> Option<&ed25519::Ed25519Identity> {
436 self.signed_with.as_ref()
437 }
438
439 pub fn cert_type(&self) -> CertType {
441 self.cert_type
442 }
443}
444
445#[derive(Clone, Debug, PartialEq, Eq)]
454pub struct KeyUnknownCert {
455 cert: UncheckedCert,
457}
458
459impl KeyUnknownCert {
460 pub fn peek_cert_type(&self) -> CertType {
462 self.cert.cert.cert_type
463 }
464 pub fn peek_subject_key(&self) -> &CertifiedKey {
466 &self.cert.cert.cert_key
467 }
468
469 #[deprecated(
477 since = "0.7.1",
478 note = "Use should_have_signing_key or should_be_signed_with instead."
479 )]
480 pub fn check_key(self, pkey: Option<&ed25519::Ed25519Identity>) -> CertResult<UncheckedCert> {
481 match pkey {
482 Some(wanted) => self.should_be_signed_with(wanted),
483 None => self.should_have_signing_key(),
484 }
485 }
486
487 pub fn should_have_signing_key(self) -> CertResult<UncheckedCert> {
494 let real_key = match &self.cert.cert.signed_with {
495 Some(a) => *a,
496 None => return Err(CertError::MissingPubKey),
497 };
498
499 Ok(UncheckedCert {
500 cert: Ed25519Cert {
501 signed_with: Some(real_key),
502 ..self.cert.cert
503 },
504 ..self.cert
505 })
506 }
507
508 pub fn should_be_signed_with(
514 self,
515 pkey: &ed25519::Ed25519Identity,
516 ) -> CertResult<UncheckedCert> {
517 let real_key = match &self.cert.cert.signed_with {
518 Some(a) if a == pkey => *pkey,
519 None => *pkey,
520 Some(_) => return Err(CertError::KeyMismatch),
521 };
522
523 Ok(UncheckedCert {
524 cert: Ed25519Cert {
525 signed_with: Some(real_key),
526 ..self.cert.cert
527 },
528 ..self.cert
529 })
530 }
531}
532
533#[derive(Debug, Clone, PartialEq, Eq)]
536pub struct UncheckedCert {
537 cert: Ed25519Cert,
540
541 text: Vec<u8>,
546
547 signature: ed25519::Signature,
549}
550
551#[derive(Debug, Clone, PartialEq, Eq)]
554pub struct SigCheckedCert {
555 cert: Ed25519Cert,
557}
558
559impl UncheckedCert {
560 pub fn dangerously_split(
563 self,
564 ) -> CertResult<(SigCheckedCert, ed25519::ValidatableEd25519Signature)> {
565 use tor_checkable::SelfSigned;
566 let signing_key = self.cert.signed_with.ok_or(CertError::MissingPubKey)?;
567 let signing_key = signing_key
568 .try_into()
569 .map_err(|_| CertError::BadSignature)?;
570 let signature =
571 ed25519::ValidatableEd25519Signature::new(signing_key, self.signature, &self.text[..]);
572 Ok((self.dangerously_assume_wellsigned(), signature))
573 }
574
575 pub fn peek_subject_key(&self) -> &CertifiedKey {
577 &self.cert.cert_key
578 }
579 pub fn peek_signing_key(&self) -> &ed25519::Ed25519Identity {
581 self.cert
582 .signed_with
583 .as_ref()
584 .expect("Made an UncheckedCert without a signing key")
585 }
586}
587
588impl Writeable for UncheckedCert {
589 fn write_onto<B: Writer + ?Sized>(&self, b: &mut B) -> Result<(), tor_bytes::EncodeError> {
596 self.text.write_onto(b)?;
602 self.signature.write_onto(b)?;
603 Ok(())
604 }
605}
606
607impl tor_checkable::SelfSigned<SigCheckedCert> for UncheckedCert {
608 type Error = CertError;
609
610 fn is_well_signed(&self) -> CertResult<()> {
611 let pubkey = &self.cert.signed_with.ok_or(CertError::MissingPubKey)?;
612 let pubkey: ed25519::PublicKey = pubkey.try_into().map_err(|_| CertError::BadSignature)?;
613
614 pubkey
615 .verify(&self.text[..], &self.signature)
616 .map_err(|_| CertError::BadSignature)?;
617
618 Ok(())
619 }
620
621 fn dangerously_assume_wellsigned(self) -> SigCheckedCert {
622 SigCheckedCert { cert: self.cert }
623 }
624}
625
626impl tor_checkable::TimeBound for Ed25519Cert {
627 type Inner = Ed25519Cert;
628
629 fn bounds(&self) -> TimeRange {
630 TimeRangeBound::new((), ..=self.expiry())
631 }
632
633 fn dangerously_assume_timely(self) -> Ed25519Cert {
634 self
635 }
636}
637
638impl tor_checkable::TimeBound for SigCheckedCert {
639 type Inner = Ed25519Cert;
640
641 fn bounds(&self) -> TimeRange {
642 self.cert.bounds()
643 }
644
645 fn dangerously_assume_timely(self) -> Ed25519Cert {
646 self.cert.dangerously_assume_timely()
647 }
648}
649
650#[derive(Debug, Clone, Copy, PartialEq, Eq)]
652struct ExpiryHours(u32);
653
654const SEC_PER_HOUR: u64 = 3600;
656
657impl From<ExpiryHours> for time::SystemTime {
658 fn from(value: ExpiryHours) -> Self {
659 let d = std::time::Duration::from_secs(u64::from(value.0) * SEC_PER_HOUR);
661 std::time::SystemTime::UNIX_EPOCH + d
662 }
663}
664
665impl ExpiryHours {
666 fn try_from_systemtime_ceil(expiry: time::SystemTime) -> Result<Self, CertEncodeError> {
668 let d = expiry
669 .duration_since(time::SystemTime::UNIX_EPOCH)
670 .map_err(|_| CertEncodeError::InvalidExpiration)?;
671 let sec_ceil = d.as_secs() + if d.subsec_nanos() > 0 { 1 } else { 0 };
672 let hours = sec_ceil
673 .div_ceil(SEC_PER_HOUR)
674 .try_into()
675 .map_err(|_| CertEncodeError::InvalidExpiration)?;
676 Ok(ExpiryHours(hours))
677 }
678
679 const fn max() -> Self {
681 ExpiryHours(u32::MAX)
682 }
683}
684
685impl Readable for ExpiryHours {
686 fn take_from(b: &mut Reader<'_>) -> BytesResult<Self> {
687 Ok(ExpiryHours(b.take_u32()?))
688 }
689}
690
691impl tor_bytes::Writeable for ExpiryHours {
692 fn write_onto<B: tor_bytes::Writer + ?Sized>(&self, b: &mut B) -> tor_bytes::EncodeResult<()> {
693 b.write_u32(self.0);
694 Ok(())
695 }
696}
697
698#[cfg(test)]
699mod test {
700 #![allow(clippy::bool_assert_comparison)]
702 #![allow(clippy::clone_on_copy)]
703 #![allow(clippy::dbg_macro)]
704 #![allow(clippy::mixed_attributes_style)]
705 #![allow(clippy::print_stderr)]
706 #![allow(clippy::print_stdout)]
707 #![allow(clippy::single_char_pattern)]
708 #![allow(clippy::unwrap_used)]
709 #![allow(clippy::unchecked_time_subtraction)]
710 #![allow(clippy::useless_vec)]
711 #![allow(clippy::needless_pass_by_value)]
712 #![allow(clippy::string_slice)] use super::*;
715 use hex_literal::hex;
716 use web_time_compat::SystemTimeExt;
717
718 #[test]
719 fn parse_unrecognized_ext() -> BytesResult<()> {
720 let b = hex!("0009 99 10 657874656e73696f6e");
722 let mut r = Reader::from_slice(&b);
723 let e: CertExt = r.extract()?;
724 r.should_be_exhausted()?;
725
726 assert_eq!(e.ext_id(), 0x99.into());
727
728 let b = hex!("0009 99 11 657874656e73696f6e");
731 let mut r = Reader::from_slice(&b);
732 let e: Result<CertExt, BytesError> = r.extract();
733 assert!(e.is_err());
734 assert_eq!(
735 e.err().unwrap(),
736 BytesError::InvalidMessage(
737 "unrecognized certificate extension, with 'affects_validation' flag set.".into()
738 )
739 );
740
741 Ok(())
742 }
743
744 #[test]
745 fn certified_key() -> BytesResult<()> {
746 let b =
747 hex!("4c27616d6f757220756e6974206365757820717527656e636861c3ae6e616974206c6520666572");
748 let mut r = Reader::from_slice(&b);
749
750 let ck = CertifiedKey::from_reader(KeyType::SHA256_OF_RSA, &mut r)?;
751 assert_eq!(ck.as_bytes(), &b[..32]);
752 assert_eq!(ck.key_type(), KeyType::SHA256_OF_RSA);
753 assert_eq!(r.remaining(), 7);
754
755 let mut r = Reader::from_slice(&b);
756 let ck = CertifiedKey::from_reader(42.into(), &mut r)?;
757 assert_eq!(ck.as_bytes(), &b[..32]);
758 assert_eq!(ck.key_type(), 42.into());
759 assert_eq!(r.remaining(), 7);
760
761 Ok(())
762 }
763
764 #[test]
765 fn expiry_hours_ceil() {
766 use std::time::{Duration, SystemTime};
767
768 let now = SystemTime::get();
769 let mut exp = now + Duration::from_secs(24 * 60 * 60);
770 for _ in 0..=3600 {
771 let eh = ExpiryHours::try_from_systemtime_ceil(exp).unwrap();
772 assert!(SystemTime::from(eh) >= exp);
773 assert!(SystemTime::from(eh) < exp + Duration::from_secs(SEC_PER_HOUR));
774
775 exp += Duration::from_secs(1);
776 }
777 }
778}