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

            
55
mod err;
56
pub mod rsa;
57

            
58
#[cfg(feature = "x509")]
59
pub use tor_cert_x509 as x509;
60

            
61
use caret::caret_int;
62
use tor_bytes::{Error as BytesError, Result as BytesResult};
63
use tor_bytes::{Readable, Reader, Writeable, Writer};
64
use tor_checkable::{TimeRange, TimeRangeBound};
65
use tor_llcrypto::pk::*;
66

            
67
use web_time_compat as time;
68

            
69
pub use err::CertError;
70

            
71
mod encode;
72
pub use encode::{EncodedCert, EncodedEd25519Cert};
73
pub use err::CertEncodeError;
74

            
75
/// A Result defined to use CertError
76
type CertResult<T> = std::result::Result<T, CertError>;
77

            
78
caret_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

            
152
caret_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

            
162
caret_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))]
178
pub 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]
202
pub 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)]
218
pub 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

            
225
impl CertifiedKey {
226
    /// Return the byte that identifies the type of this key.
227
45573
    pub fn key_type(&self) -> KeyType {
228
45573
        match self {
229
45081
            CertifiedKey::Ed25519(_) => KeyType::ED25519_KEY,
230
211
            CertifiedKey::RsaSha256Digest(_) => KeyType::SHA256_OF_RSA,
231
280
            CertifiedKey::X509Sha256Digest(_) => KeyType::SHA256_OF_X509,
232

            
233
1
            CertifiedKey::Unrecognized(u) => u.key_type,
234
        }
235
45573
    }
236
    /// Return the bytes that are used for the body of this certified
237
    /// key or object.
238
46623
    pub fn as_bytes(&self) -> &[u8] {
239
46623
        match self {
240
45571
            CertifiedKey::Ed25519(k) => k.as_bytes(),
241
421
            CertifiedKey::RsaSha256Digest(k) => &k[..],
242
630
            CertifiedKey::X509Sha256Digest(k) => &k[..],
243
1
            CertifiedKey::Unrecognized(u) => &u.key_digest[..],
244
        }
245
46623
    }
246
    /// If this is an Ed25519 public key, return Some(key).
247
    /// Otherwise, return None.
248
53690
    pub fn as_ed25519(&self) -> Option<&ed25519::Ed25519Identity> {
249
53690
        match self {
250
53410
            CertifiedKey::Ed25519(k) => Some(k),
251
280
            _ => None,
252
        }
253
53690
    }
254
    /// Try to extract a CertifiedKey from a Reader, given that we have
255
    /// already read its type as `key_type`.
256
97023
    fn from_reader(key_type: KeyType, r: &mut Reader<'_>) -> BytesResult<Self> {
257
97023
        Ok(match key_type {
258
96321
            KeyType::ED25519_KEY => CertifiedKey::Ed25519(r.extract()?),
259
211
            KeyType::SHA256_OF_RSA => CertifiedKey::RsaSha256Digest(r.extract()?),
260
490
            KeyType::SHA256_OF_X509 => CertifiedKey::X509Sha256Digest(r.extract()?),
261
            _ => CertifiedKey::Unrecognized(UnrecognizedKey {
262
1
                key_type,
263
1
                key_digest: r.extract()?,
264
            }),
265
        })
266
97023
    }
267
}
268

            
269
/// An extension in a Tor certificate.
270
#[derive(Debug, Clone, PartialEq, Eq)]
271
enum 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)]
281
struct 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

            
291
impl CertExt {
292
    /// Return the identifier code for this Extension.
293
58031
    fn ext_id(&self) -> ExtType {
294
58031
        match self {
295
58030
            CertExt::SignedWithEd25519(_) => ExtType::SIGNED_WITH_ED25519_KEY,
296
1
            CertExt::Unrecognized(u) => u.ext_type,
297
        }
298
58031
    }
299
}
300

            
301
/// Extension indicating that a key that signed a given certificate.
302
#[derive(Debug, Clone, PartialEq, Eq)]
303
struct SignedWithEd25519Ext {
304
    /// The key that signed the certificate including this extension.
305
    pk: ed25519::Ed25519Identity,
306
}
307

            
308
impl Readable for CertExt {
309
58173
    fn take_from(b: &mut Reader<'_>) -> BytesResult<Self> {
310
58173
        let len = b.take_u16()?;
311
58173
        let ext_type: ExtType = b.take_u8()?.into();
312
58173
        let flags = b.take_u8()?;
313
58173
        let body = b.take(len as usize)?;
314

            
315
58173
        Ok(match ext_type {
316
            ExtType::SIGNED_WITH_ED25519_KEY => CertExt::SignedWithEd25519(SignedWithEd25519Ext {
317
58100
                pk: ed25519::Ed25519Identity::from_bytes(body).ok_or_else(|| {
318
70
                    BytesError::InvalidMessage("wrong length on Ed25519 key".into())
319
70
                })?,
320
            }),
321
            _ => {
322
73
                if (flags & 1) != 0 {
323
71
                    return Err(BytesError::InvalidMessage(
324
71
                        "unrecognized certificate extension, with 'affects_validation' flag set."
325
71
                            .into(),
326
71
                    ));
327
2
                }
328
2
                CertExt::Unrecognized(UnrecognizedExt {
329
2
                    affects_validation: false,
330
2
                    ext_type,
331
2
                    body: body.into(),
332
2
                })
333
            }
334
        })
335
58173
    }
336
}
337

            
338
impl Writeable for KeyUnknownCert {
339
176
    fn write_onto<B: Writer + ?Sized>(&self, b: &mut B) -> Result<(), tor_bytes::EncodeError> {
340
176
        self.cert.write_onto(b)
341
176
    }
342
}
343

            
344
impl Readable for KeyUnknownCert {
345
75460
    fn take_from(r: &mut Reader<'_>) -> BytesResult<KeyUnknownCert> {
346
75460
        let b = r.take_rest();
347
75460
        Ed25519Cert::decode(b)
348
75460
    }
349
}
350

            
351
impl 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
97231
    pub fn decode(cert: &[u8]) -> BytesResult<KeyUnknownCert> {
361
97231
        let mut r = Reader::from_slice(cert);
362
97231
        let v = r.take_u8()?;
363
97231
        if v != 1 {
364
            // This would be something other than a "v1" certificate. We don't
365
            // understand those.
366
140
            return Err(BytesError::InvalidMessage(
367
140
                "Unrecognized certificate version".into(),
368
140
            ));
369
97091
        }
370
97091
        let cert_type = r.take_u8()?.into();
371
97091
        let exp_hours = r.extract()?;
372
97021
        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
97021
        if cert_type == CertType::SIGNING_V_TLS_CERT && cert_key_type == KeyType::ED25519_KEY {
378
            cert_key_type = KeyType::SHA256_OF_X509;
379
97021
        }
380

            
381
97021
        let cert_key = CertifiedKey::from_reader(cert_key_type, &mut r)?;
382
97021
        let n_exts = r.take_u8()?;
383
97021
        let mut extensions = Vec::new();
384
97021
        for _ in 0..n_exts {
385
58170
            let e: CertExt = r.extract()?;
386
58030
            extensions.push(e);
387
        }
388

            
389
96881
        let sig_offset = r.consumed();
390
96881
        let signature: ed25519::Signature = r.extract()?;
391
96881
        r.should_be_exhausted()?;
392
        // See comment in `impl Writeable for UncheckedCert`.
393

            
394
96881
        let keyext = extensions
395
96881
            .iter()
396
58030
            .find(|e| e.ext_id() == ExtType::SIGNED_WITH_ED25519_KEY);
397

            
398
96881
        let included_pkey = match keyext {
399
58030
            Some(CertExt::SignedWithEd25519(s)) => Some(s.pk),
400
38851
            _ => None,
401
        };
402

            
403
96881
        Ok(KeyUnknownCert {
404
96881
            cert: UncheckedCert {
405
96881
                cert: Ed25519Cert {
406
96881
                    exp_hours,
407
96881
                    cert_type,
408
96881
                    cert_key,
409
96881
                    extensions,
410
96881

            
411
96881
                    signed_with: included_pkey,
412
96881
                },
413
96881
                text: cert[0..sig_offset].into(),
414
96881
                signature,
415
96881
            },
416
96881
        })
417
97231
    }
