Skip to main content

tor_cert/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3// @@ begin lint list maintained by maint/add_warning @@
4#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6#![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)] // See arti#2556
15#![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)] // This can reasonably be done for explicitness
40#![allow(clippy::uninlined_format_args)]
41#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44#![allow(clippy::needless_lifetimes)] // See arti#1765
45#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46#![allow(clippy::collapsible_if)] // See arti#2342
47#![deny(clippy::unused_async)]
48#![deny(clippy::string_slice)] // See arti#2571
49//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
50
51// TODO: add to the list maintained by maint/add_warning once it's available on all crates
52#![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
74/// A Result defined to use CertError
75type CertResult<T> = std::result::Result<T, CertError>;
76
77caret_int! {
78    /// Recognized values for Tor's certificate type field.
79    ///
80    /// In the names used here, "X_V_Y" means "key X verifying key Y",
81    /// whereas "X_CC_Y" means "key X cross-certifying key Y".  In both
82    /// cases, X is the key that is doing the signing, and Y is the key
83    /// or object that is getting signed.
84    ///
85    /// Not every one of these types is valid for an Ed25519
86    /// certificate.  Some are for X.509 certs in a CERTS cell; some
87    /// are for RSA->Ed crosscerts in a CERTS cell.
88    pub struct CertType(u8) {
89        /// TLS link key, signed with RSA identity. X.509 format. (Obsolete)
90        TLS_LINK_X509 = 0x01,
91        /// Self-signed RSA identity certificate. X.509 format. (Legacy)
92        RSA_ID_X509 = 0x02,
93        /// RSA lnk authentication key signed with RSA identity
94        /// key. X.509 format. (Obsolete)
95        LINK_AUTH_X509 = 0x03,
96
97        /// Identity verifying a signing key, directly.
98        IDENTITY_V_SIGNING = 0x04,
99
100        /// Signing key verifying a TLS certificate by digest.
101        SIGNING_V_TLS_CERT = 0x05,
102
103        /// Signing key verifying a link authentication key.
104        SIGNING_V_LINK_AUTH = 0x06,
105
106        /// RSA identity key certifying an Ed25519 identity key. RSA
107        /// crosscert format. (Legacy)
108        RSA_ID_V_IDENTITY = 0x07,
109
110        /// For onion services: short-term descriptor signing key
111        /// (`KP_hs_desc_sign`), signed with blinded onion service identity
112        /// (`KP_hs_blind_id`).
113        HS_BLINDED_ID_V_SIGNING = 0x08,
114
115        /// For onion services: Introduction point authentication key
116        /// (`KP_hs_ipt_sid`), signed with short term descriptor signing key
117        /// (`KP_hs_desc_sign`).
118        ///
119        /// This one is, sadly, a bit complicated. In the original specification
120        /// it was meant to be a cross-certificate, where the signature would be
121        /// _on_ the descriptor signing key, _signed with_ the intro TID key.
122        /// But we got it backwards in the C Tor implementation, and now, for
123        /// compatibility, we are stuck doing it backwards in the future.
124        ///
125        /// If we find in the future that it is actually important to
126        /// cross-certify these keys (as originally intended), then we should
127        /// add a new certificate type, and put the new certificate in the onion
128        /// service descriptor.
129        HS_IP_V_SIGNING = 0x09,
130
131        /// An ntor key converted to a ed25519 key, cross-certifying an
132        /// identity key.
133        NTOR_CC_IDENTITY = 0x0A,
134
135        /// For onion services: Ntor encryption key (`KP_hss_ntor`),
136        /// converted to ed25519, signed with the descriptor signing key
137        /// (`KP_hs_desc_sign`).
138        ///
139        /// As with [`HS_IP_V_SIGNING`](CertType::HS_IP_V_SIGNING), this
140        /// certificate type is backwards.  In the original specification it was
141        /// meant to be a cross certificate, with the signing and signed keys
142        /// reversed.
143        HS_IP_CC_SIGNING = 0x0B,
144
145        /// For relays: family key certifying membership of a relay
146        /// by signing its identity.
147        FAMILY_V_IDENTITY = 0x0C,
148    }
149}
150
151caret_int! {
152    /// Extension identifiers for extensions in certificates.
153    pub struct ExtType(u8) {
154        /// Extension indicating an Ed25519 key that signed this certificate.
155        ///
156        /// Certificates do not always contain the key that signed them.
157        SIGNED_WITH_ED25519_KEY = 0x04,
158    }
159}
160
161caret_int! {
162    /// Identifiers for the type of key or object getting signed.
163    pub struct KeyType(u8) {
164        /// Identifier for an Ed25519 key.
165        ED25519_KEY = 0x01,
166        /// Identifier for the SHA256 of an DER-encoded RSA key.
167        SHA256_OF_RSA = 0x02,
168        /// Identifies the SHA256 of an X.509 certificate.
169        SHA256_OF_X509 = 0x03,
170    }
171}
172
173/// Structure for an Ed25519-signed certificate as described in Tor's
174/// cert-spec.txt.
175#[derive(Debug, Clone, PartialEq, Eq, derive_builder::Builder)]
176#[builder(build_fn(skip))]
177pub struct Ed25519Cert {
178    /// How many _hours_ after the epoch will this certificate expire?
179    #[builder(setter(custom))]
180    exp_hours: ExpiryHours,
181    /// Type of the certificate; recognized values are in certtype::*
182    cert_type: CertType,
183    /// The key or object being certified.
184    cert_key: CertifiedKey,
185    /// A list of extensions.
186    #[allow(unused)] // TODO review CertExt and make it pub, and add a getter
187    #[builder(setter(custom))]
188    extensions: Vec<CertExt>,
189    /// The key that signed this cert.
190    ///
191    /// Once the cert has been unwrapped from an KeyUnknownCert, this field will
192    /// be set.  If there is a `SignedWithEd25519` extension in
193    /// `self.extensions`, this will match it.
194    #[builder(setter(custom))]
195    signed_with: Option<ed25519::Ed25519Identity>,
196}
197
198/// One of the data types that can be certified by an Ed25519Cert.
199#[derive(Debug, Clone, PartialEq, Eq, derive_more::From)]
200#[non_exhaustive]
201pub enum CertifiedKey {
202    /// An Ed25519 public key, signed directly.
203    Ed25519(ed25519::Ed25519Identity),
204    /// The SHA256 digest of a DER-encoded RsaPublicKey
205    #[from(skip)]
206    RsaSha256Digest([u8; 32]),
207    /// The SHA256 digest of an X.509 certificate.
208    #[from(skip)]
209    X509Sha256Digest([u8; 32]),
210    /// Some unrecognized key type.
211    #[from(skip)]
212    Unrecognized(UnrecognizedKey),
213}
214
215/// A key whose type we didn't recognize.
216#[derive(Debug, Clone, PartialEq, Eq)]
217pub struct UnrecognizedKey {
218    /// Actual type of the key.
219    key_type: KeyType,
220    /// digest of the key, or the key itself.
221    key_digest: [u8; 32],
222}
223
224impl CertifiedKey {
225    /// Return the byte that identifies the type of this key.
226    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    /// Return the bytes that are used for the body of this certified
236    /// key or object.
237    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    /// If this is an Ed25519 public key, return Some(key).
246    /// Otherwise, return None.
247    pub fn as_ed25519(&self) -> Option<&ed25519::Ed25519Identity> {
248        match self {
249            CertifiedKey::Ed25519(k) => Some(k),
250            _ => None,
251        }
252    }
253    /// Try to extract a CertifiedKey from a Reader, given that we have
254    /// already read its type as `key_type`.
255    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/// An extension in a Tor certificate.
269#[derive(Debug, Clone, PartialEq, Eq)]
270enum CertExt {
271    /// Indicates which Ed25519 public key signed this cert.
272    SignedWithEd25519(SignedWithEd25519Ext),
273    /// An extension whose identity we don't recognize.
274    Unrecognized(UnrecognizedExt),
275}
276
277/// Any unrecognized extension on a Tor certificate.
278#[derive(Debug, Clone, PartialEq, Eq)]
279#[allow(unused)]
280struct UnrecognizedExt {
281    /// True iff this extension must be understand in order to validate the
282    /// certificate.
283    affects_validation: bool,
284    /// The type of the extension
285    ext_type: ExtType,
286    /// The body of the extension.
287    body: Vec<u8>,
288}
289
290impl CertExt {
291    /// Return the identifier code for this Extension.
292    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/// Extension indicating that a key that signed a given certificate.
301#[derive(Debug, Clone, PartialEq, Eq)]
302struct SignedWithEd25519Ext {
303    /// The key that signed the certificate including this extension.
304    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    /// Try to decode a certificate from a byte slice.
352    ///
353    /// This function returns an error if the byte slice is not
354    /// completely exhausted.
355    ///
356    /// Note that the resulting KeyUnknownCertificate is not checked
357    /// for validity at all: you will need to provide it with an expected
358    /// signing key, then check it for timeliness and well-signedness.
359    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            // This would be something other than a "v1" certificate. We don't
364            // understand those.
365            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        // This is a workaround for a tor bug: the key type is
374        // wrong. It was fixed in tor#40124, which got merged into Tor
375        // 0.4.5.x and later.
376        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        // See comment in `impl Writeable for UncheckedCert`.
392
393        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    /// Return the time at which this certificate becomes expired
419    pub fn expiry(&self) -> std::time::SystemTime {
420        self.exp_hours.into()
421    }
422
423    /// Return true iff this certificate will be expired at the time `when`.
424    ///
425    /// This is inclusive, meaning that `when == self.expiry()` is still valid.
426    pub fn is_expired_at(&self, when: std::time::SystemTime) -> bool {
427        when > self.expiry()
428    }
429
430    /// Return the signed key or object that is authenticated by this
431    /// certificate.
432    pub fn subject_key(&self) -> &CertifiedKey {
433        &self.cert_key
434    }
435
436    /// Return the ed25519 key that signed this certificate.
437    pub fn signing_key(&self) -> Option<&ed25519::Ed25519Identity> {
438        self.signed_with.as_ref()
439    }
440
441    /// Return the type of this certificate.
442    pub fn cert_type(&self) -> CertType {
443        self.cert_type
444    }
445}
446
447/// A parsed Ed25519 certificate. Maybe it includes its signing key;
448/// maybe it doesn't.
449///
450/// To validate this cert, either it must contain its signing key,
451/// or the caller must know the signing key.  In the first case, call
452/// [`should_have_signing_key`](KeyUnknownCert::should_have_signing_key);
453/// in the latter, call
454/// [`should_be_signed_with`](KeyUnknownCert::should_be_signed_with).
455#[derive(Clone, Debug, PartialEq, Eq)]
456pub struct KeyUnknownCert {
457    /// The certificate whose signing key might not be known.
458    cert: UncheckedCert,
459}
460
461impl KeyUnknownCert {
462    /// Return the certificate type of the underling cert.
463    pub fn peek_cert_type(&self) -> CertType {
464        self.cert.cert.cert_type
465    }
466    /// Return subject key of the underlying cert.
467    pub fn peek_subject_key(&self) -> &CertifiedKey {
468        &self.cert.cert.cert_key
469    }
470
471    /// Check whether a given pkey is (or might be) a key that has correctly
472    /// signed this certificate.
473    ///
474    /// If pkey is None, this certificate must contain its signing key.
475    ///
476    /// On success, we can check whether the certificate is well-signed;
477    /// otherwise, we can't check the certificate.
478    #[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    /// Declare that this should be a self-contained certificate that contains its own
490    /// signing key.
491    ///
492    /// On success, this certificate did indeed turn out to be self-contained, and so
493    /// we can validate it.
494    /// On failure, this certificate was not self-contained.
495    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    /// Declare that this should be a certificate signed with a given key.
511    ///
512    /// On success, this certificate either listed the provided key, or did not
513    /// list any key: in either case, we can validate it.
514    /// On failure, this certificate claims to be signed with a different key.
515    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/// A certificate that has been parsed, but whose signature and
536/// timeliness have not been checked.
537#[derive(Debug, Clone, PartialEq, Eq)]
538pub struct UncheckedCert {
539    /// The parsed certificate, possibly modified by inserting an externally
540    /// supplied key as its signing key.
541    cert: Ed25519Cert,
542
543    /// The signed text of the certificate. (Checking ed25519 signatures
544    /// forces us to store this.
545    // TODO(nickm)  It would be better to store a hash here, but we
546    // don't have the right Ed25519 API.
547    text: Vec<u8>,
548
549    /// The alleged signature
550    signature: ed25519::Signature,
551}
552
553/// A certificate that has been parsed and signature-checked, but whose
554/// timeliness has not been checked.
555#[derive(Debug, Clone, PartialEq, Eq)]
556pub struct SigCheckedCert {
557    /// The certificate that might or might not be timely
558    cert: Ed25519Cert,
559}
560
561impl UncheckedCert {
562    /// Split this unchecked cert into a component that assumes it has
563    /// been checked, and a signature to validate.
564    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    /// Return subject key of the underlying cert.
578    pub fn peek_subject_key(&self) -> &CertifiedKey {
579        &self.cert.cert_key
580    }
581    /// Return signing key of the underlying cert.
582    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    // TODO in some sense this duplicates things in encode.rs.
592    // However, encode.rs is not useable in type-driven (derive-based) situations,
593    // because it uses entirely different types for encoding to those for decoding.
594    //
595    // Therefore, here we implement tor_bytes's encoding trait for the type which can
596    // also be decoded.  Perhaps the encode module could be abolished.
597    fn write_onto<B: Writer + ?Sized>(&self, b: &mut B) -> Result<(), tor_bytes::EncodeError> {
598        // Ed25519Cert::decode does a lot of work, which finds a lot of fields,
599        // but also `sig_offset`.  It then splits the incoming byte buffer at `sig_offset`
600        // into `text` and `signature`, insisting that there is nothing else.
601        //
602        // Therefore this is guaranteed to write precisely the input to `decode`.
603        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/// A certificate expiration time, represented in _hours_ since the unix epoch.
653#[derive(Debug, Clone, Copy, PartialEq, Eq)]
654struct ExpiryHours(u32);
655
656/// The number of seconds in an hour.
657const SEC_PER_HOUR: u64 = 3600;
658
659impl From<ExpiryHours> for time::SystemTime {
660    fn from(value: ExpiryHours) -> Self {
661        // TODO MSRV 1.91; use from_hours.
662        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    /// Return the earliest possible `ExpiryHours` that is no earlier than `expiry`.
669    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    /// Return the latest possible ExpiryHours
682    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    // @@ begin test lint list maintained by maint/add_warning @@
703    #![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)] // See arti#2571
715    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
716    use super::*;
717    use hex_literal::hex;
718    use web_time_compat::SystemTimeExt;
719
720    #[test]
721    fn parse_unrecognized_ext() -> BytesResult<()> {
722        // case one: a flag is set but we don't know it
723        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        // case two: we've been told to ignore the cert if we can't
731        // handle the extension.
732        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}