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
use std::cmp::{min, Ordering};
use std::fmt;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use memsec;
#[derive(Clone, Eq, Hash)]
pub struct Protected(Pin<Box<[u8]>>);
impl PartialEq for Protected {
fn eq(&self, other: &Self) -> bool {
secure_cmp(&self.0, &other.0) == Ordering::Equal
}
}
impl Protected {
pub unsafe fn into_vec(self) -> Vec<u8> {
self.iter().cloned().collect()
}
}
impl Deref for Protected {
type Target = [u8];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl AsRef<[u8]> for Protected {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl AsMut<[u8]> for Protected {
fn as_mut(&mut self) -> &mut [u8] {
&mut self.0
}
}
impl DerefMut for Protected {
fn deref_mut(&mut self) -> &mut [u8] {
&mut self.0
}
}
impl From<Vec<u8>> for Protected {
fn from(v: Vec<u8>) -> Self {
Protected(Pin::new(v.into_boxed_slice()))
}
}
impl From<Box<[u8]>> for Protected {
fn from(v: Box<[u8]>) -> Self {
Protected(Pin::new(v))
}
}
impl From<&[u8]> for Protected {
fn from(v: &[u8]) -> Self {
Vec::from(v).into()
}
}
impl Drop for Protected {
fn drop(&mut self) {
unsafe {
memsec::memzero(self.0.as_mut_ptr(), self.0.len());
}
}
}
impl fmt::Debug for Protected {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if cfg!(debug_assertions) {
write!(f, "{:?}", self.0)
} else {
f.write_str("[<Redacted>]")
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Encrypted {
ciphertext: Protected,
iv: Protected,
}
const ENCRYPTED_MEMORY_PREKEY_PAGES: usize = 4;
const ENCRYPTED_MEMORY_PAGE_SIZE: usize = 4096;
mod has_access_to_prekey {
use std::io::{self, Cursor, Write};
use lazy_static;
use crate::types::{AEADAlgorithm, HashAlgorithm, SymmetricAlgorithm};
use crate::crypto::{aead, SessionKey};
use super::*;
lazy_static::lazy_static! {
static ref PREKEY: Box<[Box<[u8]>]> = {
let mut pages = Vec::new();
for _ in 0..ENCRYPTED_MEMORY_PREKEY_PAGES {
let mut page = vec![0; ENCRYPTED_MEMORY_PAGE_SIZE];
crate::crypto::random(&mut page);
pages.push(page.into());
}
pages.into()
};
}
const HASH_ALGO: HashAlgorithm = HashAlgorithm::SHA256;
const SYMMETRIC_ALGO: SymmetricAlgorithm = SymmetricAlgorithm::AES256;
const AEAD_ALGO: AEADAlgorithm = AEADAlgorithm::EAX;
impl Encrypted {
fn sealing_key() -> SessionKey {
let mut ctx = HASH_ALGO.context()
.expect("Mandatory algorithm unsupported");
PREKEY.iter().for_each(|page| ctx.update(page));
let mut sk: SessionKey = vec![0; 256/8].into();
ctx.digest(&mut sk);
sk
}
pub fn new(p: Protected) -> Self {
let mut iv =
vec![0; AEAD_ALGO.iv_size()
.expect("Mandatory algorithm unsupported")];
crate::crypto::random(&mut iv);
let mut ciphertext = Vec::new();
{
let mut encryptor =
aead::Encryptor::new(1,
SYMMETRIC_ALGO,
AEAD_ALGO,
4096,
&iv,
&Self::sealing_key(),
&mut ciphertext)
.expect("Mandatory algorithm unsupported");
encryptor.write_all(&p).unwrap();
encryptor.finish().unwrap();
}
Encrypted {
ciphertext: ciphertext.into(),
iv: iv.into(),
}
}
pub fn map<F, T>(&self, mut fun: F) -> T
where F: FnMut(&Protected) -> T
{
let mut plaintext = Vec::new();
let mut decryptor =
aead::Decryptor::new(1,
SYMMETRIC_ALGO,
AEAD_ALGO,
4096,
&self.iv,
&Self::sealing_key(),
Cursor::new(&self.ciphertext))
.expect("Mandatory algorithm unsupported");
io::copy(&mut decryptor, &mut plaintext)
.expect("Encrypted memory modified or corrupted");
let plaintext: Protected = plaintext.into();
fun(&plaintext)
}
}
}
pub fn secure_cmp(a: &[u8], b: &[u8]) -> Ordering {
let ord1 = a.len().cmp(&b.len());
let ord2 = unsafe {
memsec::memcmp(a.as_ptr(), b.as_ptr(), min(a.len(), b.len()))
};
let ord2 = match ord2 {
0 => Ordering::Equal,
a if a < 0 => Ordering::Less,
a if a > 0 => Ordering::Greater,
_ => unreachable!(),
};
if ord1 == Ordering::Equal { ord2 } else { ord1 }
}