tor-keymgr 0.42.0

Key management for the Arti Tor implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! ArtiEphemeralKeystore implementation (in-memory ephemeral key storage)

pub(crate) mod err;

use std::collections::HashMap;
use std::result::Result as StdResult;
use std::sync::{Arc, Mutex};

use tor_error::{internal, into_internal};
use tor_key_forge::{
    CertData, EncodableItem, ErasedKey, KeystoreItem, KeystoreItemType, ParsedEd25519Cert,
};

use crate::keystore::ephemeral::err::ArtiEphemeralKeystoreError;
use crate::raw::RawEntryId;
use crate::{ArtiPath, Error, KeySpecifier, Keystore, KeystoreEntry, KeystoreId, Result};

use super::KeystoreEntryResult;

/// The identifier of a key stored in the `ArtiEphemeralKeystore`.
type KeyIdent = (ArtiPath, KeystoreItemType);

/// The Ephemeral Arti key store
///
/// This is a purely in-memory key store. Keys written to this store
/// are never written to disk, and are stored in-memory as [`KeystoreItem`]s.
/// Keys saved in this Keystore do not persist between restarts!
///
/// While Arti never writes the keys for this key store to disk, the operating
/// system may do so for reasons outside of this library's control. Some
/// examples are swapping RAM to disk, generating core dumps, invoking
/// suspend-to-disk power management, etc. This key store does not attempt to
/// prevent this operating system behaviour.
pub struct ArtiEphemeralKeystore {
    /// Identifier hard-coded to 'ephemeral'
    id: KeystoreId,
    /// Keys stored as [`KeystoreItem`].
    key_dictionary: Arc<Mutex<HashMap<KeyIdent, KeystoreItem>>>,
}

impl ArtiEphemeralKeystore {
    /// Create a new [`ArtiEphemeralKeystore`]
    pub fn new(id: String) -> Self {
        Self {
            id: KeystoreId(id),
            key_dictionary: Default::default(),
        }
    }
}

impl Keystore for ArtiEphemeralKeystore {
    fn id(&self) -> &KeystoreId {
        &self.id
    }

    fn contains(
        &self,
        key_spec: &dyn KeySpecifier,
        item_type: &KeystoreItemType,
    ) -> StdResult<bool, Error> {
        let arti_path = key_spec
            .arti_path()
            .map_err(ArtiEphemeralKeystoreError::ArtiPathUnavailableError)?;
        let key_dictionary = self.key_dictionary.lock().expect("lock poisoned");
        let contains_key = key_dictionary.contains_key(&(arti_path, item_type.clone()));
        Ok(contains_key)
    }

    fn get(
        &self,
        key_spec: &dyn KeySpecifier,
        item_type: &KeystoreItemType,
    ) -> StdResult<Option<ErasedKey>, Error> {
        let arti_path = key_spec
            .arti_path()
            .map_err(ArtiEphemeralKeystoreError::ArtiPathUnavailableError)?;
        let key_dictionary = self.key_dictionary.lock().expect("lock poisoned");
        match key_dictionary.get(&(arti_path.clone(), item_type.clone())) {
            Some(key) if key.item_type()? != *item_type => {
                // This should only happen if some external factor alters the
                // process memory or if there's a bug in our implementation of
                // Keystore::insert().
                Err(internal!(
                    "the specified KeystoreItemType does not match key type of the fetched key?!"
                )
                .into())
            }
            Some(key) => {
                let key: KeystoreItem = key.clone();

                match key {
                    KeystoreItem::Key(key) => {
                        let key: ErasedKey = key.into_erased()?;
                        Ok(Some(key))
                    }
                    KeystoreItem::Cert(CertData::TorEd25519Cert(c)) => {
                        // Important: The KeyMgr expects the returned certs to be of the
                        // ParsedCert type of the ToEncodableCert implementation.
                        //
                        // For TorEd25519Cert, that type is ParsedEd25519Cert.
                        let cert = ParsedEd25519Cert::decode(c.to_vec())
                            .map_err(into_internal!("found invalid cert in ephemeral store?!"))?;

                        Ok(Some(Box::new(cert)))
                    }
                    _ => Err(internal!("unknown item type {key:?} in the keystore").into()),
                }
            }
            None => Ok(None),
        }
    }

