-
-
Notifications
You must be signed in to change notification settings - Fork 213
Implement PKCS8 certificate support for all three backends. #147
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
Changes from 6 commits
eb269b8
c400390
1a6d7ba
ab437ba
beb8ebc
28eade4
7e9a612
da4cf1a
255dd54
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
extern crate native_tls; | ||
|
||
use native_tls::{Identity, TlsAcceptor, TlsStream}; | ||
use std::fs::File; | ||
use std::io::{Read, Write}; | ||
use std::net::{TcpListener, TcpStream}; | ||
use std::sync::Arc; | ||
use std::thread; | ||
|
||
fn main() { | ||
let mut cert_file = File::open("test/cert.pem").unwrap(); | ||
let mut certs = vec![]; | ||
cert_file.read_to_end(&mut certs).unwrap(); | ||
let mut key_file = File::open("test/key.pem").unwrap(); | ||
let mut key = vec![]; | ||
key_file.read_to_end(&mut key).unwrap(); | ||
let pkcs8 = Identity::from_pkcs8(&certs, &key).unwrap(); | ||
|
||
let acceptor = TlsAcceptor::new(pkcs8).unwrap(); | ||
let acceptor = Arc::new(acceptor); | ||
|
||
let listener = TcpListener::bind("0.0.0.0:8443").unwrap(); | ||
|
||
fn handle_client(mut stream: TlsStream<TcpStream>) { | ||
let mut buf = [0; 1024]; | ||
let read = stream.read(&mut buf).unwrap(); | ||
let received = std::str::from_utf8(&buf[0..read]).unwrap(); | ||
stream.write_all(format!("received '{}'", received).as_bytes()).unwrap(); | ||
} | ||
|
||
for stream in listener.incoming() { | ||
match stream { | ||
Ok(stream) => { | ||
let acceptor = acceptor.clone(); | ||
thread::spawn(move || { | ||
let stream = acceptor.accept(stream).unwrap(); | ||
handle_client(stream); | ||
}); | ||
} | ||
Err(_e) => { /* connection failed */ } | ||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,7 +5,7 @@ use self::openssl::error::ErrorStack; | |
use self::openssl::hash::MessageDigest; | ||
use self::openssl::nid::Nid; | ||
use self::openssl::pkcs12::Pkcs12; | ||
use self::openssl::pkey::PKey; | ||
use self::openssl::pkey::{PKey, Private}; | ||
use self::openssl::ssl::{ | ||
self, MidHandshakeSslStream, SslAcceptor, SslConnector, SslContextBuilder, SslMethod, | ||
SslVerifyMode, | ||
|
@@ -17,7 +17,6 @@ use std::io; | |
use std::sync::{Once, ONCE_INIT}; | ||
|
||
use {Protocol, TlsAcceptorBuilder, TlsConnectorBuilder}; | ||
use self::openssl::pkey::Private; | ||
|
||
#[cfg(have_min_max_version)] | ||
fn supported_protocols( | ||
|
@@ -168,6 +167,19 @@ impl Identity { | |
chain: parsed.chain.into_iter().flat_map(|x| x).collect(), | ||
}) | ||
} | ||
|
||
pub fn from_pkcs8(buf: &[u8], key: &[u8]) -> Result<Identity, Error> { | ||
let pkey = PKey::private_key_from_pem(key)?; | ||
let mut cert_chain = X509::stack_from_pem(buf)?.into_iter(); | ||
let cert = cert_chain.next(); | ||
let chain = cert_chain.collect(); | ||
Ok(Identity { | ||
pkey, | ||
// an identity must have at least one certificate, the leaf cert | ||
cert: cert.expect("at least one certificate must be provided to create an identity"), | ||
chain: chain, | ||
}) | ||
} | ||
} | ||
|
||
#[derive(Clone)] | ||
|
@@ -265,7 +277,10 @@ impl TlsConnector { | |
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().rev() { | ||
for cert in identity.0.chain.iter() { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I do not believe this change is correct: 05fb5e5 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
This is from https://www.openssl.org/docs/manmaster/man3/SSL_CTX_add_extra_chain_cert.html , though looking at https://www.openssl.org/docs/manmaster/man3/PKCS12_parse.html I don't see any documentation about ordering restrictions for There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There really needs to be a cross-platform test for this behavior. |
||
// 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())?; | ||
} | ||
} | ||
|
@@ -314,7 +329,10 @@ impl TlsAcceptor { | |
let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls())?; | ||
acceptor.set_private_key(&builder.identity.0.pkey)?; | ||
acceptor.set_certificate(&builder.identity.0.cert)?; | ||
for cert in builder.identity.0.chain.iter().rev() { | ||
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)?; | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,9 @@ | ||
extern crate schannel; | ||
|
||
use self::schannel::cert_context::{CertContext, HashAlgorithm}; | ||
use self::schannel::cert_context::{CertContext, HashAlgorithm, KeySpec}; | ||
use self::schannel::cert_store::{CertAdd, CertStore, Memory, PfxImportOptions}; | ||
use self::schannel::schannel_cred::{Direction, Protocol, SchannelCred}; | ||
use self::schannel::crypt_prov::{AcquireOptions, ProviderType}; | ||
use self::schannel::tls_stream; | ||
use std::error; | ||
use std::fmt; | ||
|
@@ -96,6 +97,38 @@ impl Identity { | |
|
||
Ok(Identity { cert: identity }) | ||
} | ||
|
||
pub fn from_pkcs8(pem: &[u8], key: &[u8]) -> Result<Identity, Error> { | ||
let mut store = Memory::new()?.into_store(); | ||
let mut cert_iter = crate::pem::PemBlock::new(pem).into_iter(); | ||
let leaf = cert_iter.next().expect("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 mut options = AcquireOptions::new(); | ||
options.container("schannel"); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I seem to remember there being problems on windows if the same container name is used multiple times. Probably worth a test that parses a couple of identities to confirm. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is the test case that caused issues on my previous attempt: b0b9164 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think this test still needs to be added. |
||
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("schannel") | ||
.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, schannel::cert_store::CertAdd::Always)?; | ||
} | ||
Ok(Identity{cert: context}) | ||
} | ||
} | ||
|
||
#[derive(Clone)] | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,113 @@ | ||
#![allow(unused)] | ||
Goirad marked this conversation as resolved.
Show resolved
Hide resolved
|
||
use rustc_serialize::base64::{self, FromBase64, ToBase64}; | ||
|
||
/// Type of the various `PEM_*` constants supplied to `pem_to_der` / `der_to_pem`. | ||
pub struct PemGuard { | ||
begin: &'static str, | ||
end: &'static str, | ||
} | ||
|
||
macro_rules! pem_guard { | ||
($n:expr) => { | ||
&PemGuard { | ||
begin: concat!("-----BEGIN ", $n, "-----"), | ||
end: concat!("-----END ", $n, "-----"), | ||
} | ||
} | ||
} | ||
|
||
// Ref. RFC7468, although these are not universally respected. | ||
pub const PEM_CERTIFICATE: &'static PemGuard = pem_guard!("CERTIFICATE"); | ||
pub const PEM_CERTIFICATE_REQUEST: &'static PemGuard = pem_guard!("CERTIFICATE REQUEST"); | ||
pub const PEM_ENCRYPTED_PRIVATE_KEY: &'static PemGuard = pem_guard!("ENCRYPTED PRIVATE KEY"); | ||
pub const PEM_PRIVATE_KEY: &'static PemGuard = pem_guard!("PRIVATE KEY"); | ||
pub const PEM_PUBLIC_KEY: &'static PemGuard = pem_guard!("PUBLIC KEY"); | ||
pub const PEM_CMS: &'static PemGuard = pem_guard!("CMS"); | ||
|
||
const BASE64_PEM_WRAP: usize = 64; | ||
|
||
lazy_static!{ | ||
static ref BASE64_PEM: base64::Config = base64::Config { | ||
Goirad marked this conversation as resolved.
Show resolved
Hide resolved
|
||
char_set: base64::CharacterSet::Standard, | ||
newline: base64::Newline::LF, | ||
pad: true, | ||
line_length: Some(BASE64_PEM_WRAP), | ||
}; | ||
} | ||
|
||
/// Split data by PEM guard lines | ||
pub struct PemBlock<'a> { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Since this is only used by the schannel backend, could you move it into that module? |
||
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, | ||
}; | ||
return Some(&self.pem_block[begin..self.cur_end].as_bytes()); | ||
} | ||
} | ||
|
||
#[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]]); | ||
} |
Uh oh!
There was an error while loading. Please reload this page.