Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TlsStream::certificate_chain, ChainIterator type and Certificate::public_key_info_der #117

Open
wants to merge 21 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ readme = "README.md"
vendored = ["openssl/vendored"]

[target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies]
security-framework = "0.3.1"
security-framework-sys = "0.3.1"
security-framework = {version = "0.3.1", features = ["OSX_10_12"]}
security-framework-sys = {version = "0.3.1", features = ["OSX_10_12"]}
lazy_static = "1.0"
libc = "0.2"
tempfile = "3.0"

[target.'cfg(target_os = "windows")'.dependencies]
schannel = "0.1.13"
schannel = {version = "0.1.15"}

[target.'cfg(not(any(target_os = "windows", target_os = "macos", target_os = "ios")))'.dependencies]
log = "0.4.5"
Expand Down
29 changes: 28 additions & 1 deletion src/imp/openssl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ use self::openssl::ssl::{
self, MidHandshakeSslStream, SslAcceptor, SslConnector, SslContextBuilder, SslMethod,
SslVerifyMode,
};
use self::openssl::x509::{X509, X509VerifyResult};
use self::openssl::stack;
use self::openssl::x509::{X509VerifyResult, X509};
use std::error;
use std::fmt;
use std::io;
Expand Down Expand Up @@ -177,6 +178,12 @@ impl Certificate {
let der = self.0.to_der()?;
Ok(der)
}

pub fn public_key_info_der(&self) -> Result<Vec<u8>, Error> {
let pk = self.0.public_key()?;
let der = pk.public_key_to_der()?;
Ok(der)
}
}

pub struct MidHandshakeTlsStream<S>(MidHandshakeSslStream<S>);
Expand Down Expand Up @@ -324,6 +331,19 @@ impl TlsAcceptor {
}
}

pub struct ChainIterator<'a, S: 'a>(Option<stack::Iter<'a, X509>>, &'a TlsStream<S>);

impl<'a, S> Iterator for ChainIterator<'a, S> {
type Item = Certificate;

fn next(&mut self) -> Option<Self::Item> {
if let Some(i) = self.0.as_mut() {
return i.next().map(|c| Certificate(c.to_owned()));
}
None
}
}

pub struct TlsStream<S>(ssl::SslStream<S>);

impl<S: fmt::Debug> fmt::Debug for TlsStream<S> {
Expand All @@ -349,6 +369,13 @@ impl<S: io::Read + io::Write> TlsStream<S> {
Ok(self.0.ssl().peer_certificate().map(Certificate))
}

pub fn certificate_chain(&mut self) -> Result<ChainIterator<S>, Error> {
Ok(ChainIterator(
self.0.ssl().peer_cert_chain().map(|stack| stack.iter()),
self,
))
}

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())
Expand Down
89 changes: 70 additions & 19 deletions src/imp/schannel.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
extern crate schannel;

use self::schannel::cert_context::{CertContext, HashAlgorithm};
use self::schannel::cert_store::{CertAdd, CertStore, Memory, PfxImportOptions};
use self::schannel::cert_store::{CertAdd, CertStore, Certs, Memory, PfxImportOptions};
use self::schannel::schannel_cred::{Direction, Protocol, SchannelCred};
use self::schannel::tls_stream;
use std::error;
Expand Down Expand Up @@ -89,7 +89,8 @@ impl Identity {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"No identity found in PKCS #12 archive",
).into());
)
.into());
}
};

Expand All @@ -115,13 +116,18 @@ impl Certificate {
Err(_) => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"PEM representation contains non-UTF-8 bytes",
).into()),
)
.into()),
}
}

pub fn to_der(&self) -> Result<Vec<u8>, Error> {
Ok(self.0.to_der().to_vec())
}

pub fn public_key_info_der(&self) -> Result<Vec<u8>, Error> {
Ok(self.0.subject_public_key_info_der()?)
}
}

pub struct MidHandshakeTlsStream<S>(tls_stream::MidHandshakeTlsStream<S>);
Expand Down Expand Up @@ -149,7 +155,10 @@ where

