1
//!
2
//! A "router descriptor" is a signed statement that a relay makes
3
//! about itself, explaining its keys, its capabilities, its location,
4
//! and its status.
5
//!
6
//! Relays upload their router descriptors to authorities, which use
7
//! them to build consensus documents.  Old clients and relays used to
8
//! fetch and use router descriptors for all the relays, but nowadays they use
9
//! microdescriptors instead.
10
//!
11
//! Clients still use router descriptors when communicating with
12
//! bridges: since bridges are not passed through an authority,
13
//! clients accept their descriptors directly.
14
//!
15
//! For full information about the router descriptor format, see
16
//! [dir-spec.txt](https://spec.torproject.org/dir-spec).
17
//!
18
//! # Limitations
19
//!
20
//! TODO: This needs to get tested much more!
21
//!
22
//! TODO: This implementation can be memory-inefficient.  In practice,
23
//! it gets really expensive storing policy entries, family
24
//! descriptions, parsed keys, and things like that.  We will probably want to
25
//! de-duplicate those.
26
//!
27
//! TODO: There should be accessor functions for some or all of the
28
//! fields in RouterDesc.  I'm deferring those until I know what they
29
//! should be.
30
use crate::encode::{ItemEncoder, ItemValueEncodable};
31
use crate::parse::keyword::Keyword;
32
use crate::parse::parser::{Section, SectionRules};
33
use crate::parse::tokenize::{ItemResult, NetDocReader};
34
use crate::parse2::{
35
    ArgumentError, ErrorProblem, ItemValueParseable, SignaturesData, UnparsedItem, VerifyFailed,
36
};
37
use crate::types::descriptor::*;
38
use crate::types::family::{RelayFamily, RelayFamilyIds};
39
use crate::types::policy::*;
40
use crate::types::version::TorVersion;
41
use crate::types::{EmbeddedCert, misc::*};
42
use crate::util::PeekableIterator;
43
use crate::{
44
    AllowAnnotations, Error, KeywordEncodable, NetdocErrorKind as EK, NormalItemArgument, Result,
45
};
46

            
47
use derive_deftly::Deftly;
48
use ll::pk::ed25519::Ed25519Identity;
49
use saturating_time::SaturatingTime;
50
use std::fmt::Display;
51
use std::sync::LazyLock;
52
use std::{iter, net, time};
53
use tor_basic_utils::intern::Intern;
54
use tor_cert::{CertType, KeyUnknownCert};
55
use tor_checkable::timed::{TimeRangeBound, TimeRangeBoundBuilder};
56
use tor_checkable::{Timebound, signed, timed};
57
use tor_error::{internal, into_internal};
58
use tor_llcrypto as ll;
59
use tor_llcrypto::pk::ed25519;
60
use tor_llcrypto::pk::keymanip::convert_curve25519_to_ed25519_public;
61
use tor_llcrypto::pk::rsa::RsaIdentity;
62

            
63
use digest::Digest;
64

            
65
/// Length of a router descriptor digest
66
pub const DOC_DIGEST_LEN: usize = 20;
67

            
68
/// The digest of a RouterDesc document, as reported in a NS consensus.
69
pub type RdDigest = [u8; DOC_DIGEST_LEN];
70

            
71
/// The digest of an ExtraInfo document, as reported in a RouterDesc.
72
pub type ExtraInfoDigest = [u8; DOC_DIGEST_LEN];
73

            
74
/// A router descriptor, with possible annotations.
75
#[non_exhaustive]
76
pub struct AnnotatedRouterDesc {
77
    /// Annotation for this router descriptor; possibly empty.
78
    pub ann: RouterAnnotation,
79
    /// Underlying router descriptor; signatures not checked yet.
80
    pub router: UncheckedRouterDesc,
81
}
82

            
83
/// Annotations about a router descriptor, as stored on disc.
84
#[derive(Default)]
85
#[non_exhaustive]
86
pub struct RouterAnnotation {
87
    /// Description of where we got this router descriptor
88
    pub source: Option<String>,
89
    /// When this descriptor was first downloaded.
90
    pub downloaded: Option<time::SystemTime>,
91
    /// Description of what we're willing to use this descriptor for.
92
    pub purpose: Option<String>,
93
}
94

            
95
/// Information about a relay, parsed from a router descriptor.
96
///
97
/// This type does not hold all the information in the router descriptor
98
///
99
/// # Limitations
100
///
101
/// See module documentation.
102
///
103
/// Additionally, some fields that from router descriptors are not yet
104
/// parsed: see the comments in ROUTER_BODY_RULES for information about those.
105
///
106
/// Before using this type to connect to a relay, you MUST check that
107
/// it is valid, using is_expired_at().
108
///
109
/// # Specification
110
///
111
/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html>
112
#[derive(Clone, Debug, Deftly, PartialEq)]
113
#[derive_deftly(Constructor)]
114
#[derive_deftly(NetdocParseableUnverified, NetdocEncodable)]
115
#[allow(clippy::exhaustive_structs)]
116
pub struct RouterDesc {
117
    /// `router` --- Introduce a router descriptor.
118
    ///
119
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:router>
120
    #[deftly(constructor)]
121
    pub router: RouterDescIntroItem,
122

            
123
    /// `identity-ed25519` --- Specify the router's ed25519 identity.
124
    ///
125
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:identity-ed25519>
126
    #[deftly(constructor)]
127
    pub identity_ed25519: EmbeddedCert<Ed25519IdentityCert, KeyUnknownCert>,
128

            
129
    /// `master-key-ed25519` --- Redundantly specify the router's ed25519 identity.
130
    ///
131
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:master-key-ed25519>
132
    #[deftly(netdoc(single_arg))]
133
    #[deftly(constructor)]
134
    pub master_key_ed25519: Ed25519Public,
135

            
136
    /// `bandwidth` --- Report router's network bandwidth.
137
    ///
138
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:bandwidth>
139
    pub bandwidth: Bandwidth,
140

            
141
    /// `platform` --- Describe the platform on which this relay is running.
142
    ///
143
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:platform>
144
    pub platform: Option<RelayPlatform>,
145

            
146
    /// `published` --- Time this descriptor (and extra-info) was generated.
147
    ///
148
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:published>
149
    #[deftly(netdoc(single_arg))]
150
    #[deftly(constructor)]
151
    pub published: Iso8601TimeSp,
152

            
153
    /// `fingerprint` --- Redundant hash of ASN-1 encoding of router identity key.
154
    ///
155
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:fingerprint>
156
    #[deftly(netdoc(single_arg))]
157
    pub fingerprint: Option<SpFingerprint>,
158

            
159
    /// `hibernating` --- Whether the relay is hibernating.
160
    ///
161
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:hibernating>
162
    #[deftly(netdoc(single_arg, default(skip)))]
163
    pub hibernating: NumericBoolean,
164

            
165
    /// `uptime` --- How long this relay has been continously running
166
    ///
167
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:uptime>
168
    #[deftly(netdoc(single_arg))]
169
    pub uptime: Option<u64>,
170

            
171
    /// `ntor-onion-key` --- The circuit extension key.
172
    ///
173
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:ntor-onion-key>
174
    #[deftly(netdoc(single_arg))]
175
    #[deftly(constructor)]
176
    pub ntor_onion_key: Curve25519Public,
177

            
178
    /// `ntor-onion-key-crosscert` --- Reverse cert by K_ntor on KP_relayid_ed
179
    ///
180
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:ntor-onion-key-crosscert>
181
    #[deftly(constructor)]
182
    pub ntor_onion_key_crosscert: NtorOnionKeyCrossCert,
183

            
184
    /// `signing-key` --- Obsolete RSA identity key.
185
    ///
186
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:signing-key>
187
    #[deftly(constructor)]
188
    pub signing_key: ll::pk::rsa::PublicKey,
189

            
190
    /// `accept, reject` --- Exit policy.
191
    ///
192
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:accept>
193
    // TODO: these polices can get bulky too. Perhaps we should
194
    // de-duplicate them too.
195
    // Not skipping the default here is probably desirable, as this field should
196
    // generally always be ended with a default policy (i.e. default accept,
197
    // default deny).
198
    #[deftly(netdoc(flatten))]
199
    pub ipv4_policy: AddrPolicy,
200

            
201
    /// `ipv6-policy` --- Exit plicy summary for IPv6
202
    ///
203
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:ipv6-policy>
204
    #[deftly(netdoc(default(skip)))]
205
    pub ipv6_policy: Intern<PortPolicy>,
206

            
207
    /// `overload-general` --- Relay is overloaded.
208
    ///
209
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:overload-general>
210
    // TODO in OverloadGeneral use ConstantString (from !3985) for version
211
    pub overload_general: Option<OverloadGeneral>,
212

            
213
    /// `contact` --- Server administrator contact information.
214
    ///
215
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:contact>
216
    pub contact: Option<ContactInfo>,
217

            
218
    /// `family` --- Group relays for the purpose of path selection.
219
    ///
220
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:family>
221
    #[deftly(netdoc(default(skip)))]
222
    pub family: Intern<RelayFamily>,
223

            
224
    /// `family-cert` --- Prove membership in a relay family.
225
    ///
226
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:family-cert>
227
    pub family_cert: RetainedOrderVec<EmbeddedCert<Ed25519FamilyCert, KeyUnknownCert>>,
228

            
229
    /// `caches-extra-info` --- Router provides extra-info as a dirmirror.
230
    ///
231
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#caches-extra-info>
232
    pub caches_extra_info: Option<ItemPresent<CachesExtraInfoToken>>,
233

            
234
    /// `extra-info-digest` --- Hash of the extra-info document.
235
    ///
236
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:extra-info-digest>
237
    pub extra_info_digest: Option<ExtraInfoDigests>,
238

            
239
    /// `hidden-service-dir` --- Declares this router to be a hidden service directory
240
    ///
241
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:hidden-service-dir>
242
    pub hidden_service_dir: Option<ItemPresent<HiddenServiceDirToken>>,
243

            
244
    /// `or-address` --- Alternative ORport address and port
245
    ///
246
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:or-address>
247
    #[deftly(netdoc(single_arg))]
248
    pub or_address: Vec<net::SocketAddr>,
249

            
250
    /// `tunnelled-dir-server` --- Accepts a `BEGIN_DIR` relay message.
251
    ///
252
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#tunnelled-dir-server>
253
    pub tunnelled_dir_server: Option<ItemPresent<TunnelledDirServerToken>>,
254

            
255
    /// `proto` --- Subprotocol capabilities supported.
256
    ///
257
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:proto>
258
    pub proto: tor_protover::Protocols,
259

            
260
    #[doc(hidden)]
261
    #[deftly(netdoc(skip))]
262
    pub __non_exhaustive: (),
263
}
264

            
265
/// Signatures of a [`RouterDesc`].
266
///
267
/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:router-sig-ed25519>
268
#[derive(Clone, Debug, PartialEq, Deftly)]
269
#[derive_deftly(NetdocParseableSignatures, NetdocEncodable)]
270
#[deftly(netdoc(signatures(hashes_accu = "RouterHashAccu")))]
271
#[non_exhaustive]
272
pub struct RouterDescSignatures {
273
    /// `router-sig-ed25519` --- Ed25519 signature
274
    ///
275
    /// Ed25519 signature by the Ed25519 signing key on the SHA-256 digest of
276
    /// the document prefixed by a magic up until and including the
277
    /// `router-sig-ed25519` keyword plus space.
278
    pub router_sig_ed25519: RouterSigEd25519,
279

            
280
    /// `router-signature` --- RSA signature
281
    ///
282
    /// * At end, exactly once.
283
    /// * RSA signature of the document, including `router-sig-ed25519`.
284
    pub router_signature: RouterSignature,
285
}
286

            
287
// TODO: Implement a .encode_sign() method.
288
impl RouterDescUnverified {
289
    /// Verifies a self-signed [`RouterDescUnverified`].
290
    ///
291
    /// This verification performs the following checks:
292
    /// * [`RouterDesc::identity_ed25519`] is validly signed.
293
    /// * [`RouterDesc::master_key_ed25519`] is as implied by [`RouterDesc::identity_ed25519`].
294
    /// * [`RouterDesc::fingerprint`] is as implied by [`RouterDesc::signing_key`].
295
    /// * [`RouterDesc::ntor_onion_key_crosscert`] is validly signed.
296
    /// * [`RouterDesc::signing_key`] has correct length and exponent.
297
    /// * All [`RouterDesc::family_cert`] elements are valid.
298
    /// * The inner and outer [`RouterDescSignatures`] are valid.
299
    ///
300
    /// The result will be a [`TimeRangeBound`] composed from the respective
301
    /// minimums and maximums found in the present certificates.  For the lower
302
    /// bound, [`RouterDesc::published`] will also be taken into account when
303
    /// determining the minimum.
304
    //
305
    // We deny the use of unused variables as a hint to use all TimeRangeBound
306
    // values obtained through a dangerous split.
307
    #[deny(unused_variables)]
308
10636
    pub fn verify(self) -> std::result::Result<TimeRangeBound<RouterDesc>, VerifyFailed> {
309
10884
        let logic = |trbb: &mut TimeRangeBoundBuilder| -> _ {
310
            // Type annotations to make LSP happy.
311
10636
            let (mut body, sigs): (RouterDesc, SignaturesData<_>) = (self.body, self.sigs);
312

            
313
            // Verify the ed25519 identity certificate.
314
            // This also includes a check for the master-key-ed25519.
315
10636
            let identity_ed25519 =
316
10636
                Ed25519IdentityCert::verify(body.identity_ed25519.raw_unverified().clone())?
317
10636
                    .unwrap_with(trbb);
318
            let Ed25519IdentityCert {
319
10636
                id_ed25519,
320
10636
                sign_ed25519,
321
10636
            } = identity_ed25519;
322
10636
            if id_ed25519 != body.master_key_ed25519.0 {
323
2
                return Err(VerifyFailed::Inconsistent);
324
10634
            }
325
10634
            body.identity_ed25519.set_verified(identity_ed25519);
326

            
327
            // Keep track of the published value as lower time bound.
328
10634
            trbb.intersect_bounds(TimeRangeBound::new((), body.published.0..));
329

            
330
            // If set, ensure that the fingerprint equals to the signing key id.
331
10634
            if body
332
10634
                .fingerprint
333
10634
                .is_some_and(|fp| fp.0 != body.signing_key.to_rsa_identity())
334
            {
335
2
                return Err(VerifyFailed::Inconsistent);
336
10632
            }
337

            
338
            // Verify the ntor-onion-key-crosscert.
339
            // For this, we also need to convert the X25519 ntor key to an Ed25519
340
            // key using convert_curve25519_to_ed25519_public().
341
10632
            let ntor_pk = convert_curve25519_to_ed25519_public(
342
10632
                &body.ntor_onion_key.0,
343
                // Rust std turns false into 0 and true into 1.
344
10632
                body.ntor_onion_key_crosscert.bit.0.into(),
345
            )
346
10632
            .ok_or(VerifyFailed::Other)?;
347
10632
            let ntor_cc = Ed25519NtorCrossCert::verify(
348
10632
                ntor_pk.into(),
349
10632
                id_ed25519,
350
10632
                body.ntor_onion_key_crosscert.cert.raw_unverified().clone(),
351
2
            )?
352
10630
            .unwrap_with(trbb);
353
10630
            body.ntor_onion_key_crosscert.cert.set_verified(ntor_cc);
354

            
355
            // Verify that the signing key has the proper exponent and length.
356
            // TODO DIRAUTH: We want to enforce this type wise with parse2.
357
10630
            if body.signing_key.bits() != 1024 || !body.signing_key.exponent_is(65537) {
358
                return Err(VerifyFailed::Other);
359
10630
            }
360

            
361
            // Verify all family certificates.
362
10630
            for cert in body.family_cert.0.iter_mut() {
363
486
                let cert_verified =
364
486
                    Ed25519FamilyCert::verify(id_ed25519, cert.raw_unverified().clone())?
365
486
                        .unwrap_with(trbb);
366
486
                cert.set_verified(cert_verified);
367
            }
368

            
369
            // Verify the actual outer document signatures.
370
            // VerifyFailed should be an okay error variant in case that the hashes
371
            // were not accumulated, as it is not possible to verify without a
372
            // hash.
373
10630
            ed25519::PublicKey::try_from(sign_ed25519)
374
10630
                .map_err(|_| VerifyFailed::Other)?
375
10630
                .verify(
376
10630
                    &sigs.hashes.sha256.ok_or(VerifyFailed::VerifyFailed)?,
377
10630
                    &sigs.sigs.router_sig_ed25519.0,
378
2
                )?;
379
10628
            body.signing_key.verify(
380
10628
                sigs.hashes.sha1.ok_or(VerifyFailed::VerifyFailed)?.as_ref(),
381
10628
                sigs.sigs.router_signature.0.as_ref(),
382
4
            )?;
383

            
384
10624
            Ok(body)
385
10636
        };
386

            
387
10636
        TimeRangeBound::build_intersect(logic)
388
10636
    }
389
}
390

            
391
/// Description of the software a relay is running.
392
///
393
/// `platform` line in a routerstatus.
394
/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:platform>
395
// TODO: Move this to types/misc.rs.
396
#[derive(Debug, Clone, PartialEq, Eq)]
397
#[non_exhaustive]
398
pub enum RelayPlatform {
399
    /// Software advertised to be some version of Tor, on some platform.
400
    Tor(TorVersion, Option<String>),
401
    /// Software not advertised to be Tor.
402
    Other(String),
403
}
404

            
405
/// Zero-sized token type for use in [`RouterDesc::caches_extra_info`].
406
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
407
#[non_exhaustive]
408
pub struct CachesExtraInfoToken;
409

            
410
/// Zero-sized token type for use in [`RouterDesc::hidden_service_dir`].
411
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
412
#[non_exhaustive]
413
pub struct HiddenServiceDirToken;
414

            
415
/// Zero-sized token type for use in [`RouterDesc::tunnelled_dir_server`].
416
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
417
#[non_exhaustive]
418
pub struct TunnelledDirServerToken;
419

            
420
impl std::str::FromStr for RelayPlatform {
421
    type Err = Error;
422
13002
    fn from_str(args: &str) -> Result<Self> {
423
13002
        if args.starts_with("Tor ") {
424
13000
            let v: Vec<_> = args.splitn(4, ' ').collect();
425
13000
            match &v[..] {
426
12994
                ["Tor", ver, "on", p] => {
427
12994
                    Ok(RelayPlatform::Tor(ver.parse()?, Some((*p).to_string())))
428
                }
429
6
                ["Tor", ver, ..] => Ok(RelayPlatform::Tor(ver.parse()?, None)),
430
                _ => unreachable!(),
431
            }
432
        } else {
433
2
            Ok(RelayPlatform::Other(args.to_string()))
434
        }
435
13002
    }
436
}
437

            
438
impl Display for RelayPlatform {
439
50
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
440
48
        match &self {
441
42
            Self::Tor(v, Some(p)) => write!(f, "Tor {v} on {p}"),
442
6
            Self::Tor(v, None) => write!(f, "Tor {v}"),
443
2
            Self::Other(s) => write!(f, "{s}"),
444
        }
445
50
    }
