1
//! Parsing implementation for Tor authority certificates
2
//!
3
//! An "authority certificate" is a short signed document that binds a
4
//! directory authority's permanent "identity key" to its medium-term
5
//! "signing key".  Using separate keys here enables the authorities
6
//! to keep their identity keys securely offline, while using the
7
//! signing keys to sign votes and consensuses.
8

            
9
use crate::batching_split_before::IteratorExt as _;
10
use crate::encode::{
11
    Bug, ItemArgument, ItemEncoder, ItemObjectEncodable, NetdocEncodable, NetdocEncoder,
12
};
13
use crate::parse::keyword::Keyword;
14
use crate::parse::parser::{Section, SectionRules};
15
use crate::parse::tokenize::{ItemResult, NetDocReader};
16
use crate::parse2::{
17
    self, ArgumentError, ArgumentStream, ItemArgumentParseable, ItemObjectParseable,
18
    NetdocParseableUnverified as _, sig_hashes::Sha1WholeKeywordLine,
19
};
20
use crate::types::misc::{Fingerprint, Iso8601TimeSp, RsaPublicParse1Helper, RsaSha1Signature};
21
use crate::util::str::Extent;
22
use crate::{NetdocErrorKind as EK, NormalItemArgument, Result};
23

            
24
use tor_basic_utils::impl_debug_hex;
25
use tor_checkable::{
26
    TimeBound, signed,
27
    timed::{self, TimeRangeBound},
28
};
29
use tor_error::{internal, into_internal};
30
use tor_llcrypto::pk::rsa;
31
use tor_llcrypto::{d, pk, pk::rsa::RsaIdentity};
32

            
33
use std::sync::LazyLock;
34

            
35
use std::result::Result as StdResult;
36
use std::{net, time, time::SystemTime};
37

            
38
use derive_deftly::Deftly;
39
use digest::Digest;
40

            
41
#[cfg(feature = "build_docs")]
42
mod build;
43

            
44
#[cfg(feature = "build_docs")]
45
#[allow(deprecated)]
46
pub use build::AuthCertBuilder;
47

            
48
mod encoded;
49
pub use encoded::EncodedAuthCert;
50

            
51
decl_keyword! {
52
    pub(crate) AuthCertKwd {
53
        "dir-key-certificate-version" => DIR_KEY_CERTIFICATE_VERSION,
54
        "dir-address" => DIR_ADDRESS,
55
        "fingerprint" => FINGERPRINT,
56
        "dir-identity-key" => DIR_IDENTITY_KEY,
57
        "dir-key-published" => DIR_KEY_PUBLISHED,
58
        "dir-key-expires" => DIR_KEY_EXPIRES,
59
        "dir-signing-key" => DIR_SIGNING_KEY,
60
        "dir-key-crosscert" => DIR_KEY_CROSSCERT,
61
        "dir-key-certification" => DIR_KEY_CERTIFICATION,
62
    }
63
}
64

            
65
/// Rules about entries that must appear in an AuthCert, and how they must
66
/// be formed.
67
1
static AUTHCERT_RULES: LazyLock<SectionRules<AuthCertKwd>> = LazyLock::new(|| {
68
    use AuthCertKwd::*;
69

            
70
1
    let mut rules = SectionRules::builder();
71
1
    rules.add(DIR_KEY_CERTIFICATE_VERSION.rule().required().args(1..));
72
1
    rules.add(DIR_ADDRESS.rule().args(1..));
73
1
    rules.add(FINGERPRINT.rule().required().args(1..));
74
1
    rules.add(DIR_IDENTITY_KEY.rule().required().no_args().obj_required());
75
1
    rules.add(DIR_SIGNING_KEY.rule().required().no_args().obj_required());
76
1
    rules.add(DIR_KEY_PUBLISHED.rule().required());
77
1
    rules.add(DIR_KEY_EXPIRES.rule().required());
78
1
    rules.add(DIR_KEY_CROSSCERT.rule().required().no_args().obj_required());
79
1
    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
80
1
    rules.add(
81
1
        DIR_KEY_CERTIFICATION
82
1
            .rule()
83
1
            .required()
84
1
            .no_args()
85
1
            .obj_required(),
86
1
    );
87
1
    rules.build()
88
1
});
89

            
90
/// A single directory authority key certificate
91
///
92
/// This is the body, not including signatures.
93
///
94
/// <https://spec.torproject.org/dir-spec/creating-key-certificates.html>
95
///
96
/// To make a fresh `AuthCert`, use [`AuthCertConstructor`].
97
#[derive(Clone, Debug, Deftly)]
98
#[derive_deftly(Constructor)]
99
#[derive_deftly(NetdocParseableUnverified, NetdocEncodable)]
100
#[cfg_attr(test, derive(PartialEq, Eq))]
101
#[allow(clippy::exhaustive_structs)]
102
pub struct AuthCert {
103
    /// Intro line
104
    ///
105
    /// Currently must be version 3.
106
    ///
107
    /// <https://spec.torproject.org/dir-spec/creating-key-certificates.html#item:dir-key-certificate-version>
108
    #[deftly(constructor(default = AuthCertVersion::V3))]
109
    #[deftly(netdoc(single_arg))]
110
    pub dir_key_certificate_version: AuthCertVersion,
111

            
112
    /// An IPv4 address for this authority.
113
    #[deftly(netdoc(single_arg))]
114
    pub dir_address: Option<net::SocketAddrV4>,
115

            
116
    /// H(KP_auth_id_rsa)
117
    ///
118
    /// <https://spec.torproject.org/dir-spec/creating-key-certificates.html#item:fingerprint>
119
    #[deftly(constructor)]
120
    #[deftly(netdoc(single_arg))]
121
    pub fingerprint: Fingerprint,
122

            
123
    /// Declared time when this certificate was published
124
    ///
125
    /// <https://spec.torproject.org/dir-spec/creating-key-certificates.html#item:dir-key-published>
126
    #[deftly(constructor)]
127
    #[deftly(netdoc(single_arg))]
128
    pub dir_key_published: Iso8601TimeSp,
129

            
130
    /// Declared time when this certificate expires.
131
    ///
132
    /// <https://spec.torproject.org/dir-spec/creating-key-certificates.html#item:dir-key-expires>
133
    #[deftly(constructor)]
134
    #[deftly(netdoc(single_arg))]
135
    pub dir_key_expires: Iso8601TimeSp,
136

            
137
    /// KP_auth_id_rsa
138
    ///
139
    /// The long-term RSA identity key for this authority
140
    ///
141
    /// <https://spec.torproject.org/dir-spec/creating-key-certificates.html#item:dir-identity-key>
142
    #[deftly(constructor)]
143
    pub dir_identity_key: rsa::PublicKey,
144

            
145
    /// KP_auth_sign_rsa
146
    ///
147
    /// The medium-term RSA signing key for this authority
148
    ///
149
    /// <https://spec.torproject.org/dir-spec/creating-key-certificates.html#item:dir-signing-key>
150
    #[deftly(constructor)]
151
    pub dir_signing_key: rsa::PublicKey,
152

            
153
    /// SHA1(DER(KP_auth_id_rsa)) signed by KP_auth_sign_rsa
154
    ///
155
    /// <https://spec.torproject.org/dir-spec/creating-key-certificates.html#item:dir-key-crosscert>
156
    #[deftly(constructor)]
157
    pub dir_key_crosscert: CrossCert,
158

            
159
    #[doc(hidden)]
160
    #[deftly(netdoc(skip))]
161
    pub __non_exhaustive: (),
162
}
163

            
164
/// Represents the version of an [`AuthCert`].
165
///
166
/// Single argument.
167
///
168
/// <https://spec.torproject.org/dir-spec/creating-key-certificates.html#item:dir-key-certificate-version>
169
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, strum::EnumString, strum::Display)]
170
#[non_exhaustive]
171
pub enum AuthCertVersion {
172
    /// The current and only version understood.
173
    #[strum(serialize = "3")]
174
    V3,
175
}
176

            
177
impl NormalItemArgument for AuthCertVersion {}
178

            
179
/// A pair of key identities that identifies a certificate.
180
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
181
#[allow(clippy::exhaustive_structs)]
182
pub struct AuthCertKeyIds {
183
    /// Fingerprint of identity key
184
    pub id_fingerprint: rsa::RsaIdentity,
185
    /// Fingerprint of signing key
186
    pub sk_fingerprint: rsa::RsaIdentity,
187
}
188

            
189
/// An authority certificate whose signature and validity time we
190
/// haven't checked.
191
pub struct UncheckedAuthCert {
192
    /// Where we found this AuthCert within the string containing it.
193
    location: Option<Extent>,
194

            
195
    /// The actual unchecked certificate.
196
    c: signed::SignatureGated<timed::TimeRangeBound<AuthCert>>,
197
}
198

            
199
impl UncheckedAuthCert {
200
    /// If this AuthCert was originally parsed from `haystack`, return its
201
    /// text.
202
    ///
203
    /// TODO: This is a pretty bogus interface; there should be a
204
    /// better way to remember where to look for this thing if we want
205
    /// it without keeping the input alive forever.  We should
206
    /// refactor.
207
    pub fn within<'a>(&self, haystack: &'a str) -> Option<&'a str> {
