flex-alloc-secure 0.0.1

Secured allocations for flex-alloc
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
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
//! Support for memory protection around collection types.

use core::any::type_name;
use core::cell::UnsafeCell;
use core::fmt;
use core::mem::ManuallyDrop;
use core::ptr::{addr_of, addr_of_mut};
use core::slice;
use core::sync::atomic;
use std::sync::Once;

use chacha20poly1305::{
    aead::{AeadInPlace, KeyInit},
    ChaCha8Poly1305,
};
use flex_alloc::boxed::Box;
use rand_core::{OsRng, RngCore};
use zeroize::ZeroizeOnDrop;

use crate::alloc::{ProtectionMode, SecureAlloc};
use crate::bytes::FillBytes;
use crate::protect::{ExposeProtected, SecureRef};
use crate::vec::SecureVec;

const ASSOC_DATA_SIZE: usize = 16384;

/// A [`flex-alloc Box`](flex_alloc::boxed::Box) which is backed by a
/// secured allocator and keeps its contents in physical memory. When
/// released, the allocated memory is securely zeroed.
///
/// This container should be converted into a
/// [`ProtectedBox`] or [`ShieldedBox`] to protect secret data.
///
/// This type does NOT protect against accidental output of
/// contained values using the [`Debug`] trait.
///
/// When possible, prefer initialization of the protected container
/// using the [`ProtectedInit`](`crate::ProtectedInit`) or
/// [`ProtectedInitSlice`](`crate::ProtectedInitSlice`) traits.
pub type SecureBox<T> = Box<T, SecureAlloc>;

/// A [`flex-alloc Box`](flex_alloc::boxed::Box) container type which applies
/// additional protections around the memory allocation.
///
/// - The memory is allocated using [`SecureAlloc`] and flagged to remain
///   resident in physical memory (using `mlock`/`VirtualLock`).
/// - When released, the allocated memory is securely zeroed.
/// - When not currently being accessed by the methods of the
///   [`ExposeProtected`] trait, the allocated memory pages are flagged
///   for protection from other processes (using `mprotect`/`VirtualProtect`).
pub struct ProtectedBox<T: ?Sized> {
    shared: SharedAccess<SecureBox<T>>,
}

impl<T: Default> Default for ProtectedBox<T> {
    fn default() -> Self {
        Self::from(SecureBox::default())
    }
}

impl<T: ?Sized> fmt::Debug for ProtectedBox<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("ProtectedBox<{}>", type_name::<T>()))
    }
}

impl<T: ?Sized> Drop for ProtectedBox<T> {
    fn drop(&mut self) {
        BoxData::for_boxed(self.shared.as_mut()).set_protection_mode(ProtectionMode::ReadWrite);
    }
}

impl<T: ?Sized> ExposeProtected for ProtectedBox<T> {
    type Target = T;

    fn expose_read<F>(&self, f: F)
    where
        F: FnOnce(SecureRef<&T>),
    {
        let shared = &self.shared;
        let data = shared.acquire_read(|boxed| {
            BoxData::for_boxed(boxed).set_protection_mode(ProtectionMode::ReadOnly);
        });
        let guard = OnDrop::new(|| {
            shared.release_read(|boxed| {
                BoxData::for_boxed(boxed).set_protection_mode(ProtectionMode::NoAccess);
            });
        });
        f(SecureRef::new(data));
        drop(guard);
    }

    fn expose_write<F>(&mut self, f: F)
    where
        F: FnOnce(SecureRef<&mut Self::Target>),
    {
        let boxed = self.shared.as_mut();
        let mut data = BoxData::for_boxed(boxed);
        data.set_protection_mode(ProtectionMode::ReadWrite);
        let guard = OnDrop::new(|| {
            data.set_protection_mode(ProtectionMode::NoAccess);
        });
        f(SecureRef::new_mut(boxed.as_mut()));
        drop(guard);
    }

    fn unprotect(self) -> SecureBox<Self::Target> {
        let mut shared = unsafe { addr_of!(ManuallyDrop::new(self).shared).read() };
        BoxData::for_boxed(shared.as_mut()).set_protection_mode(ProtectionMode::ReadWrite);
        shared.into_inner()
    }
}

impl<T> From<T> for ProtectedBox<T> {
    fn from(value: T) -> Self {
        Self::from(SecureBox::from(value))
    }
}

