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 crate::types::misc::LongIdent;
7
use crate::{NetdocErrorKind, NormalItemArgument, Pos};
8
use base64ct::Encoding;
9
use derive_deftly::Deftly;
10
use tor_basic_utils::derive_deftly_template_GloballyInternable;
11
use tor_basic_utils::intern::{GloballyInternable, Intern};
12
use tor_llcrypto::pk::ed25519::{ED25519_ID_LEN, Ed25519Identity};
13
use tor_llcrypto::pk::rsa::RsaIdentity;
14

            
15
/// Information about a relay family.
16
///
17
/// Tor relays may declare that they belong to the same family, to
18
/// indicate that they are controlled by the same party or parties,
19
/// and as such should not be used in the same circuit. Two relays
20
/// belong to the same family if and only if each one lists the other
21
/// as belonging to its family.
22
///
23
/// NOTE: when parsing, this type always discards incorrectly-formatted
24
/// entries, including entries that are only nicknames.
25
//
26
// TODO: This type probably belongs in a different crate.
27
//
28
// TODO (cve, Diziet): Overhaul or remove LegacyFamily, HappyFamilyId, HappyFamilyIds:
29
//   - Possibly, these don't all warrant newtype wrappers
30
//   - Where they do warrant newtype wrappers the API should be appropriate for that
31
// See <https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/4117#note_3428678>
32
#[derive(Clone, Debug, Default, Hash, Eq, PartialEq, Ord, PartialOrd, Deftly)]
33
#[derive_deftly(ItemValueEncodable, ItemValueParseable, GloballyInternable)]
34
pub struct LegacyFamily(Vec<LongIdent>);
35

            
36
impl LegacyFamily {
37
    /// Return a new empty LegacyFamily.
38
3
    pub fn new() -> Self {
39
3
        LegacyFamily::default()
40
3
    }
41

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

            
47
    /// Convert this family to a standard format (with all IDs sorted and de-duplicated).
48
5
    fn normalize(&mut self) {
49
8
        self.0.sort_by_key(|v| v.0);
50
5
        self.0.dedup();
51
5
    }
52

            
53
    /// Consume this family, and return a new canonical interned representation
54
    /// of the family.
55
5
    pub fn intern(mut self) -> Intern<Self> {
56
5
        self.normalize();
57
5
        Self::into_intern(self)
58
5
    }
59

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

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

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

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

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

            
105
/// Prefix for a HappyFamilyId derived from an ed25519 `KP_familyid_ed`.
106
const ED25519_ID_PREFIX: &str = "ed25519:";
107

            
108
impl std::str::FromStr for HappyFamilyId {
109
    type Err = crate::Error;
110

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

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

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

            
149
impl From<Ed25519Identity> for HappyFamilyId {
150
479
    fn from(value: Ed25519Identity) -> Self {
151
479
        Self::Ed25519(value)
152
479
    }
153
}
154

            
155
impl NormalItemArgument for HappyFamilyId {}
156

            
157
/// A list of multiple [`HappyFamilyId`] entries as found in microdescs.
158
///
159
/// Using the [`FromIterator`] implementation for [`HappyFamilyId`] leads the
160
/// result to get deduplicated and sorted automatically using
161
/// [`HappyFamilyIds::dedup()`] and [`HappyFamilyIds::sort()`], as those calls
162
/// are effectively required for a useful use of this type.
163
#[derive(Clone, Debug, Default, Eq, PartialEq, Deftly, derive_more::AsRef)]
164
#[derive_deftly(ItemValueEncodable, ItemValueParseable)]
165
pub struct HappyFamilyIds(
166
    // TODO DIRMIRROR: Replace with BTreeSet at one point.
167
    // TODO could/should this be a type alias instead?
168
    Vec<HappyFamilyId>,
169
);
170

            
171
impl HappyFamilyIds {
172
    /// Return a new empty [`HappyFamilyIds`].
173
466404
    pub fn new() -> Self {
174
466404
        Self::default()
175
466404
    }
176

            
177
    /// Push `family_id` onto this instance.
178
476788
    pub fn push(&mut self, family_id: HappyFamilyId) {
179
476788
        self.0.push(family_id);
180
476788
    }
181

            
182
    /// Sort entries ascending by their [`HappyFamilyId`].
183
1075
    pub fn sort(&mut self) {
184
1075
        self.0.sort();
185
1075
    }
186

            
187
    /// Deduplicates entries.
188
1075
    pub fn dedup(&mut self) {
189
1075
        self.0.dedup();
190
1075
    }
191
}
192

            
193
impl FromIterator<HappyFamilyId> for HappyFamilyIds {
194
243
    fn from_iter<T: IntoIterator<Item = HappyFamilyId>>(iter: T) -> Self {
195
243
        let mut res = Self(iter.into_iter().collect());
196
        // TODO: We should really reconsider this because it does not achieve
197
        // the same as subsequent calls to push.  As outlined above, we probably
198
        // want to switch to a BTreeSet in the long run anyways.
199
243
        res.sort();
200
243
        res.dedup();
201
243
        res
202
243
    }
203
}
204

            
205
#[cfg(test)]
206
mod test {
207
    // @@ begin test lint list maintained by maint/add_warning @@
208
    #![allow(clippy::bool_assert_comparison)]
209
    #![allow(clippy::clone_on_copy)]
210
    #![allow(clippy::dbg_macro)]
211
    #![allow(clippy::mixed_attributes_style)]
212
    #![allow(clippy::print_stderr)]
213
    #![allow(clippy::print_stdout)]
214
    #![allow(clippy::single_char_pattern)]
215
    #![allow(clippy::unwrap_used)]
216
    #![allow(clippy::unchecked_time_subtraction)]
217
    #![allow(clippy::useless_vec)]
218
    #![allow(clippy::needless_pass_by_value)]
219
    #![allow(clippy::string_slice)] // See arti#2571
220
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
221
    use std::str::FromStr;
222

            
223
    use super::*;
224
    use crate::Result;
225
    #[test]
226
    fn family() -> Result<()> {
227
        let f = "nickname1 nickname2 $ffffffffffffffffffffffffffffffffffffffff=foo eeeeeeeeeeeeeeeeeeeEEEeeeeeeeeeeeeeeeeee ddddddddddddddddddddddddddddddddd  $cccccccccccccccccccccccccccccccccccccccc~blarg ".parse::<LegacyFamily>()?;
228
        let v = vec![
229
            RsaIdentity::from_bytes(
230
                &hex::decode("ffffffffffffffffffffffffffffffffffffffff").unwrap()[..],
231
            )
232
            .unwrap(),
233
            RsaIdentity::from_bytes(
234
                &hex::decode("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee").unwrap()[..],
235
            )
236
            .unwrap(),
237
            RsaIdentity::from_bytes(
238
                &hex::decode("cccccccccccccccccccccccccccccccccccccccc").unwrap()[..],
239
            )
240
            .unwrap(),
241
        ];
242
        assert_eq!(f.members().cloned().collect::<Vec<_>>(), v);
243
        Ok(())
244
    }
245

            
246
    #[test]
247
    fn test_contains() -> Result<()> {
248
        let family =
249
            "ffffffffffffffffffffffffffffffffffffffff eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
250
                .parse::<LegacyFamily>()?;
251
        let in_family = RsaIdentity::from_bytes(
252
            &hex::decode("ffffffffffffffffffffffffffffffffffffffff").unwrap()[..],
253
        )
254
        .unwrap();
255
        let not_in_family = RsaIdentity::from_bytes(
256
            &hex::decode("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap()[..],
257
        )
258
        .unwrap();
259
        assert!(family.contains(&in_family), "Relay not found in family");
260
        assert!(
261
            !family.contains(&not_in_family),
262
            "Extra relay found in family"
263
        );
264
        Ok(())
265
    }
266

            
267
    #[test]
268
    fn mutable() {
269
        let mut family = LegacyFamily::default();
270
        let key = RsaIdentity::from_hex("ffffffffffffffffffffffffffffffffffffffff").unwrap();
271
        assert!(!family.contains(&key));
272
        family.push(key);
273
        assert!(family.contains(&key));
274
    }
275

            
276
    #[test]
277
    fn family_ids() {
278
        let ed_str_rep = "ed25519:7sToQRuge1bU2hS0CG0ViMndc4m82JhO4B4kdrQey80";
279
        let ed_id = HappyFamilyId::from_str(ed_str_rep).unwrap();
280
        assert!(matches!(ed_id, HappyFamilyId::Ed25519(_)));
281
        assert_eq!(ed_id.to_string().as_str(), ed_str_rep);
282

            
283
        let other_str_rep = "hello-world";
284
        let other_id = HappyFamilyId::from_str(other_str_rep).unwrap();
285
        assert!(matches!(other_id, HappyFamilyId::Unrecognized(_)));
286
        assert_eq!(other_id.to_string().as_str(), other_str_rep);
287

            
288
        assert_eq!(ed_id, ed_id);
289
        assert_ne!(ed_id, other_id);
290
    }
291

            
292
    #[test]
293
    fn parse2() {
294
        #[derive(Debug, PartialEq, Eq, derive_deftly::Deftly)]
295
        #[derive_deftly(NetdocParseable)]
296
        struct Wrapper {
297
            family: LegacyFamily,
298
        }
299

            
300
        const LINE: &str = "family $0000000000000000000000000000000000000000 $FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
301
        let parsed =
302
            crate::parse2::parse_netdoc::<Wrapper>(&crate::parse2::ParseInput::new(LINE, ""))
303
                .unwrap();
304
        assert_eq!(
305
            parsed,
306
            Wrapper {
307
                family: LegacyFamily(vec![
308
                    RsaIdentity::from_hex("0000000000000000000000000000000000000000")
309
                        .unwrap()
310
                        .into(),
311
                    RsaIdentity::from_hex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")
312
                        .unwrap()
313
                        .into()
314
                ])
315
            }
316
        );
317
    }
318
}