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
// Copyright 2020-2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use crate::{boxed::Boxed, types::*};

use core::{
    fmt::{self, Debug, Formatter},
    ops::{Deref, DerefMut},
};

/// A guarded type for protecting fixed-length secrets allocated on the heap.
///
/// Provides the following features and guarantees:
/// * Causes segfault upon access without using a borrow.
/// * Protected using mprotect:
///    * `Prot::NoAccess` - when the box has no current borrows.
///    * `Prot::ReadOnly` - when the box has at least one current immutable borrow.
///    * `Prot::ReadWrite` - when the box has a current mutable borrow (can only have one at a time).
/// * The allocated memory uses guard pages both proceeding and following the memory. Overflows and large underflows
///   cause immediate termination of the program.
/// * A canary proceeds the memory location to detect smaller underflows.  The program will drop the underlying memory
///   and terminate if detected.
/// * The Memory is locked with `mlock`.
/// * When the memory is freed, `munlock` is called.
/// * The memory is zeroed when no longer in use via `sodium_free`.
/// * `Guarded` types can be compared in constant time.
/// * `Guarded` types can not be printed using `Debug`.
/// * The interior data of a `Guarded` type may not be `Clone`.

#[derive(Clone, Eq)]
pub struct Guarded<T: Bytes> {
    boxed: Boxed<T>,
}

pub struct Ref<'a, T: Bytes> {
    boxed: &'a Boxed<T>,
}

pub struct RefMut<'a, T: Bytes> {
    boxed: &'a mut Boxed<T>,
}

impl<T: Bytes> Guarded<T> {
    pub fn new<F>(f: F) -> Self
    where
        F: FnOnce(&mut T),
    {
        Self {
            boxed: Boxed::new(1, |b| f(b.as_mut())),
        }
    }

    pub fn try_new<R, E, F>(f: F) -> Result<Self, E>
    where
        F: FnOnce(&mut T) -> Result<R, E>,
    {
        Boxed::try_new(1, |b| f(b.as_mut())).map(|b| Self { boxed: b })
    }

    pub fn size(&self) -> usize {
        self.boxed.size()
    }

    pub fn borrow(&self) -> Ref<'_, T> {
        Ref::new(&self.boxed)
    }

    pub fn borrow_mut(&mut self) -> RefMut<'_, T> {
        RefMut::new(&mut self.boxed)
    }
}

impl<'a, T: Bytes> Ref<'a, T> {
    fn new(boxed: &'a Boxed<T>) -> Self {
        assert!(boxed.len() == 1, "Attempted to dereference a box with zero length");

        Self { boxed: boxed.unlock() }
    }
}

impl<T: Bytes> PartialEq for Ref<'_, T> {
    fn eq(&self, rhs: &Self) -> bool {
        self.const_eq(rhs)
    }
}

impl<T: Bytes> PartialEq<RefMut<'_, T>> for Ref<'_, T> {
    fn eq(&self, rhs: &RefMut<'_, T>) -> bool {
        self.const_eq(rhs)
    }
}

impl<T: Bytes> Eq for Ref<'_, T> {}

impl<'a, T: Bytes> RefMut<'a, T> {
    fn new(boxed: &'a mut Boxed<T>) -> Self {
        assert!(boxed.len() == 1, "Attempted to dereference a boxed with zero length");

        Self {
            boxed: boxed.unlock_mut(),
        }
    }
}

impl<T: Bytes> Clone for Ref<'_, T> {
    fn clone(&self) -> Self {
        Self {
            boxed: self.boxed.unlock(),
        }
    }
}

impl<T: Bytes> Drop for Ref<'_, T> {
    fn drop(&mut self) {
        self.boxed.lock();
    }
}

impl<T: Bytes> Deref for Ref<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.boxed.as_ref()
    }
}

impl<T: Bytes> Debug for Ref<'_, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.boxed.fmt(f)
    }
}

impl<T: Bytes> Drop for RefMut<'_, T> {
    fn drop(&mut self) {
        self.boxed.lock();
    }
}

impl<T: Bytes> Deref for RefMut<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.boxed.as_ref()
    }
}

impl<T: Bytes> DerefMut for RefMut<'_, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.boxed.as_mut()
    }
}

impl<T: Bytes> Debug for RefMut<'_, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.boxed.fmt(f)
    }
}