446
}
447

            
448
impl ItemValueParseable for RelayPlatform {
449
10714
    fn from_unparsed(item: UnparsedItem<'_>) -> std::result::Result<Self, ErrorProblem> {
450
10714
        let mut args = item.args_copy();
451
10714
        item.check_no_object()?;
452
10714
        args.into_remaining()
453
10714
            .parse()
454
10714
            .map_err(|_| args.handle_error("platform", ArgumentError::Invalid))
455
10714
    }
456
}
457

            
458
impl ItemValueEncodable for RelayPlatform {
459
40
    fn write_item_value_onto(
460
40
        &self,
461
40
        mut out: ItemEncoder,
462
40
    ) -> std::result::Result<(), tor_error::Bug> {
463
        // Adding a raw string is fine because this is effectively a free form
464
        // field.
465
40
        out.args_raw_string(&self);
466
40
        Ok(())
467
40
    }
468
}
469

            
470
/// Version argument found in an `overload-general` item.
471
///
472
/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:overload-general>
473
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, strum::EnumString, strum::Display)]
474
#[non_exhaustive]
475
pub enum OverloadGeneralVersion {
476
    /// Version 1, currently the only supported and specified one.
477
    #[strum(serialize = "1")]
478
    V1,
479
}
480

            
481
impl NormalItemArgument for OverloadGeneralVersion {}
482

            
483
/// The overload general type found in router descriptors.
484
///
485
/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:overload-general>
486
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deftly)]
487
#[derive_deftly(ItemValueParseable, ItemValueEncodable)]
488
#[non_exhaustive]
489
pub struct OverloadGeneral {
490
    /// The version of the item.
491
    pub version: OverloadGeneralVersion,
492
    /// The timestamp since when the relay is overloaded.
493
    pub since: Iso8601TimeSp,
494
}
495

            
496
/// Introduction line of a router descriptor.
497
///
498
/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:router>
499
#[derive(Clone, Debug, PartialEq, Eq, Deftly)]
500
#[derive_deftly(ItemValueParseable, ItemValueEncodable)]
501
#[non_exhaustive]
502
pub struct RouterDescIntroItem {
503
    /// A valid router [`Nickname`].
504
    pub nickname: Nickname,
505

            
506
    /// An IPv4 address in dotted-squad format.
507
    pub address: std::net::Ipv4Addr,
508

            
509
    /// The TCP port of the onion router.
510
    pub orport: u16,
511

            
512
    /// Legacy.
513
    pub socksport: u16,
514

            
515
    /// Legacy.
516
    pub dirport: u16,
517
}
518

            
519
/// Digest identifying the extra-info document.
520
///
521
/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:extra-info-digest>
522
#[derive(Clone, Debug, PartialEq, Eq, Deftly)]
523
#[derive_deftly(ItemValueParseable, ItemValueEncodable)]
524
#[non_exhaustive]
525
pub struct ExtraInfoDigests {
526
    /// Mandatory SHA-1 of the signed data in base 16.
527
    pub sha1: FixedB16U<20>,
528

            
529
    /// Optional SHA-256 of the entire extra-info in base 64.
530
    pub sha2: Option<FixedB64<32>>,
531
}
532

            
533
/// Estimated bandwidth for a router.
534
///
535
/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:bandwidth>
536
// Does not derive Ord because it only makes sense to order on a single
537
// field but not all.
538
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Deftly)]
539
#[derive_deftly(ItemValueParseable, ItemValueEncodable)]
540
#[non_exhaustive]
541
pub struct Bandwidth {
542
    /// The volume that the relay is willing to sustain over long periods.
543
    pub average: u64,
544

            
545
    /// The volume that the relay is willing to sustain in very short intervals.
546
    pub burst: u64,
547

            
548
    /// The estimate of the capacity this relay can handle.
549
    pub observed: u64,
550
}
551

            
552
/// Ntor onion key cross-certificate.
553
///
554
/// This struct contains an [`Ed25519NtorCrossCert`] alongside the `bit`
555
/// field required for converting the ntor X25519 key to an Ed25519 key.
556
///
557
/// # See Also
558
///
559
/// * [`Ed25519NtorCrossCert`]
560
/// * <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:ntor-onion-key-crosscert>
561
#[derive(Debug, Clone, Deftly, PartialEq)]
562
#[derive_deftly(ItemValueParseable, ItemValueEncodable)]
563
#[deftly(netdoc(no_extra_args))]
564
#[non_exhaustive]
565
pub struct NtorOnionKeyCrossCert {
566
    /// True if X coordinate of the ntor onion key is negative, false if
567
    /// positive.
568
    // TODO spec: This name is very unfortunate, how about we change it
569
    // to `is_negative`.  Also, using a boolean for storing a sign bit feels
570
    // wrong to me due to the zero edge case, which would not be negative,
571
    // but also not positive either.
572
    pub bit: NumericBoolean,
573

            
574
    /// The actual embedded ntor onion key certificate.
575
    #[deftly(netdoc(object))]
576
    pub cert: EmbeddedCert<Ed25519NtorCrossCert, KeyUnknownCert>,
577
}
578

            
579
decl_keyword! {
580
    /// RouterKwd is an instance of Keyword, used to denote the different
581
    /// Items that are recognized as appearing in a router descriptor.
582
    RouterKwd {
583
        annotation "@source" => ANN_SOURCE,
584
        annotation "@downloaded-at" => ANN_DOWNLOADED_AT,
585
        annotation "@purpose" => ANN_PURPOSE,
586
        "accept" | "reject" => POLICY,
587
        "bandwidth" => BANDWIDTH,
588
        "bridge-distribution-request" => BRIDGE_DISTRIBUTION_REQUEST,
589
        "caches-extra-info" => CACHES_EXTRA_INFO,
590
        "contact" => CONTACT,
591
        "extra-info-digest" => EXTRA_INFO_DIGEST,
592
        "family" => FAMILY,
593
        "family-cert" => FAMILY_CERT,
594
        "fingerprint" => FINGERPRINT,
595
        "hibernating" => HIBERNATING,
596
        "identity-ed25519" => IDENTITY_ED25519,
597
        "ipv6-policy" => IPV6_POLICY,
598
        "master-key-ed25519" => MASTER_KEY_ED25519,
599
        "ntor-onion-key" => NTOR_ONION_KEY,
600
        "ntor-onion-key-crosscert" => NTOR_ONION_KEY_CROSSCERT,
601
        "or-address" => OR_ADDRESS,
602
        "platform" => PLATFORM,
603
        "proto" => PROTO,
604
        "published" => PUBLISHED,
605
        "router" => ROUTER,
606
        "router-sig-ed25519" => ROUTER_SIG_ED25519,
607
        "router-signature" => ROUTER_SIGNATURE,
608
        "signing-key" => SIGNING_KEY,
609
        "tunnelled_dir_server" => TUNNELLED_DIR_SERVER,
610
        "uptime" => UPTIME,
611
        // "protocols" once existed, but is obsolete
612
        // "eventdns" once existed, but is obsolete
613
        // "allow-single-hop-exits" is also obsolete.
614
    }
615
}
616

            
617
/// Rules for parsing a set of router descriptor annotations.
618
2
static ROUTER_ANNOTATIONS: LazyLock<SectionRules<RouterKwd>> = LazyLock::new(|| {
619
    use RouterKwd::*;
620

            
621
2
    let mut rules = SectionRules::builder();
622
2
    rules.add(ANN_SOURCE.rule());
623
2
    rules.add(ANN_DOWNLOADED_AT.rule().args(1..));
624
2
    rules.add(ANN_PURPOSE.rule().args(1..));
625
2
    rules.add(ANN_UNRECOGNIZED.rule().may_repeat().obj_optional());
626
    // Unrecognized annotations are fine; anything else is an error in this
627
    // context.
628
2
    rules.reject_unrecognized();
629
2
    rules.build()
630
2
});
631
/// Rules for tokens that are allowed in the first part of a
632
/// router descriptor.
633
56
static ROUTER_HEADER_RULES: LazyLock<SectionRules<RouterKwd>> = LazyLock::new(|| {
634
    use RouterKwd::*;
635

            
636
56
    let mut rules = SectionRules::builder();
637
56
    rules.add(ROUTER.rule().required().args(5..));
638
56
    rules.add(IDENTITY_ED25519.rule().required().no_args().obj_required());
639
    // No other intervening tokens are permitted in the header.
640
56
    rules.reject_unrecognized();
641
56
    rules.build()
642
56
});
643
/// Rules for  tokens that are allowed in the first part of a
644
/// router descriptor.
645
56
static ROUTER_BODY_RULES: LazyLock<SectionRules<RouterKwd>> = LazyLock::new(|| {
646
    use RouterKwd::*;
647

            
648
56
    let mut rules = SectionRules::builder();
649
56
    rules.add(MASTER_KEY_ED25519.rule().required().args(1..));
650
56
    rules.add(PLATFORM.rule());
651
56
    rules.add(PUBLISHED.rule().required());
652
56
    rules.add(FINGERPRINT.rule());
653
56
    rules.add(UPTIME.rule().args(1..));
654
56
    rules.add(NTOR_ONION_KEY.rule().required().args(1..));
655
56
    rules.add(
656
56
        NTOR_ONION_KEY_CROSSCERT
657
56
            .rule()
658
56
            .required()
659
56
            .args(1..=1)
660
56
            .obj_required(),
661
    );
662
56
    rules.add(SIGNING_KEY.rule().no_args().required().obj_required());
663
56
    rules.add(POLICY.rule().may_repeat().args(1..));
664
56
    rules.add(IPV6_POLICY.rule().args(2..));
665
56
    rules.add(FAMILY.rule().args(1..));
666
56
    rules.add(FAMILY_CERT.rule().obj_required().may_repeat());
667
56
    rules.add(CACHES_EXTRA_INFO.rule().no_args());
668
56
    rules.add(OR_ADDRESS.rule().may_repeat().args(1..));
669
56
    rules.add(TUNNELLED_DIR_SERVER.rule());
670
56
    rules.add(PROTO.rule().required().args(1..));
671
56
    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
672
    // TODO: these aren't parsed yet.  Only authorities use them.
673
56
    {
674
56
        rules.add(BANDWIDTH.rule().required().args(3..));
675
56
        rules.add(BRIDGE_DISTRIBUTION_REQUEST.rule().args(1..));
676
56
        rules.add(HIBERNATING.rule().args(1..));
677
56
        rules.add(CONTACT.rule());
678
56
    }
679
    // TODO: this is ignored for now.
680
56
    {
681
56
        rules.add(EXTRA_INFO_DIGEST.rule().args(1..));
682
56
    }
683
56
    rules.build()
684
56
});
685

            
686
/// Rules for items that appear at the end of a router descriptor.
687
56
static ROUTER_SIG_RULES: LazyLock<SectionRules<RouterKwd>> = LazyLock::new(|| {
688
    use RouterKwd::*;
689

            
690
56
    let mut rules = SectionRules::builder();
691
56
    rules.add(ROUTER_SIG_ED25519.rule().required().args(1..));
692
56
    rules.add(ROUTER_SIGNATURE.rule().required().no_args().obj_required());
693
    // No intervening tokens are allowed in the footer.
694
56
    rules.reject_unrecognized();
695
56
    rules.build()
696
56
});
697

            
698
impl RouterAnnotation {
699
    /// Extract a single RouterAnnotation (possibly empty) from a reader.
700
8
    fn take_from_reader(reader: &mut NetDocReader<'_, RouterKwd>) -> Result<RouterAnnotation> {
701
        use RouterKwd::*;
702
20
        let mut items = reader.pause_at(|item| item.is_ok_with_non_annotation());
703

            
704
8
        let body = ROUTER_ANNOTATIONS.parse(&mut items)?;
705

            
706
6
        let source = body.maybe(ANN_SOURCE).args_as_str().map(String::from);
707
6
        let purpose = body.maybe(ANN_PURPOSE).args_as_str().map(String::from);
708
6
        let downloaded = body
709
6
            .maybe(ANN_DOWNLOADED_AT)
710
6
            .parse_args_as_str::<Iso8601TimeSp>()?
711
6
            .map(|t| t.into());
712
6
        Ok(RouterAnnotation {
713
6
            source,
714
6
            downloaded,
715
6
            purpose,
716
6
        })
717
8
    }
718
}
719

            
720
/// A parsed router descriptor whose signatures and/or validity times
721
/// may or may not be invalid.
722
pub type UncheckedRouterDesc = signed::SignatureGated<timed::TimeRangeBound<RouterDesc>>;
723

            
724
/// How long after its published time is a router descriptor officially
725
/// supposed to be usable?
726
const ROUTER_EXPIRY_SECONDS: u64 = 5 * 86400;
727

            
728
/// How long before its published time is a router descriptor usable?
729
// TODO(nickm): This valid doesn't match C tor, which only enforces this rule
730
// ("routers should not some from the future") at directory authorities, and
731
// there only enforces a 12-hour limit (`ROUTER_ALLOW_SKEW`).  Eventually we
732
// should probably harmonize these cutoffs.
733
const ROUTER_PRE_VALIDITY_SECONDS: u64 = 86400;
734

            
735
impl RouterDesc {
736
    /// Return a reference to this relay's RSA identity.
737
1298
    pub fn rsa_identity(&self) -> RsaIdentity {
738
1298
        self.signing_key.to_rsa_identity()
739
1298
    }
740

            
741
    /// Return a reference to this relay's Ed25519 identity.
742
2
    pub fn ed_identity(&self) -> &Ed25519Identity {
743
2
        &self
744
2
            .identity_ed25519
745
2
            .get()
746
2
            .expect("ed25519 identity cert should be verified")
747
2
            .id_ed25519
748
2
    }
749

            
750
    /// Return a reference to the list of subprotocol versions supported by this
751
    /// relay.
752
2
    pub fn protocols(&self) -> &tor_protover::Protocols {
753
2
        &self.proto
754
2
    }
755

            
756
    /// Return a reference to this relay's Ntor onion key.
757
2
    pub fn ntor_onion_key(&self) -> &ll::pk::curve25519::PublicKey {
758
2
        &self.ntor_onion_key.0
759
2
    }
760

            
761
    /// Return the publication
762
326
    pub fn published(&self) -> time::SystemTime {
763
326
        self.published.0
764
326
    }
765

            
766
    /// Return an iterator of every `SocketAddr` at which this descriptor says
767
    /// its relay can be reached.
768
2
    pub fn or_ports(&self) -> impl Iterator<Item = net::SocketAddr> + '_ {
769
2
        iter::once(net::SocketAddr::new(
770
2
            self.router.address.into(),
771
2
            self.router.orport,
772
        ))
773
2
        .chain(self.or_address.iter().copied())
774
2
    }