impl<T: Clone> From<&[T]> for ProtectedBox<[T]> {
    fn from(data: &[T]) -> Self {
        Self::from(SecureBox::from(data))
    }
}

impl<T, const N: usize> From<[T; N]> for ProtectedBox<[T]> {
    fn from(data: [T; N]) -> Self {
        Self::from(SecureBox::from(data))
    }
}

impl From<&str> for ProtectedBox<str> {
    fn from(data: &str) -> Self {
        Self::from(SecureBox::from(data))
    }
}

impl<T: ?Sized> From<SecureBox<T>> for ProtectedBox<T> {
    fn from(boxed: SecureBox<T>) -> Self {
        let mut wrapper = Self {
            shared: SharedAccess::new(boxed),
        };
        BoxData::for_boxed(wrapper.shared.as_mut()).set_protection_mode(ProtectionMode::NoAccess);
        wrapper
    }
}

impl<T> From<SecureVec<T>> for ProtectedBox<[T]> {
    fn from(vec: SecureVec<T>) -> Self {
        Self::from(vec.into_boxed_slice())
    }
}

unsafe impl<T: Send + ?Sized> Send for ProtectedBox<T> {}
unsafe impl<T: Sync + ?Sized> Sync for ProtectedBox<T> {}

impl<T: ?Sized> ZeroizeOnDrop for ProtectedBox<T> {}

/// A [`flex-alloc Box`](flex_alloc::boxed::Box) container type which applies
/// additional protections around the allocated memory, and is encrypted when
/// not currently being accessed.
///
/// - The memory is allocated using [`SecureAlloc`] and flagged to remain
///   resident in physical memory (using `mlock`/`VirtualLock`).
/// - When released, the allocated memory is securely zeroed.
/// - When not currently being accessed by the methods of the
///   [`ExposeProtected`] trait, the allocated memory pages are flagged
///   for protection from other processes using (`mprotect`/`VirtualProtect`).
/// - When not currently being accessed, the allocated memory is
///   encrypted using the ChaCha8 encryption cipher. A large (16Kb)
///   buffer of randomized bytes is used as associated data during the
///   encryption and decryption process.
pub struct ShieldedBox<T: ?Sized> {
    shared: SharedAccess<SecureBox<T>>,
    key: chacha20poly1305::Key,
    tag: chacha20poly1305::Tag,
}

impl<T: Default> Default for ShieldedBox<T> {
    fn default() -> Self {
        Self::from(SecureBox::default())
    }
}

impl<T: ?Sized> fmt::Debug for ShieldedBox<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("ShieldedBox<{}>", type_name::<T>()))
    }
}

impl<T: ?Sized> Drop for ShieldedBox<T> {
    fn drop(&mut self) {
        BoxData::for_boxed(self.shared.as_mut()).set_protection_mode(ProtectionMode::ReadWrite);
    }
}

impl<T: ?Sized> ExposeProtected for ShieldedBox<T> {
    type Target = T;

    fn expose_read<F>(&self, f: F)
    where
        F: FnOnce(SecureRef<&T>),
    {
        let shared = &self.shared;
        let expose = shared.acquire_read(|boxed| {
            let mut data = BoxData::for_boxed(boxed);
            data.set_protection_mode(ProtectionMode::ReadWrite);
            data.decrypt(&self.key, self.tag);
        });
        let guard = OnDrop::new(|| {
            shared.release_read(|boxed| {
                let mut data = BoxData::for_boxed(boxed);
                data.set_protection_mode(ProtectionMode::ReadWrite);
                let tag = data.encrypt(&self.key);
                if self.tag != tag {
                    panic!("Unshielded box was modified while read-only");
                }
                data.set_protection_mode(ProtectionMode::NoAccess);
            });
        });
        f(SecureRef::new(expose));
        drop(guard);
    }

    fn expose_write<F>(&mut self, f: F)
    where
        F: FnOnce(SecureRef<&mut Self::Target>),
    {
        let boxed = self.shared.as_mut();
        let mut data = BoxData::for_boxed(boxed);
        data.set_protection_mode(ProtectionMode::ReadWrite);
        data.decrypt(&self.key, self.tag);
        let guard = OnDrop::new(|| {
            self.tag = data.encrypt(&self.key);
            data.set_protection_mode(ProtectionMode::NoAccess);
        });
        f(SecureRef::new_mut(boxed.as_mut()));
        drop(guard);
    }

