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

Add support for client and peer certificates #129

Open
wants to merge 3 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
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ yaml-rust = "0.4.3"
url = "2.1.1"
linked-hash-map = "0.5.3"
tokio = { version = "0.2.20", features = ["rt-core", "rt-threaded", "time", "net", "io-driver"] }
reqwest = { version = "0.10.4", features = ["cookies", "trust-dns"] }
reqwest = { version = "0.10.4", features = ["cookies", "trust-dns", "native-tls"] }
async-trait = "0.1.30"
futures = "0.3.5"
lazy_static = "1.4.0"
Expand All @@ -29,9 +29,9 @@ hdrhistogram = "7.4.0"

# Add openssl-sys as a direct dependency so it can be cross compiled to
# x86_64-unknown-linux-musl using the "vendored" feature below
openssl-sys = "0.9.66"
openssl = "0.10.35"

[features]
# Force openssl-sys to statically link in the openssl library. Necessary when
# cross compiling to x86_64-unknown-linux-musl.
vendored = ["openssl-sys/vendored"]
vendored = ["openssl/vendored"]
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,8 @@ FLAGS:

OPTIONS:
-b, --benchmark <benchmark> Sets the benchmark file
--cacert <cacert> Use the specified certificate to verify the peer (analogous to curl --cacert)
--cert <cert> Use the specified client certificate (analogous to curl --cert)
-c, --compare <compare> Sets a compare file
-r, --report <report> Sets a report file
-t, --threshold <threshold> Sets a threshold value in ms amongst the compared file
Expand Down
48 changes: 47 additions & 1 deletion src/actions/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::time::{Duration, Instant};

