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(NetdocParseableUnverified, NetdocEncodable)]
114
#[non_exhaustive]
115
pub struct RouterDesc {
116
    /// `router` --- Introduce a router descriptor.
117
    ///
118
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:router>
119
    pub router: RouterDescIntroItem,
120

            
121
    /// `identity-ed25519` --- Specify the router's ed25519 identity.
122
    ///
123
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:identity-ed25519>
124
    pub identity_ed25519: EmbeddedCert<Ed25519IdentityCert, KeyUnknownCert>,
125

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

            
132
    /// `bandwidth` --- Report router's network bandwidth.
133
    ///
134
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:bandwidth>
135
    pub bandwidth: Bandwidth,
136

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

            
142
    /// `published` --- Time this descriptor (and extra-info) was generated.
143
    ///
144
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:published>
145
    #[deftly(netdoc(single_arg))]
146
    pub published: Iso8601TimeSp,
147

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

            
154
    /// `hibernating` --- Whether the relay is hibernating.
155
    ///
156
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:hibernating>
157
    #[deftly(netdoc(single_arg, default(skip)))]
158
    pub hibernating: NumericBoolean,
159

            
160
    /// `uptime` --- How long this relay has been continously running
161
    ///
162
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:uptime>
163
    #[deftly(netdoc(single_arg))]
164
    pub uptime: Option<u64>,
165

            
166
    /// `ntor-onion-key` --- The circuit extension key.
167
    ///
168
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:ntor-onion-key>
169
    #[deftly(netdoc(single_arg))]
170
    pub ntor_onion_key: Curve25519Public,
171

            
172
    /// `ntor-onion-key-crosscert` --- Reverse cert by K_ntor on KP_relayid_ed
173
    ///
174
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:ntor-onion-key-crosscert>
175
    pub ntor_onion_key_crosscert: NtorOnionKeyCrossCert,
176

            
177
    /// `signing-key` --- Obsolete RSA identity key.
178
    ///
179
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:signing-key>
180
    pub signing_key: ll::pk::rsa::PublicKey,
181

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

            
193
    /// `ipv6-policy` --- Exit plicy summary for IPv6
194
    ///
195
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:ipv6-policy>
196
    #[deftly(netdoc(default(skip)))]
197
    pub ipv6_policy: Intern<PortPolicy>,
198

            
199
    /// `overload-general` --- Relay is overloaded.
200
    ///
201
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:overload-general>
202
    // TODO in OverloadGeneral use ConstantString (from !3985) for version
203
    pub overload_general: Option<OverloadGeneral>,
204

            
205
    /// `contact` --- Server administrator contact information.
206
    ///
207
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:contact>
208
    pub contact: Option<ContactInfo>,
209

            
210
    /// `family` --- Group relays for the purpose of path selection.
211
    ///
212
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:family>
213
    #[deftly(netdoc(default(skip)))]
214
    pub family: Intern<RelayFamily>,
215

            
216
    /// `family-cert` --- Prove membership in a relay family.
217
    ///
218
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:family-cert>
219
    pub family_cert: RetainedOrderVec<EmbeddedCert<Ed25519FamilyCert, KeyUnknownCert>>,
220

            
221
    /// `caches-extra-info` --- Router provides extra-info as a dirmirror.
222
    ///
223
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#caches-extra-info>
224
    pub caches_extra_info: Option<ItemPresent<CachesExtraInfoToken>>,
225

            
226
    /// `extra-info-digest` --- Hash of the extra-info document.
227
    ///
228
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:extra-info-digest>
229
    pub extra_info_digest: Option<ExtraInfoDigests>,
230

            
231
    /// `hidden-service-dir` --- Declares this router to be a hidden service directory
232
    ///
233
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:hidden-service-dir>
234
    pub hidden_service_dir: Option<ItemPresent<HiddenServiceDirToken>>,
235

            
236
    /// `or-address` --- Alternative ORport address and port
237
    ///
238
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:or-address>
239
    #[deftly(netdoc(single_arg))]
240
    pub or_address: Vec<net::SocketAddr>,
241

            
242
    /// `tunnelled-dir-server` --- Accepts a `BEGIN_DIR` relay message.
243
    ///
244
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#tunnelled-dir-server>
245
    pub tunnelled_dir_server: Option<ItemPresent<TunnelledDirServerToken>>,
246

            
247
    /// `proto` --- Subprotocol capabilities supported.
248
    ///
249
    /// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:proto>
250
    pub proto: tor_protover::Protocols,
251
}
252

            
253
/// Signatures of a [`RouterDesc`].
254
///
255
/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:router-sig-ed25519>
256
#[derive(Clone, Debug, PartialEq, Deftly)]
257
#[derive_deftly(NetdocParseableSignatures, NetdocEncodable)]
258
#[deftly(netdoc(signatures(hashes_accu = "RouterHashAccu")))]
259
#[non_exhaustive]
260
pub struct RouterDescSignatures {
261
    /// `router-sig-ed25519` --- Ed25519 signature
262
    ///
263
    /// Ed25519 signature by the Ed25519 signing key on the SHA-256 digest of
264
    /// the document prefixed by a magic up until and including the
265
    /// `router-sig-ed25519` keyword plus space.
266
    pub router_sig_ed25519: RouterSigEd25519,
267

            
268
    /// `router-signature` --- RSA signature
269
    ///
270
    /// * At end, exactly once.
271
    /// * RSA signature of the document, including `router-sig-ed25519`.
272
    pub router_signature: RouterSignature,
273
}
274

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

            
301
            // Verify the ed25519 identity certificate.
