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
    pub fn lifetime(&self) -> &Lifetime {
48
        &self.preamble.lifetime
49
    }
50

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

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

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

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

            
73
    /// Return the previous shared random value, if the consensus
74
    /// contains one.
75
    pub fn shared_rand_prev(&self) -> Option<&SharedRandStatus> {
76
        self.preamble.shared_rand.shared_rand_previous_value.as_ref()
77
    }
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
    pub fn relay_protocol_status(&self) -> &ProtoStatus {
82
        &self.preamble.proto_statuses.relay
83
    }
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
    pub fn protocol_statuses(&self) -> &Arc<ProtoStatuses> {
93
        &self.preamble.proto_statuses
94
    }
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
2
    pub fn builder() -> ConsensusBuilder {
104
2
        ConsensusBuilder::new(RouterStatus::flavor())
105
2
    }
106

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

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

            
125
22
        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
88
        let mut p = r.pause_at(|i| match i {
129
            Err(_) => false,
130
            Ok(item) => {
131
88
                item.kwd() == RS_R
132
81
                    || if item.kwd() == DIR_SOURCE {
133
37
                        let was_first = first_dir_source;
134
37
                        first_dir_source = false;
135
37
                        !was_first
136
                    } else {
137
44
                        false
138
                    }
139
            }
140
88
        });
141

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

            
145
22
        Ok(Some(voter))
146
29
    }
147

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

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

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

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

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

            
189
38
        let rs_sec = rules.parse(&mut p)?;
190
38
        let rs = RouterStatus::from_section(&rs_sec)?;
191
35
        Ok(Some((pos, rs)))
192
41
    }
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
9
    fn parse_from_reader<'a>(
199
9
        r: &mut NetDocReader<'a, NetstatusKwd>,
200
9
    ) -> crate::Result<(&'a str, &'a str, UncheckedConsensus)> {
201
        use NetstatusKwd::*;
202
        let ((flavor, preamble), start_pos) = {
203
136
            let mut h = r.pause_at(|i| i.is_ok_with_kwd_in(&[DIR_SOURCE]));
204
9
            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
9
            let pos = preamble_sec.first_item().unwrap().offset_in(r.str()).unwrap();
209
9
            (Preamble::from_section(&preamble_sec)?, pos)
210
        };
211
7
        if RouterStatus::flavor() != flavor {
212
            return Err(EK::BadDocumentType.with_msg(format!(
213
                "Expected {:?}, got {:?}",
214
                RouterStatus::flavor(),
215
                flavor
216
            )));
217
7
        }
218

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

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

            
225
7
        let mut relays: Vec<RouterStatus> = Vec::new();
226
41
        while let Some((pos, routerstatus)) = Self::take_routerstatus(r)? {
227
35
            if let Some(prev) = relays.last() {
228
29
                if prev.rsa_identity() >= routerstatus.rsa_identity() {
229
1
                    return Err(EK::WrongSortOrder.at_pos(pos));
230
28
                }
231
6
            }
232
34
            relays.push(routerstatus);
233
        }
234
3
        relays.shrink_to_fit();
235

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

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

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

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

            
264
2
        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
2
            Some(sig) => sig.offset_in(r.str()).unwrap() + "directory-signature ".len(),
269
        };
270

            
271
        // Find the appropriate digest.
272
2
        let signed_str = r
273
2
            .str()
274
2
            .get(start_pos..end_pos)
275
            .ok_or_else(|| internal!("chopped utf8"))?;
276
2
        let remainder = r
277
2
            .str()
278
2
            .get(end_pos..)
279
            .ok_or_else(|| internal!("chopped utf8"))?;
280
2
        let (sha256, sha1) = match RouterStatus::flavor() {
281
1
            ConsensusFlavor::Plain => (
282
1
                None,
283
1
                Some(ll::d::Sha1::digest(signed_str.as_bytes()).into()),
284
1
            ),
285
1
            ConsensusFlavor::Microdesc => (
286
1
                Some(ll::d::Sha256::digest(signed_str.as_bytes()).into()),
287
1
                None,
288
1
            ),
289
        };
290
2
        let hashes = DirectorySignaturesHashesAccu {
291
2
            sha256,
292
2
            sha1,
293
2
        };