208
        self.location
209
            .as_ref()
210
            .and_then(|ext| ext.reconstruct(haystack))
211
    }
212
}
213

            
214
impl AuthCert {
215
    /// Make an [`AuthCertBuilder`] object that can be used to
216
    /// construct authority certificates for testing.
217
    #[cfg(feature = "build_docs")]
218
    #[deprecated = "use AuthCertConstructor instead"]
219
    #[allow(deprecated)]
220
5
    pub fn builder() -> AuthCertBuilder {
221
5
        AuthCertBuilder::new()
222
5
    }
223

            
224
    /// Parse an authority certificate from a string.
225
    ///
226
    /// This function verifies the certificate's signatures, but doesn't
227
    /// check its expiration dates.
228
7
    pub fn parse(s: &str) -> Result<UncheckedAuthCert> {
229
7
        let mut reader = NetDocReader::new(s)?;
230
7
        let body = AUTHCERT_RULES.parse(&mut reader)?;
231
7
        reader.should_be_exhausted()?;
232
7
        AuthCert::from_body(&body, s).map_err(|e| e.within(s))
233
7
    }
234

            
235
    /// Return an iterator yielding authority certificates from a string.
236
4
    pub fn parse_multiple(s: &str) -> Result<impl Iterator<Item = Result<UncheckedAuthCert>> + '_> {
237
        use AuthCertKwd::*;
238
4
        let sections = NetDocReader::new(s)?
239
91
            .batching_split_before_loose(|item| item.is_ok_with_kwd(DIR_KEY_CERTIFICATE_VERSION));
240
4
        Ok(sections
241
11
            .map(|mut section| {
242
11
                let body = AUTHCERT_RULES.parse(&mut section)?;
243
10
                AuthCert::from_body(&body, s)
244
11
            })
245
11
            .map(|r| r.map_err(|e| e.within(s))))
246
4
    }
247
    /*
248
        /// Return true if this certificate is expired at a given time, or
249
        /// not yet valid at that time.
250
        pub fn is_expired_at(&self, when: time::SystemTime) -> bool {
251
            when < self.published || when > self.expires
252
        }
253
    */
254
    /// Return the signing key certified by this certificate.
255
2031
    pub fn signing_key(&self) -> &rsa::PublicKey {
256
2031
        &self.dir_signing_key
257
2031
    }
258

            
259
    /// Return an AuthCertKeyIds object describing the keys in this
260
    /// certificate.
261
5371
    pub fn key_ids(&self) -> AuthCertKeyIds {
262
5371
        AuthCertKeyIds {
263
5371
            id_fingerprint: self.fingerprint.0,
264
5371
            sk_fingerprint: self.dir_signing_key.to_rsa_identity(),
265
5371
        }
266
5371
    }
267

            
268
    /// Return an RsaIdentity for this certificate's identity key.
269
8
    pub fn id_fingerprint(&self) -> &rsa::RsaIdentity {
270
8
        &self.fingerprint
271
8
    }
272

            
273
    /// Return the time when this certificate says it was published.
274
54
    pub fn published(&self) -> time::SystemTime {
275
54
        *self.dir_key_published
276
54
    }
277

            
278
    /// Return the time when this certificate says it should expire.
279
54
    pub fn expires(&self) -> time::SystemTime {
280
54
        *self.dir_key_expires
281
54
    }
282

            
283
    /// Parse an authority certificate from a reader.
