Debian Codegraph @

crt/s2n/bindings/rust/standard/tls-harness/src/cohort/openssl.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 openssl::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 impl SessionTicketStorage {
27 // panics if no ticket is available
28 pub fn get_ticket(self) -> SslSession {
29 self.stored_ticket.lock().unwrap().take().unwrap()
30 }
31 }
32
33 pub struct OpenSslConnection {
34 pub connection: SslStream<ViewIO>,
35 }
36
37 pub struct OpenSslConfig {
38 pub config: SslContext,
39 pub session_ticket_storage: SessionTicketStorage,
40 }
41
42 impl From<SslContext> for OpenSslConfig {
43 fn from(value: SslContext) -> Self {
44 OpenSslConfig {
45 config: value,
46 session_ticket_storage: Default::default(),
47 }
48 }
49 }
50
51 impl TlsConnection for OpenSslConnection {
52 type Config = OpenSslConfig;
53
54 fn new_from_config(
55 mode: harness::Mode,
56 config: &Self::Config,
57 io: &Rc<harness::TestPairIO>,
58 ) -> Result<Self, Box<dyn Error>> {
59 // check if there is a session ticket available
60 // a session ticket will only be available if the Config was created
61 // with session resumption enabled
62 let maybe_ticket = config
63 .session_ticket_storage
64 .stored_ticket
65 .lock()
66 .unwrap()
67 .take();
68 if let Some(ticket) = &maybe_ticket {
69 let _result = unsafe { config.config.add_session(ticket) };
70 }
71
72 let mut connection = Ssl::new(&config.config)?;
73 if let Some(ticket) = &maybe_ticket {
74 unsafe { connection.set_session(ticket)? };
75 }
76
77 let io = match mode {
78 Mode::Client => io.client_view(),
79 Mode::Server => io.server_view(),
80 };
81
82 let connection = SslStream::new(connection, io)?;
83 Ok(Self { connection })
84 }
85
86 fn handshake(&mut self) -> Result<(), Box<dyn Error>> {
87 let result = if self.connection.ssl().is_server() {
88 self.connection.accept()
89 } else {
90 self.connection.connect()
91 };
92
93 // treat blocking (`ErrorCode::WANT_READ`) as `Ok`, expected during handshake
94 match result {
95 Ok(_) => Ok(()),
96 Err(err) => {
97 if err.code() != ErrorCode::WANT_READ {
98 Err(err.into())
99 } else {
100 Ok(())
101 }
102 }
103 }
104 }
105
106 fn handshake_completed(&self) -> bool {
107 self.connection.ssl().is_init_finished()
108 }
109
110 fn send(&mut self, data: &[u8]) {
111 let mut write_offset = 0;
112 while write_offset < data.len() {
113 write_offset += self
114 .connection
115 .write(&data[write_offset..data.len()])
116 .unwrap();
117 self.connection.flush().unwrap(); // make sure internal buffers don't fill up
118 }
119 }
120
121 fn recv(&mut self, data: &mut [u8]) -> std::io::Result<()> {
122 let data_len = data.len();
123 let mut read_offset = 0;
124 while read_offset < data.len() {
125 read_offset += self.connection.read(&mut data[read_offset..data_len])?
126 }
127 Ok(())
128 }
129
130 fn shutdown_send(&mut self) {
131 // this method will not read in a CloseNotify
132 assert_eq!(self.connection.shutdown().unwrap(), ShutdownResult::Sent);
133 }
134
135 fn shutdown_finish(&mut self) -> bool {
136 self.connection.shutdown().unwrap() == ShutdownResult::Received
137 }
138 }
139
140 impl TlsInfo for OpenSslConnection {
141 fn name() -> String {
142 let version_num = openssl::version::number() as u64;
143 let patch: u8 = (version_num >> 4) as u8;
144 let fix = (version_num >> 12) as u8;
145 let minor = (version_num >> 20) as u8;
146 let major = (version_num >> 28) as u8;
147 format!(
148 "openssl{}.{}.{}{}",
149 major,
150 minor,
151 fix,
152 (b'a' + patch - 1) as char
153 )
154 }
155
156 fn get_negotiated_cipher_suite(&self) -> String {
157 let cipher_suite = self
158 .connection
159 .ssl()
160 .current_cipher()
161 .expect("Handshake not completed")
162 .name();
163 cipher_suite.to_string()
164 }
165
166 fn negotiated_tls13(&self) -> bool {
167 self.connection
168 .ssl()
169 .version2() // version() -> &str is deprecated, version2() returns an enum instead
170 .expect("Handshake not completed")
171 == SslVersion::TLS1_3
172 }
173
174 fn resumed_connection(&self) -> bool {
175 self.connection.ssl().session_reused()
176 }
177
178 fn mutual_auth(&self) -> bool {
179 assert!(self.connection.ssl().is_server());
180 self.connection.ssl().verified_chain().is_some()
181 }
182 }
183
184 impl TlsConfigBuilder for SslContextBuilder {
185 type Config = OpenSslConfig;
186
187 fn new_test_config(mode: Mode) -> Self {
188 let mut builder = match mode {
189 Mode::Client => SslContext::builder(SslMethod::tls_client()).unwrap(),
190 Mode::Server => SslContext::builder(SslMethod::tls_server()).unwrap(),
191 };
192 builder.set_security_level(0);
193 builder
194 }
195
196 fn set_chain(&mut self, sig_type: crate::SigType) {
197 self.set_certificate_chain_file(get_cert_path(PemType::ServerCertChain, sig_type))
198 .unwrap();
199 self.set_private_key_file(
200 get_cert_path(PemType::ServerKey, sig_type),
201 SslFiletype::PEM,
202 )
203 .unwrap();
204 }
205
206 fn set_trust(&mut self, sig_type: crate::SigType) {
207 self.set_ca_file(get_cert_path(PemType::CACert, sig_type))
208 .unwrap();
209 }
210
211 fn build(self) -> Self::Config {
212 OpenSslConfig {
213 config: self.build(),
214 session_ticket_storage: SessionTicketStorage::default(),
215 }
216 }
217 }
218
219 #[cfg(test)]
220 mod tests {
221 use crate::test_utilities;
222
223 use super::*;
224
225 #[test]
226 fn handshake() {
227 test_utilities::handshake::<OpenSslConnection, SslContextBuilder>();
228 }
229
230 #[test]
231 fn transfer() {
232 test_utilities::transfer::<OpenSslConnection, SslContextBuilder>();
233 }
234 }