1use alloc::boxed::Box;
2use alloc::collections::VecDeque;
3use alloc::vec::Vec;
4#[cfg(feature = "std")]
5use core::fmt::Debug;
6
7use crate::common_state::Side;
9use crate::crypto::cipher::{AeadKey, Iv};
10use crate::crypto::tls13::{Hkdf, HkdfExpander, OkmBlock};
11use crate::enums::AlertDescription;
12use crate::error::Error;
13use crate::tls13::Tls13CipherSuite;
14use crate::tls13::key_schedule::{
15 hkdf_expand_label, hkdf_expand_label_aead_key, hkdf_expand_label_block,
16};
17
18#[cfg(feature = "std")]
19mod connection {
20 use alloc::vec::Vec;
21 use core::fmt::{self, Debug};
22 use core::ops::{Deref, DerefMut};
23
24 use pki_types::ServerName;
25
26 use super::{DirectionalKeys, KeyChange, Version};
27 use crate::client::{ClientConfig, ClientConnectionData};
28 use crate::common_state::{CommonState, DEFAULT_BUFFER_LIMIT, Protocol};
29 use crate::conn::{ConnectionCore, SideData};
30 use crate::enums::{AlertDescription, ContentType, ProtocolVersion};
31 use crate::error::Error;
32 use crate::msgs::base::Payload;
33 use crate::msgs::deframer::buffers::{DeframerVecBuffer, Locator};
34 use crate::msgs::handshake::{
35 ClientExtensionsInput, ServerExtensionsInput, TransportParameters,
36 };
37 use crate::msgs::message::InboundPlainMessage;
38 use crate::server::{ServerConfig, ServerConnectionData};
39 use crate::sync::Arc;
40 use crate::vecbuf::ChunkVecBuffer;
41
42 #[derive(Debug)]
44 pub enum Connection {
45 Client(ClientConnection),
47 Server(ServerConnection),
49 }
50
51 impl Connection {
52 pub fn quic_transport_parameters(&self) -> Option<&[u8]> {
56 match self {
57 Self::Client(conn) => conn.quic_transport_parameters(),
58 Self::Server(conn) => conn.quic_transport_parameters(),
59 }
60 }
61
62 pub fn zero_rtt_keys(&self) -> Option<DirectionalKeys> {
64 match self {
65 Self::Client(conn) => conn.zero_rtt_keys(),
66 Self::Server(conn) => conn.zero_rtt_keys(),
67 }
68 }
69
70 pub fn read_hs(&mut self, plaintext: &[u8]) -> Result<(), Error> {
74 match self {
75 Self::Client(conn) => conn.read_hs(plaintext),
76 Self::Server(conn) => conn.read_hs(plaintext),
77 }
78 }
79
80 pub fn write_hs(&mut self, buf: &mut Vec<u8>) -> Option<KeyChange> {
84 match self {
85 Self::Client(conn) => conn.write_hs(buf),
86 Self::Server(conn) => conn.write_hs(buf),
87 }
88 }
89
90 pub fn alert(&self) -> Option<AlertDescription> {
94 match self {
95 Self::Client(conn) => conn.alert(),
96 Self::Server(conn) => conn.alert(),
97 }
98 }
99
100 #[inline]
116 pub fn export_keying_material<T: AsMut<[u8]>>(
117 &self,
118 output: T,
119 label: &[u8],
120 context: Option<&[u8]>,
121 ) -> Result<T, Error> {
122 match self {
123 Self::Client(conn) => conn
124 .core
125 .export_keying_material(output, label, context),
126 Self::Server(conn) => conn
127 .core
128 .export_keying_material(output, label, context),
129 }
130 }
131 }
132
133 impl Deref for Connection {
134 type Target = CommonState;
135
136 fn deref(&self) -> &Self::Target {
137 match self {
138 Self::Client(conn) => &conn.core.common_state,
139 Self::Server(conn) => &conn.core.common_state,
140 }
141 }
142 }
143
144 impl DerefMut for Connection {
145 fn deref_mut(&mut self) -> &mut Self::Target {
146 match self {
147 Self::Client(conn) => &mut conn.core.common_state,
148 Self::Server(conn) => &mut conn.core.common_state,
149 }
150 }
151 }
152
153 pub struct ClientConnection {
155 inner: ConnectionCommon<ClientConnectionData>,
156 }
157
158 impl ClientConnection {
159 pub fn new(
164 config: Arc<ClientConfig>,
165 quic_version: Version,
166 name: ServerName<'static>,
167 params: Vec<u8>,
168 ) -> Result<Self, Error> {
169 Self::new_with_alpn(
170 config.clone(),
171 quic_version,
172 name,
173 params,
174 config.alpn_protocols.clone(),
175 )
176 }
177
178 pub fn new_with_alpn(
180 config: Arc<ClientConfig>,
181 quic_version: Version,
182 name: ServerName<'static>,
183 params: Vec<u8>,
184 alpn_protocols: Vec<Vec<u8>>,
185 ) -> Result<Self, Error> {
186 if !config.supports_version(ProtocolVersion::TLSv1_3) {
187 return Err(Error::General(
188 "TLS 1.3 support is required for QUIC".into(),
189 ));
190 }
191
192 if !config.supports_protocol(Protocol::Quic) {
193 return Err(Error::General(
194 "at least one ciphersuite must support QUIC".into(),
195 ));
196 }
197
198 let exts = ClientExtensionsInput {
199 transport_parameters: Some(match quic_version {
200 Version::V1Draft => TransportParameters::QuicDraft(Payload::new(params)),
201 Version::V1 | Version::V2 => TransportParameters::Quic(Payload::new(params)),
202 }),
203
204 ..ClientExtensionsInput::from_alpn(alpn_protocols)
205 };
206
207 let mut inner = ConnectionCore::for_client(config, name, exts, Protocol::Quic)?;
208 inner.common_state.quic.version = quic_version;
209 Ok(Self {
210 inner: inner.into(),
211 })
212 }
213
214 pub fn is_early_data_accepted(&self) -> bool {
220 self.inner.core.is_early_data_accepted()
221 }
222
223 pub fn tls13_tickets_received(&self) -> u32 {
225 self.inner.tls13_tickets_received
226 }
227 }
228
229 impl Deref for ClientConnection {
230 type Target = ConnectionCommon<ClientConnectionData>;
231
232 fn deref(&self) -> &Self::Target {
233 &self.inner
234 }
235 }
236
237 impl DerefMut for ClientConnection {
238 fn deref_mut(&mut self) -> &mut Self::Target {
239 &mut self.inner
240 }
241 }
242
243 impl Debug for ClientConnection {
244 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245 f.debug_struct("quic::ClientConnection")
246 .finish()
247 }
248 }
249
250 impl From<ClientConnection> for Connection {
251 fn from(c: ClientConnection) -> Self {
252 Self::Client(c)
253 }
254 }
255
256 pub struct ServerConnection {
258 inner: ConnectionCommon<ServerConnectionData>,
259 }
260
261 impl ServerConnection {
262 pub fn new(
267 config: Arc<ServerConfig>,
268 quic_version: Version,
269 params: Vec<u8>,
270 ) -> Result<Self, Error> {
271 if !config.supports_version(ProtocolVersion::TLSv1_3) {
272 return Err(Error::General(
273 "TLS 1.3 support is required for QUIC".into(),
274 ));
275 }
276
277 if !config.supports_protocol(Protocol::Quic) {
278 return Err(Error::General(
279 "at least one ciphersuite must support QUIC".into(),
280 ));
281 }
282
283 if config.max_early_data_size != 0 && config.max_early_data_size != 0xffff_ffff {
284 return Err(Error::General(
285 "QUIC sessions must set a max early data of 0 or 2^32-1".into(),
286 ));
287 }
288
289 let exts = ServerExtensionsInput {
290 transport_parameters: Some(match quic_version {
291 Version::V1Draft => TransportParameters::QuicDraft(Payload::new(params)),
292 Version::V1 | Version::V2 => TransportParameters::Quic(Payload::new(params)),
293 }),
294 };
295
296 let mut core = ConnectionCore::for_server(config, exts)?;
297 core.common_state.protocol = Protocol::Quic;
298 core.common_state.quic.version = quic_version;
299 Ok(Self { inner: core.into() })
300 }
301
302 pub fn reject_early_data(&mut self) {
308 self.inner.core.reject_early_data()
309 }
310
311 pub fn server_name(&self) -> Option<&str> {
327 self.inner.core.get_sni_str()
328 }
329 }
330
331 impl Deref for ServerConnection {
332 type Target = ConnectionCommon<ServerConnectionData>;
333
334 fn deref(&self) -> &Self::Target {
335 &self.inner
336 }
337 }
338
339 impl DerefMut for ServerConnection {
340 fn deref_mut(&mut self) -> &mut Self::Target {
341 &mut self.inner
342 }
343 }
344
345 impl Debug for ServerConnection {
346 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
347 f.debug_struct("quic::ServerConnection")
348 .finish()
349 }
350 }
351
352 impl From<ServerConnection> for Connection {
353 fn from(c: ServerConnection) -> Self {
354 Self::Server(c)
355 }
356 }
357
358 pub struct ConnectionCommon<Data> {
360 core: ConnectionCore<Data>,
361 deframer_buffer: DeframerVecBuffer,
362 sendable_plaintext: ChunkVecBuffer,
363 }
364
365 impl<Data: SideData> ConnectionCommon<Data> {
366 pub fn quic_transport_parameters(&self) -> Option<&[u8]> {
374 self.core
375 .common_state
376 .quic
377 .params
378 .as_ref()
379 .map(|v| v.as_ref())
380 }
381
382 pub fn zero_rtt_keys(&self) -> Option<DirectionalKeys> {
384 let suite = self
385 .core
386 .common_state
387 .suite
388 .and_then(|suite| suite.tls13())?;
389 Some(DirectionalKeys::new(
390 suite,
391 suite.quic?,
392 self.core
393 .common_state
394 .quic
395 .early_secret
396 .as_ref()?,
397 self.core.common_state.quic.version,
398 ))
399 }
400
401 pub fn read_hs(&mut self, plaintext: &[u8]) -> Result<(), Error> {
405 let range = self.deframer_buffer.extend(plaintext);
406
407 self.core.hs_deframer.input_message(
408 InboundPlainMessage {
409 typ: ContentType::Handshake,
410 version: ProtocolVersion::TLSv1_3,
411 payload: &self.deframer_buffer.filled()[range.clone()],
412 },
413 &Locator::new(self.deframer_buffer.filled()),
414 range.end,
415 );
416
417 self.core
418 .hs_deframer
419 .coalesce(self.deframer_buffer.filled_mut())?;
420
421 self.core
422 .process_new_packets(&mut self.deframer_buffer, &mut self.sendable_plaintext)?;
423
424 Ok(())
425 }
426
427 pub fn write_hs(&mut self, buf: &mut Vec<u8>) -> Option<KeyChange> {
431 self.core
432 .common_state
433 .quic
434 .write_hs(buf)
435 }
436
437 pub fn alert(&self) -> Option<AlertDescription> {
441 self.core.common_state.quic.alert
442 }
443 }
444
445 impl<Data> Deref for ConnectionCommon<Data> {
446 type Target = CommonState;
447
448 fn deref(&self) -> &Self::Target {
449 &self.core.common_state
450 }
451 }
452
453 impl<Data> DerefMut for ConnectionCommon<Data> {
454 fn deref_mut(&mut self) -> &mut Self::Target {
455 &mut self.core.common_state
456 }
457 }
458
459 impl<Data> From<ConnectionCore<Data>> for ConnectionCommon<Data> {
460 fn from(core: ConnectionCore<Data>) -> Self {
461 Self {
462 core,
463 deframer_buffer: DeframerVecBuffer::default(),
464 sendable_plaintext: ChunkVecBuffer::new(Some(DEFAULT_BUFFER_LIMIT)),
465 }
466 }
467 }
468}
469
470#[cfg(feature = "std")]
471pub use connection::{ClientConnection, Connection, ConnectionCommon, ServerConnection};
472
473#[derive(Default)]
474pub(crate) struct Quic {
475 pub(crate) params: Option<Vec<u8>>,
477 pub(crate) alert: Option<AlertDescription>,
478 pub(crate) hs_queue: VecDeque<(bool, Vec<u8>)>,
479 pub(crate) early_secret: Option<OkmBlock>,
480 pub(crate) hs_secrets: Option<Secrets>,
481 pub(crate) traffic_secrets: Option<Secrets>,
482 #[cfg(feature = "std")]
484 pub(crate) returned_traffic_keys: bool,
485 pub(crate) version: Version,
486}
487
488#[cfg(feature = "std")]
489impl Quic {
490 pub(crate) fn write_hs(&mut self, buf: &mut Vec<u8>) -> Option<KeyChange> {
491 while let Some((_, msg)) = self.hs_queue.pop_front() {
492 buf.extend_from_slice(&msg);
493 if let Some(&(true, _)) = self.hs_queue.front() {
494 if self.hs_secrets.is_some() {
495 break;
497 }
498 }
499 }
500
501 if let Some(secrets) = self.hs_secrets.take() {
502 return Some(KeyChange::Handshake {
503 keys: Keys::new(&secrets),
504 });
505 }
506
507 if let Some(mut secrets) = self.traffic_secrets.take() {
508 if !self.returned_traffic_keys {
509 self.returned_traffic_keys = true;
510 let keys = Keys::new(&secrets);
511 secrets.update();
512 return Some(KeyChange::OneRtt {
513 keys,
514 next: secrets,
515 });
516 }
517 }
518
519 None
520 }
521}
522
523#[derive(Clone)]
525pub struct Secrets {
526 pub(crate) client: OkmBlock,
528 pub(crate) server: OkmBlock,
530 suite: &'static Tls13CipherSuite,
532 quic: &'static dyn Algorithm,
533 side: Side,
534 version: Version,
535}
536
537impl Secrets {
538 pub(crate) fn new(
539 client: OkmBlock,
540 server: OkmBlock,
541 suite: &'static Tls13CipherSuite,
542 quic: &'static dyn Algorithm,
543 side: Side,
544 version: Version,
545 ) -> Self {
546 Self {
547 client,
548 server,
549 suite,
550 quic,
551 side,
552 version,
553 }
554 }
555
556 pub fn next_packet_keys(&mut self) -> PacketKeySet {
558 let keys = PacketKeySet::new(self);
559 self.update();
560 keys
561 }
562
563 pub(crate) fn update(&mut self) {
564 self.client = hkdf_expand_label_block(
565 self.suite
566 .hkdf_provider
567 .expander_for_okm(&self.client)
568 .as_ref(),
569 self.version.key_update_label(),
570 &[],
571 );
572 self.server = hkdf_expand_label_block(
573 self.suite
574 .hkdf_provider
575 .expander_for_okm(&self.server)
576 .as_ref(),
577 self.version.key_update_label(),
578 &[],
579 );
580 }
581
582 fn local_remote(&self) -> (&OkmBlock, &OkmBlock) {
583 match self.side {
584 Side::Client => (&self.client, &self.server),
585 Side::Server => (&self.server, &self.client),
586 }
587 }
588}
589
590pub struct DirectionalKeys {
592 pub header: Box<dyn HeaderProtectionKey>,
594 pub packet: Box<dyn PacketKey>,
596}
597
598impl DirectionalKeys {
599 pub(crate) fn new(
600 suite: &'static Tls13CipherSuite,
601 quic: &'static dyn Algorithm,
602 secret: &OkmBlock,
603 version: Version,
604 ) -> Self {
605 let builder = KeyBuilder::new(secret, version, quic, suite.hkdf_provider);
606 Self {
607 header: builder.header_protection_key(),
608 packet: builder.packet_key(),
609 }
610 }
611}
612
613const TAG_LEN: usize = 16;
615
616pub struct Tag([u8; TAG_LEN]);
618
619impl From<&[u8]> for Tag {
620 fn from(value: &[u8]) -> Self {
621 let mut array = [0u8; TAG_LEN];
622 array.copy_from_slice(value);
623 Self(array)
624 }
625}
626
627impl AsRef<[u8]> for Tag {
628 fn as_ref(&self) -> &[u8] {
629 &self.0
630 }
631}
632
633pub trait Algorithm: Send + Sync {
635 fn packet_key(&self, key: AeadKey, iv: Iv) -> Box<dyn PacketKey>;
640
641 fn header_protection_key(&self, key: AeadKey) -> Box<dyn HeaderProtectionKey>;
645
646 fn aead_key_len(&self) -> usize;
650
651 fn fips(&self) -> bool {
653 false
654 }
655}
656
657pub trait HeaderProtectionKey: Send + Sync {
659 fn encrypt_in_place(
680 &self,
681 sample: &[u8],
682 first: &mut u8,
683 packet_number: &mut [u8],
684 ) -> Result<(), Error>;
685
686 fn decrypt_in_place(
708 &self,
709 sample: &[u8],
710 first: &mut u8,
711 packet_number: &mut [u8],
712 ) -> Result<(), Error>;
713
714 fn sample_len(&self) -> usize;
716}
717
718pub trait PacketKey: Send + Sync {
720 fn encrypt_in_place(
728 &self,
729 packet_number: u64,
730 header: &[u8],
731 payload: &mut [u8],
732 ) -> Result<Tag, Error>;
733
734 fn decrypt_in_place<'a>(
742 &self,
743 packet_number: u64,
744 header: &[u8],
745 payload: &'a mut [u8],
746 ) -> Result<&'a [u8], Error>;
747
748 fn tag_len(&self) -> usize;
750
751 fn confidentiality_limit(&self) -> u64;
762
763 fn integrity_limit(&self) -> u64;
772}
773
774pub struct PacketKeySet {
776 pub local: Box<dyn PacketKey>,
778 pub remote: Box<dyn PacketKey>,
780}
781
782impl PacketKeySet {
783 fn new(secrets: &Secrets) -> Self {
784 let (local, remote) = secrets.local_remote();
785 let (version, alg, hkdf) = (secrets.version, secrets.quic, secrets.suite.hkdf_provider);
786 Self {
787 local: KeyBuilder::new(local, version, alg, hkdf).packet_key(),
788 remote: KeyBuilder::new(remote, version, alg, hkdf).packet_key(),
789 }
790 }
791}
792
793pub(crate) struct KeyBuilder<'a> {
794 expander: Box<dyn HkdfExpander>,
795 version: Version,
796 alg: &'a dyn Algorithm,
797}
798
799impl<'a> KeyBuilder<'a> {
800 pub(crate) fn new(
801 secret: &OkmBlock,
802 version: Version,
803 alg: &'a dyn Algorithm,
804 hkdf: &'a dyn Hkdf,
805 ) -> Self {
806 Self {
807 expander: hkdf.expander_for_okm(secret),
808 version,
809 alg,
810 }
811 }
812
813 pub(crate) fn packet_key(&self) -> Box<dyn PacketKey> {
815 let aead_key_len = self.alg.aead_key_len();
816 let packet_key = hkdf_expand_label_aead_key(
817 self.expander.as_ref(),
818 aead_key_len,
819 self.version.packet_key_label(),
820 &[],
821 );
822
823 let packet_iv =
824 hkdf_expand_label(self.expander.as_ref(), self.version.packet_iv_label(), &[]);
825 self.alg
826 .packet_key(packet_key, packet_iv)
827 }
828
829 pub(crate) fn header_protection_key(&self) -> Box<dyn HeaderProtectionKey> {
831 let header_key = hkdf_expand_label_aead_key(
832 self.expander.as_ref(),
833 self.alg.aead_key_len(),
834 self.version.header_key_label(),
835 &[],
836 );
837 self.alg
838 .header_protection_key(header_key)
839 }
840}
841
842#[derive(Clone, Copy)]
844pub struct Suite {
845 pub suite: &'static Tls13CipherSuite,
847 pub quic: &'static dyn Algorithm,
849}
850
851impl Suite {
852 pub fn keys(&self, client_dst_connection_id: &[u8], side: Side, version: Version) -> Keys {
854 Keys::initial(
855 version,
856 self.suite,
857 self.quic,
858 client_dst_connection_id,
859 side,
860 )
861 }
862}
863
864pub struct Keys {
866 pub local: DirectionalKeys,
868 pub remote: DirectionalKeys,
870}
871
872impl Keys {
873 pub fn initial(
875 version: Version,
876 suite: &'static Tls13CipherSuite,
877 quic: &'static dyn Algorithm,
878 client_dst_connection_id: &[u8],
879 side: Side,
880 ) -> Self {
881 const CLIENT_LABEL: &[u8] = b"client in";
882 const SERVER_LABEL: &[u8] = b"server in";
883 let salt = version.initial_salt();
884 let hs_secret = suite
885 .hkdf_provider
886 .extract_from_secret(Some(salt), client_dst_connection_id);
887
888 let secrets = Secrets {
889 version,
890 client: hkdf_expand_label_block(hs_secret.as_ref(), CLIENT_LABEL, &[]),
891 server: hkdf_expand_label_block(hs_secret.as_ref(), SERVER_LABEL, &[]),
892 suite,
893 quic,
894 side,
895 };
896 Self::new(&secrets)
897 }
898
899 fn new(secrets: &Secrets) -> Self {
900 let (local, remote) = secrets.local_remote();
901 Self {
902 local: DirectionalKeys::new(secrets.suite, secrets.quic, local, secrets.version),
903 remote: DirectionalKeys::new(secrets.suite, secrets.quic, remote, secrets.version),
904 }
905 }
906}
907
908pub enum KeyChange {
922 Handshake {
924 keys: Keys,
926 },
927 OneRtt {
929 keys: Keys,
931 next: Secrets,
933 },
934}
935
936#[non_exhaustive]
940#[derive(Clone, Copy, Debug)]
941pub enum Version {
942 V1Draft,
944 V1,
946 V2,
948}
949
950impl Version {
951 fn initial_salt(self) -> &'static [u8; 20] {
952 match self {
953 Self::V1Draft => &[
954 0xaf, 0xbf, 0xec, 0x28, 0x99, 0x93, 0xd2, 0x4c, 0x9e, 0x97, 0x86, 0xf1, 0x9c, 0x61,
956 0x11, 0xe0, 0x43, 0x90, 0xa8, 0x99,
957 ],
958 Self::V1 => &[
959 0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17, 0x9a, 0xe6, 0xa4, 0xc8,
961 0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a,
962 ],
963 Self::V2 => &[
964 0x0d, 0xed, 0xe3, 0xde, 0xf7, 0x00, 0xa6, 0xdb, 0x81, 0x93, 0x81, 0xbe, 0x6e, 0x26,
966 0x9d, 0xcb, 0xf9, 0xbd, 0x2e, 0xd9,
967 ],
968 }
969 }
970
971 pub(crate) fn packet_key_label(&self) -> &'static [u8] {
973 match self {
974 Self::V1Draft | Self::V1 => b"quic key",
975 Self::V2 => b"quicv2 key",
976 }
977 }
978
979 pub(crate) fn packet_iv_label(&self) -> &'static [u8] {
981 match self {
982 Self::V1Draft | Self::V1 => b"quic iv",
983 Self::V2 => b"quicv2 iv",
984 }
985 }
986
987 pub(crate) fn header_key_label(&self) -> &'static [u8] {
989 match self {
990 Self::V1Draft | Self::V1 => b"quic hp",
991 Self::V2 => b"quicv2 hp",
992 }
993 }
994
995 fn key_update_label(&self) -> &'static [u8] {
996 match self {
997 Self::V1Draft | Self::V1 => b"quic ku",
998 Self::V2 => b"quicv2 ku",
999 }
1000 }
1001}
1002
1003impl Default for Version {
1004 fn default() -> Self {
1005 Self::V1
1006 }
1007}
1008
1009#[cfg(test)]
1010mod tests {
1011 use std::prelude::v1::*;
1012
1013 use super::PacketKey;
1014 use crate::quic::HeaderProtectionKey;
1015
1016 #[test]
1017 fn auto_traits() {
1018 fn assert_auto<T: Send + Sync>() {}
1019 assert_auto::<Box<dyn PacketKey>>();
1020 assert_auto::<Box<dyn HeaderProtectionKey>>();
1021 }
1022}