-
Notifications
You must be signed in to change notification settings - Fork 597
/
aead.rs
231 lines (194 loc) · 6.93 KB
/
aead.rs
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
use alloc::boxed::Box;
use chacha20poly1305::aead::Buffer;
use chacha20poly1305::{AeadInPlace, KeyInit, KeySizeUser};
use rustls::crypto::cipher::{
make_tls12_aad, make_tls13_aad, AeadKey, BorrowedPayload, InboundOpaqueMessage,
InboundPlainMessage, Iv, KeyBlockShape, MessageDecrypter, MessageEncrypter, Nonce,
OutboundOpaqueMessage, OutboundPlainMessage, PrefixedPayload, Tls12AeadAlgorithm,
Tls13AeadAlgorithm, UnsupportedOperationError, NONCE_LEN,
};
use rustls::{ConnectionTrafficSecrets, ContentType, ProtocolVersion};
pub struct Chacha20Poly1305;
impl Tls13AeadAlgorithm for Chacha20Poly1305 {
fn encrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageEncrypter> {
Box::new(Tls13Cipher(
chacha20poly1305::ChaCha20Poly1305::new_from_slice(key.as_ref()).unwrap(),
iv,
))
}
fn decrypter(&self, key: AeadKey, iv: Iv) -> Box<dyn MessageDecrypter> {
Box::new(Tls13Cipher(
chacha20poly1305::ChaCha20Poly1305::new_from_slice(key.as_ref()).unwrap(),
iv,
))
}
fn key_len(&self) -> usize {
chacha20poly1305::ChaCha20Poly1305::key_size()
}
fn extract_keys(
&self,
key: AeadKey,
iv: Iv,
) -> Result<ConnectionTrafficSecrets, UnsupportedOperationError> {
Ok(ConnectionTrafficSecrets::Chacha20Poly1305 { key, iv })
}
}
impl Tls12AeadAlgorithm for Chacha20Poly1305 {
fn encrypter(&self, key: AeadKey, iv: &[u8], _: &[u8]) -> Box<dyn MessageEncrypter> {
Box::new(Tls12Cipher(
chacha20poly1305::ChaCha20Poly1305::new_from_slice(key.as_ref()).unwrap(),
Iv::copy(iv),
))
}
fn decrypter(&self, key: AeadKey, iv: &[u8]) -> Box<dyn MessageDecrypter> {
Box::new(Tls12Cipher(
chacha20poly1305::ChaCha20Poly1305::new_from_slice(key.as_ref()).unwrap(),
Iv::copy(iv),
))
}
fn key_block_shape(&self) -> KeyBlockShape {
KeyBlockShape {
enc_key_len: 32,
fixed_iv_len: 12,
explicit_nonce_len: 0,
}
}
fn extract_keys(
&self,
key: AeadKey,
iv: &[u8],
_explicit: &[u8],
) -> Result<ConnectionTrafficSecrets, UnsupportedOperationError> {
// This should always be true because KeyBlockShape and the Iv nonce len are in agreement.
debug_assert_eq!(NONCE_LEN, iv.len());
Ok(ConnectionTrafficSecrets::Chacha20Poly1305 {
key,
iv: Iv::new(iv[..].try_into().unwrap()),
})
}
}
struct Tls13Cipher(chacha20poly1305::ChaCha20Poly1305, Iv);
impl MessageEncrypter for Tls13Cipher {
fn encrypt(
&mut self,
m: OutboundPlainMessage,
seq: u64,
) -> Result<OutboundOpaqueMessage, rustls::Error> {
let total_len = self.encrypted_payload_len(m.payload.len());
let mut payload = PrefixedPayload::with_capacity(total_len);
payload.extend_from_chunks(&m.payload);
payload.extend_from_slice(&m.typ.to_array());
let nonce = chacha20poly1305::Nonce::from(Nonce::new(&self.1, seq).0);
let aad = make_tls13_aad(total_len);
self.0
.encrypt_in_place(&nonce, &aad, &mut EncryptBufferAdapter(&mut payload))
.map_err(|_| rustls::Error::EncryptError)
.map(|_| {
OutboundOpaqueMessage::new(
ContentType::ApplicationData,
ProtocolVersion::TLSv1_2,
payload,
)
})
}
fn encrypted_payload_len(&self, payload_len: usize) -> usize {
payload_len + 1 + CHACHAPOLY1305_OVERHEAD
}
}
impl MessageDecrypter for Tls13Cipher {
fn decrypt<'a>(
&mut self,
mut m: InboundOpaqueMessage<'a>,
seq: u64,
) -> Result<InboundPlainMessage<'a>, rustls::Error> {
let payload = &mut m.payload;
let nonce = chacha20poly1305::Nonce::from(Nonce::new(&self.1, seq).0);
let aad = make_tls13_aad(payload.len());
self.0
.decrypt_in_place(&nonce, &aad, &mut DecryptBufferAdapter(payload))
.map_err(|_| rustls::Error::DecryptError)?;
m.into_tls13_unpadded_message()
}
}
struct Tls12Cipher(chacha20poly1305::ChaCha20Poly1305, Iv);
impl MessageEncrypter for Tls12Cipher {
fn encrypt(
&mut self,
m: OutboundPlainMessage,
seq: u64,
) -> Result<OutboundOpaqueMessage, rustls::Error> {
let total_len = self.encrypted_payload_len(m.payload.len());
let mut payload = PrefixedPayload::with_capacity(total_len);
payload.extend_from_chunks(&m.payload);
let nonce = chacha20poly1305::Nonce::from(Nonce::new(&self.1, seq).0);
let aad = make_tls12_aad(seq, m.typ, m.version, m.payload.len());
self.0
.encrypt_in_place(&nonce, &aad, &mut EncryptBufferAdapter(&mut payload))
.map_err(|_| rustls::Error::EncryptError)
.map(|_| OutboundOpaqueMessage::new(m.typ, m.version, payload))
}
fn encrypted_payload_len(&self, payload_len: usize) -> usize {
payload_len + CHACHAPOLY1305_OVERHEAD
}
}
impl MessageDecrypter for Tls12Cipher {
fn decrypt<'a>(
&mut self,
mut m: InboundOpaqueMessage<'a>,
seq: u64,
) -> Result<InboundPlainMessage<'a>, rustls::Error> {
let payload = &m.payload;
let nonce = chacha20poly1305::Nonce::from(Nonce::new(&self.1, seq).0);
let aad = make_tls12_aad(
seq,
m.typ,
m.version,
payload.len() - CHACHAPOLY1305_OVERHEAD,
);
let payload = &mut m.payload;
self.0
.decrypt_in_place(&nonce, &aad, &mut DecryptBufferAdapter(payload))
.map_err(|_| rustls::Error::DecryptError)?;
Ok(m.into_plain_message())
}
}
const CHACHAPOLY1305_OVERHEAD: usize = 16;
struct EncryptBufferAdapter<'a>(&'a mut PrefixedPayload);
impl AsRef<[u8]> for EncryptBufferAdapter<'_> {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl AsMut<[u8]> for EncryptBufferAdapter<'_> {
fn as_mut(&mut self) -> &mut [u8] {
self.0.as_mut()
}
}
impl Buffer for EncryptBufferAdapter<'_> {
fn extend_from_slice(&mut self, other: &[u8]) -> chacha20poly1305::aead::Result<()> {
self.0.extend_from_slice(other);
Ok(())
}
fn truncate(&mut self, len: usize) {
self.0.truncate(len)
}
}
struct DecryptBufferAdapter<'a, 'p>(&'a mut BorrowedPayload<'p>);
impl AsRef<[u8]> for DecryptBufferAdapter<'_, '_> {
fn as_ref(&self) -> &[u8] {
self.0
}
}
impl AsMut<[u8]> for DecryptBufferAdapter<'_, '_> {
fn as_mut(&mut self) -> &mut [u8] {
self.0
}
}
impl Buffer for DecryptBufferAdapter<'_, '_> {
fn extend_from_slice(&mut self, _: &[u8]) -> chacha20poly1305::aead::Result<()> {
unreachable!("not used by `AeadInPlace::decrypt_in_place`")
}
fn truncate(&mut self, len: usize) {
self.0.truncate(len)
}
}