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