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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
use std::convert::TryInto as _;

use anyhow;
use hmac::{Hmac, Mac as _};
use sha2::Sha512_256;
use slog::error;
use thiserror::Error;
use zeroize::{Zeroize, Zeroizing};

pub use crate::core::common::crypto::mrae::deoxysii::KEY_SIZE;
use crate::{
    core::{
        common::crypto::{
            hash::Hash,
            mrae::deoxysii::{self, NONCE_SIZE},
        },
        storage::mkvs,
    },
    storage::Store,
};

type Nonce = [u8; NONCE_SIZE];
type Kdf = Hmac<Sha512_256>;

/// Unpack the concatenation of (nonce || byte_slice) into (Nonce, &[u8]).
fn unpack_nonce_slice<'a>(packed: &'a [u8]) -> Option<(&'a Nonce, &'a [u8])> {
    if packed.len() <= NONCE_SIZE {
        return None;
    }
    let nonce_ref: &'a Nonce = packed[..NONCE_SIZE]
        .try_into()
        .expect("nonce size mismatch");
    Some((nonce_ref, &packed[NONCE_SIZE..]))
}

/// Errors emitted by the confidential store.
#[derive(Error, Debug)]
pub enum Error {
    #[error("corrupt key")]
    CorruptKey,

    #[error("corrupt value")]
    CorruptValue,

    #[error("decryption failure: {0}")]
    DecryptionFailure(anyhow::Error),
}

/// A key-value store that encrypts all content with DeoxysII.
pub struct ConfidentialStore<S: Store> {
    inner: S,
    deoxys: deoxysii::DeoxysII,
    base_value_prefix: Vec<u8>,
    nonce_counter: usize,
    nonce_key: Zeroizing<Vec<u8>>,
}

impl<S: Store> ConfidentialStore<S> {
    /// Create a new confidential store with the given keypair.
    pub fn new_with_key(inner: S, key: [u8; KEY_SIZE], value_context: &[&[u8]]) -> Self {
        let actual_key = Zeroizing::new(key);

        // Derive a nonce key for nonces used to encrypt storage keys in the store:
        // nonce_key = KDF(key)
        let mut kdf = Kdf::new_from_slice(b"oasis-runtime-sdk/confidential-store: nonce key")
            .expect("Hmac::new_from_slice");
        kdf.update(&key);
        let mut derived = kdf.finalize().into_bytes();
        // Try to destroy as much of the bytes as possible; there's
        // no neat way to get from kdf output to a Vec<u8> without copying a lot.
        let derived = Zeroizing::new(derived.iter_mut());

        ConfidentialStore {
            inner,
            deoxys: deoxysii::DeoxysII::new(&actual_key),
            base_value_prefix: value_context.concat(),
            nonce_counter: 0,
            nonce_key: Zeroizing::new(derived.as_slice().to_vec()),
        }
    }

    fn pack_nonce_slice(&self, nonce: &Nonce, slice: &[u8]) -> Vec<u8> {
        let mut ret = Vec::with_capacity(nonce.len() + slice.len());
        ret.extend_from_slice(nonce);
        ret.extend_from_slice(slice);
        ret
    }

    fn make_key(&self, plain_key: &[u8]) -> (Nonce, Vec<u8>) {
        // The nonce used to encrypt storage keys is derived from a combination
        // of a base nonce key (derived from the encryption key) and the
        // incoming plaintext storage key:
        // nonce = Trunc(NONCE_SIZE, H(nonce_key || plain_key))
        let mut nonce = [0u8; NONCE_SIZE];

        let mut nonce_src = self.nonce_key.clone();
        nonce_src.extend_from_slice(plain_key);

        let hash = Hash::digest_bytes(&nonce_src);
        nonce.copy_from_slice(hash.truncated(NONCE_SIZE));

        let enc_key = self.deoxys.seal(&nonce, plain_key, vec![]);
        let key = self.pack_nonce_slice(&nonce, &enc_key);
        (nonce, key)
    }