    fn unprotect(self) -> SecureBox<Self::Target> {
        let (key, tag) = (self.key, self.tag);
        let mut shared = unsafe { addr_of!(ManuallyDrop::new(self).shared).read() };
        let mut data = BoxData::for_boxed(shared.as_mut());
        data.set_protection_mode(ProtectionMode::ReadWrite);
        data.decrypt(&key, tag);
        shared.into_inner()
    }
}

impl<T> From<T> for ShieldedBox<T> {
    fn from(value: T) -> Self {
        Self::from(SecureBox::from(value))
    }
}

impl<T: Clone> From<&[T]> for ShieldedBox<[T]> {
    fn from(data: &[T]) -> Self {
        Self::from(SecureBox::from(data))
    }
}

impl<T, const N: usize> From<[T; N]> for ShieldedBox<[T]> {
    fn from(data: [T; N]) -> Self {
        Self::from(SecureBox::from(data))
    }
}

impl From<&str> for ShieldedBox<str> {
    fn from(data: &str) -> Self {
        Self::from(SecureBox::from(data))
    }
}

impl<T: ?Sized> From<SecureBox<T>> for ShieldedBox<T> {
    fn from(boxed: SecureBox<T>) -> Self {
        let mut wrapper = Self {
            shared: SharedAccess::new(boxed),
            key: Default::default(),
            tag: Default::default(),
        };
        wrapper.key.fill_random(OsRng);
        let mut data = BoxData::for_boxed(wrapper.shared.as_mut());
        wrapper.tag = data.encrypt(&wrapper.key);
        data.set_protection_mode(ProtectionMode::NoAccess);
        wrapper
    }
}

impl<T> From<SecureVec<T>> for ShieldedBox<[T]> {
    fn from(vec: SecureVec<T>) -> Self {
        Self::from(vec.into_boxed_slice())
    }
}

unsafe impl<T: Send + ?Sized> Send for ShieldedBox<T> {}
unsafe impl<T: Sync + ?Sized> Sync for ShieldedBox<T> {}

impl<T: ?Sized> ZeroizeOnDrop for ShieldedBox<T> {}

struct OnDrop<F: FnOnce()>(Option<F>);

impl<F: FnOnce()> OnDrop<F> {
    pub fn new(f: F) -> Self {
        Self(Some(f))
    }
}

impl<F: FnOnce()> Drop for OnDrop<F> {
    #[inline]
    fn drop(&mut self) {
        if let Some(f) = self.0.take() {
            f()
        }
    }
}

struct SharedAccess<T> {
    data: UnsafeCell<T>,
    refs: atomic::AtomicUsize,
}

impl<T> SharedAccess<T> {
    const fn new(data: T) -> Self {
        Self {
            data: UnsafeCell::new(data),
            refs: atomic::AtomicUsize::new(0),
        }
    }

    fn acquire_read(&self, acquire: impl FnOnce(&mut T)) -> &T {
        let mut rounds = 0;
        loop {
            let prev = self.refs.fetch_or(1, atomic::Ordering::Acquire);
            if prev == 0 {
                // our responsibility to acquire
                let data = unsafe { &mut *self.data.get() };
                acquire(data);
                // any other readers are queued
                self.refs.store(2, atomic::Ordering::Release);
                break;
            } else if prev & 1 == 0 {
                if (prev + 2) >> (usize::BITS - 1) != 0 {
                    panic!("exceeded maximum number of references");
                }
                // other readers could leave while lock is held
                self.refs.fetch_add(1, atomic::Ordering::Release);
                break;
            } else {
                // busy loop
                rounds += 1;
                if rounds >= 100 {
                    std::thread::yield_now();
                    rounds = 0;
                }
            }
        }
        unsafe { &*self.data.get() }
    }

    fn release_read(&self, release: impl FnOnce(&mut T)) {
        let prev = self.refs.fetch_or(1, atomic::Ordering::Acquire);
        if prev == 2 {
            // our responsibility to release
            let data = unsafe { &mut *self.data.get() };
            release(data);
            self.refs.store(0, atomic::Ordering::Release);
        } else if prev & 1 == 0 {
            // acquired lock, but not our responsibility
            self.refs.fetch_sub(3, atomic::Ordering::Release);
        } else {
            // did not acquire lock, but we can leave
            self.refs.fetch_sub(2, atomic::Ordering::Release);
        }
    }

    pub fn as_mut(&mut self) -> &mut T {
        self.data.get_mut()
    }