294
2
        let siggroup = SignatureGroup {
295
2
            hashes,
296
2
            signatures,
297
2
        };
298

            
299
2
        let unval = UnvalidatedConsensus {
300
2
            consensus,
301
2
            siggroup,
302
2
            n_authorities: None,
303
2
        };
304
2
        let timebound_range = unval.consensus.preamble.validity_time_range();
305
2
        let timebound = TimeRangeBound::new(unval, timebound_range);
306
2
        Ok((signed_str, remainder, timebound))
307
9
    }
308
}
309

            
310
impl Preamble {
311
    /// Extract the CommonPreamble members from a single preamble section.
312
9
    fn from_section(sec: &Section<'_, NetstatusKwd>) -> crate::Result<(ConsensusFlavor, Preamble)> {
313
        use NetstatusKwd::*;
314

            
315
        {
316
            // this unwrap is safe because if there is not at least one
317
            // token in the section, the section is unparsable.
318
            #[allow(clippy::unwrap_used)]
319
9
            let first = sec.first_item().unwrap();
320
9
            if first.kwd() != NETWORK_STATUS_VERSION {
321
1
                return Err(EK::UnexpectedToken
322
1
                    .with_msg(first.kwd().to_str())
323
1
                    .at_pos(first.pos()));
324
8
            }
325
        }
326

            
327
8
        let ver_item = sec.required(NETWORK_STATUS_VERSION)?;
328

            
329
8
        let version: u32 = ver_item.parse_arg(0)?;
330
8
        if version != 3 {
331
1
            return Err(EK::BadDocumentVersion.with_msg(version.to_string()));
332
7
        }
333
7
        let flavor = ConsensusFlavor::from_opt_name(ver_item.arg(1))?;
334

            
335
7
        let valid_after = sec
336
7
            .required(VALID_AFTER)?
337
            .args_as_str()
338
            .parse::<Iso8601TimeSp>()?
339
            .into();
340
7
        let fresh_until = sec
341
7
            .required(FRESH_UNTIL)?
342
            .args_as_str()
343
            .parse::<Iso8601TimeSp>()?
344
            .into();
345
7
        let valid_until = sec
346
7
            .required(VALID_UNTIL)?
347
            .args_as_str()
348
            .parse::<Iso8601TimeSp>()?
349
            .into();
350
7
        let lifetime = Lifetime::new(valid_after, fresh_until, valid_until)?;
351

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

            
373
        let proto_statuses = {
374
7
            let client = ProtoStatus::from_section(
375
7
                sec,
376
7
                RECOMMENDED_CLIENT_PROTOCOLS,
377
7
                REQUIRED_CLIENT_PROTOCOLS,
378
7
            )?;
379
7
            let relay = ProtoStatus::from_section(
380
7
                sec,
381
7
                RECOMMENDED_RELAY_PROTOCOLS,
382
7
                REQUIRED_RELAY_PROTOCOLS,
383
7
            )?;
384
7
            Arc::new(ProtoStatuses { client, relay, __non_exhaustive: () })
385
        };
386

            
387
7
        let params = sec.maybe(PARAMS).args_as_str().unwrap_or("").parse()?;
388
7
        let params = NetParams { params };
389

            
390
7
        let status: &str = sec.required(VOTE_STATUS)?.arg(0).unwrap_or("");
391
7
        if status != "consensus" {
392
            return Err(EK::BadDocumentType.err());
393
7
        }
394

            
395
        // We're ignoring KNOWN_FLAGS in the consensus.
396

            
397
7
        let consensus_method: u32 = sec.required(CONSENSUS_METHOD)?.parse_arg(0)?;
398

            
399
7
        let shared_rand_previous_value = sec
400
7
            .get(SHARED_RAND_PREVIOUS_VALUE)
401
7
            .map(SharedRandStatus::from_item)
402
7
            .transpose()?;
403

            
404
7
        let shared_rand_current_value = sec
405
7
            .get(SHARED_RAND_CURRENT_VALUE)
406
7
            .map(SharedRandStatus::from_item)
407
7
            .transpose()?;
408

            
409
        let voting_delay = {
410
7
            let tok = sec.required(VOTING_DELAY)?;
411
7
            let vote_seconds = tok.parse_arg(0)?;
412
7
            let dist_seconds = tok.parse_arg(1)?;
413
7
            VotingDelayConstructor { vote_seconds, dist_seconds }.construct()
414
        };
415

            
416
7
        let shared_rand = SharedRandStatuses {
417
7
            shared_rand_previous_value,
418
7
            shared_rand_current_value,
419
7
            __non_exhaustive: (),
420
7
        };
421

            
422
7
        let preamble = Preamble {
423
7
            lifetime,
424
7
            client_versions,
425
7
            server_versions,
426
7
            proto_statuses,
427
7
            params,
428
7
            voting_delay,
429
7
            consensus_method: (consensus_method,),
430
7
            published: NotPresent,
431
7
            consensus_methods: NotPresent,
432
7
            known_flags: DocRelayFlags::new_empty_unknown_discarded(),
433
7
            shared_rand,
434
7
            __non_exhaustive: (),
435
7
        };
436

            
437
7
        Ok((flavor, preamble))
438
9
    }
439
}
440

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

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

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

            
484
    /// Return the lifetime of this unvalidated consensus