284
17
    fn from_body(body: &Section<'_, AuthCertKwd>, s: &str) -> Result<UncheckedAuthCert> {
285
        use AuthCertKwd::*;
286

            
287
        // Make sure first and last element are correct types.  We can
288
        // safely call unwrap() on first and last, since there are required
289
        // tokens in the rules, so we know that at least one token will have
290
        // been parsed.
291
        let start_pos = {
292
            // Unwrap should be safe because `.parse()` would have already
293
            // returned an Error
294
            #[allow(clippy::unwrap_used)]
295
17
            let first_item = body.first_item().unwrap();
296
17
            if first_item.kwd() != DIR_KEY_CERTIFICATE_VERSION {
297
1
                return Err(EK::WrongStartingToken
298
1
                    .with_msg(first_item.kwd_str().to_string())
299
1
                    .at_pos(first_item.pos()));
300
16
            }
301
16
            first_item.pos()
302
        };
303
        let end_pos = {
304
            // Unwrap should be safe because `.parse()` would have already
305
            // returned an Error
306
            #[allow(clippy::unwrap_used)]
307
16
            let last_item = body.last_item().unwrap();
308
16
            if last_item.kwd() != DIR_KEY_CERTIFICATION {
309
1
                return Err(EK::WrongEndingToken
310
1
                    .with_msg(last_item.kwd_str().to_string())
311
1
                    .at_pos(last_item.pos()));
312
15
            }
313
15
            last_item.end_pos()
314
        };
315

            
316
15
        let version = body
317
15
            .required(DIR_KEY_CERTIFICATE_VERSION)?
318
15
            .parse_arg::<u32>(0)?;
319
15
        if version != 3 {
320
2
            return Err(EK::BadDocumentVersion.with_msg(format!("unexpected version {}", version)));
321
13
        }
322
13
        let dir_key_certificate_version = AuthCertVersion::V3;
323

            
324
13
        let dir_signing_key: rsa::PublicKey = body
325
13
            .required(DIR_SIGNING_KEY)?
326
13
            .parse_obj::<RsaPublicParse1Helper>("RSA PUBLIC KEY")?
327
13
            .check_len(1024..)?
328
13
            .check_exponent(65537)?
329
            .into();
330

            
331
13
        let dir_identity_key: rsa::PublicKey = body
332
13
            .required(DIR_IDENTITY_KEY)?
333
13
            .parse_obj::<RsaPublicParse1Helper>("RSA PUBLIC KEY")?
334
13
            .check_len(1024..)?
335
13
            .check_exponent(65537)?
336
            .into();
337

            
338
13
        let dir_key_published = body
339
13
            .required(DIR_KEY_PUBLISHED)?
340
            .args_as_str()
341
            .parse::<Iso8601TimeSp>()?;
342

            
343
13
        let dir_key_expires = body
344
13
            .required(DIR_KEY_EXPIRES)?
345
            .args_as_str()
346
            .parse::<Iso8601TimeSp>()?;
347

            
348
        {
349
            // Check fingerprint for consistency with key.
350
13
            let fp_tok = body.required(FINGERPRINT)?;
351
13
            let fingerprint: RsaIdentity = fp_tok.args_as_str().parse::<Fingerprint>()?.into();
352
13
            if fingerprint != dir_identity_key.to_rsa_identity() {
353
1
                return Err(EK::BadArgument
354
1
                    .at_pos(fp_tok.pos())
355
1
                    .with_msg("fingerprint does not match RSA identity"));
356
12
            }
357
        }
358

            
359
12
        let dir_address = body
360
12
            .maybe(DIR_ADDRESS)
361
12
            .parse_args_as_str::<net::SocketAddrV4>()?;
362

            
363
        // check crosscert
364
        let dir_key_crosscert;
365
        let v_crosscert = {
366
12
            let crosscert = body.required(DIR_KEY_CROSSCERT)?;
367
            // Unwrap should be safe because `.parse()` and `required()` would
368
            // have already returned an Error
369
            #[allow(clippy::unwrap_used)]
370
12
            let mut tag = crosscert.obj_tag().unwrap();
371
            // we are required to support both.
372
12
            if tag != "ID SIGNATURE" && tag != "SIGNATURE" {
373
1
                tag = "ID SIGNATURE";
374
11
            }
375
12
            let sig = crosscert.obj(tag)?;
376

            
377
11
            let signed = dir_identity_key.to_rsa_identity();
378
            // TODO: we need to accept prefixes here. COMPAT BLOCKER.
379

            
380
11
            let v = rsa::ValidatableRsaSignature::new(&dir_signing_key, &sig, signed.as_bytes());
381

            
382
11
            dir_key_crosscert = CrossCert {
383
11
                signature: CrossCertObject(sig),
384
11
            };
385

            
386
11
            v
387
        };
388

            
389
        // check the signature
390
        let v_sig = {
391
11
            let signature = body.required(DIR_KEY_CERTIFICATION)?;
392
11
            let sig = signature.obj("SIGNATURE")?;
393

            
394
11
            let mut sha1 = d::Sha1::new();
395
            // Unwrap should be safe because `.parse()` would have already
396
            // returned an Error
397
            #[allow(clippy::unwrap_used)]
398
11
            let start_offset = body.first_item().unwrap().offset_in(s).unwrap();
399
            #[allow(clippy::unwrap_used)]
400
11
            let end_offset = body.last_item().unwrap().offset_in(s).unwrap();
401
11
            let end_offset = end_offset + "dir-key-certification\n".len();
402
11
            sha1.update(
403
11
                s.get(start_offset..end_offset)
404
                    .ok_or_else(|| internal!("chopped utf8"))?,
405
            );
406
11
            let sha1 = sha1.finalize();
407
            // TODO: we need to accept prefixes here. COMPAT BLOCKER.
408

            
409
11
            rsa::ValidatableRsaSignature::new(&dir_identity_key, &sig, &sha1)
410
        };
411

            
412
11
        let id_fingerprint = dir_identity_key.to_rsa_identity();
413

            
414
        let location = {
415
11
            let start_idx = start_pos.offset_within(s);
416
11
            let end_idx = end_pos.offset_within(s);
417
11
            match (start_idx, end_idx) {
418
                (Some(a), Some(b)) => {
419
11
                    Extent::new(s, s.get(a..b + 1).ok_or_else(|| internal!("chopped utf8"))?)
420
                }
421
                _ => None,
422
            }
423
        };
424

            
425
11
        let authcert = AuthCert {
426
11
            dir_key_certificate_version,
427
11
            dir_address,
428
11
            dir_identity_key,
429
11
            dir_signing_key,
430
11
            dir_key_published,
431
11
            dir_key_expires,
432
11
            dir_key_crosscert,
433
11
            fingerprint: Fingerprint(id_fingerprint),
434
11
            __non_exhaustive: (),
435
11
        };
436

            
437
        let signatures: Vec<Box<dyn pk::ValidatableSignature>> =
438
11
            vec![Box::new(v_crosscert), Box::new(v_sig)];
439

            
440
11
        let timed = timed::TimeRangeBound::new(authcert, *dir_key_published..*dir_key_expires);
441
11
        let signed = signed::SignatureGated::new(timed, signatures);
442
11
        let unchecked = UncheckedAuthCert {
443
11
            location,
444
11
            c: signed,
445
11
        };
446
11
        Ok(unchecked)
447
17
    }
