1
//! Manager-global identifiers, for things that need to be identified outside
2
//! the scope of a single RPC connection.
3
//!
4
//! We expect to use this code to identify `TorClient`s and similar objects that
5
//! can be passed as the target of a SOCKS request.  Since the SOCKS request is
6
//! not part of the RPC session, we need a way for it to refer to these objects.
7

            
8
use tor_bytes::Reader;
9
use tor_llcrypto::util::ct::CtByteArray;
10
use tor_rpcbase::{LookupError, ObjectId};
11
use zeroize::Zeroizing;
12

            
13
use crate::{connection::ConnectionId, objmap::GenIdx};
14

            
15
/// A [RpcMgr](crate::RpcMgr)-scoped identifier for an RPC object.
16
///
17
/// A `GlobalId` identifies an RPC object uniquely among all the objects visible
18
/// to any active session on an RpcMgr.
19
///
20
/// Its encoding is unforgeable.
21
#[derive(Clone, Debug, Eq, PartialEq)]
22
pub(crate) struct GlobalId {
23
    /// The RPC connection within whose object map `local_id` is visible.
24
    pub(crate) connection: ConnectionId,
25
    /// The identifier of the object within `connection`'s object map.
26
    pub(crate) local_id: GenIdx,
27
}
28

            
29
/// The number of bytes in our [`MacKey`].
30
///
31
/// (Our choice of algorithm allows any key length we want; 128 bits should be
32
/// secure enough.)
33
const MAC_KEY_LEN: usize = 16;
34
/// The number of bytes in a [`Mac`].
35
///
36
/// (Our choice of algorithm allows any MAC length we want; 128 bits should be
37
/// enough to make the results unforgeable.)
38
const MAC_LEN: usize = 16;
39

            
40
/// An key that we use to compute message authentication codes (MACs) for our
41
/// [`GlobalId`]s
42
///
43
/// We do not guarantee any particular MAC algorithm; we should be able to
44
/// change MAC algorithms without breaking any user code. Right now, we choose a
45
/// Kangaroo12-based construction in order to be reasonably fast.
46
#[derive(Clone)]
47
pub(crate) struct MacKey {
48
    /// The key itself.
49
    key: Zeroizing<[u8; MAC_KEY_LEN]>,
50
}
51

            
52
/// A message authentication code produced by [`MacKey::mac`].
53
type Mac = CtByteArray<MAC_LEN>;
54

            
55
impl MacKey {
56
    /// Construct a new random `MacKey`.
57
6
    pub(crate) fn new<Rng: rand::Rng + rand::CryptoRng>(rng: &mut Rng) -> Self {
58
6
        Self {
59
6
            key: Zeroizing::new(rng.random()),
60
6
        }
61
6
    }
62

            
63
    /// Compute the AMC of a given input `inp`, and store the result into `out`.
64
    ///
65
    /// The current construction allows `out` to be any length.
66
14
    fn mac(&self, inp: &[u8], out: &mut [u8]) {
67
        use tiny_keccak::{Hasher as _, Kmac};
68
14
        let mut mac = Kmac::v128(&self.key[..], b"artirpc globalid");
69
14
        mac.update(inp);
70
14
        mac.finalize(out);
71
14
    }
72
}
73

            
74
impl GlobalId {
75
    /// The number of bytes used to encode a `GlobalId` in binary form.
76
    const ENCODED_LEN: usize = MAC_LEN + ConnectionId::LEN + GenIdx::BYTE_LEN;
77

            
78
    /// A prefix we use when encoding global IDs in base64.
79
    ///
80
    /// Since this isn't a valid base 64 character, we can't confuse it with
81
    /// a base64 string.
82
    const TAG_CHAR: char = '$';
83

            
84
    /// Create a new GlobalId from its parts.
85
    pub(crate) fn new(connection: ConnectionId, local_id: GenIdx) -> GlobalId {
86
        GlobalId {
87
            connection,
88
            local_id,
89
        }
90
    }
91

            
92
    /// Encode this ID in an unforgeable string that we can later use to
93
    /// uniquely identify an RPC object.
94
    ///
95
    /// As with local IDs, this encoding is nondeterministic.
96
4
    pub(crate) fn encode(&self, key: &MacKey) -> ObjectId {
97
        use base64ct::{Base64Unpadded as B64, Encoding};
98
4
        let bytes = self.encode_as_bytes(key, &mut rand::rng());
99
4
        let string = format!("{}{}", GlobalId::TAG_CHAR, B64::encode_string(&bytes[..]));
100
4
        ObjectId::from(string)
101
4
    }
102

            
103
    /// As `encode`, but do not base64-encode the result.
104
8
    fn encode_as_bytes<R: rand::RngCore>(&self, key: &MacKey, rng: &mut R) -> Vec<u8> {
105
8
        let mut bytes = Vec::with_capacity(Self::ENCODED_LEN);
106
8
        bytes.resize(MAC_LEN, 0);
107
8
        bytes.extend_from_slice(self.connection.as_ref());
108
8
        bytes.extend_from_slice(&self.local_id.to_bytes(rng));
109
8
        {
110
8
            // TODO RPC: Maybe we should stick the MAC at the end to make everything simpler.
111
8
            let (mac, text) = bytes.split_at_mut(MAC_LEN);
112
8
            key.mac(text, mac);
113
8
        }
114
8
        bytes
115
8
    }
116

            
117
    /// Try to decode and validate `s` as a [`GlobalId`].
118
    ///
119
    /// Returns `Ok(None)` if `s` is not tagged as an identifier for a `GlobalId`.
120
8
    pub(crate) fn try_decode(key: &MacKey, s: &ObjectId) -> Result<Option<Self>, LookupError> {
121
        use base64ct::{Base64Unpadded as B64, Encoding};
122
8
        if !s.as_ref().starts_with(GlobalId::TAG_CHAR) {
123
2
            return Ok(None);
124
6
        }
125
6
        let mut bytes = [0_u8; Self::ENCODED_LEN];
126
6
        let byte_slice = B64::decode(&s.as_ref()[1..], &mut bytes[..])
127
7
            .map_err(|_| LookupError::NoObject(s.clone()))?;
128
4
        Self::try_decode_from_bytes(key, byte_slice)
129
4
            .ok_or_else(|| LookupError::NoObject(s.clone()))
130
4
            .map(Some)
131
8
    }
132

            
133
    /// As `try_decode`, but expect a byte slice rather than a base64-encoded string.
134
6
    fn try_decode_from_bytes(key: &MacKey, bytes: &[u8]) -> Option<Self> {
135
6
        if bytes.len() != Self::ENCODED_LEN {
136
            return None;
137
6
        }
138

            
139
        // TODO RPC: Just use Reader here?
140

            
141
6
        let mut found_mac = [0; MAC_LEN];
142
6
        key.mac(&bytes[MAC_LEN..], &mut found_mac[..]);
143
6
        let found_mac = Mac::from(found_mac);
144

            
145
6
        let mut r: Reader = Reader::from_slice(bytes);
146
6
        let declared_mac: Mac = r.extract().ok()?;
147
6
        if found_mac != declared_mac {
148
2
            return None;
149
4
        }
150
4
        let connection = r.extract::<[u8; ConnectionId::LEN]>().ok()?.into();
151
4
        let rest = r.into_rest();
152
4
        let local_id = GenIdx::from_bytes(rest)?;
153

            
154
4
        Some(Self {
155
4
            connection,
156
4
            local_id,
157
4
        })
158
6
    }
159
}
160

            
161
#[cfg(test)]
162
mod test {
163
    // @@ begin test lint list maintained by maint/add_warning @@
164
    #![allow(clippy::bool_assert_comparison)]
165
    #![allow(clippy::clone_on_copy)]
166
    #![allow(clippy::dbg_macro)]
167
    #![allow(clippy::mixed_attributes_style)]
168
    #![allow(clippy::print_stderr)]
169
    #![allow(clippy::print_stdout)]
170
    #![allow(clippy::single_char_pattern)]
171
    #![allow(clippy::unwrap_used)]
172
    #![allow(clippy::unchecked_time_subtraction)]
173
    #![allow(clippy::useless_vec)]
174
    #![allow(clippy::needless_pass_by_value)]
175
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
176

            
177
    use super::*;
178

            
179
    const GLOBAL_ID_B64_ENCODED_LEN: usize = (GlobalId::ENCODED_LEN * 8).div_ceil(6) + 1;
180

            
181
    #[test]
182
    fn roundtrip() {
183
        use crate::objmap::{StrongIdx, WeakIdx};
184
        use slotmap_careful::KeyData;
185
        let mut rng = tor_basic_utils::test_rng::testing_rng();
186

            
187
        let conn1 = ConnectionId::from(*b"example1-------!");
188
        let conn2 = ConnectionId::from(*b"example2!!!!!!!!");
189
        let genidx_s1 = GenIdx::Strong(StrongIdx::from(KeyData::from_ffi(0x43_0000_0043)));
190
        let genidx_w2 = GenIdx::Weak(WeakIdx::from(KeyData::from_ffi(0x171_0000_0171)));
191

            
192
        let gid1 = GlobalId {
193
            connection: conn1,
194
            local_id: genidx_s1,
195
        };
196
        let gid2 = GlobalId {
197
            connection: conn2,
198
            local_id: genidx_w2,
199
        };
200

            
201
        let mac_key = MacKey::new(&mut rng);
202
        let enc1 = gid1.encode(&mac_key);
203
        let gid1_decoded = GlobalId::try_decode(&mac_key, &enc1).unwrap().unwrap();
204
        assert_eq!(gid1, gid1_decoded);
205
        assert!(enc1.as_ref().starts_with(GlobalId::TAG_CHAR));
206

            
207
        let enc2 = gid2.encode(&mac_key);
208
        let gid2_decoded = GlobalId::try_decode(&mac_key, &enc2).unwrap().unwrap();
209
        assert_eq!(gid2, gid2_decoded);
210
        assert_ne!(gid1_decoded, gid2_decoded);
211
        assert!(enc1.as_ref().starts_with(GlobalId::TAG_CHAR));
212

            
213
        assert_eq!(enc1.as_ref().len(), GLOBAL_ID_B64_ENCODED_LEN);
214
        assert_eq!(enc2.as_ref().len(), GLOBAL_ID_B64_ENCODED_LEN);
215
    }
216

            
217
    #[test]
218
    fn not_a_global_id() {
219
        let mut rng = tor_basic_utils::test_rng::testing_rng();
220
        let mac_key = MacKey::new(&mut rng);
221
        let decoded = GlobalId::try_decode(&mac_key, &ObjectId::from("helloworld"));
222
        assert!(matches!(decoded, Ok(None)));
223

            
224
        let decoded = GlobalId::try_decode(&mac_key, &ObjectId::from("$helloworld"));
225
        assert!(matches!(decoded, Err(LookupError::NoObject(_))));
226
    }
227

            
228
    #[test]
229
    fn mac_works() {
230
        use crate::objmap::{StrongIdx, WeakIdx};
231
        use slotmap_careful::KeyData;
232
        let mut rng = tor_basic_utils::test_rng::testing_rng();
233

            
234
        let conn1 = ConnectionId::from(*b"example1-------!");
235
        let conn2 = ConnectionId::from(*b"example2!!!!!!!!");
236
        let genidx_s1 = GenIdx::Strong(StrongIdx::from(KeyData::from_ffi(0x43_0000_0043)));
237
        let genidx_w1 = GenIdx::Weak(WeakIdx::from(KeyData::from_ffi(0x171_0000_0171)));
238

            
239
        let gid1 = GlobalId {
240
            connection: conn1,
241
            local_id: genidx_s1,
242
        };
243
        let gid2 = GlobalId {
244
            connection: conn2,
245
            local_id: genidx_w1,
246
        };
247
        let mac_key = MacKey::new(&mut rng);
248
        let enc1 = gid1.encode_as_bytes(&mac_key, &mut rng);
249
        let enc2 = gid2.encode_as_bytes(&mac_key, &mut rng);
250

            
251
        // Make a 'combined' encoded gid with the mac from one and the info from
252
        // the other.
253
        let mut combined = Vec::from(&enc1[0..MAC_LEN]);
254
        combined.extend_from_slice(&enc2[MAC_LEN..]);
255
        let outcome = GlobalId::try_decode_from_bytes(&mac_key, &combined[..]);
256
        // Can't decode, because MAC was wrong.
257
        assert!(outcome.is_none());
258
    }
259
}