    pub fn into_inner(self) -> T {
        self.data.into_inner()
    }
}

struct BoxData {
    ptr: *mut u8,
    len: usize,
}

impl BoxData {
    #[inline]
    pub fn for_boxed<T: ?Sized>(boxed: &mut SecureBox<T>) -> Self {
        let len = size_of_val(boxed.as_ref());
        let ptr = boxed.as_mut_ptr() as *mut u8;
        Self { ptr, len }
    }

    pub fn set_protection_mode(&mut self, mode: ProtectionMode) {
        SecureAlloc
            .set_page_protection(self.ptr, self.len, mode)
            .expect("Error setting page protection");
    }

    #[must_use]
    fn encrypt(&mut self, key: &chacha20poly1305::Key) -> chacha20poly1305::Tag {
        let buffer = unsafe { slice::from_raw_parts_mut(self.ptr, self.len) };
        let engine = ChaCha8Poly1305::new(key);
        let nonce = Default::default();
        engine
            .encrypt_in_place_detached(&nonce, encryption_assoc_data(), buffer)
            .expect("Shielded box encryption error")
    }

    pub fn decrypt(&mut self, key: &chacha20poly1305::Key, tag: chacha20poly1305::Tag) {
        let buffer = unsafe { slice::from_raw_parts_mut(self.ptr, self.len) };
        let engine = ChaCha8Poly1305::new(key);
        let nonce = Default::default();
        engine
            .decrypt_in_place_detached(&nonce, encryption_assoc_data(), buffer, &tag)
            .expect("Shielded box decryption error")
    }
}

fn encryption_assoc_data() -> &'static [u8; ASSOC_DATA_SIZE] {
    static mut DATA: [u8; ASSOC_DATA_SIZE] = [0u8; ASSOC_DATA_SIZE];
    static INIT: Once = Once::new();
    INIT.call_once(|| {
        OsRng.fill_bytes(unsafe { &mut *addr_of_mut!(DATA) });
    });
    unsafe { &*addr_of!(DATA) }
}

#[cfg(test)]
mod tests {

    use super::{
        encryption_assoc_data, ExposeProtected, ProtectedBox, ShieldedBox, ASSOC_DATA_SIZE,
    };
    use crate::vec::SecureVec;

    #[test]
    fn enc_assoc_data_init() {
        let data = encryption_assoc_data();
        assert_ne!(data, &[0u8; ASSOC_DATA_SIZE]);
    }

    #[test]
    fn protected_mut() {
        let mut prot = ProtectedBox::<usize>::default();
        prot.expose_read(|r| {
            assert_eq!(r.as_ref(), &0);
        });
        prot.expose_write(|mut w| {
            *w = 10;
        });
        prot.expose_read(|r| {
            assert_eq!(r.as_ref(), &10);
        });
    }

    #[test]
    fn shielded_mut() {
        let mut prot = ShieldedBox::<usize>::default();
        prot.expose_read(|r| {
            assert_eq!(r.as_ref(), &0);
        });
        prot.expose_write(|mut w| {
            *w = 10;
        });
        prot.expose_read(|r| {
            assert_eq!(r.as_ref(), &10);
        });
    }

    // #[test]
    // fn protected_ref_count() {
    //     let prot = ProtectedBox::<usize>::default();
    //     prot.expose_read(|r1| {
    //         assert_eq!(prot.refs.load(atomic::Ordering::Relaxed), 3);
    //         prot.expose_read(|r2| {
    //             assert_eq!(prot.refs.load(atomic::Ordering::Relaxed), 5);
    //         });
    //         assert_eq!(prot.refs.load(atomic::Ordering::Relaxed), 3);
    //     });
    //     assert_eq!(prot.refs.load(atomic::Ordering::Relaxed), 0);
    // }

    #[test]
    fn protected_vec() {
        let mut vec = SecureVec::new();
        vec.resize(100, 1usize);
        let boxed = ProtectedBox::<[usize]>::from(vec);
        boxed.expose_read(|r| {
            assert_eq!(r.len(), 100);
        });
    }

    // #[test]
    // fn protected_check_protection_crash() {
    //     use crate::boxed::SecureBox;
    //     let boxed = SecureBox::<usize>::default();
    //     let ptr = boxed.as_ptr();
    //     let prot = boxed.protect();
    //     // let read = prot.read_protected(); // would change protection mode
    //     println!("inner: {}", unsafe { &*ptr });
    // }
}