1
//! Information about directory authorities
2
//!
3
//! From a client's point of view, an authority's role is to sign the
4
//! consensus directory.
5

            
6
use std::net::SocketAddr;
7

            
8
use derive_deftly::Deftly;
9
use getset::Getters;
10
use tor_config::define_list_builder_accessors;
11
use tor_config::derive::prelude::*;
12
use tor_llcrypto::pk::rsa::RsaIdentity;
13

            
14
/// The contact information for all directory authorities this implementation is
15
/// aware of.
16
///
17
/// This data structure makes use of proposal 330 in order to distinguish
18
/// authorities by their responsibilities, hence why the fields are divided.
19
#[derive(Debug, Clone, Deftly, Eq, PartialEq, Getters)]
20
#[derive_deftly(TorConfig)]
21
pub struct AuthorityContacts {
22
    // NOTE: We aren't using list builders here, since these never actually used sub-builders,
23
    // and therefore has a slightly different API.
24
    // We might later decide to change these to proper list-builders;
25
    // if so, it will be an API break.
26
    //
27
    /// The [`RsaIdentity`] keys that may be used to sign valid consensus documents.
28
    #[deftly(tor_config(no_magic, setter(skip), default = "default_v3idents()"))]
29
    #[getset(get = "pub")]
30
    v3idents: Vec<RsaIdentity>,
31

            
32
    /// The endpoints of authorities where upload of router descriptors and other
33
    /// documents is possible.
34
    ///
35
    /// This section is primarily of interest for relays.
36
    ///
37
    /// The use of nested a [`Vec`] serves the purpose to assign multiple IPs to
38
    /// a single logical authority, such as having an IPv4 and IPv6 address.
39
    #[deftly(tor_config(no_magic, setter(skip), default = "default_uploads()"))]
40
    #[getset(get = "pub")]
41
    uploads: Vec<Vec<SocketAddr>>,
42

            
43
    /// The endpoints of authorities where download of network documents is possible.
44
    ///
45
    /// This section is primarily of interest for directory mirrors.
46
    ///
47
    /// The use of nested a [`Vec`] serves the purpose to assign multiple IPs to
48
    /// a single logical authority, such as having an IPv4 and IPv6 address.
49
    #[deftly(tor_config(no_magic, setter(skip), default = "default_downloads()"))]
50
    #[getset(get = "pub")]
51
    downloads: Vec<Vec<SocketAddr>>,
52

            
53
    /// The endpoints of authorities where voting for consensus documents is possible.
54
    ///
55
    /// This section is primarily of interest for other directory authorities.
56
    ///
57
    /// The use of nested a [`Vec`] serves the purpose to assign multiple IPs to
58
    /// a single logical authority, such as having an IPv4 and IPv6 address.
59
    #[deftly(tor_config(no_magic, setter(skip), default = "default_votes()"))]
60
    #[getset(get = "pub")]
61
    votes: Vec<Vec<SocketAddr>>,
62
}
63

            
64
define_list_builder_accessors! {
65
    struct AuthorityContactsBuilder {
66
        pub v3idents: [RsaIdentity],
67
        pub uploads: [Vec<SocketAddr>],
68
        pub downloads: [Vec<SocketAddr>],
69
        pub votes: [Vec<SocketAddr>],
70
    }
71
}
72

            
73
impl AuthorityContacts {
74
    /// Do any identity or IP address entries intersect with `other`?
75
    ///
76
    /// This compares the flattened lists of entries field-by-field.
77
    ///
78
    /// This is intended to be used to compare an `AuthorityContacts` as
79
    /// configured by the user with the default `AuthorityContacts`,
80
    /// to detect if the configured authority contacts use any of
81
    /// the authorities from the "live" Tor network.
82
    pub fn intersects(&self, other: &Self) -> bool {
83
        /// Check for an intersection between two lists of lists of `SocketAddr`s,
84
        /// but flatten them once first.
85
        fn flatten_addrs_intersect<'a, I>(a: I, b: I) -> bool
86
        where
87
            I: IntoIterator,
88
            I::Item: IntoIterator<Item = &'a SocketAddr>,
89
        {
90
            let mut a = a.into_iter().flatten();
91
            let mut b = b.into_iter().flatten();
92
            a.any(|x| b.any(|y| x == y))
93
        }
94

            
95
        // Destructure so that we ensure we consider each field.
96
        #[deny(unused)]
97
        let Self {
98
            v3idents,
99
            uploads,
100
            downloads,
101
            votes,
102
        } = self;
103

            
104
        if v3idents.iter().any(|id| other.v3idents.contains(id)) {
105
            return true;
106
        }
107

            
108
        if flatten_addrs_intersect(uploads, &other.uploads) {
109
            return true;
110
        }
111

            
112
        if flatten_addrs_intersect(downloads, &other.downloads) {
113
            return true;
114
        }
115

            
116
        if flatten_addrs_intersect(votes, &other.votes) {
117
            return true;
118
        }
119

            
120
        false
121
    }
122
}
123

            
124
/// Returns a list of the default [`RsaIdentity`]s for the directory authorities.
125
7568
fn default_v3idents() -> Vec<RsaIdentity> {
126
68112
    fn rsa(hex: &str) -> RsaIdentity {
127
68112
        RsaIdentity::from_hex(hex).expect("invalid hex?!?")
128
68112
    }
129

            
130
7568
    vec![
131
7568
        rsa("0232AF901C31A04EE9848595AF9BB7620D4C5B2E"), // dannenberg
132
7568
        rsa("E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58"), // dizum
133
7568
        rsa("70849B868D606BAECFB6128C5E3D782029AA394F"), // faravahar
134
7568
        rsa("ED03BB616EB2F60BEC80151114BB25CEF515B226"), // gabelmoo
135
7568
        rsa("23D15D965BC35114467363C165C4F724B64B4F66"), // longclaw
136
7568
        rsa("49015F787433103580E3B66A1707A00E60F2D15B"), // maatuska
137
7568
        rsa("F533C81CEF0BC0267857C99B2F471ADF249FA232"), // moria1
138
7568
        rsa("E30CF7B3DFA63FBDC5FC9E46EC75C543AB6D7403"), // sekhmet
139
7568
        rsa("2F3DF9CA0E5D36F2685A2DA67184EB8DCB8CBA8C"), // tor26
140
    ]
141
7568
}
142

            
143
/// Returns a list of the [`SocketAddr`] for the directory authorities.
144
///
145
/// The nested [`Vec`] serves dual-stack purposes
146
/// (i.e. many IPs mapping to one logical authority).
147
23607
fn default_uploads() -> Vec<Vec<SocketAddr>> {
148
    /// Converts a [`str`] to a [`SocketAddr`].
149
377712
    fn sa(s: &str) -> SocketAddr {
150
377712
        s.parse().expect("invalid socket address?!?")
151
377712
    }
152

            
153
23607
    vec![
154
        // dannenberg
155
23607
        vec![sa("193.23.244.244:80"), sa("[2001:678:558:1000::244]:80")],
156
        // dizum
157
23607
        vec![sa("45.66.35.11:80"), sa("[2a09:61c0::1337]:80")],
158
        // faravahar
159
23607
        vec![sa("216.218.219.41:80"), sa("[2001:470:164:2::2]:80")],
160
        // gabelmoo
161
23607
        vec![
162
23607
            sa("131.188.40.189:80"),
163
23607
            sa("[2001:638:a000:4140::ffff:189]:80"),
164
        ],
165
        // longclaw
166
23607
        vec![sa("199.58.81.140:80")],
167
        // maatuska
168
23607
        vec![sa("91.223.231.13:443"), sa("[2001:67c:8a4:1::13]:443")],
169
        // moria1
170
23607
        vec![sa("128.31.0.39:9231")],
171
        // sekhmet
172
23607
        vec![
173
23607
            sa("204.13.164.118:80"),
174
23607
            sa("[2620:13:4000:6000::1000:118]:80"),
175
        ],
176
        // tor26
177
23607
        vec![sa("217.196.147.77:80"), sa("[2a02:16a8:662:2203::1]:80")],
178
    ]
179
23607
}
180

            
181
/// For now, an alias to [`default_uploads()`].
182
7884
fn default_downloads() -> Vec<Vec<SocketAddr>> {
183
7884
    default_uploads()
184
7884
}
185

            
186
/// For now, an alias to [`default_uploads()`].
187
7884
fn default_votes() -> Vec<Vec<SocketAddr>> {
188
7884
    default_uploads()
189
7884
}
190

            
191
#[cfg(test)]
192
mod test {
193
    // @@ begin test lint list maintained by maint/add_warning @@
194
    #![allow(clippy::bool_assert_comparison)]
195
    #![allow(clippy::clone_on_copy)]
196
    #![allow(clippy::dbg_macro)]
197
    #![allow(clippy::mixed_attributes_style)]
198
    #![allow(clippy::print_stderr)]
199
    #![allow(clippy::print_stdout)]
200
    #![allow(clippy::single_char_pattern)]
201
    #![allow(clippy::unwrap_used)]
202
    #![allow(clippy::unchecked_time_subtraction)]
203
    #![allow(clippy::useless_vec)]
204
    #![allow(clippy::needless_pass_by_value)]
205
    #![allow(clippy::string_slice)] // See arti#2571
206
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
207
    #![allow(clippy::unnecessary_wraps)]
208

            
209
    use super::*;
210

            
211
    #[test]
212
    fn default_auths() {
213
        use itertools::Itertools;
214

            
215
        let dflt = AuthorityContacts::builder().build().unwrap();
216
        assert_eq!(dflt.v3idents, default_v3idents());
217
        assert_eq!(dflt.uploads, default_uploads());
218
        assert_eq!(dflt.downloads, default_downloads());
219
        assert_eq!(dflt.votes, default_votes());
220
        assert_eq!(dflt.v3idents.len(), dflt.uploads.len());
221
        assert_eq!(dflt.uploads, dflt.downloads);
222
        assert_eq!(dflt.uploads, dflt.votes);
223

            
224
        // These entries were copied from c-tor's "auth_dir.inc" file, and
225
        // IPv6 addresses added from the consensus where they were missing
226
        // from c-tor.
227
        let dirauths_testvec: Vec<_> = vec![
228
            // moria1
229
            (
230
                "F533C81CEF0BC0267857C99B2F471ADF249FA232",
231
                vec!["128.31.0.39:9231"],
232
            ),
233
            // tor26
234
            (
235
                "2F3DF9CA0E5D36F2685A2DA67184EB8DCB8CBA8C",
236
                vec!["217.196.147.77:80", "[2a02:16a8:662:2203::1]:80"],
237
            ),
238
            // dizum, v6 from consensus
239
            (
240
                "E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58",
241
                vec!["45.66.35.11:80", "[2a09:61c0::1337]:80"],
242
            ),
243
            // gabelmoo
244
            (
245
                "ED03BB616EB2F60BEC80151114BB25CEF515B226",
246
                vec!["131.188.40.189:80", "[2001:638:a000:4140::ffff:189]:80"],
247
            ),
248
            // dannenberg
249
            (
250
                "0232AF901C31A04EE9848595AF9BB7620D4C5B2E",
251
                vec!["193.23.244.244:80", "[2001:678:558:1000::244]:80"],
252
            ),
253
            // maatuska
254
            (
255
                "49015F787433103580E3B66A1707A00E60F2D15B",
256
                vec!["91.223.231.13:443", "[2001:67c:8a4:1::13]:443"],
257
            ),
258
            // longclaw, v6 from consensus
259
            (
260
                "23D15D965BC35114467363C165C4F724B64B4F66",
261
                vec!["199.58.81.140:80"],
262
            ),
263
            // faravahar, v6 from consensus
264
            (
265
                "70849B868D606BAECFB6128C5E3D782029AA394F",
266
                vec!["216.218.219.41:80", "[2001:470:164:2::2]:80"],
267
            ),
268
            // sekhmet
269
            (
270
                "E30CF7B3DFA63FBDC5FC9E46EC75C543AB6D7403",
271
                vec!["204.13.164.118:80", "[2620:13:4000:6000::1000:118]:80"],
272
            ),
273
        ]
274
        .iter()
275
        .map(|(id, addrs)| {
276
            (
277
                RsaIdentity::from_hex(id).unwrap(),
278
                addrs
279
                    .iter()
280
                    .map(|a| a.parse::<SocketAddr>().unwrap())
281
                    .collect(),
282
            )
283
        })
284
        .sorted()
285
        .collect();
286

            
287
        let config: Vec<_> = dflt
288
            .v3idents
289
            .into_iter()
290
            .zip(dflt.uploads)
291
            .sorted()
292
            .collect();
293

            
294
        assert_eq!(config, dirauths_testvec);
295
    }
296
}