1
//! consensus documents - items that vary by consensus flavor
2
//!
3
//! **This file is reincluded multiple times**,
4
//! by the macros in [`crate::doc::ns_variety_definition_macros`],
5
//! once for votes, and once for each consensus flavour.
6
//! It is *not* a module `crate::doc::netstatus::rs::each_flavor`.
7
//!
8
//! Each time this file is included by one of the macros mentioned above,
9
//! the `ns_***` macros (such as `ns_const_name!`) may expand to different values.
10
//!
11
//! See [`crate::doc::ns_variety_definition_macros`].
12

            
13
use super::*;
14

            
15
ns_use_this_variety! {
16
    use [crate::doc::netstatus::rs]::?::{RouterStatus};
17
}
18
#[cfg(feature = "build_docs")]
19
ns_use_this_variety! {
20
    pub(crate) use [crate::doc::netstatus::build]::?::{ConsensusBuilder};
21
    pub use [crate::doc::netstatus::rs::build]::?::{RouterStatusBuilder};
22
}
23

            
24
/// A single consensus netstatus, as produced by the old parser.
25
#[derive(Debug, Clone)]
26
#[non_exhaustive]
27
pub struct Consensus {
28
    /// What kind of consensus document is this?  Absent in votes and
29
    /// in ns-flavored consensuses.
30
    pub flavor: ConsensusFlavor,
31
    /// The preamble, except for the intro item.
32
    pub preamble: Preamble,
33
    /// List of voters whose votes contributed to this consensus.
34
    pub voters: Vec<ConsensusAuthorityEntry>,
35
    /// A list of routerstatus entries for the relays on the network,
36
    /// with one entry per relay.
37
    ///
38
    /// These are currently ordered by the router's RSA identity, but this is not
39
    /// to be relied on, since we may want to even abolish RSA at some point!
40
    pub relays: Vec<RouterStatus>,
41
    /// Footer for the consensus object.
42
    pub footer: ConsensusFooterFields,
43
}
44

            
45
impl Consensus {
46
    /// Return the Lifetime for this consensus.
47
69825
    pub fn lifetime(&self) -> &Lifetime {
48
69825
        &self.preamble.lifetime
49
69825
    }
50

            
51
    /// Return a slice of all the routerstatus entries in this consensus.
52
68022637
    pub fn relays(&self) -> &[RouterStatus] {
53
68022637
        &self.relays[..]
54
68022637
    }
55

            
56
    /// Return a mapping from keywords to integers representing how
57
    /// to weight different kinds of relays in different path positions.
58
11172
    pub fn bandwidth_weights(&self) -> &NetParams<i32> {
59
11172
        &self.footer.bandwidth_weights
60
11172
    }
61

            
62
    /// Return the map of network parameters that this consensus advertises.
63
11221
    pub fn params(&self) -> &NetParams<i32> {
64
11221
        &self.preamble.params
65
11221
    }
66

            
67
    /// Return the latest shared random value, if the consensus
68
    /// contains one.
69
44639
    pub fn shared_rand_cur(&self) -> Option<&SharedRandStatus> {
70
44639
        self.preamble.shared_rand.shared_rand_current_value.as_ref()
71
44639
    }
72

            
73
    /// Return the previous shared random value, if the consensus
74
    /// contains one.
75
44639
    pub fn shared_rand_prev(&self) -> Option<&SharedRandStatus> {
76
44639
        self.preamble.shared_rand.shared_rand_previous_value.as_ref()
77
44639
    }
78

            
79
    /// Return a [`ProtoStatus`] that lists the network's current requirements and
80
    /// recommendations for the list of protocols that every relay must implement.  
81
2205
    pub fn relay_protocol_status(&self) -> &ProtoStatus {
82
2205
        &self.preamble.proto_statuses.relay
83
2205
    }
84

            
85
    /// Return a [`ProtoStatus`] that lists the network's current requirements and
86
    /// recommendations for the list of protocols that every client must implement.
87
    pub fn client_protocol_status(&self) -> &ProtoStatus {
88
        &self.preamble.proto_statuses.client
89
    }
90

            
91
    /// Return a set of all known [`ProtoStatus`] values.
92
49
    pub fn protocol_statuses(&self) -> &Arc<ProtoStatuses> {
93
49
        &self.preamble.proto_statuses
94
49
    }
95
}
96

            
97
impl Consensus {
98
    /// Return a new ConsensusBuilder for building test consensus objects.
99
    ///
100
    /// This function is only available when the `build_docs` feature has
101
    /// been enabled.
102
    #[cfg(feature = "build_docs")]
103
13773
    pub fn builder() -> ConsensusBuilder {
104
13773
        ConsensusBuilder::new(RouterStatus::flavor())
105
13773
    }
106

            
107
    /// Try to parse a single networkstatus document from a string.
108
410
    pub fn parse(s: &str) -> crate::Result<(&str, &str, UncheckedConsensus)> {
109
410
        let mut reader = NetDocReader::new(s)?;
110
422
        Self::parse_from_reader(&mut reader).map_err(|e| e.within(s))
111
410
    }
112
    /// Extract a voter-info section from the reader; return
113
    /// Ok(None) when we are out of voter-info sections.
114
1430
    fn take_voterinfo(
115
1430
        r: &mut NetDocReader<'_, NetstatusKwd>,
116
1430
    ) -> crate::Result<Option<ConsensusAuthorityEntry>> {
117
        use NetstatusKwd::*;
118

            
119
1430
        match r.peek() {
120
            None => return Ok(None),
121
1430
            Some(e) if e.is_ok_with_kwd_in(&[RS_R, DIRECTORY_FOOTER]) => return Ok(None),
122
1073
            _ => (),
123
        };
124

            
125
1073
        let mut first_dir_source = true;
126
        // TODO: Extract this pattern into a "pause at second"???
127
        // Pause at the first 'r', or the second 'dir-source'.
128
4671
        let mut p = r.pause_at(|i| match i {
129
            Err(_) => false,
130
4628
            Ok(item) => {
131
4628
                item.kwd() == RS_R
132
4243
                    || if item.kwd() == DIR_SOURCE {
133
1929
                        let was_first = first_dir_source;
134
1929
                        first_dir_source = false;
135
1929
                        !was_first
136
                    } else {
137
2314
                        false
138
                    }
139
            }
140
4628
        });
141

            
142
1073
        let voter_sec = NS_VOTERINFO_RULES_CONSENSUS.parse(&mut p)?;
143
1073
        let voter = ConsensusAuthorityEntry::from_section(&voter_sec)?;
144

            
145
1073
        Ok(Some(voter))
146
1430
    }
147

            
148
    /// Extract the footer (but not signatures) from the reader.
149
349
    fn take_footer(r: &mut NetDocReader<'_, NetstatusKwd>) -> crate::Result<ConsensusFooterFields> {
150
        use NetstatusKwd::*;
151
1141
        let mut p = r.pause_at(|i| i.is_ok_with_kwd_in(&[DIRECTORY_SIGNATURE]));
152
349
        let footer_sec = NS_FOOTER_RULES.parse(&mut p)?;
153
349
        let footer = ConsensusFooterFields::from_section(&footer_sec)?;
154
347
        Ok(footer)
155
349
    }
156

            
157
    /// Extract a routerstatus from the reader.  Return Ok(None) if we're
158
    /// out of routerstatus entries.
159
2275
    fn take_routerstatus(r: &mut NetDocReader<'_, NetstatusKwd>) -> crate::Result<Option<(Pos, RouterStatus)>> {
160
        use NetstatusKwd::*;
161
2275
        match r.peek() {
162
            None => return Ok(None),
163
2275
            Some(e) if e.is_ok_with_kwd_in(&[DIRECTORY_FOOTER]) => return Ok(None),
164
1926
            _ => (),
165
        };
166

            
167
1926
        let pos = r.pos();
168

            
169
1926
        let mut first_r = true;
170
16256
        let mut p = r.pause_at(|i| match i {
171
            Err(_) => false,
172
16186
            Ok(item) => {
173
16186
                item.kwd() == DIRECTORY_FOOTER
174
15807
                    || if item.kwd() == RS_R {
175
3777
                        let was_first = first_r;
176
3777
                        first_r = false;
177
3777
                        !was_first
178
                    } else {
179
12030
                        false
180
                    }
181
            }
182
16186
        });
183

            
184
1926
        let rules = match RouterStatus::flavor() {
185
1912
            ConsensusFlavor::Microdesc => &NS_ROUTERSTATUS_RULES_MDCON,
186
14
            ConsensusFlavor::Plain => &NS_ROUTERSTATUS_RULES_PLAIN,
187
        };
188

            
189
1926
        let rs_sec = rules.parse(&mut p)?;
190
1926
        let rs = RouterStatus::from_section(&rs_sec)?;
191
1920
        Ok(Some((pos, rs)))
192
2275
    }
193

            
194
    /// Extract an entire UncheckedConsensus from a reader.
195
    ///
196
    /// Returns the signed portion of the string, the remainder of the
197
    /// string, and an UncheckedConsensus.
198
410
    fn parse_from_reader<'a>(
199
410
        r: &mut NetDocReader<'a, NetstatusKwd>,
200
410
    ) -> crate::Result<(&'a str, &'a str, UncheckedConsensus)> {
201
        use NetstatusKwd::*;
202
357
        let ((flavor, preamble), start_pos) = {
203
5907
            let mut h = r.pause_at(|i| i.is_ok_with_kwd_in(&[DIR_SOURCE]));
204
410
            let preamble_sec = NS_HEADER_RULES_CONSENSUS.parse(&mut h)?;
205
            // Unwrapping should be safe because above `.parse` would have
206
            // returned an Error
207
            #[allow(clippy::unwrap_used)]
208
361
            let pos = preamble_sec.first_item().unwrap().offset_in(r.str()).unwrap();
209
361
            (Preamble::from_section(&preamble_sec)?, pos)
210
        };
211
357
        if RouterStatus::flavor() != flavor {
212
            return Err(EK::BadDocumentType.with_msg(format!(
213
                "Expected {:?}, got {:?}",
214
                RouterStatus::flavor(),
215
                flavor
216
            )));
217
357
        }
218

            
219
357
        let mut voters = Vec::new();
220

            
221
1430
        while let Some(voter) = Self::take_voterinfo(r)? {
222
1073
            voters.push(voter);
223
1073
        }
224

            
225
357
        let mut relays: Vec<RouterStatus> = Vec::new();
226
2275
        while let Some((pos, routerstatus)) = Self::take_routerstatus(r)? {
227
1920
            if let Some(prev) = relays.last() {
228
1565
                if prev.rsa_identity() >= routerstatus.rsa_identity() {
229
2
                    return Err(EK::WrongSortOrder.at_pos(pos));
230
1563
                }
231
355
            }
232
1918
            relays.push(routerstatus);
233
        }
234
349
        relays.shrink_to_fit();
235

            
236
349
        let footer = Self::take_footer(r)?;
237

            
238
347
        let consensus = Consensus {
239
347
            flavor,
240
347
            preamble,
241
347
            voters,
242
347
            relays,
243
347
            footer,
244
347
        };
245

            
246
        // Find the signatures.
247
347
        let mut first_sig: Option<Item<'_, NetstatusKwd>> = None;
248
347
        let mut signatures = Vec::new();
249
1043
        for item in &mut *r {
250
1043
            let item = item?;
251
1043
            if item.kwd() != DIRECTORY_SIGNATURE {
252
                return Err(EK::UnexpectedToken
253
                    .with_msg(item.kwd().to_str())
254
                    .at_pos(item.pos()));
255
1043
            }
256

            
257
1043
            let sig = Signature::from_item(&item)?;
258
1043
            if first_sig.is_none() {
259
347
                first_sig = Some(item);
260
696
            }
261
1043
            signatures.push(sig);
262
        }
263

            
264
347
        let end_pos = match first_sig {
265
            None => return Err(EK::MissingToken.with_msg("directory-signature")),
266
            // Unwrap should be safe because `first_sig` was parsed from `r`
267
            #[allow(clippy::unwrap_used)]
268
347
            Some(sig) => sig.offset_in(r.str()).unwrap() + "directory-signature ".len(),
269
        };
270

            
271
        // Find the appropriate digest.
272
347
        let signed_str = r.str().get(start_pos..end_pos).ok_or(internal!("chopped utf8"))?;
273
347
        let remainder = r.str().get(end_pos..).ok_or(internal!("chopped utf8"))?;
274
347
        let (sha256, sha1) = match RouterStatus::flavor() {
275
2
            ConsensusFlavor::Plain => (
276
2
                None,
277
2
                Some(ll::d::Sha1::digest(signed_str.as_bytes()).into()),
278
2
            ),
279
345
            ConsensusFlavor::Microdesc => (
280
345
                Some(ll::d::Sha256::digest(signed_str.as_bytes()).into()),
281
345
                None,
282
345
            ),
283
        };
284
347
        let hashes = DirectorySignaturesHashesAccu {
285
347
            sha256,
286
347
            sha1,
287
347
            // TODO #2530 This is wrong.  There isn't one hash, there's two.
288
347
            sha1_unnamed: sha1,
289
347
        };
290
347
        let siggroup = SignatureGroup {
291
347
            hashes,
292
347
            signatures,
293
347
        };
294

            
295
347
        let unval = UnvalidatedConsensus {
296
347
            consensus,
297
347
            siggroup,
298
347
            n_authorities: None,
299
347
        };
300
347
        let timebound_range = unval.consensus.preamble.validity_time_range();
301
347
        let timebound = TimeRangeBound::new(unval, timebound_range);
302
347
        Ok((signed_str, remainder, timebound))
303
410
    }