485
    pub fn peek_lifetime(&self) -> &Lifetime {
486
        self.consensus.lifetime()
487
    }
488

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

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

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

            
525
impl ExternallySigned<Consensus> for UnvalidatedConsensus {
526
    type Key = [AuthCert];
527
    type KeyHint = Vec<AuthCertKeyIds>;
528
    type Error = Error;
529

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

            
553
/// A Consensus object that has been parsed, but not checked for
554
/// signatures and timeliness.
555
pub type UncheckedConsensus = TimeRangeBound<UnvalidatedConsensus>;
556

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

            
583
    /// Verify the signatures
584
    ///
585
    /// Doesn't check the validity period:
586
    /// the document is wrapped in [`TimeRangeBound`],
587
    /// ensuring that the caller does that check.
588
436
    pub fn verify(
589
436
        self,
590
436
        trusted_authorities: &[RsaIdentity],
591
436
        certs: &[AuthCert],
592
436
    ) -> Result<TimeRangeBound<NetworkStatus>, ConsensusVerifyFailed> {
593
436
        self.verify_sophisticated(trusted_authorities, certs).map_err(|(e, _u)| e)
594
436
    }
595

            
596
    /// Verify the signature, for sophisticated callers
597
    ///
598
    /// Like [`verify`](NetworkStatusUnverified::verify)
599
    /// but returns the input again, on error.
600
436
    pub fn verify_sophisticated(
601
436
        self,
602
436
        trusted_authorities: &[RsaIdentity],
603
436
        certs: &[AuthCert],
604
436
    ) -> Result<TimeRangeBound<NetworkStatus>, (ConsensusVerifyFailed, NetworkStatusUnverified)> {
605
436
        let (_body, sigs) = self.inspect_unverified();
606

            
607
436
        let body = match Self::verify_general(
608
436
            sigs,
609
436
            trusted_authorities,
610
436
            certs,
611
1410
            |tv| tv.verify().map_err(ConsensusVerifyFailed::InvalidSignature),
612
        ) {
613
375
            Ok(()) => self.unwrap_unverified().0,
614
61
            Err(e) => return Err((e, self)), // map_err would consume self
615
        };
616

            
617
375
        let time_range = body.preamble.validity_time_range();
618
375
        Ok(TimeRangeBound::new(
619
375
            body,
620
375
            time_range,
621
375
        ))
622
436
    }
623

            
624
    /// Glue to call `SignatureGroup::verify_general` given our `SignaturesData`
625
    ///
626
    /// [`SignatureGroup::verify_general`] contains the actual verification code,
627
    /// shared between the old parser and the new.
628
1082
    fn verify_general<E>(
629
1082
        sigs: &parse2::SignaturesData<Self>,
630
1082
        trusted: &[RsaIdentity],
631
1082
        certs: &[AuthCert],
632
1082
        do_verify: impl Fn(ConsensusSignatureToVerify) -> Result<SignatureVerifiedIfIntended, E>,
633
1082
    ) -> Result<(), E>
634
1082
    where ConsensusVerifiabilityError: Into<E>,
635
    {
636
1082
        SignatureGroup {
637
1082
            hashes: sigs.hashes,
638
1082
            signatures: sigs.sigs.directory_signature.clone(),
639
1082
        }.verify_general(
640
1082
            VerifyGeneralTrustedAuthorities::TrustThese { trusted },
641
1082
            certs,
642
1082
            do_verify,
643
1082
        )
644
1082
    }
645
}
646

            
647
#[cfg(feature = "retain-unknown")]
648
#[test]
649
2
fn verify_error_netstatus() -> Result<(), anyhow::Error> {
650
    use assert_matches::assert_matches;
651
    use ConsensusVerifiabilityError as CVE;
652

            
653
    let file = ns_expr!(
654
1
        "testdata2/cached-consensus",
655
1
        "testdata2/cached-microdesc-consensus",
656
        unreachable(),
657
    );
658
    let (mut doc, _text, certs, authorities, _now) =
659
2
        super::test::prep_netstatus_verify::<NetworkStatusUnverified>(file)?;
660

            
661
    macro_rules! assert_consensus_verifiability_error { {
662
        ( $($verify_args:tt)* ),
663
        $($assert_matches_rhs:tt)*
664
    } => {
665
        assert_matches!(
666
            doc.can_verify($($verify_args)*),
667
            Err(e)
668
                => assert_matches!(e, $($assert_matches_rhs)*)
669
        );
670
        assert_matches!(
671
            doc.clone().verify($($verify_args)*),
672
            Err(ConsensusVerifyFailed::CertificationInsufficient(e))
673
                => assert_matches!(e, $($assert_matches_rhs)*)
674
        );
675
    } }
676

            
677
    // missing authcerts
678

            
679
2
    assert_consensus_verifiability_error! {
680
2
        (&authorities, &certs[..1]),
681
        ConsensusVerifiabilityError::MissingAuthCerts { deficit, missing } => {
682
2
            assert_eq!(deficit, authorities.len() / 2); // one short of strict majority
683
2
            itertools::assert_equal(
684
2
                missing.into_iter().sorted(),
685
12
                certs[1..].iter().map(|a| a.key_ids()).sorted(),
686
            );
687
        }
688
    }
689

            
690
    // wrong signers
691

            
692
2
    let wrong_authorities = authorities
693
2
        .iter()
694
2
        .cloned()
695
2
        .enumerate()
696
8
        .map(|(i, a)| {
697
8
            if i < 2 {
698
4
                [i as u8; _].into()
699
            } else {
700
4
                a
701
            }
702
8
        })
703
        .collect_vec();
704

            
705
2
    assert_consensus_verifiability_error! {
706
2
        (&wrong_authorities, &certs),
707
        CVE::InsufficientTrustedSigners
708
    }
709

            
710
    // one broken signature, but enough others
711

            
712
2
    doc.sigs.sigs.directory_signature[0].signature.fill(0xff);
713

            
714
2
    assert_matches!(
715
2
        doc.can_verify(&authorities, &certs),
716
        Ok(())
717
    );
718
2
    assert_matches!(
719
2
        doc.clone().verify(&authorities, &certs),
720
        Ok(_)
721
    );
722

            
723
    // too few signatories, and one broken signature
724

            
725
2
    doc.sigs.sigs.directory_signature.truncate(authorities.len() / 2 + 1);
726

            
727
2
    assert_matches!(
728
2
        doc.can_verify(&authorities, &certs),
729
        Ok(())
730
    );
731
2
    assert_matches!(
732
2
        doc.clone().verify(&authorities, &certs),
733
        Err(ConsensusVerifyFailed::InvalidSignature(VerifyFailed::VerifyFailed))
734
    );
735

            
736
    // too few signatures, no broken signatures
737

            
738
2
    doc.sigs.sigs.directory_signature.remove(0);
739

            
740
2
    assert_consensus_verifiability_error! {
741
2
        (&authorities, &certs),
742
        CVE::InsufficientTrustedSigners
743
    }
744

            
745
2
    Ok(())
746
2
}