    #[cfg(feature = "onion-service-cli-extra")]
    fn raw_entry_id(&self, _raw_id: &str) -> Result<RawEntryId> {
        Err(ArtiEphemeralKeystoreError::NotSupported {
            action: "raw_entry_id",
        }
        .into())
    }

    fn insert(&self, key: &dyn EncodableItem, key_spec: &dyn KeySpecifier) -> StdResult<(), Error> {
        let arti_path = key_spec
            .arti_path()
            .map_err(ArtiEphemeralKeystoreError::ArtiPathUnavailableError)?;
        let key_data = key.as_keystore_item()?;
        let item_type = key_data.item_type()?;

        // save to dictionary
        let mut key_dictionary = self.key_dictionary.lock().expect("lock poisoned");
        let _ = key_dictionary.insert((arti_path, item_type), key_data);
        Ok(())
    }

    fn remove(
        &self,
        key_spec: &dyn KeySpecifier,
        item_type: &KeystoreItemType,
    ) -> StdResult<Option<()>, Error> {
        let arti_path = key_spec
            .arti_path()
            .map_err(ArtiEphemeralKeystoreError::ArtiPathUnavailableError)?;
        let mut key_dictionary = self.key_dictionary.lock().expect("lock poisoned");
        match key_dictionary.remove(&(arti_path, item_type.clone())) {
            Some(key) if key.item_type()? != *item_type => {
                // This should only happen if some external factor alters the
                // process memory or if there's a bug in our implementation of
                // Keystore::insert().
                Err(internal!(
                    "the specified KeystoreItemType does not match key type of the removed key?!"
                )
                .into())
            }
            Some(_) => Ok(Some(())),
            None => Ok(None),
        }
    }

    #[cfg(feature = "onion-service-cli-extra")]
    fn remove_unchecked(&self, _entry_id: &RawEntryId) -> Result<()> {
        // TODO: further discussion is needed for this implementation
        Err(ArtiEphemeralKeystoreError::NotSupported {
            action: "remove_uncheked",
        }
        .into())
    }

    fn list(&self) -> Result<Vec<KeystoreEntryResult<KeystoreEntry>>> {
        let key_dictionary = self.key_dictionary.lock().expect("lock poisoned");
        Ok(key_dictionary
            .keys()
            .map(|(arti_path, item_type)| {
                let raw_id = RawEntryId::Ephemeral((arti_path.clone(), item_type.clone()));
                Ok(KeystoreEntry::new(
                    arti_path.clone().into(),
                    item_type.clone(),
                    self.id(),
                    raw_id,
                ))
            })
            .collect())
    }
}

#[cfg(test)]
mod tests {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_time_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->

    use tor_basic_utils::test_rng::{TestingRng, testing_rng};
    use tor_error::{ErrorKind, HasKind};
    use tor_key_forge::{KeyType, Keygen};
    use tor_llcrypto::pk::{curve25519, ed25519};
    use tor_llcrypto::rng::FakeEntropicRng;

    use super::*;

    use crate::test_utils::TestSpecifier;

    // some helper methods

    fn key() -> Box<dyn EncodableItem> {
        let mut rng = testing_rng();
        let keypair = ed25519::Keypair::generate(&mut rng);
        Box::new(keypair)
    }

    fn key_type() -> KeystoreItemType {
        KeyType::Ed25519Keypair.into()
    }

    fn key_bad() -> Box<dyn EncodableItem> {
        let mut rng = FakeEntropicRng::<TestingRng>(testing_rng());
        let keypair = curve25519::StaticKeypair::generate(&mut rng).unwrap();
        Box::new(keypair)
    }

    fn key_type_bad() -> KeystoreItemType {
        KeyType::X25519StaticKeypair.into()
    }

    fn key_spec() -> Box<dyn KeySpecifier> {
        Box::<TestSpecifier>::default()
    }

    // tests!

    #[test]
    fn id() {
        let key_store = ArtiEphemeralKeystore::new("test-ephemeral".to_string());

        assert_eq!(&KeystoreId("test-ephemeral".to_string()), key_store.id());
    }

