Debian Codegraph @

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

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3 mod io;
4 pub use io::{LocalDataBuffer, TestPairIO, ViewIO};
5
6 use std::{error::Error, fmt::Debug, fs::read_to_string, rc::Rc};
7 use strum::EnumIter;
8
9 #[derive(Clone, Copy, EnumIter)]
10 pub enum PemType {
11 ServerKey,
12 ServerCertChain,
13 ClientKey,
14 ClientCertChain,
15 CACert,
16 }
17
18 impl PemType {
19 fn get_filename(&self) -> &str {
20 match self {
21 PemType::ServerKey => "server-key.pem",
22 PemType::ServerCertChain => "server-chain.pem",
23 PemType::ClientKey => "client-key.pem",
24 PemType::ClientCertChain => "client-cert.pem",
25 PemType::CACert => "ca-cert.pem",
26 }
27 }
28 }
29
30 #[derive(Clone, Copy, Default, EnumIter)]
31 pub enum SigType {
32 #[default]
33 Rsa2048,
34 Rsa3072,
35 Rsa4096,
36 Ecdsa384,
37 Ecdsa256,
38 }
39
40 impl SigType {
41 pub fn get_dir_name(&self) -> &str {
42 match self {
43 SigType::Rsa2048 => "rsa2048",
44 SigType::Rsa3072 => "rsa3072",
45 SigType::Rsa4096 => "rsa4096",
46 SigType::Ecdsa384 => "ecdsa384",
47 SigType::Ecdsa256 => "ecdsa256",
48 }
49 }
50 }
51
52 impl Debug for SigType {
53 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54 write!(f, "{}", self.get_dir_name())
55 }
56 }
57
58 pub fn get_cert_path(pem_type: PemType, sig_type: SigType) -> String {
59 const TEST_PEMS_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/certs");
60
61 format!(
62 "{TEST_PEMS_PATH}/{}/{}",
63 sig_type.get_dir_name(),
64 pem_type.get_filename()
65 )
66 }
67
68 pub fn read_to_bytes(pem_type: PemType, sig_type: SigType) -> Vec<u8> {
69 read_to_string(get_cert_path(pem_type, sig_type))
70 .unwrap()
71 .into_bytes()
72 }
73
74 #[derive(Debug, Clone, Copy)]
75 pub enum Mode {
76 Client,
77 Server,
78 }
79
80 /// The TlsConnection object can be created from a corresponding config type.
81 pub trait TlsConnection: Sized {
82 /// Library-specific config struct
83 type Config;
84
85 /// Make connection from existing config and buffer
86 fn new_from_config(
87 mode: Mode,
88 config: &Self::Config,
89 io: &Rc<TestPairIO>,
90 ) -> Result<Self, Box<dyn Error>>;
91
92 /// Run one handshake step: receive msgs from other connection, process, and send new msgs
93 fn handshake(&mut self) -> Result<(), Box<dyn Error>>;
94
95 fn handshake_completed(&self) -> bool;
96
97 /// Send `data` to the peer.
98 ///
99 /// Send is infailable because it communicates over local memory.
100 fn send(&mut self, data: &[u8]);
101
102 /// Read application data from the peer into `data`.
103 fn recv(&mut self, data: &mut [u8]) -> std::io::Result<()>;
104
105 /// Send a `CloseNotify` to the peer.
106 ///
107 /// This does not read the `CloseNotify` from the peer.
108 ///
109 /// Must be followed by a call to [`TlsConnection::shutdown_finish`] to ensure
110 /// that any `CloseNotify` alerts from the peer are read.
111 fn shutdown_send(&mut self);
112
113 /// Attempt to read the `CloseNotify` from the peer.
114 ///
115 /// Returns `true` if the connection was successfully shutdown, `false` otherwise.
116 ///
117 /// The `CloseNotify` might already have been read by `shutdown_send`, depending
118 /// on the order of client/server [`TlsConnection::shutdown_send`] calls.
119 fn shutdown_finish(&mut self) -> bool;
120 }
121
122 pub trait TlsInfo: Sized {
123 fn name() -> String;
124
125 /// Return the IANA Description of the negotiated cipher suite.
126 ///
127 /// e.g. `TLS_AES_256_GCM_SHA384`
128 fn get_negotiated_cipher_suite(&self) -> String;
129
130 fn negotiated_tls13(&self) -> bool;
131
132 /// Describes whether a connection was resumed.
133 fn resumed_connection(&self) -> bool;
134
135 /// For the rustls & openssl implementations, this only works for servers.
136 fn mutual_auth(&self) -> bool;
137 }
138
139 pub trait TlsConfigBuilder {
140 /// The config produced by the [`TlsConfigBuilder::build`] operation.
141 type Config;
142
143 fn new_test_config(mode: Mode) -> Self;
144
145 /// Load a chain onto a config.
146 ///
147 /// This is most often used for servers.
148 fn set_chain(&mut self, sig_type: SigType);
149
150 /// Load a cert into a trust store.
151 ///
152 /// This is most often used for clients.
153 fn set_trust(&mut self, sig_type: SigType);
154
155 fn build(self) -> Self::Config;
156 }
157
158 /// A TlsConnPair owns the client and server tls connections along with the IO buffers.
159 pub struct TlsConnPair<C, S> {
160 pub client: C,
161 pub server: S,
162 pub io: Rc<TestPairIO>,
163 }
164
165 impl<C, S> TlsConnPair<C, S>
166 where
167 C: TlsConnection,
168 S: TlsConnection,
169 {
170 pub fn from_configs(client_config: &C::Config, server_config: &S::Config) -> Self {
171 let io = Rc::new(TestPairIO::default());
172 let client = C::new_from_config(Mode::Client, client_config, &io).unwrap();
173 let server = S::new_from_config(Mode::Server, server_config, &io).unwrap();
174 Self { client, server, io }
175 }
176
177 pub fn client(&self) -> &C {
178 &self.client
179 }
180
181 pub fn client_mut(&mut self) -> &mut C {
182 &mut self.client
183 }
184
185 pub fn server(&self) -> &S {
186 &self.server
187 }
188
189 pub fn server_mut(&mut self) -> &mut S {
190 &mut self.server
191 }
192
193 /// Run the TLS handshake between client and server until both report completion.
194 /// Continues until the handshake is finished and neither side exchanges
195 /// additional handshake or post-handshake data.
196 pub fn handshake(&mut self) -> Result<(), Box<dyn Error>> {
197 // Keep looping while handshake not complete or progress is still being made
198 while !self.handshake_completed() {
199 self.client.handshake()?;
200 self.server.handshake()?;
201 }
202 Ok(())
203 }
204
205 /// Checks if handshake is finished for both client and server
206 pub fn handshake_completed(&self) -> bool {
207 self.client.handshake_completed() && self.server.handshake_completed()
208 }
209
210 /// Send data from client to server, and then from server to client
211 pub fn round_trip_transfer(&mut self, data: &mut [u8]) -> std::io::Result<()> {
212 // send data from client to server
213 self.client.send(data);
214 self.server.recv(data)?;
215
216 // send data from server to client
217 self.server.send(data);
218 self.client.recv(data)?;
219
220 Ok(())
221 }
222
223 pub fn shutdown(&mut self) -> Result<(), Box<dyn Error>> {
224 // These assertions do not _have_ to be true, but you are likely making
225 // a mistake if you are hitting it. Generally all data should have been
226 // read before attempting to shutdown
227 assert_eq!(self.io.client_tx_stream.borrow().len(), 0);
228 assert_eq!(self.io.server_tx_stream.borrow().len(), 0);
229
230 self.client.shutdown_send();
231 self.server.shutdown_send();
232
233 let client_shutdown = self.client.shutdown_finish();
234 let server_shutdown = self.server.shutdown_finish();
235 if client_shutdown && server_shutdown {
236 Ok(())
237 } else {
238 Err(
239 format!("Shutdown Failed: client - {client_shutdown} server - {server_shutdown}")
240 .into(),
241 )
242 }
243 }
244
245 /// transfer `data_size` bytes between the client and the server.
246 pub fn round_trip_assert(&mut self, data_size: usize) -> std::io::Result<()> {
247 // we don't need "cryptographically random" data, just some non-zero data
248 let mut random_data: Vec<u8> = (0..data_size).map(|i| (i * 101 % 256) as u8).collect();
249 self.round_trip_transfer(&mut random_data)
250 }
251 }
252
253 impl<C, S> TlsConnPair<C, S>
254 where
255 C: TlsInfo,
256 S: TlsInfo,
257 {
258 pub fn get_negotiated_cipher_suite(&self) -> String {
259 assert!(
260 self.client.get_negotiated_cipher_suite() == self.server.get_negotiated_cipher_suite()
261 );
262 self.client.get_negotiated_cipher_suite()
263 }
264
265 pub fn negotiated_tls13(&self) -> bool {
266 self.client.negotiated_tls13() && self.server.negotiated_tls13()
267 }
268 }
269
270 pub struct TlsConfigBuilderPair<C, S> {
271 pub client: C,
272 pub server: S,
273 }
274
275 impl<C, S> Default for TlsConfigBuilderPair<C, S>
276 where
277 C: TlsConfigBuilder,
278 S: TlsConfigBuilder,
279 {
280 fn default() -> Self {
281 let mut pair = Self {
282 client: C::new_test_config(Mode::Client),
283 server: S::new_test_config(Mode::Server),
284 };
285
286 // set an RSA2048 cert as the default, because it is the most common
287 // cert type.
288 pair.client.set_trust(SigType::Rsa2048);
289 pair.server.set_chain(SigType::Rsa2048);
290 pair
291 }
292 }
293
294 impl<C, S> TlsConfigBuilderPair<C, S>
295 where
296 C: TlsConfigBuilder,
297 S: TlsConfigBuilder,
298 {
299 // Creates a new `TlsConfigBuilderPair` without loading any default certificate.
300 pub fn default_without_certs() -> Self {
301 Self {
302 client: C::new_test_config(Mode::Client),
303 server: S::new_test_config(Mode::Server),
304 }
305 }
306
307 pub fn set_cert(&mut self, cert: SigType) {
308 self.client.set_trust(cert);
309 self.server.set_chain(cert);
310 }
311
312 pub fn build(self) -> (C::Config, S::Config) {
313 (self.client.build(), self.server.build())
314 }
315
316 pub fn connection_pair<ClientConn, ServerConn>(self) -> TlsConnPair<ClientConn, ServerConn>
317 where
318 ClientConn: TlsConnection<Config = C::Config>,
319 ServerConn: TlsConnection<Config = S::Config>,
320 {
321 let (client_config, server_config) = self.build();
322 TlsConnPair::from_configs(&client_config, &server_config)
323 }
324 }
325
326 #[cfg(test)]
327 mod tests {
328 use super::*;
329 use std::path::Path;
330 use strum::IntoEnumIterator;
331
332 #[test]
333 fn test_cert_paths_valid() {
334 for pem_type in PemType::iter() {
335 for sig_type in SigType::iter() {
336 assert!(
337 Path::new(&get_cert_path(pem_type, sig_type)).exists(),
338 "cert not found"
339 );
340 }
341 }
342 }
343 }