sensitive 0.10.5

Memory allocator for sensitive information
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
//! Guarded [vector](mod@std::vec) type

use crate::auxiliary::zero;
use crate::pages::{Pages, Allocation, GuardedAlloc};
use crate::alloc::Sensitive;
use crate::guard::{Guard, Ref, RefMut};
use crate::traits::{AsPages, Protectable};

use std::cmp::{PartialEq, min, max};
use std::default::Default;
use std::mem::MaybeUninit;

pub(crate) type InnerVec<T> = std::vec::Vec<T, Sensitive>;

/// Guarded [vector](std::vec::Vec) type
pub type Vec<T> = Guard<InnerVec<T>>;

impl<T> AsPages for InnerVec<T> {
	fn as_pages(&self) -> Option<Pages> {
		if self.capacity() > 0 {
			Some(unsafe { GuardedAlloc::<{ Sensitive::GUARD_PAGES }>::from_ptr(self.as_ptr() as *mut T, self.capacity() * std::mem::size_of::<T>()).into_pages() })
		} else {
			None
		}
	}
}

impl<T> Vec<T> {
	const CMP_MIN: usize = 32;

	fn eq_slice<U: Copy + Into<usize>>(a: &Vec<T>, b: &[U]) -> bool
		where T: Copy + Into<usize> {
		if a.capacity() == 0 {
			debug_assert!(a.is_empty());
			b.is_empty()
		} else {
			debug_assert!(a.capacity() >= Self::CMP_MIN);

			b.iter().take(a.capacity()).enumerate().fold(0, |d, (i, e)| {
				d | unsafe { a.as_ptr().add(i).read().into() ^ (*e).into() }
			}) | (max(a.len(), b.len()) - min(a.len(), b.len())) == 0
		}
	}

	pub fn new() -> Self {
		let guard = Guard::from_inner(std::vec::Vec::new_in(Sensitive));
		debug_assert!(guard.capacity() == 0);
		guard
	}

	pub(crate) fn with_capacity_unprotected(capacity: usize) -> Self {
		Guard::from_inner(std::vec::Vec::with_capacity_in(Allocation::align(capacity), Sensitive))
	}

	pub fn with_capacity(capacity: usize) -> Self {
		let mut guard = Self::with_capacity_unprotected(capacity);
		guard.mutate(|vec| vec.lock().unwrap());
		guard
	}

	#[inline]
	pub fn capacity(&self) -> usize {
		unsafe { self.inner().capacity() }
	}

	pub fn reserve(&mut self, capacity: usize) {
		self.mutate(|vec| {
			vec.reserve(capacity);
			vec.lock().unwrap();
		});
	}

	pub fn reserve_exact(&mut self, capacity: usize) {
		self.mutate(|vec| {
			vec.reserve_exact(capacity);
			vec.lock().unwrap();
		});
	}

	#[inline]
	pub fn len(&self) -> usize {
		unsafe { self.inner().len() }
	}

	#[inline]
	pub fn is_empty(&self) -> bool {
		unsafe { self.inner().is_empty() }
	}

	#[inline]
	pub unsafe fn set_len(&mut self, len: usize) {
		self.inner_mut().set_len(len);
	}

	#[inline]
	pub fn as_ptr(&self) -> *const T {
		unsafe { self.inner() }.as_ptr()
	}

	#[inline]
	pub fn as_mut_ptr(&mut self) -> *mut T {
		unsafe { self.inner_mut() }.as_mut_ptr()
	}
}

impl<T> Default for Vec<T> {
	#[inline]
	fn default() -> Self {
		Self::new()
	}
}

impl<T> From<&mut [T]> for Vec<T> {
	fn from(source: &mut [T]) -> Self {
		let len = source.len();
		let mut guard = Self::with_capacity_unprotected(len);

		unsafe {
			guard.as_mut_ptr().copy_from_nonoverlapping(source.as_ptr(), len);
			guard.set_len(len);
			zero(source.as_mut_ptr(), len);
			guard.inner().lock().unwrap();
		}

		guard
	}
}

impl<T> From<std::vec::Vec<T>> for Vec<T> {
	fn from(mut source: std::vec::Vec<T>) -> Self {
		Self::from(source.as_mut_slice())
	}
}

impl From<&mut str> for Vec<u8> {
	fn from(source: &mut str) -> Self {
		Self::from(unsafe { source.as_bytes_mut() })
	}
}

impl From<std::string::String> for Vec<u8> {
	fn from(mut source: String) -> Self {
		Self::from(source.as_mut_str())
	}
}

