| 1 |
use futures_util::future; |
| 2 |
use std::io::{self, BufReader, Cursor, Read, Write}; |
| 3 |
use std::sync::Arc; |
| 4 |
use std::task::{Context, Poll}; |
| 5 |
|
| 6 |
use rustls::{ |
| 7 |
client::{ |
| 8 |
danger::{ServerCertVerified, ServerCertVerifier}, |
| 9 |
WebPkiServerVerifier, |
| 10 |
}, |
| 11 |
crypto::{verify_tls12_signature, verify_tls13_signature, CryptoProvider}, |
| 12 |
pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime}, |
| 13 |
CertificateError, ClientConfig, ClientConnection, Error as TlsError, RootCertStore, |
| 14 |
}; |
| 15 |
|
| 16 |
use crate::error::Error; |
| 17 |
use crate::io::ReadBuf; |
| 18 |
use crate::net::tls::util::StdSocket; |
| 19 |
use crate::net::tls::TlsConfig; |
| 20 |
use crate::net::Socket; |
| 21 |
|
| 22 |
pub struct RustlsSocket<S: Socket> { |
| 23 |
inner: StdSocket<S>, |
| 24 |
state: ClientConnection, |
| 25 |
close_notify_sent: bool, |
| 26 |
} |
| 27 |
|
| 28 |
impl<S: Socket> RustlsSocket<S> { |
| 29 |
fn poll_complete_io(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> { |
| 30 |
loop { |
| 31 |
match self.state.complete_io(&mut self.inner) { |
| 32 |
Err(e) if e.kind() == io::ErrorKind::WouldBlock => { |
| 33 |
futures_util::ready!(self.inner.poll_ready(cx))?; |
| 34 |
} |
| 35 |
ready => return Poll::Ready(ready.map(|_| ())), |
| 36 |
} |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
async fn complete_io(&mut self) -> io::Result<()> { |
| 41 |
future::poll_fn(|cx| self.poll_complete_io(cx)).await |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
impl<S: Socket> Socket for RustlsSocket<S> { |
| 46 |
fn try_read(&mut self, buf: &mut dyn ReadBuf) -> io::Result<usize> { |
| 47 |
self.state.reader().read(buf.init_mut()) |
| 48 |
} |
| 49 |
|
| 50 |
fn try_write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 51 |
match self.state.writer().write(buf) { |
| 52 |
// Returns a zero-length write when the buffer is full. |
| 53 |
Ok(0) => Err(io::ErrorKind::WouldBlock.into()), |
| 54 |
other => other, |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
fn poll_read_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> { |
| 59 |
self.poll_complete_io(cx) |
| 60 |
} |
| 61 |
|
| 62 |
fn poll_write_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> { |
| 63 |
self.poll_complete_io(cx) |
| 64 |
} |
| 65 |
|
| 66 |
fn poll_flush(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> { |
| 67 |
self.poll_complete_io(cx) |
| 68 |
} |
| 69 |
|
| 70 |
fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> { |
| 71 |
if !self.close_notify_sent { |
| 72 |
self.state.send_close_notify(); |
| 73 |
self.close_notify_sent = true; |
| 74 |
} |
| 75 |
|
| 76 |
futures_util::ready!(self.poll_complete_io(cx))?; |
| 77 |
|
| 78 |
// Server can close socket as soon as it receives the connection shutdown request. |
| 79 |
// We shouldn't expect it to stick around for the TLS session to close cleanly. |
| 80 |
// https://security.stackexchange.com/a/82034 |
| 81 |
let _ = futures_util::ready!(self.inner.socket.poll_shutdown(cx)); |
| 82 |
|
| 83 |
Poll::Ready(Ok(())) |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
pub async fn handshake<S>(socket: S, tls_config: TlsConfig<'_>) -> Result<RustlsSocket<S>, Error> |
| 88 |
where |
| 89 |
S: Socket, |
| 90 |
{ |
| 91 |
#[cfg(all( |
| 92 |
feature = "_tls-rustls-aws-lc-rs", |
| 93 |
not(feature = "_tls-rustls-ring-webpki"), |
| 94 |
not(feature = "_tls-rustls-ring-native-roots") |
| 95 |
))] |
| 96 |
let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); |
| 97 |
#[cfg(any( |
| 98 |
feature = "_tls-rustls-ring-webpki", |
| 99 |
feature = "_tls-rustls-ring-native-roots" |
| 100 |
))] |
| 101 |
let provider = Arc::new(rustls::crypto::ring::default_provider()); |
| 102 |
|
| 103 |
// Unwrapping is safe here because we use a default provider. |
| 104 |
let config = ClientConfig::builder_with_provider(provider.clone()) |
| 105 |
.with_safe_default_protocol_versions() |
| 106 |
.unwrap(); |
| 107 |
|
| 108 |
// authentication using user's key and its associated certificate |
| 109 |
let user_auth = match (tls_config.client_cert_path, tls_config.client_key_path) { |
| 110 |
(Some(cert_path), Some(key_path)) => { |
| 111 |
let cert_chain = certs_from_pem(cert_path.data().await?)?; |
| 112 |
let key_der = private_key_from_pem(key_path.data().await?)?; |
| 113 |
Some((cert_chain, key_der)) |
| 114 |
} |
| 115 |
(None, None) => None, |
| 116 |
(_, _) => { |
| 117 |
return Err(Error::Configuration( |
| 118 |
"user auth key and certs must be given together".into(), |
| 119 |
)) |
| 120 |
} |
| 121 |
}; |
| 122 |
|
| 123 |
let config = if tls_config.accept_invalid_certs { |
| 124 |
if let Some(user_auth) = user_auth { |
| 125 |
config |
| 126 |
.dangerous() |
| 127 |
.with_custom_certificate_verifier(Arc::new(DummyTlsVerifier { provider })) |
| 128 |
.with_client_auth_cert(user_auth.0, user_auth.1) |
| 129 |
.map_err(Error::tls)? |
| 130 |
} else { |
| 131 |
config |
| 132 |
.dangerous() |
| 133 |
.with_custom_certificate_verifier(Arc::new(DummyTlsVerifier { provider })) |
| 134 |
.with_no_client_auth() |
| 135 |
} |
| 136 |
} else { |
| •137 |
//#[cfg(any(feature = "_tls-rustls-aws-lc-rs", feature = "_tls-rustls-ring-webpki"))] |
| 138 |
//let mut cert_store = certs_from_webpki(); |
| 139 |
//#[cfg(feature = "_tls-rustls-ring-native-roots")] |
| 140 |
let mut cert_store = certs_from_native_store(); |
| 141 |
|
| 142 |
if let Some(ca) = tls_config.root_cert_path { |
| 143 |
let data = ca.data().await?; |
| 144 |
let mut cursor = Cursor::new(data); |
| 145 |
|
| 146 |
for result in rustls_pemfile::certs(&mut cursor) { |
| 147 |
let Ok(cert) = result else { |
| 148 |
return Err(Error::Tls(format!("Invalid certificate {ca}").into())); |
| 149 |
}; |
| 150 |
|
| 151 |
cert_store.add(cert).map_err(|err| Error::Tls(err.into()))?; |
| 152 |
} |
| 153 |
} |
| 154 |
|
| 155 |
if tls_config.accept_invalid_hostnames { |
| 156 |
let verifier = WebPkiServerVerifier::builder(Arc::new(cert_store)) |
| 157 |
.build() |
| 158 |
.map_err(|err| Error::Tls(err.into()))?; |
| 159 |
|
| 160 |
if let Some(user_auth) = user_auth { |
| 161 |
config |
| 162 |
.dangerous() |
| 163 |
.with_custom_certificate_verifier(Arc::new(NoHostnameTlsVerifier { verifier })) |
| 164 |
.with_client_auth_cert(user_auth.0, user_auth.1) |
| 165 |
.map_err(Error::tls)? |
| 166 |
} else { |
| 167 |
config |
| 168 |
.dangerous() |
| 169 |
.with_custom_certificate_verifier(Arc::new(NoHostnameTlsVerifier { verifier })) |
| 170 |
.with_no_client_auth() |
| 171 |
} |
| 172 |
} else if let Some(user_auth) = user_auth { |
| 173 |
config |
| 174 |
.with_root_certificates(cert_store) |
| 175 |
.with_client_auth_cert(user_auth.0, user_auth.1) |
| 176 |
.map_err(Error::tls)? |
| 177 |
} else { |
| 178 |
config |
| 179 |
.with_root_certificates(cert_store) |
| 180 |
.with_no_client_auth() |
| 181 |
} |
| 182 |
}; |
| 183 |
|
| 184 |
let host = ServerName::try_from(tls_config.hostname.to_owned()).map_err(Error::tls)?; |
| 185 |
|
| 186 |
let mut socket = RustlsSocket { |
| 187 |
inner: StdSocket::new(socket), |
| 188 |
state: ClientConnection::new(Arc::new(config), host).map_err(Error::tls)?, |
| 189 |
close_notify_sent: false, |
| 190 |
}; |
| 191 |
|
| 192 |
// Performs the TLS handshake or bails |
| 193 |
socket.complete_io().await?; |
| 194 |
|
| 195 |
Ok(socket) |
| 196 |
} |
| 197 |
|
| 198 |
fn certs_from_pem(pem: Vec<u8>) -> Result<Vec<CertificateDer<'static>>, Error> { |
| 199 |
let cur = Cursor::new(pem); |
| 200 |
let mut reader = BufReader::new(cur); |
| 201 |
rustls_pemfile::certs(&mut reader) |
| 202 |
.map(|result| result.map_err(|err| Error::Tls(err.into()))) |
| 203 |
.collect() |
| 204 |
} |
| 205 |
|
| 206 |
fn private_key_from_pem(pem: Vec<u8>) -> Result<PrivateKeyDer<'static>, Error> { |
| 207 |
let cur = Cursor::new(pem); |
| 208 |
let mut reader = BufReader::new(cur); |
| 209 |
match rustls_pemfile::private_key(&mut reader) { |
| 210 |
Ok(Some(key)) => Ok(key), |
| 211 |
Ok(None) => Err(Error::Configuration("no keys found pem file".into())), |
| 212 |
Err(e) => Err(Error::Configuration(e.to_string().into())), |
| 213 |
} |
| 214 |
} |
| 215 |
|
| •216 |
/*#[cfg(any(feature = "_tls-rustls-aws-lc-rs", feature = "_tls-rustls-ring-webpki"))] |
| 217 |
fn certs_from_webpki() -> RootCertStore { |
| 218 |
RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()) |
| •219 |
}*/ |
| 220 |
|
| •221 |
//#[cfg(feature = "_tls-rustls-ring-native-roots")] |
| 222 |
fn certs_from_native_store() -> RootCertStore { |
| 223 |
let mut root_cert_store = RootCertStore::empty(); |
| 224 |
|
| 225 |
let load_results = rustls_native_certs::load_native_certs(); |
| 226 |
for e in load_results.errors { |
| 227 |
log::warn!("Error loading native certificates: {e:?}"); |
| 228 |
} |
| 229 |
for cert in load_results.certs { |
| 230 |
if let Err(e) = root_cert_store.add(cert.into()) { |
| 231 |
log::warn!("rustls failed to parse native certificate: {e:?}"); |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
root_cert_store |
| 236 |
} |
| 237 |
|
| 238 |
#[derive(Debug)] |
| 239 |
struct DummyTlsVerifier { |
| 240 |
provider: Arc<CryptoProvider>, |
| 241 |
} |
| 242 |
|
| 243 |
impl ServerCertVerifier for DummyTlsVerifier { |
| 244 |
fn verify_server_cert( |
| 245 |
&self, |
| 246 |
_end_entity: &CertificateDer<'_>, |
| 247 |
_intermediates: &[CertificateDer<'_>], |
| 248 |
_server_name: &ServerName<'_>, |
| 249 |
_ocsp_response: &[u8], |
| 250 |
_now: UnixTime, |
| 251 |
) -> Result<ServerCertVerified, TlsError> { |
| 252 |
Ok(ServerCertVerified::assertion()) |
| 253 |
} |
| 254 |
|
| 255 |
fn verify_tls12_signature( |
| 256 |
&self, |
| 257 |
message: &[u8], |
| 258 |
cert: &CertificateDer<'_>, |
| 259 |
dss: &rustls::DigitallySignedStruct, |
| 260 |
) -> Result<rustls::client::danger::HandshakeSignatureValid, TlsError> { |
| 261 |
verify_tls12_signature( |
| 262 |
message, |
| 263 |
cert, |
| 264 |
dss, |
| 265 |
&self.provider.signature_verification_algorithms, |
| 266 |
) |
| 267 |
} |
| 268 |
|
| 269 |
fn verify_tls13_signature( |
| 270 |
&self, |
| 271 |
message: &[u8], |
| 272 |
cert: &CertificateDer<'_>, |
| 273 |
dss: &rustls::DigitallySignedStruct, |
| 274 |
) -> Result<rustls::client::danger::HandshakeSignatureValid, TlsError> { |
| 275 |
verify_tls13_signature( |
| 276 |
message, |
| 277 |
cert, |
| 278 |
dss, |
| 279 |
&self.provider.signature_verification_algorithms, |
| 280 |
) |
| 281 |
} |
| 282 |
|
| 283 |
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> { |
| 284 |
self.provider |
| 285 |
.signature_verification_algorithms |
| 286 |
.supported_schemes() |
| 287 |
} |
| 288 |
} |
| 289 |
|
| 290 |
#[derive(Debug)] |
| 291 |
pub struct NoHostnameTlsVerifier { |
| 292 |
verifier: Arc<WebPkiServerVerifier>, |
| 293 |
} |
| 294 |
|
| 295 |
impl ServerCertVerifier for NoHostnameTlsVerifier { |
| 296 |
fn verify_server_cert( |
| 297 |
&self, |
| 298 |
end_entity: &CertificateDer<'_>, |
| 299 |
intermediates: &[CertificateDer<'_>], |
| 300 |
server_name: &ServerName<'_>, |
| 301 |
ocsp_response: &[u8], |
| 302 |
now: UnixTime, |
| 303 |
) -> Result<ServerCertVerified, TlsError> { |
| 304 |
match self.verifier.verify_server_cert( |
| 305 |
end_entity, |
| 306 |
intermediates, |
| 307 |
server_name, |
| 308 |
ocsp_response, |
| 309 |
now, |
| 310 |
) { |
| 311 |
Err(TlsError::InvalidCertificate(CertificateError::NotValidForName)) => { |
| 312 |
Ok(ServerCertVerified::assertion()) |
| 313 |
} |
| 314 |
res => res, |
| 315 |
} |
| 316 |
} |
| 317 |
|
| 318 |
fn verify_tls12_signature( |
| 319 |
&self, |
| 320 |
message: &[u8], |
| 321 |
cert: &CertificateDer<'_>, |
| 322 |
dss: &rustls::DigitallySignedStruct, |
| 323 |
) -> Result<rustls::client::danger::HandshakeSignatureValid, TlsError> { |
| 324 |
self.verifier.verify_tls12_signature(message, cert, dss) |
| 325 |
} |
| 326 |
|
| 327 |
fn verify_tls13_signature( |
| 328 |
&self, |
| 329 |
message: &[u8], |
| 330 |
cert: &CertificateDer<'_>, |
| 331 |
dss: &rustls::DigitallySignedStruct, |
| 332 |
) -> Result<rustls::client::danger::HandshakeSignatureValid, TlsError> { |
| 333 |
self.verifier.verify_tls13_signature(message, cert, dss) |
| 334 |
} |
| 335 |
|
| 336 |
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> { |
| 337 |
self.verifier.supported_verify_schemes() |
| 338 |
} |
| 339 |
} |