418

            
419
    /// Return the time at which this certificate becomes expired
420
86731
    pub fn expiry(&self) -> std::time::SystemTime {
421
86731
        self.exp_hours.into()
422
86731
    }
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
51521
    pub fn subject_key(&self) -> &CertifiedKey {
434
51521
        &self.cert_key
435
51521
    }
436

            
437
    /// Return the ed25519 key that signed this certificate.
438
53621
    pub fn signing_key(&self) -> Option<&ed25519::Ed25519Identity> {
439
53621
        self.signed_with.as_ref()
440
53621
    }
441

            
442
    /// Return the type of this certificate.
443
34651
    pub fn cert_type(&self) -> CertType {
444
34651
        self.cert_type
445
34651
    }
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)]
457
pub struct KeyUnknownCert {
458
    /// The certificate whose signing key might not be known.
459
    cert: UncheckedCert,
460
}
461

            
462
impl KeyUnknownCert {
463
    /// Return the certificate type of the underling cert.
464
52360
    pub fn peek_cert_type(&self) -> CertType {
465
52360
        self.cert.cert.cert_type
466
52360
    }
467
    /// Return subject key of the underlying cert.
468
34020
    pub fn peek_subject_key(&self) -> &CertifiedKey {
469
34020
        &self.cert.cert.cert_key
470
34020
    }
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
52570
    pub fn should_have_signing_key(self) -> CertResult<UncheckedCert> {
497
52570
        let real_key = match &self.cert.cert.signed_with {
498
52290
            Some(a) => *a,
499
280
            None => return Err(CertError::MissingPubKey),
500
        };
501

            
502
52290
        Ok(UncheckedCert {
503
52290
            cert: Ed25519Cert {
504
52290
                signed_with: Some(real_key),
505
52290
                ..self.cert.cert
506
52290
            },
507
52290
            ..self.cert
508
52290
        })
509
52570
    }
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
34091
    pub fn should_be_signed_with(
517
34091
        self,
518
34091
        pkey: &ed25519::Ed25519Identity,
519
34091
    ) -> CertResult<UncheckedCert> {
520
34091
        let real_key = match &self.cert.cert.signed_with {
521
490
            Some(a) if a == pkey => *pkey,
522
33601
            None => *pkey,
523
70
            Some(_) => return Err(CertError::KeyMismatch),
524
        };
525

            
526
34021
        Ok(UncheckedCert {
527
34021
            cert: Ed25519Cert {
528
34021
                signed_with: Some(real_key),
529
34021
                ..self.cert.cert
530
34021
            },
531
34021
            ..self.cert
532
34021
        })
533
34091
    }
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)]
539
pub 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)]
557
pub struct SigCheckedCert {
558
    /// The certificate that might or might not be timely
559
    cert: Ed25519Cert,
560
}
561

            
562
impl UncheckedCert {
563
    /// Split this unchecked cert into a component that assumes it has
564
    /// been checked, and a signature to validate.
565
50890
    pub fn dangerously_split(
566
50890
        self,
567
50890
    ) -> CertResult<(SigCheckedCert, ed25519::ValidatableEd25519Signature)> {
568
        use tor_checkable::SelfSigned;
569
50890
        let signing_key = self.cert.signed_with.ok_or(CertError::MissingPubKey)?;
570
50890
        let signing_key = signing_key
571
50890
            .try_into()
572
            .map_err(|_| CertError::BadSignature)?;
573
        let signature =
574
50890
            ed25519::ValidatableEd25519Signature::new(signing_key, self.signature, &self.text[..]);
575
50890
        Ok((self.dangerously_assume_wellsigned(), signature))
576
50890
    }
577

            
578
    /// Return subject key of the underlying cert.
579
2520
    pub fn peek_subject_key(&self) -> &CertifiedKey {
580
2520
        &self.cert.cert_key
581
2520
    }
582
    /// Return signing key of the underlying cert.
583
1050
    pub fn peek_signing_key(&self) -> &ed25519::Ed25519Identity {
584
1050
        self.cert
585
1050
            .signed_with
586
1050
            .as_ref()
587
1050
            .expect("Made an UncheckedCert without a signing key")
588
1050
    }
589
}
590

            
591
impl 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
176
    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
