diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 09d5b7357..1f571c846 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -2,11 +2,19 @@ name: CI on: push: + paths-ignore: + - '*.md' + - 'LICENSE-APACHE' + - 'LICENSE-GPL' branches: - 'v0.*' - staging - trying pull_request: + paths-ignore: + - '*.md' + - 'LICENSE-APACHE' + - 'LICENSE-GPL' branches: - mbedtls-3 - main @@ -34,9 +42,6 @@ jobs: - rust: stable target: x86_64-pc-windows-msvc os: windows-latest - - rust: stable - target: x86_64-pc-windows-msvc - os: windows-latest - rust: stable target: x86_64-pc-windows-msvc os: windows-2019 @@ -53,7 +58,7 @@ jobs: runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: Install qemu-user for aarch64 target if: matrix.target == 'aarch64-unknown-linux-musl' @@ -73,11 +78,10 @@ jobs: key: ${{ matrix.rust }} - name: Setup Rust toolchain - uses: actions-rs/toolchain@v1 + uses: dtolnay/rust-toolchain@master with: toolchain: ${{ matrix.rust }} - target: ${{ matrix.target }} - override: true + targets: ${{ matrix.target }} - name: Run tests run: | @@ -96,12 +100,27 @@ jobs: AES_NI_SUPPORT: ${{ matrix.target == 'x86_64-unknown-linux-gnu' && 'true' || '' }} shell: bash + fmt: + name: Rustfmt + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: stable + components: rustfmt + - name: Enforce formatting + run: | + cargo fmt --check -p mbedtls + cargo fmt --check -p mbedtls-platform-support + cargo fmt --check -p mbedtls-sys-auto ci-success: name: ci if: always() needs: - test - runs-on: ubuntu-20.04 + - fmt + runs-on: ubuntu-latest steps: - run: jq --exit-status 'all(.result == "success")' <<< '${{ toJson(needs) }}' - name: Done diff --git a/mbedtls-platform-support/build.rs b/mbedtls-platform-support/build.rs index 98074ad82..9e0431066 100644 --- a/mbedtls-platform-support/build.rs +++ b/mbedtls-platform-support/build.rs @@ -22,11 +22,13 @@ fn main() { let mut b = cc::Build::new(); b.include(env::var_os("DEP_MBEDTLS_INCLUDE").unwrap()); let config_file = format!(r#""{}""#, env::var("DEP_MBEDTLS_CONFIG_H").unwrap()); - b.define("MBEDTLS_CONFIG_FILE", - Some(config_file.as_str())); - + b.define("MBEDTLS_CONFIG_FILE", Some(config_file.as_str())); + b.file("src/rust_printf.c"); - if sys_platform_components.get("c_compiler").map_or(false, |comps| comps.contains("freestanding")) { + if sys_platform_components + .get("c_compiler") + .map_or(false, |comps| comps.contains("freestanding")) + { b.flag("-U_FORTIFY_SOURCE") .define("_FORTIFY_SOURCE", Some("0")) .flag("-ffreestanding"); diff --git a/mbedtls-platform-support/src/lib.rs b/mbedtls-platform-support/src/lib.rs index b95726360..5243b991a 100644 --- a/mbedtls-platform-support/src/lib.rs +++ b/mbedtls-platform-support/src/lib.rs @@ -16,13 +16,13 @@ extern crate alloc as rust_alloc; #[cfg(not(feature = "std"))] mod alloc_prelude { #![allow(unused)] + pub(crate) use rust_alloc::borrow::Cow; pub(crate) use rust_alloc::borrow::ToOwned; pub(crate) use rust_alloc::boxed::Box; - pub(crate) use rust_alloc::sync::Arc; pub(crate) use rust_alloc::string::String; pub(crate) use rust_alloc::string::ToString; + pub(crate) use rust_alloc::sync::Arc; pub(crate) use rust_alloc::vec::Vec; - pub(crate) use rust_alloc::borrow::Cow; } pub mod self_test; @@ -43,9 +43,11 @@ pub extern "C" fn mbedtls_aesni_has_support(_what: u32) -> i32 { #[doc(hidden)] #[no_mangle] // needs to be pub for global visibility -pub extern "C" fn mbedtls_internal_aes_encrypt(_ctx: *mut mbedtls_sys::types::raw_types::c_void, - _input: *const u8, - _output: *mut u8) -> i32 { +pub extern "C" fn mbedtls_internal_aes_encrypt( + _ctx: *mut mbedtls_sys::types::raw_types::c_void, + _input: *const u8, + _output: *mut u8, +) -> i32 { panic!("AES-NI support is forced but the T-tables code was invoked") } @@ -53,43 +55,47 @@ pub extern "C" fn mbedtls_internal_aes_encrypt(_ctx: *mut mbedtls_sys::types::ra #[doc(hidden)] #[no_mangle] // needs to be pub for global visibility -pub extern "C" fn mbedtls_internal_aes_decrypt(_ctx: *mut mbedtls_sys::types::raw_types::c_void, - _input: *const u8, - _output: *mut u8) -> i32 { +pub extern "C" fn mbedtls_internal_aes_decrypt( + _ctx: *mut mbedtls_sys::types::raw_types::c_void, + _input: *const u8, + _output: *mut u8, +) -> i32 { panic!("AES-NI support is forced but the T-tables code was invoked") } - #[cfg(any(all(feature = "time", feature = "custom_gmtime_r"), sys_time_component = "custom"))] #[doc(hidden)] #[no_mangle] // needs to be pub for global visibility -pub unsafe extern "C" fn mbedtls_platform_gmtime_r(tt: *const mbedtls_sys::types::time_t, tp: *mut mbedtls_sys::types::tm) -> *mut mbedtls_sys::types::tm { +pub unsafe extern "C" fn mbedtls_platform_gmtime_r( + tt: *const mbedtls_sys::types::time_t, + tp: *mut mbedtls_sys::types::tm, +) -> *mut mbedtls_sys::types::tm { use chrono::prelude::*; //0 means no TZ offset let naive = if tp.is_null() { - return core::ptr::null_mut() + return core::ptr::null_mut(); } else { match NaiveDateTime::from_timestamp_opt(*tt, 0) { Some(t) => t, - None => return core::ptr::null_mut() + None => return core::ptr::null_mut(), } }; let utc = DateTime::::from_utc(naive, Utc); let tp = &mut *tp; - tp.tm_sec = utc.second() as i32; - tp.tm_min = utc.minute() as i32; - tp.tm_hour = utc.hour() as i32; - tp.tm_mday = utc.day() as i32; - tp.tm_mon = utc.month0() as i32; - tp.tm_year = match (utc.year() as i32).checked_sub(1900) { + tp.tm_sec = utc.second() as i32; + tp.tm_min = utc.minute() as i32; + tp.tm_hour = utc.hour() as i32; + tp.tm_mday = utc.day() as i32; + tp.tm_mon = utc.month0() as i32; + tp.tm_year = match (utc.year() as i32).checked_sub(1900) { Some(year) => year, - None => return core::ptr::null_mut() + None => return core::ptr::null_mut(), }; - tp.tm_wday = utc.weekday().num_days_from_sunday() as i32; - tp.tm_yday = utc.ordinal0() as i32; + tp.tm_wday = utc.weekday().num_days_from_sunday() as i32; + tp.tm_yday = utc.ordinal0() as i32; tp.tm_isdst = 0; tp diff --git a/mbedtls-platform-support/src/self_test.rs b/mbedtls-platform-support/src/self_test.rs index 37bb5ffb0..12806ce44 100644 --- a/mbedtls-platform-support/src/self_test.rs +++ b/mbedtls-platform-support/src/self_test.rs @@ -11,11 +11,11 @@ //! Calling MbedTLS self test functions before they're enabled using the //! `enable()` function here will result in a panic. //! -//! Using this module in multithreaded or async environment will fail. The self -//! test functions rely on global variables to track operations and anything -//! non-self-test related operations will clobber these variables, resulting in -//! self test failures. Make sure no other code uses MbedTLS while running the -//! self tests. Multiple self test operations done simultaneously may also +//! Using this module in multithreaded or async environment will fail. The self +//! test functions rely on global variables to track operations and anything +//! non-self-test related operations will clobber these variables, resulting in +//! self test failures. Make sure no other code uses MbedTLS while running the +//! self tests. Multiple self test operations done simultaneously may also //! return failures. use mbedtls_sys::types::raw_types::{c_char, c_int}; @@ -55,9 +55,9 @@ pub unsafe extern "C" fn rand() -> c_int { /// Set callback functions to enable the MbedTLS self tests. /// -/// `rand` only needs to be set on platforms that don't have a `rand()` -/// function in libc. `log` only needs to be set when using `no_std`, i.e. -/// the `std` feature of this create is not enabled. If neither function +/// `rand` only needs to be set on platforms that don't have a `rand()` +/// function in libc. `log` only needs to be set when using `no_std`, i.e. +/// the `std` feature of this create is not enabled. If neither function /// needs to be set, you don't have to call `enable()`. /// /// # Safety @@ -66,10 +66,12 @@ pub unsafe extern "C" fn rand() -> c_int { /// function in this module is called. #[allow(unused)] pub unsafe fn enable(rand: fn() -> c_int, log: Option) { - #[cfg(any(not(feature = "std"), target_env = "sgx"))] { + #[cfg(any(not(feature = "std"), target_env = "sgx"))] + { rand_f = Some(rand); } - #[cfg(not(feature = "std"))] { + #[cfg(not(feature = "std"))] + { log_f = log; } } @@ -79,26 +81,27 @@ pub unsafe fn enable(rand: fn() -> c_int, log: Option) /// The caller needs to ensure this function is not called while any other /// function in this module is called. pub unsafe fn disable() { - #[cfg(any(not(feature = "std"), target_env = "sgx"))] { + #[cfg(any(not(feature = "std"), target_env = "sgx"))] + { rand_f = None; } - #[cfg(not(feature = "std"))] { + #[cfg(not(feature = "std"))] + { log_f = None; } } /// # Safety -/// +/// /// The caller needs to ensure this function is not called while *any other* /// MbedTLS function is called. See the module documentation for more /// information. pub use mbedtls_sys::{ aes_self_test as aes, arc4_self_test as arc4, aria_self_test as aria, base64_self_test as base64, - camellia_self_test as camellia, ccm_self_test as ccm, ctr_drbg_self_test as ctr_drbg, + camellia_self_test as camellia, ccm_self_test as ccm, cmac_self_test as cmac, ctr_drbg_self_test as ctr_drbg, des_self_test as des, dhm_self_test as dhm, ecjpake_self_test as ecjpake, ecp_self_test as ecp, - entropy_self_test as entropy, gcm_self_test as gcm, hmac_drbg_self_test as hmac_drbg, - md2_self_test as md2, md4_self_test as md4, md5_self_test as md5, mpi_self_test as mpi, - pkcs5_self_test as pkcs5, ripemd160_self_test as ripemd160, rsa_self_test as rsa, - sha1_self_test as sha1, sha256_self_test as sha256, sha512_self_test as sha512, - x509_self_test as x509, xtea_self_test as xtea, nist_kw_self_test as nist_kw, cmac_self_test as cmac + entropy_self_test as entropy, gcm_self_test as gcm, hmac_drbg_self_test as hmac_drbg, md2_self_test as md2, + md4_self_test as md4, md5_self_test as md5, mpi_self_test as mpi, nist_kw_self_test as nist_kw, pkcs5_self_test as pkcs5, + ripemd160_self_test as ripemd160, rsa_self_test as rsa, sha1_self_test as sha1, sha256_self_test as sha256, + sha512_self_test as sha512, x509_self_test as x509, xtea_self_test as xtea, }; diff --git a/mbedtls-platform-support/src/threading.rs b/mbedtls-platform-support/src/threading.rs index 94aa72d78..1f1c985c1 100644 --- a/mbedtls-platform-support/src/threading.rs +++ b/mbedtls-platform-support/src/threading.rs @@ -9,16 +9,14 @@ #[cfg(not(feature = "std"))] use crate::alloc_prelude::*; -// use cfg_if to ensure conditional compilation is compatible with v0.7 code -cfg_if::cfg_if! { - if #[cfg(any(all(feature = "spin_threading", not(feature = "rust_threading")), not(feature = "std")))] { - use spin::{Mutex, MutexGuard}; - } else if #[cfg(any(feature = "rust_threading", feature = "std"))] { - use std::sync::{Mutex, MutexGuard}; - } else { - {} - } -} +#[cfg(any(all(feature = "spin_threading", not(feature = "rust_threading")), not(feature = "std")))] +use spin::{Mutex, MutexGuard}; + +#[cfg(all( + not(any(all(feature = "spin_threading", not(feature = "rust_threading")), not(feature = "std"))), + any(feature = "rust_threading", feature = "std") +))] +use std::sync::{Mutex, MutexGuard}; use core::ptr; diff --git a/mbedtls-sys/build/bindgen.rs b/mbedtls-sys/build/bindgen.rs index ba246637f..e477fc6da 100644 --- a/mbedtls-sys/build/bindgen.rs +++ b/mbedtls-sys/build/bindgen.rs @@ -19,14 +19,19 @@ struct MbedtlsParseCallbacks; impl bindgen::callbacks::ParseCallbacks for MbedtlsParseCallbacks { fn item_name(&self, original_item_name: &str) -> Option { - Some(original_item_name.trim_start_matches("mbedtls_").trim_start_matches("MBEDTLS_").to_owned()) + Some( + original_item_name + .trim_start_matches("mbedtls_") + .trim_start_matches("MBEDTLS_") + .to_owned(), + ) } fn enum_variant_name( &self, _enum_name: Option<&str>, original_variant_name: &str, - _variant_value: bindgen::callbacks::EnumVariantValue + _variant_value: bindgen::callbacks::EnumVariantValue, ) -> Option { self.item_name(original_variant_name) } @@ -39,7 +44,11 @@ impl bindgen::callbacks::ParseCallbacks for MbedtlsParseCallbacks { } } - fn blocklisted_type_implements_trait(&self, _name: &str, derive_trait: bindgen::callbacks::DeriveTrait) -> Option { + fn blocklisted_type_implements_trait( + &self, + _name: &str, + derive_trait: bindgen::callbacks::DeriveTrait, + ) -> Option { if derive_trait == bindgen::callbacks::DeriveTrait::Default { Some(bindgen::callbacks::ImplementsTrait::Manually) } else { @@ -53,7 +62,7 @@ impl bindgen::callbacks::ParseCallbacks for MbedtlsParseCallbacks { fn generate_deprecated_union_accessors(bindings: &str) -> String { #[derive(Default)] struct UnionImplBuilder { - impls: String + impls: String, } impl<'ast> syn::visit::Visit<'ast> for UnionImplBuilder { @@ -61,16 +70,21 @@ fn generate_deprecated_union_accessors(bindings: &str) -> String { let union_name = &i.ident; let field_name = i.fields.named.iter().map(|field| field.ident.as_ref().unwrap()); let field_type = i.fields.named.iter().map(|field| &field.ty); - write!(self.impls, "{}", quote::quote! { - impl #union_name { - #( - #[deprecated] - pub unsafe fn #field_name(&mut self) -> *mut #field_type { - &mut self.#field_name - } - )* + write!( + self.impls, + "{}", + quote::quote! { + impl #union_name { + #( + #[deprecated] + pub unsafe fn #field_name(&mut self) -> *mut #field_type { + &mut self.#field_name + } + )* + } } - }).unwrap(); + ) + .unwrap(); } } @@ -107,10 +121,7 @@ impl super::BuildConfig { match output { Ok(sysroot) => { let path = std::str::from_utf8(&sysroot.stdout).expect("Malformed sysroot"); - let trimmed_path = path - .strip_suffix("\r\n") - .or(path.strip_suffix("\n")) - .unwrap_or(&path); + let trimmed_path = path.strip_suffix("\r\n").or(path.strip_suffix("\n")).unwrap_or(&path); cc.flag(&format!("--sysroot={}", trimmed_path)); } _ => {} // skip toolchains without a configured sysroot @@ -151,7 +162,8 @@ impl super::BuildConfig { f.write_all(union_impls.as_bytes())?; f.write_all(b"use crate::types::*;\n")?; // for FILE, time_t, etc. Ok(()) - }).expect("bindings.rs I/O error"); + }) + .expect("bindings.rs I/O error"); let mod_bindings = self.out_dir.join("mod-bindings.rs"); fs::write(mod_bindings, b"mod bindings;\n").expect("mod-bindings.rs I/O error"); diff --git a/mbedtls-sys/build/build.rs b/mbedtls-sys/build/build.rs index 473dc0b25..0cacf32c2 100644 --- a/mbedtls-sys/build/build.rs +++ b/mbedtls-sys/build/build.rs @@ -19,11 +19,11 @@ mod mod_bindgen; #[path = "cmake.rs"] mod mod_cmake; +use features::FEATURES; use std::env; use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; -use features::FEATURES; struct BuildConfig { out_dir: PathBuf, @@ -69,24 +69,13 @@ impl BuildConfig { fn print_rerun_files(&self) { println!("cargo:rerun-if-env-changed=RUST_MBEDTLS_SYS_SOURCE"); - println!( - "cargo:rerun-if-changed={}", - self.mbedtls_src.join("CMakeLists.txt").display() - ); + println!("cargo:rerun-if-changed={}", self.mbedtls_src.join("CMakeLists.txt").display()); let include = self.mbedtls_src.join(Path::new("include").join("mbedtls")); for h in headers::enabled_ordered() { println!("cargo:rerun-if-changed={}", include.join(h).display()); } - for f in self - .mbedtls_src - .join("library") - .read_dir() - .expect("read_dir failed") - { - println!( - "cargo:rerun-if-changed={}", - f.expect("DirEntry failed").path().display() - ); + for f in self.mbedtls_src.join("library").read_dir().expect("read_dir failed") { + println!("cargo:rerun-if-changed={}", f.expect("DirEntry failed").path().display()); } } diff --git a/mbedtls-sys/build/cmake.rs b/mbedtls-sys/build/cmake.rs index 0d0545343..808527cc3 100644 --- a/mbedtls-sys/build/cmake.rs +++ b/mbedtls-sys/build/cmake.rs @@ -29,14 +29,15 @@ impl super::BuildConfig { } let target = std::env::var("TARGET").expect("TARGET environment variable should be set in build scripts"); - // thumbv6m-none-eabi, thumbv7em-none-eabi, thumbv7em-none-eabihf, thumbv7m-none-eabi - // probably use arm-none-eabi-gcc which can cause the cmake compiler test to fail. + // thumbv6m-none-eabi, thumbv7em-none-eabi, thumbv7em-none-eabihf, + // thumbv7m-none-eabi probably use arm-none-eabi-gcc which can cause the + // cmake compiler test to fail. if target.starts_with("thumbv") && target.contains("none-eabi") { // When building on Linux, -rdynamic flag is added automatically. Changing the // CMAKE_SYSTEM_NAME to Generic avoids this. cmk.define("CMAKE_SYSTEM_NAME", "Generic"); - // The compiler test requires _exit which is not available. By just trying to compile - // a library, we can fix it. + // The compiler test requires _exit which is not available. By just trying to + // compile a library, we can fix it. cmk.define("CMAKE_TRY_COMPILE_TARGET_TYPE", "STATIC_LIBRARY"); } @@ -52,7 +53,14 @@ impl super::BuildConfig { println!("cargo:rustc-link-lib=mbedx509"); println!("cargo:rustc-link-lib=mbedcrypto"); - println!("cargo:include={}", ::std::env::current_dir().unwrap().join(&self.mbedtls_include).to_str().expect("include/ UTF-8 error")); + println!( + "cargo:include={}", + ::std::env::current_dir() + .unwrap() + .join(&self.mbedtls_include) + .to_str() + .expect("include/ UTF-8 error") + ); println!("cargo:config_h={}", self.config_h.to_str().expect("config.h UTF-8 error")); } } diff --git a/mbedtls-sys/build/features.rs b/mbedtls-sys/build/features.rs index 5b3048752..6006bc0b6 100644 --- a/mbedtls-sys/build/features.rs +++ b/mbedtls-sys/build/features.rs @@ -32,9 +32,7 @@ impl Features { let have_custom_threading = self.have_feature("custom_threading"); let have_custom_gmtime_r = self.have_feature("custom_gmtime_r"); - if !self.have_feature("std") || - env_have_target_cfg("env", "sgx") || - env_have_target_cfg("os", "none") { + if !self.have_feature("std") || env_have_target_cfg("env", "sgx") || env_have_target_cfg("os", "none") { self.with_feature("c_compiler").unwrap().insert("freestanding"); } if let Some(components) = self.with_feature("threading") { @@ -64,10 +62,17 @@ impl Features { println!(r#"cargo:rustc-cfg={}_component="{}""#, feature, component); } } - println!("cargo:platform-components={}", - self.platform_components.iter().flat_map(|(feature, components)| { - components.iter().map(move |component| format!(r#"{}_component={}"#, feature, component)) - } ).collect::>().join(",") + println!( + "cargo:platform-components={}", + self.platform_components + .iter() + .flat_map(|(feature, components)| { + components + .iter() + .map(move |component| format!(r#"{}_component={}"#, feature, component)) + }) + .collect::>() + .join(",") ); } @@ -80,7 +85,9 @@ impl Features { } pub fn have_platform_component(&self, feature: &'static str, component: &'static str) -> bool { - self.platform_components.get(feature).map_or(false, |feat| feat.contains(component)) + self.platform_components + .get(feature) + .map_or(false, |feat| feat.contains(component)) } pub fn have_feature(&self, feature: &'static str) -> bool { diff --git a/mbedtls-sys/src/lib.rs b/mbedtls-sys/src/lib.rs index 577244074..e25f70274 100644 --- a/mbedtls-sys/src/lib.rs +++ b/mbedtls-sys/src/lib.rs @@ -21,4 +21,4 @@ pub use bindings::*; /* This value is defined by a C function macro, something which is not supported by bindgen currently https://github.com/rust-lang-nursery/rust-bindgen/issues/231 */ -pub const ECDSA_MAX_LEN : u32 = 141; +pub const ECDSA_MAX_LEN: u32 = 141; diff --git a/mbedtls/build.rs b/mbedtls/build.rs index b334a6c28..6f30ef140 100644 --- a/mbedtls/build.rs +++ b/mbedtls/build.rs @@ -38,12 +38,14 @@ fn main() { let mut b = cc::Build::new(); b.include(env::var_os("DEP_MBEDTLS_INCLUDE").unwrap()); let config_file = format!(r#""{}""#, env::var("DEP_MBEDTLS_CONFIG_H").unwrap()); - b.define("MBEDTLS_CONFIG_FILE", - Some(config_file.as_str())); + b.define("MBEDTLS_CONFIG_FILE", Some(config_file.as_str())); b.define("RUST_MBEDTLS_METADATA_HASH", Some(metadata_hash.as_str())); - + b.file("src/mbedtls_malloc.c"); - if sys_platform_components.get("c_compiler").map_or(false, |comps| comps.contains("freestanding")) { + if sys_platform_components + .get("c_compiler") + .map_or(false, |comps| comps.contains("freestanding")) + { b.flag("-U_FORTIFY_SOURCE") .define("_FORTIFY_SOURCE", Some("0")) .flag("-ffreestanding"); diff --git a/mbedtls/examples/client.rs b/mbedtls/examples/client.rs index f3087334d..d1182cd2f 100644 --- a/mbedtls/examples/client.rs +++ b/mbedtls/examples/client.rs @@ -46,10 +46,5 @@ fn result_main(addr: &str) -> TlsResult<()> { fn main() { let mut args = std::env::args(); args.next(); - result_main( - &args - .next() - .expect("supply destination in command-line argument"), - ) - .unwrap(); + result_main(&args.next().expect("supply destination in command-line argument")).unwrap(); } diff --git a/mbedtls/examples/client_dtls.rs b/mbedtls/examples/client_dtls.rs index e079b2aa9..4b7b846c7 100644 --- a/mbedtls/examples/client_dtls.rs +++ b/mbedtls/examples/client_dtls.rs @@ -54,10 +54,5 @@ fn result_main(addr: &str) -> TlsResult<()> { fn main() { let mut args = std::env::args(); args.next(); - result_main( - &args - .next() - .expect("supply destination in command-line argument"), - ) - .unwrap(); + result_main(&args.next().expect("supply destination in command-line argument")).unwrap(); } diff --git a/mbedtls/examples/client_psk.rs b/mbedtls/examples/client_psk.rs index 609dd099c..c31f4b63c 100644 --- a/mbedtls/examples/client_psk.rs +++ b/mbedtls/examples/client_psk.rs @@ -43,10 +43,5 @@ fn result_main(addr: &str) -> TlsResult<()> { fn main() { let mut args = std::env::args(); args.next(); - result_main( - &args - .next() - .expect("supply destination in command-line argument"), - ) - .unwrap(); + result_main(&args.next().expect("supply destination in command-line argument")).unwrap(); } diff --git a/mbedtls/src/alloc.rs b/mbedtls/src/alloc.rs index 6bca70a5f..552d9dcd5 100644 --- a/mbedtls/src/alloc.rs +++ b/mbedtls/src/alloc.rs @@ -7,10 +7,10 @@ * according to those terms. */ use core::fmt; +use core::mem::ManuallyDrop; use core::ops::{Deref, DerefMut}; -use core::ptr::NonNull; use core::ptr::drop_in_place; -use core::mem::ManuallyDrop; +use core::ptr::NonNull; use mbedtls_sys::types::raw_types::c_void; @@ -18,12 +18,15 @@ extern "C" { #[link_name = concat!("\u{1}forward_mbedtls_free_", env!("RUST_MBEDTLS_METADATA_HASH"))] pub(crate) fn mbedtls_free(n: *mut mbedtls_sys::types::raw_types::c_void); #[link_name = concat!("\u{1}forward_mbedtls_calloc_", env!("RUST_MBEDTLS_METADATA_HASH"))] - pub(crate) fn mbedtls_calloc(n: mbedtls_sys::types::size_t, size: mbedtls_sys::types::size_t) -> *mut mbedtls_sys::types::raw_types::c_void; + pub(crate) fn mbedtls_calloc( + n: mbedtls_sys::types::size_t, + size: mbedtls_sys::types::size_t, + ) -> *mut mbedtls_sys::types::raw_types::c_void; } #[repr(transparent)] pub struct Box { - pub(crate) inner: NonNull + pub(crate) inner: NonNull, } impl Box { @@ -66,5 +69,5 @@ unsafe impl Sync for Box {} #[repr(transparent)] pub struct List { - pub(crate) inner: Option> + pub(crate) inner: Option>, } diff --git a/mbedtls/src/bignum/mod.rs b/mbedtls/src/bignum/mod.rs index a692b2ff9..a560ef343 100644 --- a/mbedtls/src/bignum/mod.rs +++ b/mbedtls/src/bignum/mod.rs @@ -12,11 +12,11 @@ use mbedtls_sys::*; #[cfg(not(feature = "std"))] use crate::alloc_prelude::*; +use crate::rng::Random; use core::cmp::Ordering; use core::fmt::{Binary, Debug, Display, Formatter, Octal, Result as FmtResult, UpperHex}; use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Rem, RemAssign, Sub, SubAssign}; use core::ops::{Shl, ShlAssign, Shr, ShrAssign}; -use crate::rng::Random; pub use mbedtls_sys::mpi_sint; @@ -81,7 +81,7 @@ impl ::core::str::FromStr for Mpi { } } -#[derive(Debug,Copy,Clone,Eq,PartialEq)] +#[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum Sign { Negative, Zero, @@ -161,8 +161,7 @@ impl Mpi { pub fn to_string_radix(&self, radix: i32) -> Result { let mut olen = 0; - let r = - unsafe { mpi_write_string(&self.inner, radix, ::core::ptr::null_mut(), 0, &mut olen) }; + let r = unsafe { mpi_write_string(&self.inner, radix, ::core::ptr::null_mut(), 0, &mut olen) }; if r != ERR_MPI_BUFFER_TOO_SMALL { return Err(Error::from_mbedtls_code(r)); @@ -170,16 +169,7 @@ impl Mpi { let mut buf = vec![0u8; olen]; - unsafe { - mpi_write_string( - &self.inner, - radix, - buf.as_mut_ptr() as *mut _, - buf.len(), - &mut olen, - ) - } - .into_result()?; + unsafe { mpi_write_string(&self.inner, radix, buf.as_mut_ptr() as *mut _, buf.len(), &mut olen) }.into_result()?; // There is a null terminator plus (possibly) some garbage data. Remove it if let Some(idx) = buf.iter().position(|&b| b == 0) { @@ -197,16 +187,14 @@ impl Mpi { Ok(ret) } - /// Serialize the MPI as big endian binary data, padding to at least min_len bytes + /// Serialize the MPI as big endian binary data, padding to at least min_len + /// bytes pub fn to_binary_padded(&self, min_len: usize) -> Result> { let len = self.byte_length()?; let larger_len = if len < min_len { min_len } else { len }; let mut ret = vec![0u8; larger_len]; let pad_len = ret.len() - len; - unsafe { - mpi_write_binary(&self.inner, ret.as_mut_ptr().offset(pad_len as isize), len) - .into_result() - }?; + unsafe { mpi_write_binary(&self.inner, ret.as_mut_ptr().offset(pad_len as isize), len).into_result() }?; Ok(ret) } @@ -225,8 +213,7 @@ impl Mpi { pub fn divrem(&self, other: &Mpi) -> Result<(Mpi, Mpi)> { let mut q = Self::init(); let mut r = Self::init(); - unsafe { mpi_div_mpi(&mut q.inner, &mut r.inner, &self.inner, &other.inner) } - .into_result()?; + unsafe { mpi_div_mpi(&mut q.inner, &mut r.inner, &self.inner, &other.inner) }.into_result()?; Ok((q, r)) } @@ -264,7 +251,8 @@ impl Mpi { return Ok(zero); } - // This ignores p=2 (for which this algorithm is valid), as not cryptographically interesting. + // This ignores p=2 (for which this algorithm is valid), as not + // cryptographically interesting. if p.get_bit(0) == false || p <= &zero { return Err(Error::MpiBadInputData); } @@ -415,13 +403,7 @@ impl Mpi { /// mbedtls_mpi_is_prime. pub fn is_probably_prime(&self, k: u32, rng: &mut F) -> Result<()> { unsafe { - mpi_is_prime_ext( - &self.inner, - k as i32, - Some(F::call), - rng.data_ptr(), - ) - .into_result()?; + mpi_is_prime_ext(&self.inner, k as i32, Some(F::call), rng.data_ptr()).into_result()?; } Ok(()) } @@ -510,15 +492,7 @@ impl<'a, 'b> Div<&'b Mpi> for &'a Mpi { fn div(self, other: &Mpi) -> Result { let mut q = Mpi::init(); - unsafe { - mpi_div_mpi( - &mut q.inner, - ::core::ptr::null_mut(), - &self.inner, - other.handle(), - ) - } - .into_result()?; + unsafe { mpi_div_mpi(&mut q.inner, ::core::ptr::null_mut(), &self.inner, other.handle()) }.into_result()?; Ok(q) } } @@ -528,15 +502,7 @@ impl<'a> Div for &'a Mpi { fn div(self, other: Mpi) -> Result { let mut q = Mpi::init(); - unsafe { - mpi_div_mpi( - &mut q.inner, - ::core::ptr::null_mut(), - &self.inner, - other.handle(), - ) - } - .into_result()?; + unsafe { mpi_div_mpi(&mut q.inner, ::core::ptr::null_mut(), &self.inner, other.handle()) }.into_result()?; Ok(q) } } @@ -546,8 +512,7 @@ impl<'a> Div for &'a Mpi { fn div(self, other: mpi_sint) -> Result { let mut q = Mpi::init(); - unsafe { mpi_div_int(&mut q.inner, ::core::ptr::null_mut(), &self.inner, other) } - .into_result()?; + unsafe { mpi_div_int(&mut q.inner, ::core::ptr::null_mut(), &self.inner, other) }.into_result()?; Ok(q) } } @@ -555,18 +520,12 @@ impl<'a> Div for &'a Mpi { /// Note this will panic if other == 0 impl<'a> DivAssign<&'a Mpi> for Mpi { fn div_assign(&mut self, other: &Mpi) { - // mpi_div_mpi produces incorrect output when arguments alias, so avoid doing that + // mpi_div_mpi produces incorrect output when arguments alias, so avoid doing + // that let mut q = Mpi::init(); - unsafe { - mpi_div_mpi( - &mut q.inner, - ::core::ptr::null_mut(), - &self.inner, - other.handle(), - ) - } - .into_result() - .expect("mpi_div_mpi success"); + unsafe { mpi_div_mpi(&mut q.inner, ::core::ptr::null_mut(), &self.inner, other.handle()) } + .into_result() + .expect("mpi_div_mpi success"); *self = q; } } @@ -574,18 +533,12 @@ impl<'a> DivAssign<&'a Mpi> for Mpi { /// Note this will panic if other == 0 impl DivAssign for Mpi { fn div_assign(&mut self, other: Mpi) { - // mpi_div_mpi produces incorrect output when arguments alias, so avoid doing that + // mpi_div_mpi produces incorrect output when arguments alias, so avoid doing + // that let mut q = Mpi::init(); - unsafe { - mpi_div_mpi( - &mut q.inner, - ::core::ptr::null_mut(), - &self.inner, - other.handle(), - ) - } - .into_result() - .expect("mpi_div_mpi success"); + unsafe { mpi_div_mpi(&mut q.inner, ::core::ptr::null_mut(), &self.inner, other.handle()) } + .into_result() + .expect("mpi_div_mpi success"); *self = q; } } @@ -611,15 +564,7 @@ impl<'a, 'b> Rem<&'b Mpi> for &'a Mpi { fn rem(self, other: &Mpi) -> Result { let mut r = Mpi::init(); - unsafe { - mpi_div_mpi( - ::core::ptr::null_mut(), - &mut r.inner, - &self.inner, - other.handle(), - ) - } - .into_result()?; + unsafe { mpi_div_mpi(::core::ptr::null_mut(), &mut r.inner, &self.inner, other.handle()) }.into_result()?; Ok(r) } } @@ -629,15 +574,7 @@ impl<'a> Rem for &'a Mpi { fn rem(self, other: Mpi) -> Result { let mut r = Mpi::init(); - unsafe { - mpi_div_mpi( - ::core::ptr::null_mut(), - &mut r.inner, - &self.inner, - other.handle(), - ) - } - .into_result()?; + unsafe { mpi_div_mpi(::core::ptr::null_mut(), &mut r.inner, &self.inner, other.handle()) }.into_result()?; Ok(r) } } @@ -647,8 +584,7 @@ impl Rem for Mpi { fn rem(self, other: mpi_sint) -> Result { let mut r = Mpi::init(); - unsafe { mpi_div_int(::core::ptr::null_mut(), &mut r.inner, &self.inner, other) } - .into_result()?; + unsafe { mpi_div_int(::core::ptr::null_mut(), &mut r.inner, &self.inner, other) }.into_result()?; Ok(r) } } @@ -658,8 +594,7 @@ impl<'a> Rem for &'a Mpi { fn rem(self, other: mpi_sint) -> Result { let mut r = Mpi::init(); - unsafe { mpi_div_int(::core::ptr::null_mut(), &mut r.inner, &self.inner, other) } - .into_result()?; + unsafe { mpi_div_int(::core::ptr::null_mut(), &mut r.inner, &self.inner, other) }.into_result()?; Ok(r) } } @@ -667,18 +602,12 @@ impl<'a> Rem for &'a Mpi { /// Note this will panic if other == 0 impl<'a> RemAssign<&'a Mpi> for Mpi { fn rem_assign(&mut self, other: &Mpi) { - // mpi_div_mpi produces incorrect output when arguments alias, so avoid doing that + // mpi_div_mpi produces incorrect output when arguments alias, so avoid doing + // that let mut r = Mpi::init(); - unsafe { - mpi_div_mpi( - ::core::ptr::null_mut(), - &mut r.inner, - &self.inner, - other.handle(), - ) - } - .into_result() - .expect("mpi_div_mpi success"); + unsafe { mpi_div_mpi(::core::ptr::null_mut(), &mut r.inner, &self.inner, other.handle()) } + .into_result() + .expect("mpi_div_mpi success"); *self = r; } } @@ -686,18 +615,12 @@ impl<'a> RemAssign<&'a Mpi> for Mpi { /// Note this will panic if other == 0 impl RemAssign for Mpi { fn rem_assign(&mut self, other: Mpi) { - // mpi_div_mpi produces incorrect output when arguments alias, so avoid doing that + // mpi_div_mpi produces incorrect output when arguments alias, so avoid doing + // that let mut r = Mpi::init(); - unsafe { - mpi_div_mpi( - ::core::ptr::null_mut(), - &mut r.inner, - &self.inner, - other.handle(), - ) - } - .into_result() - .expect("mpi_div_mpi success"); + unsafe { mpi_div_mpi(::core::ptr::null_mut(), &mut r.inner, &self.inner, other.handle()) } + .into_result() + .expect("mpi_div_mpi success"); *self = r; } } diff --git a/mbedtls/src/cipher/mod.rs b/mbedtls/src/cipher/mod.rs index ec133d431..193d09a4f 100644 --- a/mbedtls/src/cipher/mod.rs +++ b/mbedtls/src/cipher/mod.rs @@ -52,10 +52,7 @@ pub enum Traditional {} impl Type for Traditional { fn is_valid_mode(mode: raw::CipherMode) -> bool { match mode { - raw::CipherMode::CBC - | raw::CipherMode::CFB - | raw::CipherMode::OFB - | raw::CipherMode::CTR => true, + raw::CipherMode::CBC | raw::CipherMode::CFB | raw::CipherMode::OFB | raw::CipherMode::CTR => true, _ => false, } } @@ -133,11 +130,7 @@ impl Cipher { } impl Cipher { - pub fn new( - cipher_id: raw::CipherId, - cipher_mode: raw::CipherMode, - key_bit_len: u32, - ) -> Result> { + pub fn new(cipher_id: raw::CipherId, cipher_mode: raw::CipherMode, key_bit_len: u32) -> Result> { assert!(T::is_valid_mode(cipher_mode)); // Create raw cipher object @@ -174,7 +167,8 @@ impl Cipher { self.raw_cipher.set_iv(iv)?; } - // Also do a reset right here so the user can start the crypto operation right away in "CipherData" + // Also do a reset right here so the user can start the crypto operation right + // away in "CipherData" self.raw_cipher.reset() } @@ -194,11 +188,7 @@ impl Cipher { } impl Cipher { - pub fn set_key_iv( - mut self, - key: &[u8], - iv: &[u8], - ) -> Result> { + pub fn set_key_iv(mut self, key: &[u8], iv: &[u8]) -> Result> { self.set_key_and_maybe_iv(key, Some(iv))?; // Put together the structure to return @@ -207,11 +197,7 @@ impl Cipher { } impl Cipher { - pub fn set_key_iv( - mut self, - key: &[u8], - iv: &[u8], - ) -> Result> { + pub fn set_key_iv(mut self, key: &[u8], iv: &[u8]) -> Result> { self.set_key_and_maybe_iv(key, Some(iv))?; // Put together the structure to return @@ -220,11 +206,7 @@ impl Cipher { } impl Cipher { - pub fn set_ad( - mut self, - ad: &[u8] - ) -> Result> { - + pub fn set_ad(mut self, ad: &[u8]) -> Result> { // For AEAD add AD self.raw_cipher.update_ad(ad)?; @@ -262,11 +244,12 @@ impl Cipher { } impl Cipher { - pub fn cmac(mut self, - key: &[u8], - in_data: &[u8], - out_data: &mut [u8]) - -> Result> { + pub fn cmac( + mut self, + key: &[u8], + in_data: &[u8], + out_data: &mut [u8], + ) -> Result> { self.raw_cipher.cmac(key, in_data, out_data)?; Ok(self.change_state()) } @@ -281,8 +264,7 @@ impl Cipher { tag_len: usize, ) -> Result<(usize, Cipher)> { Ok(( - self.raw_cipher - .encrypt_auth(ad, plain_text, cipher_and_tag, tag_len)?, + self.raw_cipher.encrypt_auth(ad, plain_text, cipher_and_tag, tag_len)?, self.change_state(), )) } @@ -293,11 +275,7 @@ impl Cipher { data: &mut [u8], tag: &mut [u8], ) -> Result<(usize, Cipher)> { - Ok(( - self.raw_cipher - .encrypt_auth_inplace(ad, data, tag)?, - self.change_state(), - )) + Ok((self.raw_cipher.encrypt_auth_inplace(ad, data, tag)?, self.change_state())) } } @@ -310,8 +288,7 @@ impl Cipher { tag_len: usize, ) -> Result<(usize, Cipher)> { Ok(( - self.raw_cipher - .decrypt_auth(ad, cipher_text_and_tag, plain_text, tag_len)?, + self.raw_cipher.decrypt_auth(ad, cipher_text_and_tag, plain_text, tag_len)?, self.change_state(), )) } @@ -322,20 +299,12 @@ impl Cipher { data: &mut [u8], tag: &[u8], ) -> Result<(usize, Cipher)> { - Ok(( - self.raw_cipher - .decrypt_auth_inplace(ad, data, tag)?, - self.change_state(), - )) + Ok((self.raw_cipher.decrypt_auth_inplace(ad, data, tag)?, self.change_state())) } } impl Cipher { - pub fn update( - mut self, - in_data: &[u8], - out_data: &mut [u8], - ) -> Result<(usize, Cipher)> { + pub fn update(mut self, in_data: &[u8], out_data: &mut [u8]) -> Result<(usize, Cipher)> { // Call the wrapper function to do update operation (multi part) let len = self.raw_cipher.update(in_data, out_data)?; @@ -372,16 +341,18 @@ impl Cipher { fn cmac() { // From NIST CAVS - let key = [0x7c, 0x0b, 0x7d, 0xb9, 0x81, 0x1f, 0x10, 0xd0, 0x0e, 0x47, 0x6c, 0x7a, 0x0d, 0x92, 0xf6, 0xe0]; - let msg = [0x1e, 0xe0, 0xec, 0x46, 0x6d, 0x46, 0xfd, 0x84, 0x9b, 0x40, 0xc0, 0x66, 0xb4, 0xfb, 0xbd, 0x22, - 0xa2, 0x0a, 0x4d, 0x80, 0xa0, 0x08, 0xac, 0x9a, 0xf1, 0x7e, 0x4f, 0xdf, 0xd1, 0x06, 0x78, 0x5e]; - let expected = vec![0xba, 0xec, 0xdc, 0x91, 0xe9, 0xa1, 0xfc, 0x35, 0x72, 0xad, 0xf1, 0xe4, 0x23, 0x2a, 0xe2, 0x85]; + let key = [ + 0x7c, 0x0b, 0x7d, 0xb9, 0x81, 0x1f, 0x10, 0xd0, 0x0e, 0x47, 0x6c, 0x7a, 0x0d, 0x92, 0xf6, 0xe0, + ]; + let msg = [ + 0x1e, 0xe0, 0xec, 0x46, 0x6d, 0x46, 0xfd, 0x84, 0x9b, 0x40, 0xc0, 0x66, 0xb4, 0xfb, 0xbd, 0x22, 0xa2, 0x0a, 0x4d, 0x80, + 0xa0, 0x08, 0xac, 0x9a, 0xf1, 0x7e, 0x4f, 0xdf, 0xd1, 0x06, 0x78, 0x5e, + ]; + let expected = vec![ + 0xba, 0xec, 0xdc, 0x91, 0xe9, 0xa1, 0xfc, 0x35, 0x72, 0xad, 0xf1, 0xe4, 0x23, 0x2a, 0xe2, 0x85, + ]; - let cipher = Cipher::<_, TraditionalNoIv, _>::new( - raw::CipherId::Aes, - raw::CipherMode::ECB, - (key.len() * 8) as _, - ).unwrap(); + let cipher = Cipher::<_, TraditionalNoIv, _>::new(raw::CipherId::Aes, raw::CipherMode::ECB, (key.len() * 8) as _).unwrap(); let mut generated = vec![0u8; 16]; cipher.cmac(&key, &msg, &mut generated).unwrap(); @@ -393,8 +364,7 @@ fn cmac() { fn ccm() { // Example vector C.1 let k = [ - 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, - 0x4f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, ]; let iv = [0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16]; let ad = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]; @@ -404,24 +374,12 @@ fn ccm() { let mut c_out = [0u8; 8]; let t = [0x4d, 0xac, 0x25, 0x5d]; - let cipher = Cipher::<_, Authenticated, _>::new( - raw::CipherId::Aes, - raw::CipherMode::CCM, - (k.len() * 8) as _, - ) - .unwrap(); + let cipher = Cipher::<_, Authenticated, _>::new(raw::CipherId::Aes, raw::CipherMode::CCM, (k.len() * 8) as _).unwrap(); let cipher = cipher.set_key_iv(&k, &iv).unwrap(); - cipher - .encrypt_auth(&ad, &p, &mut c_out, 4) - .unwrap(); + cipher.encrypt_auth(&ad, &p, &mut c_out, 4).unwrap(); assert_eq!(c, c_out[0..4]); assert_eq!(t, c_out[4..8]); - let cipher = Cipher::<_, Authenticated, _>::new( - raw::CipherId::Aes, - raw::CipherMode::CCM, - (k.len() * 8) as _, - ) - .unwrap(); + let cipher = Cipher::<_, Authenticated, _>::new(raw::CipherId::Aes, raw::CipherMode::CCM, (k.len() * 8) as _).unwrap(); let cipher = cipher.set_key_iv(&k, &iv).unwrap(); cipher.decrypt_auth(&ad, &c_out, &mut p_out, 4).unwrap(); assert_eq!(p, p_out); @@ -431,8 +389,7 @@ fn ccm() { fn ccm_inplace() { // Example vector C.1 let k = [ - 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, - 0x4f, + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, ]; let iv = [0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16]; let ad = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]; @@ -440,25 +397,13 @@ fn ccm_inplace() { let validate_cipher = [0x71, 0x62, 0x01, 0x5b, 0x4d, 0xac, 0x25, 0x5d]; let validate_plain = [0x20, 0x21, 0x22, 0x23]; - let cipher = Cipher::<_, Authenticated, _>::new( - raw::CipherId::Aes, - raw::CipherMode::CCM, - (k.len() * 8) as _, - ) - .unwrap(); + let cipher = Cipher::<_, Authenticated, _>::new(raw::CipherId::Aes, raw::CipherMode::CCM, (k.len() * 8) as _).unwrap(); let cipher = cipher.set_key_iv(&k, &iv).unwrap(); let (data, tag) = c.split_at_mut(4); - cipher - .encrypt_auth_inplace(&ad, data, tag) - .unwrap(); + cipher.encrypt_auth_inplace(&ad, data, tag).unwrap(); assert_eq!(c, validate_cipher); - let cipher = Cipher::<_, Authenticated, _>::new( - raw::CipherId::Aes, - raw::CipherMode::CCM, - (k.len() * 8) as _, - ) - .unwrap(); + let cipher = Cipher::<_, Authenticated, _>::new(raw::CipherId::Aes, raw::CipherMode::CCM, (k.len() * 8) as _).unwrap(); let cipher = cipher.set_key_iv(&k, &iv).unwrap(); let (data, tag) = c.split_at_mut(4); cipher.decrypt_auth_inplace(&ad, data, tag).unwrap(); @@ -467,40 +412,48 @@ fn ccm_inplace() { #[test] fn aes_kw() { - let k = [0x75, 0x75, 0xda, 0x3a, 0x93, 0x60, 0x7c, 0xc2, 0xbf, 0xd8, 0xce, 0xc7, 0xaa, 0xdf, 0xd9, 0xa6]; - let p = [0x42, 0x13, 0x6d, 0x3c, 0x38, 0x4a, 0x3e, 0xea, 0xc9, 0x5a, 0x06, 0x6f, 0xd2, 0x8f, 0xed, 0x3f]; - let mut p_out = [0u8; 16]; - let c = [0x03, 0x1f, 0x6b, 0xd7, 0xe6, 0x1e, 0x64, 0x3d, - 0xf6, 0x85, 0x94, 0x81, 0x6f, 0x64, 0xca, 0xa3, - 0xf5, 0x6f, 0xab, 0xea, 0x25, 0x48, 0xf5, 0xfb]; - let mut c_out = [0u8; 24]; - - let cipher = Cipher::<_, Authenticated, _>::new(raw::CipherId::Aes, raw::CipherMode::KW, (k.len() * 8) as _).unwrap(); - let cipher = cipher.set_key_iv(&k, &[]).unwrap(); - cipher.encrypt_auth(&[], &p, &mut c_out, 0).unwrap(); - assert_eq!(c, c_out); - let cipher = Cipher::<_, Authenticated, _>::new(raw::CipherId::Aes, raw::CipherMode::KW, (k.len() * 8) as _).unwrap(); - let cipher = cipher.set_key_iv(&k, &[]).unwrap(); - cipher.decrypt_auth(&[], &c, &mut p_out, 0).unwrap(); - assert_eq!(p, p_out); + let k = [ + 0x75, 0x75, 0xda, 0x3a, 0x93, 0x60, 0x7c, 0xc2, 0xbf, 0xd8, 0xce, 0xc7, 0xaa, 0xdf, 0xd9, 0xa6, + ]; + let p = [ + 0x42, 0x13, 0x6d, 0x3c, 0x38, 0x4a, 0x3e, 0xea, 0xc9, 0x5a, 0x06, 0x6f, 0xd2, 0x8f, 0xed, 0x3f, + ]; + let mut p_out = [0u8; 16]; + let c = [ + 0x03, 0x1f, 0x6b, 0xd7, 0xe6, 0x1e, 0x64, 0x3d, 0xf6, 0x85, 0x94, 0x81, 0x6f, 0x64, 0xca, 0xa3, 0xf5, 0x6f, 0xab, 0xea, + 0x25, 0x48, 0xf5, 0xfb, + ]; + let mut c_out = [0u8; 24]; + + let cipher = Cipher::<_, Authenticated, _>::new(raw::CipherId::Aes, raw::CipherMode::KW, (k.len() * 8) as _).unwrap(); + let cipher = cipher.set_key_iv(&k, &[]).unwrap(); + cipher.encrypt_auth(&[], &p, &mut c_out, 0).unwrap(); + assert_eq!(c, c_out); + let cipher = Cipher::<_, Authenticated, _>::new(raw::CipherId::Aes, raw::CipherMode::KW, (k.len() * 8) as _).unwrap(); + let cipher = cipher.set_key_iv(&k, &[]).unwrap(); + cipher.decrypt_auth(&[], &c, &mut p_out, 0).unwrap(); + assert_eq!(p, p_out); } #[test] fn aes_kwp() { - let k = [0x78, 0x65, 0xe2, 0x0f, 0x3c, 0x21, 0x65, 0x9a, 0xb4, 0x69, 0x0b, 0x62, 0x9c, 0xdf, 0x3c, 0xc4]; - let p = [0xbd, 0x68, 0x43, 0xd4, 0x20, 0x37, 0x8d, 0xc8, 0x96]; - let mut p_out = [0u8; 16]; - let c = [0x41, 0xec, 0xa9, 0x56, 0xd4, 0xaa, 0x04, 0x7e, - 0xb5, 0xcf, 0x4e, 0xfe, 0x65, 0x96, 0x61, 0xe7, - 0x4d, 0xb6, 0xf8, 0xc5, 0x64, 0xe2, 0x35, 0x00]; - let mut c_out = [0u8; 24]; - - let cipher = Cipher::<_, Authenticated, _>::new(raw::CipherId::Aes, raw::CipherMode::KWP, (k.len() * 8) as _).unwrap(); - let cipher = cipher.set_key_iv(&k, &[]).unwrap(); - cipher.encrypt_auth(&[], &p, &mut c_out, 0).unwrap(); - assert_eq!(c, c_out); - let cipher = Cipher::<_, Authenticated, _>::new(raw::CipherId::Aes, raw::CipherMode::KWP, (k.len() * 8) as _).unwrap(); - let cipher = cipher.set_key_iv(&k, &[]).unwrap(); - let out_len = cipher.decrypt_auth(&[], &c, &mut p_out, 0).unwrap().0; - assert_eq!(p, &p_out[..out_len]); + let k = [ + 0x78, 0x65, 0xe2, 0x0f, 0x3c, 0x21, 0x65, 0x9a, 0xb4, 0x69, 0x0b, 0x62, 0x9c, 0xdf, 0x3c, 0xc4, + ]; + let p = [0xbd, 0x68, 0x43, 0xd4, 0x20, 0x37, 0x8d, 0xc8, 0x96]; + let mut p_out = [0u8; 16]; + let c = [ + 0x41, 0xec, 0xa9, 0x56, 0xd4, 0xaa, 0x04, 0x7e, 0xb5, 0xcf, 0x4e, 0xfe, 0x65, 0x96, 0x61, 0xe7, 0x4d, 0xb6, 0xf8, 0xc5, + 0x64, 0xe2, 0x35, 0x00, + ]; + let mut c_out = [0u8; 24]; + + let cipher = Cipher::<_, Authenticated, _>::new(raw::CipherId::Aes, raw::CipherMode::KWP, (k.len() * 8) as _).unwrap(); + let cipher = cipher.set_key_iv(&k, &[]).unwrap(); + cipher.encrypt_auth(&[], &p, &mut c_out, 0).unwrap(); + assert_eq!(c, c_out); + let cipher = Cipher::<_, Authenticated, _>::new(raw::CipherId::Aes, raw::CipherMode::KWP, (k.len() * 8) as _).unwrap(); + let cipher = cipher.set_key_iv(&k, &[]).unwrap(); + let out_len = cipher.decrypt_auth(&[], &c, &mut p_out, 0).unwrap().0; + assert_eq!(p, &p_out[..out_len]); } diff --git a/mbedtls/src/cipher/raw/mod.rs b/mbedtls/src/cipher/raw/mod.rs index 3791a7efe..25553af5e 100644 --- a/mbedtls/src/cipher/raw/mod.rs +++ b/mbedtls/src/cipher/raw/mod.rs @@ -178,17 +178,13 @@ impl Cipher { // Setup routine - this should be the first function called // it combines several steps into one call here, they are // Cipher init, Cipher setup - pub fn setup( - cipher_id: CipherId, - cipher_mode: CipherMode, - key_bit_len: u32, - ) -> Result { + pub fn setup(cipher_id: CipherId, cipher_mode: CipherMode, key_bit_len: u32) -> Result { let mut ret = Self::init(); unsafe { // Do setup with proper cipher_info based on algorithm, key length and mode cipher_setup( &mut ret.inner, - cipher_info_from_values(cipher_id.into(), key_bit_len as i32, cipher_mode.into()) + cipher_info_from_values(cipher_id.into(), key_bit_len as i32, cipher_mode.into()), ) .into_result()?; } @@ -197,15 +193,7 @@ impl Cipher { // Cipher set key - should be called after setup pub fn set_key(&mut self, op: Operation, key: &[u8]) -> Result<()> { - unsafe { - cipher_setkey( - &mut self.inner, - key.as_ptr(), - (key.len() * 8) as _, - op.into(), - ) - .into_result_discard() - } + unsafe { cipher_setkey(&mut self.inner, key.as_ptr(), (key.len() * 8) as _, op.into()).into_result_discard() } } pub fn set_padding(&mut self, padding: CipherPadding) -> Result<()> { @@ -244,7 +232,7 @@ impl Cipher { indata.as_ptr(), indata.len(), outdata.as_mut_ptr(), - &mut olen + &mut olen, ) .into_result()?; } @@ -265,9 +253,7 @@ impl Cipher { } pub fn write_tag(&mut self, tag: &mut [u8]) -> Result<()> { - unsafe { - cipher_write_tag(&mut self.inner, tag.as_mut_ptr(), tag.len()).into_result_discard() - } + unsafe { cipher_write_tag(&mut self.inner, tag.as_mut_ptr(), tag.len()).into_result_discard() } } pub fn check_tag(&mut self, tag: &[u8]) -> Result<()> { @@ -291,9 +277,7 @@ impl Cipher { // Utility function to get mdoe for the selected / setup cipher_info pub fn is_authenticated(&self) -> bool { unsafe { - if (*self.inner.cipher_info).mode == MODE_GCM - || (*self.inner.cipher_info).mode == MODE_CCM - { + if (*self.inner.cipher_info).mode == MODE_GCM || (*self.inner.cipher_info).mode == MODE_CCM { return true; } else { return false; @@ -315,16 +299,12 @@ impl Cipher { self.do_crypto(cipher, plain) } - pub fn encrypt_auth( - &mut self, - ad: &[u8], - plain: &[u8], - cipher_and_tag: &mut [u8], - tag_len: usize, - ) -> Result { - if cipher_and_tag.len() + pub fn encrypt_auth(&mut self, ad: &[u8], plain: &[u8], cipher_and_tag: &mut [u8], tag_len: usize) -> Result { + if cipher_and_tag + .len() .checked_sub(tag_len) - .map_or(true, |cipher_len| cipher_len < plain.len()) { + .map_or(true, |cipher_len| cipher_len < plain.len()) + { return Err(Error::CipherBadInputData); } @@ -351,18 +331,14 @@ impl Cipher { Ok(cipher_len) } - pub fn decrypt_auth( - &mut self, - ad: &[u8], - cipher_and_tag: &[u8], - plain: &mut [u8], - tag_len: usize, - ) -> Result { + pub fn decrypt_auth(&mut self, ad: &[u8], cipher_and_tag: &[u8], plain: &mut [u8], tag_len: usize) -> Result { // For AES KW and KWP cipher text length can be greater than plain text length - if self.is_authenticated() && - cipher_and_tag.len() + if self.is_authenticated() + && cipher_and_tag + .len() .checked_sub(tag_len) - .map_or(true, |cipher_len| plain.len() < cipher_len) { + .map_or(true, |cipher_len| plain.len() < cipher_len) + { return Err(Error::CipherBadInputData); } @@ -389,13 +365,7 @@ impl Cipher { Ok(plain_len) } - pub fn encrypt_auth_inplace( - &mut self, - ad: &[u8], - data: &mut [u8], - tag: &mut [u8], - ) -> Result { - + pub fn encrypt_auth_inplace(&mut self, ad: &[u8], data: &mut [u8], tag: &mut [u8]) -> Result { let iv = self.inner.iv; let iv_len = self.inner.iv_size; let mut olen = data.len(); @@ -419,13 +389,7 @@ impl Cipher { Ok(olen) } - pub fn decrypt_auth_inplace( - &mut self, - ad: &[u8], - data: &mut [u8], - tag: &[u8], - ) -> Result { - + pub fn decrypt_auth_inplace(&mut self, ad: &[u8], data: &mut [u8], tag: &[u8]) -> Result { let iv = self.inner.iv; let iv_len = self.inner.iv_size; let mut plain_len = data.len(); @@ -478,12 +442,18 @@ impl Cipher { } self.reset()?; unsafe { - cipher_cmac(&*self.inner.cipher_info, key.as_ptr(), (key.len() * 8) as _, data.as_ptr(), data.len(), - outdata.as_mut_ptr()).into_result()?; + cipher_cmac( + &*self.inner.cipher_info, + key.as_ptr(), + (key.len() * 8) as _, + data.as_ptr(), + data.len(), + outdata.as_mut_ptr(), + ) + .into_result()?; } Ok(()) } - } #[test] @@ -515,7 +485,11 @@ fn one_part_ecb() { fn cmac_test() { let mut c = Cipher::setup(CipherId::Aes, CipherMode::ECB, 128).unwrap(); let mut out = [0u8; 16]; - c.cmac(b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", - b"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff", &mut out).expect("Success in CMAC"); + c.cmac( + b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", + b"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff", + &mut out, + ) + .expect("Success in CMAC"); assert_eq!(&out, b"\x38\x7b\x36\x22\x8b\xa7\x77\x44\x5b\xaf\xa0\x36\x45\xb9\x40\x10"); } diff --git a/mbedtls/src/cipher/raw/serde.rs b/mbedtls/src/cipher/raw/serde.rs index 99027b5e7..9e5238001 100644 --- a/mbedtls/src/cipher/raw/serde.rs +++ b/mbedtls/src/cipher/raw/serde.rs @@ -13,9 +13,9 @@ use core::fmt; use core::marker::PhantomData; use core::mem::size_of; use core::ptr; +use core::result::Result; use core::slice::from_raw_parts; use core::str; -use core::result::Result; use mbedtls_sys::*; use serde; use serde::de::Unexpected; @@ -49,11 +49,12 @@ enum AlgorithmContext { Des3(Bytes), Gcm { context: Bytes, - inner_cipher_ctx: Box - } + inner_cipher_ctx: Box, + }, } -// Serialization support for cipher structs. We only support serialization in the "data" state. +// Serialization support for cipher structs. We only support serialization in +// the "data" state. impl Serialize for Cipher { fn serialize(&self, s: S) -> Result @@ -62,8 +63,7 @@ impl Serialize for Cipher { { let saved_raw_cipher = unsafe { let cipher_context = self.raw_cipher.inner; - serialize_raw_cipher(cipher_context) - .map_err(ser::Error::custom)? + serialize_raw_cipher(cipher_context).map_err(ser::Error::custom)? }; match Op::is_encrypt() { @@ -73,9 +73,7 @@ impl Serialize for Cipher { } } -unsafe fn serialize_raw_cipher(mut cipher_context: cipher_context_t) - -> Result { - +unsafe fn serialize_raw_cipher(mut cipher_context: cipher_context_t) -> Result { let cipher_id = (*(*cipher_context.cipher_info).base).cipher; let cipher_mode = (*cipher_context.cipher_info).mode; let key_bit_len = (*cipher_context.cipher_info).key_bitlen; @@ -96,24 +94,15 @@ unsafe fn serialize_raw_cipher(mut cipher_context: cipher_context_t) aes_context.rk = ::core::ptr::null_mut(); AlgorithmContext::Aes(Bytes(aes_context)) } - (CIPHER_ID_ARIA, MODE_CBC) - | (CIPHER_ID_ARIA, MODE_CTR) - | (CIPHER_ID_ARIA, MODE_CFB) - | (CIPHER_ID_ARIA, MODE_ECB) => { + (CIPHER_ID_ARIA, MODE_CBC) | (CIPHER_ID_ARIA, MODE_CTR) | (CIPHER_ID_ARIA, MODE_CFB) | (CIPHER_ID_ARIA, MODE_ECB) => { AlgorithmContext::Aria(Bytes(*(cipher_context.cipher_ctx as *const aria_context))) } - (CIPHER_ID_DES, MODE_CBC) - | (CIPHER_ID_DES, MODE_CTR) - | (CIPHER_ID_DES, MODE_OFB) - | (CIPHER_ID_DES, MODE_CFB) => { + (CIPHER_ID_DES, MODE_CBC) | (CIPHER_ID_DES, MODE_CTR) | (CIPHER_ID_DES, MODE_OFB) | (CIPHER_ID_DES, MODE_CFB) => { AlgorithmContext::Des(Bytes(*(cipher_context.cipher_ctx as *const des_context))) } - (CIPHER_ID_3DES, MODE_CBC) - | (CIPHER_ID_3DES, MODE_CTR) - | (CIPHER_ID_3DES, MODE_OFB) - | (CIPHER_ID_3DES, MODE_CFB) => AlgorithmContext::Des3(Bytes( - *(cipher_context.cipher_ctx as *const des3_context), - )), + (CIPHER_ID_3DES, MODE_CBC) | (CIPHER_ID_3DES, MODE_CTR) | (CIPHER_ID_3DES, MODE_OFB) | (CIPHER_ID_3DES, MODE_CFB) => { + AlgorithmContext::Des3(Bytes(*(cipher_context.cipher_ctx as *const des3_context))) + } (CIPHER_ID_AES, MODE_GCM) => { let gcm_context = *(cipher_context.cipher_ctx as *const gcm_context); @@ -123,9 +112,9 @@ unsafe fn serialize_raw_cipher(mut cipher_context: cipher_context_t) AlgorithmContext::Gcm { context: Bytes(gcm_context), - inner_cipher_ctx: Box::new(inner_saved_cipher) + inner_cipher_ctx: Box::new(inner_saved_cipher), } - }, + } _ => { return Err("unsupported algorithm for serialization"); } @@ -167,10 +156,7 @@ impl<'de, Op: Operation, T: Type> Deserialize<'de> for Cipher &"decryption", )); } - SavedCipher::Encryption(raw, padding) | SavedCipher::Decryption(raw, padding) - => { - (raw, padding) - } + SavedCipher::Encryption(raw, padding) | SavedCipher::Decryption(raw, padding) => (raw, padding), }; unsafe { @@ -187,14 +173,11 @@ impl<'de, Op: Operation, T: Type> Deserialize<'de> for Cipher } } -unsafe fn deserialize_raw_cipher(raw: SavedRawCipher, padding: raw::CipherPadding) - -> Result { - - let mut raw_cipher = match raw::Cipher::setup( - raw.cipher_id.into(), - raw.cipher_mode.into(), - raw.key_bit_len, - ) { +unsafe fn deserialize_raw_cipher( + raw: SavedRawCipher, + padding: raw::CipherPadding, +) -> Result { + let mut raw_cipher = match raw::Cipher::setup(raw.cipher_id.into(), raw.cipher_mode.into(), raw.key_bit_len) { Ok(raw) => raw, Err(_) => { return Err(("bad cipher parameters", "valid parameters")); @@ -221,16 +204,17 @@ unsafe fn deserialize_raw_cipher(raw: SavedRawCipher, padding: raw::CipherPaddin (CIPHER_ID_ARIA, AlgorithmContext::Aria(Bytes(aria_ctx))) => { *(cipher_context.cipher_ctx as *mut aria_context) = aria_ctx } - (CIPHER_ID_DES, AlgorithmContext::Des(Bytes(des_ctx))) => { - *(cipher_context.cipher_ctx as *mut des_context) = des_ctx - } + (CIPHER_ID_DES, AlgorithmContext::Des(Bytes(des_ctx))) => *(cipher_context.cipher_ctx as *mut des_context) = des_ctx, (CIPHER_ID_3DES, AlgorithmContext::Des3(Bytes(des3_ctx))) => { *(cipher_context.cipher_ctx as *mut des3_context) = des3_ctx } - (CIPHER_ID_AES, AlgorithmContext::Gcm { - context: Bytes(mut gcm_ctx), - inner_cipher_ctx - }) => { + ( + CIPHER_ID_AES, + AlgorithmContext::Gcm { + context: Bytes(mut gcm_ctx), + inner_cipher_ctx, + }, + ) => { let inner_raw_cipher = deserialize_raw_cipher(*inner_cipher_ctx, raw::CipherPadding::None)?; gcm_ctx.cipher_ctx = inner_raw_cipher.into_inner(); @@ -251,8 +235,8 @@ unsafe fn deserialize_raw_cipher(raw: SavedRawCipher, padding: raw::CipherPaddin Ok(raw_cipher) } -// Serialization support for raw cipher structs. Custom serialization as a sequence to save the -// space of encoding all the member names. +// Serialization support for raw cipher structs. Custom serialization as a +// sequence to save the space of encoding all the member names. impl Serialize for SavedRawCipher { fn serialize(&self, s: S) -> Result @@ -311,9 +295,7 @@ impl<'de, T: BytesSerde> Deserialize<'de> for Bytes { where E: serde::de::Error, { - T::read_slice(v) - .map(Bytes) - .ok_or_else(|| E::invalid_length(v.len(), &self)) + T::read_slice(v).map(Bytes).ok_or_else(|| E::invalid_length(v.len(), &self)) } fn visit_byte_buf(self, v: Vec) -> Result @@ -339,19 +321,22 @@ unsafe impl BytesSerde for des_context {} unsafe impl BytesSerde for des3_context {} unsafe impl BytesSerde for gcm_context {} -// If the C API changes, the serde implementation needs to be reviewed for correctness. The -// following (unused) functions will most probably fail to compile when this happens so a -// compilation failure here reminds us of reviewing the serde impl. +// If the C API changes, the serde implementation needs to be reviewed for +// correctness. The following (unused) functions will most probably fail to +// compile when this happens so a compilation failure here reminds us of +// reviewing the serde impl. -// The sizes of usize and isize as well as all pointer types will be dependent on the architecture -// we are building for. So to be platform independent, the expected sizes are calculated from the -// fixed-sized fields, the number and size of pointer-sized fields and some alignment bytes. +// The sizes of usize and isize as well as all pointer types will be dependent +// on the architecture we are building for. So to be platform independent, the +// expected sizes are calculated from the fixed-sized fields, the number and +// size of pointer-sized fields and some alignment bytes. -const _SIZE_OF_CIPHER_CONTEXT: usize = size_of::() + 2 * 4 + 2 * size_of::() + 16 + size_of::() + 16 + 3 * size_of::(); +const _SIZE_OF_CIPHER_CONTEXT: usize = + size_of::() + 2 * 4 + 2 * size_of::() + 16 + size_of::() + 16 + 3 * size_of::(); const _SIZE_OF_AES_CONTEXT: usize = 2 * size_of::() + 4 * 68; const _SIZE_OF_DES_CONTEXT: usize = 4 * 32; const _SIZE_OF_DES3_CONTEXT: usize = 4 * 96; -const _SIZE_OF_GCM_CONTEXT: usize = (_SIZE_OF_CIPHER_CONTEXT+7)/8*8 + 8 * 16 + 8 * 16 + 8 + 8 + 16 + 16 + 16 + 8; // first summand: cipher_context 8-byte aligned +const _SIZE_OF_GCM_CONTEXT: usize = (_SIZE_OF_CIPHER_CONTEXT + 7) / 8 * 8 + 8 * 16 + 8 * 16 + 8 + 8 + 16 + 16 + 16 + 8; // first summand: cipher_context 8-byte aligned unsafe fn _check_cipher_context_t_size(ctx: cipher_context_t) -> [u8; _SIZE_OF_CIPHER_CONTEXT] { ::core::mem::transmute(ctx) @@ -369,4 +354,6 @@ unsafe fn _check_des3_context_size(ctx: des3_context) -> [u8; _SIZE_OF_DES3_CONT ::core::mem::transmute(ctx) } -unsafe fn _check_gcm_context_size(ctx: gcm_context) -> [u8; _SIZE_OF_GCM_CONTEXT] { ::core::mem::transmute(ctx) } +unsafe fn _check_gcm_context_size(ctx: gcm_context) -> [u8; _SIZE_OF_GCM_CONTEXT] { + ::core::mem::transmute(ctx) +} diff --git a/mbedtls/src/ecp/mod.rs b/mbedtls/src/ecp/mod.rs index 7b3c36818..4a21ffa2f 100644 --- a/mbedtls/src/ecp/mod.rs +++ b/mbedtls/src/ecp/mod.rs @@ -6,8 +6,8 @@ * option. This file may not be copied, modified, or distributed except * according to those terms. */ -use core::convert::TryFrom; use crate::error::{Error, IntoResult, Result}; +use core::convert::TryFrom; use mbedtls_sys::*; #[cfg(not(feature = "std"))] @@ -86,14 +86,7 @@ impl EcGroup { /// trusted. Failing to comply with this requirement may result in the use /// of INSECURE curves. Prefer [EcGroup::new] with known curves listed in /// [EcGroupId]. - pub fn from_parameters( - p: Mpi, - a: Mpi, - b: Mpi, - g_x: Mpi, - g_y: Mpi, - order: Mpi, - ) -> Result { + pub fn from_parameters(p: Mpi, a: Mpi, b: Mpi, g_x: Mpi, g_y: Mpi, order: Mpi) -> Result { let mut ret = Self::init(); ret.inner.pbits = p.bit_length()?; @@ -285,8 +278,7 @@ impl EcPoint { EcPoint::from_components(x, y) } else { let mut ret = Self::init(); - unsafe { ecp_point_read_binary(&group.inner, &mut ret.inner, bin.as_ptr(), bin.len()) } - .into_result()?; + unsafe { ecp_point_read_binary(&group.inner, &mut ret.inner, bin.as_ptr(), bin.len()) }.into_result()?; Ok(ret) } } @@ -345,13 +337,7 @@ impl EcPoint { } /// Compute pt1*k1 + pt2*k2 -- not const time - pub fn muladd( - group: &mut EcGroup, - pt1: &EcPoint, - k1: &Mpi, - pt2: &EcPoint, - k2: &Mpi, - ) -> Result { + pub fn muladd(group: &mut EcGroup, pt1: &EcPoint, k1: &Mpi, pt2: &EcPoint, k2: &Mpi) -> Result { let mut ret = Self::init(); if group.contains_point(&pt1)? == false { @@ -400,23 +386,10 @@ impl EcPoint { let mut olen = 0; let mut buf = vec![0u8; 133]; - let format = if compressed { - ECP_PF_COMPRESSED - } else { - ECP_PF_UNCOMPRESSED - }; + let format = if compressed { ECP_PF_COMPRESSED } else { ECP_PF_UNCOMPRESSED }; - unsafe { - ecp_point_write_binary( - &group.inner, - &self.inner, - format, - &mut olen, - buf.as_mut_ptr(), - buf.len(), - ) - } - .into_result()?; + unsafe { ecp_point_write_binary(&group.inner, &self.inner, format, &mut olen, buf.as_mut_ptr(), buf.len()) } + .into_result()?; assert!(olen <= buf.len()); @@ -441,9 +414,8 @@ mod tests { let p = secp256r1.p().unwrap().to_binary().unwrap(); let p256 = vec![ - 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, ]; assert_eq!(p, p256); @@ -460,7 +432,8 @@ mod tests { ) .unwrap(); - assert!(secp256r1 == copy); //can't use assert_eq as EcGroup doesn't impl Debug + assert!(secp256r1 == copy); //can't use assert_eq as EcGroup doesn't + // impl Debug } // FIXME: very slow on SGX https://github.com/fortanix/rust-mbedtls/issues/134 @@ -538,14 +511,12 @@ mod tests { let affine_x = pt.x().unwrap(); assert_eq!( affine_x, - Mpi::from_str("0x1E248FB0AB87942E4B74446F7C9CD151468919B525C108759876F806CA2FFC87") - .unwrap() + Mpi::from_str("0x1E248FB0AB87942E4B74446F7C9CD151468919B525C108759876F806CA2FFC87").unwrap() ); let affine_y = pt.y().unwrap(); assert_eq!( affine_y, - Mpi::from_str("0x821F40015051C2E37E85A97D96B83A9948FB108E06C98F5AD2CF275C8A9B004B") - .unwrap() + Mpi::from_str("0x821F40015051C2E37E85A97D96B83A9948FB108E06C98F5AD2CF275C8A9B004B").unwrap() ); let pt_from_components = EcPoint::from_components(affine_x, affine_y).unwrap(); assert!(pt.eq(&pt_from_components).unwrap()); @@ -567,60 +538,22 @@ mod tests { let order = Mpi::from_str("0xDB7C2ABF62E35E7628DFAC6561C5").unwrap(); // correct parameters are accepted - assert!(EcGroup::from_parameters( - p.clone(), - a.clone(), - b.clone(), - g_x.clone(), - g_y.clone(), - order.clone() - ) - .is_ok()); + assert!(EcGroup::from_parameters(p.clone(), a.clone(), b.clone(), g_x.clone(), g_y.clone(), order.clone()).is_ok()); // swap (x,y) in generator - assert!(EcGroup::from_parameters( - p.clone(), - a.clone(), - b.clone(), - g_y.clone(), - g_x.clone(), - order.clone() - ) - .is_err()); + assert!(EcGroup::from_parameters(p.clone(), a.clone(), b.clone(), g_y.clone(), g_x.clone(), order.clone()).is_err()); // swap (a,b) in equation - assert!(EcGroup::from_parameters( - p.clone(), - b.clone(), - a.clone(), - g_x.clone(), - g_y.clone(), - order.clone() - ) - .is_err()); + assert!(EcGroup::from_parameters(p.clone(), b.clone(), a.clone(), g_x.clone(), g_y.clone(), order.clone()).is_err()); // pass p as the order - assert!(EcGroup::from_parameters( - p.clone(), - b.clone(), - a.clone(), - g_x.clone(), - g_y.clone(), - p.clone() - ) - .is_err()); + assert!(EcGroup::from_parameters(p.clone(), b.clone(), a.clone(), g_x.clone(), g_y.clone(), p.clone()).is_err()); // invalid order let order_p_3 = (&order + &Mpi::new(3).unwrap()).unwrap(); - assert!(EcGroup::from_parameters( - p.clone().clone(), - b.clone(), - a.clone(), - g_x.clone(), - g_y.clone(), - order_p_3 - ) - .is_err()); + assert!( + EcGroup::from_parameters(p.clone().clone(), b.clone(), a.clone(), g_x.clone(), g_y.clone(), order_p_3).is_err() + ); } #[test] @@ -629,57 +562,41 @@ mod tests { use std::str::FromStr; // Test from RFC 7901 - let p = Mpi::from_str("0x8000000000000000000000000000000000000000000000000000000000000431") - .unwrap(); + let p = Mpi::from_str("0x8000000000000000000000000000000000000000000000000000000000000431").unwrap(); let a = Mpi::from_str("7").unwrap(); - let b = Mpi::from_str("0x5FBFF498AA938CE739B8E022FBAFEF40563F6E6A3472FC2A514C0CE9DAE23B7E") - .unwrap(); - let order = - Mpi::from_str("0x8000000000000000000000000000000150FE8A1892976154C59CFC193ACCF5B3") - .unwrap(); + let b = Mpi::from_str("0x5FBFF498AA938CE739B8E022FBAFEF40563F6E6A3472FC2A514C0CE9DAE23B7E").unwrap(); + let order = Mpi::from_str("0x8000000000000000000000000000000150FE8A1892976154C59CFC193ACCF5B3").unwrap(); let g_x = Mpi::from_str("2").unwrap(); - let g_y = - Mpi::from_str("0x8E2A8A0E65147D4BD6316030E16D19C85C97F0A9CA267122B96ABBCEA7E8FC8") - .unwrap(); + let g_y = Mpi::from_str("0x8E2A8A0E65147D4BD6316030E16D19C85C97F0A9CA267122B96ABBCEA7E8FC8").unwrap(); let mut gost = EcGroup::from_parameters(p.clone(), a, b, g_x, g_y, order.clone()).unwrap(); let gost_g = gost.generator().unwrap(); - let d = Mpi::from_str("0x7A929ADE789BB9BE10ED359DD39A72C11B60961F49397EEE1D19CE9891EC3B28") - .unwrap(); + let d = Mpi::from_str("0x7A929ADE789BB9BE10ED359DD39A72C11B60961F49397EEE1D19CE9891EC3B28").unwrap(); let pubkey = gost_g.mul(&mut gost, &d).unwrap(); let pubkey_x = pubkey.x().unwrap(); let pubkey_y = pubkey.y().unwrap(); - let exp_pub_x = - Mpi::from_str("0x7F2B49E270DB6D90D8595BEC458B50C58585BA1D4E9B788F6689DBD8E56FD80B") - .unwrap(); - let exp_pub_y = - Mpi::from_str("0x26F1B489D6701DD185C8413A977B3CBBAF64D1C593D26627DFFB101A87FF77DA") - .unwrap(); + let exp_pub_x = Mpi::from_str("0x7F2B49E270DB6D90D8595BEC458B50C58585BA1D4E9B788F6689DBD8E56FD80B").unwrap(); + let exp_pub_y = Mpi::from_str("0x26F1B489D6701DD185C8413A977B3CBBAF64D1C593D26627DFFB101A87FF77DA").unwrap(); assert_eq!(pubkey_x, exp_pub_x); assert_eq!(pubkey_y, exp_pub_y); - let k = Mpi::from_str("0x77105C9B20BCD3122823C8CF6FCC7B956DE33814E95B7FE64FED924594DCEAB3") - .unwrap(); + let k = Mpi::from_str("0x77105C9B20BCD3122823C8CF6FCC7B956DE33814E95B7FE64FED924594DCEAB3").unwrap(); let gk = gost_g.mul(&mut gost, &k).unwrap(); - let exp_gk_x = - Mpi::from_str("0x41AA28D2F1AB148280CD9ED56FEDA41974053554A42767B83AD043FD39DC0493"); - let exp_gk_y = - Mpi::from_str("0x489C375A9941A3049E33B34361DD204172AD98C3E5916DE27695D22A61FAE46E"); + let exp_gk_x = Mpi::from_str("0x41AA28D2F1AB148280CD9ED56FEDA41974053554A42767B83AD043FD39DC0493"); + let exp_gk_y = Mpi::from_str("0x489C375A9941A3049E33B34361DD204172AD98C3E5916DE27695D22A61FAE46E"); assert_eq!(gk.x(), exp_gk_x); assert_eq!(gk.y(), exp_gk_y); - let hm = - Mpi::from_str("0x2DFBC1B372D89A1188C09C52E0EEC61FCE52032AB1022E8E67ECE6672B043EE5") - .unwrap(); + let hm = Mpi::from_str("0x2DFBC1B372D89A1188C09C52E0EEC61FCE52032AB1022E8E67ECE6672B043EE5").unwrap(); let mut e = hm.modulo(&order).unwrap(); @@ -695,12 +612,8 @@ mod tests { let ke = (&k * &e).unwrap(); let s = ((&rd + &ke).unwrap()).modulo(&order).unwrap(); - let exp_r = - Mpi::from_str("0x41AA28D2F1AB148280CD9ED56FEDA41974053554A42767B83AD043FD39DC0493") - .unwrap(); - let exp_s = - Mpi::from_str("0x1456C64BA4642A1653C235A98A60249BCD6D3F746B631DF928014F6C5BF9C40") - .unwrap(); + let exp_r = Mpi::from_str("0x41AA28D2F1AB148280CD9ED56FEDA41974053554A42767B83AD043FD39DC0493").unwrap(); + let exp_s = Mpi::from_str("0x1456C64BA4642A1653C235A98A60249BCD6D3F746B631DF928014F6C5BF9C40").unwrap(); assert_eq!(r, exp_r); assert_eq!(s, exp_s); @@ -769,12 +682,12 @@ mod tests { #[cfg(feature = "std")] struct Params<'a> { - p: &'a str, - a: &'a str, - b: &'a str, + p: &'a str, + a: &'a str, + b: &'a str, g_x: &'a str, g_y: &'a str, - n: &'a str, + n: &'a str, } #[cfg(feature = "std")] @@ -797,13 +710,14 @@ mod tests { fn pathological_parameters() { // y² = x³ mod 7 (note a == b == 0) let singular: super::Result<_> = Params { - p: "0x07", - a: "0x00", - b: "0x00", + p: "0x07", + a: "0x00", + b: "0x00", g_x: "0x01", g_y: "0x02", - n: "0x0b", - }.into(); + n: "0x0b", + } + .into(); assert!(singular.is_err()); } @@ -812,24 +726,26 @@ mod tests { fn bad_generators() { // y² = x³ + x + 6 (mod 7) with bad generator (1, 2) and prime order 11 let small_curve: super::Result<_> = Params { - p: "0x07", - a: "0x01", - b: "0x06", + p: "0x07", + a: "0x01", + b: "0x06", g_x: "0x01", g_y: "0x02", - n: "0x0b", - }.into(); + n: "0x0b", + } + .into(); assert!(small_curve.is_err()); // y² = x³ + x + 6 (mod 7) with bad generator (0, 0) and prime order 11 let small_curve_zero_gen: super::Result<_> = Params { - p: "0x07", - a: "0x01", - b: "0x06", + p: "0x07", + a: "0x01", + b: "0x06", g_x: "0x00", g_y: "0x00", - n: "0x0b", - }.into(); + n: "0x0b", + } + .into(); assert!(small_curve_zero_gen.is_err()); } @@ -838,13 +754,14 @@ mod tests { fn unknown_cofactor() { // y² = x³ + x + 6 (mod 7) with generator (1, 6) and prime order 11 let small_curve: super::Result<_> = Params { - p: "0x07", - a: "0x01", - b: "0x06", + p: "0x07", + a: "0x01", + b: "0x06", g_x: "0x01", g_y: "0x06", - n: "0x0b", - }.into(); + n: "0x0b", + } + .into(); assert!(small_curve.unwrap().cofactor().is_err()); } @@ -854,66 +771,71 @@ mod tests { use super::Result; // Barreto-Naehrig 254, note a = 0 let bn254: Result<_> = Params { - p: "0x2523648240000001BA344D80000000086121000000000013A700000000000013", - a: "0x0000000000000000000000000000000000000000000000000000000000000000", - b: "0x0000000000000000000000000000000000000000000000000000000000000002", + p: "0x2523648240000001BA344D80000000086121000000000013A700000000000013", + a: "0x0000000000000000000000000000000000000000000000000000000000000000", + b: "0x0000000000000000000000000000000000000000000000000000000000000002", g_x: "0x2523648240000001BA344D80000000086121000000000013A700000000000012", g_y: "0x0000000000000000000000000000000000000000000000000000000000000001", - n: "0x2523648240000001BA344D8000000007FF9F800000000010A10000000000000D", - }.into(); + n: "0x2523648240000001BA344D8000000007FF9F800000000010A10000000000000D", + } + .into(); assert!(bn254.is_ok()); // Prescribed embedded degree of 12, BLS12-381 let bls12_381: Result<_> = Params { - p: "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab", - a: "0x00", - b: "0x04", + p: "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab", + a: "0x00", + b: "0x04", g_x: "0x17F1D3A73197D7942695638C4FA9AC0FC3688C4F9774B905A14E3A3F171BAC586C55E83FF97A1AEFFB3AF00ADB22C6BB", g_y: "0x08B3F481E3AAA0F1A09E30ED741D8AE4FCF5E095D5D00AF600DB18CB2C04B3EDD03CC744A2888AE40CAA232946C5E7E1", - n: "0x73EDA753299D7D483339D80809A1D80553BDA402FFFE5BFEFFFFFFFF00000001", - }.into(); + n: "0x73EDA753299D7D483339D80809A1D80553BDA402FFFE5BFEFFFFFFFF00000001", + } + .into(); assert!(bls12_381.is_ok()); // Fp256BN let fp256_bn: Result<_> = Params { - p: "0xfffffffffffcf0cd46e5f25eee71a49f0cdc65fb12980a82d3292ddbaed33013", - a: "0x00", - b: "0x03", + p: "0xfffffffffffcf0cd46e5f25eee71a49f0cdc65fb12980a82d3292ddbaed33013", + a: "0x00", + b: "0x03", g_x: "0x01", g_y: "0x02", - n: "0xfffffffffffcf0cd46e5f25eee71a49e0cdc65fb1299921af62d536cd10b500d", - }.into(); + n: "0xfffffffffffcf0cd46e5f25eee71a49e0cdc65fb1299921af62d536cd10b500d", + } + .into(); assert!(fp256_bn.is_ok()); // id-GostR3410-2001-CryptoPro-C-ParamSet, note g_x = 0 let gost_r3410: Result<_> = Params { - p: "0x9b9f605f5a858107ab1ec85e6b41c8aacf846e86789051d37998f7b9022d759b", - a: "0x9b9f605f5a858107ab1ec85e6b41c8aacf846e86789051d37998f7b9022d7598", - b: "0x805a", + p: "0x9b9f605f5a858107ab1ec85e6b41c8aacf846e86789051d37998f7b9022d759b", + a: "0x9b9f605f5a858107ab1ec85e6b41c8aacf846e86789051d37998f7b9022d7598", + b: "0x805a", g_x: "0x00", g_y: "0x41ece55743711a8c3cbf3783cd08c0ee4d4dc440d4641a8f366e550dfdb3bb67", - n: "0x9b9f605f5a858107ab1ec85e6b41c8aa582ca3511eddfb74f02f3a6598980bb9", - }.into(); + n: "0x9b9f605f5a858107ab1ec85e6b41c8aa582ca3511eddfb74f02f3a6598980bb9", + } + .into(); assert!(gost_r3410.is_ok()); // secp256k1 (Bitcoin), note a = 0 let my_secp256k1: Result = Params { - p: "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f", - a: "0x0000000000000000000000000000000000000000000000000000000000000000", - b: "0x0000000000000000000000000000000000000000000000000000000000000007", + p: "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f", + a: "0x0000000000000000000000000000000000000000000000000000000000000000", + b: "0x0000000000000000000000000000000000000000000000000000000000000007", g_x: "0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", g_y: "0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8", - n: "0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", - }.into(); + n: "0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", + } + .into(); assert!(my_secp256k1.is_ok()); let my_secp256k1 = my_secp256k1.unwrap(); // We compare against the known SecP256K1 let secp256k1 = EcGroup::new(EcGroupId::SecP256K1).unwrap(); - assert!(my_secp256k1.p() == secp256k1.p()); - assert!(my_secp256k1.a() == secp256k1.a()); - assert!(my_secp256k1.b() == secp256k1.b()); + assert!(my_secp256k1.p() == secp256k1.p()); + assert!(my_secp256k1.a() == secp256k1.a()); + assert!(my_secp256k1.b() == secp256k1.b()); assert!(my_secp256k1.generator() == secp256k1.generator()); - assert!(my_secp256k1.order() == secp256k1.order()); + assert!(my_secp256k1.order() == secp256k1.order()); } } diff --git a/mbedtls/src/error.rs b/mbedtls/src/error.rs index ef997a228..690a7804e 100644 --- a/mbedtls/src/error.rs +++ b/mbedtls/src/error.rs @@ -6,9 +6,9 @@ * option. This file may not be copied, modified, or distributed except * according to those terms. */ +use core::convert::Infallible; use core::fmt; use core::str::Utf8Error; -use core::convert::Infallible; #[cfg(feature = "std")] use std::error::Error as StdError; @@ -98,9 +98,7 @@ impl From for Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - &Error::Utf8Error(Some(ref e)) => { - f.write_fmt(format_args!("Error converting to UTF-8: {}", e)) - } + &Error::Utf8Error(Some(ref e)) => f.write_fmt(format_args!("Error converting to UTF-8: {}", e)), &Error::Utf8Error(None) => f.write_fmt(format_args!("Error converting to UTF-8")), &Error::Other(i) => f.write_fmt(format_args!("mbedTLS unknown error ({})", i)), &Error::__Nonexhaustive => unreachable!("__Nonexhaustive value should not be instantiated"), diff --git a/mbedtls/src/hash/mod.rs b/mbedtls/src/hash/mod.rs index 7779607d0..c9799b155 100644 --- a/mbedtls/src/hash/mod.rs +++ b/mbedtls/src/hash/mod.rs @@ -172,15 +172,7 @@ impl Hmac { if out.len() < olen { return Err(Error::MdBadInputData); } - md_hmac( - md.inner, - key.as_ptr(), - key.len(), - data.as_ptr(), - data.len(), - out.as_mut_ptr(), - ) - .into_result()?; + md_hmac(md.inner, key.as_ptr(), key.len(), data.as_ptr(), data.len(), out.as_mut_ptr()).into_result()?; Ok(olen) } } @@ -227,13 +219,7 @@ impl Clone for Md { } } -pub fn pbkdf2_hmac( - md: Type, - password: &[u8], - salt: &[u8], - iterations: u32, - key: &mut [u8], -) -> Result<()> { +pub fn pbkdf2_hmac(md: Type, password: &[u8], salt: &[u8], iterations: u32, key: &mut [u8]) -> Result<()> { let md: MdInfo = match md.into() { Some(md) => md, None => return Err(Error::MdBadInputData), @@ -257,14 +243,7 @@ pub fn pbkdf2_hmac( } } -pub fn pbkdf_pkcs12( - md: Type, - password: &[u8], - salt: &[u8], - id: u8, - iterations: u32, - key: &mut [u8], -) -> Result<()> { +pub fn pbkdf_pkcs12(md: Type, password: &[u8], salt: &[u8], id: u8, iterations: u32, key: &mut [u8]) -> Result<()> { unsafe { pkcs12_derivation( key.as_mut_ptr(), diff --git a/mbedtls/src/lib.rs b/mbedtls/src/lib.rs index 3f8e38dde..dc73d8d5d 100644 --- a/mbedtls/src/lib.rs +++ b/mbedtls/src/lib.rs @@ -13,7 +13,6 @@ #[cfg(not(any(feature = "std", feature = "no_std_deps")))] compile_error!("Either the `std` or `no_std_deps` feature needs to be enabled"); - #[macro_use] extern crate serde_derive; // required explicitly to force inclusion at link time @@ -34,13 +33,13 @@ pub mod ecp; pub mod hash; pub mod pk; pub mod rng; -pub use mbedtls_platform_support::self_test as self_test; +pub use mbedtls_platform_support::self_test; +#[cfg(any(feature = "x509", feature = "ssl", feature = "pkcs12"))] +pub mod alloc; #[cfg(feature = "ssl")] pub mod ssl; #[cfg(feature = "x509")] pub mod x509; -#[cfg(any(feature = "x509", feature = "ssl", feature = "pkcs12"))] -pub mod alloc; #[cfg(feature = "pkcs12")] pub mod pkcs12; @@ -86,13 +85,13 @@ extern crate alloc as rust_alloc; #[cfg(not(feature = "std"))] mod alloc_prelude { #![allow(unused)] + pub(crate) use rust_alloc::borrow::Cow; pub(crate) use rust_alloc::borrow::ToOwned; pub(crate) use rust_alloc::boxed::Box; - pub(crate) use rust_alloc::sync::Arc; pub(crate) use rust_alloc::string::String; pub(crate) use rust_alloc::string::ToString; + pub(crate) use rust_alloc::sync::Arc; pub(crate) use rust_alloc::vec::Vec; - pub(crate) use rust_alloc::borrow::Cow; } cfg_if::cfg_if! { @@ -139,7 +138,7 @@ mod tests { use core::marker::PhantomData; pub struct NonImplTrait { - inner: PhantomData + inner: PhantomData, } pub struct TestTrait { @@ -151,7 +150,10 @@ mod tests { impl TestTrait { pub fn new() -> Self { - TestTrait { non_impl: NonImplTrait { inner: PhantomData }, phantom: PhantomData } + TestTrait { + non_impl: NonImplTrait { inner: PhantomData }, + phantom: PhantomData, + } } } diff --git a/mbedtls/src/pk/dsa/mod.rs b/mbedtls/src/pk/dsa/mod.rs index fdf030149..cb3430c59 100644 --- a/mbedtls/src/pk/dsa/mod.rs +++ b/mbedtls/src/pk/dsa/mod.rs @@ -7,15 +7,15 @@ * according to those terms. */ use crate::bignum::Mpi; -use crate::rng::Random; use crate::hash::{MdInfo, Type as MdType}; use crate::pk::rfc6979::generate_rfc6979_nonce; -use crate::{Result, Error}; +use crate::rng::Random; +use crate::{Error, Result}; +use bit_vec::BitVec; +use num_bigint::BigUint; use yasna::models::ObjectIdentifier; pub use yasna::{ASN1Error, ASN1ErrorKind}; -use num_bigint::BigUint; -use bit_vec::BitVec; #[derive(Debug, Clone, Eq, PartialEq)] pub struct DsaParams { @@ -48,11 +48,7 @@ fn reduce_mod_q(m: &[u8], q: &Mpi) -> Result { let m_bits = m.len() * 8; - let dec_len = if m_bits < q_bits { - m.len() - } else { - (q_bits + 7) / 8 - }; + let dec_len = if m_bits < q_bits { m.len() } else { (q_bits + 7) / 8 }; let m_bn = Mpi::from_binary(&m[..dec_len])?; m_bn.modulo(q) @@ -67,7 +63,6 @@ pub struct DsaPublicKey { const DSA_OBJECT_IDENTIFIER: &[u64] = &[1, 2, 840, 10040, 4, 1]; impl DsaPublicKey { - pub fn from_components(params: DsaParams, y: Mpi) -> Result { if y < Mpi::new(1)? || y >= params.p { return Err(Error::PkBadInputData); @@ -80,9 +75,9 @@ impl DsaPublicKey { } pub fn from_der(der: &[u8]) -> Result { - let (p,q,g,y) = yasna::parse_der(der, |r| { + let (p, q, g, y) = yasna::parse_der(der, |r| { r.read_sequence(|r| { - let (p,q,g) = r.next().read_sequence(|r| { + let (p, q, g) = r.next().read_sequence(|r| { let oid = r.next().read_oid()?; if oid != ObjectIdentifier::from_slice(DSA_OBJECT_IDENTIFIER) { return Err(ASN1Error::new(ASN1ErrorKind::Invalid)); @@ -91,17 +86,16 @@ impl DsaPublicKey { let p = r.next().read_biguint()?; let q = r.next().read_biguint()?; let g = r.next().read_biguint()?; - Ok((p,q,g)) + Ok((p, q, g)) }) })?; let y = r.next().read_bitvec()?; - Ok((p,q,g,y)) + Ok((p, q, g, y)) }) - }).map_err(|_| Error::PkInvalidPubkey)?; + }) + .map_err(|_| Error::PkInvalidPubkey)?; - let y = yasna::parse_der(&y.to_bytes(), |r| { - r.read_biguint() - }).map_err(|_| Error::PkInvalidPubkey)?; + let y = yasna::parse_der(&y.to_bytes(), |r| r.read_biguint()).map_err(|_| Error::PkInvalidPubkey)?; let p = Mpi::from_binary(&p.to_bytes_be()).expect("Success"); let q = Mpi::from_binary(&q.to_bytes_be()).expect("Success"); @@ -119,9 +113,7 @@ impl DsaPublicKey { let g = BigUint::from_bytes_be(&self.params.g.to_binary()?); let y = BigUint::from_bytes_be(&self.y.to_binary()?); - let y_as_int = yasna::construct_der(|w| { - w.write_biguint(&y) - }); + let y_as_int = yasna::construct_der(|w| w.write_biguint(&y)); let der = yasna::construct_der(|w| { w.write_sequence(|w| { @@ -141,13 +133,14 @@ impl DsaPublicKey { } pub fn verify(&self, signature: &[u8], pre_hashed_message: &[u8]) -> Result<()> { - let (r,s) = yasna::parse_der(signature, |r| { + let (r, s) = yasna::parse_der(signature, |r| { r.read_sequence(|rdr| { let r = rdr.next().read_biguint()?; let s = rdr.next().read_biguint()?; - Ok((r,s)) + Ok((r, s)) }) - }).map_err(|_| Error::X509InvalidSignature)?; + }) + .map_err(|_| Error::X509InvalidSignature)?; let r = Mpi::from_binary(&r.to_bytes_be()).expect("Success"); let s = Mpi::from_binary(&s.to_bytes_be()).expect("Success"); @@ -190,7 +183,7 @@ impl DsaPublicKey { } pub fn key_size(&self) -> Result<(usize, usize)> { - return self.params.key_size() + return self.params.key_size(); } pub fn parameters(&self) -> &DsaParams { @@ -243,12 +236,12 @@ impl DsaPrivateKey { } pub fn from_der(der: &[u8]) -> Result { - let (p,q,g,x) = yasna::parse_der(der, |r| { + let (p, q, g, x) = yasna::parse_der(der, |r| { r.read_sequence(|r| { if r.next().read_u8()? != 0 { return Err(ASN1Error::new(ASN1ErrorKind::Invalid)); } - let (p,q,g) = r.next().read_sequence(|r| { + let (p, q, g) = r.next().read_sequence(|r| { let oid = r.next().read_oid()?; if oid != ObjectIdentifier::from_slice(DSA_OBJECT_IDENTIFIER) { return Err(ASN1Error::new(ASN1ErrorKind::Invalid)); @@ -257,16 +250,16 @@ impl DsaPrivateKey { let p = r.next().read_biguint()?; let q = r.next().read_biguint()?; let g = r.next().read_biguint()?; - Ok((p,q,g)) + Ok((p, q, g)) }) })?; let x = r.next().read_bytes()?; - Ok((p,q,g,x)) + Ok((p, q, g, x)) }) - }).map_err(|_| Error::PkInvalidPubkey)?; + }) + .map_err(|_| Error::PkInvalidPubkey)?; - let x = yasna::parse_der(&x, |r| { r.read_biguint() }). - map_err(|_| Error::PkInvalidPubkey)?; + let x = yasna::parse_der(&x, |r| r.read_biguint()).map_err(|_| Error::PkInvalidPubkey)?; let p = Mpi::from_binary(&p.to_bytes_be()).expect("Success"); let q = Mpi::from_binary(&q.to_bytes_be()).expect("Success"); @@ -284,7 +277,7 @@ impl DsaPrivateKey { let g = BigUint::from_bytes_be(&self.params.g.to_binary()?); let x = BigUint::from_bytes_be(&self.x.to_binary()?); - let x_as_int = yasna::construct_der(|w| { w.write_biguint(&x) }); + let x_as_int = yasna::construct_der(|w| w.write_biguint(&x)); let der = yasna::construct_der(|w| { w.write_sequence(|w| { @@ -358,7 +351,7 @@ impl DsaPrivateKey { } pub fn key_size(&self) -> Result<(usize, usize)> { - return self.params.key_size() + return self.params.key_size(); } pub fn parameters(&self) -> &DsaParams { @@ -373,8 +366,8 @@ mod tests { use crate::mbedtls::bignum::Mpi; use crate::mbedtls::hash::{Md, Type as MdType}; use crate::mbedtls::rng::HmacDrbg; - use std::time::SystemTime; use std::collections::HashMap; + use std::time::SystemTime; fn hardcoded_2048_256() -> Result { use core::str::FromStr; @@ -386,7 +379,6 @@ mod tests { ) } - fn hex_to_bn(input: &str) -> Mpi { let bin = hex::decode(input).expect("valid hex"); Mpi::from_binary(&bin).unwrap() @@ -399,7 +391,7 @@ mod tests { "SHA-256" => MdType::Sha256, "SHA-384" => MdType::Sha384, "SHA-512" => MdType::Sha512, - _ => panic!("unknown hash") + _ => panic!("unknown hash"), } } @@ -442,7 +434,10 @@ mod tests { let key = DsaPublicKey::from_der(&dsa_der).unwrap(); - assert_eq!(key.params.q, hex_to_bn("94843407f4c5c7d71470464dcf36fe222882589b0e901c6658107229ec3d499f")); + assert_eq!( + key.params.q, + hex_to_bn("94843407f4c5c7d71470464dcf36fe222882589b0e901c6658107229ec3d499f") + ); let reencoded = key.to_der().unwrap(); @@ -461,8 +456,14 @@ mod tests { let key = DsaPrivateKey::from_der(&dsa_der).unwrap(); - assert_eq!(key.params.q, hex_to_bn("94843407f4c5c7d71470464dcf36fe222882589b0e901c6658107229ec3d499f")); - assert_eq!(key.x, hex_to_bn("4F9E2260F06C2B742001EE5D618C8A5848A56A39BDF92EF903314298C8E33874")); + assert_eq!( + key.params.q, + hex_to_bn("94843407f4c5c7d71470464dcf36fe222882589b0e901c6658107229ec3d499f") + ); + assert_eq!( + key.x, + hex_to_bn("4F9E2260F06C2B742001EE5D618C8A5848A56A39BDF92EF903314298C8E33874") + ); let reencoded = key.to_der().unwrap(); @@ -481,7 +482,7 @@ mod tests { let pubkey = DsaPublicKey::from_components(params, y).unwrap(); let zero_sig = encode_dsa_signature(&Mpi::new(0).unwrap(), &Mpi::new(0).unwrap()).unwrap(); - let junk_message = vec![42; q_bits*8]; + let junk_message = vec![42; q_bits * 8]; assert!(pubkey.verify(&zero_sig, &junk_message).is_err()); @@ -521,7 +522,7 @@ mod tests { let mdt = MdType::Sha512; let mdinfo: MdInfo = match mdt.into() { Some(m) => m, - None => panic!() + None => panic!(), }; let bad_seed = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_nanos(); @@ -531,7 +532,8 @@ mod tests { let digest = hash_input(kat.0.as_bytes(), kat.1); let sig = privkey.sign_deterministic(kat.1, &digest, &mut rng).unwrap(); - // We keep the KAT in the RFC 6979 format for clarity, here we must re-encode to DER for comparison + // We keep the KAT in the RFC 6979 format for clarity, here we must re-encode to + // DER for comparison let kat_sig = hex::decode(kat.2).unwrap(); let half = kat_sig.len() / 2; @@ -581,7 +583,10 @@ mod tests { assert!(pubkey.verify(&encoded_sig, &hashed_message).is_ok()); - assert_eq!(privkey.sign_with_explicit_nonce(&hashed_message, k, &mut rng).unwrap(), encoded_sig); + assert_eq!( + privkey.sign_with_explicit_nonce(&hashed_message, k, &mut rng).unwrap(), + encoded_sig + ); // Additional tests done per KAT input: @@ -606,7 +611,7 @@ mod tests { let dsa_kats = include_str!("../../../tests/data/dsa.kat"); - let mut params : HashMap = HashMap::new(); + let mut params: HashMap = HashMap::new(); for line in dsa_kats.lines() { if line == "" || line.chars().nth(0) == Some('#') { diff --git a/mbedtls/src/pk/ec.rs b/mbedtls/src/pk/ec.rs index 79b843d0d..2cc8a0151 100644 --- a/mbedtls/src/pk/ec.rs +++ b/mbedtls/src/pk/ec.rs @@ -54,8 +54,8 @@ impl From for EcGroupId { } } -/// Maximum size of an elliptic curve signature generated by `sign`, and the minimum -/// buffer size input to `sign`. +/// Maximum size of an elliptic curve signature generated by `sign`, and the +/// minimum buffer size input to `sign`. pub const ECDSA_MAX_LEN: usize = MBEDTLS_ECDSA_MAX_LEN as usize; define!( @@ -92,11 +92,7 @@ impl Ecdh { Ok(ret) } - pub fn calc_secret( - &mut self, - shared: &mut [u8], - rng: &mut F, - ) -> Result { + pub fn calc_secret(&mut self, shared: &mut [u8], rng: &mut F) -> Result { let mut olen = 0; unsafe { ecdh_calc_secret( @@ -134,8 +130,8 @@ hXzA375dfGH6yIsRgRveMo6KDRK/AanSBLUj -----END PUBLIC KEY-----\0"; const DH_P192: &'static [u8] = &[ - 0x80, 0x3d, 0x8a, 0xb2, 0xe5, 0xb6, 0xe6, 0xfc, 0xa7, 0x15, 0x73, 0x7c, 0x3a, 0x82, - 0xf7, 0xce, 0x3c, 0x78, 0x31, 0x24, 0xf6, 0xd5, 0x1c, 0xd0, + 0x80, 0x3d, 0x8a, 0xb2, 0xe5, 0xb6, 0xe6, 0xfc, 0xa7, 0x15, 0x73, 0x7c, 0x3a, 0x82, 0xf7, 0xce, 0x3c, 0x78, 0x31, + 0x24, 0xf6, 0xd5, 0x1c, 0xd0, ]; let mut k_pr = Pk::from_private_key(PRIVATE_P192, None).unwrap(); diff --git a/mbedtls/src/pk/mod.rs b/mbedtls/src/pk/mod.rs index e91f63281..53fd08561 100644 --- a/mbedtls/src/pk/mod.rs +++ b/mbedtls/src/pk/mod.rs @@ -12,12 +12,12 @@ use mbedtls_sys::*; use mbedtls_sys::types::raw_types::c_void; -use core::ptr; -use core::convert::TryInto; use crate::error::{Error, IntoResult, Result}; +use crate::hash::Type as MdType; use crate::private::UnsafeFrom; use crate::rng::Random; -use crate::hash::Type as MdType; +use core::convert::TryInto; +use core::ptr; use byteorder::{BigEndian, ByteOrder}; @@ -137,7 +137,8 @@ const CUSTOM_PK_INFO: pk_info_t = { } }; -// If this changes then certificate.rs unsafe code in public_key needs to also change. +// If this changes then certificate.rs unsafe code in public_key needs to also +// change. define!( #[c_ty(pk_context)] #[repr(C)] @@ -155,80 +156,102 @@ define!( // A. Usage example of Pk. // // 1.1. Common use case is to to pass it as parameter to the SSL Config class. -// 1.2. SSL Config class is then used by multiple Context classes (one for each connection) -// 1.3. Context classes, handled by different threads will do calls towards Pk. +// 1.2. SSL Config class is then used by multiple Context classes (one for each +// connection) 1.3. Context classes, handled by different threads will do calls +// towards Pk. // -// Since this is a common use case for MbedTLS it should be thread safe if threading is enabled. +// Since this is a common use case for MbedTLS it should be thread safe if +// threading is enabled. // // B. Verifying thread safety. // -// 1. Calls towards the specific Pk implementation are done via function pointers. -// -// - Example call towards Pk: -// ../../../mbedtls-sys/vendor/library/ssl_srv.c:3707 - mbedtls_pk_decrypt( private_key, p, len, ... +// 1. Calls towards the specific Pk implementation are done via function +// pointers. +// +// - Example call towards Pk: ../../../mbedtls-sys/vendor/library/ssl_srv.c:3707 +// - mbedtls_pk_decrypt( private_key, p, len, ... // - This calls a generic function pointer via: -// ../../../mbedtls-sys/vendor/crypto/library/pk.c:475 - return( ctx->pk_info->decrypt_func( ctx->pk_ctx, input, ilen, +// ../../../mbedtls-sys/vendor/crypto/library/pk.c:475 - return( +// ctx->pk_info->decrypt_func( ctx->pk_ctx, input, ilen, // // 2. Pk implementation types. // // - The function pointers are defined via function: -// ../../../mbedtls-sys/vendor/crypto/library/pk.c:115 - mbedtls_pk_info_from_type -// - They are as follows: mbedtls_rsa_info / mbedtls_eckey_info / mbedtls_ecdsa_info -// - These are defined in: -// ../../../mbedtls-sys/vendor/crypto/library/pk_wrap.c:196 +// ../../../mbedtls-sys/vendor/crypto/library/pk.c:115 - +// mbedtls_pk_info_from_type +// - They are as follows: mbedtls_rsa_info / mbedtls_eckey_info / +// mbedtls_ecdsa_info +// - These are defined in: +// ../../../mbedtls-sys/vendor/crypto/library/pk_wrap.c:196 // // C. Checking types one by one. // -// 1. RSA: mbedtls_rsa_info at ../../../mbedtls-sys/vendor/crypto/library/pk_wrap.c:196 -// This uses internal locks in: ../../../mbedtls-sys/vendor/crypto/library/rsa.c:718 +// 1. RSA: mbedtls_rsa_info at +// ../../../mbedtls-sys/vendor/crypto/library/pk_wrap.c:196 +// This uses internal locks in: +// ../../../mbedtls-sys/vendor/crypto/library/rsa.c:718 // -// 2. ECKEY: mbedtls_eckey_info at ../../../mbedtls-sys/vendor/crypto/library/pk_wrap.c:418 +// 2. ECKEY: mbedtls_eckey_info at +// ../../../mbedtls-sys/vendor/crypto/library/pk_wrap.c:418 // This does not use internal locks but avoids interior mutability. // // Function checks one by one: -// - Only const access to context: eckey_check_pair, eckey_get_bitlen, eckey_can_do, eckey_check_pair +// - Only const access to context: eckey_check_pair, eckey_get_bitlen, +// eckey_can_do, eckey_check_pair // -// - Const acccess / copies context to a stack based variable -// eckey_verify_wrap, eckey_sign_wrap: ../../../mbedtls-sys/vendor/crypto/library/pk_wrap.c:251 -// creates a stack ecdsa variable and uses ctx to initialize it. -// ctx is passed as 'key', a const pointer to mbedtls_ecdsa_from_keypair( &ecdsa, ctx ) -// ../../../mbedtls-sys/vendor/crypto/library/ecdsa.c:819 -// int mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, const mbedtls_ecp_keypair *key ) -// key does not mutate. +// - Const acccess / copies context to a stack based variable eckey_verify_wrap, +// eckey_sign_wrap: ../../../mbedtls-sys/vendor/crypto/library/pk_wrap.c:251 +// creates a stack ecdsa variable and uses ctx to initialize it. ctx is passed +// as 'key', a const pointer to mbedtls_ecdsa_from_keypair( &ecdsa, ctx ) +// ../../../mbedtls-sys/vendor/crypto/library/ecdsa.c:819 int +// mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, const +// mbedtls_ecp_keypair *key ) key does not mutate. // // - Ignored due to not defined: eckey_verify_rs_wrap, eckey_sign_rs_wrap -// (Undefined - MBEDTLS_ECP_RESTARTABLE - ../../../mbedtls-sys/build/config.rs:173) +// (Undefined - MBEDTLS_ECP_RESTARTABLE - +// ../../../mbedtls-sys/build/config.rs:173) // -// - Only used when creating/freeing - which is safe by design - eckey_alloc_wrap / eckey_free_wrap +// - Only used when creating/freeing - which is safe by design - +// eckey_alloc_wrap / eckey_free_wrap // -// 3. ECDSA: mbedtls_ecdsa_info at ../../../mbedtls-sys/vendor/crypto/library/pk_wrap.c:729 +// 3. ECDSA: mbedtls_ecdsa_info at +// ../../../mbedtls-sys/vendor/crypto/library/pk_wrap.c:729 // This does not use internal locks but avoids interior mutability. // -// - Const access / copies context to stack based variables: -// ecdsa_verify_wrap: ../../../mbedtls-sys/vendor/crypto/library/pk_wrap.c:544 -// This copies the public key on the stack - in buf[] and copies the group id and nbits. -// That is done via: mbedtls_pk_write_pubkey( &p, buf, &key ) where key.pk_ctx = ctx; -// And the key is a const parameter to mbedtls_pk_write_pubkey - ../../../mbedtls-sys/vendor/crypto/library/pkwrite.c:158 +// - Const access / copies context to stack based variables: ecdsa_verify_wrap: +// ../../../mbedtls-sys/vendor/crypto/library/pk_wrap.c:544 This copies the +// public key on the stack - in buf[] and copies the group id and nbits. That +// is done via: mbedtls_pk_write_pubkey( &p, buf, &key ) where key.pk_ctx = +// ctx; And the key is a const parameter to mbedtls_pk_write_pubkey - +// ../../../mbedtls-sys/vendor/crypto/library/pkwrite.c:158 // // - Const access with additional notes due to call stacks involved. // // ecdsa_sign_wrap: ../../../mbedtls-sys/vendor/crypto/library/pk_wrap.c:657 -// mbedtls_ecdsa_write_signature ../../../mbedtls-sys/vendor/crypto/library/ecdsa.c:688 -// mbedtls_ecdsa_write_signature_restartable ../../../mbedtls-sys/vendor/crypto/library/ecdsa.c:640 -// MBEDTLS_ECDSA_DETERMINISTIC is not defined. -// MBEDTLS_ECDSA_SIGN_ALT is not defined. -// Passes grp to: ecdsa_sign_restartable: ../../../mbedtls-sys/vendor/crypto/library/ecdsa.c:253 -// Const access to group - reads parameters, passed as const to mbedtls_ecp_gen_privkey, -// mbedtls_ecp_mul_restartable: ../../../mbedtls-sys/vendor/crypto/library/ecp.c:2351 -// MBEDTLS_ECP_INTERNAL_ALT is not defined. (otherwise it might not be safe depending on ecp_init/ecp_free) ../../../mbedtls-sys/build/config.rs:131 -// Passes as const to: mbedtls_ecp_check_privkey / mbedtls_ecp_check_pubkey / mbedtls_ecp_get_type( grp -// -// - Ignored due to not defined: ecdsa_verify_rs_wrap, ecdsa_sign_rs_wrap, ecdsa_rs_alloc, ecdsa_rs_free -// (Undefined - MBEDTLS_ECP_RESTARTABLE - ../../../mbedtls-sys/build/config.rs:173) +// mbedtls_ecdsa_write_signature +// ../../../mbedtls-sys/vendor/crypto/library/ecdsa.c:688 +// mbedtls_ecdsa_write_signature_restartable +// ../../../mbedtls-sys/vendor/crypto/library/ecdsa.c:640 +// MBEDTLS_ECDSA_DETERMINISTIC is not defined. +// MBEDTLS_ECDSA_SIGN_ALT is not defined. Passes grp to: +// ecdsa_sign_restartable: +// ../../../mbedtls-sys/vendor/crypto/library/ecdsa.c:253 +// Const access to group - reads parameters, passed as const to +// mbedtls_ecp_gen_privkey, mbedtls_ecp_mul_restartable: +// ../../../mbedtls-sys/vendor/crypto/library/ecp.c:2351 +// MBEDTLS_ECP_INTERNAL_ALT is not defined. (otherwise it might not be safe +// depending on ecp_init/ecp_free) ../../../mbedtls-sys/build/config.rs:131 +// Passes as const to: mbedtls_ecp_check_privkey / +// mbedtls_ecp_check_pubkey / mbedtls_ecp_get_type( grp +// +// - Ignored due to not defined: ecdsa_verify_rs_wrap, ecdsa_sign_rs_wrap, +// ecdsa_rs_alloc, ecdsa_rs_free (Undefined - MBEDTLS_ECP_RESTARTABLE - +// ../../../mbedtls-sys/build/config.rs:173) // // - Only const access to context: eckey_check_pair // -// - Only used when creating/freeing - which is safe by design: ecdsa_alloc_wrap, ecdsa_free_wrap +// - Only used when creating/freeing - which is safe by design: +// ecdsa_alloc_wrap, ecdsa_free_wrap // unsafe impl Sync for Pk {} @@ -264,14 +287,7 @@ impl Pk { let mut ret = Self::init(); unsafe { pk_setup(&mut ret.inner, pk_info_from_type(Type::Rsa.into())).into_result()?; - rsa_gen_key( - ret.inner.pk_ctx as *mut _, - Some(F::call), - rng.data_ptr(), - bits, - exponent as _, - ) - .into_result()?; + rsa_gen_key(ret.inner.pk_ctx as *mut _, Some(F::call), rng.data_ptr(), bits, exponent as _).into_result()?; } Ok(ret) } @@ -279,18 +295,11 @@ impl Pk { pub fn generate_ec>>(rng: &mut F, curve: C) -> Result { let mut ret = Self::init(); unsafe { - let curve : EcGroup = curve.try_into().map_err(|e| e.into())?; + let curve: EcGroup = curve.try_into().map_err(|e| e.into())?; pk_setup(&mut ret.inner, pk_info_from_type(Type::Eckey.into())).into_result()?; let ctx = ret.inner.pk_ctx as *mut ecp_keypair; (*ctx).grp = curve.clone().into_inner(); - ecp_gen_keypair( - &mut (*ctx).grp, - &mut (*ctx).d, - &mut (*ctx).Q, - Some(F::call), - rng.data_ptr(), - ) - .into_result()?; + ecp_gen_keypair(&mut (*ctx).grp, &mut (*ctx).d, &mut (*ctx).Q, Some(F::call), rng.data_ptr()).into_result()?; } Ok(ret) } @@ -381,8 +390,7 @@ impl Pk { pub fn set_options(&mut self, options: Options) { unsafe { match (Type::from(pk_get_type(&self.inner)), options) { - (Type::Rsa, Options::Rsa { padding }) - | (Type::RsassaPss, Options::Rsa { padding }) => { + (Type::Rsa, Options::Rsa { padding }) | (Type::RsassaPss, Options::Rsa { padding }) => { let (padding, hash_id) = match padding { RsaPadding::Pkcs1V15 => (RSA_PKCS_V15, 0), RsaPadding::Pkcs1V21 { mgf } => (RSA_PKCS_V21, mgf.into()), @@ -408,9 +416,7 @@ impl Pk { } pub fn check_pair(public: &Self, private: &Self) -> bool { - unsafe { pk_check_pair(&public.inner, &private.inner) } - .into_result() - .is_ok() + unsafe { pk_check_pair(&public.inner, &private.inner) }.into_result().is_ok() } getter!( @@ -676,28 +682,17 @@ impl Pk { Ok(::core::str::from_utf8(s)?) } - pub fn decrypt( - &mut self, - cipher: &[u8], - plain: &mut [u8], - rng: &mut F, - ) -> Result { + pub fn decrypt(&mut self, cipher: &[u8], plain: &mut [u8], rng: &mut F) -> Result { if self.pk_type() == Type::Rsa { let ctx = self.inner.pk_ctx as *mut rsa_context; - if unsafe { (*ctx).padding == RAW_RSA_DECRYPT } { + if unsafe { (*ctx).padding == RAW_RSA_DECRYPT } { let olen = self.len() / 8; if plain.len() < olen { return Err(Error::RsaOutputTooLarge); } unsafe { - rsa_private( - ctx, - Some(F::call), - rng.data_ptr(), - cipher.as_ptr(), - plain.as_mut_ptr() - ).into_result()?; + rsa_private(ctx, Some(F::call), rng.data_ptr(), cipher.as_ptr(), plain.as_mut_ptr()).into_result()?; }; return Ok(olen); } @@ -714,14 +709,16 @@ impl Pk { plain.len(), Some(F::call), rng.data_ptr(), - ).into_result()?; + ) + .into_result()?; }; Ok(ret) } /// Decrypt using a custom label. /// - /// This function may only be called on an RSA key with its padding set to RSA_PKCS_V21. + /// This function may only be called on an RSA key with its padding set to + /// RSA_PKCS_V21. pub fn decrypt_with_label( &mut self, cipher: &[u8], @@ -750,17 +747,13 @@ impl Pk { cipher.as_ptr(), plain.as_mut_ptr(), plain.len(), - ).into_result()?; + ) + .into_result()?; } Ok(ret) } - pub fn encrypt( - &mut self, - plain: &[u8], - cipher: &mut [u8], - rng: &mut F, - ) -> Result { + pub fn encrypt(&mut self, plain: &[u8], cipher: &mut [u8], rng: &mut F) -> Result { let mut ret = 0usize; unsafe { pk_encrypt( @@ -772,14 +765,16 @@ impl Pk { cipher.len(), Some(F::call), rng.data_ptr(), - ).into_result()?; + ) + .into_result()?; }; Ok(ret) } /// Encrypt using a custom label. /// - /// This function may only be called on an RSA key with its padding set to RSA_PKCS_V21. + /// This function may only be called on an RSA key with its padding set to + /// RSA_PKCS_V21. pub fn encrypt_with_label( &mut self, plain: &[u8], @@ -809,32 +804,30 @@ impl Pk { label.len(), plain.len(), plain.as_ptr(), - cipher.as_mut_ptr() - ).into_result()?; + cipher.as_mut_ptr(), + ) + .into_result()?; } Ok(olen) } - /// Sign the hash `hash` of type `md`, placing the signature in `sig`. `rng` must be a - /// cryptographically secure RNG. + /// Sign the hash `hash` of type `md`, placing the signature in `sig`. `rng` + /// must be a cryptographically secure RNG. /// - /// For RSA signatures, the length of `sig` must be greater than or equal to the RSA - /// modulus length, otherwise `sign()` fails with `Error::PkSigLenMismatch`. + /// For RSA signatures, the length of `sig` must be greater than or equal to + /// the RSA modulus length, otherwise `sign()` fails with + /// `Error::PkSigLenMismatch`. /// - /// For EC signatures, the length of `sig` must be greater than or equal to `ECDSA_MAX_LEN`, - /// otherwise `sign()` fails with `Error::PkSigLenMismatch`. + /// For EC signatures, the length of `sig` must be greater than or equal to + /// `ECDSA_MAX_LEN`, otherwise `sign()` fails with + /// `Error::PkSigLenMismatch`. /// /// On success, returns the actual number of bytes written to `sig`. - pub fn sign( - &mut self, - md: MdType, - hash: &[u8], - sig: &mut [u8], - rng: &mut F, - ) -> Result { - // If hash or sig are allowed with size 0 (&[]) then mbedtls will attempt to auto-detect size and cause an invalid write. + pub fn sign(&mut self, md: MdType, hash: &[u8], sig: &mut [u8], rng: &mut F) -> Result { + // If hash or sig are allowed with size 0 (&[]) then mbedtls will attempt to + // auto-detect size and cause an invalid write. if hash.len() == 0 || sig.len() == 0 { - return Err(Error::PkBadInputData) + return Err(Error::PkBadInputData); } match self.pk_type() { @@ -861,21 +854,17 @@ impl Pk { &mut ret, Some(F::call), rng.data_ptr(), - ).into_result()?; + ) + .into_result()?; }; Ok(ret) } - pub fn sign_deterministic( - &mut self, - md: MdType, - hash: &[u8], - sig: &mut [u8], - rng: &mut F, - ) -> Result { - // If hash or sig are allowed with size 0 (&[]) then mbedtls will attempt to auto-detect size and cause an invalid write. + pub fn sign_deterministic(&mut self, md: MdType, hash: &[u8], sig: &mut [u8], rng: &mut F) -> Result { + // If hash or sig are allowed with size 0 (&[]) then mbedtls will attempt to + // auto-detect size and cause an invalid write. if hash.len() == 0 || sig.len() == 0 { - return Err(Error::PkBadInputData) + return Err(Error::PkBadInputData); } use crate::rng::RngCallbackMut; @@ -905,7 +894,8 @@ impl Pk { &mut ret, Some(Rfc6979Rng::call_mut), rng.data_ptr_mut(), - ).into_result()?; + ) + .into_result()?; }; Ok(ret) } else if self.pk_type() == Type::Rsa { @@ -914,7 +904,8 @@ impl Pk { return Err(Error::PkInvalidAlg); } - // This is a PKCSv1.5 signature which is already deterministic; just pass it to sign + // This is a PKCSv1.5 signature which is already deterministic; just pass it to + // sign return self.sign(md, hash, sig, rng); } else { // Some non-deterministic scheme @@ -923,32 +914,21 @@ impl Pk { } pub fn verify(&mut self, md: MdType, hash: &[u8], sig: &[u8]) -> Result<()> { - // If hash or sig are allowed with size 0 (&[]) then mbedtls will attempt to auto-detect size and cause an invalid write. + // If hash or sig are allowed with size 0 (&[]) then mbedtls will attempt to + // auto-detect size and cause an invalid write. if hash.len() == 0 || sig.len() == 0 { - return Err(Error::PkBadInputData) + return Err(Error::PkBadInputData); } - + unsafe { - pk_verify( - &mut self.inner, - md.into(), - hash.as_ptr(), - hash.len(), - sig.as_ptr(), - sig.len(), - ) - .into_result() - .map(|_| ()) + pk_verify(&mut self.inner, md.into(), hash.as_ptr(), hash.len(), sig.as_ptr(), sig.len()) + .into_result() + .map(|_| ()) } } /// Agree on a shared secret with another public key. - pub fn agree( - &mut self, - other: &Pk, - shared: &mut [u8], - rng: &mut F, - ) -> Result { + pub fn agree(&mut self, other: &Pk, shared: &mut [u8], rng: &mut F) -> Result { match (self.pk_type(), other.pk_type()) { (Type::Eckey, Type::Eckey) | (Type::EckeyDh, Type::Eckey) @@ -965,9 +945,7 @@ impl Pk { } pub fn write_private_der<'buf>(&mut self, buf: &'buf mut [u8]) -> Result> { - match unsafe { - pk_write_key_der(&mut self.inner, buf.as_mut_ptr(), buf.len()).into_result() - } { + match unsafe { pk_write_key_der(&mut self.inner, buf.as_mut_ptr(), buf.len()).into_result() } { Err(Error::Asn1BufTooSmall) => Ok(None), Err(e) => Err(e), Ok(n) => Ok(Some(&buf[buf.len() - (n as usize)..])), @@ -975,16 +953,11 @@ impl Pk { } pub fn write_private_der_vec(&mut self) -> Result> { - crate::private::alloc_vec_repeat( - |buf, size| unsafe { pk_write_key_der(&mut self.inner, buf, size) }, - true, - ) + crate::private::alloc_vec_repeat(|buf, size| unsafe { pk_write_key_der(&mut self.inner, buf, size) }, true) } pub fn write_private_pem<'buf>(&mut self, buf: &'buf mut [u8]) -> Result> { - match unsafe { - pk_write_key_pem(&mut self.inner, buf.as_mut_ptr(), buf.len()).into_result() - } { + match unsafe { pk_write_key_pem(&mut self.inner, buf.as_mut_ptr(), buf.len()).into_result() } { Err(Error::Base64BufferTooSmall) => Ok(None), Err(e) => Err(e), Ok(n) => Ok(Some(&buf[buf.len() - (n as usize)..])), @@ -1001,9 +974,7 @@ impl Pk { } pub fn write_public_der<'buf>(&mut self, buf: &'buf mut [u8]) -> Result> { - match unsafe { - pk_write_pubkey_der(&mut self.inner, buf.as_mut_ptr(), buf.len()).into_result() - } { + match unsafe { pk_write_pubkey_der(&mut self.inner, buf.as_mut_ptr(), buf.len()).into_result() } { Err(Error::Asn1BufTooSmall) => Ok(None), Err(e) => Err(e), Ok(n) => Ok(Some(&buf[buf.len() - (n as usize)..])), @@ -1011,16 +982,11 @@ impl Pk { } pub fn write_public_der_vec(&mut self) -> Result> { - crate::private::alloc_vec_repeat( - |buf, size| unsafe { pk_write_pubkey_der(&mut self.inner, buf, size) }, - true, - ) + crate::private::alloc_vec_repeat(|buf, size| unsafe { pk_write_pubkey_der(&mut self.inner, buf, size) }, true) } pub fn write_public_pem<'buf>(&mut self, buf: &'buf mut [u8]) -> Result> { - match unsafe { - pk_write_pubkey_pem(&mut self.inner, buf.as_mut_ptr(), buf.len()).into_result() - } { + match unsafe { pk_write_pubkey_pem(&mut self.inner, buf.as_mut_ptr(), buf.len()).into_result() } { Err(Error::Base64BufferTooSmall) => Ok(None), Err(e) => Err(e), Ok(n) => Ok(Some(&buf[buf.len() - (n as usize)..])), @@ -1055,7 +1021,7 @@ impl Pk { #[cfg(test)] mod tests { use super::*; - use crate::hash::{Type, MdInfo}; + use crate::hash::{MdInfo, Type}; use crate::pk::Type as PkType; // This is test data that must match library output *exactly* @@ -1089,92 +1055,71 @@ iy6KC991zzvaWY/Ys+q/84Afqa+0qJKQnPuy/7F5GkVdQA/lfbhi \0"; const TEST_DER: &'static [u8] = &[ - 0x30, 0x82, 0x04, 0xa3, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, 0x8d, 0x76, 0xa1, - 0x2e, 0xb6, 0xc0, 0xe5, 0x1e, 0x1a, 0x06, 0x74, 0x13, 0x57, 0x6a, 0xc2, 0x6c, 0x02, 0x9d, - 0x82, 0x91, 0x5b, 0xb0, 0xe5, 0xa9, 0x7f, 0xe0, 0x6d, 0x3f, 0xc0, 0x94, 0x88, 0x8e, 0x72, - 0xd4, 0x4a, 0xc1, 0xf5, 0x54, 0x71, 0x63, 0x10, 0xaa, 0xef, 0x9d, 0xa5, 0x1a, 0xdc, 0x00, - 0x82, 0x2d, 0xea, 0x5f, 0x5b, 0xe8, 0x73, 0x6e, 0x03, 0xf8, 0x07, 0x90, 0x8c, 0xd5, 0x52, - 0xf5, 0x6d, 0xfc, 0x4d, 0xe5, 0x6a, 0x87, 0x5a, 0x85, 0xf7, 0x34, 0x85, 0x9a, 0x19, 0x3a, - 0x74, 0x46, 0x1e, 0xcb, 0x30, 0x77, 0x8d, 0x68, 0x8a, 0xb8, 0xfd, 0x6e, 0xbc, 0xee, 0xd2, - 0xd0, 0xb3, 0xd0, 0x1c, 0x44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6, 0x19, 0x38, 0xb4, 0x87, 0x46, 0x72, 0xb8, 0x0d, 0xeb, 0x77, 0x41, 0xde, 0xe4, 0xbb, - 0x34, 0xef, 0x87, 0x02, 0x98, 0xdc, 0x78, 0xa8, 0x84, 0xae, 0x9d, 0x3c, 0x5d, 0xbb, 0xa3, - 0x3c, 0x35, 0x8a, 0xe3, 0x62, 0x1f, 0x25, 0x95, 0x20, 0x99, 0x02, 0x81, 0x80, 0x5b, 0xfb, - 0x99, 0x65, 0xaa, 0x0d, 0x55, 0xf5, 0x66, 0x27, 0x95, 0xc8, 0xb2, 0x68, 0x7f, 0x8b, 0xd3, - 0x26, 0xd1, 0x51, 0x68, 0xe3, 0x5f, 0x84, 0x1b, 0x13, 0xbf, 0xec, 0xb4, 0x92, 0x09, 0xa8, - 0x0c, 0xac, 0x5f, 0x99, 0x3a, 0xd5, 0xda, 0xdd, 0xee, 0xba, 0x1c, 0xce, 0x92, 0x7c, 0x54, - 0xd4, 0xf8, 0x6a, 0xc3, 0xb3, 0x07, 0xea, 0xce, 0x18, 0xad, 0x8e, 0x26, 0x5e, 0x54, 0xa1, - 0x87, 0x77, 0x6a, 0x7b, 0x23, 0x2e, 0x76, 0xb6, 0x3a, 0xe7, 0xd9, 0x67, 0x0d, 0x7e, 0x19, - 0xd9, 0x6e, 0x2c, 0xe0, 0x00, 0xd6, 0x8e, 0xd2, 0x5a, 0xc9, 0x59, 0x44, 0x58, 0xd8, 0x73, - 0x15, 0x0f, 0x17, 0x63, 0x3e, 0xef, 0x74, 0x2f, 0xfe, 0xbd, 0x50, 0x07, 0x5f, 0x7d, 0x15, - 0x23, 0xab, 0xc2, 0x77, 0x6d, 0xc9, 0x3d, 0x08, 0x1a, 0x88, 0xdd, 0x45, 0x26, 0xd9, 0x2d, - 0xe9, 0xde, 0xb9, 0x58, 0x36, 0x5f, + 0x30, 0x82, 0x04, 0xa3, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, 0x8d, 0x76, 0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4, 0xf8, 0x6a, 0xc3, 0xb3, 0x07, 0xea, 0xce, 0x18, 0xad, + 0x8e, 0x26, 0x5e, 0x54, 0xa1, 0x87, 0x77, 0x6a, 0x7b, 0x23, 0x2e, 0x76, 0xb6, 0x3a, 0xe7, 0xd9, 0x67, 0x0d, 0x7e, 0x19, + 0xd9, 0x6e, 0x2c, 0xe0, 0x00, 0xd6, 0x8e, 0xd2, 0x5a, 0xc9, 0x59, 0x44, 0x58, 0xd8, 0x73, 0x15, 0x0f, 0x17, 0x63, 0x3e, + 0xef, 0x74, 0x2f, 0xfe, 0xbd, 0x50, 0x07, 0x5f, 0x7d, 0x15, 0x23, 0xab, 0xc2, 0x77, 0x6d, 0xc9, 0x3d, 0x08, 0x1a, 0x88, + 0xdd, 0x45, 0x26, 0xd9, 0x2d, 0xe9, 0xde, 0xb9, 0x58, 0x36, 0x5f, ]; #[test] fn generate_rsa() { - let mut pk = - Pk::generate_rsa(&mut crate::test_support::rand::test_rng(), 2048, 0x10001).unwrap(); + let mut pk = Pk::generate_rsa(&mut crate::test_support::rand::test_rng(), 2048, 0x10001).unwrap(); let generated = pk.write_private_pem_string().unwrap(); assert_eq!(0x10001, pk.rsa_public_exponent().unwrap()); assert_eq!(generated, TEST_PEM[..TEST_PEM.len() - 1]); @@ -1182,43 +1127,36 @@ iy6KC991zzvaWY/Ys+q/84Afqa+0qJKQnPuy/7F5GkVdQA/lfbhi #[test] fn generate_ec_curve25519() { - let _generated = - Pk::generate_ec(&mut crate::test_support::rand::test_rng(), EcGroupId::Curve25519).unwrap(); + let _generated = Pk::generate_ec(&mut crate::test_support::rand::test_rng(), EcGroupId::Curve25519).unwrap(); // mbedtls does not have an OID for Curve25519, so can't write it as PEM } #[test] fn generate_ec_secp192r1() { - let _generated = - Pk::generate_ec(&mut crate::test_support::rand::test_rng(), EcGroupId::SecP192R1) - .unwrap() - .write_private_pem_string() - .unwrap(); + let _generated = Pk::generate_ec(&mut crate::test_support::rand::test_rng(), EcGroupId::SecP192R1) + .unwrap() + .write_private_pem_string() + .unwrap(); } #[test] fn generate_ec_secp256r1() { - let mut key1 = - Pk::generate_ec(&mut crate::test_support::rand::test_rng(), EcGroupId::SecP256R1).unwrap(); + let mut key1 = Pk::generate_ec(&mut crate::test_support::rand::test_rng(), EcGroupId::SecP256R1).unwrap(); let pem1 = key1.write_private_pem_string().unwrap(); let secp256r1 = EcGroup::new(EcGroupId::SecP256R1).unwrap(); - let mut key2 = - Pk::generate_ec(&mut crate::test_support::rand::test_rng(), secp256r1.clone()) - .unwrap(); + let mut key2 = Pk::generate_ec(&mut crate::test_support::rand::test_rng(), secp256r1.clone()).unwrap(); let pem2 = key2.write_private_pem_string().unwrap(); assert_eq!(pem1, pem2); - let mut key_from_components = - Pk::private_from_ec_components(secp256r1.clone(), key1.ec_private().unwrap()).unwrap(); + let mut key_from_components = Pk::private_from_ec_components(secp256r1.clone(), key1.ec_private().unwrap()).unwrap(); let pem3 = key_from_components.write_private_pem_string().unwrap(); assert_eq!(pem3, pem2); let mut pub1 = Pk::from_public_key(&key1.write_public_der_vec().unwrap()).unwrap(); - let mut pub2 = - Pk::public_from_ec_components(secp256r1.clone(), key1.ec_public().unwrap()).unwrap(); + let mut pub2 = Pk::public_from_ec_components(secp256r1.clone(), key1.ec_public().unwrap()).unwrap(); assert_eq!( pub1.write_public_pem_string().unwrap(), @@ -1228,11 +1166,10 @@ iy6KC991zzvaWY/Ys+q/84Afqa+0qJKQnPuy/7F5GkVdQA/lfbhi #[test] fn generate_ec_secp256k1() { - let _generated = - Pk::generate_ec(&mut crate::test_support::rand::test_rng(), EcGroupId::SecP256K1) - .unwrap() - .write_private_pem_string() - .unwrap(); + let _generated = Pk::generate_ec(&mut crate::test_support::rand::test_rng(), EcGroupId::SecP256K1) + .unwrap() + .write_private_pem_string() + .unwrap(); } #[test] @@ -1246,17 +1183,13 @@ iy6KC991zzvaWY/Ys+q/84Afqa+0qJKQnPuy/7F5GkVdQA/lfbhi #[test] fn parse_write_der() { - let parsed = Pk::from_private_key(TEST_DER, None) - .unwrap() - .write_private_der_vec() - .unwrap(); + let parsed = Pk::from_private_key(TEST_DER, None).unwrap().write_private_der_vec().unwrap(); assert!(parsed == TEST_DER); } #[test] fn rsa_sign_verify_pkcs1v15() { - let mut pk = - Pk::generate_rsa(&mut crate::test_support::rand::test_rng(), 2048, 0x10001).unwrap(); + let mut pk = Pk::generate_rsa(&mut crate::test_support::rand::test_rng(), 2048, 0x10001).unwrap(); let data = b"SIGNATURE TEST SIGNATURE TEST SIGNATURE TEST SIGNATURE TEST SIGN"; let mut signature = vec![0u8; (pk.len() + 7) / 8]; @@ -1281,33 +1214,41 @@ iy6KC991zzvaWY/Ys+q/84Afqa+0qJKQnPuy/7F5GkVdQA/lfbhi }; let len = pk - .sign( - digest, - data, - &mut signature, - &mut crate::test_support::rand::test_rng(), - ) + .sign(digest, data, &mut signature, &mut crate::test_support::rand::test_rng()) .unwrap(); pk.verify(digest, data, &signature[0..len]).unwrap(); assert_eq!(pk.verify(digest, data, &[]).unwrap_err(), Error::PkBadInputData); assert_eq!(pk.verify(digest, &[], &signature[0..len]).unwrap_err(), Error::PkBadInputData); - let mut dummy_sig = []; - assert_eq!(pk.sign(digest, data, &mut dummy_sig, &mut crate::test_support::rand::test_rng()).unwrap_err(), Error::PkBadInputData); - assert_eq!(pk.sign(digest, &[], &mut signature, &mut crate::test_support::rand::test_rng()).unwrap_err(), Error::PkBadInputData); - - assert_eq!(pk.sign_deterministic(digest, data, &mut dummy_sig, &mut crate::test_support::rand::test_rng()).unwrap_err(), Error::PkBadInputData); - assert_eq!(pk.sign_deterministic(digest, &[], &mut signature, &mut crate::test_support::rand::test_rng()).unwrap_err(), Error::PkBadInputData); - + assert_eq!( + pk.sign(digest, data, &mut dummy_sig, &mut crate::test_support::rand::test_rng()) + .unwrap_err(), + Error::PkBadInputData + ); + assert_eq!( + pk.sign(digest, &[], &mut signature, &mut crate::test_support::rand::test_rng()) + .unwrap_err(), + Error::PkBadInputData + ); + + assert_eq!( + pk.sign_deterministic(digest, data, &mut dummy_sig, &mut crate::test_support::rand::test_rng()) + .unwrap_err(), + Error::PkBadInputData + ); + assert_eq!( + pk.sign_deterministic(digest, &[], &mut signature, &mut crate::test_support::rand::test_rng()) + .unwrap_err(), + Error::PkBadInputData + ); } } #[test] fn rsa_sign_verify_pss() { - let mut pk = - Pk::generate_rsa(&mut crate::test_support::rand::test_rng(), 2048, 0x10001).unwrap(); + let mut pk = Pk::generate_rsa(&mut crate::test_support::rand::test_rng(), 2048, 0x10001).unwrap(); let data = b"SIGNATURE TEST SIGNATURE TEST SIGNATURE TEST SIGNATURE TEST SIGN"; let mut signature = vec![0u8; (pk.len() + 7) / 8]; @@ -1337,21 +1278,11 @@ iy6KC991zzvaWY/Ys+q/84Afqa+0qJKQnPuy/7F5GkVdQA/lfbhi if digest == Type::None { assert!(pk - .sign( - digest, - data, - &mut signature, - &mut crate::test_support::rand::test_rng() - ) + .sign(digest, data, &mut signature, &mut crate::test_support::rand::test_rng()) .is_err()); } else { let len = pk - .sign( - digest, - data, - &mut signature, - &mut crate::test_support::rand::test_rng(), - ) + .sign(digest, data, &mut signature, &mut crate::test_support::rand::test_rng()) .unwrap(); pk.verify(digest, data, &signature[0..len]).unwrap(); } @@ -1369,9 +1300,7 @@ iy6KC991zzvaWY/Ys+q/84Afqa+0qJKQnPuy/7F5GkVdQA/lfbhi cipher1.len() ); pk.set_options(Options::Rsa { - padding: RsaPadding::Pkcs1V21 { - mgf: Type::Sha256, - }, + padding: RsaPadding::Pkcs1V21 { mgf: Type::Sha256 }, }); assert_eq!( pk.encrypt(b"test", &mut cipher2, &mut crate::test_support::rand::test_rng()) @@ -1387,18 +1316,14 @@ iy6KC991zzvaWY/Ys+q/84Afqa+0qJKQnPuy/7F5GkVdQA/lfbhi let mut cipher = [0u8; 2048 / 8]; let mut rng = crate::test_support::rand::test_rng(); pk.set_options(Options::Rsa { - padding: RsaPadding::Pkcs1V15 + padding: RsaPadding::Pkcs1V15, }); - assert_eq!( - pk.encrypt(b"test", &mut cipher, &mut rng) - .unwrap(), - cipher.len() - ); + assert_eq!(pk.encrypt(b"test", &mut cipher, &mut rng).unwrap(), cipher.len()); let mut decrypted_data1 = [0u8; 2048 / 8]; let length_with_padding = pk.decrypt(&cipher, &mut decrypted_data1, &mut rng).unwrap(); // set raw decryption padding mode to perform raw decryption pk.set_options(Options::Rsa { - padding: RsaPadding::None + padding: RsaPadding::None, }); let mut decrypted_data2 = [0u8; 2048 / 8]; let length_without_padding = pk.decrypt(&cipher, &mut decrypted_data2, &mut rng).unwrap(); @@ -1414,7 +1339,7 @@ iy6KC991zzvaWY/Ys+q/84Afqa+0qJKQnPuy/7F5GkVdQA/lfbhi let mut cipher = [0u8; 2048 / 8]; // set raw decryption padding mode pk.set_options(Options::Rsa { - padding: RsaPadding::None + padding: RsaPadding::None, }); assert_eq!( pk.encrypt(b"test", &mut cipher, &mut crate::test_support::rand::test_rng()) @@ -1429,32 +1354,42 @@ iy6KC991zzvaWY/Ys+q/84Afqa+0qJKQnPuy/7F5GkVdQA/lfbhi let mut cipher = [0u8; 2048 / 8]; // set raw decryption padding mode pk.set_options(Options::Rsa { - padding: RsaPadding::Pkcs1V21 { mgf: MdType::Sha256 } + padding: RsaPadding::Pkcs1V21 { mgf: MdType::Sha256 }, }); let plain = b"testing123"; - let cipher_len = pk.encrypt_with_label(plain, &mut cipher, - &mut crate::test_support::rand::test_rng(), - b"MY_LABEL").unwrap(); + let cipher_len = pk + .encrypt_with_label(plain, &mut cipher, &mut crate::test_support::rand::test_rng(), b"MY_LABEL") + .unwrap(); assert_eq!(cipher_len, cipher.len()); let mut plain_decrypted = [0u8; 10]; - let plain_len = pk.decrypt_with_label(&cipher, &mut plain_decrypted, - &mut crate::test_support::rand::test_rng(), - b"MY_LABEL").unwrap(); + let plain_len = pk + .decrypt_with_label( + &cipher, + &mut plain_decrypted, + &mut crate::test_support::rand::test_rng(), + b"MY_LABEL", + ) + .unwrap(); assert_eq!(plain_len, plain.len()); assert_eq!(&plain_decrypted, plain); - assert_eq!(pk.decrypt_with_label(&cipher, &mut plain_decrypted, - &mut crate::test_support::rand::test_rng(), - b"WRONG_LABEL").unwrap_err(), - Error::RsaInvalidPadding); + assert_eq!( + pk.decrypt_with_label( + &cipher, + &mut plain_decrypted, + &mut crate::test_support::rand::test_rng(), + b"WRONG_LABEL" + ) + .unwrap_err(), + Error::RsaInvalidPadding + ); } #[test] fn rsa_sign_with_none_padding() { - let mut pk = - Pk::generate_rsa(&mut crate::test_support::rand::test_rng(), 2048, 0x10001).unwrap(); + let mut pk = Pk::generate_rsa(&mut crate::test_support::rand::test_rng(), 2048, 0x10001).unwrap(); let data = b"SIGNATURE TEST SIGNATURE TEST SI"; let mut signature = vec![0u8; (pk.len() + 7) / 8]; // set raw decryption padding mode @@ -1470,8 +1405,7 @@ iy6KC991zzvaWY/Ys+q/84Afqa+0qJKQnPuy/7F5GkVdQA/lfbhi #[test] fn rsa_verify_with_none_padding() { - let mut pk = - Pk::generate_rsa(&mut crate::test_support::rand::test_rng(), 2048, 0x10001).unwrap(); + let mut pk = Pk::generate_rsa(&mut crate::test_support::rand::test_rng(), 2048, 0x10001).unwrap(); let data = b"SIGNATURE TEST SIGNATURE TEST SI"; let mut signature = vec![0u8; (pk.len() + 7) / 8]; @@ -1479,15 +1413,15 @@ iy6KC991zzvaWY/Ys+q/84Afqa+0qJKQnPuy/7F5GkVdQA/lfbhi pk.set_options(Options::Rsa { padding: RsaPadding::Pkcs1V21 { mgf: digest }, }); - let len = pk.sign(digest, data, &mut signature, &mut crate::test_support::rand::test_rng()) + let len = pk + .sign(digest, data, &mut signature, &mut crate::test_support::rand::test_rng()) .unwrap(); // set raw decryption padding mode pk.set_options(Options::Rsa { padding: RsaPadding::None, }); assert_eq!( - pk.verify(digest, data, &signature[0..len]) - .unwrap_err(), + pk.verify(digest, data, &signature[0..len]).unwrap_err(), Error::RsaInvalidPadding ); } @@ -1536,5 +1470,4 @@ iy6KC991zzvaWY/Ys+q/84Afqa+0qJKQnPuy/7F5GkVdQA/lfbhi assert!(pk.custom_public_key().is_err()); assert!(pk.custom_private_key().is_err()); } - } diff --git a/mbedtls/src/pk/rfc6979.rs b/mbedtls/src/pk/rfc6979.rs index 01624d60b..d18b41bda 100644 --- a/mbedtls/src/pk/rfc6979.rs +++ b/mbedtls/src/pk/rfc6979.rs @@ -14,8 +14,8 @@ use mbedtls_sys::types::size_t; use crate::rng::{HmacDrbg, Random, RngCallbackMut}; -use crate::error::Result; use crate::bignum::Mpi; +use crate::error::Result; use crate::hash::{MdInfo, Type}; pub(crate) fn generate_rfc6979_nonce(md: &MdInfo, x: &Mpi, q: &Mpi, digest_bytes: &[u8]) -> Result> { @@ -72,13 +72,7 @@ pub(crate) struct Rfc6979Rng { /// An RNG which first outputs the k for RFC 6797 followed by random data impl Rfc6979Rng { - pub fn new( - md_type: Type, - q: &Mpi, - x: &Mpi, - digest_bytes: &[u8], - random_seed: &[u8], - ) -> Result { + pub fn new(md_type: Type, q: &Mpi, x: &Mpi, digest_bytes: &[u8], random_seed: &[u8]) -> Result { let md: MdInfo = match md_type.into() { Some(md) => md, None => panic!("no such digest"), @@ -111,11 +105,7 @@ impl Rfc6979Rng { } impl RngCallbackMut for Rfc6979Rng { - unsafe extern "C" fn call_mut( - user_data: *mut c_void, - data_ptr: *mut c_uchar, - len: size_t, - ) -> c_int { + unsafe extern "C" fn call_mut(user_data: *mut c_void, data_ptr: *mut c_uchar, len: size_t) -> c_int { let rng: &mut Rfc6979Rng = (user_data as *mut Rfc6979Rng).as_mut().unwrap(); let slice = ::core::slice::from_raw_parts_mut(data_ptr, len); let result = rng.random_callback(slice); diff --git a/mbedtls/src/pkcs12/mod.rs b/mbedtls/src/pkcs12/mod.rs index 4f572ed33..a9dc9ba93 100644 --- a/mbedtls/src/pkcs12/mod.rs +++ b/mbedtls/src/pkcs12/mod.rs @@ -29,12 +29,12 @@ use yasna::tags::*; pub use yasna::{ASN1Error, ASN1ErrorKind}; use yasna::{ASN1Result, BERDecodable, BERReader, BERReaderSeq, Tag}; +use crate::alloc::Box as MbedtlsBox; use crate::cipher::raw::{CipherId, CipherMode}; use crate::cipher::{Cipher, Decryption, Fresh, Traditional}; use crate::hash::{pbkdf_pkcs12, Hmac, MdInfo, Type as MdType}; use crate::pk::Pk; use crate::x509::Certificate; -use crate::alloc::{Box as MbedtlsBox}; use crate::Error as MbedtlsError; // Constants for various object identifiers used in PKCS12: @@ -86,8 +86,7 @@ fn read_string_type(der: &[u8]) -> ASN1Result { // IA5 is (roughly speaking) equivalent to ASCII reader.read_tagged_implicit(TAG_IA5STRING, |reader| { let bytes = reader.read_bytes()?; - Ok(String::from_utf8(bytes) - .map_err(|_| ASN1Error::new(ASN1ErrorKind::Invalid))?) + Ok(String::from_utf8(bytes).map_err(|_| ASN1Error::new(ASN1ErrorKind::Invalid))?) }) } @@ -97,10 +96,7 @@ fn read_string_type(der: &[u8]) -> ASN1Result { return Err(ASN1Error::new(ASN1ErrorKind::Invalid)); } - let utf16 = bytes - .chunks(2) - .map(|c| (c[0] as u16) * 256 + c[1] as u16) - .collect::>(); + let utf16 = bytes.chunks(2).map(|c| (c[0] as u16) * 256 + c[1] as u16).collect::>(); Ok(String::from_utf16_lossy(&utf16)) }), @@ -290,9 +286,7 @@ impl BERDecodable for ContentInfo { fn decode_ber(reader: BERReader) -> ASN1Result { reader.read_sequence(|reader| { let oid = reader.next().read_oid()?; - let contents = reader - .next() - .read_tagged(Tag::context(0), |reader| reader.read_bytes())?; + let contents = reader.next().read_tagged(Tag::context(0), |reader| reader.read_bytes())?; let contents = read_seq_of::(&contents)?; Ok(ContentInfo { oid, contents }) }) @@ -310,9 +304,7 @@ impl BERDecodable for AuthenticatedSafe { fn decode_ber(reader: BERReader) -> ASN1Result { let r = reader.read_sequence(|reader| { let oid = reader.next().read_oid()?; - let blob = reader - .next() - .read_tagged(Tag::context(0), |reader| reader.read_der())?; + let blob = reader.next().read_tagged(Tag::context(0), |reader| reader.read_der())?; Ok((oid, blob)) })?; @@ -342,10 +334,7 @@ impl BERDecodable for EncryptedData { reader.read_sequence(|reader| { let version = reader.next().read_u32()?; let content_info = read_struct::(reader)?; - Ok(EncryptedData { - version, - content_info, - }) + Ok(EncryptedData { version, content_info }) }) } } @@ -387,13 +376,8 @@ impl BERDecodable for CertTypes { fn decode_ber(reader: BERReader) -> ASN1Result { reader.read_sequence(|reader| { let cert_type = reader.next().read_oid()?; - let cert_blob = reader - .next() - .read_tagged(Tag::context(0), |reader| reader.read_bytes())?; - Ok(CertTypes { - cert_type, - cert_blob, - }) + let cert_blob = reader.next().read_tagged(Tag::context(0), |reader| reader.read_bytes())?; + Ok(CertTypes { cert_type, cert_blob }) }) } } @@ -483,9 +467,7 @@ impl BERDecodable for SafeBag { fn decode_ber(reader: BERReader) -> ASN1Result { reader.read_sequence(|reader| { let bag_id = reader.next().read_oid()?; - let bag_blob = reader - .next() - .read_tagged(Tag::context(0), |reader| reader.read_der())?; + let bag_blob = reader.next().read_tagged(Tag::context(0), |reader| reader.read_der())?; let mut bag_attributes = Vec::new(); if let Ok(attr) = reader.next().read_der() { @@ -551,21 +533,13 @@ fn format_passphrase_for_pkcs12(passphrase: &str) -> Vec { fn decrypt_contents(data: &EncryptedData, passphrase: &[u8]) -> Pkcs12Result { if data.version != 0 { - return Err(Pkcs12Error::Custom(format!( - "Unknown EncryptedData version {}", - data.version - ))); + return Err(Pkcs12Error::Custom(format!("Unknown EncryptedData version {}", data.version))); } let encryption_algo = &data.content_info.encryption_algo.algo; let pbe_params: Pkcs12PbeParams = yasna::decode_der(&data.content_info.encryption_algo.params)?; - let pt = decrypt_data( - &data.content_info.encrypted_content, - &pbe_params, - encryption_algo, - passphrase, - )?; + let pt = decrypt_data(&data.content_info.encrypted_content, &pbe_params, encryption_algo, passphrase)?; let sc = read_struct_from_bytes::(&pt)?; return Ok(sc); @@ -578,8 +552,7 @@ fn decrypt_pkcs8(pkcs8: &[u8], passphrase: &[u8]) -> Pkcs12Result> { let pbe_params = read_struct_from_bytes::(&alg_id.params)?; let enc_p8 = reader.next().read_bytes()?; - decrypt_data(&enc_p8, &pbe_params, &alg_id.algo, passphrase) - .map_err(|_| ASN1Error::new(ASN1ErrorKind::Invalid)) + decrypt_data(&enc_p8, &pbe_params, &alg_id.algo, passphrase).map_err(|_| ASN1Error::new(ASN1ErrorKind::Invalid)) }) })?; @@ -587,11 +560,7 @@ fn decrypt_pkcs8(pkcs8: &[u8], passphrase: &[u8]) -> Pkcs12Result> { } fn decrypt_3des(ciphertext: &[u8], key: &[u8], iv: &[u8]) -> Pkcs12Result> { - let cipher = Cipher::::new( - CipherId::Des3, - CipherMode::CBC, - (key.len() * 8) as u32, - )?; + let cipher = Cipher::::new(CipherId::Des3, CipherMode::CBC, (key.len() * 8) as u32)?; let cipher = cipher.set_key_iv(&key, &iv)?; let mut plaintext = vec![0; ciphertext.len() + 8]; let len = cipher.decrypt(&ciphertext, &mut plaintext)?; @@ -603,9 +572,7 @@ fn decrypt_3des(ciphertext: &[u8], key: &[u8], iv: &[u8]) -> Pkcs12Result Pkcs12Result> { use rc2::cipher::{block_padding::Pkcs7, BlockDecryptMut, KeyIvInit}; - let cipher = - cbc::Decryptor::::new_from_slices(key, iv) - .map_err(|e| Pkcs12Error::Custom(format!("{:?}", e)))?; + let cipher = cbc::Decryptor::::new_from_slices(key, iv).map_err(|e| Pkcs12Error::Custom(format!("{:?}", e)))?; let mut pt = ciphertext.to_vec(); let pt = cipher @@ -616,9 +583,7 @@ fn decrypt_rc2(ciphertext: &[u8], key: &[u8], iv: &[u8]) -> Pkcs12Result #[cfg(not(feature = "pkcs12_rc2"))] fn decrypt_rc2(_ciphertext: &[u8], _key: &[u8], _iv: &[u8]) -> Pkcs12Result> { - return Err(Pkcs12Error::Custom( - "RC2 not supported in this build".to_owned(), - )); + return Err(Pkcs12Error::Custom("RC2 not supported in this build".to_owned())); } #[derive(Debug, Clone, Copy)] @@ -651,10 +616,7 @@ fn decrypt_data( PKCS12_PBE_SHA_3DES_112 => Ok(Pkcs12EncryptionAlgo::TDES_112_SHA), PKCS12_PBE_SHA_RC2_128 => Ok(Pkcs12EncryptionAlgo::RC2_128_SHA), PKCS12_PBE_SHA_RC2_40 => Ok(Pkcs12EncryptionAlgo::RC2_40_SHA), - _ => Err(Pkcs12Error::Custom(format!( - "Unknown encryption algo {}", - oid - ))), + _ => Err(Pkcs12Error::Custom(format!("Unknown encryption algo {}", oid))), } } @@ -708,10 +670,7 @@ impl Pfx { let pfx: Pfx = yasna::decode_der(data)?; if pfx.version != 3 { - return Err(Pkcs12Error::Custom(format!( - "Unknown PKCS12 version {}", - pfx.version - ))); + return Err(Pkcs12Error::Custom(format!("Unknown PKCS12 version {}", pfx.version))); } Ok(pfx) @@ -785,10 +744,7 @@ impl Pfx { } } - fn decrypt_data( - data: &AuthenticatedSafe, - passphrase: &[u8], - ) -> Pkcs12Result { + fn decrypt_data(data: &AuthenticatedSafe, passphrase: &[u8]) -> Pkcs12Result { match data { &AuthenticatedSafe::Data(ref sc) => { let mut contents = Vec::new(); @@ -825,33 +781,45 @@ impl Pfx { Ok(decrypted) } - fn authsafe_decrypted_contents(&self) -> impl Iterator { - self.authsafe.contents.iter() - .flat_map(|d| if let AuthenticatedSafe::Data(ref d) = d { d.0.as_slice() } else { &[] }) + fn authsafe_decrypted_contents(&self) -> impl Iterator { + self.authsafe.contents.iter().flat_map(|d| { + if let AuthenticatedSafe::Data(ref d) = d { + d.0.as_slice() + } else { + &[] + } + }) } - /// Return the certificates stored in this Pfx along with a possibly empty list - /// of "friendly names" which are associated with said certificate. - /// Some or all of the certificates stored in a Pfx may be encrypted in which case - /// decrypt must be called to access them. - pub fn certificates<'a>(&'a self) -> impl Iterator, crate::Error>, Vec)> + 'a { - self.authsafe_decrypted_contents() - .filter_map(|sb| if let Pkcs12BagSet::Cert(CertBag(Some(cert))) = &sb.bag_value { + /// Return the certificates stored in this Pfx along with a possibly empty + /// list of "friendly names" which are associated with said certificate. + /// Some or all of the certificates stored in a Pfx may be encrypted in + /// which case decrypt must be called to access them. + pub fn certificates<'a>( + &'a self, + ) -> impl Iterator, crate::Error>, Vec)> + 'a { + self.authsafe_decrypted_contents().filter_map(|sb| { + if let Pkcs12BagSet::Cert(CertBag(Some(cert))) = &sb.bag_value { Some((Certificate::from_der(cert), sb.friendly_name())) - } else { None }) + } else { + None + } + }) } - /// Return the private keys stored in this Pfx along with a possibly empty list - /// of "friendly names" which are associated with said private key. - pub fn private_keys<'a>(&'a self) -> impl Iterator, Vec)> + 'a { - self.authsafe_decrypted_contents() - .filter_map(|sb| - match &sb.bag_value { - Pkcs12BagSet::Pkcs8(pkcs8) | Pkcs12BagSet::Key(KeyBag { pkcs8 }) => - Some((Pk::from_private_key(pkcs8, None), sb.friendly_name())), - _ => /* not a private key */ None - } - ) + /// Return the private keys stored in this Pfx along with a possibly empty + /// list of "friendly names" which are associated with said private key. + pub fn private_keys<'a>(&'a self) -> impl Iterator, Vec)> + 'a { + self.authsafe_decrypted_contents().filter_map(|sb| match &sb.bag_value { + Pkcs12BagSet::Pkcs8(pkcs8) | Pkcs12BagSet::Key(KeyBag { pkcs8 }) => { + Some((Pk::from_private_key(pkcs8, None), sb.friendly_name())) + } + _ => + /* not a private key */ + { + None + } + }) } } @@ -874,9 +842,7 @@ impl BERDecodable for Pfx { let raw_data = yasna::parse_der(&raw_safe, |reader| { reader.read_sequence(|reader| { let _oid = reader.next().read_oid()?; - let contents = reader - .next() - .read_tagged(Tag::context(0), |reader| reader.read_bytes())?; + let contents = reader.next().read_tagged(Tag::context(0), |reader| reader.read_bytes())?; Ok(contents) }) })?; @@ -1049,24 +1015,19 @@ mod tests { let pfx_bits = include_bytes!("../../tests/data/nomac_pass.pfx"); let correct_password = "xyzzy"; let wrong_password = "unicorn"; - // This password happens to produce a correct CBC padding so causes a different error + // This password happens to produce a correct CBC padding so causes a different + // error let wrong_password_correct_padding = "zork#364"; let parsed_pfx = Pfx::parse(pfx_bits).unwrap(); let pfx = parsed_pfx.decrypt(&wrong_password, None); assert!(pfx.is_err()); - assert_eq!( - pfx.unwrap_err(), - Pkcs12Error::Crypto(crate::Error::CipherInvalidPadding) - ); + assert_eq!(pfx.unwrap_err(), Pkcs12Error::Crypto(crate::Error::CipherInvalidPadding)); let pfx = parsed_pfx.decrypt(&wrong_password_correct_padding, None); assert!(pfx.is_err()); - assert_eq!( - pfx.unwrap_err(), - Pkcs12Error::ASN1(ASN1Error::new(ASN1ErrorKind::Eof)) - ); + assert_eq!(pfx.unwrap_err(), Pkcs12Error::ASN1(ASN1Error::new(ASN1ErrorKind::Eof))); let pfx = parsed_pfx.decrypt(&correct_password, None).unwrap(); @@ -1169,9 +1130,7 @@ mod tests { let parsed_pfx = Pfx::parse(pfx_bits).unwrap(); // Test that decrypting an already decrypted Pfx works: - let pfx = parsed_pfx - .decrypt(&enc_password, Some(&mac_password)) - .unwrap(); + let pfx = parsed_pfx.decrypt(&enc_password, Some(&mac_password)).unwrap(); let pfx = pfx.decrypt(&enc_password, Some(&mac_password)).unwrap(); let certs = pfx.certificates().collect::>(); @@ -1220,5 +1179,4 @@ mod tests { assert_eq!(pk.name().unwrap(), "RSA"); assert_eq!(pk.len(), 2048); } - } diff --git a/mbedtls/src/private.rs b/mbedtls/src/private.rs index 06ba9a749..33df9b6f9 100644 --- a/mbedtls/src/private.rs +++ b/mbedtls/src/private.rs @@ -31,7 +31,7 @@ where with malformed datastructures, mbedtls may return a too-small error regardless of how much buffer space is provided. This causes a loop which terminates with a out of memory panic. */ - const MAX_VECTOR_ALLOCATION : usize = 4 * 1024 * 1024; + const MAX_VECTOR_ALLOCATION: usize = 4 * 1024 * 1024; let mut vec = Vec::with_capacity(2048 /* big because of bug in x509write */); loop { diff --git a/mbedtls/src/rng/ctr_drbg.rs b/mbedtls/src/rng/ctr_drbg.rs index 96e7e465e..a3a378234 100644 --- a/mbedtls/src/rng/ctr_drbg.rs +++ b/mbedtls/src/rng/ctr_drbg.rs @@ -9,10 +9,10 @@ #[cfg(feature = "std")] use std::sync::Arc; -pub use mbedtls_sys::CTR_DRBG_RESEED_INTERVAL as RESEED_INTERVAL; -use mbedtls_sys::*; use mbedtls_sys::types::raw_types::{c_int, c_uchar, c_void}; use mbedtls_sys::types::size_t; +pub use mbedtls_sys::CTR_DRBG_RESEED_INTERVAL as RESEED_INTERVAL; +use mbedtls_sys::*; #[cfg(not(feature = "std"))] use crate::alloc_prelude::*; @@ -46,14 +46,14 @@ define!( // That function has an internal mutex to guarantee thread safety. // // The other potential conflict is a mutable reference changing class. -// That is avoided by having any users of the callback hold an 'Arc' to this class. -// Rust will then ensure that a mutable reference cannot be aquired if more then 1 Arc exists to the same class. +// That is avoided by having any users of the callback hold an 'Arc' to this +// class. Rust will then ensure that a mutable reference cannot be aquired if +// more then 1 Arc exists to the same class. // unsafe impl Sync for CtrDrbg {} #[allow(dead_code)] impl CtrDrbg { - pub fn new(entropy: Arc, additional_entropy: Option<&[u8]>) -> Result { let mut inner = Box::new(ctr_drbg_context::default()); @@ -64,11 +64,15 @@ impl CtrDrbg { Some(T::call), entropy.data_ptr(), additional_entropy.map(<[_]>::as_ptr).unwrap_or(::core::ptr::null()), - additional_entropy.map(<[_]>::len).unwrap_or(0) - ).into_result()?; + additional_entropy.map(<[_]>::len).unwrap_or(0), + ) + .into_result()?; } - Ok(CtrDrbg { inner, entropy: EntropyHolder::Shared(entropy) }) + Ok(CtrDrbg { + inner, + entropy: EntropyHolder::Shared(entropy), + }) } pub fn with_mut_entropy(entropy: T, additional_entropy: Option<&[u8]>) -> Result { @@ -83,14 +87,17 @@ impl CtrDrbg { Some(T::call_mut), entropy.data_ptr_mut(), additional_entropy.map(<[_]>::as_ptr).unwrap_or(::core::ptr::null()), - additional_entropy.map(<[_]>::len).unwrap_or(0) - ).into_result()?; + additional_entropy.map(<[_]>::len).unwrap_or(0), + ) + .into_result()?; } - Ok(CtrDrbg { inner, entropy: EntropyHolder::Unique(entropy) }) + Ok(CtrDrbg { + inner, + entropy: EntropyHolder::Unique(entropy), + }) } - pub fn prediction_resistance(&self) -> bool { if self.inner.prediction_resistance == CTR_DRBG_PR_OFF { false @@ -100,12 +107,7 @@ impl CtrDrbg { } pub fn set_prediction_resistance(&mut self, pr: bool) { - unsafe { - ctr_drbg_set_prediction_resistance( - &mut *self.inner, - if pr { CTR_DRBG_PR_ON } else { CTR_DRBG_PR_OFF }, - ) - } + unsafe { ctr_drbg_set_prediction_resistance(&mut *self.inner, if pr { CTR_DRBG_PR_ON } else { CTR_DRBG_PR_OFF }) } } getter!(entropy_len() -> size_t = .entropy_len); @@ -117,10 +119,8 @@ impl CtrDrbg { unsafe { ctr_drbg_reseed( &mut *self.inner, - additional_entropy - .map(<[_]>::as_ptr) - .unwrap_or(::core::ptr::null()), - additional_entropy.map(<[_]>::len).unwrap_or(0) + additional_entropy.map(<[_]>::as_ptr).unwrap_or(::core::ptr::null()), + additional_entropy.map(<[_]>::len).unwrap_or(0), ) .into_result()? }; @@ -141,8 +141,12 @@ impl CtrDrbg { impl RngCallbackMut for CtrDrbg { #[inline(always)] - unsafe extern "C" fn call_mut(user_data: *mut c_void, data: *mut c_uchar, len: size_t) -> c_int where Self: Sized { - // Mutex used in ctr_drbg_random at: ../../../mbedtls-sys/vendor/crypto/library/ctr_drbg.c:546 + unsafe extern "C" fn call_mut(user_data: *mut c_void, data: *mut c_uchar, len: size_t) -> c_int + where + Self: Sized, + { + // Mutex used in ctr_drbg_random at: + // ../../../mbedtls-sys/vendor/crypto/library/ctr_drbg.c:546 ctr_drbg_random(user_data, data, len) } @@ -153,11 +157,15 @@ impl RngCallbackMut for CtrDrbg { impl RngCallback for CtrDrbg { #[inline(always)] - unsafe extern "C" fn call(user_data: *mut c_void, data: *mut c_uchar, len: size_t) -> c_int where Self: Sized { - // Mutex used in ctr_drbg_random at: ../../../mbedtls-sys/vendor/crypto/library/ctr_drbg.c:546 + unsafe extern "C" fn call(user_data: *mut c_void, data: *mut c_uchar, len: size_t) -> c_int + where + Self: Sized, + { + // Mutex used in ctr_drbg_random at: + // ../../../mbedtls-sys/vendor/crypto/library/ctr_drbg.c:546 ctr_drbg_random(user_data, data, len) } - + fn data_ptr(&self) -> *mut c_void { self.handle() as *const _ as *mut _ } diff --git a/mbedtls/src/rng/hmac_drbg.rs b/mbedtls/src/rng/hmac_drbg.rs index 32dfaf5b7..27d5688eb 100644 --- a/mbedtls/src/rng/hmac_drbg.rs +++ b/mbedtls/src/rng/hmac_drbg.rs @@ -6,14 +6,13 @@ * option. This file may not be copied, modified, or distributed except * according to those terms. */ - #[cfg(feature = "std")] use std::sync::Arc; -pub use mbedtls_sys::HMAC_DRBG_RESEED_INTERVAL as RESEED_INTERVAL; -use mbedtls_sys::*; use mbedtls_sys::types::raw_types::{c_int, c_uchar, c_void}; use mbedtls_sys::types::size_t; +pub use mbedtls_sys::HMAC_DRBG_RESEED_INTERVAL as RESEED_INTERVAL; +use mbedtls_sys::*; #[cfg(not(feature = "std"))] use crate::alloc_prelude::*; @@ -38,12 +37,11 @@ impl HmacDrbg { entropy: Arc, additional_entropy: Option<&[u8]>, ) -> Result { - let mut ret = HmacDrbg { inner: hmac_drbg_context::default(), entropy: Some(entropy), }; - + unsafe { hmac_drbg_init(&mut ret.inner); hmac_drbg_seed( @@ -52,14 +50,13 @@ impl HmacDrbg { Some(T::call), ret.entropy.as_ref().unwrap().data_ptr(), additional_entropy.map(<[_]>::as_ptr).unwrap_or(::core::ptr::null()), - additional_entropy.map(<[_]>::len).unwrap_or(0) + additional_entropy.map(<[_]>::len).unwrap_or(0), ) .into_result()? }; Ok(ret) } - pub fn from_buf(md_info: MdInfo, entropy: &[u8]) -> Result { let mut ret = HmacDrbg { inner: hmac_drbg_context::default(), @@ -68,13 +65,7 @@ impl HmacDrbg { unsafe { hmac_drbg_init(&mut ret.inner); - hmac_drbg_seed_buf( - &mut ret.inner, - md_info.into(), - entropy.as_ptr(), - entropy.len() - ) - .into_result()? + hmac_drbg_seed_buf(&mut ret.inner, md_info.into(), entropy.as_ptr(), entropy.len()).into_result()? }; Ok(ret) } @@ -88,16 +79,7 @@ impl HmacDrbg { } pub fn set_prediction_resistance(&mut self, pr: bool) { - unsafe { - hmac_drbg_set_prediction_resistance( - &mut self.inner, - if pr { - HMAC_DRBG_PR_ON - } else { - HMAC_DRBG_PR_OFF - }, - ) - } + unsafe { hmac_drbg_set_prediction_resistance(&mut self.inner, if pr { HMAC_DRBG_PR_ON } else { HMAC_DRBG_PR_OFF }) } } getter!(entropy_len() -> size_t = .entropy_len); @@ -109,10 +91,8 @@ impl HmacDrbg { unsafe { hmac_drbg_reseed( &mut self.inner, - additional_entropy - .map(<[_]>::as_ptr) - .unwrap_or(::core::ptr::null()), - additional_entropy.map(<[_]>::len).unwrap_or(0) + additional_entropy.map(<[_]>::as_ptr).unwrap_or(::core::ptr::null()), + additional_entropy.map(<[_]>::len).unwrap_or(0), ) .into_result()? }; @@ -145,7 +125,8 @@ impl RngCallbackMut for HmacDrbg { impl RngCallback for HmacDrbg { #[inline(always)] unsafe extern "C" fn call(user_data: *mut c_void, data: *mut c_uchar, len: size_t) -> c_int { - // Mutex used in hmac_drbg_random: ../../../mbedtls-sys/vendor/crypto/library/hmac_drbg.c:363 + // Mutex used in hmac_drbg_random: + // ../../../mbedtls-sys/vendor/crypto/library/hmac_drbg.c:363 hmac_drbg_random(user_data, data, len) } diff --git a/mbedtls/src/rng/mod.rs b/mbedtls/src/rng/mod.rs index 88d1b5e52..f60d49316 100644 --- a/mbedtls/src/rng/mod.rs +++ b/mbedtls/src/rng/mod.rs @@ -23,7 +23,7 @@ pub use self::os_entropy::OsEntropy; #[cfg(any(feature = "rdrand", target_env = "sgx"))] pub use self::rdrand::{Entropy as Rdseed, Nrbg as Rdrand}; -use crate::error::{Result, IntoResult}; +use crate::error::{IntoResult, Result}; use mbedtls_sys::types::raw_types::{c_int, c_uchar}; use mbedtls_sys::types::size_t; @@ -31,7 +31,10 @@ callback!(EntropyCallbackMut,EntropyCallback(data: *mut c_uchar, len: size_t) -> callback!(RngCallbackMut,RngCallback(data: *mut c_uchar, len: size_t) -> c_int); pub trait Random: RngCallback { - fn random(&mut self, data: &mut [u8]) -> Result<()> where Self: Sized { + fn random(&mut self, data: &mut [u8]) -> Result<()> + where + Self: Sized, + { unsafe { Self::call(self.data_ptr(), data.as_mut_ptr(), data.len()) }.into_result()?; Ok(()) } diff --git a/mbedtls/src/rng/os_entropy.rs b/mbedtls/src/rng/os_entropy.rs index 5f8533d8b..924234a30 100644 --- a/mbedtls/src/rng/os_entropy.rs +++ b/mbedtls/src/rng/os_entropy.rs @@ -8,12 +8,12 @@ use std::sync::Arc; -use mbedtls_sys::*; use mbedtls_sys::types::raw_types::{c_int, c_uchar, c_void}; use mbedtls_sys::types::size_t; +use mbedtls_sys::*; use crate::error::{IntoResult, Result}; -use crate::rng::{EntropyCallback,EntropyCallbackMut}; +use crate::rng::{EntropyCallback, EntropyCallbackMut}; callback!(EntropySourceCallbackMut,EntropySourceCallback(data: *mut c_uchar, size: size_t, out: *mut size_t) -> c_int); @@ -33,8 +33,9 @@ define!( // That function has an internal mutex to guarantee thread safety. // // The other potential conflict is a mutable reference changing class. -// That is avoided by having any users of the callback hold an 'Arc' to this class. -// Rust will then ensure that a mutable reference cannot be aquired if more then 1 Arc exists to the same class. +// That is avoided by having any users of the callback hold an 'Arc' to this +// class. Rust will then ensure that a mutable reference cannot be aquired if +// more then 1 Arc exists to the same class. // unsafe impl Sync for OsEntropy {} @@ -47,14 +48,16 @@ impl OsEntropy { strong: bool, ) -> Result<()> { unsafe { - // add_source is guarded with internal mutex: mbedtls-sys/vendor/crypto/library/entropy.c:143 - // all sources are called at later points via 'entropy_gather_internal' which in turn is called with internal mutex locked. + // add_source is guarded with internal mutex: + // mbedtls-sys/vendor/crypto/library/entropy.c:143 all sources are + // called at later points via 'entropy_gather_internal' which in turn is called + // with internal mutex locked. entropy_add_source( self.inner_ffi_mut(), Some(F::call), source.data_ptr(), threshold, - if strong { ENTROPY_SOURCE_STRONG } else { ENTROPY_SOURCE_WEAK } + if strong { ENTROPY_SOURCE_STRONG } else { ENTROPY_SOURCE_WEAK }, ) .into_result()? }; @@ -65,18 +68,19 @@ impl OsEntropy { } pub fn gather(&self) -> Result<()> { - // function is guarded with internal mutex: mbedtls-sys/vendor/crypto/library/entropy.c:310 + // function is guarded with internal mutex: + // mbedtls-sys/vendor/crypto/library/entropy.c:310 unsafe { entropy_gather(self.inner_ffi_mut()) }.into_result()?; Ok(()) } pub fn update_manual(&self, data: &[u8]) -> Result<()> { - // function is guarded with internal mutex: mbedtls-sys/vendor/crypto/library/entropy.c:241 + // function is guarded with internal mutex: + // mbedtls-sys/vendor/crypto/library/entropy.c:241 unsafe { entropy_update_manual(self.inner_ffi_mut(), data.as_ptr(), data.len()) }.into_result()?; Ok(()) } - // TODO // entropy_write_seed_file // entropy_update_seed_file @@ -86,8 +90,10 @@ impl OsEntropy { impl EntropyCallback for OsEntropy { #[inline(always)] unsafe extern "C" fn call(user_data: *mut c_void, data: *mut c_uchar, len: size_t) -> c_int { - // mutex used in entropy_func: ../../../mbedtls-sys/vendor/crypto/library/entropy.c:348 - // note: we're not using MBEDTLS_ENTROPY_NV_SEED so the initialization is not present or a race condition. + // mutex used in entropy_func: + // ../../../mbedtls-sys/vendor/crypto/library/entropy.c:348 note: we're + // not using MBEDTLS_ENTROPY_NV_SEED so the initialization is not present or a + // race condition. entropy_func(user_data, data, len) } @@ -99,8 +105,10 @@ impl EntropyCallback for OsEntropy { impl EntropyCallbackMut for OsEntropy { #[inline(always)] unsafe extern "C" fn call_mut(user_data: *mut c_void, data: *mut c_uchar, len: size_t) -> c_int { - // mutex used in entropy_func: ../../../mbedtls-sys/vendor/crypto/library/entropy.c:348 - // note: we're not using MBEDTLS_ENTROPY_NV_SEED so the initialization is not present or a race condition. + // mutex used in entropy_func: + // ../../../mbedtls-sys/vendor/crypto/library/entropy.c:348 note: we're + // not using MBEDTLS_ENTROPY_NV_SEED so the initialization is not present or a + // race condition. entropy_func(user_data, data, len) } diff --git a/mbedtls/src/rng/rdrand.rs b/mbedtls/src/rng/rdrand.rs index 6ca4936f1..0b7270b17 100644 --- a/mbedtls/src/rng/rdrand.rs +++ b/mbedtls/src/rng/rdrand.rs @@ -16,12 +16,12 @@ use core::arch::x86_64::{_rdrand32_step as _rdrand_step, _rdseed32_step as _rdse #[cfg(target_arch = "x86_64")] use core::arch::x86_64::{_rdrand64_step as _rdrand_step, _rdseed64_step as _rdseed_step}; -// Intel documentation claims that if hardware is working RDRAND will produce output -// after at most 10 attempts +// Intel documentation claims that if hardware is working RDRAND will produce +// output after at most 10 attempts const RDRAND_READ_ATTEMPTS: usize = 10; -// Intel does not document the number of times RDSEED might consecutively fail, but in -// example code uses 75 as the upper bound. +// Intel does not document the number of times RDSEED might consecutively fail, +// but in example code uses 75 as the upper bound. const RDSEED_READ_ATTEMPTS: usize = 75; fn call_cpu_rng(attempts: usize, intrin: unsafe fn(&mut T) -> i32, cast: F) -> Option @@ -96,7 +96,7 @@ impl RngCallbackMut for Nrbg { unsafe extern "C" fn call_mut(_: *mut c_void, data: *mut c_uchar, len: size_t) -> c_int { // outbuf data/len are stack variables let mut outbuf = from_raw_parts_mut(data, len); - + // rdrand function is thread safe write_rng_to_slice(&mut outbuf, rdrand) } @@ -110,7 +110,7 @@ impl RngCallback for Nrbg { unsafe extern "C" fn call(_: *mut c_void, data: *mut c_uchar, len: size_t) -> c_int { // outbuf data/len are stack variables let mut outbuf = from_raw_parts_mut(data, len); - + // rdrand function is thread safe write_rng_to_slice(&mut outbuf, rdrand) } @@ -119,4 +119,3 @@ impl RngCallback for Nrbg { ::core::ptr::null_mut() } } - diff --git a/mbedtls/src/ssl/async_io.rs b/mbedtls/src/ssl/async_io.rs index 0613efbfb..eca3d84ae 100644 --- a/mbedtls/src/ssl/async_io.rs +++ b/mbedtls/src/ssl/async_io.rs @@ -121,14 +121,13 @@ where return Poll::Ready(Err(IoError::new(IoErrorKind::Other, "stream has been shutdown"))); } - self - .with_bio_async(cx, |ssl_ctx| match ssl_ctx.async_write(buf) { - Err(Error::SslPeerCloseNotify) => Poll::Ready(Ok(0)), - Err(Error::SslWantWrite) => Poll::Pending, - Err(e) => Poll::Ready(Err(crate::private::error_to_io_error(e))), - Ok(i) => Poll::Ready(Ok(i)), - }) - .unwrap_or_else(|| Poll::Ready(Err(crate::private::error_to_io_error(Error::NetSendFailed)))) + self.with_bio_async(cx, |ssl_ctx| match ssl_ctx.async_write(buf) { + Err(Error::SslPeerCloseNotify) => Poll::Ready(Ok(0)), + Err(Error::SslWantWrite) => Poll::Pending, + Err(e) => Poll::Ready(Err(crate::private::error_to_io_error(e))), + Ok(i) => Poll::Ready(Ok(i)), + }) + .unwrap_or_else(|| Poll::Ready(Err(crate::private::error_to_io_error(Error::NetSendFailed)))) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll> { diff --git a/mbedtls/src/ssl/config.rs b/mbedtls/src/ssl/config.rs index 29747b639..4b6ab4cb2 100644 --- a/mbedtls/src/ssl/config.rs +++ b/mbedtls/src/ssl/config.rs @@ -6,28 +6,27 @@ * option. This file may not be copied, modified, or distributed except * according to those terms. */ -#[cfg(feature = "std")] -use std::sync::Arc; #[cfg(feature = "std")] use std::borrow::Cow; +#[cfg(feature = "std")] +use std::sync::Arc; use core::slice::from_raw_parts; -use mbedtls_sys::*; use mbedtls_sys::types::raw_types::*; use mbedtls_sys::types::size_t; +use mbedtls_sys::*; - -use crate::alloc::{List as MbedtlsList}; +use crate::alloc::List as MbedtlsList; #[cfg(not(feature = "std"))] use crate::alloc_prelude::*; -use crate::error::{Error, Result, IntoResult}; -use crate::pk::Pk; +use crate::error::{Error, IntoResult, Result}; use crate::pk::dhparam::Dhm; +use crate::pk::Pk; use crate::private::UnsafeFrom; use crate::rng::RngCallback; -use crate::ssl::cookie::CookieCallback; use crate::ssl::context::HandshakeContext; +use crate::ssl::cookie::CookieCallback; use crate::ssl::ticket::TicketCallback; use crate::x509::{self, Certificate, Crl, Profile, VerifyCallback}; @@ -102,7 +101,6 @@ callback!(DbgCallback: Fn(i32, Cow<'_, str>, i32, Cow<'_, str>) -> ()); callback!(SniCallback: Fn(&mut HandshakeContext, &[u8]) -> Result<()>); callback!(CaCallback: Fn(&MbedtlsList) -> Result>); - #[repr(transparent)] pub struct NullTerminatedStrList { c: Vec<*mut c_char>, @@ -114,13 +112,19 @@ unsafe impl Sync for NullTerminatedStrList {} impl NullTerminatedStrList { #[cfg(feature = "std")] pub fn new(list: &[&str]) -> Result { - let mut ret = NullTerminatedStrList { c: Vec::with_capacity(list.len() + 1) }; + let mut ret = NullTerminatedStrList { + c: Vec::with_capacity(list.len() + 1), + }; for item in list { - ret.c.push(::std::ffi::CString::new(*item).map_err(|_| Error::SslBadInputData)?.into_raw()); + ret.c.push( + ::std::ffi::CString::new(*item) + .map_err(|_| Error::SslBadInputData)? + .into_raw(), + ); } - - ret.c.push(core::ptr::null_mut()); + + ret.c.push(core::ptr::null_mut()); Ok(ret) } @@ -150,16 +154,16 @@ define!( // This allows caller to share structure on multiple configs if needed. own_cert: Vec>>, own_pk: Vec>, - + ca_cert: Option>>, crl: Option>, - + rng: Option>, - + ciphersuites: Vec>>, curves: Option>>, protocols: Option>, - + verify_callback: Option>, #[cfg(feature = "std")] dbg_callback: Option>, @@ -182,7 +186,8 @@ impl Config { // This is just a memset to 0. ssl_config_init(&mut inner); - // Set default values - after this point we will need ssl_config_free to be called. + // Set default values - after this point we will need ssl_config_free to be + // called. ssl_config_defaults(&mut inner, e as c_int, t as c_int, p as c_int); }; @@ -237,7 +242,7 @@ impl Config { self.protocols = Some(protocols); Ok(()) } - + pub fn set_ciphersuites_for_version(&mut self, list: Arc>, major: c_int, minor: c_int) { Self::check_c_list(&list); unsafe { ssl_conf_ciphersuites_for_version(self.into(), list.as_ptr(), major, minor) } @@ -254,14 +259,16 @@ impl Config { unsafe { ssl_conf_rng(self.into(), Some(T::call), rng.data_ptr()) }; self.rng = Some(rng); } - + pub fn set_min_version(&mut self, version: Version) -> Result<()> { let minor = match version { Version::Ssl3 => 0, Version::Tls1_0 => 1, Version::Tls1_1 => 2, Version::Tls1_2 => 3, - _ => { return Err(Error::SslBadHsProtocolVersion); } + _ => { + return Err(Error::SslBadHsProtocolVersion); + } }; unsafe { ssl_conf_min_version(self.into(), 3, minor) }; @@ -274,13 +281,16 @@ impl Config { Version::Tls1_0 => 1, Version::Tls1_1 => 2, Version::Tls1_2 => 3, - _ => { return Err(Error::SslBadHsProtocolVersion); } + _ => { + return Err(Error::SslBadHsProtocolVersion); + } }; unsafe { ssl_conf_max_version(self.into(), 3, minor) }; Ok(()) } - // Profile as implemented in profile.rs can only point to global variables from mbedtls which would have 'static lifetime + // Profile as implemented in profile.rs can only point to global variables from + // mbedtls which would have 'static lifetime setter!(set_cert_profile(p: &'static Profile) = ssl_conf_cert_profile); /// Takes both DER and PEM forms of FFDH parameters in `DHParams` format. @@ -298,11 +308,17 @@ impl Config { pub fn set_ca_list(&mut self, ca_cert: Arc>, crl: Option>) { // This will override internal pointers to what we provide. - - unsafe { ssl_conf_ca_chain(self.into(), ca_cert.inner_ffi_mut(), crl.as_ref().map(|crl| crl.inner_ffi_mut()).unwrap_or(::core::ptr::null_mut())); } + + unsafe { + ssl_conf_ca_chain( + self.into(), + ca_cert.inner_ffi_mut(), + crl.as_ref().map(|crl| crl.inner_ffi_mut()).unwrap_or(::core::ptr::null_mut()), + ); + } self.ca_cert = Some(ca_cert); - self.crl = crl; + self.crl = crl; } pub fn push_cert(&mut self, own_cert: Arc>, own_pk: Arc) -> Result<()> { @@ -314,22 +330,17 @@ impl Config { self.own_pk.push(own_pk.clone()); // This will append pointers to our certificates inside mbedtls - unsafe { ssl_conf_own_cert(self.into(), own_cert.inner_ffi_mut(), own_pk.inner_ffi_mut()) - .into_result() - .map(|_| ()) + unsafe { + ssl_conf_own_cert(self.into(), own_cert.inner_ffi_mut(), own_pk.inner_ffi_mut()) + .into_result() + .map(|_| ()) } } - - /// Server only: configure callback to use for generating/interpreting session tickets. + + /// Server only: configure callback to use for generating/interpreting + /// session tickets. pub fn set_session_tickets_callback(&mut self, cb: Arc) { - unsafe { - ssl_conf_session_tickets_cb( - self.into(), - Some(T::call_write), - Some(T::call_parse), - cb.data_ptr(), - ) - }; + unsafe { ssl_conf_session_tickets_cb(self.into(), Some(T::call_write), Some(T::call_parse), cb.data_ptr()) }; self.ticket_callback = Some(cb); } @@ -345,7 +356,7 @@ impl Config { /// Client only: minimal FFDH group size set_ffdh_min_bitlen(bitlen: c_uint) = ssl_conf_dhm_min_bitlen ); - + pub fn set_sni_callback(&mut self, cb: F) where F: SniCallback + 'static, @@ -369,12 +380,13 @@ impl Config { // mbedtls-sys/vendor/library/ssl_srv.c - ssl_parse_servername_ext // // As such: - // - The ssl_context is a rust 'Context' structure that we have a mutable reference to via 'establish' + // - The ssl_context is a rust 'Context' structure that we have a mutable + // reference to via 'establish' // - We can pointer cast to it to allow storing additional objects. // let cb = &mut *(closure as *mut F); let ctx = UnsafeFrom::from(ctx).unwrap(); - + let name = from_raw_parts(name, name_len); match cb(ctx, name) { Ok(()) => 0, @@ -382,20 +394,32 @@ impl Config { } } - self.sni_callback = Some(Arc::new(cb)); - unsafe { ssl_conf_sni(self.into(), Some(sni_callback::), &**self.sni_callback.as_mut().unwrap() as *const _ as *mut c_void) } + unsafe { + ssl_conf_sni( + self.into(), + Some(sni_callback::), + &**self.sni_callback.as_mut().unwrap() as *const _ as *mut c_void, + ) + } } - // The docs for mbedtls_x509_crt_verify say "The [callback] should return 0 for anything but a - // fatal error.", so verify callbacks should return Ok(()) for anything but a fatal error. - // Report verification errors by updating the flags in VerifyError. + // The docs for mbedtls_x509_crt_verify say "The [callback] should return 0 for + // anything but a fatal error.", so verify callbacks should return Ok(()) + // for anything but a fatal error. Report verification errors by updating + // the flags in VerifyError. pub fn set_verify_callback(&mut self, cb: F) where F: VerifyCallback + 'static, { self.verify_callback = Some(Arc::new(cb)); - unsafe { ssl_conf_verify(self.into(), Some(x509::verify_callback::), &**self.verify_callback.as_ref().unwrap() as *const _ as *mut c_void) } + unsafe { + ssl_conf_verify( + self.into(), + Some(x509::verify_callback::), + &**self.verify_callback.as_ref().unwrap() as *const _ as *mut c_void, + ) + } } pub fn set_ca_callback(&mut self, cb: F) @@ -405,7 +429,7 @@ impl Config { unsafe extern "C" fn ca_callback( closure: *mut c_void, child: *const x509_crt, - candidate_cas: *mut *mut x509_crt + candidate_cas: *mut *mut x509_crt, ) -> c_int where F: CaCallback + 'static, @@ -418,16 +442,24 @@ impl Config { let crt: &MbedtlsList = UnsafeFrom::from(&child as *const *const x509_crt).expect("valid certificate"); match cb(&crt) { Ok(list) => { - // This does not leak due to mbedtls taking ownership from us and freeing the certificates itself. (logic is in: mbedtls-sys/vendor/library/x509_crt.c:2904) + // This does not leak due to mbedtls taking ownership from us and freeing the + // certificates itself. (logic is in: + // mbedtls-sys/vendor/library/x509_crt.c:2904) *candidate_cas = list.into_raw(); 0 - }, + } Err(e) => e.to_int(), } } self.ca_callback = Some(Arc::new(cb)); - unsafe { ssl_conf_ca_cb( self.into(), Some(ca_callback::), &**self.ca_callback.as_mut().unwrap() as *const _ as *mut c_void) } + unsafe { + ssl_conf_ca_cb( + self.into(), + Some(ca_callback::), + &**self.ca_callback.as_mut().unwrap() as *const _ as *mut c_void, + ) + } } #[cfg(feature = "std")] @@ -441,7 +473,7 @@ impl Config { level: c_int, file: *const c_char, line: c_int, - message: *const c_char + message: *const c_char, ) -> () where F: DbgCallback + 'static, @@ -452,35 +484,55 @@ impl Config { false => std::ffi::CStr::from_ptr(file).to_string_lossy(), true => Cow::from(""), }; - + let message = match message.is_null() { false => std::ffi::CStr::from_ptr(message).to_string_lossy(), true => Cow::from(""), }; - + cb(level, file, line, message); } self.dbg_callback = Some(Arc::new(cb)); - unsafe { ssl_conf_dbg(self.into(), Some(dbg_callback::), &**self.dbg_callback.as_mut().unwrap() as *const _ as *mut c_void) } + unsafe { + ssl_conf_dbg( + self.into(), + Some(dbg_callback::), + &**self.dbg_callback.as_mut().unwrap() as *const _ as *mut c_void, + ) + } } /// Sets the PSK and the PSK-Identity /// - /// Only a single entry is supported at the moment. If another one was set before, it will be - /// overridden. + /// Only a single entry is supported at the moment. If another one was set + /// before, it will be overridden. pub fn set_psk(&mut self, psk: &[u8], psk_identity: &str) -> Result<()> { unsafe { // This allocates and copies the buffers and does not store any pointer to them - ssl_conf_psk(self.into(), psk.as_ptr(), psk.len(), psk_identity.as_ptr(), psk_identity.len()) - .into_result() - .map(|_| ()) + ssl_conf_psk( + self.into(), + psk.as_ptr(), + psk.len(), + psk_identity.as_ptr(), + psk_identity.len(), + ) + .into_result() + .map(|_| ()) } } - /// Sets the cookie context and callbacks which are required for DTLS servers + /// Sets the cookie context and callbacks which are required for DTLS + /// servers pub fn set_dtls_cookies(&mut self, dtls_cookies: Arc) { - unsafe { ssl_conf_dtls_cookies(self.into(), Some(T::cookie_write), Some(T::cookie_check), dtls_cookies.data_ptr()) }; + unsafe { + ssl_conf_dtls_cookies( + self.into(), + Some(T::cookie_write), + Some(T::cookie_check), + dtls_cookies.data_ptr(), + ) + }; self.dtls_cookies = Some(dtls_cookies); } } diff --git a/mbedtls/src/ssl/context.rs b/mbedtls/src/ssl/context.rs index 015848afb..349a34e99 100644 --- a/mbedtls/src/ssl/context.rs +++ b/mbedtls/src/ssl/context.rs @@ -14,26 +14,24 @@ use std::sync::Arc; use mbedtls_sys::types::raw_types::{c_int, c_void}; use mbedtls_sys::*; +use crate::alloc::List as MbedtlsList; #[cfg(not(feature = "std"))] use crate::alloc_prelude::*; -use crate::alloc::List as MbedtlsList; -use crate::error::{Error, Result, IntoResult}; +use crate::error::{Error, IntoResult, Result}; use crate::pk::Pk; use crate::private::UnsafeFrom; -use crate::ssl::config::{Config, Version, AuthMode}; +use crate::ssl::config::{AuthMode, Config, Version}; use crate::ssl::io::IoCallbackUnsafe; use crate::x509::{Certificate, Crl, VerifyError}; pub trait TimerCallback: Send + Sync { - unsafe extern "C" fn set_timer( - p_timer: *mut c_void, - int_ms: u32, - fin_ms: u32, - ) where Self: Sized; + unsafe extern "C" fn set_timer(p_timer: *mut c_void, int_ms: u32, fin_ms: u32) + where + Self: Sized; - unsafe extern "C" fn get_timer( - p_timer: *mut c_void, - ) -> c_int where Self: Sized; + unsafe extern "C" fn get_timer(p_timer: *mut c_void) -> c_int + where + Self: Sized; fn data_ptr(&mut self) -> *mut c_void; } @@ -58,20 +56,20 @@ impl Timer { #[cfg(feature = "std")] impl TimerCallback for Timer { - unsafe extern "C" fn set_timer( - p_timer: *mut c_void, - int_ms: u32, - fin_ms: u32, - ) where Self: Sized { + unsafe extern "C" fn set_timer(p_timer: *mut c_void, int_ms: u32, fin_ms: u32) + where + Self: Sized, + { let slf = (p_timer as *mut Timer).as_mut().unwrap(); slf.timer_start = std::time::Instant::now(); slf.timer_int_ms = int_ms; slf.timer_fin_ms = fin_ms; } - unsafe extern "C" fn get_timer( - p_timer: *mut c_void, - ) -> c_int where Self: Sized { + unsafe extern "C" fn get_timer(p_timer: *mut c_void) -> c_int + where + Self: Sized, + { let slf = (p_timer as *mut Timer).as_mut().unwrap(); if slf.timer_int_ms == 0 || slf.timer_fin_ms == 0 { return 0; @@ -97,7 +95,7 @@ define!( struct HandshakeContext { handshake_ca_cert: Option>>, handshake_crl: Option>, - + handshake_cert: Vec>>, handshake_pk: Vec>, }; @@ -111,17 +109,18 @@ define!( pub struct Context { // Base structure used in SNI callback where we cannot determine the io type. inner: HandshakeContext, - + // config is used read-only for multiple contexts and is immutable once configured. - config: Arc, - + config: Arc, + // Must be held in heap and pointer to it as pointer is sent to MbedSSL and can't be re-allocated. io: Option>, timer_callback: Option>, - /// Stores the client identification on the DTLS server-side for the current connection. Must - /// be stored in [`Context`] first so that it can be set after the `ssl_session_reset` in the + /// Stores the client identification on the DTLS server-side for the current + /// connection. Must be stored in [`Context`] first so that it can be + /// set after the `ssl_session_reset` in the /// [`establish`](Context::establish) call. client_transport_id: Option>, } @@ -149,7 +148,7 @@ impl<'a, T> Into<*mut ssl_context> for &'a mut Context { impl Context { pub fn new(config: Arc) -> Self { let mut inner = ssl_context::default(); - + unsafe { ssl_init(&mut inner); ssl_setup(&mut inner, (&*config).into()); @@ -160,7 +159,7 @@ impl Context { inner, handshake_ca_cert: None, handshake_crl: None, - + handshake_cert: vec![], handshake_pk: vec![], }, @@ -183,29 +182,30 @@ impl Context { /// # Safety /// `io` must live as long as `ctx` or the next time bio is set/cleared. unsafe fn set_bio_raw>(ctx: *mut ssl_context, io: &mut T) { - ssl_set_bio( - ctx, - io as *mut T as *mut c_void, - Some(T::call_send), - Some(T::call_recv), - None, - ); + ssl_set_bio(ctx, io as *mut T as *mut c_void, Some(T::call_send), Some(T::call_recv), None); } -/// This function provides a way to apply async context to bio before running +/// This function provides a way to apply async context to bio before running /// any logic. -/// Note: `bio` is a concept in common TLS implementation which refers to basic IO. -/// openssl and mbedtls both use this concept. +/// Note: `bio` is a concept in common TLS implementation which refers to basic +/// IO. openssl and mbedtls both use this concept. /// Ref: https://stackoverflow.com/questions/51672133/what-are-openssl-bios-how-do-they-work-how-are-bios-used-in-openssl #[cfg(all(feature = "std", feature = "async"))] -impl Context { - pub(super) fn with_bio_async<'cx, R, IoType>(&mut self, cx: &mut std::task::Context<'cx>, f: impl FnOnce(&mut Self) -> R) -> Option where for<'c> (&'c mut std::task::Context<'cx>, &'c mut T): IoCallbackUnsafe { +impl Context { + pub(super) fn with_bio_async<'cx, R, IoType>( + &mut self, + cx: &mut std::task::Context<'cx>, + f: impl FnOnce(&mut Self) -> R, + ) -> Option + where + for<'c> (&'c mut std::task::Context<'cx>, &'c mut T): IoCallbackUnsafe, + { let ret; struct BioGuard<'a, T> { context: &'a mut Context, } - + impl<'a, T> Drop for BioGuard<'a, T> { fn drop(&mut self) { self.context.clear_bio(); @@ -217,7 +217,7 @@ impl Context { unsafe { // Points to `self.inner`, so safe to borrow at the same time as `self.io` let ctx = self.into(); - let mut user_data = (cx, &mut**self.io.as_mut()?); + let mut user_data = (cx, &mut **self.io.as_mut()?); set_bio_raw(ctx, &mut user_data); let guard = BioGuard { context: self }; @@ -231,17 +231,22 @@ impl Context { // This function is created to handle the odd behavior of `mbedtls_ssl_write()` // Please check this https://github.com/Mbed-TLS/mbedtls/issues/4183 to learn more about how `mbedtls_ssl_write()` works in c-mbedtls 2.28 // This function ultimately ensure the semantics: - // Returned value `Ok(n)` always means n bytes of data has been sent into c-mbedtls's buffer (some of them might be sent out through underlying IO) + // Returned value `Ok(n)` always means n bytes of data has been sent into + // c-mbedtls's buffer (some of them might be sent out through underlying IO) pub(super) fn async_write(&mut self, buf: &[u8]) -> Result { while self.handle().out_left > 0 { self.flush_output()?; } // when calling `send()` here, already ensured that `ssl_context.out_left` == 0 match self.send(buf) { - // Although got `Error::SslWantWrite` means underlying IO is blocked, but some of `buf` is still saved into c-mbedtls's - // buffer, so we need to return size of bytes that has been buffered. - // Since we know before this call `out_left` was 0, all buffer (with in the MBEDTLS_SSL_OUT_CONTENT_LEN part) is buffered - Err(Error::SslWantWrite) => Ok(std::cmp::min(unsafe { ssl_get_max_out_record_payload((&*self).into()).into_result()? as usize }, buf.len())), + // Although got `Error::SslWantWrite` means underlying IO is blocked, but some of `buf` is still saved into + // c-mbedtls's buffer, so we need to return size of bytes that has been buffered. + // Since we know before this call `out_left` was 0, all buffer (with in the MBEDTLS_SSL_OUT_CONTENT_LEN part) is + // buffered + Err(Error::SslWantWrite) => Ok(std::cmp::min( + unsafe { ssl_get_max_out_record_payload((&*self).into()).into_result()? as usize }, + buf.len(), + )), res => res, } } @@ -253,13 +258,16 @@ impl Context { /// Upon successful return, the context can be communicated with using the /// `std::io::Read` and `std::io::Write` traits if `io` implements those as /// well, and using the `mbedtls::ssl::io::Io` trait otherwise. - pub fn establish(&mut self, io: T, hostname: Option<&str>) -> Result<()> where T: IoCallbackUnsafe { + pub fn establish(&mut self, io: T, hostname: Option<&str>) -> Result<()> + where + T: IoCallbackUnsafe, + { // SAFETY: In the call to `set_bio_raw`, `self.io` must live as long as // `self`, or until the bio is cleared from `ctx`. It lives as long as // `self` since it is stored in self and never cleared. unsafe { self.prepare_handshake(io, hostname)?; - set_bio_raw(self.into(), &mut**self.io.as_mut().unwrap()); + set_bio_raw(self.into(), &mut **self.io.as_mut().unwrap()); } self.handshake() } @@ -281,15 +289,19 @@ impl Context { impl Context { /// Try to complete the handshake procedure to set up a (D)TLS connection /// - /// In general, this should not be called directly. Instead, [`establish`](Context::establish) - /// should be used which properly sets up the [`IoCallbackUnsafe`] and resets any previous sessions. + /// In general, this should not be called directly. Instead, + /// [`establish`](Context::establish) should be used which properly sets + /// up the [`IoCallbackUnsafe`] and resets any previous sessions. /// - /// This should only be used directly if the handshake could not be completed successfully in - /// `establish`, i.e.: - /// - If using non-blocking operation and `establish` failed with [`Error::SslWantRead`] or + /// This should only be used directly if the handshake could not be + /// completed successfully in `establish`, i.e.: + /// - If using non-blocking operation and `establish` failed with + /// [`Error::SslWantRead`] or /// [`Error::SslWantWrite`] - /// - If running a DTLS server and it answers the first `ClientHello` (without cookie) with a - /// `HelloVerifyRequest`, i.e. `establish` failed with [`Error::SslHelloVerifyRequired`] + /// - If running a DTLS server and it answers the first `ClientHello` + /// (without cookie) with a + /// `HelloVerifyRequest`, i.e. `establish` failed with + /// [`Error::SslHelloVerifyRequired`] pub fn handshake(&mut self) -> Result<()> { match self.inner_handshake() { Ok(()) => Ok(()), @@ -303,7 +315,10 @@ impl Context { // `ssl_session_reset`. let mut client_transport_id = None; if !self.inner.handle().cli_id.is_null() { - client_transport_id = Some(Vec::from(core::slice::from_raw_parts(self.inner.handle().cli_id, self.inner.handle().cli_id_len))); + client_transport_id = Some(Vec::from(core::slice::from_raw_parts( + self.inner.handle().cli_id, + self.inner.handle().cli_id_len, + ))); } ssl_session_reset(self.into()).into_result()?; if let Some(client_id) = client_transport_id.take() { @@ -315,15 +330,13 @@ impl Context { Err(e) => { self.close(); Err(e) - }, + } } } fn inner_handshake(&mut self) -> Result<()> { self.flush_output()?; - unsafe { - ssl_handshake(self.into()).into_result_discard() - } + unsafe { ssl_handshake(self.into()).into_result_discard() } } pub(super) fn flush_output(&mut self) -> Result<()> { @@ -345,11 +358,7 @@ impl Context { fn set_hostname(&mut self, hostname: Option<&str>) -> Result<()> { if let Some(s) = hostname { let cstr = ::std::ffi::CString::new(s).map_err(|_| Error::SslBadInputData)?; - unsafe { - ssl_set_hostname(self.into(), cstr.as_ptr()) - .into_result() - .map(|_| ()) - } + unsafe { ssl_set_hostname(self.into(), cstr.as_ptr()).into_result().map(|_| ()) } } else { Ok(()) } @@ -367,9 +376,7 @@ impl Context { } pub(super) fn close_notify(&mut self) -> Result<()> { - unsafe { - ssl_close_notify(self.into()).into_result().map(|_| ()) - } + unsafe { ssl_close_notify(self.into()).into_result().map(|_| ()) } } pub fn close(&mut self) { @@ -378,14 +385,14 @@ impl Context { } pub(super) fn clear_bio(&mut self) { - // It is safe to set the bio to null using the `ssl_set_bio` function. If the bio - // is null, mbedtls can handle this case and will return an error if you attempt - // to continue using SSL after calling this function. + // It is safe to set the bio to null using the `ssl_set_bio` function. If the + // bio is null, mbedtls can handle this case and will return an error if + // you attempt to continue using SSL after calling this function. unsafe { ssl_set_bio(self.into(), ::core::ptr::null_mut(), None, None, None); } } - + pub(super) fn drop_io(&mut self) { self.clear_bio(); self.io = None; @@ -394,11 +401,11 @@ impl Context { pub fn io(&self) -> Option<&T> { self.io.as_ref().map(|v| &**v) } - + pub fn io_mut(&mut self) -> Option<&mut T> { self.io.as_mut().map(|v| &mut **v) } - + /// Return the minor number of the negotiated TLS version pub fn minor_version(&self) -> i32 { self.handle().minor_ver @@ -424,13 +431,12 @@ impl Context { 1 => Version::Tls1_0, 2 => Version::Tls1_1, 3 => Version::Tls1_2, - _ => unreachable!("unexpected TLS version") + _ => unreachable!("unexpected TLS version"), } } - // Session specific functions - + /// Return the 16-bit ciphersuite identifier. /// All assigned ciphersuites are listed by the IANA in /// @@ -438,7 +444,7 @@ impl Context { if self.handle().session.is_null() { return Err(Error::SslBadInputData); } - + Ok(unsafe { self.handle().session.as_ref().unwrap().ciphersuite as u16 }) } @@ -448,13 +454,16 @@ impl Context { } unsafe { - // We cannot call the peer cert function as we need a pointer to a pointer to create the MbedtlsList, we need something in the heap / cannot use any local variable for that. - let peer_cert : &MbedtlsList = UnsafeFrom::from(&((*self.handle().session).peer_cert) as *const *mut x509_crt as *const *const x509_crt).ok_or(Error::SslBadInputData)?; + // We cannot call the peer cert function as we need a pointer to a pointer to + // create the MbedtlsList, we need something in the heap / cannot use any local + // variable for that. + let peer_cert: &MbedtlsList = + UnsafeFrom::from(&((*self.handle().session).peer_cert) as *const *mut x509_crt as *const *const x509_crt) + .ok_or(Error::SslBadInputData)?; Ok(Some(peer_cert)) } } - #[cfg(feature = "std")] pub fn get_alpn_protocol(&self) -> Result> { unsafe { @@ -490,23 +499,28 @@ impl Context { /// /// See `mbedtls_ssl_set_client_transport_id` /// - /// The `info` is used only for the next connection, i.e. it will be used for the next - /// [`establish`](Context::establish) call. Afterwards, it will be unset again. This is to - /// ensure that no client identification is accidentally reused if this [`Context`] is reused - /// for further connections. + /// The `info` is used only for the next connection, i.e. it will be used + /// for the next [`establish`](Context::establish) call. Afterwards, it + /// will be unset again. This is to ensure that no client identification + /// is accidentally reused if this [`Context`] is reused for further + /// connections. pub fn set_client_transport_id_once(&mut self, info: &[u8]) { self.client_transport_id = Some(info.into()); } pub(super) fn recv(&mut self, buf: &mut [u8]) -> Result { unsafe { - ssl_read(self.into(), buf.as_mut_ptr(), buf.len()).into_result().map(|r| r as usize) + ssl_read(self.into(), buf.as_mut_ptr(), buf.len()) + .into_result() + .map(|r| r as usize) } } pub(super) fn send(&mut self, buf: &[u8]) -> Result { unsafe { - ssl_write(self.into(), buf.as_ptr(), buf.len()).into_result().map(|w| w as usize) + ssl_write(self.into(), buf.as_ptr(), buf.len()) + .into_result() + .map(|w| w as usize) } } } @@ -522,15 +536,18 @@ impl Drop for Context { // // Class exists only during SNI callback that is configured from Config. -// SNI Callback must provide input whose lifetime exceeds the SNI closure to avoid memory corruptions. -// That can be achieved easily by storing certificate chains/CRLs inside the closure for the lifetime of the closure. +// SNI Callback must provide input whose lifetime exceeds the SNI closure to +// avoid memory corruptions. That can be achieved easily by storing certificate +// chains/CRLs inside the closure for the lifetime of the closure. // // That is due to SNI being held by an Arc inside Config. // Config lives longer then Context. Context lives longer then Handshake. // // Alternatives are not possible due to: // - mbedtls not providing any callbacks on handshake finish. -// - no reasonable way to obtain a storage within the sni callback tied to the handshake or to the rust Context. (without resorting to a unscalable map or pointer magic that mbedtls may invalidate) +// - no reasonable way to obtain a storage within the sni callback tied to the +// handshake or to the rust Context. (without resorting to a unscalable map or +// pointer magic that mbedtls may invalidate) // impl HandshakeContext { fn reset_handshake(&mut self) { @@ -539,21 +556,17 @@ impl HandshakeContext { self.handshake_ca_cert = None; self.handshake_crl = None; } - + pub fn set_authmode(&mut self, am: AuthMode) -> Result<()> { if self.inner.handshake as *const _ == ::core::ptr::null() { return Err(Error::SslBadInputData); } - + unsafe { ssl_set_hs_authmode(self.into(), am as i32) } Ok(()) } - pub fn set_ca_list( - &mut self, - chain: Option>>, - crl: Option>, - ) -> Result<()> { + pub fn set_ca_list(&mut self, chain: Option>>, crl: Option>) -> Result<()> { // mbedtls_ssl_set_hs_ca_chain does not check for NULL handshake. if self.inner.handshake as *const _ == ::core::ptr::null() { return Err(Error::SslBadInputData); @@ -563,7 +576,10 @@ impl HandshakeContext { unsafe { ssl_set_hs_ca_chain( self.into(), - chain.as_ref().map(|chain| chain.inner_ffi_mut()).unwrap_or(::core::ptr::null_mut()), + chain + .as_ref() + .map(|chain| chain.inner_ffi_mut()) + .unwrap_or(::core::ptr::null_mut()), crl.as_ref().map(|crl| crl.inner_ffi_mut()).unwrap_or(::core::ptr::null_mut()), ); } @@ -577,11 +593,7 @@ impl HandshakeContext { /// certificates configured in the `Config` associated with this `Context`. /// If this is called at least once, all those are ignored and the set /// specified using this function is used. - pub fn push_cert( - &mut self, - chain: Arc>, - key: Arc, - ) -> Result<()> { + pub fn push_cert(&mut self, chain: Arc>, key: Arc) -> Result<()> { // mbedtls_ssl_set_hs_own_cert does not check for NULL handshake. if self.inner.handshake as *const _ == ::core::ptr::null() || chain.is_empty() { return Err(Error::SslBadInputData); @@ -601,14 +613,17 @@ impl HandshakeContext { #[cfg(test)] mod tests { #[cfg(feature = "std")] - use std::io::{Read,Write, Result as IoResult}; + use std::io::{Read, Result as IoResult, Write}; - use crate::ssl::context::{HandshakeContext, Context}; + use crate::ssl::context::{Context, HandshakeContext}; use crate::tests::TestTrait; - + #[test] fn handshake_context_sync() { - assert!(!TestTrait::::new().impls_trait(), "HandshakeContext must be !Sync"); + assert!( + !TestTrait::::new().impls_trait(), + "HandshakeContext must be !Sync" + ); } struct NonSendSyncStream { @@ -621,7 +636,7 @@ mod tests { unimplemented!() } } - + #[cfg(feature = "std")] impl Write for NonSendSyncStream { fn write(&mut self, _: &[u8]) -> IoResult { @@ -643,7 +658,7 @@ mod tests { unimplemented!() } } - + #[cfg(feature = "std")] impl Write for SendSyncStream { fn write(&mut self, _: &[u8]) -> IoResult { @@ -657,17 +672,40 @@ mod tests { #[test] fn context_send_sync() { - assert!(!TestTrait::::new().impls_trait(), "NonSendSyncStream can't be send"); - assert!(!TestTrait::>::new().impls_trait(), "Context can't be send"); - assert!(!TestTrait::::new().impls_trait(), "NonSendSyncStream can't be sync"); - assert!(!TestTrait::>::new().impls_trait(), "Context can't be sync"); - - assert!(TestTrait::::new().impls_trait(), "SendSyncStream is send"); - assert!(TestTrait::>::new().impls_trait(), "Context is send"); - assert!(TestTrait::::new().impls_trait(), "SendSyncStream is sync"); - assert!(TestTrait::>::new().impls_trait(), "Context is sync"); + assert!( + !TestTrait::::new().impls_trait(), + "NonSendSyncStream can't be send" + ); + assert!( + !TestTrait::>::new().impls_trait(), + "Context can't be send" + ); + assert!( + !TestTrait::::new().impls_trait(), + "NonSendSyncStream can't be sync" + ); + assert!( + !TestTrait::>::new().impls_trait(), + "Context can't be sync" + ); + + assert!( + TestTrait::::new().impls_trait(), + "SendSyncStream is send" + ); + assert!( + TestTrait::>::new().impls_trait(), + "Context is send" + ); + assert!( + TestTrait::::new().impls_trait(), + "SendSyncStream is sync" + ); + assert!( + TestTrait::>::new().impls_trait(), + "Context is sync" + ); } - } // ssl_get_alpn_protocol diff --git a/mbedtls/src/ssl/cookie.rs b/mbedtls/src/ssl/cookie.rs index 17a50ca9b..ee9fab08b 100644 --- a/mbedtls/src/ssl/cookie.rs +++ b/mbedtls/src/ssl/cookie.rs @@ -40,16 +40,18 @@ pub trait CookieCallback { where Self: Sized; - /// Returns a mutable pointer to this shared reference which will be used as first argument to - /// the other two methods + /// Returns a mutable pointer to this shared reference which will be used as + /// first argument to the other two methods /// - /// A mutable pointer is required because the underlying cookie implementation should be - /// allowed to store some information, e.g. mbedtls' implementation uses an internal counter. - /// We only have a shared reference because in general, the `CookieCallback` will be behind an - /// `Arc` (in [`Config`](crate::ssl::Config)). So we need to remove - /// const-ness here which is unsafe in general. Each respective implementation has to - /// guarantee that shared accesses are safe. mbedtls' implementation uses internal mutexes in - /// multithreaded contexts (when the `threading` feature is activated) to do so. + /// A mutable pointer is required because the underlying cookie + /// implementation should be allowed to store some information, e.g. + /// mbedtls' implementation uses an internal counter. We only have a + /// shared reference because in general, the `CookieCallback` will be behind + /// an `Arc` (in [`Config`](crate::ssl::Config)). So + /// we need to remove const-ness here which is unsafe in general. Each + /// respective implementation has to guarantee that shared accesses are + /// safe. mbedtls' implementation uses internal mutexes in multithreaded + /// contexts (when the `threading` feature is activated) to do so. fn data_ptr(&self) -> *mut c_void; } diff --git a/mbedtls/src/ssl/io.rs b/mbedtls/src/ssl/io.rs index fbfa0219d..237468e6d 100644 --- a/mbedtls/src/ssl/io.rs +++ b/mbedtls/src/ssl/io.rs @@ -16,7 +16,7 @@ #[cfg(feature = "std")] use std::{ - io::{Read, Write, Result as IoResult, Error as IoError, ErrorKind as IoErrorKind}, + io::{Error as IoError, ErrorKind as IoErrorKind, Read, Result as IoResult, Write}, net::UdpSocket, result::Result as StdResult, }; @@ -24,18 +24,22 @@ use std::{ use mbedtls_sys::types::raw_types::{c_int, c_uchar, c_void}; use mbedtls_sys::types::size_t; +use super::context::Context; #[cfg(feature = "std")] use crate::error::Error; use crate::error::Result; -use super::context::Context; /// A direct representation of the `mbedtls_ssl_send_t` and `mbedtls_ssl_recv_t` /// callback function pointers. /// /// You probably want to implement `IoCallback` instead. pub trait IoCallbackUnsafe { - unsafe extern "C" fn call_recv(user_data: *mut c_void, data: *mut c_uchar, len: size_t) -> c_int where Self: Sized; - unsafe extern "C" fn call_send(user_data: *mut c_void, data: *const c_uchar, len: size_t) -> c_int where Self: Sized; + unsafe extern "C" fn call_recv(user_data: *mut c_void, data: *mut c_uchar, len: size_t) -> c_int + where + Self: Sized; + unsafe extern "C" fn call_send(user_data: *mut c_void, data: *const c_uchar, len: size_t) -> c_int + where + Self: Sized; fn data_ptr(&mut self) -> *mut c_void; } @@ -119,14 +123,14 @@ impl IoCallback for IO { fn recv(&mut self, buf: &mut [u8]) -> Result { self.read(buf).map_err(|e| match e { ref e if e.kind() == std::io::ErrorKind::WouldBlock => Error::SslWantRead, - _ => Error::NetRecvFailed + _ => Error::NetRecvFailed, }) } fn send(&mut self, buf: &[u8]) -> Result { self.write(buf).map_err(|e| match e { ref e if e.kind() == std::io::ErrorKind::WouldBlock => Error::SslWantWrite, - _ => Error::NetSendFailed + _ => Error::NetSendFailed, }) } } @@ -143,9 +147,7 @@ pub struct ConnectedUdpSocket { impl ConnectedUdpSocket { pub fn connect(socket: UdpSocket, addr: A) -> StdResult { match socket.connect(addr) { - Ok(_) => Ok(ConnectedUdpSocket { - socket, - }), + Ok(_) => Ok(ConnectedUdpSocket { socket }), Err(e) => Err((e, socket)), } } @@ -161,7 +163,7 @@ impl Io for ConnectedUdpSocket { match self.socket.recv(buf) { Ok(i) => Ok(i), Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => Err(Error::SslWantRead), - Err(_) => Err(Error::NetRecvFailed) + Err(_) => Err(Error::NetRecvFailed), } } @@ -181,10 +183,11 @@ impl> Io for Context { } #[cfg(feature = "std")] -/// Implements [`std::io::Read`] whenever T implements `Read`, too. This ensures that -/// `Read`, which is designated for byte-oriented sources, is only implemented when the -/// underlying [`IoCallbackUnsafe`] is byte-oriented, too. Specifically, this means that it is implemented -/// for `Context`, i.e. TLS connections but not for DTLS connections. +/// Implements [`std::io::Read`] whenever T implements `Read`, too. This ensures +/// that `Read`, which is designated for byte-oriented sources, is only +/// implemented when the underlying [`IoCallbackUnsafe`] is byte-oriented, too. +/// Specifically, this means that it is implemented for `Context`, +/// i.e. TLS connections but not for DTLS connections. impl> Read for Context { fn read(&mut self, buf: &mut [u8]) -> IoResult { match self.recv(buf) { @@ -197,10 +200,11 @@ impl> Read for Context { } #[cfg(feature = "std")] -/// Implements [`std::io::Write`] whenever T implements `Write`, too. This ensures that -/// `Write`, which is designated for byte-oriented sinks, is only implemented when the -/// underlying [`IoCallbackUnsafe`] is byte-oriented, too. Specifically, this means that it is implemented -/// for `Context`, i.e. TLS connections but not for DTLS connections. +/// Implements [`std::io::Write`] whenever T implements `Write`, too. This +/// ensures that `Write`, which is designated for byte-oriented sinks, is only +/// implemented when the underlying [`IoCallbackUnsafe`] is byte-oriented, too. +/// Specifically, this means that it is implemented for `Context`, +/// i.e. TLS connections but not for DTLS connections. impl> Write for Context { fn write(&mut self, buf: &[u8]) -> IoResult { match self.send(buf) { diff --git a/mbedtls/src/ssl/mod.rs b/mbedtls/src/ssl/mod.rs index e9b0d173c..e083d94c9 100644 --- a/mbedtls/src/ssl/mod.rs +++ b/mbedtls/src/ssl/mod.rs @@ -6,18 +6,18 @@ * option. This file may not be copied, modified, or distributed except * according to those terms. */ +pub mod async_io; pub mod ciphersuites; pub mod config; pub mod context; pub mod cookie; pub mod io; -pub mod async_io; pub mod ticket; #[doc(inline)] pub use self::ciphersuites::CipherSuite; #[doc(inline)] -pub use self::config::{Config, Version, UseSessionTickets}; +pub use self::config::{Config, UseSessionTickets, Version}; #[doc(inline)] pub use self::context::Context; #[doc(inline)] diff --git a/mbedtls/src/ssl/ticket.rs b/mbedtls/src/ssl/ticket.rs index 438050765..e66331ccf 100644 --- a/mbedtls/src/ssl/ticket.rs +++ b/mbedtls/src/ssl/ticket.rs @@ -9,9 +9,9 @@ #[cfg(feature = "std")] use std::sync::Arc; -use mbedtls_sys::*; use mbedtls_sys::types::raw_types::{c_int, c_uchar, c_void}; use mbedtls_sys::types::size_t; +use mbedtls_sys::*; #[cfg(not(feature = "std"))] use crate::alloc_prelude::*; @@ -27,18 +27,16 @@ pub trait TicketCallback: Sync { end: *const c_uchar, tlen: *mut size_t, lifetime: *mut u32, - ) -> c_int where Self: Sized; - unsafe extern "C" fn call_parse( - p_ticket: *mut c_void, - session: *mut ssl_session, - buf: *mut c_uchar, - len: size_t, - ) -> c_int where Self: Sized; + ) -> c_int + where + Self: Sized; + unsafe extern "C" fn call_parse(p_ticket: *mut c_void, session: *mut ssl_session, buf: *mut c_uchar, len: size_t) -> c_int + where + Self: Sized; fn data_ptr(&self) -> *mut c_void; } - define!( #[c_ty(ssl_ticket_context)] #[repr(C)] @@ -54,23 +52,15 @@ define!( unsafe impl Sync for TicketContext {} impl TicketContext { - pub fn new( - rng: Arc, - cipher: CipherType, - lifetime: u32, - ) -> Result { - - let mut ret = TicketContext { inner: ssl_ticket_context::default(), rng }; + pub fn new(rng: Arc, cipher: CipherType, lifetime: u32) -> Result { + let mut ret = TicketContext { + inner: ssl_ticket_context::default(), + rng, + }; unsafe { ssl_ticket_init(&mut ret.inner); - ssl_ticket_setup( - &mut ret.inner, - Some(T::call), - ret.rng.data_ptr(), - cipher.into(), - lifetime, - ).into_result()?; + ssl_ticket_setup(&mut ret.inner, Some(T::call), ret.rng.data_ptr(), cipher.into(), lifetime).into_result()?; } Ok(ret) @@ -89,12 +79,7 @@ impl TicketCallback for TicketContext { ssl_ticket_write(p_ticket, session, start, end, tlen, lifetime) } - unsafe extern "C" fn call_parse( - p_ticket: *mut c_void, - session: *mut ssl_session, - buf: *mut c_uchar, - len: size_t, - ) -> c_int { + unsafe extern "C" fn call_parse(p_ticket: *mut c_void, session: *mut ssl_session, buf: *mut c_uchar, len: size_t) -> c_int { ssl_ticket_parse(p_ticket, session, buf, len) } diff --git a/mbedtls/src/wrapper_macros.rs b/mbedtls/src/wrapper_macros.rs index 8a3d916ff..6dbeb52a6 100644 --- a/mbedtls/src/wrapper_macros.rs +++ b/mbedtls/src/wrapper_macros.rs @@ -34,7 +34,7 @@ macro_rules! callback { pub trait $m: Send + Sync { unsafe extern "C" fn call(user_data: *mut ::mbedtls_sys::types::raw_types::c_void, $($arg:$ty),*) -> $ret where Self: Sized; - + fn data_ptr(&self) -> *mut ::mbedtls_sys::types::raw_types::c_void; } @@ -172,7 +172,7 @@ macro_rules! define_struct { unsafe impl<$($l)*> Send for $name<$($l)*> {} ); }; - + { << $name:ident $(lifetime $l:tt)* inner $inner:ident >> const init: fn() -> Self = $ctor:ident $({ $($member:ident: $member_init:expr,)* })?; $($defs:tt)* } => { define_struct!(init $name () init $ctor $(lifetime $l)* members $($($member: $member_init,)*)* ); define_struct!(<< $name $(lifetime $l)* inner $inner >> $($defs)*); @@ -297,8 +297,6 @@ macro_rules! getter { }; } - - #[cfg(test)] mod tests { use crate::tests::{TestTrait, Testable}; @@ -313,24 +311,51 @@ mod tests { #[test] fn callback_sync() { fn test_closure() { - assert!(TestTrait::::new().impls_trait(), "RustTest should be Send + Sync"); + assert!( + TestTrait::::new().impls_trait(), + "RustTest should be Send + Sync" + ); } fn test_native_closure() { - assert!(TestTrait::::new().impls_trait(), "NativeTest should be Send + Sync"); + assert!( + TestTrait::::new().impls_trait(), + "NativeTest should be Send + Sync" + ); } fn test_native_mut_closure() { - assert!(TestTrait::::new().impls_trait(), "NativeTestMut should be Send + Sync"); + assert!( + TestTrait::::new().impls_trait(), + "NativeTestMut should be Send + Sync" + ); } - test_closure::()>(); - test_native_closure::()>(); - test_native_mut_closure::()>(); + test_closure:: ()>(); + test_native_closure:: ()>(); + test_native_mut_closure:: ()>(); - assert!(!TestTrait::()>::new().impls_trait(), "non-Sync closure shouldn't be RustTest"); - assert!(TestTrait::() + Send + Sync)>::new().impls_trait(), "Sync closure should be RustTest"); - assert!(!TestTrait::()>::new().impls_trait(), "non-Sync closure shouldn't be NativeTest"); - assert!(TestTrait::() + Send + Sync)>::new().impls_trait(), "Sync closure should be NativeTest"); - assert!(!TestTrait::()>::new().impls_trait(), "non-Sync closure shouldn't be NativeTestMut"); - assert!(TestTrait::() + Send + Sync)>::new().impls_trait(), "Sync closure should be NativeTestMut"); + assert!( + !TestTrait:: ()>::new().impls_trait(), + "non-Sync closure shouldn't be RustTest" + ); + assert!( + TestTrait:: () + Send + Sync)>::new().impls_trait(), + "Sync closure should be RustTest" + ); + assert!( + !TestTrait:: ()>::new().impls_trait(), + "non-Sync closure shouldn't be NativeTest" + ); + assert!( + TestTrait:: () + Send + Sync)>::new().impls_trait(), + "Sync closure should be NativeTest" + ); + assert!( + !TestTrait:: ()>::new().impls_trait(), + "non-Sync closure shouldn't be NativeTestMut" + ); + assert!( + TestTrait:: () + Send + Sync)>::new().impls_trait(), + "Sync closure should be NativeTestMut" + ); } } diff --git a/mbedtls/src/x509/certificate.rs b/mbedtls/src/x509/certificate.rs index 58317acbc..4b79104be 100644 --- a/mbedtls/src/x509/certificate.rs +++ b/mbedtls/src/x509/certificate.rs @@ -10,10 +10,10 @@ use core::fmt; use core::iter::FromIterator; use core::ptr::NonNull; -use mbedtls_sys::*; use mbedtls_sys::types::raw_types::{c_char, c_void}; +use mbedtls_sys::*; -use crate::alloc::{List as MbedtlsList, Box as MbedtlsBox, mbedtls_calloc}; +use crate::alloc::{mbedtls_calloc, Box as MbedtlsBox, List as MbedtlsList}; #[cfg(not(feature = "std"))] use crate::alloc_prelude::*; use crate::error::{Error, IntoResult, Result}; @@ -24,13 +24,13 @@ use crate::rng::Random; use crate::x509::{self, Crl, Time, VerifyCallback}; #[cfg(feature = "std")] -use yasna::{BERDecodable, BERReader, ASN1Result, ASN1Error, ASN1ErrorKind, models::ObjectIdentifier}; +use yasna::{models::ObjectIdentifier, ASN1Error, ASN1ErrorKind, ASN1Result, BERDecodable, BERReader}; -#[derive(Debug,Copy,Clone,Eq,PartialEq)] +#[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum CertificateVersion { V1, V2, - V3 + V3, } #[cfg(feature = "std")] @@ -53,7 +53,6 @@ impl BERDecodable for Extension { } } - define!( #[c_ty(x509_crt)] #[repr(transparent)] @@ -80,10 +79,17 @@ fn x509_time_to_time(tm: &x509_time) -> Result