1
//! Implements the relay 'family' type.
2
//!
3
//! Families are opt-in lists of relays with the same operators,
4
//! used to avoid building insecure circuits.
5

            
6
use std::sync::Arc;
7

            
8
use crate::types::misc::LongIdent;
9
use crate::{Error, NetdocErrorKind, NormalItemArgument, Pos, Result};
10
use base64ct::Encoding;
11
use derive_deftly::Deftly;
12
use tor_basic_utils::intern::InternCache;
13
use tor_llcrypto::pk::ed25519::{ED25519_ID_LEN, Ed25519Identity};
14
use tor_llcrypto::pk::rsa::RsaIdentity;
15

            
16
/// Information about a relay family.
17
///
18
/// Tor relays may declare that they belong to the same family, to
19
/// indicate that they are controlled by the same party or parties,
20
/// and as such should not be used in the same circuit. Two relays
21
/// belong to the same family if and only if each one lists the other
22
/// as belonging to its family.
23
///
24
/// NOTE: when parsing, this type always discards incorrectly-formatted
25
/// entries, including entries that are only nicknames.
26
///
27
/// TODO: This type probably belongs in a different crate.
28
#[derive(Clone, Debug, Default, Hash, Eq, PartialEq, Deftly)]
29
#[cfg_attr(feature = "parse2", derive_deftly(ItemValueParseable))]
30
pub struct RelayFamily(Vec<LongIdent>);
31

            
32
/// Cache of RelayFamily objects, for saving memory.
33
//
34
/// This only holds weak references to the policy objects, so we don't
35
/// need to worry about running out of space because of stale entries.
36
static FAMILY_CACHE: InternCache<RelayFamily> = InternCache::new();
37

            
38
impl RelayFamily {
39
    /// Return a new empty RelayFamily.
40
471200
    pub fn new() -> Self {
41
471200
        RelayFamily::default()
42
471200
    }
43

            
44
    /// Add `rsa_id` to this family.
45
6
    pub fn push(&mut self, rsa_id: RsaIdentity) {
46
6
        self.0.push(rsa_id.into());
47
6
    }
48

            
49
    /// Convert this family to a standard format (with all IDs sorted and de-duplicated).
50
481808
    fn normalize(&mut self) {
51
487988
        self.0.sort_by(|a, b| a.0.cmp(&b.0));
52
481808
        self.0.dedup();
53
481808
    }
54

            
55
    /// Consume this family, and return a new canonical interned representation
56
    /// of the family.
57
481808
    pub fn intern(mut self) -> Arc<Self> {
58
481808
        self.normalize();
59
481808
        FAMILY_CACHE.intern(self)
60
481808
    }
61

            
62
    /// Does this family include the given relay?
63
57605127
    pub fn contains(&self, rsa_id: &RsaIdentity) -> bool {
64
57605127
        self.0.contains(&LongIdent(*rsa_id))
65
57605127
    }
66

            
67
    /// Return an iterator over the RSA identity keys listed in this
68
    /// family.
69
112
    pub fn members(&self) -> impl Iterator<Item = &RsaIdentity> {
70
112
        self.0.iter().map(|id| &id.0)
71
112
    }
72

            
73
    /// Return true if this family has no members.
74
2236
    pub fn is_empty(&self) -> bool {
75
2236
        self.0.is_empty()
76
2236
    }
77
}
78

            
79
impl std::str::FromStr for RelayFamily {
80
    type Err = Error;
81
480147
    fn from_str(s: &str) -> Result<Self> {
82
480147
        let v: Result<Vec<LongIdent>> = s
83
480147
            .split(crate::parse::tokenize::is_sp)
84
809873
            .map(|e| e.parse::<LongIdent>())
85
480147
            .filter(Result::is_ok)
86
480147
            .collect();
87
480147
        Ok(RelayFamily(v?))
88
480147
    }
89
}
90

            
91
/// An identifier representing a relay family.
92
///
93
/// In the ["happy families"](https://spec.torproject.org/proposals/321) scheme,
94
/// microdescriptors will no longer have to contain a list of relay members,
95
/// but will instead contain these identifiers.
96
///
97
/// If two relays have a `RelayFamilyId` in common, they belong to the same family.
98
#[derive(Clone, Debug, Eq, PartialEq)]
99
#[non_exhaustive]
100
pub enum RelayFamilyId {
101
    /// An identifier derived from an Ed25519 relay family key. (`KP_familyid_ed`)
102
    Ed25519(Ed25519Identity),
103
    /// An unrecognized string.
104
    Unrecognized(String),
105
}
106

            
107
/// Prefix for a RelayFamilyId derived from an ed25519 `KP_familyid_ed`.
108
const ED25519_ID_PREFIX: &str = "ed25519:";
109

            
110
impl std::str::FromStr for RelayFamilyId {
111
    type Err = Error;
112

            
113
2138
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
114
2138
        let mut buf = [0_u8; ED25519_ID_LEN];
115
2138
        if let Some(s) = s.strip_prefix(ED25519_ID_PREFIX) {
116
12
            if let Ok(decoded) = base64ct::Base64Unpadded::decode(s, &mut buf) {
117
12
                if let Some(ed_id) = Ed25519Identity::from_bytes(decoded) {
118
12
                    return Ok(RelayFamilyId::Ed25519(ed_id));
119
                }
120
            }
121
            return Err(NetdocErrorKind::BadArgument
122
                .with_msg("Invalid ed25519 family ID")
123
                .at_pos(Pos::at(s)));
124
2126
        }
125
2126
        Ok(RelayFamilyId::Unrecognized(s.to_string()))
126
2138
    }
