Debian Codegraph @

crt/s2n/bindings/rust/standard/tls-harness/src/cohort/boringssl.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 get_cert_path,
6 harness::{self, Mode, TlsConfigBuilder, TlsConnection, TlsInfo, ViewIO},
7 PemType,
8 };
9 use boring::ssl::{
10 ErrorCode, ShutdownResult, Ssl, SslContext, SslContextBuilder, SslFiletype, SslMethod,
11 SslSession, SslStream, SslVersion,
12 };
13 use std::{
14 error::Error,
15 io::{Read, Write},
16 rc::Rc,
17 sync::{Arc, Mutex},
18 };
19
20 // Creates session ticket callback handler
21 #[derive(Clone, Default)]
22 pub struct SessionTicketStorage {
23 pub stored_ticket: Arc<Mutex<Option<SslSession>>>,
24 }
25
26 pub struct BoringSslConnection {
27 mode: Mode,
28 connection: SslStream<ViewIO>,
29 }
30
31 pub struct BoringSslConfig {
32 pub config: SslContext,
33 pub session_ticket_storage: SessionTicketStorage,
34 }
35
36 impl From<SslContext> for BoringSslConfig {
37 fn from(ctx: SslContext) -> Self {
38 BoringSslConfig {
39 config: ctx,
40 session_ticket_storage: Default::default(),
41 }
42 }
43 }
44
45 impl TlsConnection for BoringSslConnection {
46 type Config = BoringSslConfig;
47
48 fn new_from_config(
49 mode: harness::Mode,
50 config: &Self::Config,
51 io: &Rc<harness::TestPairIO>,
52 ) -> Result<Self, Box<dyn Error>> {
53 // Check if there is a session ticket available.
54 // A session ticket will only be available if the Config was created
55 // with session resumption enabled (and a previous handshake stored it).
56 let maybe_ticket = config
57 .session_ticket_storage
58 .stored_ticket
59 .lock()
60 .unwrap()
61 .take();
62
63 // Populate the internal session cache (mirrors the OpenSSL harness pattern).
64 if let Some(ticket) = &maybe_ticket {
65 let _ = unsafe { config.config.add_session(ticket) };
66 }
67
68 let mut ssl = Ssl::new(&config.config)?;
69
70 // If we have a ticket, attempt to resume with it.
71 if let Some(ticket) = &maybe_ticket {
72 unsafe { ssl.set_session(ticket)? };
73 }
74
75 let view = match mode {
76 Mode::Client => io.client_view(),
77 Mode::Server => io.server_view(),
78 };
79
80 let stream = SslStream::new(ssl, view)?;
81 Ok(Self {
82 mode,
83 connection: stream,
84 })
85 }
86
87 fn handshake(&mut self) -> Result<(), Box<dyn Error>> {
88 // If the handshake is already complete, no further work is needed.
89 if self.connection.ssl().is_init_finished() {
90 return Ok(());
91 }
92
93 // Drive handshake based on configured mode.
94 let result = match self.mode {
95 Mode::Server => self.connection.accept(),
96 Mode::Client => self.connection.connect(),
97 };
98
99 match result {
100 // Completed a handshake step — not necessarily “done” yet.
101 Ok(_) => Ok(()),
102
103 // Nonblocking WANT_READ / WANT_WRITE are normal while handshaking.
104 Err(err) => match err.code() {
105 ErrorCode::WANT_READ | ErrorCode::WANT_WRITE => Ok(()),
106 _ => Err(err.into()),
107 },
108 }
109 }
110
111 fn handshake_completed(&self) -> bool {
112 self.connection.ssl().is_init_finished()
113 }
114
115 fn send(&mut self, data: &[u8]) {
116 let mut write_offset = 0;
117 while write_offset < data.len() {
118 write_offset += self.connection.write(&data[write_offset..]).unwrap();
119 self.connection.flush().unwrap(); // make sure internal buffers don't fill up
120 }
121 }
122
123 fn recv(&mut self, data: &mut [u8]) -> std::io::Result<()> {
124 let data_len = data.len();
125 let mut read_offset = 0;
126 while read_offset < data_len {
127 read_offset += self.connection.read(&mut data[read_offset..data_len])?
128 }
129 Ok(())
130 }
131
132 fn shutdown_send(&mut self) {
133 // this method will not read in a CloseNotify
134 assert_eq!(self.connection.shutdown().unwrap(), ShutdownResult::Sent);
135 }
136
137 fn shutdown_finish(&mut self) -> bool {
138 self.connection.shutdown().unwrap() == ShutdownResult::Received
139 }
140 }
141
142 impl TlsInfo for BoringSslConnection {
143 fn name() -> String {
144 "boringssl".to_string()
145 }
146
147 fn get_negotiated_cipher_suite(&self) -> String {
148 self.connection
149 .ssl()
150 .current_cipher()
151 .expect("Handshake not completed")
152 .name()
153 .to_string()
154 }
155
156 fn negotiated_tls13(&self) -> bool {
157 self.connection
158 .ssl()
159 .version2()
160 .expect("Handshake not completed")
161 == SslVersion::TLS1_3
162 }
163
164 fn resumed_connection(&self) -> bool {
165 self.connection.ssl().session_reused()
166 }
167
168 fn mutual_auth(&self) -> bool {
169 assert!(self.connection.ssl().is_server());
170 self.connection.ssl().peer_certificate().is_some()
171 && self.connection.ssl().verify_result().is_ok()
172 }
173 }
174
175 impl TlsConfigBuilder for SslContextBuilder {
176 type Config = BoringSslConfig;
177
178 fn new_test_config(mode: Mode) -> Self {
179 match mode {
180 Mode::Client => SslContext::builder(SslMethod::tls_client()).unwrap(),
181 Mode::Server => SslContext::builder(SslMethod::tls_server()).unwrap(),
182 }
183 }
184
185 fn set_chain(&mut self, sig_type: crate::SigType) {
186 self.set_certificate_chain_file(get_cert_path(PemType::ServerCertChain, sig_type))
187 .unwrap();
188 self.set_private_key_file(
189 get_cert_path(PemType::ServerKey, sig_type),
190 SslFiletype::PEM,
191 )
192 .unwrap();
193 }
194
195 fn set_trust(&mut self, sig_type: crate::SigType) {
196 self.set_ca_file(get_cert_path(PemType::CACert, sig_type))
197 .unwrap();
198 }
199
200 fn build(self) -> Self::Config {
201 BoringSslConfig {
202 config: self.build(),
203 session_ticket_storage: SessionTicketStorage::default(),
204 }
205 }
206 }
207
208 #[cfg(test)]
209 mod tests {
210 use crate::test_utilities;
211
212 use super::*;
213
214 #[test]
215 fn handshake() {
216 test_utilities::handshake::<BoringSslConnection, SslContextBuilder>();
217 }
218
219 #[test]
220 fn transfer() {
221 test_utilities::transfer::<BoringSslConnection, SslContextBuilder>();
222 }
223 }