Debian Codegraph @

crt/s2n/bindings/rust/standard/tls-harness/src/cohort/rustls.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 use crate::{
5 harness::{self, read_to_bytes, Mode, TlsConfigBuilder, TlsConnection, TlsInfo, ViewIO},
6 PemType::{self, *},
7 SigType,
8 };
9 use rustls::{
10 pki_types::{CertificateDer, PrivateKeyDer, ServerName},
11 server::ProducesTickets,
12 ClientConfig, ClientConnection, CommonState, Connection, HandshakeKind,
13 ProtocolVersion::TLSv1_3,
14 RootCertStore, ServerConfig, ServerConnection, SupportedProtocolVersion,
15 };
16 use std::{
17 error::Error,
18 io::{BufReader, Read, Write},
19 rc::Rc,
20 sync::Arc,
21 };
22
23 pub struct RustlsConnection {
24 // the rustls connection has to own the io view, because it is passed as an
25 // argument to read/write rather than being part of the connection configuration
26 io: ViewIO,
27 connection: Connection,
28 }
29
30 impl RustlsConnection {
31 pub fn connection(&self) -> &Connection {
32 &self.connection
33 }
34
35 /// Treat `WouldBlock` as an `Ok` value for when blocking is expected
36 ///
37 /// Blocking is expected during the initial negotiation. Calls to "read_tls"
38 /// will eventually block, because the peer hasn't actually responded to the
39 /// written messages.
40 ///
41 /// Blocking is expected during the reading of application data, because rustls
42 /// will return a WouldBlock error when the record is too large to fit into
43 /// its internal buffer. Following this error Rustls will increase the size
44 /// of the buffer, so that the read call eventually succeeds.
45 /// https://github.com/rustls/rustls/blob/87f37dd44e32b2771fa471a5d8111749ca9e7aa7/rustls/src/msgs/deframer/buffers.rs#L220
46 fn ignore_block<T: Default>(res: Result<T, std::io::Error>) -> Result<T, std::io::Error> {
47 match res {
48 Ok(t) => Ok(t),
49 Err(err) => match err.kind() {
50 std::io::ErrorKind::WouldBlock => Ok(T::default()),
51 _ => Err(err),
52 },
53 }
54 }
55
56 fn connection_common(&self) -> &CommonState {
57 match &self.connection {
58 Connection::Client(client_connection) => client_connection,
59 Connection::Server(server_connection) => server_connection,
60 }
61 }
62 }
63
64 #[derive(Debug)]
65 pub struct NoOpTicketer {}
66
67 impl ProducesTickets for NoOpTicketer {
68 fn enabled(&self) -> bool {
69 false
70 }
71
72 fn lifetime(&self) -> u32 {
73 panic!("session resumption is disabled");
74 }
75
76 fn encrypt(&self, _plain: &[u8]) -> Option<Vec<u8>> {
77 panic!("session resumption is disabled");
78 }
79
80 fn decrypt(&self, _cipher: &[u8]) -> Option<Vec<u8>> {
81 panic!("session resumption is disabled");
82 }
83 }
84
85 impl RustlsConfig {
86 pub fn get_root_cert_store(sig_type: SigType) -> RootCertStore {
87 let mut root_store = RootCertStore::empty();
88 root_store.add_parsable_certificates(
89 rustls_pemfile::certs(&mut BufReader::new(&*read_to_bytes(CACert, sig_type)))
90 .map(|r| r.unwrap()),
91 );
92 root_store
93 }
94
95 pub fn get_cert_chain(pem_type: PemType, sig_type: SigType) -> Vec<CertificateDer<'static>> {
96 rustls_pemfile::certs(&mut BufReader::new(&*read_to_bytes(pem_type, sig_type)))
97 .map(|result| result.unwrap())
98 .collect()
99 }
100
101 pub fn get_key(pem_type: PemType, sig_type: SigType) -> PrivateKeyDer<'static> {
102 let key =
103 rustls_pemfile::read_one(&mut BufReader::new(&*read_to_bytes(pem_type, sig_type)))
104 .unwrap();
105 if let Some(rustls_pemfile::Item::Pkcs8Key(pkcs_8_key)) = key {
106 pkcs_8_key.into()
107 } else {
108 // https://docs.rs/rustls-pemfile/latest/rustls_pemfile/enum.Item.html
109 panic!("unexpected key type: {key:?}");
110 }
111 }
112 }
113
114 /// Clients and servers have different config types in Rustls, so wrap them in an enum
115 pub enum RustlsConfig {
116 Client(Arc<ClientConfig>),
117 Server(Arc<ServerConfig>),
118 }
119
120 impl From<ClientConfig> for RustlsConfig {
121 fn from(value: ClientConfig) -> Self {
122 RustlsConfig::Client(value.into())
123 }
124 }
125
126 impl From<ServerConfig> for RustlsConfig {
127 fn from(value: ServerConfig) -> Self {
128 RustlsConfig::Server(value.into())
129 }
130 }
131
132 impl TlsConnection for RustlsConnection {
133 type Config = RustlsConfig;
134
135 fn new_from_config(
136 mode: harness::Mode,
137 config: &Self::Config,
138 io: &Rc<harness::TestPairIO>,
139 ) -> Result<Self, Box<dyn Error>> {
140 let connection = match config {
141 RustlsConfig::Client(config) => Connection::Client(ClientConnection::new(
142 config.clone(),
143 ServerName::try_from("localhost")?,
144 )?),
145 RustlsConfig::Server(config) => {
146 Connection::Server(ServerConnection::new(config.clone())?)
147 }
148 };
149
150 let io = match mode {
151 Mode::Client => io.client_view(),
152 Mode::Server => io.server_view(),
153 };
154
155 Ok(Self { io, connection })
156 }
157
158 fn handshake(&mut self) -> Result<(), Box<dyn Error>> {
159 Self::ignore_block(self.connection.complete_io(&mut self.io))?;
160 Ok(())
161 }
162
163 fn handshake_completed(&self) -> bool {
164 !self.connection.is_handshaking()
165 }
166
167 fn send(&mut self, data: &[u8]) {
168 let mut write_offset = 0;
169 while write_offset < data.len() {
170 write_offset += self
171 .connection
172 .writer()
173 .write(&data[write_offset..data.len()])
174 .unwrap();
175 self.connection.writer().flush().unwrap();
176 self.connection.complete_io(&mut self.io).unwrap();
177 }
178 }
179
180 fn recv(&mut self, data: &mut [u8]) -> std::io::Result<()> {
181 let data_len = data.len();
182 let mut read_offset = 0;
183 while read_offset < data.len() {
184 self.connection.complete_io(&mut self.io)?;
185 read_offset += Self::ignore_block(
186 self.connection
187 .reader()
188 .read(&mut data[read_offset..data_len]),
189 )?;
190 }
191 Ok(())
192 }
193
194 fn shutdown_send(&mut self) {
195 match &mut self.connection {
196 Connection::Client(client_connection) => client_connection.send_close_notify(),
197 Connection::Server(server_connection) => server_connection.send_close_notify(),
198 }
199 self.connection.write_tls(&mut self.io).unwrap();
200 }
201
202 fn shutdown_finish(&mut self) -> bool {
203 self.connection.read_tls(&mut self.io).unwrap();
204 self.connection.process_new_packets().unwrap();
205
206 let res = self.connection.reader().read(&mut [0]);
207 matches!(res, Ok(0))
208 }
209 }
210
211 impl TlsInfo for RustlsConnection {
212 fn name() -> String {
213 "rustls".to_string()
214 }
215
216 fn get_negotiated_cipher_suite(&self) -> String {
217 // let rustls cipher
218 let version_prefixed_cipher = self
219 .connection
220 .negotiated_cipher_suite()
221 .unwrap()
222 .suite()
223 .as_str()
224 .unwrap();
225 debug_assert!(version_prefixed_cipher.starts_with("TLS13_"));
226 format!(
227 "TLS_{}",
228 version_prefixed_cipher.strip_prefix("TLS13_").unwrap()
229 )
230 }
231
232 fn negotiated_tls13(&self) -> bool {
233 self.connection
234 .protocol_version()
235 .expect("Handshake not completed")
236 == TLSv1_3
237 }
238
239 fn resumed_connection(&self) -> bool {
240 self.connection_common().handshake_kind().unwrap() == HandshakeKind::Resumed
241 }
242
243 fn mutual_auth(&self) -> bool {
244 assert!(matches!(self.connection, Connection::Server(_)));
245 //> For servers, this is the certificate chain or the raw public key of
246 //> the client, if client authentication was completed.
247 //> https://docs.rs/rustls/latest/rustls/struct.CommonState.html#method.peer_certificates
248 self.connection_common().peer_certificates().is_some()
249 }
250 }
251
252 #[derive(Debug, Default)]
253 pub struct RustlsConfigBuilder {
254 mode: Option<Mode>,
255 cert: Option<SigType>,
256 supported_protocols: Vec<&'static SupportedProtocolVersion>,
257 }
258
259 impl TlsConfigBuilder for RustlsConfigBuilder {
260 type Config = RustlsConfig;
261
262 fn new_test_config(mode: Mode) -> Self {
263 Self {
264 mode: Some(mode),
265 supported_protocols: vec![&rustls::version::TLS13],
266 ..Default::default()
267 }
268 }
269
270 fn set_chain(&mut self, sig_type: SigType) {
271 self.cert = Some(sig_type)
272 }
273
274 fn set_trust(&mut self, sig_type: SigType) {
275 self.cert = Some(sig_type)
276 }
277
278 fn build(self) -> Self::Config {
279 let mode = self.mode.unwrap();
280 let cert = self.cert.unwrap();
281
282 let crypto_provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
283 match mode {
284 Mode::Client => ClientConfig::builder_with_provider(crypto_provider)
285 .with_protocol_versions(&self.supported_protocols)
286 .unwrap()
287 .with_root_certificates(RustlsConfig::get_root_cert_store(cert))
288 .with_no_client_auth()
289 .into(),
290 Mode::Server => ServerConfig::builder_with_provider(crypto_provider)
291 .with_protocol_versions(&self.supported_protocols)
292 .unwrap()
293 .with_no_client_auth()
294 .with_single_cert(
295 RustlsConfig::get_cert_chain(ServerCertChain, cert),
296 RustlsConfig::get_key(ServerKey, cert),
297 )
298 .unwrap()
299 .into(),
300 }
301 }
302 }
303
304 impl RustlsConfigBuilder {
305 pub fn set_protocol_versions(
306 &mut self,
307 protocol_versions: &[&'static SupportedProtocolVersion],
308 ) {
309 self.supported_protocols = protocol_versions.to_vec();
310 }
311 }
312
313 #[cfg(test)]
314 mod tests {
315 use super::*;
316 use crate::test_utilities;
317
318 #[test]
319 fn handshake() {
320 test_utilities::handshake::<RustlsConnection, RustlsConfigBuilder>();
321 }
322
323 #[test]
324 fn transfer() {
325 test_utilities::transfer::<RustlsConnection, RustlsConfigBuilder>();
326 }
327 }