    fn make_value(&mut self, plain_value: &[u8]) -> (Nonce, Vec<u8>) {
        // Nonces for value encryption are derived from deterministic
        // environmental data which hopefully changes a lot. In particular,
        // the base_value_prefix should change every time the store is
        // instantiated, and the nonce_counter changes during the store's lifetime.
        // nonce = Trunc(NONCE_SIZE, H(base_prefix || nonce_counter))
        let mut nonce = [0u8; NONCE_SIZE];

        self.nonce_counter += 1;
        let hash = Hash::digest_bytes_list(&[
            self.base_value_prefix.as_slice(),
            self.nonce_counter.to_le_bytes().as_slice(),
        ]);
        nonce.copy_from_slice(hash.truncated(NONCE_SIZE));

        let enc_value = self.deoxys.seal(&nonce, plain_value, vec![]);
        let value = self.pack_nonce_slice(&nonce, &enc_value);
        (nonce, value)
    }

    fn get_item(&self, raw: &[u8]) -> Result<(Nonce, Vec<u8>), Error> {
        match unpack_nonce_slice(raw) {
            Some((nonce, enc_ref)) => {
                let enc = Vec::from(enc_ref);
                let plain = self
                    .deoxys
                    .open(nonce, enc, vec![])
                    .map_err(|err| Error::DecryptionFailure(err.into()))?;
                Ok((*nonce, plain))
            }
            None => Err(Error::CorruptKey),
        }
    }
}

impl<S: Store> Zeroize for ConfidentialStore<S> {
    fn zeroize(&mut self) {
        self.deoxys.zeroize();
        self.nonce_key.zeroize();
    }
}

impl<S: Store> Store for ConfidentialStore<S> {
    fn get(&self, key: &[u8]) -> Option<Vec<u8>> {
        let (_, inner_key) = self.make_key(key);
        self.inner.get(&inner_key).map(|inner_value| {
            self.get_item(&inner_value)
                .expect("error decrypting value")
                .1
        })
    }

    fn insert(&mut self, key: &[u8], value: &[u8]) {
        let (_, inner_key) = self.make_key(key);
        let (_, inner_value) = self.make_value(value);
        self.inner.insert(&inner_key, &inner_value)
    }

    fn remove(&mut self, key: &[u8]) {
        let (_, inner_key) = self.make_key(key);
        self.inner.remove(&inner_key)
    }

    fn iter(&self) -> Box<dyn mkvs::Iterator + '_> {
        Box::new(ConfidentialStoreIterator::new(self))
    }

    fn prefetch_prefixes(&mut self, prefixes: Vec<mkvs::Prefix>, limit: u16) {
        self.inner.prefetch_prefixes(prefixes, limit);
    }
}

struct ConfidentialStoreIterator<'store, S: Store> {
    inner: Box<dyn mkvs::Iterator + 'store>,
    store: &'store ConfidentialStore<S>,

    key: Option<mkvs::Key>,
    value: Option<Vec<u8>>,
    error: Option<anyhow::Error>,
}