127
}
128

            
129
impl std::fmt::Display for RelayFamilyId {
130
8
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131
8
        match self {
132
6
            RelayFamilyId::Ed25519(id) => write!(f, "{}{}", ED25519_ID_PREFIX, id),
133
2
            RelayFamilyId::Unrecognized(s) => write!(f, "{}", s),
134
        }
135
8
    }
136
}
137

            
138
impl PartialOrd for RelayFamilyId {
139
2
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
140
2
        Some(Ord::cmp(self, other))
141
2
    }
142
}
143
impl Ord for RelayFamilyId {
144
2
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
145
        // We sort RelayFamilyId values by string representation.
146
        // This is not super-efficient, but we don't need to do it very often.
147
2
        Ord::cmp(&self.to_string(), &other.to_string())
148
2
    }
149
}
150

            
151
impl NormalItemArgument for RelayFamilyId {}
152

            
153
/// A list of multiple [`RelayFamilyId`] entries as found in microdescs.
154
#[derive(Clone, Debug, Default, Eq, PartialEq, Deftly, derive_more::AsRef)]
155
#[cfg_attr(feature = "parse2", derive_deftly(ItemValueParseable))]
156
pub struct RelayFamilyIds(Vec<RelayFamilyId>);
157

            
158
impl RelayFamilyIds {
159
    /// Return a new empty [`RelayFamilyIds`].
160
468528
    pub fn new() -> Self {
161
468528
        Self::default()
162
468528
    }
163

            
164
    /// Push `family_id` onto this instance.
165
2120
    pub fn push(&mut self, family_id: RelayFamilyId) {
166
2120
        self.0.push(family_id);
167
2120
    }
168
}
169

            
170
impl FromIterator<RelayFamilyId> for RelayFamilyIds {
171
450
    fn from_iter<T: IntoIterator<Item = RelayFamilyId>>(iter: T) -> Self {
172
450
        Self(iter.into_iter().collect())
173
450
    }
174
}
175

            
176
#[cfg(test)]
177
mod test {
178
    // @@ begin test lint list maintained by maint/add_warning @@
179
    #![allow(clippy::bool_assert_comparison)]
180
    #![allow(clippy::clone_on_copy)]
181
    #![allow(clippy::dbg_macro)]
182
    #![allow(clippy::mixed_attributes_style)]
183
    #![allow(clippy::print_stderr)]
184
    #![allow(clippy::print_stdout)]
185
    #![allow(clippy::single_char_pattern)]
186
    #![allow(clippy::unwrap_used)]
187
    #![allow(clippy::unchecked_time_subtraction)]
188
    #![allow(clippy::useless_vec)]
189
    #![allow(clippy::needless_pass_by_value)]
190
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
191
    use std::str::FromStr;
192

            
193
    use super::*;
194
    use crate::Result;
195
    #[test]
196
    fn family() -> Result<()> {
197
        let f = "nickname1 nickname2 $ffffffffffffffffffffffffffffffffffffffff=foo eeeeeeeeeeeeeeeeeeeEEEeeeeeeeeeeeeeeeeee ddddddddddddddddddddddddddddddddd  $cccccccccccccccccccccccccccccccccccccccc~blarg ".parse::<RelayFamily>()?;
198
        let v = vec![
199
            RsaIdentity::from_bytes(
200
                &hex::decode("ffffffffffffffffffffffffffffffffffffffff").unwrap()[..],
201
            )
202
            .unwrap(),
203
            RsaIdentity::from_bytes(
204
                &hex::decode("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee").unwrap()[..],
205
            )
206
            .unwrap(),
207
            RsaIdentity::from_bytes(
208
                &hex::decode("cccccccccccccccccccccccccccccccccccccccc").unwrap()[..],
209
            )
210
            .unwrap(),
211
        ];
212
        assert_eq!(f.members().cloned().collect::<Vec<_>>(), v);
213
        Ok(())
214
    }
215

            
216
    #[test]
217
    fn test_contains() -> Result<()> {
218
        let family =
219
            "ffffffffffffffffffffffffffffffffffffffff eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
220
                .parse::<RelayFamily>()?;
221
        let in_family = RsaIdentity::from_bytes(
222
            &hex::decode("ffffffffffffffffffffffffffffffffffffffff").unwrap()[..],
223
        )
224
        .unwrap();
225
        let not_in_family = RsaIdentity::from_bytes(
226
            &hex::decode("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap()[..],
227
        )
228
        .unwrap();
229
        assert!(family.contains(&in_family), "Relay not found in family");
230
        assert!(
231
            !family.contains(&not_in_family),
232
            "Extra relay found in family"
233
        );
234
        Ok(())
235
    }
236

            
237
    #[test]
238
    fn mutable() {
239
        let mut family = RelayFamily::default();
240
        let key = RsaIdentity::from_hex("ffffffffffffffffffffffffffffffffffffffff").unwrap();
241
        assert!(!family.contains(&key));
242
        family.push(key);
243
        assert!(family.contains(&key));
244
    }
245

            
246
    #[test]
247
    fn family_ids() {
248
        let ed_str_rep = "ed25519:7sToQRuge1bU2hS0CG0ViMndc4m82JhO4B4kdrQey80";
249
        let ed_id = RelayFamilyId::from_str(ed_str_rep).unwrap();
250
        assert!(matches!(ed_id, RelayFamilyId::Ed25519(_)));
251
        assert_eq!(ed_id.to_string().as_str(), ed_str_rep);
252

            
253
        let other_str_rep = "hello-world";
254
        let other_id = RelayFamilyId::from_str(other_str_rep).unwrap();
255
        assert!(matches!(other_id, RelayFamilyId::Unrecognized(_)));
256
        assert_eq!(other_id.to_string().as_str(), other_str_rep);
257

            
258
        assert_eq!(ed_id, ed_id);
259
        assert_ne!(ed_id, other_id);
260
    }
261

            
262
    #[test]
263
    #[cfg(feature = "parse2")]
264
    fn parse2() {
265
        #[derive(Debug, PartialEq, Eq, derive_deftly::Deftly)]
266
        #[cfg_attr(feature = "parse2", derive_deftly(NetdocParseable))]
267
        struct Wrapper {
268
            family: RelayFamily,
269
        }
270

            
271
        const LINE: &str = "family $0000000000000000000000000000000000000000 $FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
272
        let parsed =
273
            crate::parse2::parse_netdoc::<Wrapper>(&crate::parse2::ParseInput::new(LINE, ""))
274
                .unwrap();
275
        assert_eq!(
276
            parsed,
277
            Wrapper {
278
                family: RelayFamily(vec![
279
                    RsaIdentity::from_hex("0000000000000000000000000000000000000000")
280
                        .unwrap()
281
                        .into(),
282
                    RsaIdentity::from_hex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")
283
                        .unwrap()
284
                        .into()
285
                ])
286
            }
287
        );
288
    }
289
}