1#[cfg(not(feature = "use_os"))]
2use alloc::{Layout, alloc, dealloc};
3
4use super::{Error, SecureVec};
5use core::{marker::PhantomData, mem, ptr::NonNull};
6use zeroize::Zeroize;
7
8#[cfg(feature = "use_os")]
9use super::{alloc_aligned, free, page_aligned_size};
10#[cfg(feature = "use_os")]
11use memsec::Prot;
12
13pub struct SecureArray<T, const LENGTH: usize>
58where
59 T: Zeroize,
60{
61 ptr: NonNull<T>,
62 _marker: PhantomData<T>,
63}
64
65unsafe impl<T: Zeroize + Send, const LENGTH: usize> Send for SecureArray<T, LENGTH> {}
66unsafe impl<T: Zeroize + Send + Sync, const LENGTH: usize> Sync for SecureArray<T, LENGTH> {}
67
68impl<T, const LENGTH: usize> SecureArray<T, LENGTH>
69where
70 T: Zeroize,
71{
72 pub fn empty() -> Result<Self, Error> {
76 let size = LENGTH * mem::size_of::<T>();
77 if size == 0 {
78 return Err(Error::LengthCannotBeZero);
80 }
81
82 let ptr = unsafe { alloc_aligned::<T>(size)? };
83
84 let secure_array = SecureArray {
85 ptr,
86 _marker: PhantomData,
87 };
88
89 let (encrypted, locked) = secure_array.lock_memory();
90
91 #[cfg(feature = "use_os")]
92 if !locked {
93 return Err(Error::LockFailed);
94 }
95
96 #[cfg(feature = "use_os")]
97 if !encrypted {
98 return Err(Error::CryptProtectMemoryFailed);
99 }
100
101 Ok(secure_array)
102 }
103
104 pub fn from_slice_mut(content: &mut [T; LENGTH]) -> Result<Self, Error> {
108 let secure_array = Self::empty()?;
109
110 secure_array.unlock_memory();
111
112 unsafe {
113 core::ptr::copy_nonoverlapping(
115 content.as_ptr(),
116 secure_array.ptr.as_ptr(),
117 LENGTH,
118 );
119 }
120
121 content.zeroize();
122
123 let (encrypted, locked) = secure_array.lock_memory();
124
125 #[cfg(feature = "use_os")]
126 if !locked {
127 return Err(Error::LockFailed);
128 }
129
130 #[cfg(feature = "use_os")]
131 if !encrypted {
132 return Err(Error::CryptProtectMemoryFailed);
133 }
134
135 Ok(secure_array)
136 }
137
138 pub fn from_slice(content: &[T; LENGTH]) -> Result<Self, Error> {
142 let secure_array = Self::empty()?;
143
144 secure_array.unlock_memory();
145
146 unsafe {
147 core::ptr::copy_nonoverlapping(
149 content.as_ptr(),
150 secure_array.ptr.as_ptr(),
151 LENGTH,
152 );
153 }
154
155 let (encrypted, locked) = secure_array.lock_memory();
156
157 #[cfg(feature = "use_os")]
158 if !locked {
159 return Err(Error::LockFailed);
160 }
161
162 #[cfg(feature = "use_os")]
163 if !encrypted {
164 return Err(Error::CryptProtectMemoryFailed);
165 }
166
167 Ok(secure_array)
168 }
169
170 pub fn len(&self) -> usize {
171 LENGTH
172 }
173
174 pub fn is_empty(&self) -> bool {
175 self.len() == 0
176 }
177
178 pub fn as_ptr(&self) -> *const T {
179 self.ptr.as_ptr()
180 }
181
182 pub fn as_mut_ptr(&mut self) -> *mut u8 {
183 self.ptr.as_ptr() as *mut u8
184 }
185
186 #[allow(dead_code)]
187 fn aligned_size(&self) -> usize {
188 let size = self.len() * mem::size_of::<T>();
189 #[cfg(feature = "use_os")]
190 {
191 unsafe { page_aligned_size(size) }
192 }
193 #[cfg(not(feature = "use_os"))]
194 {
195 size }
197 }
198
199 #[cfg(all(feature = "use_os", windows))]
200 fn encypt_memory(&self) -> bool {
201 let ptr = self.as_ptr() as *mut u8;
202 super::crypt_protect_memory(ptr, self.aligned_size())
203 }
204
205 #[cfg(all(feature = "use_os", windows))]
206 fn decrypt_memory(&self) -> bool {
207 let ptr = self.as_ptr() as *mut u8;
208 super::crypt_unprotect_memory(ptr, self.aligned_size())
209 }
210
211 pub(crate) fn lock_memory(&self) -> (bool, bool) {
212 #[cfg(feature = "use_os")]
213 {
214 #[cfg(windows)]
215 {
216 let encrypt_ok = self.encypt_memory();
217 let mprotect_ok = super::mprotect(self.ptr, Prot::NoAccess);
218 (encrypt_ok, mprotect_ok)
219 }
220 #[cfg(unix)]
221 {
222 let mprotect_ok = super::mprotect(self.ptr, Prot::NoAccess);
223 (true, mprotect_ok)
224 }
225 }
226 #[cfg(not(feature = "use_os"))]
227 {
228 (true, true) }
230 }
231
232 pub(crate) fn unlock_memory(&self) -> (bool, bool) {
233 #[cfg(feature = "use_os")]
234 {
235 #[cfg(windows)]
236 {
237 let mprotect_ok = super::mprotect(self.ptr, Prot::ReadWrite);
238 if !mprotect_ok {
239 return (false, false);
240 }
241 let decrypt_ok = self.decrypt_memory();
242 (decrypt_ok, mprotect_ok)
243 }
244 #[cfg(unix)]
245 {
246 let mprotect_ok = super::mprotect(self.ptr, Prot::ReadWrite);
247 (true, mprotect_ok)
248 }
249 }
250
251 #[cfg(not(feature = "use_os"))]
252 {
253 (true, true) }
255 }
256
257 pub fn unlock<F, R>(&self, f: F) -> R
259 where
260 F: FnOnce(&[T]) -> R,
261 {
262 self.unlock_memory();
263 let slice = unsafe { core::slice::from_raw_parts(self.ptr.as_ptr(), LENGTH) };
264 let result = f(slice);
265 self.lock_memory();
266 result
267 }
268
269 pub fn unlock_mut<F, R>(&mut self, f: F) -> R
271 where
272 F: FnOnce(&mut [T]) -> R,
273 {
274 self.unlock_memory();
275 let slice = unsafe { core::slice::from_raw_parts_mut(self.ptr.as_ptr(), LENGTH) };
276 let result = f(slice);
277 self.lock_memory();
278 result
279 }
280
281 pub fn erase(&mut self) {
283 self.unlock_mut(|slice| {
284 for element in slice.iter_mut() {
285 element.zeroize();
286 }
287 });
288 }
289}
290
291impl<T: Zeroize, const LENGTH: usize> core::ops::Index<usize> for SecureArray<T, LENGTH> {
292 type Output = T;
293 fn index(&self, index: usize) -> &Self::Output {
294 assert!(index < self.len(), "Index out of bounds");
295 unsafe {
296 let ptr = self.ptr.as_ptr().add(index);
297 &*ptr
298 }
299 }
300}
301
302impl<T: Zeroize, const LENGTH: usize> core::ops::IndexMut<usize> for SecureArray<T, LENGTH> {
303 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
304 assert!(index < self.len(), "Index out of bounds");
305 unsafe {
306 let ptr = self.ptr.as_ptr().add(index);
307 &mut *ptr
308 }
309 }
310}
311
312impl<T: Zeroize, const LENGTH: usize> Drop for SecureArray<T, LENGTH> {
313 fn drop(&mut self) {
314 self.erase();
315 self.unlock_memory();
316
317 let size = LENGTH * mem::size_of::<T>();
318 if size == 0 {
319 return;
320 }
321
322 #[cfg(feature = "use_os")]
323 free(self.ptr);
324
325 #[cfg(not(feature = "use_os"))]
326 {
327 let layout = Layout::from_size_align_unchecked(size, mem::align_of::<T>());
328 dealloc(self.ptr.as_ptr() as *mut u8, layout);
329 }
330 }
331}
332
333impl<T: Clone + Zeroize, const LENGTH: usize> Clone for SecureArray<T, LENGTH> {
334 fn clone(&self) -> Self {
335 let mut new_array = Self::empty().unwrap();
336 self.unlock(|src_slice| {
337 new_array.unlock_mut(|dest_slice| {
338 dest_slice.clone_from_slice(src_slice);
339 });
340 });
341 new_array
342 }
343}
344
345impl<const LENGTH: usize> TryFrom<SecureVec<u8>> for SecureArray<u8, LENGTH> {
346 type Error = Error;
347
348 fn try_from(vec: SecureVec<u8>) -> Result<Self, Self::Error> {
354 if vec.len() != LENGTH {
355 return Err(Error::LengthMismatch);
356 }
357
358 let mut new_array = Self::empty()?;
359
360 vec.unlock_slice(|vec_slice| {
361 new_array.unlock_mut(|array_slice| {
362 array_slice.copy_from_slice(vec_slice);
363 });
364 });
365
366 Ok(new_array)
367 }
368}
369
370#[cfg(feature = "serde")]
371impl<const LENGTH: usize> serde::Serialize for SecureArray<u8, LENGTH> {
372 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
373 where
374 S: serde::Serializer,
375 {
376 self.unlock(|slice| serializer.collect_seq(slice.iter()))
377 }
378}
379
380#[cfg(feature = "serde")]
381impl<'de, const LENGTH: usize> serde::Deserialize<'de> for SecureArray<u8, LENGTH> {
382 fn deserialize<D>(deserializer: D) -> Result<SecureArray<u8, LENGTH>, D::Error>
383 where
384 D: serde::Deserializer<'de>,
385 {
386 struct SecureArrayVisitor<const L: usize>;
387
388 impl<'de, const L: usize> serde::de::Visitor<'de> for SecureArrayVisitor<L> {
389 type Value = SecureArray<u8, L>;
390
391 fn expecting(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
392 write!(formatter, "a byte array of length {}", L)
393 }
394
395 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
396 where
397 A: serde::de::SeqAccess<'de>,
398 {
399 let mut data: SecureVec<u8> =
400 SecureVec::new_with_capacity(L).map_err(serde::de::Error::custom)?;
401 while let Some(byte) = seq.next_element()? {
402 data.push(byte);
403 }
404
405 if data.len() != L {
407 return Err(serde::de::Error::invalid_length(
408 data.len(),
409 &self,
410 ));
411 }
412
413 SecureArray::try_from(data).map_err(serde::de::Error::custom)
414 }
415 }
416
417 deserializer.deserialize_bytes(SecureArrayVisitor::<LENGTH>)
418 }
419}
420
421#[cfg(all(test, feature = "use_os"))]
422mod tests {
423 use super::*;
424 use std::process::{Command, Stdio};
425 use std::sync::{Arc, Mutex};
426
427 #[test]
428 fn test_creation() {
429 let exposed_mut = &mut [1, 2, 3];
430 let array: SecureArray<u8, 3> = SecureArray::from_slice_mut(exposed_mut).unwrap();
431 assert_eq!(array.len(), 3);
432
433 array.unlock(|slice| {
434 assert_eq!(slice, &[1, 2, 3]);
435 });
436
437 assert_eq!(exposed_mut, &[0u8; 3]);
438
439 let exposed = &[1, 2, 3];
440 let array: SecureArray<u8, 3> = SecureArray::from_slice(exposed).unwrap();
441 assert_eq!(array.len(), 3);
442
443 array.unlock(|slice| {
444 assert_eq!(slice, &[1, 2, 3]);
445 });
446
447 assert_eq!(exposed, &[1, 2, 3]);
448 }
449
450 #[test]
451 fn test_from_secure_vec() {
452 let vec: SecureVec<u8> = SecureVec::from_slice(&[1, 2, 3]).unwrap();
453 let array: SecureArray<u8, 3> = vec.try_into().unwrap();
454 assert_eq!(array.len(), 3);
455 array.unlock(|slice| {
456 assert_eq!(slice, &[1, 2, 3]);
457 });
458 }
459
460 #[test]
461 fn test_erase() {
462 let exposed: &mut [u8; 3] = &mut [1, 2, 3];
463 let mut array: SecureArray<u8, 3> = SecureArray::from_slice_mut(exposed).unwrap();
464 array.erase();
465 array.unlock(|slice| {
466 assert_eq!(slice, &[0u8; 3]);
467 });
468 }
469
470 #[test]
471 fn test_size_cannot_be_zero() {
472 let secure: SecureArray<u8, 3> = SecureArray::from_slice(&[1, 2, 3]).unwrap();
473 let size = secure.aligned_size();
474 assert_eq!(size > 0, true);
475
476 let secure: SecureArray<u8, 3> = SecureArray::empty().unwrap();
477 let size = secure.aligned_size();
478 assert_eq!(size > 0, true);
479 }
480
481 #[test]
482 #[should_panic]
483 fn test_length_cannot_be_zero() {
484 let secure_vec = SecureVec::new().unwrap();
485 let _secure_array: SecureArray<u8, 0> = SecureArray::try_from(secure_vec).unwrap();
486 }
487
488 #[test]
489 fn lock_unlock() {
490 let exposed: &mut [u8; 3] = &mut [1, 2, 3];
491 let secure: SecureArray<u8, 3> = SecureArray::from_slice_mut(exposed).unwrap();
492 let size = secure.aligned_size();
493 assert_eq!(size > 0, true);
494
495 let (decrypted, unlocked) = secure.unlock_memory();
496 assert!(decrypted);
497 assert!(unlocked);
498
499 let (encrypted, locked) = secure.lock_memory();
500 assert!(encrypted);
501 assert!(locked);
502 }
503
504 #[test]
505 fn test_clone() {
506 let mut array1: SecureArray<u8, 3> = SecureArray::empty().unwrap();
507 array1.unlock_mut(|slice| {
508 slice[0] = 1;
509 slice[1] = 2;
510 slice[2] = 3;
511 });
512
513 let array2 = array1.clone();
514
515 array2.unlock(|slice| {
516 assert_eq!(slice, &[1, 2, 3]);
517 });
518
519 array1.unlock(|slice| {
520 assert_eq!(slice, &[1, 2, 3]);
521 });
522 }
523
524 #[test]
525 fn test_thread_safety() {
526 let exposed: &mut [u8; 3] = &mut [1, 2, 3];
527 let array: SecureArray<u8, 3> = SecureArray::from_slice_mut(exposed).unwrap();
528 let arc_array = Arc::new(Mutex::new(array));
529 let mut handles = Vec::new();
530
531 for _ in 0..5u8 {
532 let array_clone = Arc::clone(&arc_array);
533 let handle = std::thread::spawn(move || {
534 let mut guard = array_clone.lock().unwrap();
535 guard.unlock_mut(|slice| {
536 slice[0] += 1;
537 });
538 });
539 handles.push(handle);
540 }
541
542 for handle in handles {
543 handle.join().unwrap();
544 }
545
546 let final_array = arc_array.lock().unwrap();
547 final_array.unlock(|slice| {
548 assert_eq!(slice[0], 6);
549 assert_eq!(slice[1], 2);
550 assert_eq!(slice[2], 3);
551 });
552 }
553
554 #[test]
555 fn test_index_should_fail_when_locked() {
556 let arg = "CRASH_TEST_ARRAY_LOCKED";
557
558 if std::env::args().any(|a| a == arg) {
559 let exposed: &mut [u8; 3] = &mut [1, 2, 3];
560 let array: SecureArray<u8, 3> = SecureArray::from_slice_mut(exposed).unwrap();
561 let _value = core::hint::black_box(array[0]);
562
563 std::process::exit(1);
564 }
565
566 let child = Command::new(std::env::current_exe().unwrap())
567 .arg("array::tests::test_index_should_fail_when_locked")
568 .arg(arg)
569 .arg("--nocapture")
570 .stdout(Stdio::piped())
571 .stderr(Stdio::piped())
572 .spawn()
573 .expect("Failed to spawn child process");
574
575 let output = child.wait_with_output().expect("Failed to wait on child");
576 let status = output.status;
577
578 assert!(
579 !status.success(),
580 "Process exited successfully with code {:?}, but it should have crashed.",
581 status.code()
582 );
583
584 #[cfg(unix)]
585 {
586 use std::os::unix::process::ExitStatusExt;
587 let signal = status
588 .signal()
589 .expect("Process was not terminated by a signal on Unix.");
590 assert!(
591 signal == libc::SIGSEGV || signal == libc::SIGBUS,
592 "Process terminated with unexpected signal: {}",
593 signal
594 );
595 println!(
596 "Test passed: Process correctly terminated with signal {}.",
597 signal
598 );
599 }
600
601 #[cfg(windows)]
602 {
603 const STATUS_ACCESS_VIOLATION: i32 = 0xC0000005_u32 as i32;
604 assert_eq!(
605 status.code(),
606 Some(STATUS_ACCESS_VIOLATION),
607 "Process exited with unexpected code: {:x?}. Expected STATUS_ACCESS_VIOLATION.",
608 status.code()
609 );
610 eprintln!("Test passed: Process correctly terminated with STATUS_ACCESS_VIOLATION.");
611 }
612 }
613
614 #[test]
615 fn test_unlock_mut() {
616 let exposed: &mut [u8; 3] = &mut [1, 2, 3];
617 let mut array: SecureArray<u8, 3> = SecureArray::from_slice_mut(exposed).unwrap();
618
619 array.unlock_mut(|slice| {
620 slice[1] = 100;
621 });
622
623 array.unlock(|slice| {
624 assert_eq!(slice, &[1, 100, 3]);
625 });
626 }
627
628 #[cfg(feature = "serde")]
629 #[test]
630 fn test_serde() {
631 let exposed: &mut [u8; 3] = &mut [1, 2, 3];
632 let array: SecureArray<u8, 3> = SecureArray::from_slice_mut(exposed).unwrap();
633 let json_string = serde_json::to_string(&array).expect("Serialization failed");
634 let json_bytes = serde_json::to_vec(&array).expect("Serialization failed");
635
636 let deserialized_string: SecureArray<u8, 3> =
637 serde_json::from_str(&json_string).expect("Deserialization failed");
638
639 let deserialized_bytes: SecureArray<u8, 3> =
640 serde_json::from_slice(&json_bytes).expect("Deserialization failed");
641
642 deserialized_string.unlock(|slice| {
643 assert_eq!(slice, &[1, 2, 3]);
644 });
645
646 deserialized_bytes.unlock(|slice| {
647 assert_eq!(slice, &[1, 2, 3]);
648 });
649 }
650}