pub fn handshake(self) -> Result<TlsStream<S>, HandshakeError<S>> {
match self.0.handshake() {
Ok(s) => Ok(TlsStream(s)),
Ok(stream) => Ok(TlsStream {
stream,
store: None,
}),
Err(e) => Err(e.into()),
}
}
Expand Down Expand Up @@ -227,7 +236,10 @@ impl TlsConnector {
builder.verify_callback(|_| Ok(()));
}
match builder.connect(cred, stream) {
Ok(s) => Ok(TlsStream(s)),
Ok(stream) => Ok(TlsStream {
stream,
store: None,
}),
Err(e) => Err(e.into()),
}
}
Expand Down Expand Up @@ -259,46 +271,85 @@ impl TlsAcceptor {
// FIXME we're probably missing the certificate chain?
let cred = builder.acquire(Direction::Inbound)?;
match tls_stream::Builder::new().accept(cred, stream) {
Ok(s) => Ok(TlsStream(s)),
Ok(stream) => Ok(TlsStream {
stream,
store: None,
}),
Err(e) => Err(e.into()),
}
}
}

pub struct TlsStream<S>(tls_stream::TlsStream<S>);
pub struct ChainIterator<'a, S: 'a> {
certs: Option<Certs<'a>>,
_stream: &'a TlsStream<S>,
}
impl<'a, S> Iterator for ChainIterator<'a, S> {
type Item = Certificate;

fn next(&mut self) -> Option<Self::Item> {
if let Some(certs) = self.certs.as_mut() {
return certs.next().map(Certificate);
}
None
}
}

pub struct TlsStream<S> {
stream: tls_stream::TlsStream<S>,
store: Option<CertStore>,
}

impl<S: fmt::Debug> fmt::Debug for TlsStream<S> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.0, fmt)
fmt::Debug::fmt(&self.stream, fmt)
}
}

impl<S: io::Read + io::Write> TlsStream<S> {
pub fn get_ref(&self) -> &S {
self.0.get_ref()
self.stream.get_ref()
}

pub fn get_mut(&mut self) -> &mut S {
self.0.get_mut()
self.stream.get_mut()
}

pub fn buffered_read_size(&self) -> Result<usize, Error> {
Ok(self.0.get_buf().len())
Ok(self.stream.get_buf().len())
}

pub fn peer_certificate(&self) -> Result<Option<Certificate>, Error> {
match self.0.peer_certificate() {
match self.stream.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)),
}
}

pub fn certificate_chain(&mut self) -> Result<ChainIterator<S>, Error> {
if self.store.is_none() {
match self.stream.peer_certificate() {
Ok(cert) => {
self.store = cert.cert_store();
}
Err(ref e) if e.raw_os_error() == Some(SEC_E_NO_CREDENTIALS as i32) => {
self.store = None;
}
Err(e) => return Err(Error(e)),
}
}
Ok(ChainIterator {
certs: self.store.as_ref().map(|c| c.certs()),
_stream: self,
})
}