302
            // This also includes a check for the master-key-ed25519.
303
106
            let identity_ed25519 =
304
106
                Ed25519IdentityCert::verify(body.identity_ed25519.raw_unverified().clone())?
305
106
                    .unwrap_with(trbb);
306
            let Ed25519IdentityCert {
307
106
                id_ed25519,
308
106
                sign_ed25519,
309
106
            } = identity_ed25519;
310
106
            if id_ed25519 != body.master_key_ed25519.0 {
311
2
                return Err(VerifyFailed::Inconsistent);
312
104
            }
313
104
            body.identity_ed25519.set_verified(identity_ed25519);
314

            
315
            // Keep track of the published value as lower time bound.
316
104
            trbb.intersect_bounds(TimeRangeBound::new((), body.published.0..));
317

            
318
            // If set, ensure that the fingerprint equals to the signing key id.
319
104
            if body
320
104
                .fingerprint
321
104
                .is_some_and(|fp| fp.0 != body.signing_key.to_rsa_identity())
322
            {
323
2
                return Err(VerifyFailed::Inconsistent);
324
102
            }
325

            
326
            // Verify the ntor-onion-key-crosscert.
327
            // For this, we also need to convert the X25519 ntor key to an Ed25519
328
            // key using convert_curve25519_to_ed25519_public().
329
102
            let ntor_pk = convert_curve25519_to_ed25519_public(
330
102
                &body.ntor_onion_key.0,
331
                // Rust std turns false into 0 and true into 1.
332
102
                body.ntor_onion_key_crosscert.bit.0.into(),
333
            )
334
102
            .ok_or(VerifyFailed::Other)?;
335
102
            let ntor_cc = Ed25519NtorCrossCert::verify(
336
102
                ntor_pk.into(),
337
102
                id_ed25519,
338
102
                body.ntor_onion_key_crosscert.cert.raw_unverified().clone(),
339
2
            )?
340
100
            .unwrap_with(trbb);
341
100
            body.ntor_onion_key_crosscert.cert.set_verified(ntor_cc);
342

            
343
            // Verify that the signing key has the proper exponent and length.
344
            // TODO DIRAUTH: We want to enforce this type wise with parse2.
345
100
            if body.signing_key.bits() != 1024 || !body.signing_key.exponent_is(65537) {
346
                return Err(VerifyFailed::Other);
347
100
            }
348

            
349
            // Verify all family certificates.
350
100
            for cert in body.family_cert.0.iter_mut() {
351
                let cert_verified =
352
                    Ed25519FamilyCert::verify(id_ed25519, cert.raw_unverified().clone())?
353
                        .unwrap_with(trbb);
354
                cert.set_verified(cert_verified);
355
            }
356

            
357
            // Verify the actual outer document signatures.
358
            // VerifyFailed should be an okay error variant in case that the hashes
359
            // were not accumulated, as it is not possible to verify without a
360
            // hash.
361
100
            ed25519::PublicKey::try_from(sign_ed25519)
362
100
                .map_err(|_| VerifyFailed::Other)?
363
100
                .verify(
364
100
                    &sigs.hashes.sha256.ok_or(VerifyFailed::VerifyFailed)?,
365
100
                    &sigs.sigs.router_sig_ed25519.0,
366
2
                )?;
367
98
            body.signing_key.verify(
368
98
                sigs.hashes.sha1.ok_or(VerifyFailed::VerifyFailed)?.as_ref(),
369
98
                sigs.sigs.router_signature.0.as_ref(),
370
4
            )?;
371

            
372
94
            Ok(body)
373
106
        };
374

            
375
106
        TimeRangeBound::build_intersect(logic)
376
106
    }
