navid/veins / 5cec66944879958839c3441fea831ebf0f26f343353220445e794abd21872a3f / veinsrs/src/protocol/tls.rs
tls.rs
← veinsrs/src/protocol · 7679 bytes · raw · download
use std::net::TcpStream;
use std::sync::Arc;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
use rustls::{
ClientConfig, ClientConnection, DigitallySignedStruct, RootCertStore, ServerConfig,
ServerConnection, SignatureScheme, StreamOwned,
};
use crate::error::{Error, Result};
use super::wire::Stream;
const EXPORTER_LABEL: &[u8] = b"EXPORTER-veins-auth/1";
#[derive(Debug)]
struct PinnedVerifier {
algorithms: rustls::crypto::WebPkiSupportedAlgorithms,
}
impl ServerCertVerifier for PinnedVerifier {
fn verify_server_cert(
&self,
_end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
_server_name: &ServerName<'_>,
_ocsp_response: &[u8],
_now: UnixTime,
) -> std::result::Result<ServerCertVerified, rustls::Error> {
Ok(ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
signature: &DigitallySignedStruct,
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls12_signature(message, cert, signature, &self.algorithms)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
signature: &DigitallySignedStruct,
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls13_signature(message, cert, signature, &self.algorithms)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.algorithms.supported_schemes()
}
}
pub fn client_context(pinned: bool) -> Result<Arc<ClientConfig>> {
let provider = rustls::crypto::ring::default_provider();
let builder = ClientConfig::builder_with_provider(Arc::new(provider.clone()))
.with_protocol_versions(&[&rustls::version::TLS13])
.map_err(|error| Error::new(error.to_string()))?;
let config = if pinned {
builder
.dangerous()
.with_custom_certificate_verifier(Arc::new(PinnedVerifier {
algorithms: provider.signature_verification_algorithms,
}))
.with_no_client_auth()
} else {
let mut roots = RootCertStore::empty();
let native = rustls_native_certs::load_native_certs();
roots.add_parsable_certificates(native.certs);
if roots.is_empty() {
roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
}
if roots.is_empty() {
return Err(Error::new("no trusted TLS roots are available"));
}
builder.with_root_certificates(roots).with_no_client_auth()
};
Ok(Arc::new(config))
}
pub fn connect(host: &str, port: i32, pin: &str) -> Result<Stream> {
let pinned = !pin.is_empty();
let config = client_context(pinned)?;
let name =
ServerName::try_from(host.to_string()).map_err(|_| Error::new("invalid TLS host name"))?;
let mut socket = TcpStream::connect((host, port as u16))
.map_err(|_| Error::new("cannot connect: host refused the connection or is unreachable"))?;
let mut connection = ClientConnection::new(config, name)
.map_err(|error| Error::new(format!("TLS handshake failed: {error}")))?;
connection
.complete_io(&mut socket)
.map_err(|error| Error::new(format!("TLS handshake failed: {error}")))?;
if pinned {
let Some(certificate) = connection
.peer_certificates()
.and_then(|certs| certs.first())
else {
return Err(Error::new("TLS certificate pin mismatch"));
};
let digest = ring::digest::digest(&ring::digest::SHA256, certificate.as_ref());
if !hex_equal(&hex_encode(digest.as_ref()), pin) {
return Err(Error::new("TLS certificate pin mismatch"));
}
}
let binding = exporter(&connection);
Ok(Stream::from_duplex(
Box::new(StreamOwned::new(connection, socket)),
binding,
))
}
pub fn server_context(cert_path: &str, key_path: &str) -> Result<Arc<ServerConfig>> {
let certificates: Vec<CertificateDer<'static>> = CertificateDer::pem_file_iter(cert_path)
.map_err(|_| Error::new("cannot read the TLS certificate"))?
.collect::<std::result::Result<_, _>>()
.map_err(|_| Error::new("cannot parse the TLS certificate"))?;
if certificates.is_empty() {
return Err(Error::new("cannot parse the TLS certificate"));
}
let key = PrivateKeyDer::from_pem_file(key_path)
.map_err(|_| Error::new("cannot read the TLS private key"))?;
let provider = rustls::crypto::ring::default_provider();
let config = ServerConfig::builder_with_provider(Arc::new(provider))
.with_protocol_versions(&[&rustls::version::TLS13])
.map_err(|error| Error::new(error.to_string()))?
.with_no_client_auth()
.with_single_cert(certificates, key)
.map_err(|_| Error::new("cannot load the TLS certificate or key"))?;
Ok(Arc::new(config))
}
pub fn accept(socket: TcpStream, config: Arc<ServerConfig>) -> Result<Stream> {
let mut connection = ServerConnection::new(config)
.map_err(|error| Error::new(format!("TLS handshake failed: {error}")))?;
let mut socket = socket;
connection
.complete_io(&mut socket)
.map_err(|error| Error::new(format!("TLS handshake failed: {error}")))?;
let binding = exporter(&connection);
Ok(Stream::from_duplex(
Box::new(StreamOwned::new(connection, socket)),
binding,
))
}
fn exporter(connection: &impl Exportable) -> Vec<u8> {
let mut output = [0u8; 32];
if connection
.export_keying_material(&mut output, EXPORTER_LABEL, None)
.is_ok()
{
output.to_vec()
} else {
Vec::new()
}
}
trait Exportable {
fn export_keying_material<T: AsMut<[u8]>>(
&self,
output: T,
label: &[u8],
context: Option<&[u8]>,
) -> std::result::Result<T, rustls::Error>;
}
impl Exportable for ClientConnection {
fn export_keying_material<T: AsMut<[u8]>>(
&self,
output: T,
label: &[u8],
context: Option<&[u8]>,
) -> std::result::Result<T, rustls::Error> {
ConnectionCommon::export_keying_material(self, output, label, context)
}
}
impl Exportable for ServerConnection {
fn export_keying_material<T: AsMut<[u8]>>(
&self,
output: T,
label: &[u8],
context: Option<&[u8]>,
) -> std::result::Result<T, rustls::Error> {
ConnectionCommon::export_keying_material(self, output, label, context)
}
}
use rustls::ConnectionCommon;
fn hex_encode(data: &[u8]) -> String {
const DIGITS: &[u8; 16] = b"0123456789abcdef";
let mut output = String::with_capacity(data.len() * 2);
for byte in data {
output.push(DIGITS[(byte >> 4) as usize] as char);
output.push(DIGITS[(byte & 0x0f) as usize] as char);
}
output
}
fn hex_equal(left: &str, right: &str) -> bool {
let mut left = left
.bytes()
.filter(|byte| !byte.is_ascii_whitespace() && *byte != b':');
let mut right = right
.bytes()
.filter(|byte| !byte.is_ascii_whitespace() && *byte != b':');
loop {
match (left.next(), right.next()) {
(None, None) => return true,
(Some(a), Some(b)) if a.to_ascii_lowercase() == b.to_ascii_lowercase() => {}
_ => return false,
}
}
}