pub fn tls_server_end_point(&self) -> Result<Option<Vec<u8>>, Error> {
let cert = if self.0.is_server() {
self.0.certificate()
let cert = if self.stream.is_server() {
self.stream.certificate()
} else {
self.0.peer_certificate()
self.stream.peer_certificate()
};

let cert = match cert {
Expand All @@ -320,23 +371,23 @@ impl<S: io::Read + io::Write> TlsStream<S> {
}

pub fn shutdown(&mut self) -> io::Result<()> {
self.0.shutdown()?;
self.stream.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)
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.0.write(buf)
self.stream.write(buf)
}

fn flush(&mut self) -> io::Result<()> {
self.0.flush()
self.stream.flush()
}
}
41 changes: 40 additions & 1 deletion src/imp/security_framework.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,20 @@ extern crate security_framework;
extern crate security_framework_sys;
extern crate tempfile;

use self::security_framework::base;
use self::security_framework::certificate::SecCertificate;
use self::security_framework::identity::SecIdentity;
use self::security_framework::import_export::{ImportedIdentity, Pkcs12ImportOptions};
use self::security_framework::secure_transport::{
self, ClientBuilder, SslConnectionType, SslContext, SslProtocol, SslProtocolSide,
};
use self::security_framework::{base, trust::SecTrust};
use self::security_framework_sys::base::errSecIO;

use self::tempfile::TempDir;
use std::error;
use std::fmt;
use std::io;

use std::sync::Mutex;
use std::sync::{Once, ONCE_INIT};

Expand Down Expand Up @@ -174,6 +176,10 @@ impl Certificate {
pub fn to_der(&self) -> Result<Vec<u8>, Error> {
Ok(self.0.to_der())
}

pub fn public_key_info_der(&self) -> Result<Vec<u8>, Error> {
Ok(self.0.public_key_info_der()?.unwrap_or(Vec::new()))
}
}

pub enum HandshakeError<S> {
Expand Down Expand Up @@ -351,6 +357,24 @@ impl TlsAcceptor {
}
}

pub struct ChainIterator<'a, S: 'a> {
trust: Option<SecTrust>,
pos: usize,
_stream: &'a TlsStream<S>,
}
impl<'a, S> Iterator for ChainIterator<'a, S> {
type Item = Certificate;

fn next(&mut self) -> Option<Self::Item> {
if let Some(trust) = self.trust.as_ref() {
let pos = self.pos;
self.pos += 1;
return trust.certificate_at_index(pos as _).map(Certificate);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs to stop at the end of the chain, right?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Trust will return None once it is over limit.

}
None
}
}

pub struct TlsStream<S> {
stream: secure_transport::SslStream<S>,
cert: Option<SecCertificate>,
Expand Down Expand Up @@ -385,6 +409,21 @@ impl<S: io::Read + io::Write> TlsStream<S> {
Ok(trust.certificate_at_index(0).map(Certificate))
}

pub fn certificate_chain(&mut self) -> Result<ChainIterator<S>, Error> {
let trust = match self.stream.context().peer_trust2()? {
Some(trust) => {
trust.evaluate()?;
Some(trust)
}
None => None,
};
Ok(ChainIterator {
trust,
pos: 0,
_stream: self,
})
}

#[cfg(target_os = "ios")]
pub fn tls_server_end_point(&self) -> Result<Option<Vec<u8>>, Error> {
Ok(None)
Expand Down
22 changes: 22 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,23 @@ impl Certificate {
let der = self.0.to_der()?;
Ok(der)
}

/// Returns der encoded subjectPublicKeyInfo.
pub fn public_key_info_der(&self) -> Result<Vec<u8>> {
let der = self.0.public_key_info_der()?;
Ok(der)
}
}

/// An iterator over a certificate chain.
pub struct ChainIterator<'a, S: 'a>(imp::ChainIterator<'a, S>);

impl<'a, S> Iterator for ChainIterator<'a, S> {
type Item = Certificate;

fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(Certificate)
}
}

/// A TLS stream which has been interrupted midway through the handshake process.
Expand Down Expand Up @@ -630,6 +647,11 @@ impl<S: io::Read + io::Write> TlsStream<S> {
Ok(self.0.peer_certificate()?.map(Certificate))
}

/// Returns an iterator over certificate chain. It may be an empty iterator if chain not available.
pub fn certificate_chain(&mut self) -> Result<ChainIterator<S>> {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we distinguish the "no chain present" case here by returning something like Result<Option<ChainIterator>>?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer to create an empty iterator that just returns None immediately. That is what happens in the downstream crates. Result<Option> is a pretty annoying API.

Ok(ChainIterator(self.0.certificate_chain()?))
}

/// Returns the tls-server-end-point channel binding data as defined in [RFC 5929].
///
/// [RFC 5929]: https://tools.ietf.org/html/rfc5929
Expand Down