377
}
378

            
379
/// Description of the software a relay is running.
380
///
381
/// `platform` line in a routerstatus.
382
/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:platform>
383
// TODO: Move this to types/misc.rs.
384
#[derive(Debug, Clone, PartialEq, Eq)]
385
#[non_exhaustive]
386
pub enum RelayPlatform {
387
    /// Software advertised to be some version of Tor, on some platform.
388
    Tor(TorVersion, Option<String>),
389
    /// Software not advertised to be Tor.
390
    Other(String),
391
}
392

            
393
/// Zero-sized token type for use in [`RouterDesc::caches_extra_info`].
394
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
395
#[non_exhaustive]
396
pub struct CachesExtraInfoToken;
397

            
398
/// Zero-sized token type for use in [`RouterDesc::hidden_service_dir`].
399
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
400
#[non_exhaustive]
401
pub struct HiddenServiceDirToken;
402

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

            
408
impl std::str::FromStr for RelayPlatform {
409
    type Err = Error;
410
2366
    fn from_str(args: &str) -> Result<Self> {
411
2366
        if args.starts_with("Tor ") {
412
2364
            let v: Vec<_> = args.splitn(4, ' ').collect();
413
2364
            match &v[..] {
414
2358
                ["Tor", ver, "on", p] => {
415
2358
                    Ok(RelayPlatform::Tor(ver.parse()?, Some((*p).to_string())))
416
                }
417
6
                ["Tor", ver, ..] => Ok(RelayPlatform::Tor(ver.parse()?, None)),
418
                _ => unreachable!(),
419
            }
420
        } else {
421
2
            Ok(RelayPlatform::Other(args.to_string()))
422
        }
423
2366
    }
424
}
425

            
426
impl Display for RelayPlatform {
427
50
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
428
48
        match &self {
429
42
            Self::Tor(v, Some(p)) => write!(f, "Tor {v} on {p}"),
430
6
            Self::Tor(v, None) => write!(f, "Tor {v}"),
431
2
            Self::Other(s) => write!(f, "{s}"),
432
        }
433
50
    }
434
}
435

            
436
impl ItemValueParseable for RelayPlatform {
437
120
    fn from_unparsed(item: UnparsedItem<'_>) -> std::result::Result<Self, ErrorProblem> {
438
120
        let mut args = item.args_copy();
439
120
        item.check_no_object()?;
440
120
        args.into_remaining()
441
120
            .parse()
442
120
            .map_err(|_| args.handle_error("platform", ArgumentError::Invalid))
443
120
    }
444
}
445

            
446
impl ItemValueEncodable for RelayPlatform {
447
40
    fn write_item_value_onto(
448
40
        &self,
449
40
        mut out: ItemEncoder,
450
40
    ) -> std::result::Result<(), tor_error::Bug> {
451
        // Adding a raw string is fine because this is effectively a free form
452
        // field.
453
40
        out.args_raw_string(&self);
454
40
        Ok(())
455
40
    }
456
}
457

            
458
/// Version argument found in an `overload-general` item.
459
///
460
/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:overload-general>
461
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, strum::EnumString, strum::Display)]
462
#[non_exhaustive]
463
pub enum OverloadGeneralVersion {
464
    /// Version 1, currently the only supported and specified one.
465
    #[strum(serialize = "1")]
466
    V1,
467
}
468

            
469
impl NormalItemArgument for OverloadGeneralVersion {}
470

            
471
/// The overload general type found in router descriptors.
472
///
473
/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:overload-general>
474
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deftly)]
475
#[derive_deftly(ItemValueParseable, ItemValueEncodable)]
476
#[non_exhaustive]
477
pub struct OverloadGeneral {
478
    /// The version of the item.
479
    pub version: OverloadGeneralVersion,
480
    /// The timestamp since when the relay is overloaded.
481
    pub since: Iso8601TimeSp,
482
}
483

            
484
/// Introduction line of a router descriptor.
485
///
486
/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:router>
487
#[derive(Clone, Debug, PartialEq, Eq, Deftly)]
488
#[derive_deftly(ItemValueParseable, ItemValueEncodable)]
489
#[non_exhaustive]
490
pub struct RouterDescIntroItem {
491
    /// A valid router [`Nickname`].
492
    pub nickname: Nickname,
493

            
494
    /// An IPv4 address in dotted-squad format.
495
    pub address: std::net::Ipv4Addr,
496

            
497
    /// The TCP port of the onion router.
498
    pub orport: u16,
499

            
500
    /// Legacy.
501
    pub socksport: u16,
502

            
503
    /// Legacy.
504
    pub dirport: u16,
505
}
506

            
507
/// Digest identifying the extra-info document.
508
///
509
/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:extra-info-digest>
510
#[derive(Clone, Debug, PartialEq, Eq, Deftly)]
511
#[derive_deftly(ItemValueParseable, ItemValueEncodable)]
512
#[non_exhaustive]
513
pub struct ExtraInfoDigests {
514
    /// Mandatory SHA-1 of the signed data in base 16.
515
    pub sha1: FixedB16U<20>,
516

            
517
    /// Optional SHA-256 of the entire extra-info in base 64.
518
    pub sha2: Option<FixedB64<32>>,
519
}
520

            
521
/// Estimated bandwidth for a router.
522
///
523
/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:bandwidth>
524
// Does not derive Ord because it only makes sense to order on a single
525
// field but not all.
526
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Deftly)]
527
#[derive_deftly(ItemValueParseable, ItemValueEncodable)]
528
#[non_exhaustive]
529
pub struct Bandwidth {
530
    /// The volume that the relay is willing to sustain over long periods.
531
    pub average: u64,
532

            
533
    /// The volume that the relay is willing to sustain in very short intervals.
534
    pub burst: u64,
535

            
536
    /// The estimate of the capacity this relay can handle.
537
    pub observed: u64,
538
}
539

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

            
562
    /// The actual embedded ntor onion key certificate.