448
}
449

            
450
/// Parsing/encoding module for `AuthCertKeyIds` as found in `directory-signature`
451
///
452
/// Use with `#[deftly(netdoc(with = ...))]` when deriving
453
/// `ItemValueParseable` and `ItemValueEncodable`.
454
///
455
/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:directory-signature>
456
//
457
// Currently the only use site is `netstatus::Signature`.
458
// If we find this is being used in many places, and is therefore a standard thing,
459
// we should arrange for the derives to be able to derive from an argument collection,
460
// and use that.
461
pub(crate) mod keyids_directory_signature_args {
462
    use super::*;
463
    use std::result::Result;
464

            
465
    /// Parse
466
182543
    pub(crate) fn from_args<'s>(
467
182543
        args: &mut ArgumentStream<'s>,
468
182543
    ) -> Result<AuthCertKeyIds, ArgumentError> {
469
365086
        let mut fp = || Ok::<_, ArgumentError>(Fingerprint::from_args(args)?.0);
470
        Ok(AuthCertKeyIds {
471
182543
            id_fingerprint: fp()?,
472
182543
            sk_fingerprint: fp()?,
473
        })
474
182543
    }
475

            
476
    /// Encode
477
31
    pub(crate) fn write_arg_onto(
478
31
        self_: &AuthCertKeyIds,
479
31
        out: &mut ItemEncoder<'_>,
480
31
    ) -> Result<(), Bug> {
481
62
        let mut fp = |id| Fingerprint(id).write_arg_onto(out);
482
31
        fp(self_.id_fingerprint)?;
483
31
        fp(self_.sk_fingerprint)?;
484
31
        Ok(())
485
31
    }