176
        self.text.write_onto(b)?;
605
176
        self.signature.write_onto(b)?;
606
176
        Ok(())
607
176
    }
608
}
609

            
610
impl tor_checkable::SelfSigned<SigCheckedCert> for UncheckedCert {
611
    type Error = CertError;
612

            
613
34721
    fn is_well_signed(&self) -> CertResult<()> {
614
34721
        let pubkey = &self.cert.signed_with.ok_or(CertError::MissingPubKey)?;
615
34721
        let pubkey: ed25519::PublicKey = pubkey.try_into().map_err(|_| CertError::BadSignature)?;
616

            
617
34721
        pubkey
618
34721
            .verify(&self.text[..], &self.signature)
619
            .map_err(|_| CertError::BadSignature)?;
620

            
621
34721
        Ok(())
622
34721
    }
623

            
624
85681
    fn dangerously_assume_wellsigned(self) -> SigCheckedCert {
625
85681
        SigCheckedCert { cert: self.cert }
626
85681
    }
627
}
628

            
629
impl tor_checkable::TimeBound for Ed25519Cert {
630
    type Inner = Ed25519Cert;
631

            
632
1681
    fn bounds(&self) -> TimeRange {
633
1681
        TimeRangeBound::new((), ..=self.expiry())
634
1681
    }
635

            
636
85611
    fn dangerously_assume_timely(self) -> Ed25519Cert {
637
85611
        self
638
85611
    }
639
}
640

            
641
impl tor_checkable::TimeBound for SigCheckedCert {
642
    type Inner = Ed25519Cert;
643

            
644
1681
    fn bounds(&self) -> TimeRange {
645
1681
        self.cert.bounds()
646
1681
    }
647

            
648
85611
    fn dangerously_assume_timely(self) -> Ed25519Cert {
649
85611
        self.cert.dangerously_assume_timely()
650
85611
    }
651
}
652

            
653
/// A certificate expiration time, represented in _hours_ since the unix epoch.
654
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
655
struct ExpiryHours(u32);
656

            
657
/// The number of seconds in an hour.
658
const SEC_PER_HOUR: u64 = 3600;
659

            
660
impl From<ExpiryHours> for time::SystemTime {
661
94495
    fn from(value: ExpiryHours) -> Self {
662
        // TODO MSRV 1.91; use from_hours.
663
94495
        let d = std::time::Duration::from_secs(u64::from(value.0) * SEC_PER_HOUR);
664
94495
        std::time::SystemTime::UNIX_EPOCH + d
665
94495
    }
666
}
667

            
668
impl ExpiryHours {
669
    /// Return the earliest possible `ExpiryHours` that is no earlier than `expiry`.
670
49243
    fn try_from_systemtime_ceil(expiry: time::SystemTime) -> Result<Self, CertEncodeError> {
671
49243
        let d = expiry
672
49243
            .duration_since(time::SystemTime::UNIX_EPOCH)
673
            .map_err(|_| CertEncodeError::InvalidExpiration)?;
674
49243
        let sec_ceil = d.as_secs() + if d.subsec_nanos() > 0 { 1 } else { 0 };
675
49243
        let hours = sec_ceil
676
49243
            .div_ceil(SEC_PER_HOUR)
677
49243
            .try_into()
678
            .map_err(|_| CertEncodeError::InvalidExpiration)?;
679
49243
        Ok(ExpiryHours(hours))
680
49243
    }
681

            
682
    /// Return the latest possible ExpiryHours
683
    const fn max() -> Self {
684
        ExpiryHours(u32::MAX)
685
    }
686
}
687

            
688
impl Readable for ExpiryHours {
689
97722
    fn take_from(b: &mut Reader<'_>) -> BytesResult<Self> {
690
97722
        Ok(ExpiryHours(b.take_u32()?))
691
97722
    }
692
}
693

            
694
impl tor_bytes::Writeable for ExpiryHours {
695
45642
    fn write_onto<B: tor_bytes::Writer + ?Sized>(&self, b: &mut B) -> tor_bytes::EncodeResult<()> {
696
45642
        b.write_u32(self.0);
697
45642
        Ok(())
698
45642
    }
699
}
700

            
701
#[cfg(test)]
702
mod 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
}