563
    #[deftly(netdoc(object))]
564
    pub cert: EmbeddedCert<Ed25519NtorCrossCert, KeyUnknownCert>,
565
}
566

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

            
605
/// Rules for parsing a set of router descriptor annotations.
606
2
static ROUTER_ANNOTATIONS: LazyLock<SectionRules<RouterKwd>> = LazyLock::new(|| {
607
    use RouterKwd::*;
608

            
609
2
    let mut rules = SectionRules::builder();
610
2
    rules.add(ANN_SOURCE.rule());
611
2
    rules.add(ANN_DOWNLOADED_AT.rule().args(1..));
612
2
    rules.add(ANN_PURPOSE.rule().args(1..));
613
2
    rules.add(ANN_UNRECOGNIZED.rule().may_repeat().obj_optional());
614
    // Unrecognized annotations are fine; anything else is an error in this
615
    // context.
616
2
    rules.reject_unrecognized();
617
2
    rules.build()
618
2
});
619
/// Rules for tokens that are allowed in the first part of a
620
/// router descriptor.
621
55
static ROUTER_HEADER_RULES: LazyLock<SectionRules<RouterKwd>> = LazyLock::new(|| {
622
    use RouterKwd::*;
623

            
624
55
    let mut rules = SectionRules::builder();
625
55
    rules.add(ROUTER.rule().required().args(5..));
626
55
    rules.add(IDENTITY_ED25519.rule().required().no_args().obj_required());
627
    // No other intervening tokens are permitted in the header.
628
55
    rules.reject_unrecognized();
629
55
    rules.build()
630
55
});
631
/// Rules for  tokens that are allowed in the first part of a
632
/// router descriptor.
633
55
static ROUTER_BODY_RULES: LazyLock<SectionRules<RouterKwd>> = LazyLock::new(|| {
634
    use RouterKwd::*;
635

            
636
55
    let mut rules = SectionRules::builder();
637
55
    rules.add(MASTER_KEY_ED25519.rule().required().args(1..));
638
55
    rules.add(PLATFORM.rule());
639
55
    rules.add(PUBLISHED.rule().required());
640
55
    rules.add(FINGERPRINT.rule());
641
55
    rules.add(UPTIME.rule().args(1..));
642
55
    rules.add(NTOR_ONION_KEY.rule().required().args(1..));
643
55
    rules.add(
644
55
        NTOR_ONION_KEY_CROSSCERT
645
55
            .rule()
646
55
            .required()
647
55
            .args(1..=1)
648
55
            .obj_required(),
649
    );
650
55
    rules.add(SIGNING_KEY.rule().no_args().required().obj_required());
651
55
    rules.add(POLICY.rule().may_repeat().args(1..));
652
55
    rules.add(IPV6_POLICY.rule().args(2..));
653
55
    rules.add(FAMILY.rule().args(1..));
654
55
    rules.add(FAMILY_CERT.rule().obj_required().may_repeat());
655
55
    rules.add(CACHES_EXTRA_INFO.rule().no_args());
656
55
    rules.add(OR_ADDRESS.rule().may_repeat().args(1..));
657
55
    rules.add(TUNNELLED_DIR_SERVER.rule());
658
55
    rules.add(PROTO.rule().required().args(1..));
659
55
    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
660
    // TODO: these aren't parsed yet.  Only authorities use them.
661
55
    {
662
55
        rules.add(BANDWIDTH.rule().required().args(3..));
663
55
        rules.add(BRIDGE_DISTRIBUTION_REQUEST.rule().args(1..));
664
55
        rules.add(HIBERNATING.rule().args(1..));
665
55
        rules.add(CONTACT.rule());
666
55
    }
667
    // TODO: this is ignored for now.
668
55
    {
669
55
        rules.add(EXTRA_INFO_DIGEST.rule().args(1..));
670
55
    }
671
55
    rules.build()
672
55
});
673

            
674
/// Rules for items that appear at the end of a router descriptor.
675
55
static ROUTER_SIG_RULES: LazyLock<SectionRules<RouterKwd>> = LazyLock::new(|| {
676
    use RouterKwd::*;
677

            
678
55
    let mut rules = SectionRules::builder();
679
55
    rules.add(ROUTER_SIG_ED25519.rule().required().args(1..));
680
55
    rules.add(ROUTER_SIGNATURE.rule().required().no_args().obj_required());
681
    // No intervening tokens are allowed in the footer.
682
55
    rules.reject_unrecognized();
683
55
    rules.build()
684
55
});
685

            
686
impl RouterAnnotation {
687
    /// Extract a single RouterAnnotation (possibly empty) from a reader.
688
8
    fn take_from_reader(reader: &mut NetDocReader<'_, RouterKwd>) -> Result<RouterAnnotation> {
689
        use RouterKwd::*;
690
20
        let mut items = reader.pause_at(|item| item.is_ok_with_non_annotation());
691

            
692
8
        let body = ROUTER_ANNOTATIONS.parse(&mut items)?;
693

            
694
6
        let source = body.maybe(ANN_SOURCE).args_as_str().map(String::from);
695
6
        let purpose = body.maybe(ANN_PURPOSE).args_as_str().map(String::from);
696
6
        let downloaded = body
697
6
            .maybe(ANN_DOWNLOADED_AT)
698
6
            .parse_args_as_str::<Iso8601TimeSp>()?
699
6
            .map(|t| t.into());
700
6
        Ok(RouterAnnotation {
701
6
            source,
702
6
            downloaded,
703
6
            purpose,
704
6
        })
705
8
    }
706
}
707

            
708
/// A parsed router descriptor whose signatures and/or validity times
709
/// may or may not be invalid.
710
pub type UncheckedRouterDesc = signed::SignatureGated<timed::TimeRangeBound<RouterDesc>>;
711

            
712
/// How long after its published time is a router descriptor officially
713
/// supposed to be usable?
714
const ROUTER_EXPIRY_SECONDS: u64 = 5 * 86400;
715

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

            
723
impl RouterDesc {
724
    /// Return a reference to this relay's RSA identity.
725
1274
    pub fn rsa_identity(&self) -> RsaIdentity {
726
1274
        self.signing_key.to_rsa_identity()
727
1274
    }
728

            
729
    /// Return a reference to this relay's Ed25519 identity.
730
2
    pub fn ed_identity(&self) -> &Ed25519Identity {
731
2
        &self
732
2
            .identity_ed25519
733
2
            .get()
734
2
            .expect("ed25519 identity cert should be verified")
735
2
            .id_ed25519
736
2
    }
737

            
738
    /// Return a reference to the list of subprotocol versions supported by this
739
    /// relay.
740
2
    pub fn protocols(&self) -> &tor_protover::Protocols {
741
2
        &self.proto
742
2
    }
743

            
744
    /// Return a reference to this relay's Ntor onion key.
745
2
    pub fn ntor_onion_key(&self) -> &ll::pk::curve25519::PublicKey {
746
2
        &self.ntor_onion_key.0
747
2
    }
748

            
749
    /// Return the publication
750
320
    pub fn published(&self) -> time::SystemTime {
751
320
        self.published.0
752
320
    }
753

            
754
    /// Return an iterator of every `SocketAddr` at which this descriptor says
755
    /// its relay can be reached.
756
2
    pub fn or_ports(&self) -> impl Iterator<Item = net::SocketAddr> + '_ {
757
2
        iter::once(net::SocketAddr::new(
758
2
            self.router.address.into(),
759
2
            self.router.orport,
760
        ))
761
2
        .chain(self.or_address.iter().copied())
762
2
    }
