rustls/conn/kernel.rs
1//! Kernel connection API.
2//!
3//! This module gives you the bare minimum you need to implement a TLS connection
4//! that does its own encryption and decryption while still using rustls to manage
5//! connection secrets and session tickets. It is intended for use cases like kTLS
6//! where you want to use rustls to establish the connection but want to use
7//! something else to do the encryption/decryption after that.
8//!
9//! There are only two things that [`KernelConnection`] is able to do:
10//! 1. Compute new traffic secrets when a key update occurs.
11//! 2. Save received session tickets sent by a server peer.
12//!
13//! That's it. Everything else you will need to implement yourself.
14//!
15//! # Entry Point
16//! The entry points into this API are
17//! [`UnbufferedClientConnection::dangerous_into_kernel_connection`][client-into]
18//! and
19//! [`UnbufferedServerConnection::dangerous_into_kernel_connection`][server-into].
20//!
21//! In order to actually create an [`KernelConnection`] all of the following
22//! must be true:
23//! - the connection must have completed its handshake,
24//! - the connection must have no buffered TLS data waiting to be sent, and,
25//! - the config used to create the connection must have `enable_extract_secrets`
26//! set to true.
27//!
28//! This sounds fairly complicated to achieve at first glance. However, if you
29//! drive an unbuffered connection through the handshake until it returns
30//! [`WriteTraffic`] then it will end up in an appropriate state to convert
31//! into an external connection.
32//!
33//! [client-into]: crate::client::UnbufferedClientConnection::dangerous_into_kernel_connection
34//! [server-into]: crate::server::UnbufferedServerConnection::dangerous_into_kernel_connection
35//! [`WriteTraffic`]: crate::unbuffered::ConnectionState::WriteTraffic
36//!
37//! # Cipher Suite Confidentiality Limits
38//! Some cipher suites (notably AES-GCM) have vulnerabilities where they are no
39//! longer secure once a certain number of messages have been sent. Normally,
40//! rustls tracks how many messages have been written or read and will
41//! automatically either refresh keys or emit an error when approaching the
42//! confidentiality limit of the cipher suite.
43//!
44//! [`KernelConnection`] has no way to track this. It is the responsibility
45//! of the user of the API to track approximately how many messages have been
46//! sent and either refresh the traffic keys or abort the connection before the
47//! confidentiality limit is reached.
48//!
49//! You can find the current confidentiality limit by looking at
50//! [`CipherSuiteCommon::confidentiality_limit`] for the cipher suite selected
51//! by the connection.
52//!
53//! [`CipherSuiteCommon::confidentiality_limit`]: crate::CipherSuiteCommon::confidentiality_limit
54//! [`KernelConnection`]: crate::kernel::KernelConnection
55
56use core::marker::PhantomData;
57
58use alloc::boxed::Box;
59
60use crate::client::ClientConnectionData;
61use crate::common_state::Protocol;
62use crate::msgs::codec::Codec;
63use crate::msgs::handshake::{CertificateChain, NewSessionTicketPayloadTls13};
64use crate::quic::Quic;
65use crate::{CommonState, ConnectionTrafficSecrets, Error, ProtocolVersion, SupportedCipherSuite};
66
67/// A kernel connection.
68///
69/// This does not directly wrap a kernel connection, rather it gives you the
70/// minimal interfaces you need to implement a well-behaved TLS connection on
71/// top of kTLS.
72///
73/// See the [`crate::kernel`] module docs for more details.
74pub struct KernelConnection<Data> {
75 state: Box<dyn KernelState>,
76
77 peer_certificates: Option<CertificateChain<'static>>,
78 quic: Quic,
79
80 negotiated_version: ProtocolVersion,
81 protocol: Protocol,
82 suite: SupportedCipherSuite,
83
84 _data: PhantomData<Data>,
85}
86
87impl<Data> KernelConnection<Data> {
88 pub(crate) fn new(state: Box<dyn KernelState>, common: CommonState) -> Result<Self, Error> {
89 Ok(Self {
90 state,
91
92 peer_certificates: common.peer_certificates,
93 quic: common.quic,
94 negotiated_version: common
95 .negotiated_version
96 .ok_or(Error::HandshakeNotComplete)?,
97 protocol: common.protocol,
98 suite: common
99 .suite
100 .ok_or(Error::HandshakeNotComplete)?,
101
102 _data: PhantomData,
103 })
104 }
105
106 /// Retrieves the ciphersuite agreed with the peer.
107 pub fn negotiated_cipher_suite(&self) -> SupportedCipherSuite {
108 self.suite
109 }
110
111 /// Retrieves the protocol version agreed with the peer.
112 pub fn protocol_version(&self) -> ProtocolVersion {
113 self.negotiated_version
114 }
115
116 /// Update the traffic secret used for encrypting messages sent to the peer.
117 ///
118 /// Returns the new traffic secret and initial sequence number to use.
119 ///
120 /// In order to use the new secret you should send a TLS 1.3 key update to
121 /// the peer and then use the new traffic secrets to encrypt any future
122 /// messages.
123 ///
124 /// Note that it is only possible to update the traffic secrets on a TLS 1.3
125 /// connection. Attempting to do so on a non-TLS 1.3 connection will result
126 /// in an error.
127 pub fn update_tx_secret(&mut self) -> Result<(u64, ConnectionTrafficSecrets), Error> {
128 // The sequence number always starts at 0 after a key update.
129 self.state
130 .update_secrets(Direction::Transmit)
131 .map(|secret| (0, secret))
132 }
133
134 /// Update the traffic secret used for decrypting messages received from the
135 /// peer.
136 ///
137 /// Returns the new traffic secret and initial sequence number to use.
138 ///
139 /// You should call this method once you receive a TLS 1.3 key update message
140 /// from the peer.
141 ///
142 /// Note that it is only possible to update the traffic secrets on a TLS 1.3
143 /// connection. Attempting to do so on a non-TLS 1.3 connection will result
144 /// in an error.
145 pub fn update_rx_secret(&mut self) -> Result<(u64, ConnectionTrafficSecrets), Error> {
146 // The sequence number always starts at 0 after a key update.
147 self.state
148 .update_secrets(Direction::Receive)
149 .map(|secret| (0, secret))
150 }
151}
152
153impl KernelConnection<ClientConnectionData> {
154 /// Handle a `new_session_ticket` message from the peer.
155 ///
156 /// This will register the session ticket within with rustls so that it can
157 /// be used to establish future TLS connections.
158 ///
159 /// # Getting the right payload
160 ///
161 /// This method expects to be passed the inner payload of the handshake
162 /// message. This means that you will need to parse the header of the
163 /// handshake message in order to determine the correct payload to pass in.
164 /// The message format is described in [RFC 8446 section 4][0]. `payload`
165 /// should not include the `msg_type` or `length` fields.
166 ///
167 /// Code to parse out the payload should look something like this
168 /// ```no_run
169 /// use rustls::{ContentType, HandshakeType};
170 /// use rustls::kernel::KernelConnection;
171 /// use rustls::client::ClientConnectionData;
172 ///
173 /// # fn doctest(conn: &mut KernelConnection<ClientConnectionData>, typ: ContentType, message: &[u8]) -> Result<(), rustls::Error> {
174 /// let conn: &mut KernelConnection<ClientConnectionData> = // ...
175 /// # conn;
176 /// let typ: ContentType = // ...
177 /// # typ;
178 /// let mut message: &[u8] = // ...
179 /// # message;
180 ///
181 /// // Processing for other messages not included in this example
182 /// assert_eq!(typ, ContentType::Handshake);
183 ///
184 /// // There may be multiple handshake payloads within a single handshake message.
185 /// while !message.is_empty() {
186 /// let (typ, len, rest) = match message {
187 /// &[typ, a, b, c, ref rest @ ..] => (
188 /// HandshakeType::from(typ),
189 /// u32::from_be_bytes([0, a, b, c]) as usize,
190 /// rest
191 /// ),
192 /// _ => panic!("error handling not included in this example")
193 /// };
194 ///
195 /// // Processing for other messages not included in this example.
196 /// assert_eq!(typ, HandshakeType::NewSessionTicket);
197 /// assert!(rest.len() >= len, "invalid handshake message");
198 ///
199 /// let (payload, rest) = rest.split_at(len);
200 /// message = rest;
201 ///
202 /// conn.handle_new_session_ticket(payload)?;
203 /// }
204 /// # Ok(())
205 /// # }
206 /// ```
207 ///
208 /// # Errors
209 /// This method will return an error if:
210 /// - This connection is not a TLS 1.3 connection (in TLS 1.2 session tickets
211 /// are sent as part of the handshake).
212 /// - The provided payload is not a valid `new_session_ticket` payload or has
213 /// extra unparsed trailing data.
214 /// - An error occurs while the connection updates the session ticket store.
215 ///
216 /// [0]: https://datatracker.ietf.org/doc/html/rfc8446#section-4
217 pub fn handle_new_session_ticket(&mut self, payload: &[u8]) -> Result<(), Error> {
218 // We want to return a more specific error here first if this is called
219 // on a non-TLS 1.3 connection since a parsing error isn't the real issue
220 // here.
221 if self.protocol_version() != ProtocolVersion::TLSv1_3 {
222 return Err(Error::General(
223 "TLS 1.2 session tickets may not be sent once the handshake has completed".into(),
224 ));
225 }
226
227 let nst = NewSessionTicketPayloadTls13::read_bytes(payload)?;
228 let mut cx = KernelContext {
229 peer_certificates: self.peer_certificates.as_ref(),
230 protocol: self.protocol,
231 quic: &self.quic,
232 };
233 self.state
234 .handle_new_session_ticket(&mut cx, &nst)
235 }
236}
237
238pub(crate) trait KernelState: Send + Sync {
239 /// Update the traffic secret for the specified direction on the connection.
240 fn update_secrets(&mut self, dir: Direction) -> Result<ConnectionTrafficSecrets, Error>;
241
242 /// Handle a new session ticket.
243 ///
244 /// This will only ever be called for client connections, as [`KernelConnection`]
245 /// only exposes the relevant API for client connections.
246 fn handle_new_session_ticket(
247 &mut self,
248 cx: &mut KernelContext<'_>,
249 message: &NewSessionTicketPayloadTls13,
250 ) -> Result<(), Error>;
251}
252
253pub(crate) struct KernelContext<'a> {
254 pub(crate) peer_certificates: Option<&'a CertificateChain<'static>>,
255 pub(crate) protocol: Protocol,
256 pub(crate) quic: &'a Quic,
257}
258
259impl KernelContext<'_> {
260 pub(crate) fn is_quic(&self) -> bool {
261 self.protocol == Protocol::Quic
262 }
263}
264
265#[derive(Copy, Clone, Debug, Eq, PartialEq)]
266pub(crate) enum Direction {
267 Transmit,
268 Receive,
269}