1use alloc::{
2 boxed::Box,
3 format,
4 string::{String, ToString},
5 sync::Arc,
6 vec::Vec,
7};
8use core::{any::Any, str};
9use std::io;
10
11use aes_gcm::{KeyInit, aead::AeadMutInPlace};
12use bytes::BytesMut;
13pub use rustls::Error;
14use rustls::{
15 self, CipherSuite,
16 pki_types::{CertificateDer, ServerName},
17 quic::{Connection, HeaderProtectionKey, KeyChange, PacketKey, Secrets, Suite, Version},
18};
19#[cfg(any(feature = "aws-lc-rs", feature = "ring"))]
20use rustls::{client::danger::ServerCertVerifier, pki_types::PrivateKeyDer};
21
22use crate::{
23 ConnectError, ConnectionId, PathId, Side, TransportError, TransportErrorCode,
24 crypto::{
25 self, CryptoError, ExportKeyingMaterialError, HeaderKey, KeyPair, Keys, UnsupportedVersion,
26 },
27 transport_parameters::TransportParameters,
28};
29
30impl From<Side> for rustls::Side {
31 fn from(s: Side) -> Self {
32 match s {
33 Side::Client => Self::Client,
34 Side::Server => Self::Server,
35 }
36 }
37}
38
39pub struct TlsSession {
41 version: Version,
42 got_handshake_data: bool,
43 next_secrets: Option<Secrets>,
44 inner: Connection,
45 suite: Suite,
46}
47
48impl TlsSession {
49 fn side(&self) -> Side {
50 match self.inner {
51 Connection::Client(_) => Side::Client,
52 Connection::Server(_) => Side::Server,
53 }
54 }
55}
56
57impl crypto::Session for TlsSession {
58 fn initial_keys(&self, dst_cid: ConnectionId, side: Side) -> Keys {
59 initial_keys(self.version, dst_cid, side, &self.suite)
60 }
61
62 fn handshake_data(&self) -> Option<Box<dyn Any>> {
63 if !self.got_handshake_data {
64 return None;
65 }
66 Some(Box::new(HandshakeData {
67 protocol: self.inner.alpn_protocol().map(|x| x.into()),
68 server_name: match self.inner {
69 Connection::Client(_) => None,
70 Connection::Server(ref session) => session.server_name().map(|x| x.into()),
71 },
72 negotiated_key_exchange_group: self
73 .inner
74 .negotiated_key_exchange_group()
75 .map(|kx| kx.name()),
76 }))
77 }
78
79 fn peer_identity(&self) -> Option<Box<dyn Any>> {
81 self.inner.peer_certificates().map(|v| -> Box<dyn Any> {
82 Box::new(
83 v.iter()
84 .map(|v| v.clone().into_owned())
85 .collect::<Vec<CertificateDer<'static>>>(),
86 )
87 })
88 }
89
90 fn early_crypto(&self) -> Option<(Box<dyn HeaderKey>, Box<dyn crypto::PacketKey>)> {
91 let keys = self.inner.zero_rtt_keys()?;
92 Some((Box::new(keys.header), Box::new(keys.packet)))
93 }
94
95 fn early_data_accepted(&self) -> Option<bool> {
96 match self.inner {
97 Connection::Client(ref session) => Some(session.is_early_data_accepted()),
98 _ => None,
99 }
100 }
101
102 fn is_handshaking(&self) -> bool {
103 self.inner.is_handshaking()
104 }
105
106 fn read_handshake(&mut self, buf: &[u8]) -> Result<bool, TransportError> {
107 self.inner.read_hs(buf).map_err(|e| {
108 if let Some(alert) = self.inner.alert() {
109 TransportError {
110 code: TransportErrorCode::crypto(alert.into()),
111 frame: crate::frame::MaybeFrame::None,
112 reason: e.to_string(),
113 crypto: Some(Arc::new(e)),
114 }
115 } else {
116 TransportError::PROTOCOL_VIOLATION(format!("TLS error: {e}"))
117 }
118 })?;
119 if !self.got_handshake_data {
120 let have_server_name = match self.inner {
124 Connection::Client(_) => false,
125 Connection::Server(ref session) => session.server_name().is_some(),
126 };
127 if self.inner.alpn_protocol().is_some() || have_server_name || !self.is_handshaking() {
128 self.got_handshake_data = true;
129 return Ok(true);
130 }
131 }
132 Ok(false)
133 }
134
135 fn transport_parameters(&self) -> Result<Option<TransportParameters>, TransportError> {
136 match self.inner.quic_transport_parameters() {
137 None => Ok(None),
138 Some(buf) => match TransportParameters::read(self.side(), &mut io::Cursor::new(buf)) {
139 Ok(params) => Ok(Some(params)),
140 Err(e) => Err(e.into()),
141 },
142 }
143 }
144
145 fn write_handshake(&mut self, buf: &mut Vec<u8>) -> Option<Keys> {
146 let keys = match self.inner.write_hs(buf)? {
147 KeyChange::Handshake { keys } => keys,
148 KeyChange::OneRtt { keys, next } => {
149 self.next_secrets = Some(next);
150 keys
151 }
152 };
153
154 Some(Keys {
155 header: KeyPair {
156 local: Box::new(keys.local.header),
157 remote: Box::new(keys.remote.header),
158 },
159 packet: KeyPair {
160 local: Box::new(keys.local.packet),
161 remote: Box::new(keys.remote.packet),
162 },
163 })
164 }
165
166 fn next_1rtt_keys(&mut self) -> Option<KeyPair<Box<dyn crypto::PacketKey>>> {
167 let secrets = self.next_secrets.as_mut()?;
168 let keys = secrets.next_packet_keys();
169 Some(KeyPair {
170 local: Box::new(keys.local),
171 remote: Box::new(keys.remote),
172 })
173 }
174
175 fn is_valid_retry(&self, orig_dst_cid: ConnectionId, header: &[u8], payload: &[u8]) -> bool {
176 if payload.len() < 16 {
177 return false;
178 }
179
180 let mut pseudo_packet =
181 Vec::with_capacity(header.len() + payload.len() + orig_dst_cid.len() + 1);
182 pseudo_packet.push(orig_dst_cid.len() as u8);
183 pseudo_packet.extend_from_slice(&orig_dst_cid);
184 pseudo_packet.extend_from_slice(header);
185 pseudo_packet.extend_from_slice(payload);
186
187 let (nonce, key) = match self.version {
188 Version::V1 => (&RETRY_INTEGRITY_NONCE_V1, &RETRY_INTEGRITY_KEY_V1),
189 Version::V1Draft => (&RETRY_INTEGRITY_NONCE_DRAFT, &RETRY_INTEGRITY_KEY_DRAFT),
190 _ => unreachable!(),
191 };
192
193 let Some((aad, tag)) = pseudo_packet.split_last_chunk::<16>() else {
194 return false; };
196
197 let key = aes_gcm::Key::<aes_gcm::Aes128Gcm>::from_slice(key);
199 let nonce = aes_gcm::Nonce::from_slice(nonce);
200 let tag = aes_gcm::Tag::from_slice(tag);
201 aes_gcm::Aes128Gcm::new(key)
202 .decrypt_in_place_detached(nonce, aad, &mut [], tag)
203 .is_ok()
204 }
205
206 fn export_keying_material(
207 &self,
208 output: &mut [u8],
209 label: &[u8],
210 context: &[u8],
211 ) -> Result<(), ExportKeyingMaterialError> {
212 self.inner
213 .export_keying_material(output, label, Some(context))
214 .map_err(|_| ExportKeyingMaterialError)?;
215 Ok(())
216 }
217}
218
219const RETRY_INTEGRITY_KEY_DRAFT: [u8; 16] = [
220 0xcc, 0xce, 0x18, 0x7e, 0xd0, 0x9a, 0x09, 0xd0, 0x57, 0x28, 0x15, 0x5a, 0x6c, 0xb9, 0x6b, 0xe1,
221];
222const RETRY_INTEGRITY_NONCE_DRAFT: [u8; 12] = [
223 0xe5, 0x49, 0x30, 0xf9, 0x7f, 0x21, 0x36, 0xf0, 0x53, 0x0a, 0x8c, 0x1c,
224];
225
226const RETRY_INTEGRITY_KEY_V1: [u8; 16] = [
227 0xbe, 0x0c, 0x69, 0x0b, 0x9f, 0x66, 0x57, 0x5a, 0x1d, 0x76, 0x6b, 0x54, 0xe3, 0x68, 0xc8, 0x4e,
228];
229const RETRY_INTEGRITY_NONCE_V1: [u8; 12] = [
230 0x46, 0x15, 0x99, 0xd3, 0x5d, 0x63, 0x2b, 0xf2, 0x23, 0x98, 0x25, 0xbb,
231];
232
233impl HeaderKey for Box<dyn HeaderProtectionKey> {
234 fn decrypt(&self, pn_offset: usize, packet: &mut [u8]) {
235 let (header, sample) = packet.split_at_mut(pn_offset + 4);
236 let (first, rest) = header.split_at_mut(1);
237 let pn_end = Ord::min(pn_offset + 3, rest.len());
238 self.decrypt_in_place(
239 &sample[..self.sample_size()],
240 &mut first[0],
241 &mut rest[pn_offset - 1..pn_end],
242 )
243 .unwrap();
244 }
245
246 fn encrypt(&self, pn_offset: usize, packet: &mut [u8]) {
247 let (header, sample) = packet.split_at_mut(pn_offset + 4);
248 let (first, rest) = header.split_at_mut(1);
249 let pn_end = Ord::min(pn_offset + 3, rest.len());
250 self.encrypt_in_place(
251 &sample[..self.sample_size()],
252 &mut first[0],
253 &mut rest[pn_offset - 1..pn_end],
254 )
255 .unwrap();
256 }
257
258 fn sample_size(&self) -> usize {
259 self.sample_len()
260 }
261}
262
263#[non_exhaustive]
265pub struct HandshakeData {
266 pub protocol: Option<Vec<u8>>,
270 pub server_name: Option<String>,
274 pub negotiated_key_exchange_group: Option<rustls::NamedGroup>,
278}
279
280#[derive(Clone)] pub struct QuicClientConfig {
301 pub(crate) inner: Arc<rustls::ClientConfig>,
302 initial: Suite,
303}
304
305impl QuicClientConfig {
306 #[cfg(all(
307 feature = "platform-verifier",
308 any(feature = "aws-lc-rs", feature = "ring")
309 ))]
310 pub(crate) fn with_platform_verifier() -> Result<Self, Error> {
311 use rustls_platform_verifier::BuilderVerifierExt;
312
313 let mut inner = rustls::ClientConfig::builder_with_provider(configured_provider())
315 .with_protocol_versions(&[&rustls::version::TLS13])
316 .unwrap() .with_platform_verifier()?
318 .with_no_client_auth();
319
320 inner.enable_early_data = true;
321 Ok(Self {
322 initial: initial_suite_from_provider(inner.crypto_provider())
324 .expect("no initial cipher suite found"),
325 inner: Arc::new(inner),
326 })
327 }
328
329 #[cfg(any(feature = "aws-lc-rs", feature = "ring"))]
334 pub(crate) fn new(verifier: Arc<dyn ServerCertVerifier>) -> Self {
335 let inner = Self::inner(verifier);
336 Self {
337 initial: initial_suite_from_provider(inner.crypto_provider())
339 .expect("no initial cipher suite found"),
340 inner: Arc::new(inner),
341 }
342 }
343
344 pub fn with_initial(
348 inner: Arc<rustls::ClientConfig>,
349 initial: Suite,
350 ) -> Result<Self, NoInitialCipherSuite> {
351 match initial.suite.common.suite {
352 CipherSuite::TLS13_AES_128_GCM_SHA256 => Ok(Self { inner, initial }),
353 _ => Err(NoInitialCipherSuite { specific: true }),
354 }
355 }
356
357 pub fn set_alpn_protocols(&mut self, alpn_protocols: Vec<Vec<u8>>) {
359 let config = Arc::make_mut(&mut self.inner);
360 config.alpn_protocols = alpn_protocols;
361 }
362
363 #[cfg(any(feature = "aws-lc-rs", feature = "ring"))]
364 pub(crate) fn inner(verifier: Arc<dyn ServerCertVerifier>) -> rustls::ClientConfig {
365 let mut config = rustls::ClientConfig::builder_with_provider(configured_provider())
367 .with_protocol_versions(&[&rustls::version::TLS13])
368 .unwrap() .dangerous()
370 .with_custom_certificate_verifier(verifier)
371 .with_no_client_auth();
372
373 config.enable_early_data = true;
374 config
375 }
376}
377
378impl crypto::ClientConfig for QuicClientConfig {
379 fn start_session(
380 &self,
381 version: u32,
382 server_name: &str,
383 params: &TransportParameters,
384 ) -> Result<Box<dyn crypto::Session>, ConnectError> {
385 let version = interpret_version(version)?;
386 Ok(Box::new(TlsSession {
387 version,
388 got_handshake_data: false,
389 next_secrets: None,
390 inner: Connection::Client(
391 rustls::quic::ClientConnection::new(
392 self.inner.clone(),
393 version,
394 ServerName::try_from(server_name)
395 .map_err(|_| ConnectError::InvalidServerName(server_name.into()))?
396 .to_owned(),
397 to_vec(params),
398 )
399 .unwrap(),
400 ),
401 suite: self.initial,
402 }))
403 }
404}
405
406impl TryFrom<rustls::ClientConfig> for QuicClientConfig {
407 type Error = NoInitialCipherSuite;
408
409 fn try_from(inner: rustls::ClientConfig) -> Result<Self, Self::Error> {
410 Arc::new(inner).try_into()
411 }
412}
413
414impl TryFrom<Arc<rustls::ClientConfig>> for QuicClientConfig {
415 type Error = NoInitialCipherSuite;
416
417 fn try_from(inner: Arc<rustls::ClientConfig>) -> Result<Self, Self::Error> {
418 Ok(Self {
419 initial: initial_suite_from_provider(inner.crypto_provider())
420 .ok_or(NoInitialCipherSuite { specific: false })?,
421 inner,
422 })
423 }
424}
425
426#[derive(Clone, Debug)]
434pub struct NoInitialCipherSuite {
435 specific: bool,
437}
438
439impl core::fmt::Display for NoInitialCipherSuite {
440 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
441 f.write_str(match self.specific {
442 true => "invalid cipher suite specified",
443 false => "no initial cipher suite found",
444 })
445 }
446}
447
448impl core::error::Error for NoInitialCipherSuite {}
449
450#[derive(Clone)] pub struct QuicServerConfig {
464 inner: Arc<rustls::ServerConfig>,
465 initial: Suite,
466}
467
468impl QuicServerConfig {
469 #[cfg(any(feature = "aws-lc-rs", feature = "ring"))]
470 pub(crate) fn new(
471 cert_chain: Vec<CertificateDer<'static>>,
472 key: PrivateKeyDer<'static>,
473 ) -> Result<Self, Error> {
474 let inner = Self::inner(cert_chain, key)?;
475 Ok(Self {
476 initial: initial_suite_from_provider(inner.crypto_provider())
478 .expect("no initial cipher suite found"),
479 inner: Arc::new(inner),
480 })
481 }
482
483 pub fn with_initial(
487 inner: Arc<rustls::ServerConfig>,
488 initial: Suite,
489 ) -> Result<Self, NoInitialCipherSuite> {
490 match initial.suite.common.suite {
491 CipherSuite::TLS13_AES_128_GCM_SHA256 => Ok(Self { inner, initial }),
492 _ => Err(NoInitialCipherSuite { specific: true }),
493 }
494 }
495
496 pub fn set_alpn_protocols(&mut self, alpn_protocols: Vec<Vec<u8>>) {
498 let config = Arc::make_mut(&mut self.inner);
499 config.alpn_protocols = alpn_protocols;
500 }
501
502 #[cfg(any(feature = "aws-lc-rs", feature = "ring"))]
508 pub(crate) fn inner(
509 cert_chain: Vec<CertificateDer<'static>>,
510 key: PrivateKeyDer<'static>,
511 ) -> Result<rustls::ServerConfig, Error> {
512 let mut inner = rustls::ServerConfig::builder_with_provider(configured_provider())
513 .with_protocol_versions(&[&rustls::version::TLS13])
514 .unwrap() .with_no_client_auth()
516 .with_single_cert(cert_chain, key)?;
517
518 inner.max_early_data_size = u32::MAX;
519 Ok(inner)
520 }
521}
522
523impl TryFrom<rustls::ServerConfig> for QuicServerConfig {
524 type Error = NoInitialCipherSuite;
525
526 fn try_from(inner: rustls::ServerConfig) -> Result<Self, Self::Error> {
527 Arc::new(inner).try_into()
528 }
529}
530
531impl TryFrom<Arc<rustls::ServerConfig>> for QuicServerConfig {
532 type Error = NoInitialCipherSuite;
533
534 fn try_from(inner: Arc<rustls::ServerConfig>) -> Result<Self, Self::Error> {
535 Ok(Self {
536 initial: initial_suite_from_provider(inner.crypto_provider())
537 .ok_or(NoInitialCipherSuite { specific: false })?,
538 inner,
539 })
540 }
541}
542
543impl crypto::ServerConfig for QuicServerConfig {
544 fn start_session(
545 &self,
546 version: u32,
547 params: &TransportParameters,
548 ) -> Box<dyn crypto::Session> {
549 let version = interpret_version(version).unwrap();
551 Box::new(TlsSession {
552 version,
553 got_handshake_data: false,
554 next_secrets: None,
555 inner: Connection::Server(
556 rustls::quic::ServerConnection::new(self.inner.clone(), version, to_vec(params))
557 .unwrap(),
558 ),
559 suite: self.initial,
560 })
561 }
562
563 fn initial_keys(
564 &self,
565 version: u32,
566 dst_cid: ConnectionId,
567 ) -> Result<Keys, UnsupportedVersion> {
568 let version = interpret_version(version)?;
569 Ok(initial_keys(version, dst_cid, Side::Server, &self.initial))
570 }
571
572 fn retry_tag(&self, version: u32, orig_dst_cid: ConnectionId, packet: &[u8]) -> [u8; 16] {
573 let version = interpret_version(version).unwrap();
575 let (nonce, key) = match version {
576 Version::V1 => (&RETRY_INTEGRITY_NONCE_V1, &RETRY_INTEGRITY_KEY_V1),
577 Version::V1Draft => (&RETRY_INTEGRITY_NONCE_DRAFT, &RETRY_INTEGRITY_KEY_DRAFT),
578 _ => unreachable!(),
579 };
580
581 let mut pseudo_packet = Vec::with_capacity(packet.len() + orig_dst_cid.len() + 1);
582 pseudo_packet.push(orig_dst_cid.len() as u8);
583 pseudo_packet.extend_from_slice(&orig_dst_cid);
584 pseudo_packet.extend_from_slice(packet);
585
586 let nonce = aes_gcm::Nonce::from_slice(nonce);
587 let key = aes_gcm::Key::<aes_gcm::Aes128Gcm>::from_slice(key);
588 let tag = aes_gcm::Aes128Gcm::new(key)
589 .encrypt_in_place_detached(nonce, &pseudo_packet, &mut [])
590 .unwrap();
591 tag.into()
592 }
593}
594
595pub(crate) fn initial_suite_from_provider(
596 provider: &Arc<rustls::crypto::CryptoProvider>,
597) -> Option<Suite> {
598 provider
599 .cipher_suites
600 .iter()
601 .find_map(|cs| match (cs.suite(), cs.tls13()) {
602 (CipherSuite::TLS13_AES_128_GCM_SHA256, Some(suite)) => Some(suite.quic_suite()),
603 _ => None,
604 })
605 .flatten()
606}
607
608#[cfg(all(feature = "aws-lc-rs", not(feature = "ring")))]
609pub(crate) fn configured_provider() -> Arc<rustls::crypto::CryptoProvider> {
610 Arc::new(rustls::crypto::aws_lc_rs::default_provider())
611}
612
613#[cfg(feature = "ring")]
614pub(crate) fn configured_provider() -> Arc<rustls::crypto::CryptoProvider> {
615 Arc::new(rustls::crypto::ring::default_provider())
616}
617
618fn to_vec(params: &TransportParameters) -> Vec<u8> {
619 let mut bytes = Vec::new();
620 params.write(&mut bytes);
621 bytes
622}
623
624pub(crate) fn initial_keys(
625 version: Version,
626 dst_cid: ConnectionId,
627 side: Side,
628 suite: &Suite,
629) -> Keys {
630 let keys = suite.keys(&dst_cid, side.into(), version);
631 Keys {
632 header: KeyPair {
633 local: Box::new(keys.local.header),
634 remote: Box::new(keys.remote.header),
635 },
636 packet: KeyPair {
637 local: Box::new(keys.local.packet),
638 remote: Box::new(keys.remote.packet),
639 },
640 }
641}
642
643impl crypto::PacketKey for Box<dyn PacketKey> {
644 fn encrypt(&self, path_id: PathId, packet: u64, buf: &mut [u8], header_len: usize) {
645 let (header, payload_tag) = buf.split_at_mut(header_len);
646 let (payload, tag_storage) = payload_tag.split_at_mut(payload_tag.len() - self.tag_len());
647 let tag = self
648 .encrypt_in_place_for_path(path_id.as_u32(), packet, &*header, payload)
649 .unwrap();
650 tag_storage.copy_from_slice(tag.as_ref());
651 }
652
653 fn decrypt(
654 &self,
655 path_id: PathId,
656 packet: u64,
657 header: &[u8],
658 payload: &mut BytesMut,
659 ) -> Result<(), CryptoError> {
660 let plain = self
661 .decrypt_in_place_for_path(path_id.as_u32(), packet, header, payload.as_mut())
662 .map_err(|_| CryptoError)?;
663 let plain_len = plain.len();
664 payload.truncate(plain_len);
665 Ok(())
666 }
667
668 fn tag_len(&self) -> usize {
669 (**self).tag_len()
670 }
671
672 fn confidentiality_limit(&self) -> u64 {
673 (**self).confidentiality_limit()
674 }
675
676 fn integrity_limit(&self) -> u64 {
677 (**self).integrity_limit()
678 }
679}
680
681fn interpret_version(version: u32) -> Result<Version, UnsupportedVersion> {
682 match version {
683 0xff00_001d..=0xff00_0020 => Ok(Version::V1Draft),
684 0x0000_0001 | 0xff00_0021..=0xff00_0022 => Ok(Version::V1),
685 _ => Err(UnsupportedVersion),
686 }
687}