763

            
764
    /// Return the declared family of this descriptor.
765
    pub fn family(&self) -> Intern<RelayFamily> {
766
        Intern::clone(&self.family)
767
    }
768

            
769
    /// Return the authenticated family IDs of this descriptor.
770
2
    pub fn family_ids(&self) -> RelayFamilyIds {
771
2
        RelayFamilyIds::from_iter(
772
2
            self.family_cert
773
2
                .iter()
774
5
                .map(|cert| cert.get().expect("unverified family cert?"))
775
5
                .map(|cert| cert.family_ed25519.into()),
776
        )
777
2
    }
778

            
779
    /// Helper: tokenize `s`, and divide it into three validated sections.
780
2366
    fn parse_sections<'a>(
781
2366
        reader: &mut NetDocReader<'a, RouterKwd>,
782
2366
    ) -> Result<(
783
2366
        Section<'a, RouterKwd>,
784
2366
        Section<'a, RouterKwd>,
785
2366
        Section<'a, RouterKwd>,
786
2366
    )> {
787
        use RouterKwd::*;
788

            
789
        // Parse everything up through the header.
790
2366
        let header = ROUTER_HEADER_RULES.parse(
791
6941
            reader.pause_at(|item| item.is_ok_with_kwd_not_in(&[ROUTER, IDENTITY_ED25519])),
792
110
        )?;
793

            
794
        // Parse everything up to but not including the signature.
795
2256
        let body =
796
38453
            ROUTER_BODY_RULES.parse(reader.pause_at(|item| {
797
38396
                item.is_ok_with_kwd_in(&[ROUTER_SIGNATURE, ROUTER_SIG_ED25519])
798
38396
            }))?;
799

            
800
        // Parse the signature.
801
4583
        let sig = ROUTER_SIG_RULES.parse(reader.pause_at(|item| {
802
4526
            item.is_ok_with_annotation() || item.is_ok_with_kwd(ROUTER) || item.is_empty_line()
803
4526
        }))?;
804

            
805
2256
        Ok((header, body, sig))
806
2366
    }
