-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathcrypto.rs
More file actions
363 lines (328 loc) · 12 KB
/
Copy pathcrypto.rs
File metadata and controls
363 lines (328 loc) · 12 KB
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
// SPDX-FileCopyrightText: © 2024 Phala Network <dstack@phala.network>
//
// SPDX-License-Identifier: Apache-2.0
use aes_gcm::{
aead::{Aead, Nonce, Payload},
Aes256Gcm, KeyInit,
};
use anyhow::{anyhow, ensure, Context, Result};
use binrw::{binrw, io::NoSeek, BinRead, BinWrite};
use std::io::{Cursor, Read, Write};
use x25519_dalek::{PublicKey, StaticSecret};
pub const STREAM_MAGIC: &[u8; 8] = b"dstkscrt";
pub const DEFAULT_CHUNK_SIZE: usize = 1024 * 1024;
pub const MAX_CHUNK_SIZE: usize = 16 * 1024 * 1024;
const STREAM_VERSION: u8 = 0;
const FINAL_CHUNK: u8 = 1;
#[binrw]
#[brw(little)]
struct StreamHeader {
version: u8,
ephemeral_public_key: [u8; 32],
nonce_prefix: [u8; 8],
chunk_size: u32,
}
#[binrw]
#[brw(little)]
struct FrameHeader {
flags: u8,
plaintext_len: u32,
}
pub fn dh_agree(secret: [u8; 32], their_pubkey: [u8; 32]) -> [u8; 32] {
let secret = StaticSecret::from(secret);
let their_public = PublicKey::from(their_pubkey);
let shared_secret = secret.diffie_hellman(&their_public);
shared_secret.to_bytes()
}
pub fn dh_decrypt(secret: [u8; 32], ciphertext: &[u8]) -> Result<Vec<u8>> {
// Extract components (matching JS implementation)
let ephemeral_pubkey = ciphertext
.get(..32)
.ok_or(anyhow!("invalid ephemeral public key length"))?
.try_into()
.map_err(|_| anyhow!("invalid ephemeral public key length"))?;
let iv = &ciphertext.get(32..44).ok_or(anyhow!("invalid IV length"))?;
let ciphertext = &ciphertext
.get(44..)
.ok_or(anyhow!("invalid ciphertext length"))?;
// Derive shared secret using X25519
let shared_secret = dh_agree(secret, ephemeral_pubkey);
if shared_secret.iter().all(|byte| *byte == 0) {
return Err(anyhow!("invalid X25519 shared secret"));
}
// Create AES-GCM cipher
let cipher = Aes256Gcm::new_from_slice(&shared_secret)
.map_err(|e| anyhow!("failed to create cipher: {}", e))?;
// Decrypt using AES-GCM
cipher
.decrypt(Nonce::<Aes256Gcm>::from_slice(iv), ciphertext.as_ref())
.map_err(|e| anyhow!("Decryption failed: {}", e))
}
fn stream_nonce(prefix: &[u8; 8], index: u32) -> [u8; 12] {
let mut nonce = [0u8; 12];
nonce[..8].copy_from_slice(prefix);
nonce[8..].copy_from_slice(&index.to_be_bytes());
nonce
}
fn stream_aad(header: &StreamHeader, index: u32, frame_header: &FrameHeader) -> Result<Vec<u8>> {
let mut aad = Cursor::new(Vec::new());
aad.write_all(STREAM_MAGIC)
.context("failed to encode stream magic as AAD")?;
header
.write(&mut aad)
.context("failed to encode stream header as AAD")?;
index
.write_le(&mut aad)
.context("failed to encode chunk index as AAD")?;
frame_header
.write(&mut aad)
.context("failed to encode frame header as AAD")?;
Ok(aad.into_inner())
}
/// Encrypts a reader as independently authenticated chunks.
pub fn dh_encrypt_stream(
remote_public_key: [u8; 32],
mut input: impl Read,
mut output: impl Write,
chunk_size: usize,
) -> Result<()> {
ensure!(
(1..=MAX_CHUNK_SIZE).contains(&chunk_size),
"chunk size must be between 1 and {MAX_CHUNK_SIZE} bytes"
);
let mut ephemeral_secret = [0u8; 32];
getrandom::fill(&mut ephemeral_secret).context("failed to generate ephemeral secret")?;
let ephemeral_secret = StaticSecret::from(ephemeral_secret);
let ephemeral_public_key = PublicKey::from(&ephemeral_secret).to_bytes();
let remote_public_key = PublicKey::from(remote_public_key);
let shared_secret = ephemeral_secret
.diffie_hellman(&remote_public_key)
.to_bytes();
ensure!(
!shared_secret.iter().all(|byte| *byte == 0),
"invalid X25519 shared secret"
);
let cipher = Aes256Gcm::new_from_slice(&shared_secret)
.map_err(|e| anyhow!("failed to create cipher: {e}"))?;
let mut nonce_prefix = [0u8; 8];
getrandom::fill(&mut nonce_prefix).context("failed to generate nonce prefix")?;
let header = StreamHeader {
version: STREAM_VERSION,
ephemeral_public_key,
nonce_prefix,
chunk_size: chunk_size as u32,
};
output
.write_all(STREAM_MAGIC)
.context("failed to write stream magic")?;
header
.write(&mut NoSeek::new(&mut output))
.context("failed to write stream header")?;
let mut current = vec![0u8; chunk_size];
let mut next = vec![0u8; chunk_size];
let mut current_len = read_chunk(&mut input, &mut current)?;
let mut index = 0u32;
loop {
let next_len = read_chunk(&mut input, &mut next)?;
let final_chunk = next_len == 0;
let flags = if final_chunk { FINAL_CHUNK } else { 0 };
let frame_header = FrameHeader {
flags,
plaintext_len: current_len as u32,
};
let aad = stream_aad(&header, index, &frame_header)?;
let nonce = stream_nonce(&nonce_prefix, index);
let encrypted = cipher
.encrypt(
(&nonce).into(),
Payload {
msg: ¤t[..current_len],
aad: &aad,
},
)
.map_err(|e| anyhow!("failed to encrypt chunk {index}: {e}"))?;
frame_header
.write(&mut NoSeek::new(&mut output))
.with_context(|| format!("failed to write header for chunk {index}"))?;
output
.write_all(&encrypted)
.with_context(|| format!("failed to write chunk {index}"))?;
if final_chunk {
break;
}
index = index.checked_add(1).context("too many chunks")?;
std::mem::swap(&mut current, &mut next);
current_len = next_len;
}
output.flush().context("failed to flush encrypted output")?;
Ok(())
}
fn read_chunk(input: &mut impl Read, buffer: &mut [u8]) -> Result<usize> {
let mut read = 0;
while read < buffer.len() {
match input
.read(&mut buffer[read..])
.context("failed to read input")?
{
0 => break,
n => read += n,
}
}
Ok(read)
}
/// Decrypts a chunked stream after the caller has consumed [`STREAM_MAGIC`].
pub fn dh_decrypt_stream(
secret: [u8; 32],
mut input: impl Read,
mut output: impl Write,
) -> Result<()> {
let header =
StreamHeader::read(&mut NoSeek::new(&mut input)).context("invalid stream header")?;
ensure!(
header.version == STREAM_VERSION,
"unsupported stream version: {}",
header.version
);
let chunk_size = header.chunk_size as usize;
ensure!(
(1..=MAX_CHUNK_SIZE).contains(&chunk_size),
"invalid chunk size: {chunk_size}"
);
let shared_secret = dh_agree(secret, header.ephemeral_public_key);
ensure!(
!shared_secret.iter().all(|byte| *byte == 0),
"invalid X25519 shared secret"
);
let cipher = Aes256Gcm::new_from_slice(&shared_secret)
.map_err(|e| anyhow!("failed to create cipher: {e}"))?;
let mut index = 0u32;
loop {
let frame_header = FrameHeader::read(&mut NoSeek::new(&mut input))
.with_context(|| format!("missing final chunk at chunk {index}"))?;
ensure!(
frame_header.flags & !FINAL_CHUNK == 0,
"invalid chunk flags"
);
let final_chunk = frame_header.flags == FINAL_CHUNK;
let plaintext_len = frame_header.plaintext_len as usize;
ensure!(plaintext_len <= chunk_size, "chunk {index} is too large");
ensure!(
final_chunk || plaintext_len == chunk_size,
"non-final chunk {index} has an invalid length"
);
let mut encrypted = vec![0u8; plaintext_len + 16];
input
.read_exact(&mut encrypted)
.with_context(|| format!("truncated chunk {index}"))?;
let nonce = stream_nonce(&header.nonce_prefix, index);
let aad = stream_aad(&header, index, &frame_header)?;
let plaintext = cipher
.decrypt(
(&nonce).into(),
Payload {
msg: &encrypted,
aad: &aad,
},
)
.map_err(|e| anyhow!("failed to decrypt chunk {index}: {e}"))?;
output
.write_all(&plaintext)
.with_context(|| format!("failed to write chunk {index}"))?;
if final_chunk {
let mut trailing = [0u8; 1];
ensure!(
input.read(&mut trailing).context("failed to read input")? == 0,
"trailing data after final chunk"
);
output.flush().context("failed to flush plaintext output")?;
return Ok(());
}
index = index.checked_add(1).context("too many chunks")?;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_dh_agree() {
use rand::Rng;
let secret = rand::thread_rng().gen::<[u8; 32]>();
let pubkey = rand::thread_rng().gen::<[u8; 32]>();
let shared = dh_agree(secret, pubkey);
assert_eq!(shared.len(), 32);
println!("secret: {:?}", hex::encode(secret));
println!("pubkey: {:?}", hex::encode(pubkey));
println!("shared: {:?}", hex::encode(shared));
}
#[test]
fn test_dh_decrypt_invalid_input() {
let secret = [0u8; 32];
// Test empty input
assert!(dh_decrypt(secret, &[]).is_err());
// Test input too short for public key
assert!(dh_decrypt(secret, &[0u8; 31]).is_err());
// Test input too short for IV
assert!(dh_decrypt(secret, &[0u8; 43]).is_err());
// Test input with no ciphertext
assert!(dh_decrypt(secret, &[0u8; 44]).is_err());
}
#[test]
fn test_dh_decrypt() {
let secret: [u8; 32] =
hex::decode("7c282bf94b35dc47801dc953bfa0896fc2bd313381d3e8eca4e42f6536d2a96f")
.unwrap()
.try_into()
.unwrap();
let ciphertext = hex::decode("0bd18749612f4c8b9dd583c7d6a646b90abd34e3c731a7708d0caf9039095641e1f0948e775f0b7351788db7f246d51806954626dcccb6a60d64665ca3715c6bef75616cab476d27bba04080361200d6a58cec").unwrap();
let decrypted = dh_decrypt(secret, &ciphertext).unwrap();
let decrypted_str = String::from_utf8(decrypted).unwrap();
assert_eq!(decrypted_str, "[{\"key\":\"\",\"value\":\"\"}]");
}
#[test]
fn test_stream_roundtrip() {
let secret = StaticSecret::random_from_rng(rand::thread_rng());
let public_key = PublicKey::from(&secret).to_bytes();
let plaintext = vec![0x5a; 2500];
let mut encrypted = Vec::new();
dh_encrypt_stream(public_key, plaintext.as_slice(), &mut encrypted, 1024).unwrap();
assert_eq!(&encrypted[..STREAM_MAGIC.len()], STREAM_MAGIC);
let mut decrypted = Vec::new();
dh_decrypt_stream(
secret.to_bytes(),
&encrypted[STREAM_MAGIC.len()..],
&mut decrypted,
)
.unwrap();
assert_eq!(decrypted, plaintext);
}
#[test]
fn test_stream_rejects_tampering_and_truncation() {
let secret = StaticSecret::random_from_rng(rand::thread_rng());
let public_key = PublicKey::from(&secret).to_bytes();
let mut encrypted = Vec::new();
dh_encrypt_stream(public_key, b"hello".as_slice(), &mut encrypted, 4).unwrap();
let mut unknown_version = encrypted.clone();
unknown_version[STREAM_MAGIC.len()] = STREAM_VERSION + 1;
assert!(dh_decrypt_stream(
secret.to_bytes(),
&unknown_version[STREAM_MAGIC.len()..],
Vec::new(),
)
.is_err());
let mut tampered = encrypted.clone();
*tampered.last_mut().unwrap() ^= 1;
assert!(dh_decrypt_stream(
secret.to_bytes(),
&tampered[STREAM_MAGIC.len()..],
Vec::new(),
)
.is_err());
encrypted.truncate(encrypted.len() - 1);
assert!(dh_decrypt_stream(
secret.to_bytes(),
&encrypted[STREAM_MAGIC.len()..],
Vec::new(),
)
.is_err());
}
}