486
}
487

            
488
/// Pseudo-Signature of the long-term identity key by the medium-term key.
489
///
490
/// This type does not implement `SignatureItemParseable` because that trait
491
/// is reserved for signatures on *netdocs*, such as [`AuthCertSignature`].
492
/// As `CrossCert` does not sign a full document, it implements only
493
/// `ItemValueParseable`, instead.
494
///
495
/// Verification of this signature is done in `AuthCertUnverified::verify`,
496
/// and during parsing by the old parser.
497
/// So a `CrossCert` in [`AuthCert::dir_key_crosscert`] in a bare `AuthCert` has been validated.
498
//
499
// TODO SPEC (Diziet): it is far from clear to me that this cert serves any useful purpose.
500
// However, we are far too busy now with rewriting the universe to consider transitioning it away.
501
#[derive(Debug, Clone, PartialEq, Eq, Deftly)]
502
#[derive_deftly(ItemValueParseable, ItemValueEncodable)]
503
#[deftly(netdoc(no_extra_args))]
504
#[non_exhaustive]
505
pub struct CrossCert {
506
    /// The bytes of the signature (base64-decoded).
507
    #[deftly(netdoc(object))]
508
    pub signature: CrossCertObject,
509
}
510

            
511
/// Wrapper around [`Vec<u8>`] implementing [`ItemObjectParseable`] properly.
512
///
513
/// Unfortunately, this wrapper is necessary, because the specification
514
/// demands that these certificate objects must accept two labels:
515
/// `SIGNATURE` and `ID SIGNATURE`.  Because the deftly template for
516
/// `ItemValueParseable` only allows for a single label
517
/// (`#[deftly(netdoc(object(label = "LABEL")))]`), we must implement this
518
/// trait ourselves in order to allow multiple ones.
519
///
520
/// TODO: In the future, it might be nice to let the respective fmeta
521
/// accept a pattern, as pattern matching would allow trivially for one
522
/// to infinity different combinations.
523
/// TODO SPEC: Alternatively we could abolish the wrong labels,
524
/// or we could abolish Objects completely and just have long lines.
525
///
526
/// # Specifications
527
///
528
/// <https://spec.torproject.org/dir-spec/creating-key-certificates.html#item:dir-key-crosscert>
529
#[derive(Clone, PartialEq, Eq, derive_more::Deref)]
530
#[non_exhaustive]
531
pub struct CrossCertObject(pub Vec<u8>);
532
impl_debug_hex! { CrossCertObject . 0 }
533

            
534
impl CrossCert {
535
    /// Make a `CrossCert`
536
1
    pub fn new(
537
1
        k_auth_sign_rsa: &rsa::KeyPair,
538
1
        h_kp_auth_id_rsa: &RsaIdentity,
539
1
    ) -> StdResult<Self, Bug> {
540
1
        let signature = k_auth_sign_rsa
541
1
            .sign(h_kp_auth_id_rsa.as_bytes())
542
1
            .map_err(into_internal!("failed to sign cross-cert"))?;
543
1
        Ok(CrossCert {
544
1
            signature: CrossCertObject(signature),
545
1
        })
546
1
    }
547
}
548

            
549
/// Signatures for [`AuthCert`]
550
///
551
/// Signed by [`AuthCert::dir_identity_key`] in order to prove ownership.
552
/// Can be seen as the opposite of [`AuthCert::dir_key_crosscert`].
553
///
554
/// # Specifications
555
///
556
/// * <https://spec.torproject.org/dir-spec/creating-key-certificates.html#item:dir-key-certification>
557
/// * <https://spec.torproject.org/dir-spec/netdoc.html#signing>
558
#[derive(Debug, Clone, PartialEq, Eq, Deftly)]
559
#[derive_deftly(NetdocParseableSignatures, NetdocEncodable)]
560
#[deftly(netdoc(signatures(hashes_accu = Sha1WholeKeywordLine)))]
561
#[non_exhaustive]
562
pub struct AuthCertSignatures {
563
    /// Contains the actual signature, see [`AuthCertSignatures`].
564
    pub dir_key_certification: RsaSha1Signature,
565
}
566

            
567
/// RSA signature for data in [`AuthCert`]
568
///
569
/// <https://spec.torproject.org/dir-spec/netdoc.html#signing>
570
///
571
/// Compatibility type alias for [`RsaSha1Signature`].
572
#[deprecated = "use RsaSha1Signature"]
573
pub type AuthCertSignature = RsaSha1Signature;
574

            
575
impl ItemObjectParseable for CrossCertObject {
576
5940
    fn check_label(label: &str) -> StdResult<(), parse2::EP> {
577
5940
        match label {
578
5939
            "SIGNATURE" | "ID SIGNATURE" => Ok(()),
579
1
            _ => Err(parse2::EP::ObjectIncorrectLabel),
580
        }
581
5940
    }
582

            
583
5939
    fn from_bytes(input: &[u8]) -> StdResult<Self, parse2::EP> {
584
5939
        Ok(Self(input.to_vec()))
585
5939
    }
586
}
587

            
588
impl ItemObjectEncodable for CrossCertObject {
589
1
    fn label(&self) -> &str {
590
1
        "ID SIGNATURE"
591
1
    }
592

            
593
1
    fn write_object_onto(&self, b: &mut Vec<u8>) -> StdResult<(), Bug> {
594
1
        b.extend(&self.0);
595
1
        Ok(())
596
1
    }
597
}
598

            
599
impl tor_checkable::SelfSigned<timed::TimeRangeBound<AuthCert>> for UncheckedAuthCert {
600
    type Error = signature::Error;
601

            
602
8
    fn dangerously_assume_wellsigned(self) -> timed::TimeRangeBound<AuthCert> {
603
8
        self.c.dangerously_assume_wellsigned()
604
8
    }
605
8
    fn is_well_signed(&self) -> std::result::Result<(), Self::Error> {
606
8
        self.c.is_well_signed()
607
8
    }
608
}
609

            
610
impl AuthCertUnverified {
611
    /// Verifies the signature of a [`AuthCert`]
612
    ///
613
    /// # Algorithm
614
    ///
615
    /// 1. Check whether this comes from a valid authority in `v3idents`.
616
    /// 2. Check whether the timestamps are valid (± tolerance).
617
    /// 3. Check whether the fingerprint and long-term identity key match.
618
    /// 4. Check the cross-certificate (proof-of-ownership of signing key).
619
    /// 5. Check the outer certificate (proof-of-ownership of identity key).
620
    ///
621
    /// TODO: Replace `pre_tolerance` and `post_tolerance` with
622
    /// `tor_dircommon::config::DirTolerance` which is not possible at the
623
    /// moment due to a circular dependency of `tor-dircommon` depending
624
    /// upon `tor-netdoc`.
625
    ///
626
    /// TODO: Consider whether to try to deduplicate this signature checking
627
    /// somehow, wrt to [`UncheckedAuthCert`].
628
5941
    pub fn verify(
629
5941
        self,
630
5941
        v3idents: &[RsaIdentity],
631
5941
    ) -> StdResult<TimeRangeBound<AuthCert>, parse2::VerifyFailed> {
632
5941
        let (body, sigs) = (self.body, self.sigs);
633

            
634
        // (1) Check whether this comes from a valid authority in `v3idents`.
635
5941
        if !v3idents.contains(&body.fingerprint.0) {
636
214
            return Err(parse2::VerifyFailed::InsufficientTrustedSigners);
637
5727
        }
638

            
639
        // (2) Check whether the timestamps are valid (± tolerance).
640
5727
        let validity = *body.dir_key_published..=*body.dir_key_expires;
641

            
642
        // (3) Check whether the fingerprint and long-term identity key match.
643
5727
        if body.dir_identity_key.to_rsa_identity() != *body.fingerprint {
644
1
            return Err(parse2::VerifyFailed::Inconsistent);
645
5726
        }
646

            
647
        // (4) Check the cross-certificate (proof-of-ownership of signing key).
648
5726
        body.dir_signing_key.verify(
649
5726
            body.fingerprint.0.as_bytes(),
650
5726
            &body.dir_key_crosscert.signature,
651
5726
        )?;
652

            
653
        // (5) Check the outer certificate (proof-of-ownership of identity key).
654
5725
        body.dir_identity_key.verify(
655
5725
            &sigs.hashes.0.ok_or(parse2::VerifyFailed::Bug)?,
656
5725
            &sigs.sigs.dir_key_certification.signature,
657
1
        )?;
658

            
659
5724
        Ok(TimeRangeBound::new(body, validity))
660
5941
    }
661

            
662
    /// Verify the signatures (and check validity times)
663
    ///
664
    /// The pre and post tolerance (time check allowances) used are both zero.
665
    ///
666
    /// # Security considerations
667
    ///
668
    /// The caller must check that the KP_auth_id is correct/relevant.
669
33
    pub fn verify_selfcert(self, now: SystemTime) -> StdResult<AuthCert, parse2::VerifyFailed> {
670
33
        let h_kp_auth_id_rsa = self.inspect_unverified().0.fingerprint.0;
671
33
        Ok(self.verify(&[h_kp_auth_id_rsa])?.if_valid_at(&now)?)
672
33
    }
673
}
674

            
675
impl AuthCert {
676
    /// Make the base for a new `AuthCert`
677
    ///
678
    /// This contains only the mandatory fields (the ones in `AuthCertConstructor`).
679
    /// This method is an alternative to providing a `AuthCertConstructor` value display,
680
    /// and is convenient because an authcert contains much recapitulated information.
681
    ///
682
    /// # Example
683
    ///
684
    /// ```no_run
685
    /// # fn main() -> Result<(), anyhow::Error> {
686
    /// use tor_netdoc::doc::authcert::AuthCert;
687
    /// let (k_auth_id_rsa, k_auth_sign_rsa, published, expires) = todo!();
688
    /// let authcert = AuthCert {
689
    ///     dir_address: Some("192.0.2.17:7000".parse()?),
690
    ///     ..AuthCert::new_base(&k_auth_id_rsa, &k_auth_sign_rsa, published, expires)?
691
    /// };
692
    /// # Ok(())
693
    /// # }
694
    /// ```
695
1
    pub fn new_base(
696
1
        k_auth_id_rsa: &rsa::KeyPair,
697
1
        k_auth_sign_rsa: &rsa::KeyPair,
698
1
        published: SystemTime,
699
1
        expires: SystemTime,
700
1
    ) -> StdResult<Self, Bug> {
701
1
        let fingerprint = k_auth_id_rsa.to_public_key().to_rsa_identity();
702
1
        let dir_key_crosscert = CrossCert::new(k_auth_sign_rsa, &fingerprint)?;
703

            
704
1
        let base = AuthCertConstructor {
705
1
            fingerprint: fingerprint.into(),
706
1
            dir_key_published: published.into(),
707
1
            dir_key_expires: expires.into(),
708
1
            dir_identity_key: k_auth_id_rsa.to_public_key(),
709
1
            dir_signing_key: k_auth_sign_rsa.to_public_key(),
710
1
            dir_key_crosscert,
711
1
        }
712
1
        .construct();
713

            
714
1
        Ok(base)
715
1
    }
716

            
717
    /// Encode this `AuthCert` and sign it with `k_auth_id_rsa`
718
    ///
719
    /// Yields the string representation of the signed, encoded, document,
720
    /// as an [`EncodedAuthCert`].
721
1
    pub fn encode_sign(&self, k_auth_id_rsa: &rsa::KeyPair) -> StdResult<EncodedAuthCert, Bug> {
722
1
        let mut encoder = NetdocEncoder::new();
723
1
        self.encode_unsigned(&mut encoder)?;
724

            
725
        let signature =
726
1
            RsaSha1Signature::new_sign_netdoc(k_auth_id_rsa, &encoder, "dir-key-certification")?;
727
1
        let sigs = AuthCertSignatures {
728
1
            dir_key_certification: signature,
729
1
        };
730
1
        sigs.encode_unsigned(&mut encoder)?;
731

            
732
1
        let encoded = encoder.finish()?;
733
        // This rechecks the invariants which ought to be true by construction.
734
        // That is convenient for the code here, and the perf implications are irrelevant.
735
1
        let encoded = encoded
736
1
            .try_into()
737
1
            .map_err(into_internal!("generated broken authcert"))?;
738
1
        Ok(encoded)
739
1
    }
740
}
741

            
742
#[cfg(test)]
743
mod test {
744
    // @@ begin test lint list maintained by maint/add_warning @@
745
    #![allow(clippy::bool_assert_comparison)]
746
    #![allow(clippy::clone_on_copy)]
747
    #![allow(clippy::dbg_macro)]
748
    #![allow(clippy::mixed_attributes_style)]
749
    #![allow(clippy::print_stderr)]
750
    #![allow(clippy::print_stdout)]
751
    #![allow(clippy::single_char_pattern)]
752
    #![allow(clippy::unwrap_used)]
753
    #![allow(clippy::unchecked_time_subtraction)]
754
    #![allow(clippy::useless_vec)]
755
    #![allow(clippy::needless_pass_by_value)]
756
    #![allow(clippy::string_slice)] // See arti#2571
757
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
758
    use super::*;
759
    use crate::{
760
        Pos,
761
        encode::encode_netdoc_unsigned,
762
        parse2::{ErrorProblem, ParseError, ParseInput, VerifyFailed, parse_netdoc},
763
        test_support::{raw_find_item_rhs, raw_find_object},
764
        types,
765
    };
766
    use humantime::parse_rfc3339;
767
    use std::result::Result;
768
    use std::{fs, net::SocketAddrV4, time::Duration};
769
    use tor_basic_utils::test_rng;
770

            
771
    const TESTDATA: &str = include_str!("../../testdata/authcert1.txt");
772

            
773
    fn bad_data(fname: &str) -> String {
774
        use std::fs;
775
        use std::path::PathBuf;
776
        let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
777
        path.push("testdata");
778
        path.push("bad-certs");
779
        path.push(fname);
780

            
781
        fs::read_to_string(path).unwrap()
782
    }
783

            
784
    #[test]
785
    fn parse_one() -> crate::Result<()> {
786
        use tor_checkable::{SelfSigned, TimeBound};
787
        let cert = AuthCert::parse(TESTDATA)?
788
            .check_signature()
789
            .unwrap()
790
            .dangerously_assume_timely();
791

            
792
        // Taken from TESTDATA
793
        assert_eq!(
794
            cert.id_fingerprint().to_string(),
795
            "$ed03bb616eb2f60bec80151114bb25cef515b226"
796
        );
797
        assert_eq!(
798
            cert.key_ids().sk_fingerprint.to_string(),
799
            "$c4f720e2c59f9ddd4867fff465ca04031e35648f"
800
        );
801

            
802
        Ok(())
803
    }
804

            
805
    #[test]
806
    fn parse_bad() {
807
        fn check(fname: &str, err: &crate::Error) {
808
            let contents = bad_data(fname);
809
            let cert = AuthCert::parse(&contents);
810
            assert!(cert.is_err());
811
            assert_eq!(&cert.err().unwrap(), err);
812
        }
813

            
814
        check(
815
            "bad-cc-tag",
816
            &EK::WrongObject.at_pos(Pos::from_line(27, 12)),
817
        );
818
        check(
819
            "bad-fingerprint",
820
            &EK::BadArgument
821
                .at_pos(Pos::from_line(2, 1))
822
                .with_msg("fingerprint does not match RSA identity"),
823
        );
824
        check(
825
            "bad-version",
826
            &EK::BadDocumentVersion.with_msg("unexpected version 4"),
827
        );
828
        check(
829
            "wrong-end",
830
            &EK::WrongEndingToken
831
                .with_msg("dir-key-crosscert")
832
                .at_pos(Pos::from_line(37, 1)),
833
        );
834
        check(
835
            "wrong-start",
836
            &EK::WrongStartingToken
837
                .with_msg("fingerprint")
838
                .at_pos(Pos::from_line(1, 1)),
839
        );
840
    }
841

            
842
    #[test]
843
    fn test_recovery_1() {
844
        let mut data = "<><><<><>\nfingerprint ABC\n".to_string();
845
        data += TESTDATA;
846

            
847
        let res: Vec<crate::Result<_>> = AuthCert::parse_multiple(&data).unwrap().collect();
848

            
849
        // We should recover from the failed case and read the next data fine.
850
        assert!(res[0].is_err());
851
        assert!(res[1].is_ok());
852
        assert_eq!(res.len(), 2);
853
    }
854

            
855
    #[test]
856
    fn test_recovery_2() {
857
        let mut data = bad_data("bad-version");
858
        data += TESTDATA;
859

            
860
        let res: Vec<crate::Result<_>> = AuthCert::parse_multiple(&data).unwrap().collect();
861

            
862
        // We should recover from the failed case and read the next data fine.
863
        assert!(res[0].is_err());
864
        assert!(res[1].is_ok());
865
        assert_eq!(res.len(), 2);
866
    }
867

            
868
    const AUTHCERT_RAW: &str = include_str!("../../testdata2/keys/authority_certificate");
869

            
870
    fn raw_authcert_time(kw: &str) -> SystemTime {
871
        let t: Iso8601TimeSp = raw_find_item_rhs(AUTHCERT_RAW, kw).parse().expect(kw);
872
        t.0
873
    }
874
    fn t_dir_key_published() -> SystemTime {
875
        raw_authcert_time("dir-key-published")
876
    }
877
    fn t_dir_key_expires() -> SystemTime {
878
        raw_authcert_time("dir-key-expires")
879
    }
880
    /// A system time in the range of [`DIR_KEY_PUBLISHED`] and [`DIR_KEY_EXPIRES`].
881
    ///
882
    /// Constructed by ourselves to have a time point we can use for testing
883
    /// timestamp verification.
884
    fn t_valid_system_time() -> SystemTime {
885
        let a = t_dir_key_published();
886
        let b = t_dir_key_expires();
887
        a + (b.duration_since(a).unwrap() / 2)
888
    }
889

            
890
    fn t_dir_address() -> SocketAddrV4 {
891
        raw_find_item_rhs(AUTHCERT_RAW, "dir-address")
892
            .parse()
893
            .unwrap()
894
    }
895

            
896
    fn t_dir_identity_key() -> &'static str {
897
        raw_find_object(AUTHCERT_RAW, "dir-identity-key")
898
    }