775

            
776
    /// Return the declared family of this descriptor.
777
    pub fn family(&self) -> Intern<RelayFamily> {
778
        Intern::clone(&self.family)
779
    }
780

            
781
    /// Return the authenticated family IDs of this descriptor.
782
2
    pub fn family_ids(&self) -> RelayFamilyIds {
783
2
        RelayFamilyIds::from_iter(
784
2
            self.family_cert
785
2
                .iter()
786
5
                .map(|cert| cert.get().expect("unverified family cert?"))
787
5
                .map(|cert| cert.family_ed25519.into()),
788
        )
789
2
    }
790

            
791
    /// Helper: tokenize `s`, and divide it into three validated sections.
792
2410
    fn parse_sections<'a>(
793
2410
        reader: &mut NetDocReader<'a, RouterKwd>,
794
2410
    ) -> Result<(
795
2410
        Section<'a, RouterKwd>,
796
2410
        Section<'a, RouterKwd>,
797
2410
        Section<'a, RouterKwd>,
798
2410
    )> {
799
        use RouterKwd::*;
800

            
801
        // Parse everything up through the header.
802
2410
        let header = ROUTER_HEADER_RULES.parse(
803
7069
            reader.pause_at(|item| item.is_ok_with_kwd_not_in(&[ROUTER, IDENTITY_ED25519])),
804
112
        )?;
805

            
806
        // Parse everything up to but not including the signature.
807
2298
        let body =
808
39167
            ROUTER_BODY_RULES.parse(reader.pause_at(|item| {
809
39110
                item.is_ok_with_kwd_in(&[ROUTER_SIGNATURE, ROUTER_SIG_ED25519])
810
39110
            }))?;
811

            
812
        // Parse the signature.
813
4667
        let sig = ROUTER_SIG_RULES.parse(reader.pause_at(|item| {
814
4610
            item.is_ok_with_annotation() || item.is_ok_with_kwd(ROUTER) || item.is_empty_line()
815
4610
        }))?;
816

            
817
2298
        Ok((header, body, sig))
818
2410
    }