impl<T: Bytes + Randomized> Guarded<T> {
    pub fn random() -> Self {
        Self {
            boxed: Boxed::random(1),
        }
    }
}

impl<T: Bytes + Zeroed> Guarded<T> {
    pub fn zero() -> Self {
        Self { boxed: Boxed::zero(1) }
    }
}

impl<T: Bytes + Zeroed> From<&mut T> for Guarded<T> {
    fn from(data: &mut T) -> Self {
        Self { boxed: data.into() }
    }
}

impl<T: Bytes> Debug for Guarded<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.boxed.fmt(f)
    }
}

impl<T: Bytes + ConstEq> PartialEq for Guarded<T> {
    fn eq(&self, rhs: &Self) -> bool {
        self.boxed.eq(&rhs.boxed)
    }
}

impl<T: Bytes> PartialEq for RefMut<'_, T> {
    fn eq(&self, rhs: &Self) -> bool {
        self.const_eq(rhs)
    }
}

impl<T: Bytes> PartialEq<Ref<'_, T>> for RefMut<'_, T> {
    fn eq(&self, rhs: &Ref<'_, T>) -> bool {
        self.const_eq(rhs)
    }
}

impl<T: Bytes> Eq for RefMut<'_, T> {}

unsafe impl<T: Bytes + Send> Send for Guarded<T> {}
unsafe impl<T: Bytes + Sync> Sync for Guarded<T> {}

#[cfg(test)]
mod test {
    extern crate alloc;

    use alloc::format;

    use super::*;

    #[test]
    fn test_init() {
        let _ = Guarded::<u64>::new(|v| {
            *v = 0x8f1a;

            assert_eq!(*v, 0x8f1a);
        });

        assert!(Guarded::<u8>::try_new(|_| Ok::<(), ()>(())).is_ok());
    }

    #[test]
    fn test_borrows() {
        let guarded = Guarded::<u64>::zero();
        let borrow = guarded.borrow();

        assert_eq!(*borrow, 0);

        let mut guarded = Guarded::<u64>::zero();
        let mut borrow = guarded.borrow_mut();

        *borrow = 0x01ab_cdef;

        assert_eq!(*borrow, 0x01ab_cdef);
    }

    #[test]
    fn test_arrays() {
        let guarded = Guarded::<[u8; 10]>::new(|v| *v = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

        assert_eq!(*guarded.borrow(), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
        assert_eq!(guarded.size(), 10);

        let guarded = Guarded::<[u128; 4]>::zero();

        assert_eq!(guarded.size(), 64);
    }

    #[test]
    fn test_guard() {
        let mut guard = Guarded::<u64>::random();

        assert_eq!(format!("{{ size: {}, hidden }}", 8), format!("{:?}", guard),);

        assert_eq!(format!("{{ size: {}, hidden }}", 8), format!("{:?}", guard.borrow()),);

        assert_eq!(
            format!("{{ size: {}, hidden }}", 8),
            format!("{:?}", guard.borrow_mut()),
        );
    }

    #[test]
    fn test_moving_and_cloning() {
        let guard = Guarded::<u8>::zero();

        let moved = guard;

        assert_eq!(*moved.borrow(), 0);

        let guard = Guarded::<u8>::random();

        let borrow = guard.borrow();
        let clone = borrow.clone();

        assert_eq!(borrow, clone);
    }

    #[test]
    fn test_comparisons() {
        let guard = Guarded::<u8>::random();

        let clone = guard.clone();

        assert_eq!(guard, clone);

        let guard_a = Guarded::<[u128; 8]>::random();
        let guard_b = Guarded::<[u128; 8]>::random();

        assert_ne!(guard_a, guard_b);

        let mut guard = Guarded::<u8>::from(&mut 0xaf);
        let mut clone = guard.clone();

        assert_eq!(guard.borrow_mut(), clone.borrow_mut());
        assert_eq!(guard.borrow_mut(), clone.borrow());
    }

    #[test]
    #[should_panic]
    fn test_borrowing_zero_length() {
        let boxed = Boxed::<u8>::zero(0);
        let _ = boxed.as_ref();
    }

    #[test]
    #[should_panic]
    fn test_borrowing_zero_length_mut() {
        let mut boxed = Boxed::<u8>::zero(0);
        let _ = boxed.as_mut();
    }
}