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)] #![warn(unnameable_types)]
53
54mod err;
55pub mod rsa;
56
57#[cfg(feature = "x509")]
58pub use tor_cert_x509 as x509;
59
60use caret::caret_int;
61use tor_bytes::{Error as BytesError, Result as BytesResult};
62use tor_bytes::{Readable, Reader, Writeable, Writer};
63use tor_checkable::{TimeRange, TimeRangeBound};
64use tor_llcrypto::pk::*;
65
66use web_time_compat as time;
67
68pub use err::CertError;
69
70mod encode;
71pub use encode::{EncodedCert, EncodedEd25519Cert};
72pub use err::CertEncodeError;
73
74type CertResult<T> = std::result::Result<T, CertError>;
76
77caret_int! {
78 pub struct CertType(u8) {
89 TLS_LINK_X509 = 0x01,
91 RSA_ID_X509 = 0x02,
93 LINK_AUTH_X509 = 0x03,
96
97 IDENTITY_V_SIGNING = 0x04,
99
100 SIGNING_V_TLS_CERT = 0x05,
102
103 SIGNING_V_LINK_AUTH = 0x06,
105
106 RSA_ID_V_IDENTITY = 0x07,
109
110 HS_BLINDED_ID_V_SIGNING = 0x08,
114
115 HS_IP_V_SIGNING = 0x09,
130
131 NTOR_CC_IDENTITY = 0x0A,
134
135 HS_IP_CC_SIGNING = 0x0B,
144
145 FAMILY_V_IDENTITY = 0x0C,
148 }
149}
150
151caret_int! {
152 pub struct ExtType(u8) {
154 SIGNED_WITH_ED25519_KEY = 0x04,
158 }
159}
160
161caret_int! {
162 pub struct KeyType(u8) {
164 ED25519_KEY = 0x01,
166 SHA256_OF_RSA = 0x02,
168 SHA256_OF_X509 = 0x03,
170 }
171}
172
173#[derive(Debug, Clone, PartialEq, Eq, derive_builder::Builder)]
176#[builder(build_fn(skip))]
177pub struct Ed25519Cert {
178 #[builder(setter(custom))]
180 exp_hours: ExpiryHours,
181 cert_type: CertType,
183 cert_key: CertifiedKey,
185 #[allow(unused)] #[builder(setter(custom))]
188 extensions: Vec<CertExt>,
189 #[builder(setter(custom))]
195 signed_with: Option<ed25519::Ed25519Identity>,
196}
197
198#[derive(Debug, Clone, PartialEq, Eq, derive_more::From)]
200#[non_exhaustive]
201pub enum CertifiedKey {
202 Ed25519(ed25519::Ed25519Identity),
204 #[from(skip)]
206 RsaSha256Digest([u8; 32]),
207 #[from(skip)]
209 X509Sha256Digest([u8; 32]),
210 #[from(skip)]
212 Unrecognized(UnrecognizedKey),
213}
214
215#[derive(Debug, Clone, PartialEq, Eq)]
217pub struct UnrecognizedKey {
218 key_type: KeyType,
220 key_digest: [u8; 32],
222}
223
224impl CertifiedKey {
225 pub fn key_type(&self) -> KeyType {
227 match self {
228 CertifiedKey::Ed25519(_) => KeyType::ED25519_KEY,
229 CertifiedKey::RsaSha256Digest(_) => KeyType::SHA256_OF_RSA,
230 CertifiedKey::X509Sha256Digest(_) => KeyType::SHA256_OF_X509,
231
232 CertifiedKey::Unrecognized(u) => u.key_type,
233 }
234 }
235 pub fn as_bytes(&self) -> &[u8] {
238 match self {
239 CertifiedKey::Ed25519(k) => k.as_bytes(),
240 CertifiedKey::RsaSha256Digest(k) => &k[..],
241 CertifiedKey::X509Sha256Digest(k) => &k[..],
242 CertifiedKey::Unrecognized(u) => &u.key_digest[..],
243 }
244 }
245 pub fn as_ed25519(&self) -> Option<&ed25519::Ed25519Identity> {
248 match self {
249 CertifiedKey::Ed25519(k) => Some(k),
250 _ => None,
251 }
252 }
253 fn from_reader(key_type: KeyType, r: &mut Reader<'_>) -> BytesResult<Self> {
256 Ok(match key_type {
257 KeyType::ED25519_KEY => CertifiedKey::Ed25519(r.extract()?),
258 KeyType::SHA256_OF_RSA => CertifiedKey::RsaSha256Digest(r.extract()?),
259 KeyType::SHA256_OF_X509 => CertifiedKey::X509Sha256Digest(r.extract()?),
260 _ => CertifiedKey::Unrecognized(UnrecognizedKey {
261 key_type,
262 key_digest: r.extract()?,
263 }),
264 })
265 }
266}
267
268#[derive(Debug, Clone, PartialEq, Eq)]
270enum CertExt {
271 SignedWithEd25519(SignedWithEd25519Ext),
273 Unrecognized(UnrecognizedExt),
275}
276
277#[derive(Debug, Clone, PartialEq, Eq)]
279#[allow(unused)]
280struct UnrecognizedExt {
281 affects_validation: bool,
284 ext_type: ExtType,
286 body: Vec<u8>,
288}
289
290impl CertExt {
291 fn ext_id(&self) -> ExtType {
293 match self {
294 CertExt::SignedWithEd25519(_) => ExtType::SIGNED_WITH_ED25519_KEY,
295 CertExt::Unrecognized(u) => u.ext_type,
296 }
297 }
298}
299
300#[derive(Debug, Clone, PartialEq, Eq)]
302struct SignedWithEd25519Ext {
303 pk: ed25519::Ed25519Identity,
305}
306
307impl Readable for CertExt {
308 fn take_from(b: &mut Reader<'_>) -> BytesResult<Self> {
309 let len = b.take_u16()?;
310 let ext_type: ExtType = b.take_u8()?.into();
311 let flags = b.take_u8()?;
312 let body = b.take(len as usize)?;
313
314 Ok(match ext_type {
315 ExtType::SIGNED_WITH_ED25519_KEY => CertExt::SignedWithEd25519(SignedWithEd25519Ext {
316 pk: ed25519::Ed25519Identity::from_bytes(body).ok_or_else(|| {
317 BytesError::InvalidMessage("wrong length on Ed25519 key".into())
318 })?,
319 }),
320 _ => {
321 if (flags & 1) != 0 {
322 return Err(BytesError::InvalidMessage(
323 "unrecognized certificate extension, with 'affects_validation' flag set."
324 .into(),
325 ));
326 }
327 CertExt::Unrecognized(UnrecognizedExt {
328 affects_validation: false,
329 ext_type,
330 body: body.into(),
331 })
332 }
333 })
334 }
335}
336
337impl Writeable for KeyUnknownCert {
338 fn write_onto<B: Writer + ?Sized>(&self, b: &mut B) -> Result<(), tor_bytes::EncodeError> {
339 self.cert.write_onto(b)
340 }
341}
342
343impl Readable for KeyUnknownCert {
344 fn take_from(r: &mut Reader<'_>) -> BytesResult<KeyUnknownCert> {
345 let b = r.take_rest();
346 Ed25519Cert::decode(b)
347 }
348}
349
350impl Ed25519Cert {
351 pub fn decode(cert: &[u8]) -> BytesResult<KeyUnknownCert> {
360 let mut r = Reader::from_slice(cert);
361 let v = r.take_u8()?;
362 if v != 1 {
363 return Err(BytesError::InvalidMessage(
366 "Unrecognized certificate version".into(),
367 ));
368 }
369 let cert_type = r.take_u8()?.into();
370 let exp_hours = r.extract()?;
371 let mut cert_key_type = r.take_u8()?.into();
372
373 if cert_type == CertType::SIGNING_V_TLS_CERT && cert_key_type == KeyType::ED25519_KEY {
377 cert_key_type = KeyType::SHA256_OF_X509;
378 }
379
380 let cert_key = CertifiedKey::from_reader(cert_key_type, &mut r)?;
381 let n_exts = r.take_u8()?;
382 let mut extensions = Vec::new();
383 for _ in 0..n_exts {
384 let e: CertExt = r.extract()?;
385 extensions.push(e);
386 }
387
388 let sig_offset = r.consumed();
389 let signature: ed25519::Signature = r.extract()?;
390 r.should_be_exhausted()?;
391 let keyext = extensions
394 .iter()
395 .find(|e| e.ext_id() == ExtType::SIGNED_WITH_ED25519_KEY);
396
397 let included_pkey = match keyext {
398 Some(CertExt::SignedWithEd25519(s)) => Some(s.pk),
399 _ => None,
400 };
401
402 Ok(KeyUnknownCert {
403 cert: UncheckedCert {
404 cert: Ed25519Cert {
405 exp_hours,
406 cert_type,
407 cert_key,
408 extensions,
409
410 signed_with: included_pkey,
411 },
412 text: cert[0..sig_offset].into(),
413 signature,
414 },
415 })
416 }
417
418 pub fn expiry(&self) -> std::time::SystemTime {
420 self.exp_hours.into()
421 }
422
423 pub fn is_expired_at(&self, when: std::time::SystemTime) -> bool {
427 when > self.expiry()
428 }
429
430 pub fn subject_key(&self) -> &CertifiedKey {
433 &self.cert_key
434 }
435
436 pub fn signing_key(&self) -> Option<&ed25519::Ed25519Identity> {
438 self.signed_with.as_ref()
439 }
440
441 pub fn cert_type(&self) -> CertType {
443 self.cert_type
444 }
445}
446
447#[derive(Clone, Debug, PartialEq, Eq)]
456pub struct KeyUnknownCert {
457 cert: UncheckedCert,
459}
460
461impl KeyUnknownCert {
462 pub fn peek_cert_type(&self) -> CertType {
464 self.cert.cert.cert_type
465 }
466 pub fn peek_subject_key(&self) -> &CertifiedKey {
468 &self.cert.cert.cert_key
469 }
470
471 #[deprecated(
479 since = "0.7.1",
480 note = "Use should_have_signing_key or should_be_signed_with instead."
481 )]
482 pub fn check_key(self, pkey: Option<&ed25519::Ed25519Identity>) -> CertResult<UncheckedCert> {
483 match pkey {
484 Some(wanted) => self.should_be_signed_with(wanted),
485 None => self.should_have_signing_key(),
486 }
487 }
488
489 pub fn should_have_signing_key(self) -> CertResult<UncheckedCert> {
496 let real_key = match &self.cert.cert.signed_with {
497 Some(a) => *a,
498 None => return Err(CertError::MissingPubKey),
499 };
500
501 Ok(UncheckedCert {
502 cert: Ed25519Cert {
503 signed_with: Some(real_key),
504 ..self.cert.cert
505 },
506 ..self.cert
507 })
508 }
509
510 pub fn should_be_signed_with(
516 self,
517 pkey: &ed25519::Ed25519Identity,
518 ) -> CertResult<UncheckedCert> {
519 let real_key = match &self.cert.cert.signed_with {
520 Some(a) if a == pkey => *pkey,
521 None => *pkey,
522 Some(_) => return Err(CertError::KeyMismatch),
523 };
524
525 Ok(UncheckedCert {
526 cert: Ed25519Cert {
527 signed_with: Some(real_key),
528 ..self.cert.cert
529 },
530 ..self.cert
531 })
532 }
533}
534
535#[derive(Debug, Clone, PartialEq, Eq)]
538pub struct UncheckedCert {
539 cert: Ed25519Cert,
542
543 text: Vec<u8>,
548
549 signature: ed25519::Signature,
551}
552
553#[derive(Debug, Clone, PartialEq, Eq)]
556pub struct SigCheckedCert {
557 cert: Ed25519Cert,
559}
560
561impl UncheckedCert {
562 pub fn dangerously_split(
565 self,
566 ) -> CertResult<(SigCheckedCert, ed25519::ValidatableEd25519Signature)> {
567 use tor_checkable::SelfSigned;
568 let signing_key = self.cert.signed_with.ok_or(CertError::MissingPubKey)?;
569 let signing_key = signing_key
570 .try_into()
571 .map_err(|_| CertError::BadSignature)?;
572 let signature =
573 ed25519::ValidatableEd25519Signature::new(signing_key, self.signature, &self.text[..]);
574 Ok((self.dangerously_assume_wellsigned(), signature))
575 }
576
577 pub fn peek_subject_key(&self) -> &CertifiedKey {
579 &self.cert.cert_key
580 }
581 pub fn peek_signing_key(&self) -> &ed25519::Ed25519Identity {
583 self.cert
584 .signed_with
585 .as_ref()
586 .expect("Made an UncheckedCert without a signing key")
587 }
588}
589
590impl Writeable for UncheckedCert {
591 fn write_onto<B: Writer + ?Sized>(&self, b: &mut B) -> Result<(), tor_bytes::EncodeError> {
598 self.text.write_onto(b)?;
604 self.signature.write_onto(b)?;
605 Ok(())
606 }
607}
608
609impl tor_checkable::SelfSigned<SigCheckedCert> for UncheckedCert {
610 type Error = CertError;
611
612 fn is_well_signed(&self) -> CertResult<()> {
613 let pubkey = &self.cert.signed_with.ok_or(CertError::MissingPubKey)?;
614 let pubkey: ed25519::PublicKey = pubkey.try_into().map_err(|_| CertError::BadSignature)?;
615
616 pubkey
617 .verify(&self.text[..], &self.signature)
618 .map_err(|_| CertError::BadSignature)?;
619
620 Ok(())
621 }
622
623 fn dangerously_assume_wellsigned(self) -> SigCheckedCert {
624 SigCheckedCert { cert: self.cert }
625 }
626}
627
628impl tor_checkable::TimeBound for Ed25519Cert {
629 type Inner = Ed25519Cert;
630
631 fn bounds(&self) -> TimeRange {
632 TimeRangeBound::new((), ..=self.expiry())
633 }
634
635 fn dangerously_assume_timely(self) -> Ed25519Cert {
636 self
637 }
638}
639
640impl tor_checkable::TimeBound for SigCheckedCert {
641 type Inner = Ed25519Cert;
642
643 fn bounds(&self) -> TimeRange {
644 self.cert.bounds()
645 }
646
647 fn dangerously_assume_timely(self) -> Ed25519Cert {
648 self.cert.dangerously_assume_timely()
649 }
650}
651
652#[derive(Debug, Clone, Copy, PartialEq, Eq)]
654struct ExpiryHours(u32);
655
656const SEC_PER_HOUR: u64 = 3600;
658
659impl From<ExpiryHours> for time::SystemTime {
660 fn from(value: ExpiryHours) -> Self {
661 let d = std::time::Duration::from_secs(u64::from(value.0) * SEC_PER_HOUR);
663 std::time::SystemTime::UNIX_EPOCH + d
664 }
665}
666
667impl ExpiryHours {
668 fn try_from_systemtime_ceil(expiry: time::SystemTime) -> Result<Self, CertEncodeError> {
670 let d = expiry
671 .duration_since(time::SystemTime::UNIX_EPOCH)
672 .map_err(|_| CertEncodeError::InvalidExpiration)?;
673 let sec_ceil = d.as_secs() + if d.subsec_nanos() > 0 { 1 } else { 0 };
674 let hours = sec_ceil
675 .div_ceil(SEC_PER_HOUR)
676 .try_into()
677 .map_err(|_| CertEncodeError::InvalidExpiration)?;
678 Ok(ExpiryHours(hours))
679 }
680
681 const fn max() -> Self {
683 ExpiryHours(u32::MAX)
684 }
685}
686
687impl Readable for ExpiryHours {
688 fn take_from(b: &mut Reader<'_>) -> BytesResult<Self> {
689 Ok(ExpiryHours(b.take_u32()?))
690 }
691}
692
693impl tor_bytes::Writeable for ExpiryHours {
694 fn write_onto<B: tor_bytes::Writer + ?Sized>(&self, b: &mut B) -> tor_bytes::EncodeResult<()> {
695 b.write_u32(self.0);
696 Ok(())
697 }
698}
699
700#[cfg(test)]
701mod test {
702 #![allow(clippy::bool_assert_comparison)]
704 #![allow(clippy::clone_on_copy)]
705 #![allow(clippy::dbg_macro)]
706 #![allow(clippy::mixed_attributes_style)]
707 #![allow(clippy::print_stderr)]
708 #![allow(clippy::print_stdout)]
709 #![allow(clippy::single_char_pattern)]
710 #![allow(clippy::unwrap_used)]
711 #![allow(clippy::unchecked_time_subtraction)]
712 #![allow(clippy::useless_vec)]
713 #![allow(clippy::needless_pass_by_value)]
714 #![allow(clippy::string_slice)] use super::*;
717 use hex_literal::hex;
718 use web_time_compat::SystemTimeExt;
719
720 #[test]
721 fn parse_unrecognized_ext() -> BytesResult<()> {
722 let b = hex!("0009 99 10 657874656e73696f6e");
724 let mut r = Reader::from_slice(&b);
725 let e: CertExt = r.extract()?;
726 r.should_be_exhausted()?;
727
728 assert_eq!(e.ext_id(), 0x99.into());
729
730 let b = hex!("0009 99 11 657874656e73696f6e");
733 let mut r = Reader::from_slice(&b);
734 let e: Result<CertExt, BytesError> = r.extract();
735 assert!(e.is_err());
736 assert_eq!(
737 e.err().unwrap(),
738 BytesError::InvalidMessage(
739 "unrecognized certificate extension, with 'affects_validation' flag set.".into()
740 )
741 );
742
743 Ok(())
744 }
745
746 #[test]
747 fn certified_key() -> BytesResult<()> {
748 let b =
749 hex!("4c27616d6f757220756e6974206365757820717527656e636861c3ae6e616974206c6520666572");
750 let mut r = Reader::from_slice(&b);
751
752 let ck = CertifiedKey::from_reader(KeyType::SHA256_OF_RSA, &mut r)?;
753 assert_eq!(ck.as_bytes(), &b[..32]);
754 assert_eq!(ck.key_type(), KeyType::SHA256_OF_RSA);
755 assert_eq!(r.remaining(), 7);
756
757 let mut r = Reader::from_slice(&b);
758 let ck = CertifiedKey::from_reader(42.into(), &mut r)?;
759 assert_eq!(ck.as_bytes(), &b[..32]);
760 assert_eq!(ck.key_type(), 42.into());
761 assert_eq!(r.remaining(), 7);
762
763 Ok(())
764 }
765
766 #[test]
767 fn expiry_hours_ceil() {
768 use std::time::{Duration, SystemTime};
769
770 let now = SystemTime::get();
771 let mut exp = now + Duration::from_secs(24 * 60 * 60);
772 for _ in 0..=3600 {
773 let eh = ExpiryHours::try_from_systemtime_ceil(exp).unwrap();
774 assert!(SystemTime::from(eh) >= exp);
775 assert!(SystemTime::from(eh) < exp + Duration::from_secs(SEC_PER_HOUR));
776
777 exp += Duration::from_secs(1);
778 }
779 }
780}