807

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

            
835
    /// Helper: parse a router descriptor from `s`.
836
    ///
837
    /// This function does the same as parse(), but returns errors based on
838
    /// byte-wise positions.  The parse() function converts such errors
839
    /// into line-and-byte positions.
840
2366
    fn parse_internal(r: &mut NetDocReader<'_, RouterKwd>) -> Result<UncheckedRouterDesc> {
841
        // TODO: This function is too long!  The little "paragraphs" here
842
        // that parse one item at a time should be made into sub-functions.
843
        use RouterKwd::*;
844

            
845
2366
        let s = r.str();
846
2366
        let (header, body, sig) = RouterDesc::parse_sections(r)?;
847

            
848
        // Unwrap should be safe because inline `required` call should return
849
        // `Error::MissingToken` if `ROUTER` is not `Ok`
850
        #[allow(clippy::unwrap_used)]
851
2256
        let start_offset = header.required(ROUTER)?.offset_in(s).unwrap();
852

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

            
899
        // master-key-ed25519: required, and should match certificate.
900
        #[allow(unexpected_cfgs)]
901
2246
        let ed25519_identity_key = {
902
2248
            let master_key_tok = body.required(MASTER_KEY_ED25519)?;
903
2248
            let ed_id: Ed25519Public = master_key_tok.parse_arg(0)?;
904
2248
            let ed_id: ll::pk::ed25519::Ed25519Identity = ed_id.into();
905
2248
            if ed_id != *identity_cert.peek_signing_key() {
906
                #[cfg(not(fuzzing))] // No feature here; never omit in production.
907
2
                return Err(EK::BadObjectVal
908
2
                    .at_pos(master_key_tok.pos())
909
2
                    .with_msg("master-key-ed25519 does not match key in identity-ed25519"));
910
2246
            }
911
2246
            ed_id
912
        };
913

            
914
        // Legacy RSA identity
915
2246
        let rsa_identity_key: ll::pk::rsa::PublicKey = body
916
2246
            .required(SIGNING_KEY)?
917
2246
            .parse_obj::<RsaPublicParse1Helper>("RSA PUBLIC KEY")?
918
2246
            .check_len_eq(1024)?
919
2246
            .check_exponent(65537)?
920
2246
            .into();
921
2246
        let rsa_identity = rsa_identity_key.to_rsa_identity();
922

            
923
2246
        let ed_sig = sig.required(ROUTER_SIG_ED25519)?;
924
2246
        let rsa_sig = sig.required(ROUTER_SIGNATURE)?;
925
        // Unwrap should be safe because above `required` calls should return
926
        // an `Error::MissingToken` if `ROUTER_...` is not `Ok`
927
        #[allow(clippy::unwrap_used)]
928
2246
        let ed_sig_pos = ed_sig.offset_in(s).unwrap();
929
        #[allow(clippy::unwrap_used)]
930
2246
        let rsa_sig_pos = rsa_sig.offset_in(s).unwrap();
931

            
932
2246
        if ed_sig_pos > rsa_sig_pos {
933
2
            return Err(EK::UnexpectedToken
934
2
                .with_msg(ROUTER_SIG_ED25519.to_str())
935
2
                .at_pos(ed_sig.pos()));
936
2244
        }
937

            
938
        // Extract ed25519 signature.
939
2244
        let ed_signature: ll::pk::ed25519::ValidatableEd25519Signature = {
940
2244
            let mut d = ll::d::Sha256::new();
941
2244
            d.update(&b"Tor router descriptor signature v1"[..]);
942
2244
            let signed_end = ed_sig_pos + b"router-sig-ed25519 ".len();
943
2244
            d.update(
944
2244
                s.get(start_offset..signed_end)
945
2244
                    .ok_or(internal!("chopped utf8"))?,
946
            );
947
2244
            let d = d.finalize();
948
2244
            let sig: [u8; 64] = ed_sig
949
2244
                .parse_arg::<B64>(0)?
950
2244
                .into_array()
951
2244
                .map_err(|_| EK::BadSignature.at_pos(ed_sig.pos()))?;
952
2244
            let sig = ll::pk::ed25519::Signature::from(sig);
953
2244
            ll::pk::ed25519::ValidatableEd25519Signature::new(ed25519_signing_key, sig, &d)
954
        };
955

            
956
        // Extract legacy RSA signature.
957
2244
        let rsa_signature: ll::pk::rsa::ValidatableRsaSignature = {
958
2244
            let mut d = ll::d::Sha1::new();
959
2244
            let signed_end = rsa_sig_pos + b"router-signature\n".len();
960
2244
            d.update(
961
2244
                s.get(start_offset..signed_end)
962
2244
                    .ok_or(internal!("chopped utf8"))?,
963
            );
964
2244
            let d = d.finalize();
965
2244
            let sig = rsa_sig.obj("SIGNATURE")?;
966
            // TODO: we need to accept prefixes here. COMPAT BLOCKER.
967

            
968
2244
            ll::pk::rsa::ValidatableRsaSignature::new(&rsa_identity_key, &sig, &d)
969
        };
970

            
971
        // router nickname ipv4addr orport socksport dirport
972
2244
        let (nickname, ipv4addr, orport, dirport) = {
973
2244
            let rtrline = header.required(ROUTER)?;
974
            (
975
2244
                rtrline.required_arg(0)?.parse::<Nickname>().map_err(|e| {
976
                    EK::BadArgument
977
                        .with_msg(e.to_string())
978
                        .at_pos(rtrline.pos())
979
                })?,
980
2244
                rtrline.parse_arg::<net::Ipv4Addr>(1)?,
981
2244
                rtrline.parse_arg(2)?,
982
                // Skipping socksport.
983
2244
                rtrline.parse_arg(4)?,
984
            )
985
        };
986

            
987
        // uptime
988
2244
        let uptime = body.maybe(UPTIME).parse_arg(0)?;
989

            
990
        // published time.
991
2244
        let published = body
992
2244
            .required(PUBLISHED)?
993
2244
            .args_as_str()
994
2244
            .parse::<Iso8601TimeSp>()?;
995

            
996
        // ntor key
997
2244
        let ntor_onion_key: Curve25519Public = body.required(NTOR_ONION_KEY)?.parse_arg(0)?;
998
        // ntor crosscert
999
2240
        let (cc_sig, cc_expiry, cc_cert) = {
2244
            let cc = body.required(NTOR_ONION_KEY_CROSSCERT)?;
2244
            let sign: u8 = cc.parse_arg(0)?;
2244
            if sign != 0 && sign != 1 {
4
                return Err(EK::BadArgument.at_pos(cc.arg_pos(0)).with_msg("not 0 or 1"));
2240
            }
2240
            let ntor_as_ed: ll::pk::ed25519::PublicKey =
2240
                ll::pk::keymanip::convert_curve25519_to_ed25519_public(&ntor_onion_key.0, sign)
2240
                    .ok_or_else(|| {
                        EK::BadArgument
                            .at_pos(cc.pos())
                            .with_msg("Uncheckable crosscert")
                    })?;
2240
            let cert = cc
2240
                .parse_obj::<UnvalidatedEdCert>("ED25519 CERT")?
2240
                .into_unchecked();
2240
            let (_, sig, expiry) = Ed25519NtorCrossCert::verify_inner(
2240
                ntor_as_ed.into(),
2240
                ed25519_identity_key,
2240
                cert.clone(),
            )
2240
            .map_err(|_| EK::BadSignature.err())?;
2240
            let cert = NtorOnionKeyCrossCert {
2240
                bit: NumericBoolean(sign != 0),
2240
                // Okay to call because we added the signature to the batch.
2240
                cert: EmbeddedCert::new(Ed25519NtorCrossCert::dangerous_new_unverified(), cert),
2240
            };
2240
            (sig, expiry, cert)
        };
        // List of subprotocol versions
2240
        let proto = {
2240
            let proto_tok = body.required(PROTO)?;
2240
            proto_tok
2240
                .args_as_str()
2240
                .parse::<tor_protover::Protocols>()
2240
                .map_err(|e| EK::BadArgument.at_pos(proto_tok.pos()).with_source(e))?
        };
        // tunneled-dir-server
2240
        let is_dircache = ((dirport != 0) || body.get(TUNNELLED_DIR_SERVER).is_some())
2240
            .then_some(ItemPresent::default());
        // caches-extra-info
2241
        let is_extrainfo_cache = body.get(CACHES_EXTRA_INFO).map(|_| ItemPresent::default());
        // fingerprint: check for consistency with RSA identity.
2240
        if let Some(fp_tok) = body.get(FINGERPRINT) {
2240
            let fp: RsaIdentity = fp_tok.args_as_str().parse::<SpFingerprint>()?.into();
2240
            if fp != rsa_identity {
4
                return Err(EK::BadArgument
4
                    .at_pos(fp_tok.pos())
4
                    .with_msg("fingerprint does not match RSA identity"));
2236
            }
        }
        // Family
2236
        let family = {
2236
            let mut family = body
2236
                .maybe(FAMILY)
2236
                .parse_args_as_str::<RelayFamily>()?
2236
                .unwrap_or_else(RelayFamily::new);
2236
            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);
2232
            }
