Auto-generate TLS server certificate for unix platform (#8)

* Add cert generation for unix targets

* Fix early-data.rs check

* Make clippy happy
This commit is contained in:
Denis Molokanov 2020-04-03 07:16:23 -07:00 committed by GitHub
parent 1c3aeb691e
commit 447a040a43
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 89 additions and 8 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
/target /target
**/*.rs.bk **/*.rs.bk
Cargo.lock Cargo.lock
.DS_Store

View File

@ -33,6 +33,9 @@ cfg-if = "0.1"
env_logger = { version = "0.6", default-features = false } env_logger = { version = "0.6", default-features = false }
futures = { version = "0.3.0", features = ["async-await"] } futures = { version = "0.3.0", features = ["async-await"] }
tempfile = "3.1"
lazy_static = "1.4.0"
[target.'cfg(all(not(target_os = "macos"), not(windows), not(target_os = "ios")))'.dev-dependencies] [target.'cfg(all(not(target_os = "macos"), not(windows), not(target_os = "ios")))'.dev-dependencies]
openssl = "0.10" openssl = "0.10"

View File

@ -0,0 +1,57 @@
#!/bin/bash
set -e
cd $1
# prepare config file for root CA generation
cat <<EOF >> root.cnf
[ req ]
distinguished_name = req_dn
[ req_dn ]
[ v3_ca ]
basicConstraints = CA:TRUE
keyUsage = digitalSignature, nonRepudiation, keyCertSign, cRLSign
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always
EOF
ROOT_CA_KEY=root-ca.key.pem
ROOT_CA=root-ca.pem
ROOT_CA_DER=root-ca.der
echo "Generate root CA key"
openssl genrsa -out $ROOT_CA_KEY 4096
echo "Generate root CA certificate"
openssl req -x509 -new -key $ROOT_CA_KEY -out $ROOT_CA -days 365 -SHA256 -subj "/C=AU/ST=Some-State/O=Internet Widgits Pty Ltd" -config root.cnf -extensions v3_ca
openssl x509 -outform der -in $ROOT_CA -out $ROOT_CA_DER
rm root.cnf
# prepare config file for server certificate generation
cat <<EOF >> server.cnf
extendedKeyUsage=serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = foobar.com
EOF
SERVER_KEY=server.key.pem
SERVER_CERT=cert.pem
SERVER_CERT_DER=cert.der
IDENTITY=identity.p12
PASSPHRASE=mypass
echo "Generate server key"
openssl genrsa -out $SERVER_KEY 4096
echo "Generate server certificate"
openssl req -out server.csr -key $SERVER_KEY -new -days 365 -SHA256 -subj "/C=AU/ST=Some-State/O=Internet Widgits Pty Ltd/CN=foobar.com"
openssl x509 -req -days 365 -SHA256 -in server.csr -CA $ROOT_CA -CAkey $ROOT_CA_KEY -CAcreateserial -out $SERVER_CERT -extfile server.cnf
openssl x509 -outform der -in $SERVER_CERT -out $SERVER_CERT_DER
openssl pkcs12 -export -out $IDENTITY -inkey $SERVER_KEY -in $SERVER_CERT -passout pass:$PASSPHRASE
rm server.csr
rm server.cnf

View File

@ -1,12 +1,32 @@
use futures::join; use futures::join;
use lazy_static::lazy_static;
use native_tls::{Certificate, Identity}; use native_tls::{Certificate, Identity};
use std::io::Error; use std::{fs, io::Error, path::PathBuf, process::Command};
use tokio::{ use tokio::{
io::{AsyncReadExt, AsyncWrite, AsyncWriteExt}, io::{AsyncReadExt, AsyncWrite, AsyncWriteExt},
net::{TcpListener, TcpStream}, net::{TcpListener, TcpStream},
}; };
use tokio_native_tls::{TlsAcceptor, TlsConnector}; use tokio_native_tls::{TlsAcceptor, TlsConnector};
lazy_static! {
static ref CERT_DIR: PathBuf = {
if cfg!(unix) {
let dir = tempfile::TempDir::new().unwrap();
let path = dir.path().to_str().unwrap();
Command::new("sh")
.arg("-c")
.arg(format!("./scripts/generate-certificate.sh {}", path))
.output()
.expect("failed to execute process");
dir.into_path()
} else {
PathBuf::from("tests")
}
};
}
#[tokio::test] #[tokio::test]
async fn client_to_server() { async fn client_to_server() {
let mut srv = TcpListener::bind("127.0.0.1:0").await.unwrap(); let mut srv = TcpListener::bind("127.0.0.1:0").await.unwrap();
@ -26,7 +46,7 @@ async fn client_to_server() {
let _peer_cert = native_tls_stream.peer_certificate().unwrap(); let _peer_cert = native_tls_stream.peer_certificate().unwrap();
let allow_std_stream: &tokio_native_tls::AllowStd<_> = native_tls_stream.get_ref(); let allow_std_stream: &tokio_native_tls::AllowStd<_> = native_tls_stream.get_ref();
let _tokio_tcp_stream: &tokio::net::TcpStream = allow_std_stream.get_ref(); let _tokio_tcp_stream: &tokio::net::TcpStream = allow_std_stream.get_ref();
let mut data = Vec::new(); let mut data = Vec::new();
socket.read_to_end(&mut data).await.unwrap(); socket.read_to_end(&mut data).await.unwrap();
data data
@ -115,14 +135,13 @@ async fn one_byte_at_a_time() {
} }
fn context() -> (TlsAcceptor, TlsConnector) { fn context() -> (TlsAcceptor, TlsConnector) {
// Certs borrowed from `rust-native-tls/tests` let pkcs12 = fs::read(CERT_DIR.join("identity.p12")).unwrap();
let pkcs12 = include_bytes!("identity.p12"); let der = fs::read(CERT_DIR.join("root-ca.der")).unwrap();
let der = include_bytes!("root-ca.der");
let identity = Identity::from_pkcs12(pkcs12, "mypass").unwrap(); let identity = Identity::from_pkcs12(&pkcs12, "mypass").unwrap();
let acceptor = native_tls::TlsAcceptor::builder(identity).build().unwrap(); let acceptor = native_tls::TlsAcceptor::builder(identity).build().unwrap();
let cert = Certificate::from_der(der).unwrap(); let cert = Certificate::from_der(&der).unwrap();
let connector = native_tls::TlsConnector::builder() let connector = native_tls::TlsConnector::builder()
.add_root_certificate(cert) .add_root_certificate(cert)
.build() .build()

View File

@ -1,10 +1,11 @@
#![cfg(feature = "early-data")] #![cfg(feature = "early-data")]
use futures_util::{future, future::Future, ready};
use rustls::ClientConfig;
use std::io::{self, BufRead, BufReader, Cursor}; use std::io::{self, BufRead, BufReader, Cursor};
use std::net::SocketAddr; use std::net::SocketAddr;
use std::pin::Pin; use std::pin::Pin;
use std::process::{Child, Command, Stdio}; use std::process::{Child, Command, Stdio};
use std::process::{Child, Command, Stdio};
use std::sync::Arc; use std::sync::Arc;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use std::time::Duration; use std::time::Duration;