impl<T: Copy + Into<usize>, U: Copy + Into<usize>> PartialEq<[U]> for Vec<T> {
	fn eq(&self, other: &[U]) -> bool {
		self.borrow() == other
	}
}

impl<T: Copy + Into<usize>, U: Copy + Into<usize>> PartialEq<&[U]> for Vec<T> {
	fn eq(&self, other: &&[U]) -> bool {
		&self.borrow() == other
	}
}

impl<T: Copy + Into<usize>, U: Copy + Into<usize>, const N: usize> PartialEq<[U; N]> for Vec<T> {
	fn eq(&self, other: &[U; N]) -> bool {
		&self.borrow() == other
	}
}

impl PartialEq<&str> for Vec<u8> {
	fn eq(&self, other: &&str) -> bool {
		&self.borrow() == other
	}
}

impl<T: Copy + Into<usize>, U: Copy + Into<usize>> PartialEq<[U]> for Ref<'_, InnerVec<T>> {
	#[inline]
	fn eq(&self, other: &[U]) -> bool {
		Vec::<T>::eq_slice(self.0, other)
	}
}

impl<T: Copy + Into<usize>, U: Copy + Into<usize>> PartialEq<&[U]> for Ref<'_, InnerVec<T>> {
	#[inline]
	fn eq(&self, other: &&[U]) -> bool {
		self == *other
	}
}

impl<T> Ref<'_, InnerVec<T>> {
	#[inline]
	pub fn as_slice(&self) -> &[T] {
		unsafe { self.0.inner() }.as_slice()
	}
}

impl<T: Copy + Into<usize>, U: Copy + Into<usize>, const N: usize> PartialEq<[U; N]> for Ref<'_, InnerVec<T>> {
	#[inline]
	fn eq(&self, other: &[U; N]) -> bool {
		self == other as &[U]
	}
}

impl PartialEq<&str> for Ref<'_, InnerVec<u8>> {
	#[inline]
	fn eq(&self, other: &&str) -> bool {
		self == other.as_bytes()
	}
}

impl<T> RefMut<'_, InnerVec<T>> {
	#[inline]
	pub fn as_slice(&self) -> &[T] {
		unsafe { self.0.inner() }.as_slice()
	}

	#[inline]
	pub fn len(&self) -> usize {
		unsafe { self.0.inner() }.len()
	}

	#[inline]
	pub fn push(&mut self, value: T) {
		self.inner_mut().push(value);
	}

	#[inline]
	pub fn pop(&mut self) -> Option<T> {
		self.inner_mut().pop()
	}

	#[inline]
	pub fn shrink_to_fit(&mut self) {
		self.inner_mut().shrink_to_fit();
	}

	#[inline]
	pub fn extend<I>(&mut self, iter: I)
		where I: IntoIterator<Item = T> {
		self.inner_mut().extend(iter);
	}

	#[inline]
	pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
		self.inner_mut().spare_capacity_mut()
	}

	#[inline]
	pub fn reserve(&mut self, capacity: usize) {
		self.inner_mut().reserve(capacity);
	}

	#[inline]
	pub fn reserve_exact(&mut self, capacity: usize) {
		self.inner_mut().reserve_exact(capacity);
	}

	#[inline]
	pub unsafe fn set_len(&mut self, len: usize) {
		self.inner_mut().set_len(len);
	}
}

impl<T: Clone> RefMut<'_, InnerVec<T>> {
	#[inline]
	pub fn resize(&mut self, len: usize, value: T) {
		self.inner_mut().resize(len, value);
	}
}

impl<T: Copy + Into<usize>, U: Copy + Into<usize>> PartialEq<[U]> for RefMut<'_, InnerVec<T>> {
	#[inline]
	fn eq(&self, other: &[U]) -> bool {
		Vec::<T>::eq_slice(self.0, other)
	}
}

impl<T: Copy + Into<usize>, U: Copy + Into<usize>> PartialEq<&[U]> for RefMut<'_, InnerVec<T>> {
	#[inline]
	fn eq(&self, other: &&[U]) -> bool {
		self == *other
	}
}

impl<T: Copy + Into<usize>, U: Copy + Into<usize>, const N: usize> PartialEq<[U; N]> for RefMut<'_, InnerVec<T>> {
	#[inline]
	fn eq(&self, other: &[U; N]) -> bool {
		self == other as &[U]
	}
}

