Debian Codegraph @

crt/s2n/bindings/rust/extended/s2n-tls/src/testing.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 callbacks::{SessionTicketCallback, VerifyHostNameCallback},
6 cert_chain::{self, CertificateChain},
7 config::{self, *},
8 connection,
9 enums::{self, Blinding},
10 error, security,
11 };
12 use alloc::{collections::VecDeque, sync::Arc};
13
14 use core::{
15 sync::atomic::{AtomicUsize, Ordering},
16 task::Poll,
17 };
18 use libc::{c_int, c_void};
19 use std::{
20 cell::RefCell,
21 io::{Read, Write},
22 pin::Pin,
23 sync::Mutex,
24 };
25
26 pub mod client_hello;
27 pub mod resumption;
28 pub mod s2n_tls;
29
30 type Error = Box<dyn std::error::Error>;
31 type Result<T, E = Error> = core::result::Result<T, E>;
32
33 pub fn test_error(msg: &str) -> crate::error::Error {
34 crate::error::Error::application(msg.into())
35 }
36
37 pub fn assert_test_error(input: crate::error::Error, expected_message: &str) {
38 let error_msg = input
39 .application_error()
40 .expect("unexpected error type")
41 .to_string();
42 assert_eq!(expected_message, error_msg.to_string())
43 }
44
45 #[derive(Clone)]
46 pub struct Counter(Arc<AtomicUsize>);
47 impl Counter {
48 fn new() -> Self {
49 Counter(Arc::new(AtomicUsize::new(0)))
50 }
51 pub fn count(&self) -> usize {
52 self.0.load(Ordering::Relaxed)
53 }
54 pub fn increment(&self) {
55 self.0.fetch_add(1, Ordering::Relaxed);
56 }
57 }
58 impl Default for Counter {
59 fn default() -> Self {
60 Self::new()
61 }
62 }
63
64 #[allow(non_camel_case_types)]
65 // allow non camel case types because the mixture of letters and numbers is easier
66 // to read with snake_case.
67 pub enum SniTestCerts {
68 AlligatorRsa,
69 AlligatorEcdsa,
70 BeaverRsa,
71 WildcardInsectRsa,
72 }
73
74 impl SniTestCerts {
75 pub fn get(&self) -> CertKeyPair {
76 let prefix = match *self {
77 SniTestCerts::AlligatorRsa => "alligator_",
78 SniTestCerts::AlligatorEcdsa => "alligator_ecdsa_",
79 SniTestCerts::BeaverRsa => "beaver_",
80 SniTestCerts::WildcardInsectRsa => "wildcard_insect_rsa_",
81 };
82 CertKeyPair::from_path(&format!("sni/{prefix}"), "cert", "key", "cert")
83 }
84 }
85
86 #[derive(Clone)]
87 pub struct CertKeyPair {
88 cert_path: String,
89 key_path: String,
90 ca_path: String,
91 cert: Vec<u8>,
92 key: Vec<u8>,
93 ca_cert: Vec<u8>,
94 }
95
96 impl Default for CertKeyPair {
97 fn default() -> Self {
98 Self::from_path("rsa_4096_sha512_client_", "cert", "key", "cert")
99 }
100 }
101
102 impl CertKeyPair {
103 /// This is the directory holding all of the pems used for s2n-tls unit tests
104 const TEST_PEMS_PATH: &'static str =
105 concat!(env!("CARGO_MANIFEST_DIR"), "/../../../../tests/pems/");
106
107 /// Create a test CertKeyPair
108 /// * `prefix`: The *relative* prefix from the s2n-tls/tests/pems/ folder.
109 /// * `chain`: The suffix indicate the full chain.
110 /// * `key`: The suffix indicate the private key.
111 /// * `ca`: The suffix indicating the CA.
112 ///
113 /// ### Example
114 /// Assuming the relevant files are at
115 /// - s2n-tls/tests/pems/permutations/rsae_pkcs_4096_sha384/server-chain.pem
116 /// - s2n-tls/tests/pems/permutations/rsae_pkcs_4096_sha384/server-key.pem
117 /// - s2n-tls/tests/pems/permutations/rsae_pkcs_4096_sha384/ca-cert.pem
118 ///
119 /// ```ignore
120 /// let cert = CertKeyPair::from(
121 /// "permutations/rsae_pkcs_4096_sha384/",
122 /// "server-chain",
123 /// "server-key",
124 /// "ca-cert"
125 /// );
126 /// ```
127 pub fn from_path(prefix: &str, chain: &str, key: &str, ca: &str) -> Self {
128 let cert_path = format!("{}{prefix}{chain}.pem", Self::TEST_PEMS_PATH);
129 let key_path = format!("{}{prefix}{key}.pem", Self::TEST_PEMS_PATH);
130 let ca_path = format!("{}{prefix}{ca}.pem", Self::TEST_PEMS_PATH);
131 let cert = std::fs::read(&cert_path)
132 .unwrap_or_else(|_| panic!("Failed to read cert at {cert_path}"));
133 let key =
134 std::fs::read(&key_path).unwrap_or_else(|_| panic!("Failed to read key at {key_path}"));
135 let ca_cert =
136 std::fs::read(&ca_path).unwrap_or_else(|_| panic!("Failed to read cert at {ca_path}"));
137 CertKeyPair {
138 cert_path,
139 key_path,
140 ca_path,
141 cert,
142 key,
143 ca_cert,
144 }
145 }
146
147 pub fn into_certificate_chain(&self) -> CertificateChain<'static> {
148 let mut chain = cert_chain::Builder::new().unwrap();
149 chain.load_pem(&self.cert, &self.key).unwrap();
150 chain.build().unwrap()
151 }
152
153 pub fn cert_path(&self) -> &str {
154 &self.cert_path
155 }
156
157 pub fn key_path(&self) -> &str {
158 &self.key_path
159 }
160
161 pub fn ca_path(&self) -> &str {
162 &self.ca_path
163 }
164
165 pub fn cert(&self) -> &[u8] {
166 &self.cert
167 }
168
169 pub fn key(&self) -> &[u8] {
170 &self.key
171 }
172
173 pub fn ca_cert(&self) -> &[u8] {
174 &self.ca_cert
175 }
176 }
177
178 pub struct InsecureAcceptAllCertificatesHandler {}
179 impl VerifyHostNameCallback for InsecureAcceptAllCertificatesHandler {
180 fn verify_host_name(&self, _host_name: &str) -> bool {
181 true
182 }
183 }
184
185 pub struct RejectAllCertificatesHandler {}
186 impl VerifyHostNameCallback for RejectAllCertificatesHandler {
187 fn verify_host_name(&self, _host_name: &str) -> bool {
188 false
189 }
190 }
191
192 pub fn build_config(cipher_prefs: &security::Policy) -> Result<crate::config::Config, Error> {
193 let builder = config_builder(cipher_prefs)?;
194 Ok(builder.build().expect("Unable to build server config"))
195 }
196
197 pub fn config_builder(cipher_prefs: &security::Policy) -> Result<crate::config::Builder, Error> {
198 let mut builder = Builder::new();
199 let keypair = CertKeyPair::default();
200 // Build a config
201 builder
202 .set_security_policy(cipher_prefs)
203 .expect("Unable to set config cipher preferences");
204 builder
205 .load_pem(keypair.cert(), keypair.key())
206 .expect("Unable to load cert/pem");
207 builder
208 .set_verify_host_callback(InsecureAcceptAllCertificatesHandler {})
209 .expect("Unable to set a host verify callback.");
210 builder.with_system_certs(false).unwrap();
211 builder.trust_pem(keypair.cert()).expect("load cert pem");
212 Ok(builder)
213 }
214
215 type LocalDataBuffer = RefCell<VecDeque<u8>>;
216
217 #[derive(Debug)]
218 // We allow dead_code, because otherwise the compiler complains about the tx_streams
219 // never being read. This is because it can't reason through the pointers that were
220 // passed into the s2n-tls connection io contexts.
221 #[allow(dead_code)]
222 pub struct TestPairIO {
223 // Pin: since we are dereferencing this pointer (because it is passed as the send/recv ctx)
224 // we need to ensure that the pointer remains in the same place
225 // Box: A Vec (or VecDeque) may be moved or reallocated, so we need another layer of
226 // indirection to have a stable (pinned) reference
227 /// a data buffer that the server writes to and the client reads from
228 pub server_tx_stream: Pin<Box<LocalDataBuffer>>,
229 /// a data buffer that the client writes to and the server reads from
230 pub client_tx_stream: Pin<Box<LocalDataBuffer>>,
231 }
232
233 /// TestPair is a testing utility used to easily test handshakes and send data.
234 ///
235 /// SAFETY: if the server or client connection is moved outside of the struct, IO
236 /// is not safe to perform. The connections use pointers to data buffers owned by
237 /// the Harness. If the Harness goes out of scope, the data buffers will be dropped
238 /// and the pointers will be invalid.
239 ///
240 /// The most common usecase is handshaking a simple config.
241 /// ```ignore
242 /// // given some config
243 /// let config = build_config(&crate::security::DEFAULT_TLS13).unwrap();
244 /// // create a pair (client + server) with uses that config
245 /// let mut pair = TestPair::from_config(&config);
246 /// // assert a successful handshake
247 /// assert!(pair.handshake().is_ok());
248 /// // we can also do IO using the poll_* functions
249 /// // this data is sent using the shared data buffers owned by the harness
250 /// assert!(pair.server.poll_send(&[3, 1, 4]).is_ready());
251 /// let mut buffer = [0; 3];
252 /// assert!(pair.client.poll_recv(&mut buffer).is_ready());
253 /// assert_eq!([3, 1, 4], buffer);
254 /// ```
255 //
256 // The doctest is `ignore`d because testing utilities are not publicly exported
257 // and therefore can't be referenced in a doc comment.
258 pub struct TestPair {
259 pub server: connection::Connection,
260 pub client: connection::Connection,
261 pub io: TestPairIO,
262 }
263
264 impl TestPair {
265 /// utility method to test simple handshakes
266 ///
267 /// Create a client and server from the associated `config`, and try to complete
268 /// a TLS handshake. The result of the handshake is returned.
269 pub fn handshake_with_config(config: &config::Config) -> Result<(), error::Error> {
270 Self::from_configs(config, config).handshake()
271 }
272
273 /// create a pair from a config
274 ///
275 /// A server and client connection will be created, and both will be associated
276 /// with `config`. The connections will be setup for IO over shared memory,
277 /// but no IO is performed. To handshake the connections, call `handshake()`.
278 pub fn from_config(config: &config::Config) -> Self {
279 Self::from_configs(config, config)
280 }
281
282 pub fn from_configs(client_config: &config::Config, server_config: &config::Config) -> Self {
283 // import in smallest namespace to avoid collision with config::Builder;
284 use crate::connection::Builder;
285
286 let client = client_config.build_connection(enums::Mode::Client).unwrap();
287 let server = server_config.build_connection(enums::Mode::Server).unwrap();
288
289 Self::from_connections(client, server)
290 }
291
292 pub fn from_connections(
293 mut client: connection::Connection,
294 mut server: connection::Connection,
295 ) -> Self {
296 let client_tx_stream = Box::pin(Default::default());
297 let server_tx_stream = Box::pin(Default::default());
298
299 Self::register_connection(&mut client, &client_tx_stream, &server_tx_stream).unwrap();
300
301 Self::register_connection(&mut server, &server_tx_stream, &client_tx_stream).unwrap();
302
303 let io = TestPairIO {
304 server_tx_stream,
305 client_tx_stream,
306 };
307 Self { server, client, io }
308 }
309
310 /// create a connection ready for harness IO
311 ///
312 /// This mostly consists of setting the IO callbacks and the IO contexts.
313 ///
314 /// We also set blinding to "SelfService" to avoid long delays after failures
315 /// in unit tests. However, this will cause calls to `poll_shutdown` to return
316 /// Poll::Pending until the blinding delay elapses.
317 fn register_connection(
318 conn: &mut connection::Connection,
319 send_ctx: &Pin<Box<LocalDataBuffer>>,
320 recv_ctx: &Pin<Box<LocalDataBuffer>>,
321 ) -> Result<(), error::Error> {
322 conn.set_blinding(Blinding::SelfService)?
323 .set_send_callback(Some(Self::send_cb))?
324 .set_receive_callback(Some(Self::recv_cb))?;
325 unsafe {
326 // cast 1 : send_ctx as &LocalDataBuffer -> get a plain reference to underlying LocalDataBuffer
327 //
328 // cast 2: &LocalDataBuffer as *const LocalDataBuffer -> cast the reference to a pointer
329 // SAFETY: the LocalDataBuffer must live as long as the connection does. This can be violated if the
330 // connections are moved out from the struct.
331 //
332 // cast 3: *const LocalDataBuffer as *mut c_void -> cast into the final *mut c_void required
333 // SAFETY: serialized access is enforced by the interior RefCell, so it is safe to vend out
334 // multiple mutable pointers to this item. We ensure this by casting back to an immutable
335 // reference in the send and recv callbacks
336 conn.set_send_context(
337 send_ctx as &LocalDataBuffer as *const LocalDataBuffer as *mut c_void,
338 )?
339 .set_receive_context(
340 recv_ctx as &LocalDataBuffer as *const LocalDataBuffer as *mut c_void,
341 )?;
342 }
343 Ok(())
344 }
345
346 /// perform a TLS handshake between the connections
347 ///
348 /// This method will call `poll_negotiate` on each connection until both return
349 /// Ready(Ok) which indicates a successful handshake, or until one of the connections
350 /// returns Ready(Err) which indicates some fatal error.
351 pub fn handshake(&mut self) -> Result<(), error::Error> {
352 loop {
353 match (self.client.poll_negotiate(), self.server.poll_negotiate()) {
354 // if everything is finished and Ok, return Ok
355 (Poll::Ready(Ok(_)), Poll::Ready(Ok(_))) => return Ok(()),
356 // if there has been an error on the server
357 (_, Poll::Ready(Err(e))) => return Err(e),
358 // or an error on the client, then return the error
359 (Poll::Ready(Err(e)), _) => return Err(e),
360 // not ready, poll again
361 _ => {}
362 }
363 }
364 }
365
366 pub(crate) unsafe extern "C" fn send_cb(
367 context: *mut c_void,
368 data: *const u8,
369 len: u32,
370 ) -> c_int {
371 let context = &*(context as *const LocalDataBuffer);
372 let data = core::slice::from_raw_parts(data, len as _);
373 let bytes_written = context.borrow_mut().write(data).unwrap();
374 bytes_written as c_int
375 }
376
377 // Note: this callback will be invoked multiple times in the event that
378 // the byte-slices of the VecDeque are not contiguous (wrap around).
379 pub(crate) unsafe extern "C" fn recv_cb(
380 context: *mut c_void,
381 data: *mut u8,
382 len: u32,
383 ) -> c_int {
384 let context = &*(context as *const LocalDataBuffer);
385 let data = core::slice::from_raw_parts_mut(data, len as _);
386 match context.borrow_mut().read(data) {
387 Ok(len) => {
388 if len == 0 {
389 // returning a length of 0 indicates a channel close (e.g. a
390 // TCP Close) which would not be correct here. To just communicate
391 // that there is no more data, we instead set the errno to
392 // WouldBlock and return -1.
393 errno::set_errno(errno::Errno(libc::EWOULDBLOCK));
394 -1
395 } else {
396 len as c_int
397 }
398 }
399 Err(err) => {
400 // VecDeque IO Operations should never fail
401 panic!("{err:?}");
402 }
403 }
404 }
405 }
406
407 type SessionState = Vec<u8>;
408
409 /// This is a simple struct to enable session resumption in unit tests.
410 ///
411 /// It will store all tickets that it gets from the server, and offering them in
412 /// a last-in, first-out manner through the connection initializer.
413 #[derive(Debug, Clone, Default)]
414 pub struct LIFOSessionResumption {
415 pub ticket: Arc<Mutex<Vec<SessionState>>>,
416 }
417
418 impl SessionTicketCallback for LIFOSessionResumption {
419 fn on_session_ticket(
420 &self,
421 _connection: &mut connection::Connection,
422 session_ticket: &crate::callbacks::SessionTicket,
423 ) {
424 println!("got a session ticket of {}", session_ticket.len().unwrap());
425 let mut ticket_buffer = vec![0; session_ticket.len().unwrap()];
426 session_ticket.data(&mut ticket_buffer).unwrap();
427 self.ticket.lock().unwrap().push(ticket_buffer);
428 }
429 }
430
431 impl ConnectionInitializer for LIFOSessionResumption {
432 fn initialize_connection(
433 &self,
434 connection: &mut crate::connection::Connection,
435 ) -> crate::callbacks::ConnectionFutureResult {
436 let latest_ticket = self.ticket.lock().unwrap().pop();
437 if let Some(ticket) = latest_ticket {
438 connection.set_session_ticket(&ticket).unwrap();
439 }
440 Ok(None)
441 }
442 }