forked from algesten/ureq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrustls.rs
252 lines (206 loc) · 7.83 KB
/
rustls.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
use std::fmt;
use std::io::{Read, Write};
use std::sync::{Arc, OnceLock};
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned, ALL_VERSIONS};
use rustls_pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs1KeyDer, PrivatePkcs8KeyDer};
use rustls_pki_types::{PrivateSec1KeyDer, ServerName};
use crate::tls::cert::KeyKind;
use crate::tls::{RootCerts, TlsProvider};
use crate::transport::time::NextTimeout;
use crate::transport::{Buffers, ConnectionDetails, Connector, LazyBuffers};
use crate::transport::{Transport, TransportAdapter};
use crate::Error;
use super::TlsConfig;
/// Wrapper for TLS using rustls.
///
/// Requires feature flag **rustls**.
#[derive(Default)]
pub struct RustlsConnector {
config: OnceLock<Arc<ClientConfig>>,
}
impl Connector for RustlsConnector {
fn connect(
&self,
details: &ConnectionDetails,
chained: Option<Box<dyn Transport>>,
) -> Result<Option<Box<dyn Transport>>, Error> {
let Some(transport) = chained else {
panic!("RustlConnector requires a chained transport");
};
// Only add TLS if we are connecting via HTTPS and the transport isn't TLS
// already, otherwise use chained transport as is.
if !details.needs_tls() || transport.is_tls() {
trace!("Skip");
return Ok(Some(transport));
}
if details.config.tls_config.provider != TlsProvider::Rustls {
debug!("Skip because config is not set to Rustls");
return Ok(Some(transport));
}
trace!("Try wrap in TLS");
let tls_config = &details.config.tls_config;
// Initialize the config on first run.
let config_ref = self.config.get_or_init(|| build_config(tls_config));
let config = config_ref.clone(); // cheap clone due to Arc
let name_borrowed: ServerName<'_> = details
.uri
.authority()
.expect("uri authority for tls")
.host()
.try_into()
.map_err(|e| {
warn!("rustls invalid dns name: {}", e);
Error::Tls("Rustls invalid dns name error")
})?;
let name = name_borrowed.to_owned();
let conn = ClientConnection::new(config, name)?;
let stream = StreamOwned {
conn,
sock: TransportAdapter::new(transport),
};
let buffers = LazyBuffers::new(
details.config.input_buffer_size,
details.config.output_buffer_size,
);
let transport = Box::new(RustlsTransport { buffers, stream });
debug!("Wrapped TLS");
Ok(Some(transport))
}
}
fn build_config(tls_config: &TlsConfig) -> Arc<ClientConfig> {
// Improve chances of ureq working out-of-the-box by not requiring the user
// to select a default crypto provider.
let provider = rustls::crypto::CryptoProvider::get_default()
.cloned()
.unwrap_or(Arc::new(rustls::crypto::ring::default_provider()));
let builder = ClientConfig::builder_with_provider(provider.clone())
.with_protocol_versions(ALL_VERSIONS)
.expect("all TLS versions");
let builder = if tls_config.disable_verification {
debug!("Certificate verification disabled");
builder
.dangerous()
.with_custom_certificate_verifier(Arc::new(DisabledVerifier))
} else {
match &tls_config.root_certs {
RootCerts::SpecificCerts(certs) => {
let root_certs = certs.iter().map(|c| CertificateDer::from(c.der()));
let mut root_store = RootCertStore::empty();
let (added, ignored) = root_store.add_parsable_certificates(root_certs);
debug!("Added {} and ignored {} root certs", added, ignored);
builder.with_root_certificates(root_store)
}
RootCerts::PlatformVerifier => builder
// This actually not dangerous. The rustls_platform_verifier is safe.
.dangerous()
.with_custom_certificate_verifier(Arc::new(
rustls_platform_verifier::Verifier::new().with_provider(provider),
)),
RootCerts::WebPki => {
let root_store = RootCertStore {
roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
};
builder.with_root_certificates(root_store)
}
}
};
let mut config = if let Some((certs, key)) = &tls_config.client_cert {
let cert_chain = certs
.iter()
.map(|c| CertificateDer::from(c.der()).into_owned());
let key_der = match key.kind() {
KeyKind::Pkcs1 => PrivateKeyDer::Pkcs1(PrivatePkcs1KeyDer::from(key.der())),
KeyKind::Pkcs8 => PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.der())),
KeyKind::Sec1 => PrivateKeyDer::Sec1(PrivateSec1KeyDer::from(key.der())),
}
.clone_key();
debug!("Use client certficiate with key kind {:?}", key.kind());
builder
.with_client_auth_cert(cert_chain.collect(), key_der)
.expect("valid client auth certificate")
} else {
builder.with_no_client_auth()
};
config.enable_sni = tls_config.use_sni;
if !tls_config.use_sni {
debug!("Disable SNI");
}
Arc::new(config)
}
struct RustlsTransport {
buffers: LazyBuffers,
stream: StreamOwned<ClientConnection, TransportAdapter>,
}
impl Transport for RustlsTransport {
fn buffers(&mut self) -> &mut dyn Buffers {
&mut self.buffers
}
fn transmit_output(&mut self, amount: usize, timeout: NextTimeout) -> Result<(), Error> {
self.stream.get_mut().timeout = timeout;
let output = &self.buffers.output()[..amount];
self.stream.write_all(output)?;
Ok(())
}
fn await_input(&mut self, timeout: NextTimeout) -> Result<bool, Error> {
if self.buffers.can_use_input() {
return Ok(true);
}
self.stream.get_mut().timeout = timeout;
let input = self.buffers.input_mut();
let amount = self.stream.read(input)?;
self.buffers.add_filled(amount);
Ok(amount > 0)
}
fn is_open(&mut self) -> bool {
self.stream.get_mut().get_mut().is_open()
}
fn is_tls(&self) -> bool {
true
}
}
#[derive(Debug)]
struct DisabledVerifier;
impl ServerCertVerifier for DisabledVerifier {
fn verify_server_cert(
&self,
_end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
_server_name: &rustls_pki_types::ServerName<'_>,
_ocsp_response: &[u8],
_now: rustls_pki_types::UnixTime,
) -> Result<ServerCertVerified, rustls::Error> {
Ok(ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
_message: &[u8],
_cert: &CertificateDer<'_>,
_dss: &rustls::DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn verify_tls13_signature(
&self,
_message: &[u8],
_cert: &CertificateDer<'_>,
_dss: &rustls::DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
vec![]
}
}
impl fmt::Debug for RustlsConnector {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RustlsConnector").finish()
}
}
impl fmt::Debug for RustlsTransport {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RustlsTransport")
.field("chained", &self.stream.sock.transport)
.finish()
}
}