impl PartialEq<&str> for RefMut<'_, InnerVec<u8>> {
	#[inline]
	fn eq(&self, other: &&str) -> bool {
		self == other.as_bytes()
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[cfg(target_os = "linux")]
	#[test]
	fn protection() {
		use bulletproof::Bulletproof;

		let mut test = Vec::<u8>::new();
		test.borrow_mut().push(0xff);

		let bp = unsafe { Bulletproof::new() };
		let ptr = test.as_mut_ptr();

		assert_eq!(unsafe { bp.load(ptr) }, Err(()));

		{
			let immutable = test.borrow();
			assert_eq!(immutable[0], 0xff);
			assert_eq!(unsafe { bp.store(ptr, &0x55) }, Err(()));
		}

		assert_eq!(unsafe { bp.load(ptr) }, Err(()));

		{
			let mut mutable = test.borrow_mut();
			assert_eq!(mutable[0], 0xff);
			mutable[0] = 0x55;
			assert_eq!(mutable[0], 0x55);
		}

		assert_eq!(unsafe { bp.load(ptr) }, Err(()));
	}

	#[test]
	fn vec_seq() {
		const LIMIT: usize = 1048576;

		let mut test: Vec<usize> = Vec::new();

		{
			let mut mutable = test.borrow_mut();

			for i in 0..LIMIT {
				mutable.push(i);
			}
		}

		{
			let immutable = test.borrow();

			for i in 0..LIMIT {
				assert_eq!(immutable[i], i);
			}
		}
	}

	#[test]
	fn vec_rng() {
		use rand::prelude::*;

		const LIMIT: usize = 1048576;

		let mut rng = rand_xoshiro::Xoshiro256PlusPlus::from_os_rng();
		let mut test: Vec<u8> = Vec::new();

		let mut mutable = test.borrow_mut();

		for i in 0..LIMIT {
			let rand = rng.random();

			mutable.push(rand);
			assert_eq!(mutable[i], rand);
		}

		for _ in 0..LIMIT {
			assert!(mutable.pop().is_some());
			mutable.shrink_to_fit();
		}
	}

	#[test]
	fn eq() {
		assert_eq!(Vec::<u8>::from(vec![]), [] as [u8; 0]);
		assert_eq!(Vec::<u8>::from(vec![0x00]), [0u8]);

		assert_ne!(Vec::<u8>::from(vec![]), [0u8]);
		assert_ne!(Vec::<u8>::from(vec![0x00]), [] as [u8; 0]);
		assert_ne!(Vec::<u8>::from(vec![0x00]), [0x55u8]);

		assert_eq!(Vec::from("".to_string()), "");
		assert_eq!(Vec::from("Some secret".to_string()), "Some secret");

		assert_ne!(Vec::from("Warum Thunfische das?".to_string()), "");
	}

	#[test]
	fn concurrent() {
		use std::cmp::max;
		use std::sync::{Arc, Barrier};
		use std::thread;

		const LIMIT: usize = 262144;

		let mut test: Vec<usize> = Vec::new();

		{
			let mut mutable = test.borrow_mut();

			for i in 0..LIMIT {
				mutable.push(i);
			}
		}

		let concurrency = max(16, 2 * thread::available_parallelism().unwrap().get());
		let barrier = Arc::new(Barrier::new(concurrency));
		let vec = Arc::new(test);
		let mut threads = std::vec::Vec::with_capacity(concurrency);

		for _ in 0..concurrency {
			let barrier = barrier.clone();
			let vec = vec.clone();

			threads.push(thread::spawn(move || {
				barrier.wait();

				for i in 0..LIMIT {
					let immutable = vec.borrow();
					assert_eq!(immutable[i], i);
				}
			}));
		}

		for thread in threads {
			thread.join().unwrap();
		}
	}

	#[test]
	fn concurrent_rw() {
		use std::cmp::max;
		use std::sync::{Arc, Barrier, RwLock};
		use std::thread;

		const LIMIT: usize = 32768;

		let mut test: Vec<usize> = Vec::new();

		{
			let mut mutable = test.borrow_mut();

			for _ in 0..LIMIT {
				mutable.push(0);
			}
		}

		let concurrency = max(16, 2 * thread::available_parallelism().unwrap().get());
		let barrier = Arc::new(Barrier::new(concurrency));
		let lock = Arc::new(RwLock::new(test));
		let mut threads = std::vec::Vec::with_capacity(concurrency);

		for _ in 0..concurrency {
			let barrier = barrier.clone();
			let lock = lock.clone();

			threads.push(thread::spawn(move || {
				barrier.wait();

				for i in 0..LIMIT {
					{
						let mut vec = lock.write().unwrap();
						let mut mutable = vec.borrow_mut();

						mutable[i] = i;
					}

					{
						let vec = lock.read().unwrap();
						let immutable = vec.borrow();

						assert_eq!(immutable[i], i);
					}
				}
			}));
		}

		for thread in threads {
			thread.join().unwrap();
		}
	}
}