ant_quic/crypto.rs
1//! Traits and implementations for the QUIC cryptography protocol
2//!
3//! The protocol logic in Quinn is contained in types that abstract over the actual
4//! cryptographic protocol used. This module contains the traits used for this
5//! abstraction layer as well as a single implementation of these traits that uses
6//! *ring* and rustls to implement the TLS protocol support.
7//!
8//! Note that usage of any protocol (version) other than TLS 1.3 does not conform to any
9//! published versions of the specification, and will not be supported in QUIC v1.
10
11use std::{any::Any, str, sync::Arc};
12
13use bytes::BytesMut;
14
15use crate::{
16 ConnectError, Side, TransportError, shared::ConnectionId,
17 transport_parameters::TransportParameters,
18};
19
20/// Cryptography interface based on *ring*
21#[cfg(any(feature = "aws-lc-rs", feature = "ring"))]
22pub(crate) mod ring_like;
23/// TLS interface based on rustls
24#[cfg(any(feature = "rustls-aws-lc-rs", feature = "rustls-ring"))]
25pub mod rustls;
26
27/// Certificate management
28pub mod certificate_manager;
29
30/// RFC 7250 Raw Public Keys support
31pub mod raw_public_keys;
32
33/// Ed25519 key pair implementation
34pub mod raw_keys;
35
36// NOTE: The following modules were removed because they were written as external
37// integrations with Quinn, but ant-quic IS a fork of Quinn, not something that
38// integrates with it. These need to be rewritten as part of the Quinn implementation
39// if their functionality is needed.
40
41// Removed modules:
42// - rpk_integration (tried to integrate RPK with Quinn from outside)
43// - quinn_integration (tried to wrap Quinn endpoints)
44// - bootstrap_support (tried to add bootstrap support on top of Quinn)
45// - peer_discovery (distributed discovery layered on Quinn)
46// - enterprise_cert_mgmt (enterprise features added on top)
47// - performance_monitoring (monitoring Quinn from outside)
48// - performance_optimization (optimizing Quinn externally)
49// - zero_rtt_rpk (0-RTT features added on top)
50// - nat_rpk_integration (NAT traversal integration)
51
52/// TLS Extensions for RFC 7250 certificate type negotiation
53pub mod tls_extensions;
54
55/// TLS Extension Simulation for RFC 7250 Raw Public Keys
56pub mod tls_extension_simulation;
57
58/// rustls Extension Handlers for certificate type negotiation
59pub mod extension_handlers;
60
61/// Certificate Type Negotiation Protocol Implementation
62pub mod certificate_negotiation;
63
64/// Test module for TLS extension simulation
65#[cfg(test)]
66mod test_tls_simulation;
67
68/// A cryptographic session (commonly TLS)
69pub trait Session: Send + Sync + 'static {
70 /// Create the initial set of keys given the client's initial destination ConnectionId
71 fn initial_keys(&self, dst_cid: &ConnectionId, side: Side) -> Keys;
72
73 /// Get data negotiated during the handshake, if available
74 ///
75 /// Returns `None` until the connection emits `HandshakeDataReady`.
76 fn handshake_data(&self) -> Option<Box<dyn Any>>;
77
78 /// Get the peer's identity, if available
79 fn peer_identity(&self) -> Option<Box<dyn Any>>;
80
81 /// Get the 0-RTT keys if available (clients only)
82 ///
83 /// On the client side, this method can be used to see if 0-RTT key material is available
84 /// to start sending data before the protocol handshake has completed.
85 ///
86 /// Returns `None` if the key material is not available. This might happen if you have
87 /// not connected to this server before.
88 fn early_crypto(&self) -> Option<(Box<dyn HeaderKey>, Box<dyn PacketKey>)>;
89
90 /// If the 0-RTT-encrypted data has been accepted by the peer
91 fn early_data_accepted(&self) -> Option<bool>;
92
93 /// Returns `true` until the connection is fully established.
94 fn is_handshaking(&self) -> bool;
95
96 /// Read bytes of handshake data
97 ///
98 /// This should be called with the contents of `CRYPTO` frames. If it returns `Ok`, the
99 /// caller should call `write_handshake()` to check if the crypto protocol has anything
100 /// to send to the peer. This method will only return `true` the first time that
101 /// handshake data is available. Future calls will always return false.
102 ///
103 /// On success, returns `true` iff `self.handshake_data()` has been populated.
104 fn read_handshake(&mut self, buf: &[u8]) -> Result<bool, TransportError>;
105
106 /// The peer's QUIC transport parameters
107 ///
108 /// These are only available after the first flight from the peer has been received.
109 fn transport_parameters(&self) -> Result<Option<TransportParameters>, TransportError>;
110
111 /// Writes handshake bytes into the given buffer and optionally returns the negotiated keys
112 ///
113 /// When the handshake proceeds to the next phase, this method will return a new set of
114 /// keys to encrypt data with.
115 fn write_handshake(&mut self, buf: &mut Vec<u8>) -> Option<Keys>;
116
117 /// Compute keys for the next key update
118 fn next_1rtt_keys(&mut self) -> Option<KeyPair<Box<dyn PacketKey>>>;
119
120 /// Verify the integrity of a retry packet
121 fn is_valid_retry(&self, orig_dst_cid: &ConnectionId, header: &[u8], payload: &[u8]) -> bool;
122
123 /// Fill `output` with `output.len()` bytes of keying material derived
124 /// from the [Session]'s secrets, using `label` and `context` for domain
125 /// separation.
126 ///
127 /// This function will fail, returning [ExportKeyingMaterialError],
128 /// if the requested output length is too large.
129 fn export_keying_material(
130 &self,
131 output: &mut [u8],
132 label: &[u8],
133 context: &[u8],
134 ) -> Result<(), ExportKeyingMaterialError>;
135}
136
137/// A pair of keys for bidirectional communication
138pub struct KeyPair<T> {
139 /// Key for encrypting data
140 pub local: T,
141 /// Key for decrypting data
142 pub remote: T,
143}
144
145/// A complete set of keys for a certain packet space
146pub struct Keys {
147 /// Header protection keys
148 pub header: KeyPair<Box<dyn HeaderKey>>,
149 /// Packet protection keys
150 pub packet: KeyPair<Box<dyn PacketKey>>,
151}
152
153/// Client-side configuration for the crypto protocol
154pub trait ClientConfig: Send + Sync {
155 /// Start a client session with this configuration
156 fn start_session(
157 self: Arc<Self>,
158 version: u32,
159 server_name: &str,
160 params: &TransportParameters,
161 ) -> Result<Box<dyn Session>, ConnectError>;
162}
163
164/// Server-side configuration for the crypto protocol
165pub trait ServerConfig: Send + Sync {
166 /// Create the initial set of keys given the client's initial destination ConnectionId
167 fn initial_keys(
168 &self,
169 version: u32,
170 dst_cid: &ConnectionId,
171 ) -> Result<Keys, UnsupportedVersion>;
172
173 /// Generate the integrity tag for a retry packet
174 ///
175 /// Never called if `initial_keys` rejected `version`.
176 fn retry_tag(&self, version: u32, orig_dst_cid: &ConnectionId, packet: &[u8]) -> [u8; 16];
177
178 /// Start a server session with this configuration
179 ///
180 /// Never called if `initial_keys` rejected `version`.
181 fn start_session(
182 self: Arc<Self>,
183 version: u32,
184 params: &TransportParameters,
185 ) -> Box<dyn Session>;
186}
187
188/// Keys used to protect packet payloads
189pub trait PacketKey: Send + Sync {
190 /// Encrypt the packet payload with the given packet number
191 fn encrypt(&self, packet: u64, buf: &mut [u8], header_len: usize);
192 /// Decrypt the packet payload with the given packet number
193 fn decrypt(
194 &self,
195 packet: u64,
196 header: &[u8],
197 payload: &mut BytesMut,
198 ) -> Result<(), CryptoError>;
199 /// The length of the AEAD tag appended to packets on encryption
200 fn tag_len(&self) -> usize;
201 /// Maximum number of packets that may be sent using a single key
202 fn confidentiality_limit(&self) -> u64;
203 /// Maximum number of incoming packets that may fail decryption before the connection must be
204 /// abandoned
205 fn integrity_limit(&self) -> u64;
206}
207
208/// Keys used to protect packet headers
209pub trait HeaderKey: Send + Sync {
210 /// Decrypt the given packet's header
211 fn decrypt(&self, pn_offset: usize, packet: &mut [u8]);
212 /// Encrypt the given packet's header
213 fn encrypt(&self, pn_offset: usize, packet: &mut [u8]);
214 /// The sample size used for this key's algorithm
215 fn sample_size(&self) -> usize;
216}
217
218/// A key for signing with HMAC-based algorithms
219pub trait HmacKey: Send + Sync {
220 /// Method for signing a message
221 fn sign(&self, data: &[u8], signature_out: &mut [u8]);
222 /// Length of `sign`'s output
223 fn signature_len(&self) -> usize;
224 /// Method for verifying a message
225 fn verify(&self, data: &[u8], signature: &[u8]) -> Result<(), CryptoError>;
226}
227
228/// Error returned by [Session::export_keying_material].
229///
230/// This error occurs if the requested output length is too large.
231#[derive(Debug, PartialEq, Eq)]
232pub struct ExportKeyingMaterialError;
233
234/// A pseudo random key for HKDF
235pub trait HandshakeTokenKey: Send + Sync {
236 /// Derive AEAD using hkdf
237 fn aead_from_hkdf(&self, random_bytes: &[u8]) -> Box<dyn AeadKey>;
238}
239
240/// A key for sealing data with AEAD-based algorithms
241pub trait AeadKey {
242 /// Method for sealing message `data`
243 fn seal(&self, data: &mut Vec<u8>, additional_data: &[u8]) -> Result<(), CryptoError>;
244 /// Method for opening a sealed message `data`
245 fn open<'a>(
246 &self,
247 data: &'a mut [u8],
248 additional_data: &[u8],
249 ) -> Result<&'a mut [u8], CryptoError>;
250}
251
252/// Generic crypto errors
253#[derive(Debug)]
254pub struct CryptoError;
255
256/// Error indicating that the specified QUIC version is not supported
257#[derive(Debug)]
258pub struct UnsupportedVersion;
259
260impl From<UnsupportedVersion> for ConnectError {
261 fn from(_: UnsupportedVersion) -> Self {
262 Self::UnsupportedVersion
263 }
264}