M1 primary view: wx-rs patched+extended (Linux/GTK3 build, widget bridge), vendored wx 3.3.3 + asic-rs in thirdparty/, UI-SPEC table+KPIs+dialogs, build scripts

This commit is contained in:
2026-09-15 13:59:55 -06:00
parent 165d899fd8
commit b264cdd6d1
16316 changed files with 4932188 additions and 58 deletions
+521
View File
@@ -0,0 +1,521 @@
use openssl::error::ErrorStack;
use openssl::hash::MessageDigest;
use openssl::nid::Nid;
use openssl::pkcs12::Pkcs12;
use openssl::pkey::{PKey, Private};
use openssl::ssl::{
self, MidHandshakeSslStream, SslAcceptor, SslConnector, SslContextBuilder, SslMethod,
SslVerifyMode,
};
use openssl::x509::store::X509StoreBuilder;
use openssl::x509::{X509VerifyResult, X509};
use openssl_probe::ProbeResult;
use std::sync::LazyLock;
use std::{error, fmt, io};
use crate::{Protocol, TlsAcceptorBuilder, TlsConnectorBuilder};
use log::debug;
static PROBE_RESULT: LazyLock<ProbeResult> = LazyLock::new(openssl_probe::probe);
#[cfg(have_min_max_version)]
fn supported_protocols(
min: Option<Protocol>,
max: Option<Protocol>,
ctx: &mut SslContextBuilder,
) -> Result<(), ErrorStack> {
use openssl::ssl::SslVersion;
fn cvt(p: Protocol) -> SslVersion {
match p {
Protocol::Sslv3 => SslVersion::SSL3,
Protocol::Tlsv10 => SslVersion::TLS1,
Protocol::Tlsv11 => SslVersion::TLS1_1,
Protocol::Tlsv12 => SslVersion::TLS1_2,
Protocol::Tlsv13 => SslVersion::TLS1_3,
}
}
ctx.set_min_proto_version(min.map(cvt))?;
ctx.set_max_proto_version(max.map(cvt))?;
Ok(())
}
#[cfg(not(have_min_max_version))]
fn supported_protocols(
min: Option<Protocol>,
max: Option<Protocol>,
ctx: &mut SslContextBuilder,
) -> Result<(), ErrorStack> {
use openssl::ssl::SslOptions;
let no_ssl_mask = SslOptions::NO_SSLV2
| SslOptions::NO_SSLV3
| SslOptions::NO_TLSV1
| SslOptions::NO_TLSV1_1
| SslOptions::NO_TLSV1_2;
ctx.clear_options(no_ssl_mask);
let mut options = SslOptions::empty();
options |= match min {
None => SslOptions::empty(),
Some(Protocol::Sslv3) => SslOptions::NO_SSLV2,
Some(Protocol::Tlsv10) => SslOptions::NO_SSLV2 | SslOptions::NO_SSLV3,
Some(Protocol::Tlsv11) => {
SslOptions::NO_SSLV2 | SslOptions::NO_SSLV3 | SslOptions::NO_TLSV1
}
Some(Protocol::Tlsv12) => {
SslOptions::NO_SSLV2
| SslOptions::NO_SSLV3
| SslOptions::NO_TLSV1
| SslOptions::NO_TLSV1_1
}
Some(Protocol::Tlsv13) => {
SslOptions::NO_SSLV2
| SslOptions::NO_SSLV3
| SslOptions::NO_TLSV1
| SslOptions::NO_TLSV1_1
| SslOptions::NO_TLSV1_2
}
};
options |= match max {
// NO_TLSV1_3 may be unavailalbe in the old versions
None | Some(Protocol::Tlsv12 | Protocol::Tlsv13) => SslOptions::empty(),
Some(Protocol::Tlsv11) => SslOptions::NO_TLSV1_2,
Some(Protocol::Tlsv10) => SslOptions::NO_TLSV1_1 | SslOptions::NO_TLSV1_2,
Some(Protocol::Sslv3) => {
SslOptions::NO_TLSV1 | SslOptions::NO_TLSV1_1 | SslOptions::NO_TLSV1_2
}
};
ctx.set_options(options);
Ok(())
}
#[cfg(target_os = "android")]
fn load_android_root_certs(connector: &mut SslContextBuilder) -> Result<(), Error> {
use std::fs;
if let Ok(dir) = fs::read_dir("/system/etc/security/cacerts") {
let certs = dir
.filter_map(|r| r.ok())
.filter_map(|e| fs::read(e.path()).ok())
.filter_map(|b| X509::from_pem(&b).ok());
for cert in certs {
if let Err(err) = connector.cert_store_mut().add_cert(cert) {
debug!("load_android_root_certs error: {:?}", err);
}
}
}
Ok(())
}
#[derive(Debug)]
pub enum Error {
Normal(ErrorStack),
Ssl(ssl::Error, X509VerifyResult),
EmptyChain,
NotPkcs8,
AlpnTooLong,
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match *self {
Error::Normal(ref e) => error::Error::source(e),
Error::Ssl(ref e, _) => error::Error::source(e),
Error::EmptyChain => None,
Error::NotPkcs8 => None,
Error::AlpnTooLong => None,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Normal(ref e) => fmt::Display::fmt(e, fmt),
Error::Ssl(ref e, X509VerifyResult::OK) => fmt::Display::fmt(e, fmt),
Error::Ssl(ref e, v) => write!(fmt, "{} ({})", e, v),
Error::EmptyChain => write!(
fmt,
"at least one certificate must be provided to create an identity"
),
Error::NotPkcs8 => write!(fmt, "expected PKCS#8 PEM"),
Error::AlpnTooLong => write!(fmt, "ALPN too long"),
}
}
}
impl From<ErrorStack> for Error {
fn from(err: ErrorStack) -> Error {
Error::Normal(err)
}
}
#[derive(Clone)]
pub struct Identity {
pkey: PKey<Private>,
cert: X509,
chain: Vec<X509>,
}
impl Identity {
pub fn from_pkcs12(buf: &[u8], pass: &str) -> Result<Identity, Error> {
let pkcs12 = Pkcs12::from_der(buf)?;
let parsed = pkcs12.parse2(pass)?;
Ok(Identity {
pkey: parsed.pkey.ok_or_else(|| Error::EmptyChain)?,
cert: parsed.cert.ok_or_else(|| Error::EmptyChain)?,
// > The stack is the reverse of what you might expect due to the way
// > PKCS12_parse is implemented, so we need to load it backwards.
// > https://github.com/sfackler/rust-native-tls/commit/05fb5e583be589ab63d9f83d986d095639f8ec44
chain: parsed.ca.into_iter().flatten().rev().collect(),
})
}
pub fn from_pkcs8(buf: &[u8], key: &[u8]) -> Result<Identity, Error> {
if !key.starts_with(b"-----BEGIN PRIVATE KEY-----") {
return Err(Error::NotPkcs8);
}
let pkey = PKey::private_key_from_pem(key)?;
let mut cert_chain = X509::stack_from_pem(buf)?.into_iter();
let cert = cert_chain.next().ok_or(Error::EmptyChain)?;
let chain = cert_chain.collect();
Ok(Identity { pkey, cert, chain })
}
}
#[derive(Clone)]
pub struct Certificate(X509);
impl Certificate {
pub fn from_der(buf: &[u8]) -> Result<Certificate, Error> {
let cert = X509::from_der(buf)?;
Ok(Certificate(cert))
}
pub fn from_pem(buf: &[u8]) -> Result<Certificate, Error> {
let cert = X509::from_pem(buf)?;
Ok(Certificate(cert))
}
pub fn stack_from_pem(buf: &[u8]) -> Result<Vec<Certificate>, Error> {
let certs = X509::stack_from_pem(buf)?;
Ok(certs.into_iter().map(Certificate).collect())
}
pub fn to_der(&self) -> Result<Vec<u8>, Error> {
let der = self.0.to_der()?;
Ok(der)
}
}
pub struct MidHandshakeTlsStream<S>(MidHandshakeSslStream<S>);
impl<S> fmt::Debug for MidHandshakeTlsStream<S>
where
S: fmt::Debug,
{
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.0, fmt)
}
}
impl<S> MidHandshakeTlsStream<S> {
pub fn get_ref(&self) -> &S {
self.0.get_ref()
}
pub fn get_mut(&mut self) -> &mut S {
self.0.get_mut()
}
}
impl<S> MidHandshakeTlsStream<S>
where
S: io::Read + io::Write,
{
pub fn handshake(self) -> Result<TlsStream<S>, HandshakeError<S>> {
match self.0.handshake() {
Ok(s) => Ok(TlsStream(s)),
Err(e) => Err(e.into()),
}
}
}
pub enum HandshakeError<S> {
Failure(Error),
WouldBlock(MidHandshakeTlsStream<S>),
}
impl<S> From<ssl::HandshakeError<S>> for HandshakeError<S> {
fn from(e: ssl::HandshakeError<S>) -> HandshakeError<S> {
match e {
ssl::HandshakeError::SetupFailure(e) => HandshakeError::Failure(e.into()),
ssl::HandshakeError::Failure(e) => {
let v = e.ssl().verify_result();
HandshakeError::Failure(Error::Ssl(e.into_error(), v))
}
ssl::HandshakeError::WouldBlock(s) => {
HandshakeError::WouldBlock(MidHandshakeTlsStream(s))
}
}
}
}
impl<S> From<ErrorStack> for HandshakeError<S> {
fn from(e: ErrorStack) -> HandshakeError<S> {
HandshakeError::Failure(e.into())
}
}
#[derive(Clone)]
pub struct TlsConnector {
connector: SslConnector,
use_sni: bool,
accept_invalid_hostnames: bool,
accept_invalid_certs: bool,
}
impl TlsConnector {
pub fn new(builder: &TlsConnectorBuilder) -> Result<TlsConnector, Error> {
let mut connector = SslConnector::builder(SslMethod::tls())?;
// We need to load these separately so an error on one doesn't prevent the other from loading.
if let Some(cert_file) = &PROBE_RESULT.cert_file {
if let Err(e) = connector.load_verify_locations(Some(cert_file), None) {
debug!("load_verify_locations cert file error: {:?}", e);
}
}
for cert_dir in &PROBE_RESULT.cert_dir {
if let Err(e) = connector.load_verify_locations(None, Some(cert_dir)) {
debug!("load_verify_locations cert dir error: {:?}", e);
}
}
if let Some(ref identity) = builder.identity {
connector.set_certificate(&identity.0.cert)?;
connector.set_private_key(&identity.0.pkey)?;
for cert in identity.0.chain.iter() {
// https://www.openssl.org/docs/manmaster/man3/SSL_CTX_add_extra_chain_cert.html
// specifies that "When sending a certificate chain, extra chain certificates are
// sent in order following the end entity certificate."
connector.add_extra_chain_cert(cert.to_owned())?;
}
}
supported_protocols(builder.min_protocol, builder.max_protocol, &mut connector)?;
if builder.disable_built_in_roots {
connector.set_cert_store(X509StoreBuilder::new()?.build());
}
for cert in &builder.root_certificates {
if let Err(err) = connector.cert_store_mut().add_cert((cert.0).0.clone()) {
debug!("add_cert error: {:?}", err);
}
}
#[cfg(feature = "alpn")]
if !builder.alpn.is_empty() {
connector.set_alpn_protos(&alpn_wire_format(&builder.alpn)?)?;
}
#[cfg(target_os = "android")]
load_android_root_certs(&mut connector)?;
Ok(TlsConnector {
connector: connector.build(),
use_sni: builder.use_sni,
accept_invalid_hostnames: builder.accept_invalid_hostnames,
accept_invalid_certs: builder.accept_invalid_certs,
})
}
pub fn connect<S>(&self, domain: &str, stream: S) -> Result<TlsStream<S>, HandshakeError<S>>
where
S: io::Read + io::Write,
{
let mut ssl = self
.connector
.configure()?
.use_server_name_indication(self.use_sni)
.verify_hostname(!self.accept_invalid_hostnames);
if self.accept_invalid_certs {
ssl.set_verify(SslVerifyMode::NONE);
}
let s = ssl.connect(domain, stream)?;
Ok(TlsStream(s))
}
}
#[cfg(any(feature = "alpn", feature = "alpn-accept"))]
fn alpn_wire_format(alpn_list: &[Box<str>]) -> Result<Vec<u8>, Error> {
// Wire format is each alpn preceded by its length as a byte.
let mut alpn_wire_format =
Vec::with_capacity(alpn_list.iter().map(|s| s.len()).sum::<usize>() + alpn_list.len());
for alpn in alpn_list.iter().map(|s| s.as_bytes()) {
let len_byte = alpn.len().try_into().map_err(|_| Error::AlpnTooLong)?;
if alpn_wire_format.capacity() - alpn_wire_format.len() >= 1 {
alpn_wire_format.push(len_byte);
}
if alpn_wire_format.capacity() - alpn_wire_format.len() >= alpn.len() {
alpn_wire_format.extend(alpn);
}
}
Ok(alpn_wire_format)
}
impl fmt::Debug for TlsConnector {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("TlsConnector")
// n.b. SslConnector is a newtype on SslContext which implements a noop Debug so it's omitted
.field("use_sni", &self.use_sni)
.field("accept_invalid_hostnames", &self.accept_invalid_hostnames)
.field("accept_invalid_certs", &self.accept_invalid_certs)
.finish()
}
}
#[derive(Clone)]
pub struct TlsAcceptor(SslAcceptor);
impl TlsAcceptor {
pub fn new(builder: &TlsAcceptorBuilder) -> Result<TlsAcceptor, Error> {
let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls())?;
acceptor.set_private_key(&builder.identity.0.pkey)?;
acceptor.set_certificate(&builder.identity.0.cert)?;
#[cfg(feature = "alpn-accept")]
if !builder.accept_alpn.is_empty() {
let alpn_wire_format = alpn_wire_format(&builder.accept_alpn)?;
acceptor.set_alpn_protos(&alpn_wire_format)?;
// set up ALPN selection routine - as select_next_proto
acceptor.set_alpn_select_callback(move |_: &mut openssl::ssl::SslRef, client_list: &[u8]| {
openssl::ssl::select_next_proto(&alpn_wire_format, client_list).and_then(|selected| {
if selected.is_empty() || selected.len() > client_list.len() {
return None;
}
// return string from the client list to separate it from alpn_wire_format's lifetime
// https://github.com/rust-openssl/rust-openssl/pull/2360#issuecomment-2651522324
client_list.windows(selected.len()).find(|&item| item == selected)
})
.ok_or(openssl::ssl::AlpnError::NOACK)
});
}
for cert in builder.identity.0.chain.iter() {
// https://www.openssl.org/docs/manmaster/man3/SSL_CTX_add_extra_chain_cert.html
// specifies that "When sending a certificate chain, extra chain certificates are
// sent in order following the end entity certificate."
acceptor.add_extra_chain_cert(cert.to_owned())?;
}
supported_protocols(builder.min_protocol, builder.max_protocol, &mut acceptor)?;
Ok(TlsAcceptor(acceptor.build()))
}
pub fn accept<S>(&self, stream: S) -> Result<TlsStream<S>, HandshakeError<S>>
where
S: io::Read + io::Write,
{
let s = self.0.accept(stream)?;
Ok(TlsStream(s))
}
}
pub struct TlsStream<S>(ssl::SslStream<S>);
impl<S: fmt::Debug> fmt::Debug for TlsStream<S> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.0, fmt)
}
}
impl<S> TlsStream<S> {
pub fn get_ref(&self) -> &S {
self.0.get_ref()
}
pub fn get_mut(&mut self) -> &mut S {
self.0.get_mut()
}
}
impl<S: io::Read + io::Write> TlsStream<S> {
pub fn buffered_read_size(&self) -> Result<usize, Error> {
Ok(self.0.ssl().pending())
}
pub fn peer_certificate(&self) -> Result<Option<Certificate>, Error> {
Ok(self.0.ssl().peer_certificate().map(Certificate))
}
#[cfg(feature = "alpn")]
pub fn negotiated_alpn(&self) -> Result<Option<Vec<u8>>, Error> {
Ok(self
.0
.ssl()
.selected_alpn_protocol()
.map(|alpn| alpn.to_vec()))
}
pub fn tls_server_end_point(&self) -> Result<Option<Vec<u8>>, Error> {
let cert = if self.0.ssl().is_server() {
self.0.ssl().certificate().map(|x| x.to_owned())
} else {
self.0.ssl().peer_certificate()
};
let cert = match cert {
Some(cert) => cert,
None => return Ok(None),
};
let algo_nid = cert.signature_algorithm().object().nid();
let signature_algorithms = match algo_nid.signature_algorithms() {
Some(algs) => algs,
None => return Ok(None),
};
let md = match signature_algorithms.digest {
Nid::MD5 | Nid::SHA1 => MessageDigest::sha256(),
nid => match MessageDigest::from_nid(nid) {
Some(md) => md,
None => return Ok(None),
},
};
let digest = cert.digest(md)?;
Ok(Some(digest.to_vec()))
}
pub fn shutdown(&mut self) -> io::Result<()> {
match self.0.shutdown() {
Ok(_) => Ok(()),
Err(ref e) if e.code() == ssl::ErrorCode::ZERO_RETURN => Ok(()),
Err(e) => Err(e.into_io_error().unwrap_or_else(io::Error::other)),
}
}
}
impl<S: io::Read + io::Write> io::Read for TlsStream<S> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
}
impl<S: io::Read + io::Write> io::Write for TlsStream<S> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
}
+579
View File
@@ -0,0 +1,579 @@
use schannel::cert_context::{CertContext, HashAlgorithm, KeySpec};
use schannel::cert_store::{CertAdd, CertStore, Memory, PfxImportOptions};
use schannel::crypt_prov::{AcquireOptions, ProviderType};
use schannel::schannel_cred::{Direction, Protocol, SchannelCred};
use schannel::tls_stream;
use std::{error, fmt, io, str};
use crate::{TlsAcceptorBuilder, TlsConnectorBuilder};
const SEC_E_NO_CREDENTIALS: u32 = 0x8009030E;
static PROTOCOLS: &[Protocol] = &[
Protocol::Ssl3,
Protocol::Tls10,
Protocol::Tls11,
Protocol::Tls12,
Protocol::Tls13,
];
fn convert_protocols(
min: Option<crate::Protocol>,
max: Option<crate::Protocol>,
) -> &'static [Protocol] {
let mut protocols = PROTOCOLS;
if let Some(p) = max.and_then(|max| protocols.get(..=max as usize)) {
protocols = p;
}
if let Some(p) = min.and_then(|min| protocols.get(min as usize..)) {
protocols = p;
}
protocols
}
pub struct Error(io::Error);
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
error::Error::source(&self.0)
}
}
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, fmt)
}
}
impl fmt::Debug for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.0, fmt)
}
}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Error {
Error(error)
}
}
#[derive(Clone)]
pub struct Identity {
cert: CertContext,
}
impl Identity {
pub fn from_pkcs12(buf: &[u8], pass: &str) -> Result<Identity, Error> {
let store = PfxImportOptions::new().password(pass).import(buf)?;
let mut identity = None;
for cert in store.certs() {
if cert
.private_key()
.silent(true)
.compare_key(true)
.acquire()
.is_ok()
{
identity = Some(cert);
break;
}
}
let identity = match identity {
Some(identity) => identity,
None => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"No identity found in PKCS #12 archive",
)
.into());
}
};
Ok(Identity { cert: identity })
}
pub fn from_pkcs8(pem: &[u8], key: &[u8]) -> Result<Identity, Error> {
if !key.starts_with(b"-----BEGIN PRIVATE KEY-----") {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "not a PKCS#8 key").into());
}
let mut store = Memory::new()?.into_store();
let mut cert_iter = pem::PemBlock::new(pem);
let leaf = cert_iter.next().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"at least one certificate must be provided to create an identity",
)
})?;
let cert = CertContext::from_pem(std::str::from_utf8(leaf).map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidInput,
"leaf cert contains invalid utf8",
)
})?)?;
let name = gen_container_name();
let mut options = AcquireOptions::new();
options.container(&name);
let type_ = ProviderType::rsa_full();
let mut container = match options.acquire(type_) {
Ok(container) => container,
Err(_) => options.new_keyset(true).acquire(type_)?,
};
container.import().import_pkcs8_pem(key)?;
cert.set_key_prov_info()
.container(&name)
.type_(type_)
.keep_open(true)
.key_spec(KeySpec::key_exchange())
.set()?;
let mut context = store.add_cert(&cert, CertAdd::Always)?;
for int_cert in cert_iter {
let certificate = Certificate::from_pem(int_cert)?;
context = store.add_cert(&certificate.0, CertAdd::Always)?;
}
Ok(Identity { cert: context })
}
}
// The name of the container must be unique to have multiple active keys.
fn gen_container_name() -> String {
use std::sync::atomic::{AtomicUsize, Ordering};
static COUNTER: AtomicUsize = AtomicUsize::new(0);
format!("native-tls-{}", COUNTER.fetch_add(1, Ordering::Relaxed))
}
#[derive(Clone)]
pub struct Certificate(CertContext);
impl Certificate {
pub fn from_der(buf: &[u8]) -> Result<Certificate, Error> {
let cert = CertContext::new(buf)?;
Ok(Certificate(cert))
}
pub fn from_pem(buf: &[u8]) -> Result<Certificate, Error> {
match str::from_utf8(buf) {
Ok(s) => {
let cert = CertContext::from_pem(s)?;
Ok(Certificate(cert))
}
Err(_) => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"PEM representation contains non-UTF-8 bytes",
)
.into()),
}
}
pub fn stack_from_pem(buf: &[u8]) -> Result<Vec<Certificate>, Error> {
pem::PemBlock::new(buf)
.map(|pem| {
CertContext::from_pem(std::str::from_utf8(pem).map_err(io::Error::other)?)
.map(Certificate)
})
.map(|res| res.map_err(Error))
.collect()
}
pub fn to_der(&self) -> Result<Vec<u8>, Error> {
Ok(self.0.to_der().to_vec())
}
}
pub struct MidHandshakeTlsStream<S>(Box<tls_stream::MidHandshakeTlsStream<S>>);
impl<S> fmt::Debug for MidHandshakeTlsStream<S>
where
S: fmt::Debug,
{
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&*self.0, fmt)
}
}
impl<S> MidHandshakeTlsStream<S> {
pub fn get_ref(&self) -> &S {
self.0.get_ref()
}
pub fn get_mut(&mut self) -> &mut S {
self.0.get_mut()
}
}
impl<S> MidHandshakeTlsStream<S>
where
S: io::Read + io::Write,
{
pub fn handshake(self) -> Result<TlsStream<S>, HandshakeError<S>> {
match self.0.handshake() {
Ok(s) => Ok(TlsStream(s)),
Err(e) => Err(e.into()),
}
}
}
pub enum HandshakeError<S> {
Failure(Error),
WouldBlock(MidHandshakeTlsStream<S>),
}
impl<S> From<tls_stream::HandshakeError<S>> for HandshakeError<S> {
fn from(e: tls_stream::HandshakeError<S>) -> HandshakeError<S> {
match e {
tls_stream::HandshakeError::Failure(e) => HandshakeError::Failure(e.into()),
tls_stream::HandshakeError::Interrupted(s) => {
HandshakeError::WouldBlock(MidHandshakeTlsStream(Box::new(s)))
}
}
}
}
impl<S> From<io::Error> for HandshakeError<S> {
fn from(e: io::Error) -> HandshakeError<S> {
HandshakeError::Failure(e.into())
}
}
#[derive(Clone, Debug)]
pub struct TlsConnector {
cert: Option<CertContext>,
roots: CertStore,
min_protocol: Option<crate::Protocol>,
max_protocol: Option<crate::Protocol>,
use_sni: bool,
accept_invalid_hostnames: bool,
accept_invalid_certs: bool,
disable_built_in_roots: bool,
#[cfg(feature = "alpn")]
alpn: Vec<Box<str>>,
}
impl TlsConnector {
pub fn new(builder: &TlsConnectorBuilder) -> Result<TlsConnector, Error> {
let cert = builder.identity.as_ref().map(|i| i.0.cert.clone());
let mut roots = Memory::new()?.into_store();
for cert in &builder.root_certificates {
roots.add_cert(&(cert.0).0, CertAdd::ReplaceExisting)?;
}
Ok(TlsConnector {
cert,
roots,
min_protocol: builder.min_protocol,
max_protocol: builder.max_protocol,
use_sni: builder.use_sni,
accept_invalid_hostnames: builder.accept_invalid_hostnames,
accept_invalid_certs: builder.accept_invalid_certs,
disable_built_in_roots: builder.disable_built_in_roots,
#[cfg(feature = "alpn")]
alpn: builder.alpn.clone(),
})
}
pub fn connect<S>(&self, domain: &str, stream: S) -> Result<TlsStream<S>, HandshakeError<S>>
where
S: io::Read + io::Write,
{
let mut builder = SchannelCred::builder();
builder.enabled_protocols(convert_protocols(self.min_protocol, self.max_protocol));
if let Some(cert) = self.cert.as_ref() {
builder.cert(cert.clone());
}
let cred = builder.acquire(Direction::Outbound)?;
let mut builder = tls_stream::Builder::new();
builder
.cert_store(self.roots.clone())
.domain(domain)
.use_sni(self.use_sni)
.accept_invalid_hostnames(self.accept_invalid_hostnames);
if self.accept_invalid_certs {
builder.verify_callback(|_| Ok(()));
} else if self.disable_built_in_roots {
let roots_copy = self.roots.clone();
builder.verify_callback(move |res| {
// Propagate previous error encountered during normal cert validation.
res.result()?;
if let Some(chain) = res.chain() {
if chain
.certificates()
.any(|cert| roots_copy.certs().any(|root_cert| root_cert == cert))
{
return Ok(());
}
}
Err(io::Error::other(
"unable to find any user-specified roots in the final cert chain",
))
});
}
#[cfg(feature = "alpn")]
{
if !self.alpn.is_empty() {
builder.request_application_protocols(
&self.alpn.iter().map(|s| s.as_bytes()).collect::<Vec<_>>(),
);
}
}
match builder.connect(cred, stream) {
Ok(s) => Ok(TlsStream(s)),
Err(e) => Err(e.into()),
}
}
}
#[derive(Clone)]
pub struct TlsAcceptor {
cert: CertContext,
min_protocol: Option<crate::Protocol>,
max_protocol: Option<crate::Protocol>,
#[cfg(feature = "alpn-accept")]
accept_alpn: Vec<Box<str>>,
}
impl TlsAcceptor {
pub fn new(builder: &TlsAcceptorBuilder) -> Result<TlsAcceptor, Error> {
Ok(TlsAcceptor {
cert: builder.identity.0.cert.clone(),
min_protocol: builder.min_protocol,
max_protocol: builder.max_protocol,
#[cfg(feature = "alpn-accept")]
accept_alpn: builder.accept_alpn.clone(),
})
}
pub fn accept<S>(&self, stream: S) -> Result<TlsStream<S>, HandshakeError<S>>
where
S: io::Read + io::Write,
{
let mut builder = SchannelCred::builder();
builder.enabled_protocols(convert_protocols(self.min_protocol, self.max_protocol));
builder.cert(self.cert.clone());
// FIXME we're probably missing the certificate chain?
let cred = builder.acquire(Direction::Inbound)?;
let mut builder = tls_stream::Builder::new();
#[cfg(feature = "alpn-accept")]
if !self.accept_alpn.is_empty() {
let accept_alpn: Vec<&[u8]> = self.accept_alpn.iter().map(|s| s.as_bytes()).collect();
builder.request_application_protocols(accept_alpn.as_slice());
}
match builder.accept(cred, stream) {
Ok(s) => Ok(TlsStream(s)),
Err(e) => Err(e.into()),
}
}
}
pub struct TlsStream<S>(tls_stream::TlsStream<S>);
impl<S: fmt::Debug> fmt::Debug for TlsStream<S> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.0, fmt)
}
}
impl<S> TlsStream<S> {
pub fn get_ref(&self) -> &S {
self.0.get_ref()
}
pub fn get_mut(&mut self) -> &mut S {
self.0.get_mut()
}
}
impl<S: io::Read + io::Write> TlsStream<S> {
pub fn buffered_read_size(&self) -> Result<usize, Error> {
Ok(self.0.get_buf().len())
}
pub fn peer_certificate(&self) -> Result<Option<Certificate>, Error> {
match self.0.peer_certificate() {
Ok(cert) => Ok(Some(Certificate(cert))),
Err(ref e) if e.raw_os_error() == Some(SEC_E_NO_CREDENTIALS as i32) => Ok(None),
Err(e) => Err(Error(e)),
}
}
#[cfg(feature = "alpn")]
pub fn negotiated_alpn(&self) -> Result<Option<Vec<u8>>, Error> {
Ok(self.0.negotiated_application_protocol()?)
}
pub fn tls_server_end_point(&self) -> Result<Option<Vec<u8>>, Error> {
let cert = if self.0.is_server() {
self.0.certificate()
} else {
self.0.peer_certificate()
};
let cert = match cert {
Ok(cert) => cert,
Err(ref e) if e.raw_os_error() == Some(SEC_E_NO_CREDENTIALS as i32) => return Ok(None),
Err(e) => return Err(Error(e)),
};
let signature_algorithms = cert.sign_hash_algorithms()?;
let hash = match signature_algorithms.rsplit('/').next().unwrap() {
"MD5" | "SHA1" | "SHA256" => HashAlgorithm::sha256(),
"SHA384" => HashAlgorithm::sha384(),
"SHA512" => HashAlgorithm::sha512(),
_ => return Ok(None),
};
let digest = cert.fingerprint(hash)?;
Ok(Some(digest))
}
pub fn shutdown(&mut self) -> io::Result<()> {
self.0.shutdown()?;
Ok(())
}
}
impl<S: io::Read + io::Write> io::Read for TlsStream<S> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
}
impl<S: io::Read + io::Write> io::Write for TlsStream<S> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
}
mod pem {
/// Split data by PEM guard lines
pub struct PemBlock<'a> {
pem_block: &'a str,
cur_end: usize,
}
impl<'a> PemBlock<'a> {
pub fn new(data: &'a [u8]) -> PemBlock<'a> {
let s = ::std::str::from_utf8(data).unwrap();
PemBlock {
pem_block: s,
cur_end: s.find("-----BEGIN").unwrap_or(s.len()),
}
}
}
impl<'a> Iterator for PemBlock<'a> {
type Item = &'a [u8];
fn next(&mut self) -> Option<Self::Item> {
let last = self.pem_block.len();
if self.cur_end >= last {
return None;
}
let begin = self.cur_end;
let pos = self.pem_block[begin + 1..].find("-----BEGIN");
self.cur_end = match pos {
Some(end) => end + begin + 1,
None => last,
};
Some(&self.pem_block.as_bytes()[begin..self.cur_end])
}
}
#[test]
fn test_split() {
// Split three certs, CRLF line terminators.
assert_eq!(
PemBlock::new(
b"-----BEGIN FIRST-----\r\n-----END FIRST-----\r\n\
-----BEGIN SECOND-----\r\n-----END SECOND\r\n\
-----BEGIN THIRD-----\r\n-----END THIRD\r\n"
)
.collect::<Vec<&[u8]>>(),
vec![
b"-----BEGIN FIRST-----\r\n-----END FIRST-----\r\n" as &[u8],
b"-----BEGIN SECOND-----\r\n-----END SECOND\r\n",
b"-----BEGIN THIRD-----\r\n-----END THIRD\r\n"
]
);
// Split three certs, CRLF line terminators except at EOF.
assert_eq!(
PemBlock::new(
b"-----BEGIN FIRST-----\r\n-----END FIRST-----\r\n\
-----BEGIN SECOND-----\r\n-----END SECOND-----\r\n\
-----BEGIN THIRD-----\r\n-----END THIRD-----"
)
.collect::<Vec<&[u8]>>(),
vec![
b"-----BEGIN FIRST-----\r\n-----END FIRST-----\r\n" as &[u8],
b"-----BEGIN SECOND-----\r\n-----END SECOND-----\r\n",
b"-----BEGIN THIRD-----\r\n-----END THIRD-----"
]
);
// Split two certs, LF line terminators.
assert_eq!(
PemBlock::new(
b"-----BEGIN FIRST-----\n-----END FIRST-----\n\
-----BEGIN SECOND-----\n-----END SECOND\n"
)
.collect::<Vec<&[u8]>>(),
vec![
b"-----BEGIN FIRST-----\n-----END FIRST-----\n" as &[u8],
b"-----BEGIN SECOND-----\n-----END SECOND\n"
]
);
// Split two certs, CR line terminators.
assert_eq!(
PemBlock::new(
b"-----BEGIN FIRST-----\r-----END FIRST-----\r\
-----BEGIN SECOND-----\r-----END SECOND\r"
)
.collect::<Vec<&[u8]>>(),
vec![
b"-----BEGIN FIRST-----\r-----END FIRST-----\r" as &[u8],
b"-----BEGIN SECOND-----\r-----END SECOND\r"
]
);
// Split two certs, LF line terminators except at EOF.
assert_eq!(
PemBlock::new(
b"-----BEGIN FIRST-----\n-----END FIRST-----\n\
-----BEGIN SECOND-----\n-----END SECOND"
)
.collect::<Vec<&[u8]>>(),
vec![
b"-----BEGIN FIRST-----\n-----END FIRST-----\n" as &[u8],
b"-----BEGIN SECOND-----\n-----END SECOND"
]
);
// Split a single cert, LF line terminators.
assert_eq!(
PemBlock::new(b"-----BEGIN FIRST-----\n-----END FIRST-----\n").collect::<Vec<&[u8]>>(),
vec![b"-----BEGIN FIRST-----\n-----END FIRST-----\n" as &[u8]]
);
// Split a single cert, LF line terminators except at EOF.
assert_eq!(
PemBlock::new(b"-----BEGIN FIRST-----\n-----END FIRST-----").collect::<Vec<&[u8]>>(),
vec![b"-----BEGIN FIRST-----\n-----END FIRST-----" as &[u8]]
);
// (Don't) split garbage.
assert_eq!(
PemBlock::new(b"junk").collect::<Vec<&[u8]>>(),
Vec::<&[u8]>::new()
);
assert_eq!(
PemBlock::new(b"junk-----BEGIN garbage").collect::<Vec<&[u8]>>(),
vec![b"-----BEGIN garbage" as &[u8]]
);
}
}
+649
View File
@@ -0,0 +1,649 @@
use security_framework::base;
use security_framework::certificate::SecCertificate;
use security_framework::identity::SecIdentity;
use security_framework::import_export::{ImportedIdentity, Pkcs12ImportOptions};
#[cfg(target_os = "macos")]
use security_framework::random::SecRandom;
use security_framework::secure_transport::{
self, ClientBuilder, SslConnectionType, SslContext, SslProtocol, SslProtocolSide,
};
#[cfg(target_os = "macos")]
use security_framework_sys::base::errSecIO;
#[cfg(any(feature = "alpn", target_os = "macos"))]
use security_framework_sys::base::errSecParam;
#[cfg(target_os = "macos")]
use std::sync::{Mutex, Once};
use std::{error, fmt, io, str};
#[cfg(target_os = "macos")]
use security_framework::os::macos::certificate::{PropertyType, SecCertificateExt};
#[cfg(target_os = "macos")]
use security_framework::os::macos::certificate_oids::CertificateOid;
#[cfg(target_os = "macos")]
use security_framework::os::macos::identity::SecIdentityExt;
#[cfg(target_os = "macos")]
use security_framework::os::macos::import_export::{
ImportOptions, Pkcs12ImportOptionsExt, SecItems,
};
#[cfg(target_os = "macos")]
use security_framework::os::macos::keychain::{self, KeychainSettings, SecKeychain};
use crate::{Protocol, TlsAcceptorBuilder, TlsConnectorBuilder};
#[cfg(target_os = "macos")]
static SET_AT_EXIT: Once = Once::new();
#[cfg(target_os = "macos")]
static TEMP_KEYCHAIN: Mutex<Option<(SecKeychain, tempfile::TempDir)>> = Mutex::new(None);
fn convert_protocol(protocol: Protocol) -> SslProtocol {
match protocol {
Protocol::Sslv3 => SslProtocol::SSL3,
Protocol::Tlsv10 => SslProtocol::TLS1,
Protocol::Tlsv11 => SslProtocol::TLS11,
Protocol::Tlsv12 => SslProtocol::TLS12,
Protocol::Tlsv13 => SslProtocol::TLS13,
}
}
pub struct Error(base::Error);
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
error::Error::source(&self.0)
}
}
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, fmt)
}
}
impl fmt::Debug for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.0, fmt)
}
}
impl From<base::Error> for Error {
fn from(error: base::Error) -> Error {
Error(error)
}
}
#[derive(Clone, Debug)]
pub struct Identity {
identity: SecIdentity,
chain: Vec<SecCertificate>,
}
impl Identity {
#[cfg(not(target_os = "macos"))]
pub fn from_pkcs8(_: &[u8], _: &[u8]) -> Result<Identity, Error> {
panic!("Not implemented on iOS");
}
#[cfg(target_os = "macos")]
pub fn from_pkcs8(pem: &[u8], key: &[u8]) -> Result<Identity, Error> {
if !key.starts_with(b"-----BEGIN PRIVATE KEY-----") {
return Err(Error(base::Error::from(errSecParam)));
}
let dir = tempfile::TempDir::new().map_err(|_| Error(base::Error::from(errSecIO)))?;
let keychain = keychain::CreateOptions::new()
.password(&random_password()?)
.create(dir.path().join("identity.keychain"))?;
let mut items = SecItems::default();
ImportOptions::new()
.filename("key.pem")
.items(&mut items)
.keychain(&keychain)
.import(key)?;
ImportOptions::new()
.filename("chain.pem")
.items(&mut items)
.keychain(&keychain)
.import(pem)?;
let cert = items
.certificates
.first()
.ok_or_else(|| Error(base::Error::from(errSecParam)))?;
let ident = SecIdentity::with_certificate(&[keychain], cert)?;
Ok(Identity {
identity: ident,
chain: items.certificates.into_iter().skip(1).collect(),
})
}
pub fn from_pkcs12(buf: &[u8], pass: &str) -> Result<Identity, Error> {
let mut imports = Identity::import_options(buf, pass)?;
let import = imports.pop().unwrap();
let identity = import
.identity
.expect("Pkcs12 files must include an identity");
// FIXME: Compare the certificates for equality using CFEqual
let identity_cert = identity.certificate()?.to_der();
Ok(Identity {
identity,
chain: import
.cert_chain
.unwrap_or(vec![])
.into_iter()
.filter(|c| c.to_der() != identity_cert)
.collect(),
})
}
#[cfg(target_os = "macos")]
fn import_options(buf: &[u8], pass: &str) -> Result<Vec<ImportedIdentity>, Error> {
SET_AT_EXIT.call_once(|| {
extern "C" fn atexit() {
*TEMP_KEYCHAIN.lock().unwrap() = None;
}
unsafe {
libc::atexit(atexit);
}
});
// keep it locked during import()
let keychain = &mut *TEMP_KEYCHAIN.lock().unwrap();
let keychain = match keychain {
Some((keychain, _)) => keychain.clone(),
lock @ None => {
let dir =
tempfile::TempDir::new().map_err(|_| Error(base::Error::from(errSecIO)))?;
let mut keychain = keychain::CreateOptions::new()
.password(pass)
.create(dir.path().join("tmp.keychain"))?;
keychain.set_settings(&KeychainSettings::new())?;
*lock = Some((keychain.clone(), dir));
keychain
}
};
let mut import_opts = Pkcs12ImportOptions::new();
// Method shadowed by deprecated method.
<Pkcs12ImportOptions as Pkcs12ImportOptionsExt>::keychain(&mut import_opts, keychain);
let imports = import_opts.passphrase(pass).import(buf)?;
Ok(imports)
}
#[cfg(not(target_os = "macos"))]
fn import_options(buf: &[u8], pass: &str) -> Result<Vec<ImportedIdentity>, Error> {
let imports = Pkcs12ImportOptions::new().passphrase(pass).import(buf)?;
Ok(imports)
}
}
#[cfg(target_os = "macos")]
fn random_password() -> Result<String, Error> {
use std::fmt::Write;
let mut bytes = [0_u8; 10];
SecRandom::default()
.copy_bytes(&mut bytes)
.map_err(|_| Error(base::Error::from(errSecIO)))?;
let mut s = String::with_capacity(2 * bytes.len());
for byte in bytes {
write!(s, "{byte:02X}").map_err(|_| Error(base::Error::from(errSecIO)))?;
}
Ok(s)
}
#[derive(Clone)]
pub struct Certificate(SecCertificate);
impl Certificate {
pub fn from_der(buf: &[u8]) -> Result<Certificate, Error> {
let cert = SecCertificate::from_der(buf)?;
Ok(Certificate(cert))
}
#[cfg(target_os = "macos")]
pub fn from_pem(buf: &[u8]) -> Result<Certificate, Error> {
let mut items = SecItems::default();
ImportOptions::new().items(&mut items).import(buf)?;
if items.certificates.len() == 1 && items.identities.is_empty() && items.keys.is_empty() {
Ok(Certificate(items.certificates.pop().unwrap()))
} else {
Err(Error(base::Error::from(errSecParam)))
}
}
#[cfg(not(target_os = "macos"))]
pub fn from_pem(_: &[u8]) -> Result<Certificate, Error> {
panic!("Not implemented on iOS, tvOS, watchOS or visionOS");
}
#[cfg(target_os = "macos")]
pub fn stack_from_pem(buf: &[u8]) -> Result<Vec<Certificate>, Error> {
let mut items = SecItems::default();
ImportOptions::new().items(&mut items).import(buf)?;
if items.identities.is_empty() && items.keys.is_empty() {
Ok(items.certificates.into_iter().map(Certificate).collect())
} else {
Err(Error(base::Error::from(errSecParam)))
}
}
#[cfg(not(target_os = "macos"))]
pub fn stack_from_pem(_buf: &[u8]) -> Result<Vec<Certificate>, Error> {
panic!("Not implemented on iOS");
}
#[allow(clippy::unnecessary_wraps)]
pub fn to_der(&self) -> Result<Vec<u8>, Error> {
Ok(self.0.to_der())
}
}
pub enum HandshakeError<S> {
WouldBlock(MidHandshakeTlsStream<S>),
Failure(Error),
}
impl<S> From<secure_transport::ClientHandshakeError<S>> for HandshakeError<S> {
fn from(e: secure_transport::ClientHandshakeError<S>) -> HandshakeError<S> {
match e {
secure_transport::ClientHandshakeError::Failure(e) => HandshakeError::Failure(e.into()),
secure_transport::ClientHandshakeError::Interrupted(s) => {
HandshakeError::WouldBlock(MidHandshakeTlsStream::Client(s))
}
}
}
}
impl<S> From<base::Error> for HandshakeError<S> {
fn from(e: base::Error) -> HandshakeError<S> {
HandshakeError::Failure(e.into())
}
}
pub enum MidHandshakeTlsStream<S> {
Server(
secure_transport::MidHandshakeSslStream<S>,
Option<SecCertificate>,
),
Client(secure_transport::MidHandshakeClientBuilder<S>),
}
impl<S> fmt::Debug for MidHandshakeTlsStream<S>
where
S: fmt::Debug,
{
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
MidHandshakeTlsStream::Server(ref s, _) => s.fmt(fmt),
MidHandshakeTlsStream::Client(ref s) => s.fmt(fmt),
}
}
}
impl<S> MidHandshakeTlsStream<S> {
pub fn get_ref(&self) -> &S {
match *self {
MidHandshakeTlsStream::Server(ref s, _) => s.get_ref(),
MidHandshakeTlsStream::Client(ref s) => s.get_ref(),
}
}
pub fn get_mut(&mut self) -> &mut S {
match *self {
MidHandshakeTlsStream::Server(ref mut s, _) => s.get_mut(),
MidHandshakeTlsStream::Client(ref mut s) => s.get_mut(),
}
}
}
impl<S> MidHandshakeTlsStream<S>
where
S: io::Read + io::Write,
{
pub fn handshake(self) -> Result<TlsStream<S>, HandshakeError<S>> {
match self {
MidHandshakeTlsStream::Server(s, cert) => match s.handshake() {
Ok(stream) => Ok(TlsStream { stream, cert }),
Err(secure_transport::HandshakeError::Failure(e)) => {
Err(HandshakeError::Failure(Error(e)))
}
Err(secure_transport::HandshakeError::Interrupted(s)) => Err(
HandshakeError::WouldBlock(MidHandshakeTlsStream::Server(s, cert)),
),
},
MidHandshakeTlsStream::Client(s) => match s.handshake() {
Ok(stream) => Ok(TlsStream { stream, cert: None }),
Err(e) => Err(e.into()),
},
}
}
}
#[derive(Clone, Debug)]
#[allow(clippy::struct_excessive_bools)]
pub struct TlsConnector {
identity: Option<Identity>,
min_protocol: Option<Protocol>,
max_protocol: Option<Protocol>,
roots: Vec<SecCertificate>,
use_sni: bool,
danger_accept_invalid_hostnames: bool,
danger_accept_invalid_certs: bool,
disable_built_in_roots: bool,
#[cfg(feature = "alpn")]
alpn: Vec<Box<str>>,
}
impl TlsConnector {
#[allow(clippy::unnecessary_wraps)]
pub fn new(builder: &TlsConnectorBuilder) -> Result<Self, Error> {
Ok(Self {
identity: builder.identity.as_ref().map(|i| i.0.clone()),
min_protocol: builder.min_protocol,
max_protocol: builder.max_protocol,
roots: builder
.root_certificates
.iter()
.map(|c| (c.0).0.clone())
.collect(),
use_sni: builder.use_sni,
danger_accept_invalid_hostnames: builder.accept_invalid_hostnames,
danger_accept_invalid_certs: builder.accept_invalid_certs,
disable_built_in_roots: builder.disable_built_in_roots,
#[cfg(feature = "alpn")]
alpn: builder.alpn.clone(),
})
}
pub fn connect<S>(&self, domain: &str, stream: S) -> Result<TlsStream<S>, HandshakeError<S>>
where
S: io::Read + io::Write,
{
let mut builder = ClientBuilder::new();
let min = self.min_protocol.map(convert_protocol);
let max = self.max_protocol.map(convert_protocol);
if let Some(min) = min {
// If the unsupported TLS 1.3 is the minimum, then let it fail
builder.protocol_min(min);
}
if let Some(max) = max {
builder.protocol_max(match max {
// If TLS 1.3 is allowed but not required, then use the latest that is actually supported - 1.2
SslProtocol::TLS13 if min != Some(SslProtocol::TLS13) => SslProtocol::TLS12,
other => other,
});
}
if let Some(identity) = self.identity.as_ref() {
builder.identity(&identity.identity, &identity.chain);
}
builder.anchor_certificates(&self.roots);
builder.use_sni(self.use_sni);
builder.danger_accept_invalid_hostnames(self.danger_accept_invalid_hostnames);
builder.danger_accept_invalid_certs(self.danger_accept_invalid_certs);
builder.trust_anchor_certificates_only(self.disable_built_in_roots);
#[cfg(feature = "alpn")]
{
if !self.alpn.is_empty() {
builder.alpn_protocols(&self.alpn.iter().map(|s| &**s).collect::<Vec<_>>());
}
}
match builder.handshake(domain, stream) {
Ok(stream) => Ok(TlsStream { stream, cert: None }),
Err(e) => Err(e.into()),
}
}
}
#[derive(Clone)]
pub struct TlsAcceptor {
identity: Identity,
min_protocol: Option<Protocol>,
max_protocol: Option<Protocol>,
}
impl TlsAcceptor {
#[allow(clippy::unnecessary_wraps)]
pub fn new(builder: &TlsAcceptorBuilder) -> Result<Self, Error> {
Ok(Self {
identity: builder.identity.0.clone(),
min_protocol: builder.min_protocol,
max_protocol: builder.max_protocol,
})
}
pub fn accept<S>(&self, stream: S) -> Result<TlsStream<S>, HandshakeError<S>>
where
S: io::Read + io::Write,
{
let mut ctx = SslContext::new(SslProtocolSide::SERVER, SslConnectionType::STREAM)?;
if let Some(min) = self.min_protocol {
ctx.set_protocol_version_min(convert_protocol(min))?;
}
if let Some(max) = self.max_protocol {
ctx.set_protocol_version_max(convert_protocol(max))?;
}
ctx.set_certificate(&self.identity.identity, &self.identity.chain)?;
let cert = Some(self.identity.identity.certificate()?);
match ctx.handshake(stream) {
Ok(stream) => Ok(TlsStream { stream, cert }),
Err(secure_transport::HandshakeError::Failure(e)) => {
Err(HandshakeError::Failure(Error(e)))
}
Err(secure_transport::HandshakeError::Interrupted(s)) => Err(
HandshakeError::WouldBlock(MidHandshakeTlsStream::Server(s, cert)),
),
}
}
}
pub struct TlsStream<S> {
stream: secure_transport::SslStream<S>,
#[cfg_attr(not(target_os = "macos"), allow(unused))]
cert: Option<SecCertificate>,
}
impl<S: fmt::Debug> fmt::Debug for TlsStream<S> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.stream, fmt)
}
}
impl<S> TlsStream<S> {
pub fn get_ref(&self) -> &S {
self.stream.get_ref()
}
pub fn get_mut(&mut self) -> &mut S {
self.stream.get_mut()
}
}
impl<S: io::Read + io::Write> TlsStream<S> {
pub fn buffered_read_size(&self) -> Result<usize, Error> {
Ok(self.stream.context().buffered_read_size()?)
}
#[allow(deprecated)]
pub fn peer_certificate(&self) -> Result<Option<Certificate>, Error> {
let Some(trust) = self.stream.context().peer_trust2()? else {
return Ok(None);
};
trust.evaluate()?;
Ok(trust.certificate_at_index(0).map(Certificate))
}
#[cfg(feature = "alpn")]
pub fn negotiated_alpn(&self) -> Result<Option<Vec<u8>>, Error> {
match self.stream.context().alpn_protocols() {
Ok(protocols) => {
// Per RFC7301, "ProtocolNameList" MUST contain exactly one "ProtocolName".
assert!(protocols.len() < 2);
if protocols.is_empty() {
// Not sure this is actually possible.
Ok(None)
} else {
Ok(Some(protocols.into_iter().next().unwrap().into_bytes()))
}
}
// The macOS API appears to return `errSecParam` whenever no ALPN was negotiated, both
// when it isn't attempted and when it isn't successful.
Err(e) if e.code() == errSecParam => Ok(None),
Err(other) => Err(Error::from(other)),
}
}
#[cfg(not(target_os = "macos"))]
pub fn tls_server_end_point(&self) -> Result<Option<Vec<u8>>, Error> {
Ok(None)
}
#[cfg(target_os = "macos")]
pub fn tls_server_end_point(&self) -> Result<Option<Vec<u8>>, Error> {
let cert = match self.cert {
Some(ref cert) => cert.clone(),
None => match self.peer_certificate()? {
Some(cert) => cert.0,
None => return Ok(None),
},
};
let Some(property) = cert
.properties(Some(&[CertificateOid::x509_v1_signature_algorithm()]))
.ok()
.and_then(|p| p.get(CertificateOid::x509_v1_signature_algorithm()))
else {
return Ok(None);
};
let PropertyType::Section(section) = property.get() else {
return Ok(None);
};
let Some(algorithm) = section.iter().find(|p| p.label() == "Algorithm") else {
return Ok(None);
};
let PropertyType::String(algorithm) = algorithm.get() else {
return Ok(None);
};
let digest = match &*algorithm.to_string() {
// MD5
"1.2.840.113549.2.5" | "1.2.840.113549.1.1.4" | "1.3.14.3.2.3" => Digest::Sha256,
// SHA-1
"1.3.14.3.2.26"
| "1.3.14.3.2.15"
| "1.2.840.113549.1.1.5"
| "1.3.14.3.2.29"
| "1.2.840.10040.4.3"
| "1.3.14.3.2.13"
| "1.2.840.10045.4.1" => Digest::Sha256,
// SHA-224
"2.16.840.1.101.3.4.2.4"
| "1.2.840.113549.1.1.14"
| "2.16.840.1.101.3.4.3.1"
| "1.2.840.10045.4.3.1" => Digest::Sha224,
// SHA-256
"2.16.840.1.101.3.4.2.1" | "1.2.840.113549.1.1.11" | "1.2.840.10045.4.3.2" => {
Digest::Sha256
}
// SHA-384
"2.16.840.1.101.3.4.2.2" | "1.2.840.113549.1.1.12" | "1.2.840.10045.4.3.3" => {
Digest::Sha384
}
// SHA-512
"2.16.840.1.101.3.4.2.3" | "1.2.840.113549.1.1.13" | "1.2.840.10045.4.3.4" => {
Digest::Sha512
}
_ => return Ok(None),
};
let der = cert.to_der();
Ok(Some(digest.hash(&der)))
}
pub fn shutdown(&mut self) -> io::Result<()> {
self.stream.close()?;
Ok(())
}
}
impl<S: io::Read + io::Write> io::Read for TlsStream<S> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.stream.read(buf)
}
}
impl<S: io::Read + io::Write> io::Write for TlsStream<S> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.stream.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.stream.flush()
}
}
#[cfg(target_os = "macos")]
enum Digest {
Sha224,
Sha256,
Sha384,
Sha512,
}
#[cfg(target_os = "macos")]
impl Digest {
fn hash(&self, data: &[u8]) -> Vec<u8> {
const CC_SHA224_DIGEST_LENGTH: usize = 28;
const CC_SHA256_DIGEST_LENGTH: usize = 32;
const CC_SHA384_DIGEST_LENGTH: usize = 48;
const CC_SHA512_DIGEST_LENGTH: usize = 64;
unsafe {
assert!(data.len() <= u32::MAX as usize);
match *self {
Digest::Sha224 => {
let mut buf = [0; CC_SHA224_DIGEST_LENGTH];
CC_SHA224(data.as_ptr(), data.len() as u32, buf.as_mut_ptr());
buf.to_vec()
}
Digest::Sha256 => {
let mut buf = [0; CC_SHA256_DIGEST_LENGTH];
CC_SHA256(data.as_ptr(), data.len() as u32, buf.as_mut_ptr());
buf.to_vec()
}
Digest::Sha384 => {
let mut buf = [0; CC_SHA384_DIGEST_LENGTH];
CC_SHA384(data.as_ptr(), data.len() as u32, buf.as_mut_ptr());
buf.to_vec()
}
Digest::Sha512 => {
let mut buf = [0; CC_SHA512_DIGEST_LENGTH];
CC_SHA512(data.as_ptr(), data.len() as u32, buf.as_mut_ptr());
buf.to_vec()
}
}
}
}
}
#[cfg(target_os = "macos")]
extern "C" {
fn CC_SHA224(data: *const u8, len: u32, md: *mut u8) -> *mut u8;
fn CC_SHA256(data: *const u8, len: u32, md: *mut u8) -> *mut u8;
fn CC_SHA384(data: *const u8, len: u32, md: *mut u8) -> *mut u8;
fn CC_SHA512(data: *const u8, len: u32, md: *mut u8) -> *mut u8;
}