819

            
820
    /// Try to parse `s` as a router descriptor.
821
    ///
822
    /// Does not actually check liveness or signatures; you need to do that
823
    /// yourself before you can do the output.
824
    ///
825
    /// The following fields are not parsed with the legacy parser and their
826
    /// default value is used instead.
827
    /// * [`RouterDescIntroItem::socksport`] in [`RouterDesc::router`]
828
    /// * [`RouterDesc::bandwidth`]
829
    /// * [`RouterDesc::or_address`]
830
    ///     * Extracts only the first IPv6 address.
831
    /// * [`RouterDesc::hibernating`]
832
    /// * [`RouterDesc::overload_general`]
833
    /// * [`RouterDesc::contact`]
834
    /// * [`RouterDesc::extra_info_digest`]
835
    /// * [`RouterDesc::hidden_service_dir`]
836
2404
    pub fn parse(s: &str) -> Result<UncheckedRouterDesc> {
837
2404
        let mut reader = crate::parse::tokenize::NetDocReader::new(s)?;
838
2417
        let result = Self::parse_internal(&mut reader).map_err(|e| e.within(s))?;
839
        // We permit empty lines at the end of router descriptors, since there's
840
        // a known issue in Tor relays that causes them to return them this way.
841
2274
        reader
842
2274
            .should_be_exhausted_but_for_empty_lines()
843
2274
            .map_err(|e| e.within(s))?;
844
2274
        Ok(result)
845
2404
    }
846

            
847
    /// Helper: parse a router descriptor from `s`.
848
    ///
849
    /// This function does the same as parse(), but returns errors based on
850
    /// byte-wise positions.  The parse() function converts such errors
851
    /// into line-and-byte positions.