use async_trait::async_trait;
use colored::Colorize;
use openssl;
use reqwest::{
header::{self, HeaderMap, HeaderName, HeaderValue},
ClientBuilder, Method, Response,
Expand Down Expand Up @@ -152,7 +153,27 @@ impl Request {
// Resolve the body
let (client, request) = {
let mut pool2 = pool.lock().unwrap();
let client = pool2.entry(domain).or_insert_with(|| ClientBuilder::default().danger_accept_invalid_certs(config.no_check_certificate).build().unwrap());
let client = pool2.entry(domain).or_insert_with(|| {
let mut builder = ClientBuilder::default().danger_accept_invalid_certs(config.no_check_certificate);
if let Some(ref pem) = config.maybe_cert {
let identity = make_identity(pem);
builder = builder.identity(identity);
}

if let Some(ref cacert) = config.maybe_cacert {
let cacert = match reqwest::Certificate::from_pem(&cacert) {
Ok(cert) => cert,
Err(e) => {
eprintln!("Reqwest certificate error: {}", e);
std::process::exit(-1);
}
};

builder = builder.add_root_certificate(cacert);
}

builder.build().unwrap()
});

let request = if let Some(body) = self.body.as_ref() {
interpolated_body = uninterpolator.get_or_insert(interpolator::Interpolator::new(context)).resolve(body, !config.relaxed_interpolations);
Expand Down Expand Up @@ -321,6 +342,31 @@ impl Runnable for Request {
}
}

fn try_pem_to_der(pem: &Vec<u8>) -> Result<Vec<u8>, openssl::error::ErrorStack> {
let key = openssl::pkey::PKey::private_key_from_pem(&pem)?;
let crt = openssl::x509::X509::from_pem(&pem)?;

let pkcs12_builder = openssl::pkcs12::Pkcs12::builder();
let pkcs12 = pkcs12_builder.build("", "client crt", &key, &crt)?;
pkcs12.to_der()
}

fn make_identity(pem: &Vec<u8>) -> reqwest::Identity {
match try_pem_to_der(pem) {
Ok(der) => match reqwest::Identity::from_pkcs12_der(&der, "") {
Ok(identity) => identity,
Err(e) => {
eprintln!("Reqwest ssl error: {}", e);
std::process::exit(-1)
}
},
Err(e) => {
eprintln!("Openssl error: {}", e);
std::process::exit(-1);
}
}
}

fn log_request(request: &reqwest::Request) {
let mut message = String::new();
write!(message, "{}", ">>>".bold().green()).unwrap();
Expand Down
4 changes: 2 additions & 2 deletions src/benchmark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ fn join<S: ToString>(l: Vec<S>, sep: &str) -> String {
)
}

pub fn execute(benchmark_path: &str, report_path_option: Option<&str>, relaxed_interpolations: bool, no_check_certificate: bool, quiet: bool, nanosec: bool, timeout: Option<&str>, verbose: bool) -> BenchmarkResult {
let config = Arc::new(Config::new(benchmark_path, relaxed_interpolations, no_check_certificate, quiet, nanosec, timeout.map_or(10, |t| t.parse().unwrap_or(10)), verbose));
pub fn execute(benchmark_path: &str, report_path_option: Option<&str>, relaxed_interpolations: bool, maybe_cert_path: Option<&str>, maybe_cacert_path: Option<&str>, no_check_certificate: bool, quiet: bool, nanosec: bool, timeout: Option<&str>, verbose: bool) -> BenchmarkResult {
let config = Arc::new(Config::new(benchmark_path, relaxed_interpolations, maybe_cert_path, maybe_cacert_path, no_check_certificate, quiet, nanosec, timeout.map_or(10, |t| t.parse().unwrap_or(10)), verbose));

if report_path_option.is_some() {
println!("{}: {}. Ignoring {} and {} properties...", "Report mode".yellow(), "on".purple(), "concurrency".yellow(), "iterations".yellow());
Expand Down
25 changes: 24 additions & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use yaml_rust::{Yaml, YamlLoader};
use crate::benchmark::Context;
use crate::interpolator;
use crate::reader;
use std::io::Read;

const NITERATIONS: i64 = 1;
const NRAMPUP: i64 = 0;
Expand All @@ -13,6 +14,8 @@ pub struct Config {
pub iterations: i64,
pub relaxed_interpolations: bool,
pub no_check_certificate: bool,
pub maybe_cert: Option<Vec<u8>>,
pub maybe_cacert: Option<Vec<u8>>,
pub rampup: i64,
pub quiet: bool,
pub nanosec: bool,
Expand All @@ -21,7 +24,7 @@ pub struct Config {
}

impl Config {
pub fn new(path: &str, relaxed_interpolations: bool, no_check_certificate: bool, quiet: bool, nanosec: bool, timeout: u64, verbose: bool) -> Config {
pub fn new(path: &str, relaxed_interpolations: bool, maybe_cert_path: Option<&str>, maybe_cacert_path: Option<&str>, no_check_certificate: bool, quiet: bool, nanosec: bool, timeout: u64, verbose: bool) -> Config {
let config_file = reader::read_file(path);

let config_docs = YamlLoader::load_from_str(config_file.as_str()).unwrap();
Expand All @@ -39,12 +42,32 @@ impl Config {
panic!("The concurrency can not be higher than the number of iterations")
}

let maybe_cert = maybe_cert_path.map(|path| {
let mut pem = Vec::new();
if let Err(e) = std::fs::File::open(path).and_then(|mut path| path.read_to_end(&mut pem)) {
eprintln!("Error opening --cert file {}: {}", path, e);
std::process::exit(-1);
}
pem
});

let maybe_cacert = maybe_cacert_path.map(|path| {
let mut cert = Vec::new();
if let Err(e) = std::fs::File::open(path).and_then(|mut path| path.read_to_end(&mut cert)) {
eprintln!("Error opening --cacert file {}: {}", path, e);
std::process::exit(-1);
}
cert
});

Config {
base,
concurrency,
iterations,
relaxed_interpolations,
no_check_certificate,
maybe_cert,
maybe_cacert,
rampup,
quiet,
nanosec,
Expand Down
1 change: 1 addition & 0 deletions src/expandable/include.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ pub fn expand_from_filepath(parent_path: &str, mut benchmark: &mut Benchmark, ac
}
}

#[cfg(test)]
mod tests {
use super::*;

Expand Down
6 changes: 5 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ fn main() {
let stats_option = matches.is_present("stats");
let compare_path_option = matches.value_of("compare");
let threshold_option = matches.value_of("threshold");
let cert = matches.value_of("cert");
let cacert = matches.value_of("cacert");
let no_check_certificate = matches.is_present("no-check-certificate");
let relaxed_interpolations = matches.is_present("relaxed-interpolations");
let quiet = matches.is_present("quiet");
Expand All @@ -32,7 +34,7 @@ fn main() {
#[cfg(windows)]
let _ = control::set_virtual_terminal(true);

let benchmark_result = benchmark::execute(benchmark_file, report_path_option, relaxed_interpolations, no_check_certificate, quiet, nanosec, timeout, verbose);
let benchmark_result = benchmark::execute(benchmark_file, report_path_option, relaxed_interpolations, cert, cacert, no_check_certificate, quiet, nanosec, timeout, verbose);
let list_reports = benchmark_result.reports;
let duration = benchmark_result.duration;

Expand All @@ -52,6 +54,8 @@ fn app_args<'a>() -> clap::ArgMatches<'a> {
.arg(Arg::with_name("compare").short("c").long("compare").help("Sets a compare file").takes_value(true).conflicts_with("report"))
.arg(Arg::with_name("threshold").short("t").long("threshold").help("Sets a threshold value in ms amongst the compared file").takes_value(true).conflicts_with("report"))
.arg(Arg::with_name("relaxed-interpolations").long("relaxed-interpolations").help("Do not panic if an interpolation is not present. (Not recommended)").takes_value(false))
.arg(Arg::with_name("cert").help("Use the specified client certificate (analogous to curl --cert)").long("cert").required(false).takes_value(true))
.arg(Arg::with_name("cacert").help("Use the specified certificate to verify the peer (analogous to curl --cacert)").long("cacert").required(false).takes_value(true))
.arg(Arg::with_name("no-check-certificate").long("no-check-certificate").help("Disables SSL certification check. (Not recommended)").takes_value(false))
.arg(Arg::with_name("quiet").short("q").long("quiet").help("Disables output").takes_value(false))
.arg(Arg::with_name("timeout").short("o").long("timeout").help("Set timeout in seconds for all requests").takes_value(true))
Expand Down