    #[test]
    fn contains() {
        let key_store = ArtiEphemeralKeystore::new("test-ephemeral".to_string());

        // verify no key in store
        assert!(
            !key_store
                .contains(key_spec().as_ref(), &key_type())
                .unwrap()
        );

        // insert key and verify in store
        assert!(
            key_store
                .insert(key().as_ref(), key_spec().as_ref())
                .is_ok()
        );
        assert!(
            key_store
                .contains(key_spec().as_ref(), &key_type())
                .unwrap()
        );
    }

    #[test]
    fn get() {
        let key_store = ArtiEphemeralKeystore::new("test-ephemeral".to_string());

        // verify no result to get
        assert!(
            key_store
                .get(key_spec().as_ref(), &key_type())
                .unwrap()
                .is_none()
        );

        // insert and verify get is a result
        assert!(
            key_store
                .insert(key().as_ref(), key_spec().as_ref())
                .is_ok()
        );

        let key = key_store
            .get(key_spec().as_ref(), &key_type())
            .unwrap()
            .unwrap();

        // Ensure the returned key is of the right type
        assert!(key.downcast::<ed25519::Keypair>().is_ok());

        // verify receiving a key of a different type results in the appropriate error
        key_store.remove(key_spec().as_ref(), &key_type()).unwrap();
        {
            let mut key_dictionary = key_store.key_dictionary.lock().unwrap();
            let _ = key_dictionary.insert(
                (key_spec().arti_path().unwrap(), key_type()),
                key_bad().as_keystore_item().unwrap(),
            );
        }
        assert!(matches!(
            key_store
                .get(key_spec().as_ref(), &key_type())
                .err()
                .unwrap()
                .kind(),
            ErrorKind::Internal
        ));
    }

    #[test]
    fn insert() {
        let key_store = ArtiEphemeralKeystore::new("test-ephemeral".to_string());

        assert!(
            !key_store
                .contains(key_spec().as_ref(), &key_type_bad())
                .unwrap()
        );
        assert!(
            key_store
                .get(key_spec().as_ref(), &key_type_bad())
                .unwrap()
                .is_none()
        );
        assert!(key_store.list().unwrap().is_empty());

        // verify inserting a key succeeds
        assert!(
            key_store
                .insert(key().as_ref(), key_spec().as_ref())
                .is_ok()
        );

        // further ensure correct side effects
        assert!(
            key_store
                .contains(key_spec().as_ref(), &key_type())
                .unwrap()
        );
        assert!(
            key_store
                .get(key_spec().as_ref(), &key_type())
                .unwrap()
                .is_some()
        );
        assert_eq!(key_store.list().unwrap().len(), 1);
    }

    #[test]
    fn remove() {
        let key_store = ArtiEphemeralKeystore::new("test-ephemeral".to_string());

        // verify removing from an empty store returns None
        assert!(
            key_store
                .remove(key_spec().as_ref(), &key_type())
                .unwrap()
                .is_none()
        );

        // verify inserting and removing results in Some(())
        assert!(
            key_store
                .insert(key().as_ref(), key_spec().as_ref())
                .is_ok()
        );
        assert!(
            key_store
                .remove(key_spec().as_ref(), &key_type())
                .unwrap()
                .is_some()
        );

        // verify mismatched key type on removal results in the appropriate error
        {
            let mut key_dictionary = key_store.key_dictionary.lock().unwrap();
            let _ = key_dictionary.insert(
                (key_spec().arti_path().unwrap(), key_type()),
                key_bad().as_keystore_item().unwrap(),
            );
        }
        assert!(matches!(
            key_store
                .remove(key_spec().as_ref(), &key_type())
                .err()
                .unwrap()
                .kind(),
            ErrorKind::Internal
        ));
    }

    #[test]
    fn list() {
        let key_store = ArtiEphemeralKeystore::new("test-ephemeral".to_string());

        // verify empty by default
        assert!(key_store.list().unwrap().is_empty());

        // verify size 1 after inserting a key
        assert!(
            key_store
                .insert(key().as_ref(), key_spec().as_ref())
                .is_ok()
        );
        assert_eq!(key_store.list().unwrap().len(), 1);
    }
}