Debian Codegraph @

crt/s2n/bindings/rust/standard/tls-harness/src/harness/io.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 std::{
5 cell::RefCell,
6 collections::VecDeque,
7 io::{BufRead, ErrorKind},
8 rc::Rc,
9 sync::atomic::{AtomicBool, Ordering},
10 };
11
12 use brass_aphid_wire_decryption::decryption::stream_decrypter::StreamDecrypter;
13 use byteorder::{BigEndian, ReadBytesExt};
14
15 use crate::Mode;
16
17 pub type LocalDataBuffer = RefCell<VecDeque<u8>>;
18
19 #[derive(Debug, Default)]
20 pub struct TestPairIO {
21 /// a data buffer that the server writes to and the client reads from
22 pub server_tx_stream: LocalDataBuffer,
23 /// a data buffer that the client writes to and the server reads from
24 pub client_tx_stream: LocalDataBuffer,
25
26 /// indicates whether all client/server writes should be stored to the
27 /// transcript fields
28 pub recording: AtomicBool,
29 pub client_tx_transcript: RefCell<Vec<u8>>,
30 pub server_tx_transcript: RefCell<Vec<u8>>,
31 /// [`Self::enable_decryption`] will initialize the stream decrypter, which
32 /// allows tests to make assertions on the decrypted TLS transcript.
33 ///
34 /// This is especially useful for TLS 1.3 where much of the handshake is encrypted.
35 pub decrypter: RefCell<Option<StreamDecrypter>>,
36 }
37
38 impl TestPairIO {
39 pub fn client_view(self: &Rc<Self>) -> ViewIO {
40 ViewIO {
41 identity: Mode::Client,
42 io: Rc::clone(self),
43 }
44 }
45
46 pub fn server_view(self: &Rc<Self>) -> ViewIO {
47 ViewIO {
48 identity: Mode::Server,
49 io: Rc::clone(self),
50 }
51 }
52
53 pub fn enable_recording(&self) {
54 self.recording.store(true, Ordering::Relaxed);
55 }
56
57 /// Note: this is only available for TLS 1.3
58 pub fn enable_decryption(
59 &self,
60 keys: brass_aphid_wire_decryption::decryption::key_manager::KeyManager,
61 ) {
62 let stream_decrypter = StreamDecrypter::new(keys);
63 *self.decrypter.borrow_mut() = Some(stream_decrypter);
64 }
65
66 pub fn client_record_sizes(&self) -> Vec<u16> {
67 Self::record_sizes(self.client_tx_transcript.borrow().as_slice()).unwrap()
68 }
69
70 pub fn server_record_sizes(&self) -> Vec<u16> {
71 Self::record_sizes(self.server_tx_transcript.borrow().as_slice()).unwrap()
72 }
73
74 /// Return a list of the record sizes contained in `buffer`.
75 ///
76 /// Note that this is always the length of the outer, obfuscated record, and
77 /// therefore includes padding.
78 ///
79 /// Data is expected to be well formed. If `buffer` contains partial records
80 /// this method will return an error.
81 fn record_sizes(mut buffer: &[u8]) -> std::io::Result<Vec<u16>> {
82 let mut record_lengths = Vec::new();
83 while !buffer.is_empty() {
84 let _content_type = buffer.read_u8()?;
85 let _protocol = buffer.read_u16::<BigEndian>()?;
86 let length = buffer.read_u16::<BigEndian>()?;
87 record_lengths.push(length);
88 buffer.consume(length as usize);
89 }
90 Ok(record_lengths)
91 }
92 }
93
94 /// A "view" of the IO.
95 ///
96 /// This view is client/server specific, and notably implements the read and write
97 /// traits.
98 pub struct ViewIO {
99 pub identity: Mode,
100 pub io: Rc<TestPairIO>,
101 }
102
103 impl ViewIO {
104 fn recv_ctx(&self) -> &LocalDataBuffer {
105 match self.identity {
106 Mode::Client => &self.io.server_tx_stream,
107 Mode::Server => &self.io.client_tx_stream,
108 }
109 }
110
111 fn send_ctx(&self) -> &LocalDataBuffer {
112 match self.identity {
113 Mode::Client => &self.io.client_tx_stream,
114 Mode::Server => &self.io.server_tx_stream,
115 }
116 }
117
118 fn send_transcript(&self) -> &RefCell<Vec<u8>> {
119 match self.identity {
120 Mode::Client => &self.io.client_tx_transcript,
121 Mode::Server => &self.io.server_tx_transcript,
122 }
123 }
124 }
125
126 impl std::io::Read for ViewIO {
127 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
128 let res = self.recv_ctx().borrow_mut().read(buf);
129 tracing::debug!("{:?} read {:?}", self.identity, res);
130
131 if let Ok(0) = res {
132 // We are "faking" a TcpStream, where a read of length 0 indicates
133 // EoF. That is incorrect for this scenario. Instead we return WouldBlock
134 // to indicate that there is simply no more data to be read.
135 Err(std::io::Error::new(ErrorKind::WouldBlock, "blocking"))
136 } else {
137 res
138 }
139 }
140 }
141
142 impl std::io::Write for ViewIO {
143 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
144 let write_result = self.send_ctx().borrow_mut().write(buf);
145 tracing::debug!("{:?} wrote {:?}", self.identity, write_result);
146
147 // if we successfully wrote data, we need to record it in the various test
148 // utilities.
149 if let Ok(written) = write_result {
150 // recorder
151 if self.io.recording.load(Ordering::Relaxed) {
152 self.send_transcript()
153 .borrow_mut()
154 .write_all(&buf[0..written])
155 .unwrap();
156 }
157
158 // decrypter
159 let mut decrypter = self.io.decrypter.borrow_mut();
160 if let Some(decrypter) = decrypter.as_mut() {
161 let wire_mode = match self.identity {
162 Mode::Client => brass_aphid_wire_decryption::decryption::Mode::Client,
163 Mode::Server => brass_aphid_wire_decryption::decryption::Mode::Server,
164 };
165 decrypter.record_tx(&buf[0..written], wire_mode);
166 decrypter.decrypt_records(wire_mode).unwrap();
167 }
168 }
169
170 write_result
171 }
172
173 fn flush(&mut self) -> std::io::Result<()> {
174 Ok(())
175 }
176 }
177
178 #[cfg(test)]
179 mod tests {
180 use std::collections::HashMap;
181
182 use openssl::ssl::SslContextBuilder;
183
184 use crate::{
185 cohort::{rustls::RustlsConfigBuilder, OpenSslConnection, RustlsConnection, S2NConnection},
186 harness::TlsConfigBuilderPair,
187 TlsConnPair,
188 };
189
190 use super::*;
191
192 #[test]
193 fn recording_off_by_default() {
194 let io = TestPairIO::default();
195 assert!(!io.recording.load(Ordering::Relaxed));
196 }
197
198 /// return the most frequently occurring number in `data`
199 fn mode(data: &Vec<u16>) -> u16 {
200 let mut count: HashMap<u16, usize> = HashMap::new();
201 for d in data {
202 let count = count.entry(*d).or_default();
203 *count += 1;
204 }
205
206 let mut counts: Vec<(u16, usize)> = count.into_iter().collect();
207 counts.sort_by_key(|(_element, count)| *count);
208 counts.last().unwrap().0
209 }
210
211 /// our "record size" methods should correctly report the defaults for various
212 /// implementations
213 #[test]
214 fn implementation_record_size() {
215 const S2N_RECORD_DEFAULT: u16 = 8104;
216 const OPENSSL_RECORD_DEFAULT: u16 = 16401;
217 const RUSTLS_RECORD_DEFAULT: u16 = 16401;
218
219 // openssl & s2n
220 {
221 let mut pair: TlsConnPair<OpenSslConnection, S2NConnection> = {
222 let configs =
223 TlsConfigBuilderPair::<SslContextBuilder, s2n_tls::config::Builder>::default();
224 configs.connection_pair()
225 };
226 pair.io.enable_recording();
227
228 pair.handshake().unwrap();
229 assert!(pair.round_trip_assert(100_000).is_ok());
230 pair.shutdown().unwrap();
231
232 let openssl_record = mode(&pair.io.client_record_sizes());
233 let s2n_record = mode(&pair.io.server_record_sizes());
234
235 assert_eq!(openssl_record, OPENSSL_RECORD_DEFAULT);
236 assert_eq!(s2n_record, S2N_RECORD_DEFAULT);
237 }
238
239 // s2n & rustls
240 {
241 let mut pair: TlsConnPair<S2NConnection, RustlsConnection> = {
242 let configs =
243 TlsConfigBuilderPair::<s2n_tls::config::Builder, RustlsConfigBuilder>::default(
244 );
245 configs.connection_pair()
246 };
247 pair.io.enable_recording();
248
249 pair.handshake().unwrap();
250 assert!(pair.round_trip_assert(100_000).is_ok());
251 pair.shutdown().unwrap();
252
253 let s2n_record = mode(&pair.io.client_record_sizes());
254 let rustls_record = mode(&pair.io.server_record_sizes());
255
256 assert_eq!(s2n_record, S2N_RECORD_DEFAULT);
257 assert_eq!(rustls_record, RUSTLS_RECORD_DEFAULT);
258 }
259 }
260 }