Skip to content

Commit

Permalink
Add MTC support to MIO examples
Browse files Browse the repository at this point in the history
  • Loading branch information
pohlm01 committed Oct 3, 2024
1 parent d8461a3 commit 52773b6
Show file tree
Hide file tree
Showing 7 changed files with 68 additions and 159 deletions.
75 changes: 0 additions & 75 deletions examples/src/bin/simpleclient_merkle_tree_certs.rs

This file was deleted.

67 changes: 0 additions & 67 deletions examples/src/bin/simpleserver_merkle_tree_certs.rs

This file was deleted.

22 changes: 21 additions & 1 deletion examples/src/bin/tlsclient-mio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ use mio::net::TcpStream;
use rustls::crypto::{aws_lc_rs as provider, CryptoProvider};
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
use rustls::RootCertStore;
use rustls::{CertificateType, RootCertStore};
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{fmt, EnvFilter};

const CLIENT: mio::Token = mio::Token(0);

Expand Down Expand Up @@ -131,6 +134,7 @@ impl TlsClient {
.reader()
.read_exact(&mut plaintext)
.unwrap();
println!("Received text:");
io::stdout()
.write_all(&plaintext)
.unwrap();
Expand Down Expand Up @@ -473,12 +477,28 @@ fn make_config(args: &Args) -> Arc<rustls::ClientConfig> {
)));
}

config.trusted_trust_anchors = vec![
"62253.12.15.0".parse().unwrap(),
"62253.12.15.1".parse().unwrap(),
];
config.supported_server_certificate_types =
vec![CertificateType::X509, CertificateType::Bikeshed];

Arc::new(config)
}

/// Parse some arguments, then make a TLS client connection
/// somewhere.
fn main() {
tracing_subscriber::registry()
.with(
fmt::layer()
.with_file(true)
.with_line_number(true),
)
.with(EnvFilter::from_default_env())
.init();

let args = Args::parse();

if args.verbose {
Expand Down
54 changes: 44 additions & 10 deletions examples/src/bin/tlsserver-mio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,6 @@
//!
//! [mio]: https://docs.rs/mio/latest/mio/
use std::collections::HashMap;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::{fs, net};

use clap::{Parser, Subcommand};
use log::{debug, error};
use mio::net::{TcpListener, TcpStream};
Expand All @@ -33,6 +27,15 @@ use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, CertificateRevocationListDer, PrivateKeyDer};
use rustls::server::WebPkiClientVerifier;
use rustls::RootCertStore;
use std::collections::HashMap;
use std::fs::File;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::{fs, net};
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{fmt, EnvFilter};

// Token for our listening socket.
const LISTENER: mio::Token = mio::Token(0);
Expand Down Expand Up @@ -447,6 +450,9 @@ struct Args {
/// private key, the last should be a root CA).
#[clap(long)]
certs: PathBuf,

#[clap(long)]
mtc_cert: Option<PathBuf>,
/// Perform client certificate revocation checking using the DER-encoded CRLs from the given
/// files.
#[clap(long)]
Expand Down Expand Up @@ -527,6 +533,13 @@ fn load_certs(filename: &Path) -> Vec<CertificateDer<'static>> {
.collect()
}

fn load_mtc_cert(filename: &Path) -> Vec<u8> {
let mut res = vec![];
let mut f = File::open(filename).unwrap();
f.read_to_end(&mut res).unwrap();
res
}

fn load_private_key(filename: &Path) -> PrivateKeyDer<'static> {
PrivateKeyDer::from_pem_file(filename).expect("cannot read private key file")
}
Expand Down Expand Up @@ -591,10 +604,14 @@ fn make_config(args: &Args) -> Arc<rustls::ServerConfig> {
};

let certs = load_certs(&args.certs);
let mtc_cert = args
.mtc_cert
.as_ref()
.map(|f| load_mtc_cert(f));
let privkey = load_private_key(&args.key);
let ocsp = load_ocsp(args.ocsp.as_deref());

let mut config = rustls::ServerConfig::builder_with_provider(
let config_builder = rustls::ServerConfig::builder_with_provider(
CryptoProvider {
cipher_suites: suites,
..provider::default_provider()
Expand All @@ -603,9 +620,17 @@ fn make_config(args: &Args) -> Arc<rustls::ServerConfig> {
)
.with_protocol_versions(&versions)
.expect("inconsistent cipher-suites/versions specified")
.with_client_cert_verifier(client_auth)
.with_single_cert_with_ocsp(certs, privkey, ocsp)
.expect("bad certificates/private key");
.with_client_cert_verifier(client_auth);

let mut config = if let Some(mtc_cert) = mtc_cert {
config_builder
.with_single_mtc_cert("62253.12.15.1", mtc_cert, privkey)
.expect("bad certificates/private key")
} else {
config_builder
.with_single_cert_with_ocsp(certs, privkey, ocsp)
.expect("bad certificates/private key")
};

config.key_log = Arc::new(rustls::KeyLogFile::new());

Expand Down Expand Up @@ -636,6 +661,15 @@ fn make_config(args: &Args) -> Arc<rustls::ServerConfig> {
}

fn main() {
tracing_subscriber::registry()
.with(
fmt::layer()
.with_file(true)
.with_line_number(true),
)
.with(EnvFilter::from_default_env())
.init();

let args = Args::parse();
if args.verbose {
env_logger::Builder::new()
Expand Down
5 changes: 1 addition & 4 deletions rustls/src/client/tls13.rs
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,6 @@ impl State<ClientConnectionData> for ExpectEncryptedExtensions {
}
}


cx.common.certificate_type = exts
.selected_server_certificate_type()
.unwrap_or(CertificateType::X509);
Expand Down Expand Up @@ -1097,9 +1096,7 @@ impl State<ClientConnectionData> for ExpectCertificate {
}
CertificateType::RawPublicKey => unimplemented!(),
CertificateType::Bikeshed => {
ServerCertDetails::from_bikeshed(
cert_payload.into_bikeshed_certificate()
)
ServerCertDetails::from_bikeshed(cert_payload.into_bikeshed_certificate())
}
CertificateType::Unknown(_) => unimplemented!(),
};
Expand Down
3 changes: 1 addition & 2 deletions rustls/src/msgs/handshake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1900,7 +1900,7 @@ impl<'a> CertificatePayloadTls13<'a> {
.collect(),
)
}

pub(crate) fn into_bikeshed_certificate(mut self) -> BikeshedCertificate<'a> {
assert_eq!(self.entries.len(), 1);
BikeshedCertificate(self.entries.remove(0).cert)
Expand Down Expand Up @@ -2271,7 +2271,6 @@ pub(crate) trait HasServerExtensions {
.is_some()
}


fn selected_server_certificate_type(&self) -> Option<CertificateType> {
let ext = self.find_extension(ExtensionType::ServerCertificateType)?;
match *ext {
Expand Down
1 change: 1 addition & 0 deletions rustls/src/msgs/persist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,7 @@ impl Codec<'_> for ServerSessionValue {
self.cipher_suite.encode(bytes);
self.master_secret.encode(bytes);
(u8::from(self.extended_ms)).encode(bytes);
// TODO @max probably comply with https://datatracker.ietf.org/doc/html/rfc5077#section-4
if let Some(ref chain) = self.client_cert_chain {
1u8.encode(bytes);
chain.encode(bytes);
Expand Down

0 comments on commit 52773b6

Please sign in to comment.