899
    fn t_dir_signing_key() -> &'static str {
900
        raw_find_object(AUTHCERT_RAW, "dir-signing-key")
901
    }
902
    fn t_dir_cross_cert_object() -> &'static str {
903
        raw_find_object(AUTHCERT_RAW, "dir-key-crosscert")
904
    }
905

            
906
    fn t_fingerprint() -> &'static str {
907
        raw_find_item_rhs(AUTHCERT_RAW, "fingerprint")
908
    }
909

            
910
    /// Different authcert, from `../../testdata2/cached-certs--*`
911
    ///
912
    /// A different authority certificate different from the one above.
913
    fn t_alternative_authcert_raw() -> &'static str {
914
        // Our "main" cert is `keys/authority_certificate` which is the one the test simulation
915
        // thinks of as the first or primary, I guess?  But to get another auth cert
916
        // we need to look in `cached-certs`, which is *all* the certs, and their sort
917
        // order doesn't seem stable.  Maybe they are sorted by *key*?  (The keys vary.)
918
        // So sometimes, the first cert (which gets split out into `--1`) is the same one!
919
        // In that case, use the 2nd.
920
        let t1 = include_str!("../../testdata2/cached-certs--1");
921
        if t1.as_bytes() != AUTHCERT_RAW.as_bytes() {
922
            t1
923
        } else {
924
            include_str!("../../testdata2/cached-certs--2")
925
        }