impl<'store, S: Store> ConfidentialStoreIterator<'store, S> {
    fn new(store: &'store ConfidentialStore<S>) -> ConfidentialStoreIterator<'_, S> {
        ConfidentialStoreIterator {
            inner: store.inner.iter(),
            store,
            key: None,
            value: None,
            error: None,
        }
    }

    fn reset(&mut self) {
        self.key = None;
        self.value = None;
        self.error = None;
    }

    fn load(&mut self, inner_key: &[u8], inner_value: &[u8]) {
        if !mkvs::Iterator::is_valid(self) {
            return;
        }

        match self.store.get_item(inner_key) {
            Ok((_, key)) => match self.store.get_item(inner_value) {
                Ok((_, value)) => {
                    self.key = Some(key);
                    self.value = Some(value);
                }
                Err(err) => {
                    self.error = Some(err.into());
                }
            },
            Err(err) => {
                self.error = Some(err.into());
            }
        }
    }

    fn reset_and_load(&mut self) {
        self.reset();
        if self.inner.is_valid() {
            if let Some(ref inner_key) = self.inner.get_key().clone() {
                if let Some(ref inner_value) = self.inner.get_value().clone() {
                    self.load(inner_key, inner_value);
                } else {
                    self.error = Some(anyhow::anyhow!("no value in valid inner iterator"));
                }
            } else {
                self.error = Some(anyhow::anyhow!("no key in valid inner iterator"));
            }
        }
    }
}

impl<'store, S: Store> Iterator for ConfidentialStoreIterator<'store, S> {
    type Item = (Vec<u8>, Vec<u8>);

    fn next(&mut self) -> Option<Self::Item> {
        self.reset_and_load();
        if !mkvs::Iterator::is_valid(self) {
            return None;
        }
        mkvs::Iterator::next(&mut *self.inner);
        Some((self.key.clone().unwrap(), self.value.clone().unwrap()))
    }
}

impl<'store, S: Store> mkvs::Iterator for ConfidentialStoreIterator<'store, S> {
    fn set_prefetch(&mut self, prefetch: usize) {
        self.inner.set_prefetch(prefetch)
    }

    fn is_valid(&self) -> bool {
        self.error.is_none() && self.inner.is_valid()
    }

    fn error(&self) -> &Option<anyhow::Error> {
        match self.error {
            Some(_) => &self.error,
            None => self.inner.error(),
        }
    }

    fn rewind(&mut self) {
        self.inner.rewind();
        self.reset_and_load();
    }

    fn seek(&mut self, key: &[u8]) {
        let (_, inner_key) = self.store.make_key(key);
        self.inner.seek(&inner_key);
        self.reset_and_load();
    }

    fn get_key(&self) -> &Option<mkvs::Key> {
        &self.key
    }

    fn get_value(&self) -> &Option<Vec<u8>> {
        &self.value
    }

    fn next(&mut self) {
        mkvs::Iterator::next(&mut *self.inner);
        self.reset_and_load();
    }
}

#[cfg(test)]
mod test {
    extern crate test;
    use super::*;
    use crate::{keymanager::KeyPair, storage, testing::mock::empty_store};
    use test::Bencher;

    const ITEM_COUNT: usize = 10_000;

    fn confidential<'ctx, S: Store + 'ctx>(inner: S, consistent: bool) -> Box<dyn Store + 'ctx> {
        let state_key = if consistent {
            [0xaau8; 32]
        } else {
            KeyPair::generate_mock().state_key.0
        };
        Box::new(ConfidentialStore::new_with_key(
            inner,
            state_key,
            &[b"confidential store unit tests"],
        ))
    }

    fn make_inner<'ctx, S: Store + 'ctx>(
        store: S,
        make_confidential: bool,
    ) -> Box<dyn Store + 'ctx> {
        let inner = storage::PrefixStore::new(
            storage::PrefixStore::new(
                storage::PrefixStore::new(store, "test module"),
                "instance prefix",
            ),
            "type prefix",
        );