2236
            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.
2236
        let family_certs = body
2236
            .slice(FAMILY_CERT)
2236
            .iter()
2238
            .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
            })
2236
            .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.
2236
        let mut ipv6addr = Vec::with_capacity(1);
2236
        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
2236
        let platform = body.maybe(PLATFORM).parse_args_as_str::<RelayPlatform>()?;
        // ipv4_policy
2236
        let ipv4_policy = {
2236
            let mut pol = AddrPolicy::new();
2238
            for ruletok in body.slice(POLICY).iter() {
2238
                let accept = match ruletok.kwd_str() {
2238
                    "accept" => RuleKind::Accept,
2236
                    "reject" => RuleKind::Reject,
                    _ => {
                        return Err(Error::from(internal!(
                            "tried to parse a strange line as a policy"
                        ))
                        .at_pos(ruletok.pos()));
                    }
                };
2238
                let pat: AddrPortPattern = ruletok
2238
                    .args_as_str()
2238
                    .parse()
2238
                    .map_err(|e| EK::BadPolicy.at_pos(ruletok.pos()).with_source(e))?;
2238
                pol.push(accept, pat);
            }
2236
            pol
        };
        // ipv6 policy
2236
        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)]
2234
            None => "reject 1-65535".parse::<PortPolicy>().unwrap(),
        };
        // Now we're going to collect signatures and expiration times.