852
2410
    fn parse_internal(r: &mut NetDocReader<'_, RouterKwd>) -> Result<UncheckedRouterDesc> {
853
        // TODO: This function is too long!  The little "paragraphs" here
854
        // that parse one item at a time should be made into sub-functions.
855
        use RouterKwd::*;
856

            
857
2410
        let s = r.str();
858
2410
        let (header, body, sig) = RouterDesc::parse_sections(r)?;
859

            
860
        // Unwrap should be safe because inline `required` call should return
861
        // `Error::MissingToken` if `ROUTER` is not `Ok`
862
        #[allow(clippy::unwrap_used)]
863
2298
        let start_offset = header.required(ROUTER)?.offset_in(s).unwrap();
864

            
865
        // ed25519 identity and signing key.
866
        //
867
        // Small digression: This is terrible.  We return a tuple containing
868
        // a KeyUnknownCert and an UncheckedCert.  This is because of a parse2
869
        // and legacy incongruence.  For parse2, we need the KeyUnknownCert
870
        // to properly include it into EmbeddedCert, whereas the legacy parser
871
        // will need an UncheckedCert because the verification chain is
872
        // performed at the end.  Because tor-cert's method all consume self,
873
        // we can not go backwards, meaning we have to store two separate
874
        // copies.  It is also not possible to do the conversion to
875
        // UncheckedCert later, because then we lose the error context returned
876
        // in EK::BadObjectVal if the signed-by extension is missing.
877
        //
878
2290
        let (ku_identity_cert, identity_cert, ed25519_signing_key) = {
879
2298
            let cert_tok = header.required(IDENTITY_ED25519)?;
880
            // Unwrap should be safe because above `required` call should
881
            // return `Error::MissingToken` if `IDENTITY_ED25519` is not `Ok`
882
            #[allow(clippy::unwrap_used)]
883
2298
            if cert_tok.offset_in(s).unwrap() < start_offset {
884
2
                return Err(EK::MisplacedToken
885
2
                    .with_msg("identity-ed25519")
886
2
                    .at_pos(cert_tok.pos()));
887
2296
            }
888
2296
            let ku_cert = cert_tok
889
2296
                .parse_obj::<UnvalidatedEdCert>("ED25519 CERT")?
890
2296
                .check_cert_type(tor_cert::CertType::IDENTITY_V_SIGNING)?
891
2296
                .into_unchecked();
892
2297
            let cert = ku_cert.clone().should_have_signing_key().map_err(|err| {
893
2
                EK::BadObjectVal
894
2
                    .err()
895
2
                    .with_source(err)
896
2
                    .at_pos(cert_tok.pos())
897
3
            })?;
898
2295
            let sk = *cert.peek_subject_key().as_ed25519().ok_or_else(|| {
899
2
                EK::BadObjectVal
900
2
                    .at_pos(cert_tok.pos())
901
2
                    .with_msg("wrong type for signing key in cert")
902
3
            })?;
903
2293
            let sk: ll::pk::ed25519::PublicKey = sk.try_into().map_err(|_| {
904
2
                EK::BadObjectVal
905
2
                    .at_pos(cert_tok.pos())
906
2
                    .with_msg("invalid ed25519 signing key")
907
3
            })?;
908
2290
            (ku_cert, cert, sk)
909
        };
910

            
911
        // master-key-ed25519: required, and should match certificate.
912
        #[allow(unexpected_cfgs)]
913
2288
        let ed25519_identity_key = {
914
2290
            let master_key_tok = body.required(MASTER_KEY_ED25519)?;
915
2290
            let ed_id: Ed25519Public = master_key_tok.parse_arg(0)?;
916
2290
            let ed_id: ll::pk::ed25519::Ed25519Identity = ed_id.into();
917
2290
            if ed_id != *identity_cert.peek_signing_key() {
918
                #[cfg(not(fuzzing))] // No feature here; never omit in production.
919
2
                return Err(EK::BadObjectVal
920
2
                    .at_pos(master_key_tok.pos())
921
2
                    .with_msg("master-key-ed25519 does not match key in identity-ed25519"));
922
2288
            }
923
2288
            ed_id
924
        };
925

            
926
        // Legacy RSA identity
927
2288
        let rsa_identity_key: ll::pk::rsa::PublicKey = body
928
2288
            .required(SIGNING_KEY)?
929
2288
            .parse_obj::<RsaPublicParse1Helper>("RSA PUBLIC KEY")?
930
2288
            .check_len_eq(1024)?
931
2288
            .check_exponent(65537)?
932
2288
            .into();
933
2288
        let rsa_identity = rsa_identity_key.to_rsa_identity();
934

            
935
2288
        let ed_sig = sig.required(ROUTER_SIG_ED25519)?;
936
2288
        let rsa_sig = sig.required(ROUTER_SIGNATURE)?;
937
        // Unwrap should be safe because above `required` calls should return
938
        // an `Error::MissingToken` if `ROUTER_...` is not `Ok`
939
        #[allow(clippy::unwrap_used)]
940
2288
        let ed_sig_pos = ed_sig.offset_in(s).unwrap();
941
        #[allow(clippy::unwrap_used)]
942
2288
        let rsa_sig_pos = rsa_sig.offset_in(s).unwrap();
943

            
944
2288
        if ed_sig_pos > rsa_sig_pos {
945
2
            return Err(EK::UnexpectedToken
946
2
                .with_msg(ROUTER_SIG_ED25519.to_str())
947
2
                .at_pos(ed_sig.pos()));
948
2286
        }
949

            
950
        // Extract ed25519 signature.
951
2286
        let ed_signature: ll::pk::ed25519::ValidatableEd25519Signature = {
952
2286
            let mut d = ll::d::Sha256::new();
953
2286
            d.update(&b"Tor router descriptor signature v1"[..]);
954
2286
            let signed_end = ed_sig_pos + b"router-sig-ed25519 ".len();
955
2286
            d.update(
956
2286
                s.get(start_offset..signed_end)
957
2286
                    .ok_or(internal!("chopped utf8"))?,
958
            );
959
2286
            let d = d.finalize();
960
2286
            let sig: [u8; 64] = ed_sig
961
2286
                .parse_arg::<B64>(0)?
962
2286
                .into_array()
963
2286
                .map_err(|_| EK::BadSignature.at_pos(ed_sig.pos()))?;
964
2286
            let sig = ll::pk::ed25519::Signature::from(sig);
965
2286
            ll::pk::ed25519::ValidatableEd25519Signature::new(ed25519_signing_key, sig, &d)
966
        };
967

            
968
        // Extract legacy RSA signature.
969
2286
        let rsa_signature: ll::pk::rsa::ValidatableRsaSignature = {
970
2286
            let mut d = ll::d::Sha1::new();
971
2286
            let signed_end = rsa_sig_pos + b"router-signature\n".len();
972
2286
            d.update(
973
2286
                s.get(start_offset..signed_end)
974
2286
                    .ok_or(internal!("chopped utf8"))?,
975
            );
976
2286
            let d = d.finalize();
977
2286
            let sig = rsa_sig.obj("SIGNATURE")?;
978
            // TODO: we need to accept prefixes here. COMPAT BLOCKER.
979

            
980
2286
            ll::pk::rsa::ValidatableRsaSignature::new(&rsa_identity_key, &sig, &d)
981
        };
982

            
983
        // router nickname ipv4addr orport socksport dirport
984
2286
        let (nickname, ipv4addr, orport, dirport) = {
985
2286
            let rtrline = header.required(ROUTER)?;
986
            (
987
2286
                rtrline.required_arg(0)?.parse::<Nickname>().map_err(|e| {
988
                    EK::BadArgument
989
                        .with_msg(e.to_string())
990
                        .at_pos(rtrline.pos())
991
                })?,
992
2286
                rtrline.parse_arg::<net::Ipv4Addr>(1)?,
993
2286
                rtrline.parse_arg(2)?,
994
                // Skipping socksport.
995
2286
                rtrline.parse_arg(4)?,
996
            )
997
        };
998

            
999
        // uptime
2286
        let uptime = body.maybe(UPTIME).parse_arg(0)?;
        // published time.
2286
        let published = body
2286
            .required(PUBLISHED)?
2286
            .args_as_str()
2286
            .parse::<Iso8601TimeSp>()?;
        // ntor key
2286
        let ntor_onion_key: Curve25519Public = body.required(NTOR_ONION_KEY)?.parse_arg(0)?;
        // ntor crosscert
2282
        let (cc_sig, cc_expiry, cc_cert) = {
2286
            let cc = body.required(NTOR_ONION_KEY_CROSSCERT)?;
2286
            let sign: u8 = cc.parse_arg(0)?;
2286
            if sign != 0 && sign != 1 {
4
                return Err(EK::BadArgument.at_pos(cc.arg_pos(0)).with_msg("not 0 or 1"));
2282
            }
2282
            let ntor_as_ed: ll::pk::ed25519::PublicKey =
2282
                ll::pk::keymanip::convert_curve25519_to_ed25519_public(&ntor_onion_key.0, sign)
2282
                    .ok_or_else(|| {
                        EK::BadArgument
                            .at_pos(cc.pos())
                            .with_msg("Uncheckable crosscert")
                    })?;
2282
            let cert = cc
2282
                .parse_obj::<UnvalidatedEdCert>("ED25519 CERT")?
2282
                .into_unchecked();
2282
            let (_, sig, expiry) = Ed25519NtorCrossCert::verify_inner(
2282
                ntor_as_ed.into(),
2282
                ed25519_identity_key,
2282
                cert.clone(),
            )
2282
            .map_err(|_| EK::BadSignature.err())?;
2282
            let cert = NtorOnionKeyCrossCert {
2282
                bit: NumericBoolean(sign != 0),
2282
                // Okay to call because we added the signature to the batch.
2282
                cert: EmbeddedCert::new(Ed25519NtorCrossCert::dangerous_new_unverified(), cert),
2282
            };
2282
            (sig, expiry, cert)
        };
        // List of subprotocol versions
2282
        let proto = {
2282
            let proto_tok = body.required(PROTO)?;
2282
            proto_tok
2282
                .args_as_str()
2282
                .parse::<tor_protover::Protocols>()
2282
                .map_err(|e| EK::BadArgument.at_pos(proto_tok.pos()).with_source(e))?
        };
        // tunneled-dir-server
2282
        let is_dircache = ((dirport != 0) || body.get(TUNNELLED_DIR_SERVER).is_some())
2282
            .then_some(ItemPresent::default());
        // caches-extra-info
2283
        let is_extrainfo_cache = body.get(CACHES_EXTRA_INFO).map(|_| ItemPresent::default());
        // fingerprint: check for consistency with RSA identity.
2282
        if let Some(fp_tok) = body.get(FINGERPRINT) {
2282
            let fp: RsaIdentity = fp_tok.args_as_str().parse::<SpFingerprint>()?.into();
2282
            if fp != rsa_identity {
4
                return Err(EK::BadArgument
4
                    .at_pos(fp_tok.pos())
4
                    .with_msg("fingerprint does not match RSA identity"));
2278
            }
        }
        // Family
2278
        let family = {
2278
            let mut family = body
2278
                .maybe(FAMILY)
2278
                .parse_args_as_str::<RelayFamily>()?
2278
                .unwrap_or_else(RelayFamily::new);
2278
            if !family.is_empty() {
4
                // If this family is nonempty, we add our own RSA id to it, on
4
                // the theory that doing so will improve the odds of having a
4
                // canonical family shared by all of the members of this family.
4
                // If the family is empty, there's no point in adding our own ID
4
                // to it, and doing so would only waste memory.
4
                family.push(rsa_identity);
2274
            }
2278
            family.intern()
        };
        // Family ids (for "happy families")
        //
        // Unfortunately we have to store this as a tuple of KeyUnknownCert and
        // UncheckedCert due to a parse2/legacy incongruence.  parse2 requires
        // KeyUnknownCert for EmbeddedCert whereas the legacy parser needs
        // descendants of it obtained by passing it irreversibly through the
        // tor_cert verification chain.
2278
        let family_certs = body
2278
            .slice(FAMILY_CERT)
2278
            .iter()
2280
            .map(|ent| {
4
                let ku = ent
4
                    .parse_obj::<UnvalidatedEdCert>("FAMILY CERT")?
4
                    .check_cert_type(CertType::FAMILY_V_IDENTITY)?
4
                    .check_subject_key_is(identity_cert.peek_signing_key())?
4
                    .into_unchecked();
4
                let unchecked = ku.clone().should_have_signing_key().map_err(|e| {
                    EK::BadObjectVal
                        .with_msg("missing public key")
                        .at_pos(ent.pos())
                        .with_source(e)
                })?;
4
                Ok((ku, unchecked))
4
            })
2278
            .collect::<Result<Vec<_>>>()?;
        // or-address
        // Extract at most one ipv6 address from the list.  It's not great,
        // but it's what the legacy parser does.
2278
        let mut ipv6addr = Vec::with_capacity(1);
2278
        for tok in body.slice(OR_ADDRESS) {
6
            if let Ok(net::SocketAddr::V6(a)) = tok.parse_arg::<net::SocketAddr>(0) {
6
                ipv6addr.push(a.into());
6
                break;
            }
            // We skip over unparsable addresses. Is that right?
        }
        // platform
2278
        let platform = body.maybe(PLATFORM).parse_args_as_str::<RelayPlatform>()?;
        // ipv4_policy
2278
        let ipv4_policy = {
2278
            let mut pol = AddrPolicy::new();
2280
            for ruletok in body.slice(POLICY).iter() {
2280
                let accept = match ruletok.kwd_str() {
2280
                    "accept" => RuleKind::Accept,
2278
                    "reject" => RuleKind::Reject,
                    _ => {
                        return Err(Error::from(internal!(
                            "tried to parse a strange line as a policy"
                        ))
                        .at_pos(ruletok.pos()));
                    }
                };
2280
                let pat: AddrPortPattern = ruletok
2280
                    .args_as_str()
2280
                    .parse()
2280
                    .map_err(|e| EK::BadPolicy.at_pos(ruletok.pos()).with_source(e))?;
2280
                pol.push(accept, pat);
            }
2278
            pol
        };
        // ipv6 policy
2278
        let ipv6_policy = match body.get(IPV6_POLICY) {
2
            Some(p) => p
2
                .args_as_str()
2
                .parse()
3
                .map_err(|e| EK::BadPolicy.at_pos(p.pos()).with_source(e))?,
            // Unwrap is safe here because str is not empty
            #[allow(clippy::unwrap_used)]
2276
            None => "reject 1-65535".parse::<PortPolicy>().unwrap(),
        };
        // Now we're going to collect signatures and expiration times.
2276
        let (identity_cert, identity_sig) = identity_cert.dangerously_split().map_err(|err| {
            EK::BadObjectVal
                .with_msg("missing public key")
                .with_source(err)
        })?;
2276
        let mut signatures: Vec<Box<dyn ll::pk::ValidatableSignature>> = vec![
2276
            Box::new(rsa_signature),
2276
            Box::new(ed_signature),
2276
            Box::new(identity_sig),
2276
            Box::new(cc_sig),
        ];
2276
        let identity_cert = identity_cert.dangerously_assume_timely();
2276
        let mut expirations = vec![
2276
            published
2276
                .0
2276
                .saturating_add(time::Duration::new(ROUTER_EXPIRY_SECONDS, 0)),
2276
            identity_cert.expiry(),
2276
            cc_expiry,
        ];
        // As outlined above, we have to do this ... :/
        //
        // Composing the verified part of the EmbeddedCert by just extracting
        // the key alone is OK because it gets checked at the end anyways
        // due to the push to signatures and expirations.
2276
        let mut embedded_family_certs = Vec::with_capacity(family_certs.len());
2276
        for (ku_cert, cert) in family_certs {
4
            let family_ed25519 = *cert.peek_signing_key();
4
            let (inner, sig) = cert.dangerously_split().map_err(into_internal!(
                "Missing a public key that was previously there."
            ))?;
4
            let embedded_cert = EmbeddedCert::new(Ed25519FamilyCert { family_ed25519 }, ku_cert);
4
            signatures.push(Box::new(sig));
4
            expirations.push(inner.dangerously_assume_timely().expiry());
4
            embedded_family_certs.push(embedded_cert);
        }
        // Unwrap is safe here because `expirations` array is not empty
        #[allow(clippy::unwrap_used)]
2276
        let expiry = *expirations.iter().min().unwrap();
2276
        let start_time = published
2276
            .0
2276
            .saturating_sub(time::Duration::new(ROUTER_PRE_VALIDITY_SECONDS, 0));
2276
        let desc = RouterDesc {
2276
            router: RouterDescIntroItem {
2276
                nickname,
2276
                address: ipv4addr,
2276
                orport,
2276
                socksport: 0,
2276
                dirport,
2276
            },
2276
            identity_ed25519: EmbeddedCert::new(
2276
                Ed25519IdentityCert {
2276
                    id_ed25519: ed25519_identity_key,
2276
                    sign_ed25519: ed25519_signing_key.into(),
2276
                },
2276
                ku_identity_cert,
2276
            ),
2276
            master_key_ed25519: ed25519_identity_key.into(),
2276
            bandwidth: Default::default(),
2276
            platform,
2276
            published,
2276
            fingerprint: Some(rsa_identity.into()),
2276
            hibernating: Default::default(),
2276
            uptime,
2276
            ntor_onion_key,
2276
            ntor_onion_key_crosscert: cc_cert,
2276
            signing_key: rsa_identity_key,
2276
            ipv4_policy,
2276
            ipv6_policy: ipv6_policy.intern(),
2276
            overload_general: Default::default(),
2276
            contact: Default::default(),
2276
            family,
2276
            family_cert: embedded_family_certs.into(),
2276
            caches_extra_info: is_extrainfo_cache,
2276
            extra_info_digest: Default::default(),
2276
            hidden_service_dir: Default::default(),
2276
            or_address: ipv6addr,
2276
            tunnelled_dir_server: is_dircache,
2276
            proto,
2276
            __non_exhaustive: (),
2276
        };
2276
        let time_gated = timed::TimeRangeBound::new(desc, start_time..expiry);
2276
        let sig_gated = signed::SignatureGated::new(time_gated, signatures);
2276
        Ok(sig_gated)
2410
    }
}
/// An iterator that parses one or more (possibly annotated
/// router descriptors from a string.
//
// TODO: This is largely copy-pasted from MicrodescReader. Can/should they
// be merged?
pub struct RouterReader<'a> {
    /// True iff we accept annotations
    annotated: bool,
    /// Reader that we're extracting items from.
    reader: NetDocReader<'a, RouterKwd>,
}
/// Skip this reader forward until the next thing it reads looks like the
/// start of a router descriptor.
///
/// Used to recover from errors.
6
fn advance_to_next_routerdesc(reader: &mut NetDocReader<'_, RouterKwd>, annotated: bool) {
    use RouterKwd::*;
    loop {
6
        let item = reader.peek();
4
        match item {
4
            Some(Ok(t)) => {
4
                let kwd = t.kwd();
4
                if (annotated && kwd.is_annotation()) || kwd == ROUTER {
4
                    return;
                }
            }
            Some(Err(_)) => {
                // Skip over broken tokens.
            }
            None => {
2
                return;
            }
        }
        let _ = reader.next();
    }
6
}
impl<'a> RouterReader<'a> {
    /// Construct a RouterReader to take router descriptors from a string.
2
    pub fn new(s: &'a str, allow: &AllowAnnotations) -> Result<Self> {
2
        let reader = NetDocReader::new(s)?;
2
        let annotated = allow == &AllowAnnotations::AnnotationsAllowed;
2
        Ok(RouterReader { annotated, reader })
2
    }
    /// Extract an annotation from this reader.
8
    fn take_annotation(&mut self) -> Result<RouterAnnotation> {
8
        if self.annotated {
8
            RouterAnnotation::take_from_reader(&mut self.reader)
        } else {
            Ok(RouterAnnotation::default())
        }
8
    }
    /// Extract an annotated router descriptor from this reader
    ///
    /// (internal helper; does not clean up on failures.)
8
    fn take_annotated_routerdesc_raw(&mut self) -> Result<AnnotatedRouterDesc> {
8
        let ann = self.take_annotation()?;
6
        let router = RouterDesc::parse_internal(&mut self.reader)?;
2
        Ok(AnnotatedRouterDesc { ann, router })
8
    }
    /// Extract an annotated router descriptor from this reader
    ///
    /// Ensure that at least one token is consumed
8
    fn take_annotated_routerdesc(&mut self) -> Result<AnnotatedRouterDesc> {
8
        let pos_orig = self.reader.pos();
8
        let result = self.take_annotated_routerdesc_raw();
8
        if result.is_err() {
6
            if self.reader.pos() == pos_orig {
                // No tokens were consumed from the reader.  We need
                // to drop at least one token to ensure we aren't in
                // an infinite loop.
                //
                // (This might not be able to happen, but it's easier to
                // explicitly catch this case than it is to prove that
                // it's impossible.)
                let _ = self.reader.next();
6
            }
6
            advance_to_next_routerdesc(&mut self.reader, self.annotated);
2
        }
8
        result
8
    }
}
impl<'a> Iterator for RouterReader<'a> {
    type Item = Result<AnnotatedRouterDesc>;
10
    fn next(&mut self) -> Option<Self::Item> {
        // Is there a next token? If not, we're done.
10
        self.reader.peek()?;
        Some(
8
            self.take_annotated_routerdesc()
11
                .map_err(|e| e.within(self.reader.str())),
        )
10
    }
}
#[cfg(test)]
mod test {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_time_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    #![allow(clippy::string_slice)] // See arti#2571
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
    use std::{net::Ipv4Addr, str::FromStr, time::Duration};
    use crate::{
        encode::{NetdocEncodable, NetdocEncoder},
        parse2::{self, NetdocParseableUnverified, ParseInput},
    };
    use tor_basic_utils::test_rng::testing_rng;
    use tor_checkable::TimeValidityError;
    use tor_llcrypto::pk::{curve25519, ed25519::Ed25519PublicKey, rsa};
    use super::*;
    const TESTDATA: &str = include_str!("../../testdata/routerdesc1.txt");
    const TESTDATA2: &str = include_str!("../../testdata/routerdesc2.txt");
    // Generated with a patched C tor to include "happy family" IDs.
    const TESTDATA3: &str = include_str!("../../testdata/routerdesc3.txt");
    fn read_bad(fname: &str) -> String {
        use std::fs;
        use std::path::PathBuf;
        let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path.push("testdata");
        path.push("bad-routerdesc");
        path.push(fname);
        fs::read_to_string(path).unwrap()
    }
    #[test]
    fn parse_arbitrary() -> Result<()> {
        use std::str::FromStr;
        use tor_checkable::{SelfSigned, TimeBound};
        let rd = RouterDesc::parse(TESTDATA)?
            .check_signature()?
            .dangerously_assume_timely();
        assert_eq!(rd.router.nickname.as_str(), "Akka");
        assert_eq!(rd.router.orport, 443);
        assert_eq!(rd.router.dirport, 0);
        assert_eq!(rd.uptime, Some(1036923));
        assert_eq!(
            rd.family.as_ref(),
            &RelayFamily::from_str(
                "$303509ab910ef207b7438c27435c4a2fd579f1b1 \
                 $56927e61b51e6f363fb55498150a6ddfcf7077f2"
            )
            .unwrap()
        );
        assert_eq!(
            rd.rsa_identity().to_string(),
            "$56927e61b51e6f363fb55498150a6ddfcf7077f2"
        );
        assert_eq!(
            rd.ed_identity().to_string(),
            "CVTjf1oeaL616hH+1+UvYZ8OgkwF3z7UMITvJzm5r7A"
        );
        assert_eq!(
            rd.protocols().to_string(),
            "Cons=1-2 Desc=1-2 DirCache=2 FlowCtrl=1-2 HSDir=2 \
             HSIntro=4-5 HSRend=1-2 Link=1-5 LinkAuth=1,3 Microdesc=1-2 \
             Padding=2 Relay=1-4"
        );
        assert_eq!(
            hex::encode(rd.ntor_onion_key().to_bytes()),
            "329b3b52991613392e35d1a821dd6753e1210458ecc3337f7b7d39bfcf5da273"
        );
        assert_eq!(
            rd.published(),
            humantime::parse_rfc3339("2022-11-14T19:58:52Z").unwrap()
        );
        assert_eq!(
            rd.or_ports().collect::<Vec<_>>(),
            vec![
                "95.216.33.58:443".parse().unwrap(),
                "[2a01:4f9:2a:2145::2]:443".parse().unwrap(),
            ]
        );
        Ok(())
    }
    #[test]
    fn parse_no_tap_key() -> Result<()> {
        use tor_checkable::{SelfSigned, TimeBound};
        let _rd = RouterDesc::parse(TESTDATA2)?
            .check_signature()?
            .dangerously_assume_timely();
        Ok(())
    }
    #[test]
    fn test_bad() {
        use crate::Pos;
        use crate::types::policy::PolicyError;
        fn check(fname: &str, e: &Error) {
            let text = read_bad(fname);
            let rd = RouterDesc::parse(&text);
            assert!(rd.is_err());
            assert_eq!(&rd.err().unwrap(), e);
        }
        check(
            "bad-sig-order",
            &EK::UnexpectedToken
                .with_msg("router-sig-ed25519")
                .at_pos(Pos::from_line(50, 1)),
        );
        check(
            "bad-start1",
            &EK::MisplacedToken
                .with_msg("identity-ed25519")
                .at_pos(Pos::from_line(1, 1)),
        );
        check("bad-start2", &EK::MissingToken.with_msg("identity-ed25519"));
        check(
            "mismatched-fp",
            &EK::BadArgument
                .at_pos(Pos::from_line(12, 1))
                .with_msg("fingerprint does not match RSA identity"),
        );
        check("no-ed-sk", &EK::MissingToken.with_msg("identity-ed25519"));
        check(
            "bad-cc-sign",
            &EK::BadArgument
                .at_pos(Pos::from_line(34, 26))
                .with_msg("not 0 or 1"),
        );
        check(
            "bad-ipv6policy",
            &EK::BadPolicy
                .at_pos(Pos::from_line(43, 1))
                .with_source(PolicyError::InvalidPolicy),
        );
        check(
            "no-ed-id-key-in-cert",
            &EK::BadObjectVal
                .at_pos(Pos::from_line(2, 1))
                .with_source(tor_cert::CertError::MissingPubKey),
        );
        check(
            "non-ed-sk-in-cert",
            &EK::BadObjectVal
                .at_pos(Pos::from_line(2, 1))
                .with_msg("wrong type for signing key in cert"),
        );
        check(
            "bad-ed-sk-in-cert",
            &EK::BadObjectVal
                .at_pos(Pos::from_line(2, 1))
                .with_msg("invalid ed25519 signing key"),
        );
        check(
            "mismatched-ed-sk-in-cert",
            &EK::BadObjectVal
                .at_pos(Pos::from_line(8, 1))
                .with_msg("master-key-ed25519 does not match key in identity-ed25519"),
        );
    }
    #[test]
    fn parse_multiple_annotated() {
        use crate::AllowAnnotations;
        let mut s = read_bad("bad-cc-sign");
        s += "\
@uploaded-at 2020-09-26 18:15:41
@source \"127.0.0.1\"
";
        s += TESTDATA;
        s += "\
@uploaded-at 2020-09-26 18:15:41
@source \"127.0.0.1\"
";
        s += &read_bad("mismatched-fp");
        let rd = RouterReader::new(&s, &AllowAnnotations::AnnotationsAllowed).unwrap();
        let v: Vec<_> = rd.collect();
        assert!(v[0].is_err());
        assert!(v[1].is_ok());
        assert_eq!(
            v[1].as_ref().unwrap().ann.source,
            Some("\"127.0.0.1\"".to_string())
        );
        assert!(v[2].is_err());
    }
    #[test]
    fn test_platform() {
        let tests = [
            // Test with platform.
            (
                "Tor 0.4.4.4-alpha on a flying bison",
                RelayPlatform::Tor(
                    "0.4.4.4-alpha".parse().unwrap(),
                    Some("a flying bison".to_string()),
                ),
            ),
            // Test without platform but potentially weird spacing.
            (
                "Tor 0.4.4.4-alpha on",
                RelayPlatform::Tor("0.4.4.4-alpha".parse().unwrap(), None),
            ),
            (
                "Tor 0.4.4.4-alpha ",
                RelayPlatform::Tor("0.4.4.4-alpha".parse().unwrap(), None),
            ),
            (
                "Tor 0.4.4.4-alpha",
                RelayPlatform::Tor("0.4.4.4-alpha".parse().unwrap(), None),
            ),
            // Test other.
            ("arti 0.0.0", RelayPlatform::Other("arti 0.0.0".to_string())),
        ];
        for (input, output) in tests {
            assert_eq!(input.parse::<RelayPlatform>().unwrap(), output);
            // Round-trip test with input stripped of " on" suffix and trimmed.
            // Otherwise we cannot really make this work because certain inputs
            // contain redundant data on purpose.
            let input = input.strip_suffix(" on").unwrap_or(input);
            let input = input.trim();
            assert_eq!(output.to_string(), input);
        }
    }
    #[test]
    fn test_family_ids() -> Result<()> {
        use tor_checkable::{SelfSigned, TimeBound};
        let rd = RouterDesc::parse(TESTDATA3)?
            .check_signature()?
            .dangerously_assume_timely();
        assert_eq!(
            rd.family_ids().as_ref(),
            &[
                "ed25519:7sToQRuge1bU2hS0CG0ViMndc4m82JhO4B4kdrQey80"
                    .parse()
                    .unwrap(),
                "ed25519:szHUS3ItRd9uk85b1UVnOZx1gg4B0266jCpbuIMNjcM"
                    .parse()
                    .unwrap(),
            ]
        );
        Ok(())
    }
    /// Simple decoding and round-trip encoding for "normal" router descriptors.
    ///
    /// In other words: No edge cases and such.
    #[test]
    fn test_parse2_simple() {
        let input = ParseInput::new(
            include_str!("../../testdata2/cached-descriptors.new"),
            "cached-descriptors.new",
        );
        let rd = parse2::parse_netdoc_multiple::<RouterDescUnverified>(&input)
            .unwrap()
            .into_iter()
            .map(|rd| {
                rd.clone().verify().unwrap();
                rd.unwrap_unverified()
            })
            .map(|(body, sig)| (body, sig.sigs))
            .collect::<Vec<(RouterDesc, RouterDescSignatures)>>();
        assert_eq!(rd.len(), 20);
        assert_eq!(
            rd[0].0.router,
            RouterDescIntroItem {
                nickname: "test002a".parse().unwrap(),
                address: net::Ipv4Addr::LOCALHOST,
                orport: 5102,
                socksport: 0,
                dirport: 7102
            }
        );
        assert_eq!(
            rd[0].0.fingerprint.unwrap(),
            "257D 06F0 360B B224 6388 724F 109E C089 5A1D 41FB"
                .parse()
                .unwrap()
        );
        // Round-trip encoding by verifying that decoding it equals the original.
        // This is the best we can get as the current encoder is not bug for
        // bug compatible with the CTor one (i.e. absence of TAP and different
        // order), so this is the closest we can get.
        //
        // Unfortunately, we cannot verify the re-encoded signatures, because
        // the re-encoded body misses the TAP related fields which are accounted
        // for in the signature however.
        let mut out = NetdocEncoder::new();
        for (body, sig) in &rd {
            body.encode_unsigned(&mut out).unwrap();
            sig.encode_unsigned(&mut out).unwrap();
        }
        let out = out.finish().unwrap();
        let input2 = ParseInput::new(out.as_str(), "<router descriptor encoding>");
        let rd2 = parse2::parse_netdoc_multiple::<RouterDescUnverified>(&input2)
            .unwrap()
            .into_iter()
            .map(|rd| rd.unwrap_unverified())
            .map(|(body, sig)| (body, sig.sigs))
            .collect::<Vec<(RouterDesc, _)>>();
        assert_eq!(rd, rd2);
    }
    /// Very bad encode and sign method for router descriptors.
    // TODO: Replace with proper one, once it exists
    fn rd_encode_sign(doc: &RouterDesc, rsa: &rsa::KeyPair, ed25519: &ed25519::Keypair) -> String {
        /// Helper for writing out router-sig-ed25519.
        #[derive(Deftly)]
        #[derive_deftly(NetdocEncodable)]
        struct Ed25519Writer {
            router_sig_ed25519: RouterSigEd25519,
        }
        /// Helper for writing out router-signature.
        #[derive(Deftly)]
        #[derive_deftly(NetdocEncodable)]
        struct RsaWriter {
            router_signature: RouterSignature,
        }
        // Add the router-sig-ed25519 signature.
        let mut out = NetdocEncoder::new();
        doc.encode_unsigned(&mut out).unwrap();
        Ed25519Writer {
            router_sig_ed25519: RouterSigEd25519::new_sign_netdoc(
                ed25519,
                &out,
                "router-sig-ed25519",
            )
            .unwrap(),
        }
        .encode_unsigned(&mut out)
        .unwrap();
        // Add the router-signature signature.
        RsaWriter {
            router_signature: RouterSignature(
                RsaSha1Signature::new_sign_netdoc(rsa, &out, "router-signature")
                    .unwrap()
                    .signature,
            ),
        }
        .encode_unsigned(&mut out)
        .unwrap();
        out.finish().unwrap()
    }
    /// Test for various succeeding and failing verifications.
    #[test]
    fn test_verify() {
        // Generate keys we will use later.
        let rng = &mut testing_rng();
        let rsa_id = rsa::KeyPair::generate(rng).unwrap();
        let ed25519_id = ed25519::Keypair::generate(rng);
        let ed25519_sign = ed25519::Keypair::generate(rng);
        let curve25519_ntor = curve25519::StaticSecret::random_from_rng(&mut *rng);
        let curve25519_ntor = curve25519::StaticKeypair {
            secret: curve25519_ntor.clone(),
            public: (&curve25519_ntor).into(),
        };
        let ed25519_ntor = tor_llcrypto::pk::keymanip::convert_curve25519_to_ed25519_private(
            &curve25519_ntor.secret,
        )
        .unwrap();
        // Values arbitrarily chosen for expirations.
        let too_early = Iso8601TimeSp::from_str("2026-05-01 03:00:00").unwrap().0;
        let published = Iso8601TimeSp::from_str("2026-06-01 03:00:00").unwrap().0;
        let now = Iso8601TimeSp::from_str("2026-06-10 15:30:12").unwrap().0;
        let expiration = Iso8601TimeSp::from_str("2026-06-20 03:00:00").unwrap().0;
        let expired = expiration + Duration::from_secs(60 * 60 * 24);
        // Very boilerplatey construction of a router descriptor.
        // TODO: Probably best to use constructor logic here.
        let mut rd = RouterDesc {
            router: RouterDescIntroItem {
                nickname: "foo".parse().unwrap(),
                address: Ipv4Addr::LOCALHOST,
                orport: 9000,
                socksport: 0,
                dirport: 0,
            },
            identity_ed25519: Ed25519IdentityCert::new_signed(
                &ed25519_id,
                Ed25519Identity::from(ed25519_sign.public_key()),
                expiration,
            )
            .unwrap(),
            master_key_ed25519: Ed25519Identity::from(ed25519_id.public_key()).into(),
            bandwidth: Bandwidth {
                average: 0,
                burst: 0,
                observed: 0,
            },
            platform: None,
            published: published.into(),
            fingerprint: Some(rsa_id.to_public_key().to_rsa_identity().into()),
            hibernating: NumericBoolean(false),
            uptime: None,
            ntor_onion_key: Curve25519Public(curve25519_ntor.public),
            ntor_onion_key_crosscert: NtorOnionKeyCrossCert {
                bit: NumericBoolean(ed25519_ntor.1 == 1),
                cert: Ed25519NtorCrossCert::new_signed(
                    &ed25519_ntor.0,
                    ed25519_id.public_key().into(),
                    expiration,
                )
                .unwrap(),
            },
            signing_key: rsa_id.to_public_key(),
            ipv4_policy: AddrPolicy::default(),
            ipv6_policy: Default::default(),
            overload_general: None,
            contact: None,
            family: Default::default(),
            family_cert: Default::default(),
            caches_extra_info: Some(Default::default()),
            extra_info_digest: None,
            hidden_service_dir: Some(Default::default()),
            or_address: Default::default(),
            tunnelled_dir_server: Some(Default::default()),
            proto: tor_protover::Protocols::new(),
            __non_exhaustive: (),
        };
        let rd_original = rd.clone();
        let verify =
            |rd: &RouterDesc| -> std::result::Result<TimeRangeBound<RouterDesc>, VerifyFailed> {
                let encoded = rd_encode_sign(rd, &rsa_id, &ed25519_sign);
                let decoded = parse2::parse_netdoc::<RouterDescUnverified>(&ParseInput::new(
                    &encoded,
                    "<test_invalid>",
                ))
                .unwrap();
                decoded.verify()
            };
        // Test valid and invalid timestamps.
        assert_eq!(
            verify(&rd).unwrap().if_valid_at(&too_early).unwrap_err(),
            TimeValidityError::NotYetValid(published.duration_since(too_early).unwrap())
        );
        verify(&rd).unwrap().if_valid_at(&published).unwrap();
        // This is our good/"everything is working" test
        verify(&rd).unwrap().if_valid_at(&now).unwrap();
        verify(&rd).unwrap().if_valid_at(&expiration).unwrap();
        assert_eq!(
            verify(&rd).unwrap().if_valid_at(&expired).unwrap_err(),
            TimeValidityError::Expired(expired.duration_since(expiration).unwrap())
        );
        // Let's make the certificate inconsistent by changing the master key.
        rd.master_key_ed25519 = Ed25519Public(Ed25519Identity::from([0x12; 32]));
        assert_eq!(verify(&rd).unwrap_err(), VerifyFailed::Inconsistent);
        rd = rd_original.clone();
        // Set the published to expired (weird on many levels).
        rd.published = expired.into();
        assert_eq!(
            verify(&rd).unwrap().if_valid_at(&now).unwrap_err(),
            TimeValidityError::NotYetValid(expired.duration_since(now).unwrap())
        );
        rd = rd_original.clone();
        // Have an inconsistent fingerprint.
        let other_rsa_key = rsa::KeyPair::generate(rng).unwrap();
        rd.fingerprint = Some(other_rsa_key.to_public_key().to_rsa_identity().into());
        assert_eq!(verify(&rd).unwrap_err(), VerifyFailed::Inconsistent);
        // It should fail with a different error if we change the signing key.
        // (No longer inconsistent but simply not validly signed)
        rd.signing_key = other_rsa_key.to_public_key();
        assert_eq!(verify(&rd).unwrap_err(), VerifyFailed::VerifyFailed);
        // It should work again if we set it to None.
        rd.signing_key = rd_original.signing_key.clone();
        rd.fingerprint = None;
        verify(&rd).unwrap().if_valid_at(&now).unwrap();
        rd = rd_original.clone();
        // If we change the ntor-onion-key, the crosscert verification will fail.
        // We must generate a valid random key here because otherwise, decompress
        // will fail.
        let other_curve25519 = curve25519::StaticSecret::random_from_rng(&mut *rng);
        let other_curve25519 = (&other_curve25519).into();
        rd.ntor_onion_key = Curve25519Public(other_curve25519);
        assert_eq!(verify(&rd).unwrap_err(), VerifyFailed::VerifyFailed);
        rd = rd_original.clone();
        // Testing for a signature key of the wrong size is hard because
        // tor-llcrypto makes it purposely hard to generate key sizes other
        // than 1024 bit.
        // TODO: Test family certificates.
        // Violate the outer ed25519 signatures, which can be done by swapping
        // the signing key to something else.
        let different_ed25519_sign = ed25519::Keypair::generate(rng);
        rd.identity_ed25519 = Ed25519IdentityCert::new_signed(
            &ed25519_id,
            Ed25519Identity::from(different_ed25519_sign.public_key()),
            expiration,
        )
        .unwrap();
        assert_eq!(verify(&rd).unwrap_err(), VerifyFailed::VerifyFailed);
        rd = rd_original.clone();
        // Violate the outer RSA signature by swapping the signing key and
        // "disabling" the fingerprint.
        let different_rsa_id = rsa::KeyPair::generate(rng).unwrap();
        rd.signing_key = different_rsa_id.to_public_key();
        rd.fingerprint = None;
        assert_eq!(verify(&rd).unwrap_err(), VerifyFailed::VerifyFailed);
    }
    #[test]
    fn ntor_onion_key_cross_cert() {
        // Dummy helper for parsing a subset of a router desc.
        #[derive(Debug, Deftly)]
        #[derive_deftly(NetdocParseable)]
        #[allow(unused)]
        struct TestDoc {
            /// Intro item.
            router: RouterDescIntroItem,
            /// Timestamp used for `now` in certificate validation.
            #[deftly(netdoc(single_arg))]
            published: Iso8601TimeSp,
            /// Required to ensure certified key of the crosscert.
            #[deftly(netdoc(single_arg))]
            master_key_ed25519: Ed25519Public,
            /// Required to obtain the key signing the crosscert.
            #[deftly(netdoc(single_arg))]
            ntor_onion_key: Curve25519Public,
            /// The actual crosscert.
            ntor_onion_key_crosscert: NtorOnionKeyCrossCert,
        }
        impl TestDoc {
            // Quick verify helper.
            fn verify(&self, now: time::SystemTime) {
                Ed25519NtorCrossCert::verify(
                    // Converts X25519 to Ed25519.
                    tor_llcrypto::pk::keymanip::convert_curve25519_to_ed25519_public(
                        &self.ntor_onion_key.0,
                        self.ntor_onion_key_crosscert.bit.0.into(),
                    )
                    .unwrap()
                    .into(),
                    self.master_key_ed25519.0,
                    self.ntor_onion_key_crosscert.cert.raw_unverified().clone(),
                )
                .unwrap()
                .check_valid_at(&now)
                .unwrap();
            }
        }
        let descs = include_str!("../../testdata2/cached-descriptors.new");
        let descs = parse2::parse_netdoc_multiple::<TestDoc>(&ParseInput::new(
            descs,
            "cached-descriptors.new",
        ))
        .unwrap();
        // Find the first with negative and first with positive X coordinate.
        let negative_rd = descs
            .iter()
            .find(|rd| rd.ntor_onion_key_crosscert.bit.0)
            .unwrap();
        let positive_rd = descs
            .iter()
            .find(|rd| !rd.ntor_onion_key_crosscert.bit.0)
            .unwrap();
        negative_rd.verify(negative_rd.published.0);
        positive_rd.verify(positive_rd.published.0);
    }
}