        // Replicate the stack as constructed in modules/contracts.
        if make_confidential {
            confidential(inner, false)
        } else {
            Box::new(storage::HashedStore::<_, blake3::Hasher>::new(inner))
        }
    }

    fn make_items(mut num: usize) -> Vec<(Vec<u8>, Vec<u8>)> {
        let mut items = Vec::new();
        if num == 0 {
            num = ITEM_COUNT;
        }
        for i in 0..num {
            items.push((
                format!("key{}", i).into_bytes(),
                format!("value{}", i).into_bytes(),
            ));
        }
        items
    }

    #[test]
    fn basic_operations() {
        let mut store = confidential(empty_store(), true);
        let items = make_items(10);

        // Nothing should exist at the beginning.
        for (k, _) in items.iter() {
            assert!(store.get(k).is_none());
        }
        let mut iter = store.iter();
        iter.rewind();
        assert!(iter.next().is_none());
        drop(iter);

        // Insert even items, then verify they're
        // exactly the ones that exist.
        for (k, v) in items.iter().step_by(2) {
            store.insert(k, v);
        }
        for (i, (k, v)) in items.iter().enumerate() {
            if i % 2 == 0 {
                assert_eq!(&store.get(k).expect("item should exist"), v);
            } else {
                assert!(store.get(k).is_none());
            }
        }
        let mut iter = store.iter();
        iter.rewind();
        assert_eq!(iter.count(), items.len() / 2);

        // Remove some items that exist and some that don't.
        // The stepper should remove key0 and key6, and also
        // try removing key3 and key9.
        for (k, _) in items.iter().step_by(3) {
            store.remove(k);
        }
        for (i, (k, v)) in items.iter().enumerate() {
            if i % 2 == 0 && i % 3 != 0 {
                assert_eq!(&store.get(k).expect("item should exist"), v);
            } else {
                assert!(store.get(k).is_none());
            }
        }
        let mut iter = store.iter();
        iter.rewind();
        assert_eq!(iter.count(), 3);
    }

    #[test]
    fn base_corruption() {
        let mut plain_store = empty_store();
        let mut store = confidential(&mut plain_store, true);

        // Insert something, try corrupting its bytes, then see
        // what the confidential store does with it.
        const KEY: &[u8] = b"key";
        const VALUE: &[u8] = b"value";

        // Insert the key and then try getting it out again, because we don't
        // know the actual bytes in the underlying store.
        store.insert(KEY, VALUE);
        drop(store);
        let mut iter = plain_store.iter();
        iter.rewind();
        let (key, value) = Iterator::next(&mut iter).expect("should have one item");
        drop(iter);

        // Actually encrypted?
        let (_, enc_key) = unpack_nonce_slice(&key).expect("unpacking encrypted key should work");
        assert_ne!(enc_key, b"key");

        // Corrupt nonce part of the key.
        let mut corrupt_key_nonce = key.clone();
        corrupt_key_nonce[4] ^= 0xaau8;
        plain_store.insert(&corrupt_key_nonce, &value);
        plain_store.remove(&key);
        let store = confidential(&mut plain_store, true);
        assert!(store.get(KEY).is_none());
        drop(store);
        plain_store.remove(&corrupt_key_nonce);

        // Corrupt key part of the key.
        let mut corrupt_key_key = key.clone();
        *corrupt_key_key.last_mut().unwrap() ^= 0xaau8;
        plain_store.insert(&corrupt_key_key, &value);
        let store = confidential(&mut plain_store, true);
        assert!(store.get(KEY).is_none());
        drop(store);
        plain_store.remove(&corrupt_key_key);

        // Validate inserting into underlying store.
        plain_store.insert(&key, &value);
        let store = confidential(&mut plain_store, true);
        assert_eq!(store.get(KEY).expect("key should exist"), VALUE);
    }

    #[test]
    #[should_panic]
    fn corruption_value_nonce() {
        let mut plain_store = empty_store();
        let mut store = confidential(&mut plain_store, true);

        // Insert something, try corrupting its bytes, then see
        // what the confidential store does with it.
        const KEY: &[u8] = b"key";
        const VALUE: &[u8] = b"value";

        // Insert the key and then try getting it out again, because we don't
        // know the actual bytes in the underlying store.
        store.insert(KEY, VALUE);
        assert!(store.get(KEY).is_some());
        drop(store);
        let mut iter = plain_store.iter();
        iter.rewind();
        let (key, value) = Iterator::next(&mut iter).expect("should have one item");
        drop(iter);

        // Corrupt the nonce part of the value.
        let mut corrupt_value_nonce = value;
        corrupt_value_nonce[4] ^= 0xaau8;
        plain_store.remove(&key);
        plain_store.insert(&key, &corrupt_value_nonce);
        let store = confidential(&mut plain_store, true);
        store.get(KEY);
        drop(store);
        plain_store.remove(&key);
    }

    #[test]
    #[should_panic]
    fn corruption_value_value() {
        let mut plain_store = empty_store();
        let mut store = confidential(&mut plain_store, true);

        // Insert something, try corrupting its bytes, then see
        // what the confidential store does with it.
        const KEY: &[u8] = b"key";
        const VALUE: &[u8] = b"value";

        // Insert the key and then try getting it out again, because we don't
        // know the actual bytes in the underlying store.
        store.insert(KEY, VALUE);
        assert!(store.get(KEY).is_some());
        drop(store);
        let mut iter = plain_store.iter();
        iter.rewind();
        let (key, value) = Iterator::next(&mut iter).expect("should have one item");
        drop(iter);

        // Corrupt the nonce part of the value.
        let mut corrupt_value_value = value;
        *corrupt_value_value.last_mut().unwrap() ^= 0xaau8;
        plain_store.remove(&key);
        plain_store.insert(&key, &corrupt_value_value);
        let store = confidential(&mut plain_store, true);
        store.get(KEY);
        drop(store);
        plain_store.remove(&key);
    }

    fn run<F>(confidential: bool, inserts: usize, mut cb: F)
    where
        F: FnMut(&mut Box<dyn Store + '_>, &Vec<(Vec<u8>, Vec<u8>)>),
    {
        let mut store = make_inner(empty_store(), confidential);

        let items = make_items(0);
        for i in 0..inserts {
            let item = &items[i % items.len()];
            store.insert(&item.0, &item.1);
        }

        cb(&mut store, &items);
    }

    #[bench]
    fn plain_insert(b: &mut Bencher) {
        run(false, 0, |store, items| {
            let mut i = 0;
            b.iter(|| {
                let item = &items[i % items.len()];
                store.insert(&item.0, &item.1);
                i += 1;
            });
        });
    }

    #[bench]
    fn plain_get(b: &mut Bencher) {
        run(false, ITEM_COUNT / 2, |store, items| {
            let mut i = 0;
            b.iter(|| {
                let j =
                    (2 * i + ((items.len() + 1) % 2) * ((i / (items.len() / 2)) % 2)) % items.len();
                let item = &items[j % items.len()];
                store.get(&item.0);
                i += 1;
            });
        });
    }

    #[bench]
    fn plain_scan(b: &mut Bencher) {
        run(false, ITEM_COUNT, |store, _| {
            let mut it = store.iter();
            b.iter(|| {
                match it.next() {
                    Some(_) => {}
                    None => {
                        it = store.iter();
                    }
                };
            });
        });
    }

    #[bench]
    fn confidential_insert(b: &mut Bencher) {
        run(true, 0, |store, items| {
            let mut i = 0;
            b.iter(|| {
                let item = &items[i % items.len()];
                store.insert(&item.0, &item.1);
                i += 1;
            });
        });
    }

    #[bench]
    fn confidential_get(b: &mut Bencher) {
        run(true, ITEM_COUNT / 2, |store, items| {
            let mut i = 0;
            b.iter(|| {
                let j =
                    (2 * i + ((items.len() + 1) % 2) * ((i / (items.len() / 2)) % 2)) % items.len();
                let item = &items[j % items.len()];
                store.get(&item.0);
                i += 1;
            });
        });
    }

    #[bench]
    fn confidential_scan(b: &mut Bencher) {
        run(true, ITEM_COUNT, |store, _| {
            let mut it = store.iter();
            b.iter(|| {
                match it.next() {
                    Some(_) => {}
                    None => {
                        it = store.iter();
                    }
                };
            });
        });
    }
}