rust-postgres/tokio-postgres-openssl/src/lib.rs

82 lines
2.2 KiB
Rust
Raw Normal View History

2018-06-27 04:00:26 +00:00
extern crate openssl;
extern crate tokio_io;
extern crate tokio_openssl;
extern crate tokio_postgres;
#[macro_use]
extern crate futures;
2018-06-27 04:00:26 +00:00
#[cfg(test)]
extern crate tokio;
use futures::{Async, Future, Poll};
use openssl::hash::MessageDigest;
use openssl::nid::Nid;
use openssl::ssl::{ConnectConfiguration, HandshakeError, SslRef};
use std::fmt::Debug;
2018-06-27 04:00:26 +00:00
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_openssl::{ConnectAsync, ConnectConfigurationExt, SslStream};
use tokio_postgres::{ChannelBinding, TlsConnect};
2018-06-27 04:00:26 +00:00
#[cfg(test)]
mod test;
pub struct TlsConnector {
ssl: ConnectConfiguration,
domain: String,
2018-06-27 04:00:26 +00:00
}
impl TlsConnector {
pub fn new(ssl: ConnectConfiguration, domain: &str) -> TlsConnector {
2018-06-27 04:00:26 +00:00
TlsConnector {
ssl,
domain: domain.to_string(),
2018-06-27 04:00:26 +00:00
}
}
}
impl<S> TlsConnect<S> for TlsConnector
where
S: AsyncRead + AsyncWrite + Debug + 'static + Sync + Send,
{
type Stream = SslStream<S>;
type Error = HandshakeError<S>;
type Future = TlsConnectFuture<S>;
2018-06-27 04:00:26 +00:00
fn connect(self, stream: S) -> TlsConnectFuture<S> {
TlsConnectFuture(self.ssl.connect_async(&self.domain, stream))
2018-06-27 04:00:26 +00:00
}
}
pub struct TlsConnectFuture<S>(ConnectAsync<S>);
2018-06-27 04:00:26 +00:00
impl<S> Future for TlsConnectFuture<S>
where
S: AsyncRead + AsyncWrite + Debug + 'static + Sync + Send,
{
type Item = (SslStream<S>, ChannelBinding);
type Error = HandshakeError<S>;
2018-06-27 04:00:26 +00:00
fn poll(&mut self) -> Poll<(SslStream<S>, ChannelBinding), HandshakeError<S>> {
let stream = try_ready!(self.0.poll());
2018-06-27 04:00:26 +00:00
2018-11-30 05:30:02 +00:00
let channel_binding = match tls_server_end_point(stream.get_ref().ssl()) {
Some(buf) => ChannelBinding::tls_server_end_point(buf),
None => ChannelBinding::none(),
};
Ok(Async::Ready((stream, channel_binding)))
}
}
fn tls_server_end_point(ssl: &SslRef) -> Option<Vec<u8>> {
let cert = ssl.peer_certificate()?;
let algo_nid = cert.signature_algorithm().object().nid();
let signature_algorithms = algo_nid.signature_algorithms()?;
let md = match signature_algorithms.digest {
Nid::MD5 | Nid::SHA1 => MessageDigest::sha256(),
nid => MessageDigest::from_nid(nid)?,
};
cert.digest(md).ok().map(|b| b.to_vec())
}