304
}
305

            
306
impl Preamble {
307
    /// Extract the CommonPreamble members from a single preamble section.
308
389
    fn from_section(sec: &Section<'_, NetstatusKwd>) -> crate::Result<(ConsensusFlavor, Preamble)> {
309
        use NetstatusKwd::*;
310

            
311
        {
312
            // this unwrap is safe because if there is not at least one
313
            // token in the section, the section is unparsable.
314
            #[allow(clippy::unwrap_used)]
315
389
            let first = sec.first_item().unwrap();
316
389
            if first.kwd() != NETWORK_STATUS_VERSION {
317
2
                return Err(EK::UnexpectedToken
318
2
                    .with_msg(first.kwd().to_str())
319
2
                    .at_pos(first.pos()));
320
387
            }
321
        }
322

            
323
387
        let ver_item = sec.required(NETWORK_STATUS_VERSION)?;
324

            
325
387
        let version: u32 = ver_item.parse_arg(0)?;
326
387
        if version != 3 {
327
2
            return Err(EK::BadDocumentVersion.with_msg(version.to_string()));
328
385
        }
329
385
        let flavor = ConsensusFlavor::from_opt_name(ver_item.arg(1))?;
330

            
331
385
        let valid_after = sec
332
385
            .required(VALID_AFTER)?
333
385
            .args_as_str()
334
385
            .parse::<Iso8601TimeSp>()?
335
385
            .into();
336
385
        let fresh_until = sec
337
385
            .required(FRESH_UNTIL)?
338
385
            .args_as_str()
339
385
            .parse::<Iso8601TimeSp>()?
340
385
            .into();
341
385
        let valid_until = sec
342
385
            .required(VALID_UNTIL)?
343
385
            .args_as_str()
344
385
            .parse::<Iso8601TimeSp>()?
345
385
            .into();
346
385
        let lifetime = Lifetime::new(valid_after, fresh_until, valid_until)?;
347

            
348
784
        let parse_rec_versions = |item| {
349
770
            let item = sec
350
770
                .maybe(item);
351
770
            let args = item
352
770
                .args_as_str()
353
770
                .unwrap_or("")
354
                // C Tor emits an item with trailing whitespace which we must ignore
355
770
                .trim();
356
            // We want only the first arg, according to the spec.
357
            // We could want to use MaybeItem::parse_arg, but it treats absence of the
358
            // argument as an error.  There is no parse_optional_arg on `MaybeItem`.
359
            // We could add that, but I am trying to avoid adding code to the old parser.
360
            // So instead we reimplement argument splitting (again).
361
770
            args
362
770
                .split_once(|c: char| c.is_ascii_whitespace()).map(|(l, _r)| l).unwrap_or(args)
363
770
                .parse()
364
770
                .map_err(|_e| EK::BadArgument.at_pos(item.pos()))
365
770
        };
366
385
        let client_versions = parse_rec_versions(CLIENT_VERSIONS)?;
367
385
        let server_versions = parse_rec_versions(SERVER_VERSIONS)?;
368

            
369
385
        let proto_statuses = {
370
385
            let client = ProtoStatus::from_section(
371
385
                sec,
372
385
                RECOMMENDED_CLIENT_PROTOCOLS,
373
385
                REQUIRED_CLIENT_PROTOCOLS,
374
            )?;
375
385
            let relay = ProtoStatus::from_section(
376
385
                sec,
377
385
                RECOMMENDED_RELAY_PROTOCOLS,
378
385
                REQUIRED_RELAY_PROTOCOLS,
379
            )?;
380
385
            Arc::new(ProtoStatuses { client, relay })
381
        };
382

            
383
385
        let params = sec.maybe(PARAMS).args_as_str().unwrap_or("").parse()?;
384

            
385
385
        let status: &str = sec.required(VOTE_STATUS)?.arg(0).unwrap_or("");
386
385
        if status != "consensus" {
387
            return Err(EK::BadDocumentType.err());
388
385
        }
389

            
390
        // We're ignoring KNOWN_FLAGS in the consensus.
391

            
392
385
        let consensus_method: u32 = sec.required(CONSENSUS_METHOD)?.parse_arg(0)?;
393

            
394
385
        let shared_rand_previous_value = sec
395
385
            .get(SHARED_RAND_PREVIOUS_VALUE)
396
385
            .map(SharedRandStatus::from_item)
397
385
            .transpose()?;
398

            
399
385
        let shared_rand_current_value = sec
400
385
            .get(SHARED_RAND_CURRENT_VALUE)
401
385
            .map(SharedRandStatus::from_item)
402
385
            .transpose()?;
403

            
404
385
        let voting_delay = if let Some(tok) = sec.get(VOTING_DELAY) {
405
385
            let n1 = tok.parse_arg(0)?;
406
385
            let n2 = tok.parse_arg(1)?;
407
385
            Some((n1, n2))
408
        } else {
409
            None
410
        };
411

            
412
385
        let shared_rand = SharedRandStatuses {
413
385
            shared_rand_previous_value,
414
385
            shared_rand_current_value,
415
385
            __non_exhaustive: (),
416
385
        };
417

            
418
385
        let preamble = Preamble {
419
385
            lifetime,
420
385
            client_versions,
421
385
            server_versions,
422
385
            proto_statuses,
423
385
            params,
424
385
            voting_delay,
425
385
            consensus_method: (consensus_method,),
426
385
            published: NotPresent,
427
385
            consensus_methods: NotPresent,
428
385
            known_flags: DocRelayFlags::new_empty_unknown_discarded(),
429
385
            shared_rand,
430
385
            __non_exhaustive: (),
431
385
        };
432

            
433
385
        Ok((flavor, preamble))
434
389
    }
435
}
436

            
437
/// A Microdesc consensus whose signatures have not yet been checked.
438
///
439
/// To validate this object, call set_n_authorities() on it, then call
440
/// check_signature() on that result with the set of certs that you
441
/// have.  Make sure only to provide authority certificates representing
442
/// real authorities!
443
#[derive(Debug, Clone)]
444
#[non_exhaustive]
445
pub struct UnvalidatedConsensus {
446
    /// The consensus object. We don't want to expose this until it's
447
    /// validated.
448
    pub consensus: Consensus,
449
    /// The signatures that need to be validated before we can call
450
    /// this consensus valid.
451
    pub siggroup: SignatureGroup,
452
    /// The total number of authorities that we believe in.  We need
453
    /// this information in order to validate the signatures, since it
454
    /// determines how many signatures we need to find valid in `siggroup`.
455
    pub n_authorities: Option<usize>,
456
}
457

            
458
impl UnvalidatedConsensus {
459
    /// Tell the unvalidated consensus how many authorities we believe in.
460
    ///
461
    /// Without knowing this number, we can't validate the signature.
462
    #[must_use]
463
249
    pub fn set_n_authorities(self, n_authorities: usize) -> Self {
464
249
        UnvalidatedConsensus {
465
249
            n_authorities: Some(n_authorities),
466
249
            ..self
467
249
        }
468
249
    }
469

            
470
    /// Return an iterator of all the certificate IDs that we might use
471
    /// to validate this consensus.
472
196
    pub fn signing_cert_ids(&self) -> impl Iterator<Item = AuthCertKeyIds> {
473
196
        match self.key_is_correct(&[]) {
474
            Ok(()) => Vec::new(),
475
196
            Err(missing) => missing,
476
        }
477
196
        .into_iter()
478
196
    }
479

            
480
    /// Return the lifetime of this unvalidated consensus
481
245
    pub fn peek_lifetime(&self) -> &Lifetime {
482
245
        self.consensus.lifetime()
483
245
    }
484

            
485
    /// Return true if a client who believes in exactly the provided
486
    /// set of authority IDs might consider this consensus to be
487
    /// well-signed.
488
    ///
489
    /// (This is the case if the consensus claims to be signed by more than
490
    /// half of the authorities in the list.)
491
255
    pub fn authorities_are_correct(&self, authorities: &[&RsaIdentity]) -> bool {
492
255
        self.siggroup.could_validate(authorities)
493
255
    }
494

            
495
    /// Return the number of relays in this unvalidated consensus.
496
    ///
497
    /// This function is unstable. It is only enabled if the crate was
498
    /// built with the `experimental-api` feature.
499
    #[cfg(feature = "experimental-api")]
500
    pub fn n_relays(&self) -> usize {
501
        self.consensus.relays.len()
502
    }
503

            
504
    /// Modify the list of relays in this unvalidated consensus.
505
    ///
506
    /// A use case for this is long-lasting custom directories. To ensure Arti can still quickly
507
    /// build circuits when the directory gets old, a tiny churn file can be regularly obtained,
508
    /// listing no longer available Tor nodes, which can then be removed from the consensus.
509
    ///
510
    /// This function is unstable. It is only enabled if the crate was
511
    /// built with the `experimental-api` feature.
512
    #[cfg(feature = "experimental-api")]
513
    pub fn modify_relays<F>(&mut self, func: F)
514
    where
515
        F: FnOnce(&mut Vec<RouterStatus>),
516
    {
517
        func(&mut self.consensus.relays);
518
    }
519
}
520

            
521
impl ExternallySigned<Consensus> for UnvalidatedConsensus {
522
    type Key = [AuthCert];
523
    type KeyHint = Vec<AuthCertKeyIds>;
524
    type Error = Error;
525

            
526
306
    fn key_is_correct(&self, k: &Self::Key) -> result::Result<(), Self::KeyHint> {
527
306
        let (n_ok, missing) = self.siggroup.list_missing(k);
528
306
        match self.n_authorities {
529
306
            Some(n) if consensus_threshold(n).contains(&n_ok) => Ok(()),
530
251
            _ => Err(missing.iter().map(|cert| cert.key_ids).collect()),
531
        }
532
306
    }
533
55
    fn is_well_signed(&self, k: &Self::Key) -> result::Result<(), Self::Error> {
534
55
        match self.n_authorities {
535
            None => Err(Error::from(internal!(
536
                "Didn't set authorities on consensus"
537
            ))),
538
55
            Some(authority) => {
539
55
                self.siggroup.validate(authority, k)
540
56
                    .map_err(|_: VerifyFailed| EK::BadSignature.err())
541
            }
542
        }
543
55
    }
544
151
    fn dangerously_assume_wellsigned(self) -> Consensus {
545
151
        self.consensus
546
151
    }
547
}
548

            
549
/// A Consensus object that has been parsed, but not checked for
550
/// signatures and timeliness.
551
pub type UncheckedConsensus = TimeRangeBound<UnvalidatedConsensus>;
552

            
553
impl NetworkStatusUnverified {
554
    /// Could we verify this consensus or do we need more authcerts?
555
    ///
556
    /// `Ok` means that we have enough authcerts to verify the signature.
557
    ///
558
    /// `Err` means that we have not enough authcerts,
559
    /// or the consensus has not enough signatures.
560
    /// The [`ConsensusVerifiabilityError`] error gives the details.
561
20
    pub fn can_verify(
562
20
        &self,
563
20
        trusted_authorities: &[RsaIdentity],
564
20
        certs_already: &[AuthCert],
565
20
    ) -> Result<(), ConsensusVerifiabilityError> {
566
20
        let sigs = self.inspect_unverified().1;
567
20
        Self::verify_general(
568
20
            sigs,
569
20
            trusted_authorities,
570
20
            certs_already,
571
48
            |_signature| {
572
                // indeed, we don't actuaally verify, so this is a no-op
573
48
                Ok(SignatureVerifiedIfIntended {})
574
48
            },
575
12
        )?;
576
8
        Ok(())
577
20
    }
578

            
579
    /// Verify the signatures
580
    ///
581
    /// Doesn't check the validity period:
582
    /// the document is wrapped in [`TimeRangeBound`],
583
    /// ensuring that the caller does that check.
584
24
    pub fn verify(
585
24
        self,
586
24
        trusted_authorities: &[RsaIdentity],
587
24
        certs: &[AuthCert],
588
24
    ) -> Result<TimeRangeBound<NetworkStatus>, ConsensusVerifyFailed> {
589
24
        let (body, sigs) = self.unwrap_unverified();
590

            
591
24
        Self::verify_general(
592
24
            &sigs,
593
24
            trusted_authorities,
594
24
            certs,
595
64
            |tv| tv.verify().map_err(ConsensusVerifyFailed::InvalidSignature),
596
16
        )?;
597

            
598
8
        let time_range = body.preamble.validity_time_range();
599
8
        Ok(TimeRangeBound::new(
600
8
            body,
601
8
            time_range,
602
8
        ))
603
24
    }
604

            
605
    /// Glue to call `SignatureGroup::verify_general` given our `SignaturesData`
606
    ///
607
    /// [`SignatureGroup::verify_general`] contains the actual verification code,
608
    /// shared between the old parser and the new.
609
44
    fn verify_general<E>(
610
44
        sigs: &parse2::SignaturesData<Self>,
611
44
        trusted: &[RsaIdentity],
612
44
        certs: &[AuthCert],
613
44
        do_verify: impl Fn(ConsensusSignatureToVerify) -> Result<SignatureVerifiedIfIntended, E>,
614
44
    ) -> Result<(), E>
615
44
    where ConsensusVerifiabilityError: Into<E>,
616
    {
617
44
        SignatureGroup {
618
44
            hashes: sigs.hashes,
619
44
            signatures: sigs.sigs.directory_signature.clone(),
620
44
        }.verify_general(
621
44
            VerifyGeneralTrustedAuthorities::TrustThese { trusted },
622
44
            certs,
623
44
            do_verify,
624
        )
625
44
    }
626
}
627

            
628
#[cfg(feature = "retain-unknown")]
629
#[test]
630
4
fn verify_error_netstatus() -> Result<(), anyhow::Error> {
631
    use assert_matches::assert_matches;
632
    use ConsensusVerifiabilityError as CVE;
633

            
634
4
    let file = ns_expr!(
635
2
        "testdata2/cached-consensus",
636
2
        "testdata2/cached-microdesc-consensus",
637
        unreachable(),
638
    );
639
4
    let (mut doc, _text, certs, authorities, _now) =
640
4
        super::test::prep_netstatus_verify::<NetworkStatusUnverified>(file)?;
641

            
642
    macro_rules! assert_consensus_verifiability_error { {
643
        ( $($verify_args:tt)* ),
644
        $($assert_matches_rhs:tt)*
645
    } => {
646
        assert_matches! {
647
            doc.can_verify($($verify_args)*),
648
            Err(e)
649
                => assert_matches!(e, $($assert_matches_rhs)*)
650
        };
651
        assert_matches! {
652
            doc.clone().verify($($verify_args)*),
653
            Err(ConsensusVerifyFailed::CertificationInsufficient(e))
654
                => assert_matches!(e, $($assert_matches_rhs)*)
655
        };
656
    } }
657

            
658
    // missing authcerts
659

            
660
4
    assert_consensus_verifiability_error! {
661
4
        (&authorities, &certs[..1]),
662
4
        ConsensusVerifiabilityError::MissingAuthCerts { deficit, missing } => {
663
4
            assert_eq!(deficit, authorities.len() / 2); // one short of strict majority
664
4
            itertools::assert_equal(
665
4
                missing.into_iter().sorted(),
666
26
                certs[1..].iter().map(|a| a.key_ids()).sorted(),
667
            );
668
        }
669
    }
670

            
671
    // wrong signers
672

            
673
4
    let wrong_authorities = authorities
674
4
        .iter()
675
4
        .cloned()
676
4
        .enumerate()
677
18
        .map(|(i, a)| {
678
16
            if i < 2 {
679
8
                [i as u8; _].into()
680
            } else {
681
8
                a
682
            }
683
16
        })
684
4
        .collect_vec();
685

            
686
4
    assert_consensus_verifiability_error! {
687
4
        (&wrong_authorities, &certs),
688
        CVE::InsufficientTrustedSigners
689
    }
690

            
691
    // one broken signature, but enough others
692

            
693
4
    doc.sigs.sigs.directory_signature[0].signature.fill(0xff);
694

            
695
    assert_matches! {
696
4
        doc.can_verify(&authorities, &certs),
697
        Ok(())
698
    }
699
    assert_matches! {
700
4
        doc.clone().verify(&authorities, &certs),
701
        Ok(_)
702
    }
703

            
704
    // too few signatories, and one broken signature
705

            
706
4
    doc.sigs.sigs.directory_signature.truncate(authorities.len() / 2 + 1);
707

            
708
    assert_matches! {
709
4
        doc.can_verify(&authorities, &certs),
710
        Ok(())
711
    }
712
    assert_matches! {
713
4
        doc.clone().verify(&authorities, &certs),
714
        Err(ConsensusVerifyFailed::InvalidSignature(VerifyFailed::VerifyFailed))
715
    }
716

            
717
    // too few signatures, no broken signatures
718

            
719
4
    doc.sigs.sigs.directory_signature.remove(0);
720

            
721
4
    assert_consensus_verifiability_error! {
722
4
        (&authorities, &certs),
723
        CVE::InsufficientTrustedSigners
724
    }
725

            
726
4
    Ok(())
727
4
}