1use crate::cipher::{MessageDecrypter, MessageEncrypter};
2use crate::common_state::{CommonState, Side};
3use crate::conn::ConnectionRandoms;
4use crate::enums::{AlertDescription, CipherSuite, SignatureScheme};
5use crate::error::{Error, InvalidMessage};
6use crate::kx;
7use crate::msgs::codec::{Codec, Reader};
8use crate::msgs::handshake::KeyExchangeAlgorithm;
9use crate::suites::{BulkAlgorithm, CipherSuiteCommon, SupportedCipherSuite};
10#[cfg(feature = "secret_extraction")]
11use crate::suites::{ConnectionTrafficSecrets, PartiallyExtractedSecrets};
12
13use ring::aead;
14use ring::digest::Digest;
15
16use std::fmt;
17
18mod cipher;
19pub(crate) use cipher::{AesGcm, ChaCha20Poly1305, Tls12AeadAlgorithm};
20
21mod prf;
22
23pub static TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: SupportedCipherSuite =
25 SupportedCipherSuite::Tls12(&Tls12CipherSuite {
26 common: CipherSuiteCommon {
27 suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
28 bulk: BulkAlgorithm::Chacha20Poly1305,
29 aead_algorithm: &aead::CHACHA20_POLY1305,
30 },
31 kx: KeyExchangeAlgorithm::ECDHE,
32 sign: TLS12_ECDSA_SCHEMES,
33 fixed_iv_len: 12,
34 explicit_nonce_len: 0,
35 aead_alg: &ChaCha20Poly1305,
36 hmac_algorithm: ring::hmac::HMAC_SHA256,
37 });
38
39pub static TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: SupportedCipherSuite =
41 SupportedCipherSuite::Tls12(&Tls12CipherSuite {
42 common: CipherSuiteCommon {
43 suite: CipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
44 bulk: BulkAlgorithm::Chacha20Poly1305,
45 aead_algorithm: &aead::CHACHA20_POLY1305,
46 },
47 kx: KeyExchangeAlgorithm::ECDHE,
48 sign: TLS12_RSA_SCHEMES,
49 fixed_iv_len: 12,
50 explicit_nonce_len: 0,
51 aead_alg: &ChaCha20Poly1305,
52 hmac_algorithm: ring::hmac::HMAC_SHA256,
53 });
54
55pub static TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: SupportedCipherSuite =
57 SupportedCipherSuite::Tls12(&Tls12CipherSuite {
58 common: CipherSuiteCommon {
59 suite: CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
60 bulk: BulkAlgorithm::Aes128Gcm,
61 aead_algorithm: &aead::AES_128_GCM,
62 },
63 kx: KeyExchangeAlgorithm::ECDHE,
64 sign: TLS12_RSA_SCHEMES,
65 fixed_iv_len: 4,
66 explicit_nonce_len: 8,
67 aead_alg: &AesGcm,
68 hmac_algorithm: ring::hmac::HMAC_SHA256,
69 });
70
71pub static TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: SupportedCipherSuite =
73 SupportedCipherSuite::Tls12(&Tls12CipherSuite {
74 common: CipherSuiteCommon {
75 suite: CipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
76 bulk: BulkAlgorithm::Aes256Gcm,
77 aead_algorithm: &aead::AES_256_GCM,
78 },
79 kx: KeyExchangeAlgorithm::ECDHE,
80 sign: TLS12_RSA_SCHEMES,
81 fixed_iv_len: 4,
82 explicit_nonce_len: 8,
83 aead_alg: &AesGcm,
84 hmac_algorithm: ring::hmac::HMAC_SHA384,
85 });
86
87pub static TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: SupportedCipherSuite =
89 SupportedCipherSuite::Tls12(&Tls12CipherSuite {
90 common: CipherSuiteCommon {
91 suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
92 bulk: BulkAlgorithm::Aes128Gcm,
93 aead_algorithm: &aead::AES_128_GCM,
94 },
95 kx: KeyExchangeAlgorithm::ECDHE,
96 sign: TLS12_ECDSA_SCHEMES,
97 fixed_iv_len: 4,
98 explicit_nonce_len: 8,
99 aead_alg: &AesGcm,
100 hmac_algorithm: ring::hmac::HMAC_SHA256,
101 });
102
103pub static TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: SupportedCipherSuite =
105 SupportedCipherSuite::Tls12(&Tls12CipherSuite {
106 common: CipherSuiteCommon {
107 suite: CipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
108 bulk: BulkAlgorithm::Aes256Gcm,
109 aead_algorithm: &aead::AES_256_GCM,
110 },
111 kx: KeyExchangeAlgorithm::ECDHE,
112 sign: TLS12_ECDSA_SCHEMES,
113 fixed_iv_len: 4,
114 explicit_nonce_len: 8,
115 aead_alg: &AesGcm,
116 hmac_algorithm: ring::hmac::HMAC_SHA384,
117 });
118
119static TLS12_ECDSA_SCHEMES: &[SignatureScheme] = &[
120 SignatureScheme::ED25519,
121 SignatureScheme::ECDSA_NISTP521_SHA512,
122 SignatureScheme::ECDSA_NISTP384_SHA384,
123 SignatureScheme::ECDSA_NISTP256_SHA256,
124];
125
126static TLS12_RSA_SCHEMES: &[SignatureScheme] = &[
127 SignatureScheme::RSA_PSS_SHA512,
128 SignatureScheme::RSA_PSS_SHA384,
129 SignatureScheme::RSA_PSS_SHA256,
130 SignatureScheme::RSA_PKCS1_SHA512,
131 SignatureScheme::RSA_PKCS1_SHA384,
132 SignatureScheme::RSA_PKCS1_SHA256,
133];
134
135pub struct Tls12CipherSuite {
137 pub common: CipherSuiteCommon,
139 pub(crate) hmac_algorithm: ring::hmac::Algorithm,
140 pub kx: KeyExchangeAlgorithm,
142
143 pub sign: &'static [SignatureScheme],
145
146 pub fixed_iv_len: usize,
151
152 pub explicit_nonce_len: usize,
157
158 pub(crate) aead_alg: &'static dyn Tls12AeadAlgorithm,
159}
160
161impl Tls12CipherSuite {
162 pub fn resolve_sig_schemes(&self, offered: &[SignatureScheme]) -> Vec<SignatureScheme> {
166 self.sign
167 .iter()
168 .filter(|pref| offered.contains(pref))
169 .cloned()
170 .collect()
171 }
172
173 pub(crate) fn hash_algorithm(&self) -> &'static ring::digest::Algorithm {
175 self.hmac_algorithm.digest_algorithm()
176 }
177}
178
179impl From<&'static Tls12CipherSuite> for SupportedCipherSuite {
180 fn from(s: &'static Tls12CipherSuite) -> Self {
181 Self::Tls12(s)
182 }
183}
184
185impl PartialEq for Tls12CipherSuite {
186 fn eq(&self, other: &Self) -> bool {
187 self.common.suite == other.common.suite
188 }
189}
190
191impl fmt::Debug for Tls12CipherSuite {
192 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193 f.debug_struct("Tls12CipherSuite")
194 .field("suite", &self.common.suite)
195 .field("bulk", &self.common.bulk)
196 .finish()
197 }
198}
199
200pub(crate) struct ConnectionSecrets {
202 pub(crate) randoms: ConnectionRandoms,
203 suite: &'static Tls12CipherSuite,
204 pub(crate) master_secret: [u8; 48],
205}
206
207impl ConnectionSecrets {
208 pub(crate) fn from_key_exchange(
209 kx: kx::KeyExchange,
210 peer_pub_key: &[u8],
211 ems_seed: Option<Digest>,
212 randoms: ConnectionRandoms,
213 suite: &'static Tls12CipherSuite,
214 ) -> Result<Self, Error> {
215 let mut ret = Self {
216 randoms,
217 suite,
218 master_secret: [0u8; 48],
219 };
220
221 let (label, seed) = match ems_seed {
222 Some(seed) => ("extended master secret", Seed::Ems(seed)),
223 None => (
224 "master secret",
225 Seed::Randoms(join_randoms(&ret.randoms.client, &ret.randoms.server)),
226 ),
227 };
228
229 kx.complete(peer_pub_key, |secret| {
230 prf::prf(
231 &mut ret.master_secret,
232 suite.hmac_algorithm,
233 secret,
234 label.as_bytes(),
235 seed.as_ref(),
236 );
237 })?;
238
239 Ok(ret)
240 }
241
242 pub(crate) 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
253 .copy_from_slice(master_secret);
254 ret
255 }
256
257 pub(crate) fn make_cipher_pair(&self, side: Side) -> MessageCipherPair {
260 fn split_key<'a>(
261 key_block: &'a [u8],
262 alg: &'static aead::Algorithm,
263 ) -> (aead::LessSafeKey, &'a [u8]) {
264 let (key, rest) = key_block.split_at(alg.key_len());
266 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
300 .aead_alg
301 .decrypter(read_key, read_iv),
302 suite
303 .aead_alg
304 .encrypter(write_key, write_iv, extra),
305 )
306 }
307
308 fn make_key_block(&self) -> Vec<u8> {
309 let suite = &self.suite;
310 let common = &self.suite.common;
311
312 let len =
313 (common.aead_algorithm.key_len() + suite.fixed_iv_len) * 2 + suite.explicit_nonce_len;
314
315 let mut out = vec![0u8; len];
316
317 let randoms = join_randoms(&self.randoms.server, &self.randoms.client);
320 prf::prf(
321 &mut out,
322 self.suite.hmac_algorithm,
323 &self.master_secret,
324 b"key expansion",
325 &randoms,
326 );
327
328 out
329 }
330
331 pub(crate) fn suite(&self) -> &'static Tls12CipherSuite {
332 self.suite
333 }
334
335 pub(crate) fn get_master_secret(&self) -> Vec<u8> {
336 let mut ret = Vec::new();
337 ret.extend_from_slice(&self.master_secret);
338 ret
339 }
340
341 fn make_verify_data(&self, handshake_hash: &Digest, label: &[u8]) -> Vec<u8> {
342 let mut out = vec![0u8; 12];
343
344 prf::prf(
345 &mut out,
346 self.suite.hmac_algorithm,
347 &self.master_secret,
348 label,
349 handshake_hash.as_ref(),
350 );
351 out
352 }
353
354 pub(crate) fn client_verify_data(&self, handshake_hash: &Digest) -> Vec<u8> {
355 self.make_verify_data(handshake_hash, b"client finished")
356 }
357
358 pub(crate) fn server_verify_data(&self, handshake_hash: &Digest) -> Vec<u8> {
359 self.make_verify_data(handshake_hash, b"server finished")
360 }
361
362 pub(crate) fn export_keying_material(
363 &self,
364 output: &mut [u8],
365 label: &[u8],
366 context: Option<&[u8]>,
367 ) {
368 let mut randoms = Vec::new();
369 randoms.extend_from_slice(&self.randoms.client);
370 randoms.extend_from_slice(&self.randoms.server);
371 if let Some(context) = context {
372 assert!(context.len() <= 0xffff);
373 (context.len() as u16).encode(&mut randoms);
374 randoms.extend_from_slice(context);
375 }
376
377 prf::prf(
378 output,
379 self.suite.hmac_algorithm,
380 &self.master_secret,
381 label,
382 &randoms,
383 );
384 }
385
386 #[cfg(feature = "secret_extraction")]
387 pub(crate) fn extract_secrets(&self, side: Side) -> Result<PartiallyExtractedSecrets, Error> {
388 let key_block = self.make_key_block();
390
391 let suite = self.suite;
392 let algo = suite.common.aead_algorithm;
393
394 let (client_key, key_block) = key_block.split_at(algo.key_len());
395 let (server_key, key_block) = key_block.split_at(algo.key_len());
396 let (client_iv, key_block) = key_block.split_at(suite.fixed_iv_len);
397 let (server_iv, extra) = key_block.split_at(suite.fixed_iv_len);
398
399 struct Pair<'a> {
401 key: &'a [u8],
402 iv: &'a [u8],
403 }
404
405 let client_pair = Pair {
406 key: client_key,
407 iv: client_iv,
408 };
409 let server_pair = Pair {
410 key: server_key,
411 iv: server_iv,
412 };
413
414 let (client_secrets, server_secrets) = if algo == &aead::AES_128_GCM {
415 let extract = |pair: Pair| -> ConnectionTrafficSecrets {
416 let mut key = [0u8; 16];
417 key.copy_from_slice(pair.key);
418
419 let mut salt = [0u8; 4];
420 salt.copy_from_slice(pair.iv);
421
422 let mut iv = [0u8; 8];
423 iv.copy_from_slice(&extra[..8]);
424
425 ConnectionTrafficSecrets::Aes128Gcm { key, salt, iv }
426 };
427
428 (extract(client_pair), extract(server_pair))
429 } else if algo == &aead::AES_256_GCM {
430 let extract = |pair: Pair| -> ConnectionTrafficSecrets {
431 let mut key = [0u8; 32];
432 key.copy_from_slice(pair.key);
433
434 let mut salt = [0u8; 4];
435 salt.copy_from_slice(pair.iv);
436
437 let mut iv = [0u8; 8];
438 iv.copy_from_slice(&extra[..8]);
439
440 ConnectionTrafficSecrets::Aes256Gcm { key, salt, iv }
441 };
442
443 (extract(client_pair), extract(server_pair))
444 } else if algo == &aead::CHACHA20_POLY1305 {
445 let extract = |pair: Pair| -> ConnectionTrafficSecrets {
446 let mut key = [0u8; 32];
447 key.copy_from_slice(pair.key);
448
449 let mut iv = [0u8; 12];
450 iv.copy_from_slice(pair.iv);
451
452 ConnectionTrafficSecrets::Chacha20Poly1305 { key, iv }
453 };
454
455 (extract(client_pair), extract(server_pair))
456 } else {
457 return Err(Error::General(format!(
458 "exporting secrets for {:?}: unimplemented",
459 algo
460 )));
461 };
462
463 let (tx, rx) = match side {
464 Side::Client => (client_secrets, server_secrets),
465 Side::Server => (server_secrets, client_secrets),
466 };
467 Ok(PartiallyExtractedSecrets { tx, rx })
468 }
469}
470
471enum Seed {
472 Ems(Digest),
473 Randoms([u8; 64]),
474}
475
476impl AsRef<[u8]> for Seed {
477 fn as_ref(&self) -> &[u8] {
478 match self {
479 Self::Ems(seed) => seed.as_ref(),
480 Self::Randoms(randoms) => randoms.as_ref(),
481 }
482 }
483}
484
485fn join_randoms(first: &[u8; 32], second: &[u8; 32]) -> [u8; 64] {
486 let mut randoms = [0u8; 64];
487 randoms[..32].copy_from_slice(first);
488 randoms[32..].copy_from_slice(second);
489 randoms
490}
491
492type MessageCipherPair = (Box<dyn MessageDecrypter>, Box<dyn MessageEncrypter>);
493
494pub(crate) fn decode_ecdh_params<T: Codec>(
495 common: &mut CommonState,
496 kx_params: &[u8],
497) -> Result<T, Error> {
498 let mut rd = Reader::init(kx_params);
499 let ecdh_params = T::read(&mut rd)?;
500 match rd.any_left() {
501 false => Ok(ecdh_params),
502 true => Err(common.send_fatal_alert(
503 AlertDescription::DecodeError,
504 InvalidMessage::InvalidDhParams,
505 )),
506 }
507}
508
509pub(crate) const DOWNGRADE_SENTINEL: [u8; 8] = [0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44, 0x01];
510
511#[cfg(test)]
512mod tests {
513 use super::*;
514 use crate::msgs::handshake::{ClientECDHParams, ServerECDHParams};
515
516 #[test]
517 fn server_ecdhe_remaining_bytes() {
518 let key = kx::KeyExchange::start(&kx::X25519).unwrap();
519 let server_params = ServerECDHParams::new(key.group(), key.pubkey.as_ref());
520 let mut server_buf = Vec::new();
521 server_params.encode(&mut server_buf);
522 server_buf.push(34);
523
524 let mut common = CommonState::new(Side::Client);
525 assert!(decode_ecdh_params::<ServerECDHParams>(&mut common, &server_buf).is_err());
526 }
527
528 #[test]
529 fn client_ecdhe_invalid() {
530 let mut common = CommonState::new(Side::Server);
531 assert!(decode_ecdh_params::<ClientECDHParams>(&mut common, &[34]).is_err());
532 }
533}