2234
        let (identity_cert, identity_sig) = identity_cert.dangerously_split().map_err(|err| {
            EK::BadObjectVal
                .with_msg("missing public key")
                .with_source(err)
        })?;
2234
        let mut signatures: Vec<Box<dyn ll::pk::ValidatableSignature>> = vec![
2234
            Box::new(rsa_signature),
2234
            Box::new(ed_signature),
2234
            Box::new(identity_sig),
2234
            Box::new(cc_sig),
        ];
2234
        let identity_cert = identity_cert.dangerously_assume_timely();
2234
        let mut expirations = vec![
2234
            published
2234
                .0
2234
                .saturating_add(time::Duration::new(ROUTER_EXPIRY_SECONDS, 0)),
2234
            identity_cert.expiry(),
2234
            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.
2234
        let mut embedded_family_certs = Vec::with_capacity(family_certs.len());
2234
        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)]
2234
        let expiry = *expirations.iter().min().unwrap();
2234
        let start_time = published
2234
            .0
2234
            .saturating_sub(time::Duration::new(ROUTER_PRE_VALIDITY_SECONDS, 0));
2234
        let desc = RouterDesc {
2234
            router: RouterDescIntroItem {
2234
                nickname,
2234
                address: ipv4addr,
2234
                orport,
2234
                socksport: 0,
2234
                dirport,
2234
            },
2234
            identity_ed25519: EmbeddedCert::new(
2234
                Ed25519IdentityCert {
2234
                    id_ed25519: ed25519_identity_key,
2234
                    sign_ed25519: ed25519_signing_key.into(),
2234
                },
2234
                ku_identity_cert,
2234
            ),
2234
            master_key_ed25519: ed25519_identity_key.into(),
2234
            bandwidth: Default::default(),
2234
            platform,
2234
            published,
2234
            fingerprint: Some(rsa_identity.into()),
2234
            hibernating: Default::default(),
2234
            uptime,
2234
            ntor_onion_key,
2234
            ntor_onion_key_crosscert: cc_cert,
2234
            signing_key: rsa_identity_key,
2234
            ipv4_policy,
2234
            ipv6_policy: ipv6_policy.intern(),
2234
            overload_general: Default::default(),
2234
            contact: Default::default(),
2234
            family,
2234
            family_cert: embedded_family_certs.into(),
2234
            caches_extra_info: is_extrainfo_cache,
2234
            extra_info_digest: Default::default(),
2234
            hidden_service_dir: Default::default(),
2234
            or_address: ipv6addr,
2234
            tunnelled_dir_server: is_dircache,
2234
            proto,
2234
        };
2234
        let time_gated = timed::TimeRangeBound::new(desc, start_time..expiry);
2234
        let sig_gated = signed::SignatureGated::new(time_gated, signatures);
2234
        Ok(sig_gated)
2366
    }
}
/// 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.
        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(),
        };
        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);
    }
}