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 rand::RngExt;
9
use tor_bytes::Reader;
10
use tor_llcrypto::util::ct::CtByteArray;
11
use tor_rpcbase::{LookupError, ObjectId};
12
use zeroize::Zeroizing;
13

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
178
    use super::*;
179

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

            
182
    #[test]
183
    fn roundtrip() {
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 genidx_s1 = GenIdx::from(KeyData::from_ffi(0x43_0000_0043));
189

            
190
        let gid1 = GlobalId {
191
            connection: conn1,
192
            local_id: genidx_s1,
193
        };
194
        let mac_key = MacKey::new(&mut rng);
195
        let enc1 = gid1.encode(&mac_key);
196
        let gid1_decoded = GlobalId::try_decode(&mac_key, &enc1).unwrap().unwrap();
197
        assert_eq!(gid1, gid1_decoded);
198
        assert!(enc1.as_ref().starts_with(GlobalId::TAG_CHAR));
199

            
200
        assert_eq!(enc1.as_ref().len(), GLOBAL_ID_B64_ENCODED_LEN);
201
    }
202

            
203
    #[test]
204
    fn not_a_global_id() {
205
        let mut rng = tor_basic_utils::test_rng::testing_rng();
206
        let mac_key = MacKey::new(&mut rng);
207
        let decoded = GlobalId::try_decode(&mac_key, &ObjectId::from("helloworld"));
208
        assert!(matches!(decoded, Ok(None)));
209

            
210
        let decoded = GlobalId::try_decode(&mac_key, &ObjectId::from("$helloworld"));
211
        assert!(matches!(decoded, Err(LookupError::NoObject(_))));
212
    }
213

            
214
    #[test]
215
    fn mac_works() {
216
        use slotmap_careful::KeyData;
217
        let mut rng = tor_basic_utils::test_rng::testing_rng();
218

            
219
        let conn1 = ConnectionId::from(*b"example1-------!");
220
        let conn2 = ConnectionId::from(*b"example2-------!");
221
        let genidx_s1 = GenIdx::from(KeyData::from_ffi(0x43_0000_0043));
222
        let genidx_s2 = GenIdx::from(KeyData::from_ffi(0x171_0000_0171));
223

            
224
        let gid1 = GlobalId {
225
            connection: conn1,
226
            local_id: genidx_s1,
227
        };
228
        let gid2 = GlobalId {
229
            connection: conn2,
230
            local_id: genidx_s2,
231
        };
232
        let mac_key = MacKey::new(&mut rng);
233
        let enc1 = gid1.encode_as_bytes(&mac_key, &mut rng);
234
        let enc2 = gid2.encode_as_bytes(&mac_key, &mut rng);
235

            
236
        // Make a 'combined' encoded gid with the mac from one and the info from
237
        // the other.
238
        let mut combined = Vec::from(&enc1[0..MAC_LEN]);
239
        combined.extend_from_slice(&enc2[MAC_LEN..]);
240
        let outcome = GlobalId::try_decode_from_bytes(&mac_key, &combined[..]);
241
        // Can't decode, because MAC was wrong.
242
        assert!(outcome.is_none());
243
    }
244
}