1use std::fmt;
2
3use ring::aead;
4use ring::digest::Digest;
5
6use crate::tls::rustls::cipher::{MessageDecrypter, MessageEncrypter};
7use crate::tls::rustls::conn::ConnectionRandoms;
8use crate::tls::rustls::kx;
9use crate::tls::rustls::msgs::enums::{CipherSuite, SignatureScheme};
10use crate::tls::rustls::msgs::handshake::KeyExchangeAlgorithm;
11use crate::tls::rustls::suites::{BulkAlgorithm, CipherSuiteCommon, SupportedCipherSuite};
12
13mod cipher;
14pub use cipher::{AesGcm, ChaCha20Poly1305, Tls12AeadAlgorithm};
15use puffin::codec::Codec;
16
17use crate::tls::rustls::conn::Side;
18use crate::tls::rustls::error::Error;
19
20pub mod prf;
21
22pub static TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: SupportedCipherSuite =
24 SupportedCipherSuite::Tls12(&Tls12CipherSuite {
25 common: CipherSuiteCommon {
26 suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
27 bulk: BulkAlgorithm::Chacha20Poly1305,
28 aead_algorithm: &ring::aead::CHACHA20_POLY1305,
29 },
30 kx: KeyExchangeAlgorithm::ECDHE,
31 sign: TLS12_ECDSA_SCHEMES,
32 fixed_iv_len: 12,
33 explicit_nonce_len: 0,
34 aead_alg: &ChaCha20Poly1305,
35 hmac_algorithm: ring::hmac::HMAC_SHA256,
36 });
37
38pub static TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: SupportedCipherSuite =
40 SupportedCipherSuite::Tls12(&Tls12CipherSuite {
41 common: CipherSuiteCommon {
42 suite: CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
43 bulk: BulkAlgorithm::Chacha20Poly1305,
44 aead_algorithm: &ring::aead::CHACHA20_POLY1305,
45 },
46 kx: KeyExchangeAlgorithm::ECDHE,
47 sign: TLS12_RSA_SCHEMES,
48 fixed_iv_len: 12,
49 explicit_nonce_len: 0,
50 aead_alg: &ChaCha20Poly1305,
51 hmac_algorithm: ring::hmac::HMAC_SHA256,
52 });
53
54pub static TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: SupportedCipherSuite =
56 SupportedCipherSuite::Tls12(&Tls12CipherSuite {
57 common: CipherSuiteCommon {
58 suite: CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
59 bulk: BulkAlgorithm::Aes128Gcm,
60 aead_algorithm: &ring::aead::AES_128_GCM,
61 },
62 kx: KeyExchangeAlgorithm::ECDHE,
63 sign: TLS12_RSA_SCHEMES,
64 fixed_iv_len: 4,
65 explicit_nonce_len: 8,
66 aead_alg: &AesGcm,
67 hmac_algorithm: ring::hmac::HMAC_SHA256,
68 });
69
70pub static TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: SupportedCipherSuite =
72 SupportedCipherSuite::Tls12(&Tls12CipherSuite {
73 common: CipherSuiteCommon {
74 suite: CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
75 bulk: BulkAlgorithm::Aes256Gcm,
76 aead_algorithm: &ring::aead::AES_256_GCM,
77 },
78 kx: KeyExchangeAlgorithm::ECDHE,
79 sign: TLS12_RSA_SCHEMES,
80 fixed_iv_len: 4,
81 explicit_nonce_len: 8,
82 aead_alg: &AesGcm,
83 hmac_algorithm: ring::hmac::HMAC_SHA384,
84 });
85
86pub static TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: SupportedCipherSuite =
88 SupportedCipherSuite::Tls12(&Tls12CipherSuite {
89 common: CipherSuiteCommon {
90 suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
91 bulk: BulkAlgorithm::Aes128Gcm,
92 aead_algorithm: &ring::aead::AES_128_GCM,
93 },
94 kx: KeyExchangeAlgorithm::ECDHE,
95 sign: TLS12_ECDSA_SCHEMES,
96 fixed_iv_len: 4,
97 explicit_nonce_len: 8,
98 aead_alg: &AesGcm,
99 hmac_algorithm: ring::hmac::HMAC_SHA256,
100 });
101
102pub static TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: SupportedCipherSuite =
104 SupportedCipherSuite::Tls12(&Tls12CipherSuite {
105 common: CipherSuiteCommon {
106 suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
107 bulk: BulkAlgorithm::Aes256Gcm,
108 aead_algorithm: &ring::aead::AES_256_GCM,
109 },
110 kx: KeyExchangeAlgorithm::ECDHE,
111 sign: TLS12_ECDSA_SCHEMES,
112 fixed_iv_len: 4,
113 explicit_nonce_len: 8,
114 aead_alg: &AesGcm,
115 hmac_algorithm: ring::hmac::HMAC_SHA384,
116 });
117
118static TLS12_ECDSA_SCHEMES: &[SignatureScheme] = &[
119 SignatureScheme::ED25519,
120 SignatureScheme::ECDSA_NISTP521_SHA512,
121 SignatureScheme::ECDSA_NISTP384_SHA384,
122 SignatureScheme::ECDSA_NISTP256_SHA256,
123];
124
125static TLS12_RSA_SCHEMES: &[SignatureScheme] = &[
126 SignatureScheme::RSA_PSS_SHA512,
127 SignatureScheme::RSA_PSS_SHA384,
128 SignatureScheme::RSA_PSS_SHA256,
129 SignatureScheme::RSA_PKCS1_SHA512,
130 SignatureScheme::RSA_PKCS1_SHA384,
131 SignatureScheme::RSA_PKCS1_SHA256,
132];
133
134pub struct Tls12CipherSuite {
136 pub common: CipherSuiteCommon,
138 pub hmac_algorithm: ring::hmac::Algorithm,
139 pub kx: KeyExchangeAlgorithm,
141
142 pub sign: &'static [SignatureScheme],
144
145 pub fixed_iv_len: usize,
150
151 pub explicit_nonce_len: usize,
156
157 pub aead_alg: &'static dyn Tls12AeadAlgorithm,
158}
159
160impl Tls12CipherSuite {
161 pub fn resolve_sig_schemes(&self, offered: &[SignatureScheme]) -> Vec<SignatureScheme> {
165 self.sign
166 .iter()
167 .filter(|pref| offered.contains(pref))
168 .cloned()
169 .collect()
170 }
171
172 pub fn hash_algorithm(&self) -> &'static ring::digest::Algorithm {
174 self.hmac_algorithm.digest_algorithm()
175 }
176}
177
178impl From<&'static Tls12CipherSuite> for SupportedCipherSuite {
179 fn from(s: &'static Tls12CipherSuite) -> Self {
180 Self::Tls12(s)
181 }
182}
183
184impl PartialEq for Tls12CipherSuite {
185 fn eq(&self, other: &Self) -> bool {
186 self.common.suite == other.common.suite
187 }
188}
189
190impl fmt::Debug for Tls12CipherSuite {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192 f.debug_struct("Tls12CipherSuite")
193 .field("suite", &self.common.suite)
194 .field("bulk", &self.common.bulk)
195 .finish()
196 }
197}
198
199pub struct ConnectionSecrets {
201 pub randoms: ConnectionRandoms,
202 suite: &'static Tls12CipherSuite,
203 pub master_secret: [u8; 48],
204}
205
206impl ConnectionSecrets {
207 pub fn from_key_exchange(
208 kx: kx::KeyExchange,
209 peer_pub_key: &[u8],
210 ems_seed: Option<Digest>,
211 randoms: ConnectionRandoms,
212 suite: &'static Tls12CipherSuite,
213 ) -> Result<Self, Error> {
214 let mut ret = Self {
215 randoms,
216 suite,
217 master_secret: [0u8; 48],
218 };
219
220 let (label, seed) = match ems_seed {
221 Some(seed) => ("extended master secret", Seed::Ems(seed)),
222 None => (
223 "master secret",
224 Seed::Randoms(join_randoms(&ret.randoms.client, &ret.randoms.server)),
225 ),
226 };
227
228 kx.complete(peer_pub_key, |secret| {
229 prf::prf(
230 &mut ret.master_secret,
231 suite.hmac_algorithm,
232 secret,
233 label.as_bytes(),
234 seed.as_ref(),
235 );
236 Ok(())
237 })?;
238
239 Ok(ret)
240 }
241
242 pub fn new_resume(
243 randoms: ConnectionRandoms,
244 suite: &'static Tls12CipherSuite,
245 master_secret: &[u8],
246 ) -> Self {
247 let mut ret = Self {
248 randoms,
249 suite,
250 master_secret: [0u8; 48],
251 };
252 ret.master_secret.copy_from_slice(master_secret);
253 ret
254 }
255
256 pub fn make_cipher_pair(&self, side: Side) -> MessageCipherPair {
259 fn split_key<'a>(
260 key_block: &'a [u8],
261 alg: &'static aead::Algorithm,
262 ) -> (aead::LessSafeKey, &'a [u8]) {
263 let (key, rest) = key_block.split_at(alg.key_len());
265 let key = aead::UnboundKey::new(alg, key).unwrap();
268 (aead::LessSafeKey::new(key), rest)
269 }
270
271 let key_block = self.make_key_block();
274
275 let suite = self.suite;
276 let scs = &suite.common;
277
278 let (client_write_key, key_block) = split_key(&key_block, scs.aead_algorithm);
279 let (server_write_key, key_block) = split_key(key_block, scs.aead_algorithm);
280 let (client_write_iv, key_block) = key_block.split_at(suite.fixed_iv_len);
281 let (server_write_iv, extra) = key_block.split_at(suite.fixed_iv_len);
282
283 let (write_key, write_iv, read_key, read_iv) = match side {
284 Side::Client => (
285 client_write_key,
286 client_write_iv,
287 server_write_key,
288 server_write_iv,
289 ),
290 Side::Server => (
291 server_write_key,
292 server_write_iv,
293 client_write_key,
294 client_write_iv,
295 ),
296 };
297
298 (
299 suite.aead_alg.decrypter(read_key, read_iv),
300 suite.aead_alg.encrypter(write_key, write_iv, extra),
301 )
302 }
303
304 fn make_key_block(&self) -> Vec<u8> {
305 let suite = &self.suite;
306 let common = &self.suite.common;
307
308 let len =
309 (common.aead_algorithm.key_len() + suite.fixed_iv_len) * 2 + suite.explicit_nonce_len;
310
311 let mut out = vec![0; len];
312
313 let randoms = join_randoms(&self.randoms.server, &self.randoms.client);
316 prf::prf(
317 &mut out,
318 self.suite.hmac_algorithm,
319 &self.master_secret,
320 b"key expansion",
321 &randoms,
322 );
323
324 out
325 }
326
327 pub fn suite(&self) -> &'static Tls12CipherSuite {
328 self.suite
329 }
330
331 pub fn get_master_secret(&self) -> Vec<u8> {
332 let mut ret = Vec::new();
333 ret.extend_from_slice(&self.master_secret);
334 ret
335 }
336
337 fn make_verify_data(&self, handshake_hash: &Digest, label: &[u8]) -> Vec<u8> {
338 let mut out = vec![0; 12];
339
340 prf::prf(
341 &mut out,
342 self.suite.hmac_algorithm,
343 &self.master_secret,
344 label,
345 handshake_hash.as_ref(),
346 );
347 out
348 }
349
350 pub fn client_verify_data(&self, handshake_hash: &Digest) -> Vec<u8> {
351 self.make_verify_data(handshake_hash, b"client finished")
352 }
353
354 pub fn server_verify_data(&self, handshake_hash: &Digest) -> Vec<u8> {
355 self.make_verify_data(handshake_hash, b"server finished")
356 }
357
358 pub fn export_keying_material(&self, output: &mut [u8], label: &[u8], context: Option<&[u8]>) {
359 let mut randoms = Vec::new();
360 randoms.extend_from_slice(&self.randoms.client);
361 randoms.extend_from_slice(&self.randoms.server);
362 if let Some(context) = context {
363 assert!(context.len() <= 0xffff);
364 (context.len() as u16).encode(&mut randoms);
365 randoms.extend_from_slice(context);
366 }
367
368 prf::prf(
369 output,
370 self.suite.hmac_algorithm,
371 &self.master_secret,
372 label,
373 &randoms,
374 )
375 }
376}
377
378enum Seed {
379 Ems(Digest),
380 Randoms([u8; 64]),
381}
382
383impl AsRef<[u8]> for Seed {
384 fn as_ref(&self) -> &[u8] {
385 match self {
386 Seed::Ems(seed) => seed.as_ref(),
387 Seed::Randoms(randoms) => randoms.as_ref(),
388 }
389 }
390}
391
392fn join_randoms(first: &[u8; 32], second: &[u8; 32]) -> [u8; 64] {
393 let mut randoms = [0u8; 64];
394 randoms[..32].copy_from_slice(first);
395 randoms[32..].copy_from_slice(second);
396 randoms
397}
398
399type MessageCipherPair = (Box<dyn MessageDecrypter>, Box<dyn MessageEncrypter>);
400
401pub const DOWNGRADE_SENTINEL: [u8; 8] = [0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44, 0x01];
402
403#[cfg(test)]
404mod tests {
405 use puffin::codec::Reader;
406
407 use super::*;
408 use crate::tls::rustls::msgs::handshake::{ClientECDHParams, ServerECDHParams};
409
410 fn decode_ecdh_params_<T: Codec>(kx_params: &[u8]) -> Option<T> {
411 let mut rd = Reader::init(kx_params);
412 let ecdh_params = T::read(&mut rd)?;
413 match rd.any_left() {
414 false => Some(ecdh_params),
415 true => None,
416 }
417 }
418
419 #[test_log::test]
420 fn server_ecdhe_remaining_bytes() {
421 let key = kx::KeyExchange::start(&kx::X25519).unwrap();
422 let server_params = ServerECDHParams::new(key.group(), key.pubkey.as_ref());
423 let mut server_buf = Vec::new();
424 server_params.encode(&mut server_buf);
425 server_buf.push(34);
426 assert!(decode_ecdh_params_::<ServerECDHParams>(&server_buf).is_none());
427 }
428
429 #[test_log::test]
430 fn client_ecdhe_invalid() {
431 assert!(decode_ecdh_params_::<ClientECDHParams>(&[34]).is_none());
432 }
433}