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
use crate::bastion::Error;
use uuid::Uuid;
use x25519_dalek::EphemeralSecret;
use zeroize::{Zeroize, Zeroizing};
pub use x25519_dalek::PublicKey;
#[derive(Zeroize)]
#[zeroize(drop)]
pub struct SharedSecret([u8; 32]);
impl SharedSecret {
pub fn from_slice_mut(bytes: &mut [u8]) -> Result<Self, Error> {
use core::convert::TryFrom;
let array =
<[u8; 32]>::try_from(&*bytes).map_err(|_| Error::InvalidSize { got: bytes.len() })?;
bytes.zeroize();
Ok(Self(array))
}
pub fn from_bytes(bytes: [u8; 32]) -> Self {
Self(bytes)
}
pub fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
}
impl From<[u8; 32]> for SharedSecret {
fn from(bytes: [u8; 32]) -> Self {
Self::from_bytes(bytes)
}
}
pub struct KeyExchange {
pub public_key: PublicKey,
secret: EphemeralSecret,
}
impl KeyExchange {
pub fn init() -> Self {
use rand_core::OsRng;
let secret = EphemeralSecret::new(OsRng);
Self {
public_key: PublicKey::from(&secret),
secret,
}
}
pub fn into_shared_secret(self, peer_public_key: &PublicKey) -> SharedSecret {
let shared = self.secret.diffie_hellman(peer_public_key);
SharedSecret(shared.to_bytes())
}
}
pub fn encrypt_key(
shared_key: &SharedSecret,
csc_uuid: Uuid,
symmetric_key_to_share: &[u8],
) -> Result<String, Error> {
use chacha20poly1305::aead::{AeadInPlace, NewAead};
use chacha20poly1305::{Key, XChaCha20Poly1305, XNonce};
use rand::rngs::OsRng;
use rand::Fill;
let aad_start = 0;
let nonce_start = aad_start + AAD_SIZE;
let data_start = nonce_start + NONCE_SIZE;
let tag_start = data_start + symmetric_key_to_share.len();
let total_len = tag_start + TAG_SIZE;
let mut buffer = Zeroizing::new(vec![0u8; total_len]);
let (aad, rest) = buffer.split_at_mut(AAD_SIZE);
aad.copy_from_slice(csc_uuid.as_bytes());
let (nonce, rest) = rest.split_at_mut(NONCE_SIZE);
nonce.try_fill(&mut OsRng)?;
let nonce = XNonce::from_slice(nonce);
let (data, rest) = rest.split_at_mut(rest.len() - TAG_SIZE);
data.copy_from_slice(symmetric_key_to_share);
let key = Key::from_slice(&shared_key.0);
let aead = XChaCha20Poly1305::new(key);
let tag = aead
.encrypt_in_place_detached(&nonce, aad, data)
.map_err(|_| Error::XChaCha20)?;
rest.copy_from_slice(&tag);
Ok(base64::encode_config(&*buffer, base64::STANDARD))
}
pub fn decrypt_key(
shared_key: &SharedSecret,
encrypted_symmetric_key: &str,
) -> Result<(Uuid, Vec<u8>), Error> {
use chacha20poly1305::aead::{AeadInPlace, NewAead, Tag};
use chacha20poly1305::{Key, XChaCha20Poly1305, XNonce};
const MIN_SIZE: usize = AAD_SIZE + NONCE_SIZE + 1 + TAG_SIZE;
let mut buffer = Zeroizing::new(base64::decode_config(
encrypted_symmetric_key,
base64::STANDARD,
)?);
if buffer.len() < MIN_SIZE {
return Err(Error::InvalidSize { got: buffer.len() });
}
let (aad, rest) = buffer.as_mut_slice().split_at_mut(AAD_SIZE);
let (nonce, rest) = rest.split_at_mut(NONCE_SIZE);
let (data, tag) = rest.split_at_mut(rest.len() - TAG_SIZE);
let nonce = XNonce::from_slice(nonce);
let tag = Tag::<<XChaCha20Poly1305 as AeadInPlace>::TagSize>::from_slice(tag);
let key = Key::from_slice(&shared_key.0);
let aead = XChaCha20Poly1305::new(key);
aead.decrypt_in_place_detached(nonce, aad, data, tag)
.map_err(|_| Error::XChaCha20)?;
let csc_id = Uuid::from_slice(&aad[..16]).expect("buffer contains enough bytes");
Ok((csc_id, data.to_vec()))
}
const AAD_SIZE: usize = 16;
const NONCE_SIZE: usize = 24;
const TAG_SIZE: usize = 16;
#[cfg(test)]
mod tests {
use super::*;
use either::Either;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::thread;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
type Msg = Either<PublicKey, String>;
const SOME_KEY: &[u8] = &[
189, 72, 50, 73, 241, 119, 140, 134, 238, 246, 196, 220, 22, 110, 240, 26, 66, 132, 74, 67,
250, 203, 21, 31, 138, 56, 229, 130, 252, 157, 13, 32,
];
const CSC_ID: Uuid = Uuid::from_u128(256);
fn client(tx: Sender<Msg>, rx: Receiver<Msg>) -> Result<()> {
let exchange = KeyExchange::init();
tx.send(Either::Left(exchange.public_key))?;
let server_public = rx.recv()?.left().unwrap();
let shared_secret = exchange.into_shared_secret(&server_public);
let encrypted_key = rx.recv()?.right().unwrap();
let (csc_id, decrypted_key) = decrypt_key(&shared_secret, &encrypted_key)?;
assert_eq!(decrypted_key, SOME_KEY);
assert_eq!(csc_id, CSC_ID);
Ok(())
}
fn server(tx: Sender<Msg>, rx: Receiver<Msg>) -> Result<()> {
let exchange = KeyExchange::init();
let client_public = rx.recv()?.left().unwrap();
tx.send(Either::Left(exchange.public_key))?;
let shared_secret = exchange.into_shared_secret(&client_public);
let encrypted_key = encrypt_key(&shared_secret, CSC_ID, SOME_KEY)?;
tx.send(Either::Right(encrypted_key))?;
Ok(())
}
#[test]
fn full_exchange() {
let (to_server, from_client) = channel();
let (to_client, from_server) = channel();
let client =
thread::spawn(move || client(to_server, from_server).map_err(|e| e.to_string()));
let server =
thread::spawn(move || server(to_client, from_client).map_err(|e| e.to_string()));
client.join().unwrap().unwrap();
server.join().unwrap().unwrap();
}
fn some_shared_secret() -> SharedSecret {
let exchange = KeyExchange::init();
let pubk = exchange.public_key.clone();
exchange.into_shared_secret(&pubk)
}
#[test]
fn invalid_size_err() {
let e = decrypt_key(&some_shared_secret(), "cGFzc3dvcmQ=")
.err()
.unwrap();
assert!(matches!(e, Error::InvalidSize { got: 8 }));
}
}