Skip to main content

tor_netdoc/doc/
routerdesc.rs

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.
30use crate::encode::{ItemEncoder, ItemValueEncodable, NetdocEncodable, NetdocEncoder};
31use crate::parse::keyword::Keyword;
32use crate::parse::parser::{Section, SectionRules};
33use crate::parse::tokenize::{ItemResult, NetDocReader};
34use crate::parse2::{
35    ArgumentError, ErrorProblem, ItemValueParseable, SignaturesData, UnparsedItem, VerifyFailed,
36};
37use crate::types::descriptor::*;
38use crate::types::family::{RelayFamily, RelayFamilyIds};
39use crate::types::policy::*;
40use crate::types::version::TorVersion;
41use crate::types::{EmbeddedCert, misc::*};
42use crate::util::PeekableIterator;
43use crate::{
44    AllowAnnotations, Error, KeywordEncodable, NetdocErrorKind as EK, NormalItemArgument, Result,
45};
46
47use derive_deftly::Deftly;
48use ll::pk::ed25519::Ed25519Identity;
49use saturating_time::SaturatingTime;
50use std::fmt::Display;
51use std::sync::LazyLock;
52use std::{iter, net, time};
53use tor_basic_utils::intern::Intern;
54use tor_cert::{CertType, KeyUnknownCert};
55use tor_checkable::timed::{TimeRangeBound, TimeRangeBoundBuilder};
56use tor_checkable::{Timebound, signed, timed};
57use tor_error::{internal, into_internal};
58use tor_llcrypto as ll;
59use tor_llcrypto::pk::ed25519::{self, Ed25519PublicKey};
60use tor_llcrypto::pk::keymanip::convert_curve25519_to_ed25519_public;
61use tor_llcrypto::pk::rsa::{self, RsaIdentity};
62
63use digest::Digest;
64
65/// Length of a router descriptor digest
66pub const DOC_DIGEST_LEN: usize = 20;
67
68/// The digest of a RouterDesc document, as reported in a NS consensus.
69pub type RdDigest = [u8; DOC_DIGEST_LEN];
70
71/// The digest of an ExtraInfo document, as reported in a RouterDesc.
72pub type ExtraInfoDigest = [u8; DOC_DIGEST_LEN];
73
74/// A router descriptor, with possible annotations.
75#[non_exhaustive]
76pub 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]
86pub 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)]
116pub 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///
269// TODO(relay): Would be grand to be able to use this within RouterDesc::encode_sign()
270// but it would need to support "signature sections" I guess or something around those
271// lines because the RSA signature covers the Ed25519 signature.
272#[derive(Clone, Debug, PartialEq, Deftly)]
273#[derive_deftly(NetdocParseableSignatures, NetdocEncodable)]
274#[deftly(netdoc(signatures(hashes_accu = "RouterHashAccu")))]
275#[non_exhaustive]
276pub struct RouterDescSignatures {
277    /// `router-sig-ed25519` --- Ed25519 signature
278    ///
279    /// Ed25519 signature by the Ed25519 signing key on the SHA-256 digest of
280    /// the document prefixed by a magic up until and including the
281    /// `router-sig-ed25519` keyword plus space.
282    pub router_sig_ed25519: RouterSigEd25519,
283
284    /// `router-signature` --- RSA signature
285    ///
286    /// * At end, exactly once.
287    /// * RSA signature of the document, including `router-sig-ed25519`.
288    pub router_signature: RouterSignature,
289}
290
291impl RouterDescUnverified {
292    /// Verifies a self-signed [`RouterDescUnverified`].
293    ///
294    /// This verification performs the following checks:
295    /// * [`RouterDesc::identity_ed25519`] is validly signed.
296    /// * [`RouterDesc::master_key_ed25519`] is as implied by [`RouterDesc::identity_ed25519`].
297    /// * [`RouterDesc::fingerprint`] is as implied by [`RouterDesc::signing_key`].
298    /// * [`RouterDesc::ntor_onion_key_crosscert`] is validly signed.
299    /// * [`RouterDesc::signing_key`] has correct length and exponent.
300    /// * All [`RouterDesc::family_cert`] elements are valid.
301    /// * The inner and outer [`RouterDescSignatures`] are valid.
302    ///
303    /// The result will be a [`TimeRangeBound`] composed from the respective
304    /// minimums and maximums found in the present certificates.  For the lower
305    /// bound, [`RouterDesc::published`] will also be taken into account when
306    /// determining the minimum.
307    //
308    // We deny the use of unused variables as a hint to use all TimeRangeBound
309    // values obtained through a dangerous split.
310    #[deny(unused_variables)]
311    pub fn verify(self) -> std::result::Result<TimeRangeBound<RouterDesc>, VerifyFailed> {
312        let logic = |trbb: &mut TimeRangeBoundBuilder| -> _ {
313            // Type annotations to make LSP happy.
314            let (mut body, sigs): (RouterDesc, SignaturesData<_>) = (self.body, self.sigs);
315
316            // Verify the ed25519 identity certificate.
317            // This also includes a check for the master-key-ed25519.
318            let identity_ed25519 =
319                Ed25519IdentityCert::verify(body.identity_ed25519.raw_unverified().clone())?
320                    .unwrap_with(trbb);
321            let Ed25519IdentityCert {
322                id_ed25519,
323                sign_ed25519,
324            } = identity_ed25519;
325            if id_ed25519 != body.master_key_ed25519.0 {
326                return Err(VerifyFailed::Inconsistent);
327            }
328            body.identity_ed25519.set_verified(identity_ed25519);
329
330            // Keep track of the published value as lower time bound.
331            trbb.intersect_bounds(TimeRangeBound::new((), body.published.0..));
332
333            // If set, ensure that the fingerprint equals to the signing key id.
334            if body
335                .fingerprint
336                .is_some_and(|fp| fp.0 != body.signing_key.to_rsa_identity())
337            {
338                return Err(VerifyFailed::Inconsistent);
339            }
340
341            // Verify the ntor-onion-key-crosscert.
342            // For this, we also need to convert the X25519 ntor key to an Ed25519
343            // key using convert_curve25519_to_ed25519_public().
344            let ntor_pk = convert_curve25519_to_ed25519_public(
345                &body.ntor_onion_key.0,
346                // Rust std turns false into 0 and true into 1.
347                body.ntor_onion_key_crosscert.bit.0.into(),
348            )
349            .ok_or(VerifyFailed::Other)?;
350            let ntor_cc = Ed25519NtorCrossCert::verify(
351                ntor_pk.into(),
352                id_ed25519,
353                body.ntor_onion_key_crosscert.cert.raw_unverified().clone(),
354            )?
355            .unwrap_with(trbb);
356            body.ntor_onion_key_crosscert.cert.set_verified(ntor_cc);
357
358            // Verify that the signing key has the proper exponent and length.
359            // TODO DIRAUTH: We want to enforce this type wise with parse2.
360            if body.signing_key.bits() != 1024 || !body.signing_key.exponent_is(65537) {
361                return Err(VerifyFailed::Other);
362            }
363
364            // Verify all family certificates.
365            for cert in body.family_cert.0.iter_mut() {
366                let cert_verified =
367                    Ed25519FamilyCert::verify(id_ed25519, cert.raw_unverified().clone())?
368                        .unwrap_with(trbb);
369                cert.set_verified(cert_verified);
370            }
371
372            // Verify the actual outer document signatures.
373            // VerifyFailed should be an okay error variant in case that the hashes
374            // were not accumulated, as it is not possible to verify without a
375            // hash.
376            ed25519::PublicKey::try_from(sign_ed25519)
377                .map_err(|_| VerifyFailed::Other)?
378                .verify(
379                    &sigs.hashes.sha256.ok_or(VerifyFailed::VerifyFailed)?,
380                    &sigs.sigs.router_sig_ed25519.0,
381                )?;
382            body.signing_key.verify(
383                sigs.hashes.sha1.ok_or(VerifyFailed::VerifyFailed)?.as_ref(),
384                sigs.sigs.router_signature.0.as_ref(),
385            )?;
386
387            Ok(body)
388        };
389
390        TimeRangeBound::build_intersect(logic)
391    }
392}
393
394/// Description of the software a relay is running.
395///
396/// `platform` line in a routerstatus.
397/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:platform>
398// TODO: Move this to types/misc.rs.
399#[derive(Debug, Clone, PartialEq, Eq)]
400#[non_exhaustive]
401pub enum RelayPlatform {
402    /// Software advertised to be some version of Tor, on some platform.
403    Tor(TorVersion, Option<String>),
404    /// Software not advertised to be Tor.
405    Other(String),
406}
407
408/// Zero-sized token type for use in [`RouterDesc::caches_extra_info`].
409#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
410#[non_exhaustive]
411pub struct CachesExtraInfoToken;
412
413/// Zero-sized token type for use in [`RouterDesc::hidden_service_dir`].
414#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
415#[non_exhaustive]
416pub struct HiddenServiceDirToken;
417
418/// Zero-sized token type for use in [`RouterDesc::tunnelled_dir_server`].
419#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
420#[non_exhaustive]
421pub struct TunnelledDirServerToken;
422
423impl std::str::FromStr for RelayPlatform {
424    type Err = Error;
425    fn from_str(args: &str) -> Result<Self> {
426        if args.starts_with("Tor ") {
427            let v: Vec<_> = args.splitn(4, ' ').collect();
428            match &v[..] {
429                ["Tor", ver, "on", p] => {
430                    Ok(RelayPlatform::Tor(ver.parse()?, Some((*p).to_string())))
431                }
432                ["Tor", ver, ..] => Ok(RelayPlatform::Tor(ver.parse()?, None)),
433                _ => unreachable!(),
434            }
435        } else {
436            Ok(RelayPlatform::Other(args.to_string()))
437        }
438    }
439}
440
441impl Display for RelayPlatform {
442    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
443        match &self {
444            Self::Tor(v, Some(p)) => write!(f, "Tor {v} on {p}"),
445            Self::Tor(v, None) => write!(f, "Tor {v}"),
446            Self::Other(s) => write!(f, "{s}"),
447        }
448    }
449}
450
451impl ItemValueParseable for RelayPlatform {
452    fn from_unparsed(item: UnparsedItem<'_>) -> std::result::Result<Self, ErrorProblem> {
453        let mut args = item.args_copy();
454        item.check_no_object()?;
455        args.into_remaining()
456            .parse()
457            .map_err(|_| args.handle_error("platform", ArgumentError::Invalid))
458    }
459}
460
461impl ItemValueEncodable for RelayPlatform {
462    fn write_item_value_onto(
463        &self,
464        mut out: ItemEncoder,
465    ) -> std::result::Result<(), tor_error::Bug> {
466        // Adding a raw string is fine because this is effectively a free form
467        // field.
468        out.args_raw_string(&self);
469        Ok(())
470    }
471}
472
473/// Version argument found in an `overload-general` item.
474///
475/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:overload-general>
476#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, strum::EnumString, strum::Display)]
477#[non_exhaustive]
478pub enum OverloadGeneralVersion {
479    /// Version 1, currently the only supported and specified one.
480    #[strum(serialize = "1")]
481    V1,
482}
483
484impl NormalItemArgument for OverloadGeneralVersion {}
485
486/// The overload general type found in router descriptors.
487///
488/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:overload-general>
489#[derive(Debug, Clone, Copy, PartialEq, Eq, Deftly)]
490#[derive_deftly(Constructor, ItemValueParseable, ItemValueEncodable)]
491#[allow(clippy::exhaustive_structs)]
492pub struct OverloadGeneral {
493    /// The version of the item.
494    #[deftly(constructor)]
495    pub version: OverloadGeneralVersion,
496    /// The timestamp since when the relay is overloaded.
497    #[deftly(constructor)]
498    pub since: Iso8601TimeSp,
499
500    #[doc(hidden)]
501    #[deftly(netdoc(skip))]
502    pub __non_exhaustive: (),
503}
504
505/// Introduction line of a router descriptor.
506///
507/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:router>
508#[derive(Clone, Debug, PartialEq, Eq, Deftly)]
509#[derive_deftly(Constructor, ItemValueParseable, ItemValueEncodable)]
510#[allow(clippy::exhaustive_structs)]
511pub struct RouterDescIntroItem {
512    /// A valid router [`Nickname`].
513    #[deftly(constructor)]
514    pub nickname: Nickname,
515
516    /// An IPv4 address in dotted-squad format.
517    #[deftly(constructor)]
518    pub address: std::net::Ipv4Addr,
519
520    /// The TCP port of the onion router.
521    #[deftly(constructor)]
522    pub orport: u16,
523
524    /// Legacy.
525    pub socksport: u16,
526
527    /// Legacy.
528    pub dirport: u16,
529
530    #[doc(hidden)]
531    #[deftly(netdoc(skip))]
532    pub __non_exhaustive: (),
533}
534
535/// Digest identifying the extra-info document.
536///
537/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:extra-info-digest>
538#[derive(Clone, Debug, PartialEq, Eq, Deftly)]
539#[derive_deftly(Constructor, ItemValueParseable, ItemValueEncodable)]
540#[allow(clippy::exhaustive_structs)]
541pub struct ExtraInfoDigests {
542    /// Mandatory SHA-1 of the signed data in base 16.
543    #[deftly(constructor)]
544    pub sha1: FixedB16U<20>,
545
546    /// Optional SHA-256 of the entire extra-info in base 64.
547    pub sha2: Option<FixedB64<32>>,
548
549    #[doc(hidden)]
550    #[deftly(netdoc(skip))]
551    pub __non_exhaustive: (),
552}
553
554/// Estimated bandwidth for a router.
555///
556/// <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:bandwidth>
557// Does not derive Ord because it only makes sense to order on a single
558// field but not all.
559#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Deftly)]
560#[derive_deftly(Constructor, ItemValueParseable, ItemValueEncodable)]
561#[allow(clippy::exhaustive_structs)]
562pub struct Bandwidth {
563    /// The volume that the relay is willing to sustain over long periods.
564    #[deftly(constructor)]
565    pub average: u64,
566
567    /// The volume that the relay is willing to sustain in very short intervals.
568    #[deftly(constructor)]
569    pub burst: u64,
570
571    /// The estimate of the capacity this relay can handle.
572    #[deftly(constructor)]
573    pub observed: u64,
574
575    #[doc(hidden)]
576    #[deftly(netdoc(skip))]
577    pub __non_exhaustive: (),
578}
579
580/// Ntor onion key cross-certificate.
581///
582/// This struct contains an [`Ed25519NtorCrossCert`] alongside the `bit`
583/// field required for converting the ntor X25519 key to an Ed25519 key.
584///
585/// # See Also
586///
587/// * [`Ed25519NtorCrossCert`]
588/// * <https://spec.torproject.org/dir-spec/server-descriptor-format.html#item:ntor-onion-key-crosscert>
589#[derive(Debug, Clone, Deftly, PartialEq)]
590#[derive_deftly(Constructor, ItemValueParseable, ItemValueEncodable)]
591#[deftly(netdoc(no_extra_args))]
592#[allow(clippy::exhaustive_structs)]
593pub struct NtorOnionKeyCrossCert {
594    /// True if X coordinate of the ntor onion key is negative, false if
595    /// positive.
596    // TODO spec: This name is very unfortunate, how about we change it
597    // to `is_negative`.  Also, using a boolean for storing a sign bit feels
598    // wrong to me due to the zero edge case, which would not be negative,
599    // but also not positive either.
600    #[deftly(constructor)]
601    pub bit: NumericBoolean,
602
603    /// The actual embedded ntor onion key certificate.
604    #[deftly(netdoc(object))]
605    #[deftly(constructor)]
606    pub cert: EmbeddedCert<Ed25519NtorCrossCert, KeyUnknownCert>,
607
608    #[doc(hidden)]
609    #[deftly(netdoc(skip))]
610    pub __non_exhaustive: (),
611}
612
613decl_keyword! {
614    /// RouterKwd is an instance of Keyword, used to denote the different
615    /// Items that are recognized as appearing in a router descriptor.
616    RouterKwd {
617        annotation "@source" => ANN_SOURCE,
618        annotation "@downloaded-at" => ANN_DOWNLOADED_AT,
619        annotation "@purpose" => ANN_PURPOSE,
620        "accept" | "reject" => POLICY,
621        "bandwidth" => BANDWIDTH,
622        "bridge-distribution-request" => BRIDGE_DISTRIBUTION_REQUEST,
623        "caches-extra-info" => CACHES_EXTRA_INFO,
624        "contact" => CONTACT,
625        "extra-info-digest" => EXTRA_INFO_DIGEST,
626        "family" => FAMILY,
627        "family-cert" => FAMILY_CERT,
628        "fingerprint" => FINGERPRINT,
629        "hibernating" => HIBERNATING,
630        "identity-ed25519" => IDENTITY_ED25519,
631        "ipv6-policy" => IPV6_POLICY,
632        "master-key-ed25519" => MASTER_KEY_ED25519,
633        "ntor-onion-key" => NTOR_ONION_KEY,
634        "ntor-onion-key-crosscert" => NTOR_ONION_KEY_CROSSCERT,
635        "or-address" => OR_ADDRESS,
636        "platform" => PLATFORM,
637        "proto" => PROTO,
638        "published" => PUBLISHED,
639        "router" => ROUTER,
640        "router-sig-ed25519" => ROUTER_SIG_ED25519,
641        "router-signature" => ROUTER_SIGNATURE,
642        "signing-key" => SIGNING_KEY,
643        "tunnelled_dir_server" => TUNNELLED_DIR_SERVER,
644        "uptime" => UPTIME,
645        // "protocols" once existed, but is obsolete
646        // "eventdns" once existed, but is obsolete
647        // "allow-single-hop-exits" is also obsolete.
648    }
649}
650
651/// Rules for parsing a set of router descriptor annotations.
652static ROUTER_ANNOTATIONS: LazyLock<SectionRules<RouterKwd>> = LazyLock::new(|| {
653    use RouterKwd::*;
654
655    let mut rules = SectionRules::builder();
656    rules.add(ANN_SOURCE.rule());
657    rules.add(ANN_DOWNLOADED_AT.rule().args(1..));
658    rules.add(ANN_PURPOSE.rule().args(1..));
659    rules.add(ANN_UNRECOGNIZED.rule().may_repeat().obj_optional());
660    // Unrecognized annotations are fine; anything else is an error in this
661    // context.
662    rules.reject_unrecognized();
663    rules.build()
664});
665/// Rules for tokens that are allowed in the first part of a
666/// router descriptor.
667static ROUTER_HEADER_RULES: LazyLock<SectionRules<RouterKwd>> = LazyLock::new(|| {
668    use RouterKwd::*;
669
670    let mut rules = SectionRules::builder();
671    rules.add(ROUTER.rule().required().args(5..));
672    rules.add(IDENTITY_ED25519.rule().required().no_args().obj_required());
673    // No other intervening tokens are permitted in the header.
674    rules.reject_unrecognized();
675    rules.build()
676});
677/// Rules for  tokens that are allowed in the first part of a
678/// router descriptor.
679static ROUTER_BODY_RULES: LazyLock<SectionRules<RouterKwd>> = LazyLock::new(|| {
680    use RouterKwd::*;
681
682    let mut rules = SectionRules::builder();
683    rules.add(MASTER_KEY_ED25519.rule().required().args(1..));
684    rules.add(PLATFORM.rule());
685    rules.add(PUBLISHED.rule().required());
686    rules.add(FINGERPRINT.rule());
687    rules.add(UPTIME.rule().args(1..));
688    rules.add(NTOR_ONION_KEY.rule().required().args(1..));
689    rules.add(
690        NTOR_ONION_KEY_CROSSCERT
691            .rule()
692            .required()
693            .args(1..=1)
694            .obj_required(),
695    );
696    rules.add(SIGNING_KEY.rule().no_args().required().obj_required());
697    rules.add(POLICY.rule().may_repeat().args(1..));
698    rules.add(IPV6_POLICY.rule().args(2..));
699    rules.add(FAMILY.rule().args(1..));
700    rules.add(FAMILY_CERT.rule().obj_required().may_repeat());
701    rules.add(CACHES_EXTRA_INFO.rule().no_args());
702    rules.add(OR_ADDRESS.rule().may_repeat().args(1..));
703    rules.add(TUNNELLED_DIR_SERVER.rule());
704    rules.add(PROTO.rule().required().args(1..));
705    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
706    // TODO: these aren't parsed yet.  Only authorities use them.
707    {
708        rules.add(BANDWIDTH.rule().required().args(3..));
709        rules.add(BRIDGE_DISTRIBUTION_REQUEST.rule().args(1..));
710        rules.add(HIBERNATING.rule().args(1..));
711        rules.add(CONTACT.rule());
712    }
713    // TODO: this is ignored for now.
714    {
715        rules.add(EXTRA_INFO_DIGEST.rule().args(1..));
716    }
717    rules.build()
718});
719
720/// Rules for items that appear at the end of a router descriptor.
721static ROUTER_SIG_RULES: LazyLock<SectionRules<RouterKwd>> = LazyLock::new(|| {
722    use RouterKwd::*;
723
724    let mut rules = SectionRules::builder();
725    rules.add(ROUTER_SIG_ED25519.rule().required().args(1..));
726    rules.add(ROUTER_SIGNATURE.rule().required().no_args().obj_required());
727    // No intervening tokens are allowed in the footer.
728    rules.reject_unrecognized();
729    rules.build()
730});
731
732impl RouterAnnotation {
733    /// Extract a single RouterAnnotation (possibly empty) from a reader.
734    fn take_from_reader(reader: &mut NetDocReader<'_, RouterKwd>) -> Result<RouterAnnotation> {
735        use RouterKwd::*;
736        let mut items = reader.pause_at(|item| item.is_ok_with_non_annotation());
737
738        let body = ROUTER_ANNOTATIONS.parse(&mut items)?;
739
740        let source = body.maybe(ANN_SOURCE).args_as_str().map(String::from);
741        let purpose = body.maybe(ANN_PURPOSE).args_as_str().map(String::from);
742        let downloaded = body
743            .maybe(ANN_DOWNLOADED_AT)
744            .parse_args_as_str::<Iso8601TimeSp>()?
745            .map(|t| t.into());
746        Ok(RouterAnnotation {
747            source,
748            downloaded,
749            purpose,
750        })
751    }
752}
753
754/// A parsed router descriptor whose signatures and/or validity times
755/// may or may not be invalid.
756pub type UncheckedRouterDesc = signed::SignatureGated<timed::TimeRangeBound<RouterDesc>>;
757
758/// How long after its published time is a router descriptor officially
759/// supposed to be usable?
760const ROUTER_EXPIRY_SECONDS: u64 = 5 * 86400;
761
762/// How long before its published time is a router descriptor usable?
763// TODO(nickm): This valid doesn't match C tor, which only enforces this rule
764// ("routers should not some from the future") at directory authorities, and
765// there only enforces a 12-hour limit (`ROUTER_ALLOW_SKEW`).  Eventually we
766// should probably harmonize these cutoffs.
767const ROUTER_PRE_VALIDITY_SECONDS: u64 = 86400;
768
769impl RouterDesc {
770    /// Encode this router descriptor and append its Ed25519 and RSA signatures in that
771    /// specific order.
772    ///
773    /// `k_relayid_rsa` must match [`Self::signing_key`] and `k_relaysign_ed`
774    /// must match the relay signing key certified by [`Self::identity_ed25519`].
775    /// Returns an error if either key's public part does not match.
776    ///
777    /// Returns the signed and encoded document as a string.
778    pub fn encode_sign(
779        &self,
780        k_relayid_rsa: &rsa::KeyPair,
781        k_relaysign_ed: &ed25519::Keypair,
782    ) -> Result<String> {
783        use RouterKwd::{ROUTER_SIG_ED25519, ROUTER_SIGNATURE};
784
785        // Extra precaution as non matching keys will successfully create a non usable
786        // descriptor with keys not matching the signatures.
787        if k_relayid_rsa.to_public_key() != self.signing_key {
788            return Err(internal!("RSA identity key does not match the one stored").into());
789        }
790        if Ed25519Identity::from(k_relaysign_ed.public_key())
791            != self.identity_ed25519.get()?.sign_ed25519
792        {
793            return Err(internal!("Ed25519 signing key does not match the one stored").into());
794        }
795
796        let mut encoder = NetdocEncoder::new();
797        self.encode_unsigned(&mut encoder)?;
798
799        // Note that we can't use RouterDescSignatures because of the overlapping
800        // signatures that is the RSA signature covers the Ed25519 signatures.
801
802        let ed_signature = RouterSigEd25519::new_sign_netdoc(
803            k_relaysign_ed,
804            &encoder,
805            ROUTER_SIG_ED25519.to_str(),
806        )?;
807        ed_signature.write_item_value_onto(encoder.item(ROUTER_SIG_ED25519))?;
808
809        // The RSA signature also covers the preceding Ed25519 signature item.
810        let rsa_signature = RouterSignature(
811            RsaSha1Signature::new_sign_netdoc(k_relayid_rsa, &encoder, ROUTER_SIGNATURE.to_str())?
812                .signature,
813        );
814        rsa_signature.write_item_value_onto(encoder.item(ROUTER_SIGNATURE))?;
815
816        Ok(encoder.finish()?)
817    }
818
819    /// Return a reference to this relay's RSA identity.
820    pub fn rsa_identity(&self) -> RsaIdentity {
821        self.signing_key.to_rsa_identity()
822    }
823
824    /// Return a reference to this relay's Ed25519 identity.
825    pub fn ed_identity(&self) -> &Ed25519Identity {
826        &self
827            .identity_ed25519
828            .get()
829            .expect("ed25519 identity cert should be verified")
830            .id_ed25519
831    }
832
833    /// Return a reference to the list of subprotocol versions supported by this
834    /// relay.
835    pub fn protocols(&self) -> &tor_protover::Protocols {
836        &self.proto
837    }
838
839    /// Return a reference to this relay's Ntor onion key.
840    pub fn ntor_onion_key(&self) -> &ll::pk::curve25519::PublicKey {
841        &self.ntor_onion_key.0
842    }
843
844    /// Return the publication
845    pub fn published(&self) -> time::SystemTime {
846        self.published.0
847    }
848
849    /// Return an iterator of every `SocketAddr` at which this descriptor says
850    /// its relay can be reached.
851    pub fn or_ports(&self) -> impl Iterator<Item = net::SocketAddr> + '_ {
852        iter::once(net::SocketAddr::new(
853            self.router.address.into(),
854            self.router.orport,
855        ))
856        .chain(self.or_address.iter().copied())
857    }
858
859    /// Return the declared family of this descriptor.
860    pub fn family(&self) -> Intern<RelayFamily> {
861        Intern::clone(&self.family)
862    }
863
864    /// Return the authenticated family IDs of this descriptor.
865    pub fn family_ids(&self) -> RelayFamilyIds {
866        RelayFamilyIds::from_iter(
867            self.family_cert
868                .iter()
869                .map(|cert| cert.get().expect("unverified family cert?"))
870                .map(|cert| cert.family_ed25519.into()),
871        )
872    }
873
874    /// Helper: tokenize `s`, and divide it into three validated sections.
875    fn parse_sections<'a>(
876        reader: &mut NetDocReader<'a, RouterKwd>,
877    ) -> Result<(
878        Section<'a, RouterKwd>,
879        Section<'a, RouterKwd>,
880        Section<'a, RouterKwd>,
881    )> {
882        use RouterKwd::*;
883
884        // Parse everything up through the header.
885        let header = ROUTER_HEADER_RULES.parse(
886            reader.pause_at(|item| item.is_ok_with_kwd_not_in(&[ROUTER, IDENTITY_ED25519])),
887        )?;
888
889        // Parse everything up to but not including the signature.
890        let body =
891            ROUTER_BODY_RULES.parse(reader.pause_at(|item| {
892                item.is_ok_with_kwd_in(&[ROUTER_SIGNATURE, ROUTER_SIG_ED25519])
893            }))?;
894
895        // Parse the signature.
896        let sig = ROUTER_SIG_RULES.parse(reader.pause_at(|item| {
897            item.is_ok_with_annotation() || item.is_ok_with_kwd(ROUTER) || item.is_empty_line()
898        }))?;
899
900        Ok((header, body, sig))
901    }
902
903    /// Try to parse `s` as a router descriptor.
904    ///
905    /// Does not actually check liveness or signatures; you need to do that
906    /// yourself before you can do the output.
907    ///
908    /// The following fields are not parsed with the legacy parser and their
909    /// default value is used instead.
910    /// * [`RouterDescIntroItem::socksport`] in [`RouterDesc::router`]
911    /// * [`RouterDesc::bandwidth`]
912    /// * [`RouterDesc::or_address`]
913    ///     * Extracts only the first IPv6 address.
914    /// * [`RouterDesc::hibernating`]
915    /// * [`RouterDesc::overload_general`]
916    /// * [`RouterDesc::contact`]
917    /// * [`RouterDesc::extra_info_digest`]
918    /// * [`RouterDesc::hidden_service_dir`]
919    pub fn parse(s: &str) -> Result<UncheckedRouterDesc> {
920        let mut reader = crate::parse::tokenize::NetDocReader::new(s)?;
921        let result = Self::parse_internal(&mut reader).map_err(|e| e.within(s))?;
922        // We permit empty lines at the end of router descriptors, since there's
923        // a known issue in Tor relays that causes them to return them this way.
924        reader
925            .should_be_exhausted_but_for_empty_lines()
926            .map_err(|e| e.within(s))?;
927        Ok(result)
928    }
929
930    /// Helper: parse a router descriptor from `s`.
931    ///
932    /// This function does the same as parse(), but returns errors based on
933    /// byte-wise positions.  The parse() function converts such errors
934    /// into line-and-byte positions.
935    fn parse_internal(r: &mut NetDocReader<'_, RouterKwd>) -> Result<UncheckedRouterDesc> {
936        // TODO: This function is too long!  The little "paragraphs" here
937        // that parse one item at a time should be made into sub-functions.
938        use RouterKwd::*;
939
940        let s = r.str();
941        let (header, body, sig) = RouterDesc::parse_sections(r)?;
942
943        // Unwrap should be safe because inline `required` call should return
944        // `Error::MissingToken` if `ROUTER` is not `Ok`
945        #[allow(clippy::unwrap_used)]
946        let start_offset = header.required(ROUTER)?.offset_in(s).unwrap();
947
948        // ed25519 identity and signing key.
949        //
950        // Small digression: This is terrible.  We return a tuple containing
951        // a KeyUnknownCert and an UncheckedCert.  This is because of a parse2
952        // and legacy incongruence.  For parse2, we need the KeyUnknownCert
953        // to properly include it into EmbeddedCert, whereas the legacy parser
954        // will need an UncheckedCert because the verification chain is
955        // performed at the end.  Because tor-cert's method all consume self,
956        // we can not go backwards, meaning we have to store two separate
957        // copies.  It is also not possible to do the conversion to
958        // UncheckedCert later, because then we lose the error context returned
959        // in EK::BadObjectVal if the signed-by extension is missing.
960        //
961        let (ku_identity_cert, identity_cert, ed25519_signing_key) = {
962            let cert_tok = header.required(IDENTITY_ED25519)?;
963            // Unwrap should be safe because above `required` call should
964            // return `Error::MissingToken` if `IDENTITY_ED25519` is not `Ok`
965            #[allow(clippy::unwrap_used)]
966            if cert_tok.offset_in(s).unwrap() < start_offset {
967                return Err(EK::MisplacedToken
968                    .with_msg("identity-ed25519")
969                    .at_pos(cert_tok.pos()));
970            }
971            let ku_cert = cert_tok
972                .parse_obj::<UnvalidatedEdCert>("ED25519 CERT")?
973                .check_cert_type(tor_cert::CertType::IDENTITY_V_SIGNING)?
974                .into_unchecked();
975            let cert = ku_cert.clone().should_have_signing_key().map_err(|err| {
976                EK::BadObjectVal
977                    .err()
978                    .with_source(err)
979                    .at_pos(cert_tok.pos())
980            })?;
981            let sk = *cert.peek_subject_key().as_ed25519().ok_or_else(|| {
982                EK::BadObjectVal
983                    .at_pos(cert_tok.pos())
984                    .with_msg("wrong type for signing key in cert")
985            })?;
986            let sk: ll::pk::ed25519::PublicKey = sk.try_into().map_err(|_| {
987                EK::BadObjectVal
988                    .at_pos(cert_tok.pos())
989                    .with_msg("invalid ed25519 signing key")
990            })?;
991            (ku_cert, cert, sk)
992        };
993
994        // master-key-ed25519: required, and should match certificate.
995        #[allow(unexpected_cfgs)]
996        let ed25519_identity_key = {
997            let master_key_tok = body.required(MASTER_KEY_ED25519)?;
998            let ed_id: Ed25519Public = master_key_tok.parse_arg(0)?;
999            let ed_id: ll::pk::ed25519::Ed25519Identity = ed_id.into();
1000            if ed_id != *identity_cert.peek_signing_key() {
1001                #[cfg(not(fuzzing))] // No feature here; never omit in production.
1002                return Err(EK::BadObjectVal
1003                    .at_pos(master_key_tok.pos())
1004                    .with_msg("master-key-ed25519 does not match key in identity-ed25519"));
1005            }
1006            ed_id
1007        };
1008
1009        // Legacy RSA identity
1010        let rsa_identity_key: ll::pk::rsa::PublicKey = body
1011            .required(SIGNING_KEY)?
1012            .parse_obj::<RsaPublicParse1Helper>("RSA PUBLIC KEY")?
1013            .check_len_eq(1024)?
1014            .check_exponent(65537)?
1015            .into();
1016        let rsa_identity = rsa_identity_key.to_rsa_identity();
1017
1018        let ed_sig = sig.required(ROUTER_SIG_ED25519)?;
1019        let rsa_sig = sig.required(ROUTER_SIGNATURE)?;
1020        // Unwrap should be safe because above `required` calls should return
1021        // an `Error::MissingToken` if `ROUTER_...` is not `Ok`
1022        #[allow(clippy::unwrap_used)]
1023        let ed_sig_pos = ed_sig.offset_in(s).unwrap();
1024        #[allow(clippy::unwrap_used)]
1025        let rsa_sig_pos = rsa_sig.offset_in(s).unwrap();
1026
1027        if ed_sig_pos > rsa_sig_pos {
1028            return Err(EK::UnexpectedToken
1029                .with_msg(ROUTER_SIG_ED25519.to_str())
1030                .at_pos(ed_sig.pos()));
1031        }
1032
1033        // Extract ed25519 signature.
1034        let ed_signature: ll::pk::ed25519::ValidatableEd25519Signature = {
1035            let mut d = ll::d::Sha256::new();
1036            d.update(&b"Tor router descriptor signature v1"[..]);
1037            let signed_end = ed_sig_pos + b"router-sig-ed25519 ".len();
1038            d.update(
1039                s.get(start_offset..signed_end)
1040                    .ok_or_else(|| internal!("chopped utf8"))?,
1041            );
1042            let d = d.finalize();
1043            let sig: [u8; 64] = ed_sig
1044                .parse_arg::<B64>(0)?
1045                .into_array()
1046                .map_err(|_| EK::BadSignature.at_pos(ed_sig.pos()))?;
1047            let sig = ll::pk::ed25519::Signature::from(sig);
1048            ll::pk::ed25519::ValidatableEd25519Signature::new(ed25519_signing_key, sig, &d)
1049        };
1050
1051        // Extract legacy RSA signature.
1052        let rsa_signature: ll::pk::rsa::ValidatableRsaSignature = {
1053            let mut d = ll::d::Sha1::new();
1054            let signed_end = rsa_sig_pos + b"router-signature\n".len();
1055            d.update(
1056                s.get(start_offset..signed_end)
1057                    .ok_or_else(|| internal!("chopped utf8"))?,
1058            );
1059            let d = d.finalize();
1060            let sig = rsa_sig.obj("SIGNATURE")?;
1061            // TODO: we need to accept prefixes here. COMPAT BLOCKER.
1062
1063            ll::pk::rsa::ValidatableRsaSignature::new(&rsa_identity_key, &sig, &d)
1064        };
1065
1066        // router nickname ipv4addr orport socksport dirport
1067        let (nickname, ipv4addr, orport, dirport) = {
1068            let rtrline = header.required(ROUTER)?;
1069            (
1070                rtrline.required_arg(0)?.parse::<Nickname>().map_err(|e| {
1071                    EK::BadArgument
1072                        .with_msg(e.to_string())
1073                        .at_pos(rtrline.pos())
1074                })?,
1075                rtrline.parse_arg::<net::Ipv4Addr>(1)?,
1076                rtrline.parse_arg(2)?,
1077                // Skipping socksport.
1078                rtrline.parse_arg(4)?,
1079            )
1080        };
1081
1082        // uptime
1083        let uptime = body.maybe(UPTIME).parse_arg(0)?;
1084
1085        // published time.
1086        let published = body
1087            .required(PUBLISHED)?
1088            .args_as_str()
1089            .parse::<Iso8601TimeSp>()?;
1090
1091        // ntor key
1092        let ntor_onion_key: Curve25519Public = body.required(NTOR_ONION_KEY)?.parse_arg(0)?;
1093        // ntor crosscert
1094        let (cc_sig, cc_expiry, cc_cert) = {
1095            let cc = body.required(NTOR_ONION_KEY_CROSSCERT)?;
1096            let sign: u8 = cc.parse_arg(0)?;
1097            if sign != 0 && sign != 1 {
1098                return Err(EK::BadArgument.at_pos(cc.arg_pos(0)).with_msg("not 0 or 1"));
1099            }
1100            let ntor_as_ed: ll::pk::ed25519::PublicKey =
1101                ll::pk::keymanip::convert_curve25519_to_ed25519_public(&ntor_onion_key.0, sign)
1102                    .ok_or_else(|| {
1103                        EK::BadArgument
1104                            .at_pos(cc.pos())
1105                            .with_msg("Uncheckable crosscert")
1106                    })?;
1107
1108            let cert = cc
1109                .parse_obj::<UnvalidatedEdCert>("ED25519 CERT")?
1110                .into_unchecked();
1111            let (_, sig, expiry) = Ed25519NtorCrossCert::verify_inner(
1112                ntor_as_ed.into(),
1113                ed25519_identity_key,
1114                cert.clone(),
1115            )
1116            .map_err(|_| EK::BadSignature.err())?;
1117
1118            let cert = NtorOnionKeyCrossCertConstructor {
1119                bit: NumericBoolean(sign != 0),
1120                // Okay to call because we added the signature to the batch.
1121                cert: EmbeddedCert::new(Ed25519NtorCrossCert::dangerous_new_unverified(), cert),
1122            }
1123            .construct();
1124
1125            (sig, expiry, cert)
1126        };
1127
1128        // List of subprotocol versions
1129        let proto = {
1130            let proto_tok = body.required(PROTO)?;
1131            proto_tok
1132                .args_as_str()
1133                .parse::<tor_protover::Protocols>()
1134                .map_err(|e| EK::BadArgument.at_pos(proto_tok.pos()).with_source(e))?
1135        };
1136
1137        // tunneled-dir-server
1138        let is_dircache = ((dirport != 0) || body.get(TUNNELLED_DIR_SERVER).is_some())
1139            .then_some(ItemPresent::default());
1140
1141        // caches-extra-info
1142        let is_extrainfo_cache = body.get(CACHES_EXTRA_INFO).map(|_| ItemPresent::default());
1143
1144        // fingerprint: check for consistency with RSA identity.
1145        if let Some(fp_tok) = body.get(FINGERPRINT) {
1146            let fp: RsaIdentity = fp_tok.args_as_str().parse::<SpFingerprint>()?.into();
1147            if fp != rsa_identity {
1148                return Err(EK::BadArgument
1149                    .at_pos(fp_tok.pos())
1150                    .with_msg("fingerprint does not match RSA identity"));
1151            }
1152        }
1153
1154        // Family
1155        let family = {
1156            let mut family = body
1157                .maybe(FAMILY)
1158                .parse_args_as_str::<RelayFamily>()?
1159                .unwrap_or_else(RelayFamily::new);
1160            if !family.is_empty() {
1161                // If this family is nonempty, we add our own RSA id to it, on
1162                // the theory that doing so will improve the odds of having a
1163                // canonical family shared by all of the members of this family.
1164                // If the family is empty, there's no point in adding our own ID
1165                // to it, and doing so would only waste memory.
1166                family.push(rsa_identity);
1167            }
1168            family.intern()
1169        };
1170
1171        // Family ids (for "happy families")
1172        //
1173        // Unfortunately we have to store this as a tuple of KeyUnknownCert and
1174        // UncheckedCert due to a parse2/legacy incongruence.  parse2 requires
1175        // KeyUnknownCert for EmbeddedCert whereas the legacy parser needs
1176        // descendants of it obtained by passing it irreversibly through the
1177        // tor_cert verification chain.
1178        let family_certs = body
1179            .slice(FAMILY_CERT)
1180            .iter()
1181            .map(|ent| {
1182                let ku = ent
1183                    .parse_obj::<UnvalidatedEdCert>("FAMILY CERT")?
1184                    .check_cert_type(CertType::FAMILY_V_IDENTITY)?
1185                    .check_subject_key_is(identity_cert.peek_signing_key())?
1186                    .into_unchecked();
1187                let unchecked = ku.clone().should_have_signing_key().map_err(|e| {
1188                    EK::BadObjectVal
1189                        .with_msg("missing public key")
1190                        .at_pos(ent.pos())
1191                        .with_source(e)
1192                })?;
1193                Ok((ku, unchecked))
1194            })
1195            .collect::<Result<Vec<_>>>()?;
1196
1197        // or-address
1198        // Extract at most one ipv6 address from the list.  It's not great,
1199        // but it's what the legacy parser does.
1200        let mut ipv6addr = Vec::with_capacity(1);
1201        for tok in body.slice(OR_ADDRESS) {
1202            if let Ok(net::SocketAddr::V6(a)) = tok.parse_arg::<net::SocketAddr>(0) {
1203                ipv6addr.push(a.into());
1204                break;
1205            }
1206            // We skip over unparsable addresses. Is that right?
1207        }
1208
1209        // platform
1210        let platform = body.maybe(PLATFORM).parse_args_as_str::<RelayPlatform>()?;
1211
1212        // ipv4_policy
1213        let ipv4_policy = {
1214            let mut pol = AddrPolicy::new();
1215            for ruletok in body.slice(POLICY).iter() {
1216                let accept = match ruletok.kwd_str() {
1217                    "accept" => RuleKind::Accept,
1218                    "reject" => RuleKind::Reject,
1219                    _ => {
1220                        return Err(Error::from(internal!(
1221                            "tried to parse a strange line as a policy"
1222                        ))
1223                        .at_pos(ruletok.pos()));
1224                    }
1225                };
1226                let pat: AddrPortPattern = ruletok
1227                    .args_as_str()
1228                    .parse()
1229                    .map_err(|e| EK::BadPolicy.at_pos(ruletok.pos()).with_source(e))?;
1230                pol.push(accept, pat);
1231            }
1232            pol
1233        };
1234
1235        // ipv6 policy
1236        let ipv6_policy = match body.get(IPV6_POLICY) {
1237            Some(p) => p
1238                .args_as_str()
1239                .parse()
1240                .map_err(|e| EK::BadPolicy.at_pos(p.pos()).with_source(e))?,
1241            // Unwrap is safe here because str is not empty
1242            #[allow(clippy::unwrap_used)]
1243            None => "reject 1-65535".parse::<PortPolicy>().unwrap(),
1244        };
1245
1246        // Now we're going to collect signatures and expiration times.
1247        let (identity_cert, identity_sig) = identity_cert.dangerously_split().map_err(|err| {
1248            EK::BadObjectVal
1249                .with_msg("missing public key")
1250                .with_source(err)
1251        })?;
1252        let mut signatures: Vec<Box<dyn ll::pk::ValidatableSignature>> = vec![
1253            Box::new(rsa_signature),
1254            Box::new(ed_signature),
1255            Box::new(identity_sig),
1256            Box::new(cc_sig),
1257        ];
1258
1259        let identity_cert = identity_cert.dangerously_assume_timely();
1260        let mut expirations = vec![
1261            published
1262                .0
1263                .saturating_add(time::Duration::new(ROUTER_EXPIRY_SECONDS, 0)),
1264            identity_cert.expiry(),
1265            cc_expiry,
1266        ];
1267
1268        // As outlined above, we have to do this ... :/
1269        //
1270        // Composing the verified part of the EmbeddedCert by just extracting
1271        // the key alone is OK because it gets checked at the end anyways
1272        // due to the push to signatures and expirations.
1273        let mut embedded_family_certs = Vec::with_capacity(family_certs.len());
1274        for (ku_cert, cert) in family_certs {
1275            let family_ed25519 = *cert.peek_signing_key();
1276            let (inner, sig) = cert.dangerously_split().map_err(into_internal!(
1277                "Missing a public key that was previously there."
1278            ))?;
1279            let embedded_cert = EmbeddedCert::new(Ed25519FamilyCert { family_ed25519 }, ku_cert);
1280            signatures.push(Box::new(sig));
1281            expirations.push(inner.dangerously_assume_timely().expiry());
1282            embedded_family_certs.push(embedded_cert);
1283        }
1284
1285        // Unwrap is safe here because `expirations` array is not empty
1286        #[allow(clippy::unwrap_used)]
1287        let expiry = *expirations.iter().min().unwrap();
1288
1289        let start_time = published
1290            .0
1291            .saturating_sub(time::Duration::new(ROUTER_PRE_VALIDITY_SECONDS, 0));
1292
1293        let desc = RouterDesc {
1294            router: RouterDescIntroItem {
1295                dirport,
1296                ..RouterDescIntroItemConstructor {
1297                    nickname,
1298                    address: ipv4addr,
1299                    orport,
1300                }
1301                .construct()
1302            },
1303            identity_ed25519: EmbeddedCert::new(
1304                Ed25519IdentityCert {
1305                    id_ed25519: ed25519_identity_key,
1306                    sign_ed25519: ed25519_signing_key.into(),
1307                },
1308                ku_identity_cert,
1309            ),
1310            master_key_ed25519: ed25519_identity_key.into(),
1311            bandwidth: Default::default(),
1312            platform,
1313            published,
1314            fingerprint: Some(rsa_identity.into()),
1315            hibernating: Default::default(),
1316            uptime,
1317            ntor_onion_key,
1318            ntor_onion_key_crosscert: cc_cert,
1319            signing_key: rsa_identity_key,
1320            ipv4_policy,
1321            ipv6_policy: ipv6_policy.intern(),
1322            overload_general: Default::default(),
1323            contact: Default::default(),
1324            family,
1325            family_cert: embedded_family_certs.into(),
1326            caches_extra_info: is_extrainfo_cache,
1327            extra_info_digest: Default::default(),
1328            hidden_service_dir: Default::default(),
1329            or_address: ipv6addr,
1330            tunnelled_dir_server: is_dircache,
1331            proto,
1332            __non_exhaustive: (),
1333        };
1334
1335        let time_gated = timed::TimeRangeBound::new(desc, start_time..expiry);
1336        let sig_gated = signed::SignatureGated::new(time_gated, signatures);
1337
1338        Ok(sig_gated)
1339    }
1340}
1341
1342/// An iterator that parses one or more (possibly annotated
1343/// router descriptors from a string.
1344//
1345// TODO: This is largely copy-pasted from MicrodescReader. Can/should they
1346// be merged?
1347pub struct RouterReader<'a> {
1348    /// True iff we accept annotations
1349    annotated: bool,
1350    /// Reader that we're extracting items from.
1351    reader: NetDocReader<'a, RouterKwd>,
1352}
1353
1354/// Skip this reader forward until the next thing it reads looks like the
1355/// start of a router descriptor.
1356///
1357/// Used to recover from errors.
1358fn advance_to_next_routerdesc(reader: &mut NetDocReader<'_, RouterKwd>, annotated: bool) {
1359    use RouterKwd::*;
1360    loop {
1361        let item = reader.peek();
1362        match item {
1363            Some(Ok(t)) => {
1364                let kwd = t.kwd();
1365                if (annotated && kwd.is_annotation()) || kwd == ROUTER {
1366                    return;
1367                }
1368            }
1369            Some(Err(_)) => {
1370                // Skip over broken tokens.
1371            }
1372            None => {
1373                return;
1374            }
1375        }
1376        let _ = reader.next();
1377    }
1378}
1379
1380impl<'a> RouterReader<'a> {
1381    /// Construct a RouterReader to take router descriptors from a string.
1382    pub fn new(s: &'a str, allow: &AllowAnnotations) -> Result<Self> {
1383        let reader = NetDocReader::new(s)?;
1384        let annotated = allow == &AllowAnnotations::AnnotationsAllowed;
1385        Ok(RouterReader { annotated, reader })
1386    }
1387
1388    /// Extract an annotation from this reader.
1389    fn take_annotation(&mut self) -> Result<RouterAnnotation> {
1390        if self.annotated {
1391            RouterAnnotation::take_from_reader(&mut self.reader)
1392        } else {
1393            Ok(RouterAnnotation::default())
1394        }
1395    }
1396
1397    /// Extract an annotated router descriptor from this reader
1398    ///
1399    /// (internal helper; does not clean up on failures.)
1400    fn take_annotated_routerdesc_raw(&mut self) -> Result<AnnotatedRouterDesc> {
1401        let ann = self.take_annotation()?;
1402        let router = RouterDesc::parse_internal(&mut self.reader)?;
1403        Ok(AnnotatedRouterDesc { ann, router })
1404    }
1405
1406    /// Extract an annotated router descriptor from this reader
1407    ///
1408    /// Ensure that at least one token is consumed
1409    fn take_annotated_routerdesc(&mut self) -> Result<AnnotatedRouterDesc> {
1410        let pos_orig = self.reader.pos();
1411        let result = self.take_annotated_routerdesc_raw();
1412        if result.is_err() {
1413            if self.reader.pos() == pos_orig {
1414                // No tokens were consumed from the reader.  We need
1415                // to drop at least one token to ensure we aren't in
1416                // an infinite loop.
1417                //
1418                // (This might not be able to happen, but it's easier to
1419                // explicitly catch this case than it is to prove that
1420                // it's impossible.)
1421                let _ = self.reader.next();
1422            }
1423            advance_to_next_routerdesc(&mut self.reader, self.annotated);
1424        }
1425        result
1426    }
1427}
1428
1429impl<'a> Iterator for RouterReader<'a> {
1430    type Item = Result<AnnotatedRouterDesc>;
1431    fn next(&mut self) -> Option<Self::Item> {
1432        // Is there a next token? If not, we're done.
1433        self.reader.peek()?;
1434
1435        Some(
1436            self.take_annotated_routerdesc()
1437                .map_err(|e| e.within(self.reader.str())),
1438        )
1439    }
1440}
1441
1442#[cfg(test)]
1443mod test {
1444    // @@ begin test lint list maintained by maint/add_warning @@
1445    #![allow(clippy::bool_assert_comparison)]
1446    #![allow(clippy::clone_on_copy)]
1447    #![allow(clippy::dbg_macro)]
1448    #![allow(clippy::mixed_attributes_style)]
1449    #![allow(clippy::print_stderr)]
1450    #![allow(clippy::print_stdout)]
1451    #![allow(clippy::single_char_pattern)]
1452    #![allow(clippy::unwrap_used)]
1453    #![allow(clippy::unchecked_time_subtraction)]
1454    #![allow(clippy::useless_vec)]
1455    #![allow(clippy::needless_pass_by_value)]
1456    #![allow(clippy::string_slice)] // See arti#2571
1457    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
1458    use std::{net::Ipv4Addr, str::FromStr, time::Duration};
1459
1460    use crate::{
1461        encode::{NetdocEncodable, NetdocEncoder},
1462        parse2::{self, NetdocParseableUnverified, ParseInput},
1463    };
1464    use tor_basic_utils::test_rng::testing_rng;
1465    use tor_checkable::TimeValidityError;
1466    use tor_llcrypto::pk::{curve25519, ed25519::Ed25519PublicKey, rsa};
1467
1468    use super::*;
1469    const TESTDATA: &str = include_str!("../../testdata/routerdesc1.txt");
1470    const TESTDATA2: &str = include_str!("../../testdata/routerdesc2.txt");
1471    // Generated with a patched C tor to include "happy family" IDs.
1472    const TESTDATA3: &str = include_str!("../../testdata/routerdesc3.txt");
1473
1474    fn read_bad(fname: &str) -> String {
1475        use std::fs;
1476        use std::path::PathBuf;
1477        let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
1478        path.push("testdata");
1479        path.push("bad-routerdesc");
1480        path.push(fname);
1481
1482        fs::read_to_string(path).unwrap()
1483    }
1484
1485    #[test]
1486    fn parse_arbitrary() -> Result<()> {
1487        use std::str::FromStr;
1488        use tor_checkable::{SelfSigned, TimeBound};
1489        let rd = RouterDesc::parse(TESTDATA)?
1490            .check_signature()?
1491            .dangerously_assume_timely();
1492
1493        assert_eq!(rd.router.nickname.as_str(), "Akka");
1494        assert_eq!(rd.router.orport, 443);
1495        assert_eq!(rd.router.dirport, 0);
1496        assert_eq!(rd.uptime, Some(1036923));
1497        assert_eq!(
1498            rd.family.as_ref(),
1499            &RelayFamily::from_str(
1500                "$303509ab910ef207b7438c27435c4a2fd579f1b1 \
1501                 $56927e61b51e6f363fb55498150a6ddfcf7077f2"
1502            )
1503            .unwrap()
1504        );
1505
1506        assert_eq!(
1507            rd.rsa_identity().to_string(),
1508            "$56927e61b51e6f363fb55498150a6ddfcf7077f2"
1509        );
1510        assert_eq!(
1511            rd.ed_identity().to_string(),
1512            "CVTjf1oeaL616hH+1+UvYZ8OgkwF3z7UMITvJzm5r7A"
1513        );
1514        assert_eq!(
1515            rd.protocols().to_string(),
1516            "Cons=1-2 Desc=1-2 DirCache=2 FlowCtrl=1-2 HSDir=2 \
1517             HSIntro=4-5 HSRend=1-2 Link=1-5 LinkAuth=1,3 Microdesc=1-2 \
1518             Padding=2 Relay=1-4"
1519        );
1520
1521        assert_eq!(
1522            hex::encode(rd.ntor_onion_key().to_bytes()),
1523            "329b3b52991613392e35d1a821dd6753e1210458ecc3337f7b7d39bfcf5da273"
1524        );
1525        assert_eq!(
1526            rd.published(),
1527            humantime::parse_rfc3339("2022-11-14T19:58:52Z").unwrap()
1528        );
1529        assert_eq!(
1530            rd.or_ports().collect::<Vec<_>>(),
1531            vec![
1532                "95.216.33.58:443".parse().unwrap(),
1533                "[2a01:4f9:2a:2145::2]:443".parse().unwrap(),
1534            ]
1535        );
1536
1537        Ok(())
1538    }
1539
1540    #[test]
1541    fn parse_no_tap_key() -> Result<()> {
1542        use tor_checkable::{SelfSigned, TimeBound};
1543        let _rd = RouterDesc::parse(TESTDATA2)?
1544            .check_signature()?
1545            .dangerously_assume_timely();
1546
1547        Ok(())
1548    }
1549
1550    #[test]
1551    fn test_bad() {
1552        use crate::Pos;
1553        use crate::types::policy::PolicyError;
1554        fn check(fname: &str, e: &Error) {
1555            let text = read_bad(fname);
1556            let rd = RouterDesc::parse(&text);
1557            assert!(rd.is_err());
1558            assert_eq!(&rd.err().unwrap(), e);
1559        }
1560
1561        check(
1562            "bad-sig-order",
1563            &EK::UnexpectedToken
1564                .with_msg("router-sig-ed25519")
1565                .at_pos(Pos::from_line(50, 1)),
1566        );
1567        check(
1568            "bad-start1",
1569            &EK::MisplacedToken
1570                .with_msg("identity-ed25519")
1571                .at_pos(Pos::from_line(1, 1)),
1572        );
1573        check("bad-start2", &EK::MissingToken.with_msg("identity-ed25519"));
1574        check(
1575            "mismatched-fp",
1576            &EK::BadArgument
1577                .at_pos(Pos::from_line(12, 1))
1578                .with_msg("fingerprint does not match RSA identity"),
1579        );
1580        check("no-ed-sk", &EK::MissingToken.with_msg("identity-ed25519"));
1581
1582        check(
1583            "bad-cc-sign",
1584            &EK::BadArgument
1585                .at_pos(Pos::from_line(34, 26))
1586                .with_msg("not 0 or 1"),
1587        );
1588        check(
1589            "bad-ipv6policy",
1590            &EK::BadPolicy
1591                .at_pos(Pos::from_line(43, 1))
1592                .with_source(PolicyError::InvalidPolicy),
1593        );
1594        check(
1595            "no-ed-id-key-in-cert",
1596            &EK::BadObjectVal
1597                .at_pos(Pos::from_line(2, 1))
1598                .with_source(tor_cert::CertError::MissingPubKey),
1599        );
1600        check(
1601            "non-ed-sk-in-cert",
1602            &EK::BadObjectVal
1603                .at_pos(Pos::from_line(2, 1))
1604                .with_msg("wrong type for signing key in cert"),
1605        );
1606        check(
1607            "bad-ed-sk-in-cert",
1608            &EK::BadObjectVal
1609                .at_pos(Pos::from_line(2, 1))
1610                .with_msg("invalid ed25519 signing key"),
1611        );
1612        check(
1613            "mismatched-ed-sk-in-cert",
1614            &EK::BadObjectVal
1615                .at_pos(Pos::from_line(8, 1))
1616                .with_msg("master-key-ed25519 does not match key in identity-ed25519"),
1617        );
1618    }
1619
1620    #[test]
1621    fn parse_multiple_annotated() {
1622        use crate::AllowAnnotations;
1623        let mut s = read_bad("bad-cc-sign");
1624        s += "\
1625@uploaded-at 2020-09-26 18:15:41
1626@source \"127.0.0.1\"
1627";
1628        s += TESTDATA;
1629        s += "\
1630@uploaded-at 2020-09-26 18:15:41
1631@source \"127.0.0.1\"
1632";
1633        s += &read_bad("mismatched-fp");
1634
1635        let rd = RouterReader::new(&s, &AllowAnnotations::AnnotationsAllowed).unwrap();
1636        let v: Vec<_> = rd.collect();
1637        assert!(v[0].is_err());
1638        assert!(v[1].is_ok());
1639        assert_eq!(
1640            v[1].as_ref().unwrap().ann.source,
1641            Some("\"127.0.0.1\"".to_string())
1642        );
1643        assert!(v[2].is_err());
1644    }
1645
1646    #[test]
1647    fn test_platform() {
1648        let tests = [
1649            // Test with platform.
1650            (
1651                "Tor 0.4.4.4-alpha on a flying bison",
1652                RelayPlatform::Tor(
1653                    "0.4.4.4-alpha".parse().unwrap(),
1654                    Some("a flying bison".to_string()),
1655                ),
1656            ),
1657            // Test without platform but potentially weird spacing.
1658            (
1659                "Tor 0.4.4.4-alpha on",
1660                RelayPlatform::Tor("0.4.4.4-alpha".parse().unwrap(), None),
1661            ),
1662            (
1663                "Tor 0.4.4.4-alpha ",
1664                RelayPlatform::Tor("0.4.4.4-alpha".parse().unwrap(), None),
1665            ),
1666            (
1667                "Tor 0.4.4.4-alpha",
1668                RelayPlatform::Tor("0.4.4.4-alpha".parse().unwrap(), None),
1669            ),
1670            // Test other.
1671            ("arti 0.0.0", RelayPlatform::Other("arti 0.0.0".to_string())),
1672        ];
1673        for (input, output) in tests {
1674            assert_eq!(input.parse::<RelayPlatform>().unwrap(), output);
1675
1676            // Round-trip test with input stripped of " on" suffix and trimmed.
1677            // Otherwise we cannot really make this work because certain inputs
1678            // contain redundant data on purpose.
1679            let input = input.strip_suffix(" on").unwrap_or(input);
1680            let input = input.trim();
1681            assert_eq!(output.to_string(), input);
1682        }
1683    }
1684
1685    #[test]
1686    fn test_family_ids() -> Result<()> {
1687        use tor_checkable::{SelfSigned, TimeBound};
1688        let rd = RouterDesc::parse(TESTDATA3)?
1689            .check_signature()?
1690            .dangerously_assume_timely();
1691
1692        assert_eq!(
1693            rd.family_ids().as_ref(),
1694            &[
1695                "ed25519:7sToQRuge1bU2hS0CG0ViMndc4m82JhO4B4kdrQey80"
1696                    .parse()
1697                    .unwrap(),
1698                "ed25519:szHUS3ItRd9uk85b1UVnOZx1gg4B0266jCpbuIMNjcM"
1699                    .parse()
1700                    .unwrap(),
1701            ]
1702        );
1703
1704        Ok(())
1705    }
1706
1707    /// Simple decoding and round-trip encoding for "normal" router descriptors.
1708    ///
1709    /// In other words: No edge cases and such.
1710    #[test]
1711    fn test_parse2_simple() {
1712        let input = ParseInput::new(
1713            include_str!("../../testdata2/cached-descriptors.new"),
1714            "cached-descriptors.new",
1715        );
1716        let rd = parse2::parse_netdoc_multiple::<RouterDescUnverified>(&input)
1717            .unwrap()
1718            .into_iter()
1719            .map(|rd| {
1720                rd.clone().verify().unwrap();
1721                rd.unwrap_unverified()
1722            })
1723            .map(|(body, sig)| (body, sig.sigs))
1724            .collect::<Vec<(RouterDesc, RouterDescSignatures)>>();
1725        assert_eq!(rd.len(), 20);
1726        assert_eq!(
1727            rd[0].0.router,
1728            RouterDescIntroItem {
1729                dirport: 7102,
1730                ..RouterDescIntroItemConstructor {
1731                    nickname: "test002a".parse().unwrap(),
1732                    address: net::Ipv4Addr::LOCALHOST,
1733                    orport: 5102,
1734                }
1735                .construct()
1736            }
1737        );
1738        assert_eq!(
1739            rd[0].0.fingerprint.unwrap(),
1740            "257D 06F0 360B B224 6388 724F 109E C089 5A1D 41FB"
1741                .parse()
1742                .unwrap()
1743        );
1744
1745        // Round-trip encoding by verifying that decoding it equals the original.
1746        // This is the best we can get as the current encoder is not bug for
1747        // bug compatible with the CTor one (i.e. absence of TAP and different
1748        // order), so this is the closest we can get.
1749        //
1750        // Unfortunately, we cannot verify the re-encoded signatures, because
1751        // the re-encoded body misses the TAP related fields which are accounted
1752        // for in the signature however.
1753        let mut out = NetdocEncoder::new();
1754        for (body, sig) in &rd {
1755            body.encode_unsigned(&mut out).unwrap();
1756            sig.encode_unsigned(&mut out).unwrap();
1757        }
1758        let out = out.finish().unwrap();
1759        let input2 = ParseInput::new(out.as_str(), "<router descriptor encoding>");
1760        let rd2 = parse2::parse_netdoc_multiple::<RouterDescUnverified>(&input2)
1761            .unwrap()
1762            .into_iter()
1763            .map(|rd| rd.unwrap_unverified())
1764            .map(|(body, sig)| (body, sig.sigs))
1765            .collect::<Vec<(RouterDesc, _)>>();
1766        assert_eq!(rd, rd2);
1767    }
1768
1769    /// Test for various succeeding and failing verifications.
1770    #[test]
1771    fn test_verify() {
1772        // Generate keys we will use later.
1773        let rng = &mut testing_rng();
1774        let rsa_id = rsa::KeyPair::generate(rng).unwrap();
1775        let ed25519_id = ed25519::Keypair::generate(rng);
1776        let ed25519_sign = ed25519::Keypair::generate(rng);
1777        let curve25519_ntor = curve25519::StaticSecret::random_from_rng(&mut *rng);
1778        let curve25519_ntor = curve25519::StaticKeypair {
1779            secret: curve25519_ntor.clone(),
1780            public: (&curve25519_ntor).into(),
1781        };
1782        let ed25519_ntor = tor_llcrypto::pk::keymanip::convert_curve25519_to_ed25519_private(
1783            &curve25519_ntor.secret,
1784        )
1785        .unwrap();
1786
1787        // Values arbitrarily chosen for expirations.
1788        let too_early = Iso8601TimeSp::from_str("2026-05-01 03:00:00").unwrap().0;
1789        let published = Iso8601TimeSp::from_str("2026-06-01 03:00:00").unwrap().0;
1790        let now = Iso8601TimeSp::from_str("2026-06-10 15:30:12").unwrap().0;
1791        let expiration = Iso8601TimeSp::from_str("2026-06-20 03:00:00").unwrap().0;
1792        let expired = expiration + Duration::from_secs(60 * 60 * 24);
1793
1794        // Very boilerplatey construction of a router descriptor.
1795        // TODO: Probably best to use constructor logic here.
1796        let mut rd = RouterDesc {
1797            router: RouterDescIntroItemConstructor {
1798                nickname: "foo".parse().unwrap(),
1799                address: Ipv4Addr::LOCALHOST,
1800                orport: 9000,
1801            }
1802            .construct(),
1803            identity_ed25519: Ed25519IdentityCert::new_signed(
1804                &ed25519_id,
1805                Ed25519Identity::from(ed25519_sign.public_key()),
1806                expiration,
1807            )
1808            .unwrap(),
1809            master_key_ed25519: Ed25519Identity::from(ed25519_id.public_key()).into(),
1810            bandwidth: BandwidthConstructor {
1811                average: 0,
1812                burst: 0,
1813                observed: 0,
1814            }
1815            .construct(),
1816            platform: None,
1817            published: published.into(),
1818            fingerprint: Some(rsa_id.to_public_key().to_rsa_identity().into()),
1819            hibernating: NumericBoolean(false),
1820            uptime: None,
1821            ntor_onion_key: Curve25519Public(curve25519_ntor.public),
1822            ntor_onion_key_crosscert: NtorOnionKeyCrossCertConstructor {
1823                bit: NumericBoolean(ed25519_ntor.1 == 1),
1824                cert: Ed25519NtorCrossCert::new_signed(
1825                    &ed25519_ntor.0,
1826                    ed25519_id.public_key().into(),
1827                    expiration,
1828                )
1829                .unwrap(),
1830            }
1831            .construct(),
1832            signing_key: rsa_id.to_public_key(),
1833            ipv4_policy: AddrPolicy::default(),
1834            ipv6_policy: Default::default(),
1835            overload_general: None,
1836            contact: None,
1837            family: Default::default(),
1838            family_cert: Default::default(),
1839            caches_extra_info: Some(Default::default()),
1840            extra_info_digest: None,
1841            hidden_service_dir: Some(Default::default()),
1842            or_address: Default::default(),
1843            tunnelled_dir_server: Some(Default::default()),
1844            proto: tor_protover::Protocols::new(),
1845            __non_exhaustive: (),
1846        };
1847        let rd_original = rd.clone();
1848
1849        let verify =
1850            |rd: &RouterDesc| -> std::result::Result<TimeRangeBound<RouterDesc>, VerifyFailed> {
1851                let encoded = rd.encode_sign(&rsa_id, &ed25519_sign).unwrap();
1852                let decoded = parse2::parse_netdoc::<RouterDescUnverified>(&ParseInput::new(
1853                    &encoded,
1854                    "<test_invalid>",
1855                ))
1856                .unwrap();
1857                decoded.verify()
1858            };
1859
1860        // Test valid and invalid timestamps.
1861        assert_eq!(
1862            verify(&rd).unwrap().if_valid_at(&too_early).unwrap_err(),
1863            TimeValidityError::NotYetValid(published.duration_since(too_early).unwrap())
1864        );
1865        verify(&rd).unwrap().if_valid_at(&published).unwrap();
1866        // This is our good/"everything is working" test
1867        verify(&rd).unwrap().if_valid_at(&now).unwrap();
1868        verify(&rd).unwrap().if_valid_at(&expiration).unwrap();
1869        assert_eq!(
1870            verify(&rd).unwrap().if_valid_at(&expired).unwrap_err(),
1871            TimeValidityError::Expired(expired.duration_since(expiration).unwrap())
1872        );
1873
1874        // Let's make the certificate inconsistent by changing the master key.
1875        rd.master_key_ed25519 = Ed25519Public(Ed25519Identity::from([0x12; 32]));
1876        assert_eq!(verify(&rd).unwrap_err(), VerifyFailed::Inconsistent);
1877        rd = rd_original.clone();
1878
1879        // Set the published to expired (weird on many levels).
1880        rd.published = expired.into();
1881        assert_eq!(
1882            verify(&rd).unwrap().if_valid_at(&now).unwrap_err(),
1883            TimeValidityError::NotYetValid(expired.duration_since(now).unwrap())
1884        );
1885        rd = rd_original.clone();
1886
1887        // Have an inconsistent fingerprint.
1888        let other_rsa_key = rsa::KeyPair::generate(rng).unwrap();
1889        rd.fingerprint = Some(other_rsa_key.to_public_key().to_rsa_identity().into());
1890        assert_eq!(verify(&rd).unwrap_err(), VerifyFailed::Inconsistent);
1891        // Encoding rejects a signing key that does not match the set keypair.
1892        rd.signing_key = other_rsa_key.to_public_key();
1893        assert!(rd.encode_sign(&rsa_id, &ed25519_sign).is_err());
1894        // It should work again if we set it to None.
1895        rd.signing_key = rd_original.signing_key.clone();
1896        rd.fingerprint = None;
1897        verify(&rd).unwrap().if_valid_at(&now).unwrap();
1898        rd = rd_original.clone();
1899
1900        // If we change the ntor-onion-key, the crosscert verification will fail.
1901        // We must generate a valid random key here because otherwise, decompress
1902        // will fail.
1903        let other_curve25519 = curve25519::StaticSecret::random_from_rng(&mut *rng);
1904        let other_curve25519 = (&other_curve25519).into();
1905        rd.ntor_onion_key = Curve25519Public(other_curve25519);
1906        assert_eq!(verify(&rd).unwrap_err(), VerifyFailed::VerifyFailed);
1907        rd = rd_original.clone();
1908
1909        // Testing for a signature key of the wrong size is hard because
1910        // tor-llcrypto makes it purposely hard to generate key sizes other
1911        // than 1024 bit.
1912
1913        // TODO: Test family certificates.
1914
1915        // Encoding rejects a certificate for a different Ed25519 signing key.
1916        let different_ed25519_sign = ed25519::Keypair::generate(rng);
1917        rd.identity_ed25519 = Ed25519IdentityCert::new_signed(
1918            &ed25519_id,
1919            Ed25519Identity::from(different_ed25519_sign.public_key()),
1920            expiration,
1921        )
1922        .unwrap();
1923        assert!(rd.encode_sign(&rsa_id, &ed25519_sign).is_err());
1924        rd = rd_original.clone();
1925
1926        // Encoding rejects a different RSA key even without a fingerprint.
1927        let different_rsa_id = rsa::KeyPair::generate(rng).unwrap();
1928        rd.signing_key = different_rsa_id.to_public_key();
1929        rd.fingerprint = None;
1930        assert!(rd.encode_sign(&rsa_id, &ed25519_sign).is_err());
1931    }
1932
1933    #[test]
1934    fn ntor_onion_key_cross_cert() {
1935        // Dummy helper for parsing a subset of a router desc.
1936        #[derive(Debug, Deftly)]
1937        #[derive_deftly(NetdocParseable)]
1938        #[allow(unused)]
1939        struct TestDoc {
1940            /// Intro item.
1941            router: RouterDescIntroItem,
1942
1943            /// Timestamp used for `now` in certificate validation.
1944            #[deftly(netdoc(single_arg))]
1945            published: Iso8601TimeSp,
1946
1947            /// Required to ensure certified key of the crosscert.
1948            #[deftly(netdoc(single_arg))]
1949            master_key_ed25519: Ed25519Public,
1950
1951            /// Required to obtain the key signing the crosscert.
1952            #[deftly(netdoc(single_arg))]
1953            ntor_onion_key: Curve25519Public,
1954
1955            /// The actual crosscert.
1956            ntor_onion_key_crosscert: NtorOnionKeyCrossCert,
1957        }
1958
1959        impl TestDoc {
1960            // Quick verify helper.
1961            fn verify(&self, now: time::SystemTime) {
1962                Ed25519NtorCrossCert::verify(
1963                    // Converts X25519 to Ed25519.
1964                    tor_llcrypto::pk::keymanip::convert_curve25519_to_ed25519_public(
1965                        &self.ntor_onion_key.0,
1966                        self.ntor_onion_key_crosscert.bit.0.into(),
1967                    )
1968                    .unwrap()
1969                    .into(),
1970                    self.master_key_ed25519.0,
1971                    self.ntor_onion_key_crosscert.cert.raw_unverified().clone(),
1972                )
1973                .unwrap()
1974                .check_valid_at(&now)
1975                .unwrap();
1976            }
1977        }
1978
1979        let descs = include_str!("../../testdata2/cached-descriptors.new");
1980        let descs = parse2::parse_netdoc_multiple::<TestDoc>(&ParseInput::new(
1981            descs,
1982            "cached-descriptors.new",
1983        ))
1984        .unwrap();
1985
1986        // Find the first with negative and first with positive X coordinate.
1987        let negative_rd = descs
1988            .iter()
1989            .find(|rd| rd.ntor_onion_key_crosscert.bit.0)
1990            .unwrap();
1991        let positive_rd = descs
1992            .iter()
1993            .find(|rd| !rd.ntor_onion_key_crosscert.bit.0)
1994            .unwrap();
1995
1996        negative_rd.verify(negative_rd.published.0);
1997        positive_rd.verify(positive_rd.published.0);
1998    }
1999}