926
    }
927

            
928
    /// Converts a PEM encoded RSA Public key to an [`rsa::PublicKey`].
929
    ///
930
    /// This function panics in the case the input is malformatted.
931
    fn pem_to_rsa_pk(s: &str) -> rsa::PublicKey {
932
        rsa::PublicKey::from_der(pem::parse(s).unwrap().contents()).unwrap()
933
    }
934

            
935
    /// Converts a hex-encoded RSA identity to an [`RsaIdentity`].
936
    ///
937
    /// This function panics in the case the input is malformatted.
938
    fn to_rsa_id(s: &str) -> RsaIdentity {
939
        RsaIdentity::from_hex(s).unwrap()
940
    }
941

            
942
    /// Tests whether a [`DirKeyCrossCert`] can be parsed properly.
943
    #[test]
944
    fn dir_auth_cross_cert() {
945
        #[derive(Debug, Clone, PartialEq, Eq, Deftly)]
946
        #[derive_deftly(NetdocParseable)]
947
        struct Dummy {
948
            dir_key_crosscert: CrossCert,
949
        }
950

            
951
        // "Encodes" a DIR_CROSS_CERT_OBJECT by simply removing the lines
952
        // indicating the BEGIN and END, as the purpose is to test multiple
953
        // labels.
954
        let encoded = t_dir_cross_cert_object()
955
            .lines()
956
            .filter(|line| !line.starts_with("-----"))
957
            .collect::<Vec<_>>()
958
            .join("\n");
959
        let decoded = pem::parse(t_dir_cross_cert_object())
960
            .unwrap()
961
            .contents()
962
            .to_vec();
963

            
964
        // Try with `SIGNATURE`.
965
        let cert = format!(
966
            "dir-key-crosscert\n-----BEGIN SIGNATURE-----\n{encoded}\n-----END SIGNATURE-----"
967
        );
968
        let res = parse2::parse_netdoc::<Dummy>(&ParseInput::new(&cert, "")).unwrap();
969
        assert_eq!(
970
            res,
971
            Dummy {
972
                dir_key_crosscert: CrossCert {
973
                    signature: CrossCertObject(decoded.clone())
974
                }
975
            }
976
        );
977

            
978
        // Try with `ID SIGNATURE`.
979
        let cert = format!(
980
            "dir-key-crosscert\n-----BEGIN ID SIGNATURE-----\n{encoded}\n-----END ID SIGNATURE-----"
981
        );
982
        let res = parse2::parse_netdoc::<Dummy>(&ParseInput::new(&cert, "")).unwrap();
983
        assert_eq!(
984
            res,
985
            Dummy {
986
                dir_key_crosscert: CrossCert {
987
                    signature: CrossCertObject(decoded.clone())
988
                }
989
            }
990
        );
991

            
992
        // Try with different label and fail.
993
        let cert =
994
            format!("dir-key-crosscert\n-----BEGIN WHAT-----\n{encoded}\n-----END WHAT-----");
995
        let res = parse2::parse_netdoc::<Dummy>(&ParseInput::new(&cert, ""));
996
        match res {
997
            Err(ParseError {
998
                problem: ErrorProblem::ObjectIncorrectLabel,
999
                doctype: "dir-key-crosscert",
                file: _,
                lno: 1,
                column: None,
            }) => {}
            other => panic!("not expected error {other:#?}"),
        }
        // Try with extra args.
        let cert = format!(
            "dir-key-crosscert arg1\n-----BEGIN ID SIGNATURE-----\n{encoded}\n-----END ID SIGNATURE-----"
        );
        let res = parse2::parse_netdoc::<Dummy>(&ParseInput::new(&cert, ""));
        match res {
            Err(ParseError {
                problem: ErrorProblem::UnexpectedArgument { column: 19 },
                doctype: "dir-key-crosscert",
                file: _,
                lno: 1,
                column: Some(19),
            }) => {}
            other => panic!("not expected error {other:#?}"),
        }
    }
    #[test]
    fn dir_auth_cert() {
        let res =
            parse2::parse_netdoc::<AuthCertUnverified>(&ParseInput::new(AUTHCERT_RAW, "")).unwrap();
        assert_eq!(
            *res.inspect_unverified().0,
            AuthCert {
                dir_key_certificate_version: AuthCertVersion::V3,
                dir_address: Some(t_dir_address()),
                fingerprint: types::Fingerprint(to_rsa_id(t_fingerprint())),
                dir_key_published: Iso8601TimeSp(t_dir_key_published()),
                dir_key_expires: Iso8601TimeSp(t_dir_key_expires()),
                dir_identity_key: pem_to_rsa_pk(t_dir_identity_key()),
                dir_signing_key: pem_to_rsa_pk(t_dir_signing_key()),
                dir_key_crosscert: CrossCert {
                    signature: CrossCertObject(
                        pem::parse(t_dir_cross_cert_object())
                            .unwrap()
                            .contents()
                            .to_vec()
                    )
                },
                __non_exhaustive: (),
            }
        );
    }
    #[test]
    fn dir_auth_signature() {
        let res =
            parse2::parse_netdoc::<AuthCertUnverified>(&ParseInput::new(AUTHCERT_RAW, "")).unwrap();
        // Test a valid signature.
        let _: AuthCert = res
            .clone()
            .verify(&[to_rsa_id(t_fingerprint())])
            .unwrap()
            .if_valid_at(&t_valid_system_time())
            .unwrap();
        // Test with an invalid authority.
        assert_eq!(
            res.clone().verify(&[],).unwrap_err(),
            VerifyFailed::InsufficientTrustedSigners
        );
        // Test a key too far in the future.
        assert_eq!(
            res.clone()
                .verify(&[to_rsa_id(t_fingerprint())],)
                .unwrap()
                .if_valid_at(&SystemTime::UNIX_EPOCH,)
                .map_err(VerifyFailed::from)
                .unwrap_err(),
            VerifyFailed::TooNew
        );
        // Test an almost too new.
        let _: AuthCert = res
            .clone()
            .verify(&[to_rsa_id(t_fingerprint())])
            .unwrap()
            .if_valid_at(&t_dir_key_published())
            .unwrap();
        // Now fail when we are 1s below ...
        assert_eq!(
            res.clone()
                .verify(&[to_rsa_id(t_fingerprint())],)
                .unwrap()
                .if_valid_at(&(t_dir_key_published() - Duration::from_secs(1)),)
                .map_err(VerifyFailed::from)
                .unwrap_err(),
            VerifyFailed::TooNew
        );
        // ... but succeed again with a clock skew tolerance.
        let _: AuthCert = res
            .clone()
            .verify(&[to_rsa_id(t_fingerprint())])
            .unwrap()
            .extend_start_bound(Duration::from_secs(1))
            .if_valid_at(&(t_dir_key_published() - Duration::from_secs(1)))
            .unwrap();
        // Test a key too old.
        assert_eq!(
            res.clone()
                .verify(&[to_rsa_id(t_fingerprint())],)
                .unwrap()
                .if_valid_at(
                    &SystemTime::UNIX_EPOCH
                        .checked_add(Duration::from_secs(2000000000))
                        .unwrap(),
                )
                .map_err(VerifyFailed::from)
                .unwrap_err(),
            VerifyFailed::TooOld
        );
        // Test an almost too old.
        let _: AuthCert = res
            .clone()
            .verify(&[to_rsa_id(t_fingerprint())])
            .unwrap()
            .if_valid_at(&t_dir_key_expires())
            .unwrap();
        // Now fail when we are 1s above ...
        assert_eq!(
            res.clone()
                .verify(&[to_rsa_id(t_fingerprint())],)
                .unwrap()
                .if_valid_at(&(t_dir_key_expires() + Duration::from_secs(1)),)
                .map_err(VerifyFailed::from)
                .unwrap_err(),
            VerifyFailed::TooOld
        );
        // ... but succeed again with a clock skew tolerance.
        let _: AuthCert = res
            .clone()
            .verify(&[to_rsa_id(t_fingerprint())])
            .unwrap()
            .extend_end_bound(Duration::from_secs(1))
            .if_valid_at(&(t_dir_key_expires() + Duration::from_secs(1)))
            .unwrap();
        // Alternative (different) cert we use for generating broken certs for testing
        let alternative_cert = parse2::parse_netdoc::<AuthCertUnverified>(&ParseInput::new(
            t_alternative_authcert_raw(),
            "",
        ))
        .unwrap();
        // Check with non-matching fingerprint and long-term identity key.
        let mut res =
            parse2::parse_netdoc::<AuthCertUnverified>(&ParseInput::new(AUTHCERT_RAW, "")).unwrap();
        res.body.dir_identity_key = alternative_cert.body.dir_identity_key.clone();
        assert_eq!(
            res.verify(&[to_rsa_id(t_fingerprint())],).unwrap_err(),
            VerifyFailed::Inconsistent
        );
        // Check invalid cross-cert.
        let mut res =
            parse2::parse_netdoc::<AuthCertUnverified>(&ParseInput::new(AUTHCERT_RAW, "")).unwrap();
        res.body.dir_key_crosscert = alternative_cert.body.dir_key_crosscert.clone();
        assert_eq!(
            res.verify(&[to_rsa_id(t_fingerprint())],).unwrap_err(),
            VerifyFailed::VerifyFailed
        );
        // Check outer signature.
        let mut res =
            parse2::parse_netdoc::<AuthCertUnverified>(&ParseInput::new(AUTHCERT_RAW, "")).unwrap();
        res.sigs = alternative_cert.sigs.clone();
        assert_eq!(
            res.verify(&[to_rsa_id(t_fingerprint())],).unwrap_err(),
            VerifyFailed::VerifyFailed
        );
    }
    #[test]
    fn keyids_for_directory_signature() -> anyhow::Result<()> {
        #[derive(Deftly)]
        #[derive_deftly(NetdocEncodable, NetdocParseable)]
        struct Doc {
            intro: (),
            ids: Item,
        }
        #[derive(Deftly)]
        #[derive_deftly(ItemValueEncodable, ItemValueParseable)]
        struct Item {
            #[deftly(netdoc(with = keyids_directory_signature_args))]
            ids: AuthCertKeyIds,
        }
        let text = r#"intro
ids 1234567812345678123456781234567812345678 ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD
"#;
        let doc = parse2::parse_netdoc::<Doc>(&ParseInput::new(text, "<text>"))?;
        let re_encode = encode_netdoc_unsigned([&doc])?;
        assert_eq_or_diff!(text, re_encode);
        Ok(())
    }
    #[test]
    fn roundtrip() -> Result<(), anyhow::Error> {
        let mut rng = test_rng::testing_rng();
        let k_auth_id_rsa = rsa::KeyPair::generate(&mut rng)?;
        let k_auth_sign_rsa = rsa::KeyPair::generate(&mut rng)?;
        let secs = |s| Duration::from_secs(s);
        let now = parse_rfc3339("1993-01-01T00:00:00Z")?;
        let published = now - secs(1000);
        let expires = published + secs(86400);
        let tolerance = secs(10);
        let input_value = AuthCert {
            dir_address: Some("192.0.2.17:7000".parse()?),
            ..AuthCert::new_base(&k_auth_id_rsa, &k_auth_sign_rsa, published, expires)?
        };
        dbg!(&input_value);
        let encoded = input_value.encode_sign(&k_auth_id_rsa)?;
        let reparsed_uv: AuthCertUnverified =
            parse_netdoc(&ParseInput::new(encoded.as_ref(), "<encoded>"))?;
        let reparsed_value = reparsed_uv
            .verify(&[k_auth_id_rsa.to_public_key().to_rsa_identity()])?
            .extend_start_bound(tolerance)
            .extend_end_bound(tolerance)
            .if_valid_at(&now)?;
        dbg!(&reparsed_value);
        assert_eq!(input_value, reparsed_value);
        Ok(())
    }
    #[test]
    fn parse_authcert() -> anyhow::Result<()> {
        let file = "testdata2/cached-certs--1";
        let now = parse_rfc3339("2000-06-01T00:00:05Z")?;
        let text = fs::read_to_string(file)?;
        let input = ParseInput::new(&text, file);
        let doc: AuthCertUnverified = parse_netdoc(&input)?;
        let doc = doc.verify_selfcert(now)?;
        println!("{doc:?}");
        assert_eq!(
            doc.fingerprint.0.to_string(),
            (*raw_find_item_rhs(&text, "fingerprint")
                .parse::<Fingerprint>()
                .unwrap())
            .to_string(),
        );
        Ok(())
    }
}