diff --git a/mbedtls-platform-support/build.rs b/mbedtls-platform-support/build.rs index 9e0431066..44126d7b7 100644 --- a/mbedtls-platform-support/build.rs +++ b/mbedtls-platform-support/build.rs @@ -12,11 +12,11 @@ use std::env; fn main() { let env_components = env::var("DEP_MBEDTLS_PLATFORM_COMPONENTS").unwrap(); let mut sys_platform_components = HashMap::<_, HashSet<_>>::new(); - for mut kv in env_components.split(",").map(|component| component.splitn(2, "=")) { + for mut kv in env_components.split(',').map(|component| component.splitn(2, '=')) { let k = kv.next().unwrap(); let v = kv.next().unwrap(); sys_platform_components.entry(k).or_insert_with(Default::default).insert(v); - println!(r#"cargo:rustc-cfg=sys_{}="{}""#, k, v); + println!(r#"cargo:rustc-cfg=sys_{k}="{v}""#); } let mut b = cc::Build::new(); diff --git a/mbedtls-platform-support/src/lib.rs b/mbedtls-platform-support/src/lib.rs index 5243b991a..25d229f9d 100644 --- a/mbedtls-platform-support/src/lib.rs +++ b/mbedtls-platform-support/src/lib.rs @@ -6,6 +6,7 @@ * option. This file may not be copied, modified, or distributed except * according to those terms. */ +#![allow(unexpected_cfgs)] #![cfg_attr(not(feature = "std"), no_std)] #[cfg(not(feature = "std"))] diff --git a/mbedtls-platform-support/src/self_test.rs b/mbedtls-platform-support/src/self_test.rs index 12806ce44..51ab8c7fc 100644 --- a/mbedtls-platform-support/src/self_test.rs +++ b/mbedtls-platform-support/src/self_test.rs @@ -6,15 +6,15 @@ * option. This file may not be copied, modified, or distributed except * according to those terms. */ -//! MbedTLS self tests. +//! `MbedTLS` self tests. //! -//! Calling MbedTLS self test functions before they're enabled using the +//! 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 test failures. Make sure no other code uses `MbedTLS` while running the //! self tests. Multiple self test operations done simultaneously may also //! return failures. @@ -53,7 +53,7 @@ pub unsafe extern "C" fn rand() -> c_int { rand_f.expect("Called self-test rand without enabling self-test")() } -/// Set callback functions to enable the MbedTLS self tests. +/// 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. @@ -94,7 +94,7 @@ pub unsafe fn disable() { /// # Safety /// /// The caller needs to ensure this function is not called while *any other* -/// MbedTLS function is called. See the module documentation for more +/// `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, diff --git a/mbedtls-sys/build/bindgen.rs b/mbedtls-sys/build/bindgen.rs index a69f84d09..992179384 100644 --- a/mbedtls-sys/build/bindgen.rs +++ b/mbedtls-sys/build/bindgen.rs @@ -35,7 +35,7 @@ impl bindgen::callbacks::ParseCallbacks for MbedtlsParseCallbacks { } fn int_macro(&self, _name: &str, value: i64) -> Option { - if value < (i32::MIN as i64) || value > (i32::MAX as i64) { + if value < i64::from(i32::MIN) || value > i64::from(i32::MAX) { Some(bindgen::callbacks::IntKind::LongLong) } else { Some(bindgen::callbacks::IntKind::Int) @@ -87,7 +87,7 @@ fn generate_deprecated_union_accessors(bindings: &str) -> String { } let mut impl_builder = UnionImplBuilder::default(); - syn::visit::visit_file(&mut impl_builder, &syn::parse_file(&bindings).unwrap()); + syn::visit::visit_file(&mut impl_builder, &syn::parse_file(bindings).unwrap()); impl_builder.impls } @@ -96,7 +96,7 @@ impl super::BuildConfig { pub fn bindgen(&self) { let mut input = String::new(); for h in headers::enabled_ordered() { - let _ = writeln!(input, "#include ", h); + let _ = writeln!(input, "#include "); } let mut cc = cc::Build::new(); @@ -115,14 +115,12 @@ impl super::BuildConfig { // uses the correct headers let compiler = cc.get_compiler(); if compiler.is_like_gnu() { - let output = compiler.to_command().args(&["--print-sysroot"]).output(); - 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); - cc.flag(&format!("--sysroot={}", trimmed_path)); - } - _ => {} // skip toolchains without a configured sysroot + let output = compiler.to_command().args(["--print-sysroot"]).output(); + // skip toolchains without a configured sysroot + if let Ok(sysroot) = output { + let path = std::str::from_utf8(&sysroot.stdout).expect("Malformed sysroot"); + let trimmed_path = path.strip_suffix("\r\n").or_else(|| path.strip_suffix("\n")).unwrap_or(path); + cc.flag(&format!("--sysroot={trimmed_path}")); }; } @@ -146,7 +144,28 @@ impl super::BuildConfig { .derive_default(true) .prepend_enum_name(false) .translate_enum_integer_types(true) - .raw_line("#![allow(dead_code, deref_nullptr, non_snake_case, non_camel_case_types, non_upper_case_globals, invalid_value)]") + .raw_line("#![allow(") + .raw_line(" dead_code,") + .raw_line(" deref_nullptr,") + .raw_line(" invalid_value,") + .raw_line(" non_snake_case,") + .raw_line(" non_camel_case_types,") + .raw_line(" non_upper_case_globals") + .raw_line(")]") + .raw_line("#![allow(") + .raw_line(" clippy::cast_lossless,") + .raw_line(" clippy::cast_possible_truncation,") + .raw_line(" clippy::default_trait_access,") + .raw_line(" clippy::missing_safety_doc,") + .raw_line(" clippy::must_use_candidate,") + .raw_line(" clippy::pub_underscore_fields,") + .raw_line(" clippy::unreadable_literal,") + .raw_line(" clippy::used_underscore_binding,") + .raw_line(" clippy::useless_transmute,") + .raw_line(" clippy::semicolon_if_nothing_returned,") + .raw_line(" clippy::type_complexity,") + .raw_line(" clippy::wildcard_imports") + .raw_line(")]") .generate() .expect("bindgen error") .to_string(); diff --git a/mbedtls-sys/build/build.rs b/mbedtls-sys/build/build.rs index 0cacf32c2..619deffc1 100644 --- a/mbedtls-sys/build/build.rs +++ b/mbedtls-sys/build/build.rs @@ -5,6 +5,7 @@ * 2.0 , at your * option. This file may not be copied, modified, or distributed except * according to those terms. */ +#![allow(clippy::unwrap_used)] extern crate bindgen; extern crate cmake; @@ -82,7 +83,7 @@ impl BuildConfig { fn new() -> Self { let out_dir = PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR environment not set?")); let config_h = out_dir.join("config.h"); - let mbedtls_src = PathBuf::from(env::var("RUST_MBEDTLS_SYS_SOURCE").unwrap_or("vendor".to_owned())); + let mbedtls_src = PathBuf::from(env::var("RUST_MBEDTLS_SYS_SOURCE").unwrap_or_else(|_| "vendor".to_owned())); let mbedtls_include = mbedtls_src.join("include"); let mut cflags = vec![]; @@ -93,11 +94,11 @@ impl BuildConfig { cflags.push("-fno-stack-protector".into()); } - BuildConfig { - config_h, + Self { out_dir, mbedtls_src, mbedtls_include, + config_h, cflags, } } diff --git a/mbedtls-sys/build/cmake.rs b/mbedtls-sys/build/cmake.rs index 92232fe71..4e0d07d1f 100644 --- a/mbedtls-sys/build/cmake.rs +++ b/mbedtls-sys/build/cmake.rs @@ -29,9 +29,7 @@ impl super::BuildConfig { } println!("cargo:rerun-if-env-changed=RUST_MBED_C_COMPILER_BAREMETAL"); - let c_compiler_baremetal = std::env::var("RUST_MBED_C_COMPILER_BAREMETAL") - .map(|val| val == "1") - .unwrap_or_default(); + let c_compiler_baremetal = std::env::var("RUST_MBED_C_COMPILER_BAREMETAL").is_ok_and(|val| val == "1"); 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, diff --git a/mbedtls-sys/build/config.rs b/mbedtls-sys/build/config.rs index f7bcdac5a..7388b020f 100644 --- a/mbedtls-sys/build/config.rs +++ b/mbedtls-sys/build/config.rs @@ -15,28 +15,28 @@ pub enum Macro { #[allow(dead_code)] DefinedAs(&'static str), } -use self::Macro::*; +use self::Macro::{Defined, DefinedAs, Undefined}; impl Macro { pub fn define(self, name: &'static str) -> String { match self { Undefined => String::new(), - Defined => format!("#define {}\n", name), - DefinedAs(v) => format!("#define {} {}\n", name, v), + Defined => format!("#define {name}\n"), + DefinedAs(v) => format!("#define {name} {v}\n"), } } } pub type CDefine = (&'static str, Macro); -pub const PREFIX: &'static str = r#" +pub const PREFIX: &str = r" #ifndef MBEDTLS_CONFIG_H #define MBEDTLS_CONFIG_H #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) #define _CRT_SECURE_NO_DEPRECATE 1 #endif -"#; +"; /* @@ -64,8 +64,8 @@ for line in open('vendor/include/mbedtls/config.h').readlines(): print format(match.group(1), "Undefined") + (" // default: %s" % (match.group(2))) */ -#[cfg_attr(rustfmt, rustfmt_skip)] -const DEFAULT_DEFINES: &'static [CDefine] = &[ +#[rustfmt::skip] +const DEFAULT_DEFINES: &[CDefine] = &[ ("MBEDTLS_HAVE_ASM", Defined), ("MBEDTLS_NO_UDBL_DIVISION", Undefined), ("MBEDTLS_NO_64BIT_MULTIPLICATION", Undefined), @@ -408,17 +408,20 @@ const DEFAULT_DEFINES: &'static [CDefine] = &[ pub fn default_defines() -> HashMap<&'static str, Macro> { let mut defines = HashMap::new(); - for (key, value) in DEFAULT_DEFINES.iter() { - if defines.insert(*key, *value).is_some() { - panic!("Duplicate default define in {}: {}", file!(), key); - } + for (key, value) in DEFAULT_DEFINES { + assert!( + defines.insert(*key, *value).is_none(), + "Duplicate default define in {}: {}", + file!(), + key + ); } defines } -#[cfg_attr(rustfmt, rustfmt_skip)] -pub const FEATURE_DEFINES: &'static [(&'static str, CDefine)] = &[ +#[rustfmt::skip] +pub const FEATURE_DEFINES: &[(&str, CDefine)] = &[ ("time", ("MBEDTLS_HAVE_TIME", Defined)), ("time", ("MBEDTLS_HAVE_TIME_DATE", Defined)), ("havege", ("MBEDTLS_HAVEGE_C", Defined)), @@ -442,8 +445,8 @@ pub const FEATURE_DEFINES: &'static [(&'static str, CDefine)] = &[ ("trusted_cert_callback", ("MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK", Defined)), ]; -#[cfg_attr(rustfmt, rustfmt_skip)] -pub const PLATFORM_DEFINES: &'static [(&'static str, &'static str, CDefine)] = &[ +#[rustfmt::skip] +pub const PLATFORM_DEFINES: &[(&str, &str, CDefine)] = &[ ("time", "libc", ("MBEDTLS_TIMING_C", Defined)), ("time", "custom", ("MBEDTLS_PLATFORM_TIME_MACRO", DefinedAs("mbedtls_time"))), ("time", "custom", ("MBEDTLS_PLATFORM_TIME_TYPE_MACRO", DefinedAs("long long"))), @@ -456,7 +459,7 @@ pub const PLATFORM_DEFINES: &'static [(&'static str, &'static str, CDefine)] = & ("std", "entropy", ("MBEDTLS_ENTROPY_C", Defined)), ]; -pub const SUFFIX: &'static str = r#" +pub const SUFFIX: &str = r#" #if defined(TARGET_LIKE_MBED) #include "mbedtls/target_config.h" #endif diff --git a/mbedtls-sys/build/features.rs b/mbedtls-sys/build/features.rs index 6006bc0b6..05156e022 100644 --- a/mbedtls-sys/build/features.rs +++ b/mbedtls-sys/build/features.rs @@ -59,7 +59,7 @@ impl Features { for (feature, components) in &self.platform_components { for component in components { - println!(r#"cargo:rustc-cfg={}_component="{}""#, feature, component); + println!(r#"cargo:rustc-cfg={feature}_component="{component}""#); } } println!( @@ -69,7 +69,7 @@ impl Features { .flat_map(|(feature, components)| { components .iter() - .map(move |component| format!(r#"{}_component={}"#, feature, component)) + .map(move |component| format!(r#"{feature}_component={component}"#)) }) .collect::>() .join(",") @@ -78,7 +78,9 @@ impl Features { fn with_feature(&mut self, feature: &'static str) -> Option<&mut HashSet<&'static str>> { if self.have_feature(feature) { - Some(self.platform_components.entry(feature).or_insert_with(HashSet::new)) + Some(self.platform_components.entry(feature).or_default()) + //This should be the same + //Some(self.platform_components.entry(feature).or_insert_with(HashSet::new)) } else { None } @@ -96,11 +98,11 @@ impl Features { } fn env_have_target_cfg(var: &'static str, value: &'static str) -> bool { - let env = format!("CARGO_CFG_TARGET_{}", var).to_uppercase().replace("-", "_"); + let env = format!("CARGO_CFG_TARGET_{var}").to_uppercase().replace('-', "_"); env::var_os(env).map_or(false, |s| s == value) } fn env_have_feature(feature: &'static str) -> bool { - let env = format!("CARGO_FEATURE_{}", feature).to_uppercase().replace("-", "_"); + let env = format!("CARGO_FEATURE_{feature}").to_uppercase().replace('-', "_"); env::var_os(env).is_some() } diff --git a/mbedtls-sys/build/headers.rs b/mbedtls-sys/build/headers.rs index 8af3f0271..46441a625 100644 --- a/mbedtls-sys/build/headers.rs +++ b/mbedtls-sys/build/headers.rs @@ -25,8 +25,8 @@ use crate::features::FEATURES; * ) */ -#[cfg_attr(rustfmt, rustfmt_skip)] -pub const ORDERED: &'static [(Option<&'static str>, &'static str)] = &[ +#[rustfmt::skip] +pub const ORDERED: &[(Option<&'static str>, &str)] = &[ (None, "config_psa.h"), (None, "platform_time.h"), (None, "platform_util.h"), diff --git a/mbedtls-sys/src/lib.rs b/mbedtls-sys/src/lib.rs index e25f70274..e0e2b0be3 100644 --- a/mbedtls-sys/src/lib.rs +++ b/mbedtls-sys/src/lib.rs @@ -6,6 +6,7 @@ * option. This file may not be copied, modified, or distributed except * according to those terms. */ +#![allow(unexpected_cfgs)] #![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "std")] extern crate core; diff --git a/mbedtls-sys/src/types.rs b/mbedtls-sys/src/types.rs index 8672febd7..dc62cc832 100644 --- a/mbedtls-sys/src/types.rs +++ b/mbedtls-sys/src/types.rs @@ -6,7 +6,7 @@ * option. This file may not be copied, modified, or distributed except * according to those terms. */ -#![allow(non_camel_case_types)] +#![allow(non_camel_case_types, clippy::module_name_repetitions)] pub type int8_t = i8; pub type int16_t = i16; diff --git a/mbedtls/build.rs b/mbedtls/build.rs index 1c4fa76c9..3b21dd561 100644 --- a/mbedtls/build.rs +++ b/mbedtls/build.rs @@ -5,6 +5,7 @@ * 2.0 , at your * option. This file may not be copied, modified, or distributed except * according to those terms. */ +#![allow(clippy::unwrap_used)] use std::collections::hash_map::DefaultHasher; use std::collections::{HashMap, HashSet}; @@ -14,8 +15,8 @@ use rustc_version::Channel; use std::env; /// Retrieves or generates a metadata value used for symbol name mangling to ensure unique C symbols. -/// When building with Cargo, the metadata value is extracted from the OUT_DIR environment variable. -/// For Bazel builds, this method generate the suffix by hashing part of the crate OUT_DIR, +/// When building with Cargo, the metadata value is extracted from the `OUT_DIR` environment variable. +/// For Bazel builds, this method generate the suffix by hashing part of the crate `OUT_DIR`, /// which are sufficient for ensuring symbol uniqueness. fn get_compilation_symbol_suffix() -> String { let out_dir: std::path::PathBuf = std::env::var_os("OUT_DIR").unwrap().into(); @@ -31,7 +32,7 @@ fn get_compilation_symbol_suffix() -> String { crate_.starts_with("mbedtls-"), "Expected second to last component of OUT_DIR to start with 'mbedtls-'" ); - return crate_[8..].to_owned(); // Return the part after "mbedtls-" + crate_[8..].to_owned() // Return the part after "mbedtls-" } else if out_dir.iter().rfind(|p| *p == "bazel-out").is_some() { // If Bazel is used as build system. let mut hasher = DefaultHasher::new(); @@ -39,7 +40,7 @@ fn get_compilation_symbol_suffix() -> String { for p in out_dir.iter().rev().take_while(|p| *p != "bazel-out") { p.hash(&mut hasher); } - return format!("{:016x}", hasher.finish()); + format!("{:016x}", hasher.finish()) } else { panic!("unexpected OUT_DIR format: {}", out_dir.display()); } @@ -51,16 +52,16 @@ fn main() { println!("cargo:rustc-cfg=nightly"); } let symbol_suffix = get_compilation_symbol_suffix(); - println!("cargo:rustc-env=RUST_MBEDTLS_SYMBOL_SUFFIX={}", symbol_suffix); + println!("cargo:rustc-env=RUST_MBEDTLS_SYMBOL_SUFFIX={symbol_suffix}"); println!("cargo:rerun-if-env-changed=CARGO_PKG_VERSION"); let env_components = env::var("DEP_MBEDTLS_PLATFORM_COMPONENTS").unwrap(); let mut sys_platform_components = HashMap::<_, HashSet<_>>::new(); - for mut kv in env_components.split(",").map(|component| component.splitn(2, "=")) { + for mut kv in env_components.split(',').map(|component| component.splitn(2, '=')) { let k = kv.next().unwrap(); let v = kv.next().unwrap(); sys_platform_components.entry(k).or_insert_with(Default::default).insert(v); - println!(r#"cargo:rustc-cfg=sys_{}="{}""#, k, v); + println!(r#"cargo:rustc-cfg=sys_{k}="{v}""#); } let mut b = cc::Build::new(); diff --git a/mbedtls/src/alloc.rs b/mbedtls/src/alloc.rs index c3433b141..ec74d43e6 100644 --- a/mbedtls/src/alloc.rs +++ b/mbedtls/src/alloc.rs @@ -60,7 +60,7 @@ impl Drop for Box { fn drop(&mut self) { unsafe { drop_in_place(self.inner.as_ptr()); - mbedtls_free(self.inner.as_ptr() as *mut c_void) + mbedtls_free(self.inner.as_ptr() as *mut c_void); } } } @@ -80,6 +80,7 @@ pub struct CString { } impl CString { + #[must_use] pub fn new(str: &str) -> Self { unsafe { let buff = crate::alloc::mbedtls_calloc(1, str.len() + 1) as *mut u8; diff --git a/mbedtls/src/bignum/mod.rs b/mbedtls/src/bignum/mod.rs index 0df9e7bc6..88c651108 100644 --- a/mbedtls/src/bignum/mod.rs +++ b/mbedtls/src/bignum/mod.rs @@ -30,7 +30,7 @@ define!( fn fmt_mpi(n: &Mpi, radix: i32) -> String { n.to_string_radix(radix) - .unwrap_or("(failed to format multi-precision integer)".to_owned()) + .unwrap_or_else(|_| "(failed to format multi-precision integer)".to_owned()) } impl Display for Mpi { @@ -67,7 +67,7 @@ impl Binary for Mpi { impl ::core::str::FromStr for Mpi { type Err = Error; - fn from_str(s: &str) -> Result { + fn from_str(s: &str) -> Result { let is_hex = s.starts_with("0x"); let radix = if is_hex { 16 } else { 10 }; let skip = if is_hex { 2 } else { 0 }; @@ -90,49 +90,46 @@ pub enum Sign { impl Clone for Mpi { fn clone(&self) -> Self { - Mpi::copy(&self.handle()).expect("copy succeeded") + Self::copy(self.handle()).expect("copy succeeded") } } impl Mpi { - pub(crate) fn copy(value: &mpi) -> Result { + pub(crate) fn copy(value: &mpi) -> Result { let mut ret = Self::init(); unsafe { mpi_copy(&mut ret.inner, value) }.into_result()?; Ok(ret) } - pub fn new(value: mpi_sint) -> Result { + pub fn new(value: mpi_sint) -> Result { let mut ret = Self::init(); unsafe { mpi_lset(&mut ret.inner, value) }.into_result()?; Ok(ret) } /// Initialize an MPI number from big endian binary data - pub fn from_binary(num: &[u8]) -> Result { + pub fn from_binary(num: &[u8]) -> Result { let mut ret = Self::init(); unsafe { mpi_read_binary(&mut ret.inner, num.as_ptr(), num.len()) }.into_result()?; Ok(ret) } + #[must_use] pub fn get_bit(&self, bit: usize) -> bool { // does not fail - if unsafe { mpi_get_bit(&self.inner, bit) } == 1 { - true - } else { - false - } + (unsafe { mpi_get_bit(&self.inner, bit) } == 1) } pub fn set_bit(&mut self, bit: usize, val: bool) -> Result<()> { unsafe { - mpi_set_bit(&mut self.inner, bit, val as u8).into_result()?; + mpi_set_bit(&mut self.inner, bit, u8::from(val)).into_result()?; } Ok(()) } fn get_limb(&self, n: usize) -> mpi_uint { if n < self.inner.n { - unsafe { *self.inner.p.offset(n as isize) } + unsafe { *self.inner.p.add(n) } } else { // zero pad 0 @@ -142,19 +139,19 @@ impl Mpi { /// Checks if an [`Mpi`] is less than the other in constant time. /// /// Will return [`Error::MpiBadInputData`] if the allocated length of the two input [`Mpi`]s is not the same. - pub fn less_than_const_time(&self, other: &Mpi) -> Result { + pub fn less_than_const_time(&self, other: &Self) -> Result { mpi_inner_less_than_const_time(&self.inner, &other.inner) } /// Compares an [`Mpi`] with the other in constant time. /// /// Will return [`Error::MpiBadInputData`] if the allocated length of the two input [`Mpi`]s is not the same. - pub fn cmp_const_time(&self, other: &Mpi) -> Result { + pub fn cmp_const_time(&self, other: &Self) -> Result { mpi_inner_cmp_const_time(&self.inner, &other.inner) } /// Checks equalness with the other in constant time. - pub fn eq_const_time(&self, other: &Mpi) -> Result { + pub fn eq_const_time(&self, other: &Self) -> Result { mpi_inner_eq_const_time(&self.inner, &other.inner) } @@ -167,14 +164,13 @@ impl Mpi { Ok(self.get_limb(0) as u32) } + #[must_use] pub fn sign(&self) -> Sign { let cmp = unsafe { mpi_cmp_int(&self.inner, 0) }; - if cmp < 0 { - Sign::Negative - } else if cmp == 0 { - Sign::Zero - } else { - Sign::Positive + match cmp.cmp(&0) { + Ordering::Greater => Sign::Positive, + Ordering::Less => Sign::Negative, + Ordering::Equal => Sign::Zero, } } @@ -192,7 +188,7 @@ impl Mpi { // There is a null terminator plus (possibly) some garbage data. Remove it if let Some(idx) = buf.iter().position(|&b| b == 0) { - buf.truncate(idx) + buf.truncate(idx); } Ok(String::from_utf8(buf).expect("radix-N data is valid UTF8")) @@ -206,14 +202,14 @@ impl Mpi { Ok(ret) } - /// Serialize the MPI as big endian binary data, padding to at least min_len + /// 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().add(pad_len), len).into_result() }?; Ok(ret) } @@ -229,7 +225,7 @@ impl Mpi { Ok(l) } - pub fn divrem(&self, other: &Mpi) -> Result<(Mpi, Mpi)> { + pub fn divrem(&self, other: &Self) -> Result<(Self, Self)> { 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()?; @@ -237,20 +233,20 @@ impl Mpi { } /// Reduce self modulo other - pub fn modulo(&self, other: &Mpi) -> Result { + pub fn modulo(&self, other: &Self) -> Result { let mut ret = Self::init(); unsafe { mpi_mod_mpi(&mut ret.inner, &self.inner, &other.inner) }.into_result()?; Ok(ret) } - pub fn divrem_int(&self, other: mpi_sint) -> Result<(Mpi, Mpi)> { + pub fn divrem_int(&self, other: mpi_sint) -> Result<(Self, Self)> { let mut q = Self::init(); let mut r = Self::init(); unsafe { mpi_div_int(&mut q.inner, &mut r.inner, &self.inner, other) }.into_result()?; Ok((q, r)) } - pub fn modinv(&self, modulus: &Mpi) -> Result { + pub fn modinv(&self, modulus: &Self) -> Result { let mut r = Self::init(); unsafe { mpi_inv_mod(&mut r.inner, &self.inner, &modulus.inner) }.into_result()?; Ok(r) @@ -260,8 +256,8 @@ impl Mpi { /// /// The modulus must be prime; computing a square root modulo /// a composite number is equivalent to factoring the composite. - pub fn mod_sqrt(&self, p: &Mpi) -> Result { - let zero = Mpi::new(0)?; + pub fn mod_sqrt(&self, p: &Self) -> Result { + let zero = Self::new(0)?; if self < &zero || self >= p { return Err(Error::MpiBadInputData); @@ -272,7 +268,7 @@ impl Mpi { // This ignores p=2 (for which this algorithm is valid), as not // cryptographically interesting. - if p.get_bit(0) == false || p <= &zero { + if !p.get_bit(0) || p <= &zero { return Err(Error::MpiBadInputData); } @@ -299,7 +295,7 @@ impl Mpi { /* Find a random quadratic nonresidue mod p. */ - let mut n = Mpi::new(2)?; + let mut n = Self::new(2)?; while n.jacobi(p)? != -1 { n += 1; } @@ -309,8 +305,8 @@ impl Mpi { let mut g = n.mod_exp(&s, p)?; let mut r = e; - let one = Mpi::new(1)?; - let two = Mpi::new(2)?; + let one = Self::new(1)?; + let two = Self::new(2)?; loop { if b == one { @@ -342,10 +338,11 @@ impl Mpi { } } + #[must_use] pub fn trailing_zeros(&self) -> usize { let mut low_zero = 0; - while self.get_bit(low_zero) == false { + while !self.get_bit(low_zero) { low_zero += 1; } @@ -353,11 +350,11 @@ impl Mpi { } /// Calculates Jacobi symbol (self|N) - pub fn jacobi(&self, n: &Mpi) -> Result { - let zero = Mpi::new(0)?; - let one = Mpi::new(1)?; + pub fn jacobi(&self, n: &Self) -> Result { + let zero = Self::new(0)?; + let one = Self::new(1)?; - if self < &zero || n < &zero || n.get_bit(0) == false { + if self < &zero || n < &zero || !n.get_bit(0) { return Err(Error::MpiBadInputData); } @@ -366,7 +363,7 @@ impl Mpi { let mut j: i32 = 1; - while &y > &one { + while y > one { x = x.modulo(&y)?; if x > (&y / 2)? { x = (&y - &x)?; @@ -385,7 +382,7 @@ impl Mpi { if trailing_zeros % 2 == 1 { let y_mod_8 = (&y % 8)?.as_u32()?; if y_mod_8 == 3 || y_mod_8 == 5 { - j = -j + j = -j; } } @@ -400,7 +397,7 @@ impl Mpi { } /// Return (self^exponent) % n - pub fn mod_exp(&self, exponent: &Mpi, modulus: &Mpi) -> Result { + pub fn mod_exp(&self, exponent: &Self, modulus: &Self) -> Result { let mut r = Self::init(); unsafe { mpi_exp_mod( @@ -419,7 +416,7 @@ impl Mpi { /// The Miller-Rabin primality test with k rounds. Returns /// `MpiNotAcceptable` if self is definitely not prime. If no error is /// returned, self is prime with a probability of 1 - 1/2^{2k}. See - /// mbedtls_mpi_is_prime. + /// `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()?; @@ -458,7 +455,7 @@ fn mpi_inner_less_than_const_time(x: &mpi, y: &mpi) -> Result { } impl Ord for Mpi { - fn cmp(&self, other: &Mpi) -> Ordering { + fn cmp(&self, other: &Self) -> Ordering { let r = unsafe { mpi_cmp_mpi(&self.inner, &other.inner) }; match r { -1 => Ordering::Less, @@ -470,13 +467,13 @@ impl Ord for Mpi { } impl PartialOrd for Mpi { - fn partial_cmp(&self, other: &Mpi) -> Option { + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl PartialEq for Mpi { - fn eq(&self, other: &Mpi) -> bool { + fn eq(&self, other: &Self) -> bool { self.cmp(other) == Ordering::Equal } } @@ -566,11 +563,11 @@ 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) { +impl<'a> DivAssign<&'a Self> for Mpi { + fn div_assign(&mut self, other: &Self) { // mpi_div_mpi produces incorrect output when arguments alias, so avoid doing // that - let mut q = Mpi::init(); + let mut q = Self::init(); unsafe { mpi_div_mpi(&mut q.inner, ::core::ptr::null_mut(), &self.inner, other.handle()) } .into_result() .expect("mpi_div_mpi success"); @@ -579,11 +576,11 @@ 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) { +impl DivAssign for Mpi { + fn div_assign(&mut self, other: Self) { // mpi_div_mpi produces incorrect output when arguments alias, so avoid doing // that - let mut q = Mpi::init(); + let mut q = Self::init(); unsafe { mpi_div_mpi(&mut q.inner, ::core::ptr::null_mut(), &self.inner, other.handle()) } .into_result() .expect("mpi_div_mpi success"); @@ -628,10 +625,10 @@ impl<'a> Rem for &'a Mpi { } impl Rem for Mpi { - type Output = Result; + type Output = Result; - fn rem(self, other: mpi_sint) -> Result { - let mut r = Mpi::init(); + fn rem(self, other: mpi_sint) -> Result { + let mut r = Self::init(); unsafe { mpi_div_int(::core::ptr::null_mut(), &mut r.inner, &self.inner, other) }.into_result()?; Ok(r) } @@ -648,11 +645,11 @@ 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) { +impl<'a> RemAssign<&'a Self> for Mpi { + fn rem_assign(&mut self, other: &Self) { // mpi_div_mpi produces incorrect output when arguments alias, so avoid doing // that - let mut r = Mpi::init(); + let mut r = Self::init(); unsafe { mpi_div_mpi(::core::ptr::null_mut(), &mut r.inner, &self.inner, other.handle()) } .into_result() .expect("mpi_div_mpi success"); @@ -661,11 +658,11 @@ 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) { +impl RemAssign for Mpi { + fn rem_assign(&mut self, other: Self) { // mpi_div_mpi produces incorrect output when arguments alias, so avoid doing // that - let mut r = Mpi::init(); + let mut r = Self::init(); unsafe { mpi_div_mpi(::core::ptr::null_mut(), &mut r.inner, &self.inner, other.handle()) } .into_result() .expect("mpi_div_mpi success"); @@ -700,10 +697,10 @@ impl<'a> Shl for &'a Mpi { } impl Shl for Mpi { - type Output = Result; + type Output = Result; - fn shl(self, shift: usize) -> Result { - let mut r = Mpi::copy(self.handle())?; + fn shl(self, shift: usize) -> Result { + let mut r = Self::copy(self.handle())?; unsafe { mpi_shift_l(&mut r.inner, shift) }.into_result()?; Ok(r) } @@ -728,10 +725,10 @@ impl<'a> Shr for &'a Mpi { } impl Shr for Mpi { - type Output = Result; + type Output = Result; - fn shr(self, shift: usize) -> Result { - let mut r = Mpi::copy(self.handle())?; + fn shr(self, shift: usize) -> Result { + let mut r = Self::copy(self.handle())?; unsafe { mpi_shift_r(&mut r.inner, shift) }.into_result()?; Ok(r) } diff --git a/mbedtls/src/cipher/mod.rs b/mbedtls/src/cipher/mod.rs index acdd038b5..439080c71 100644 --- a/mbedtls/src/cipher/mod.rs +++ b/mbedtls/src/cipher/mod.rs @@ -6,6 +6,7 @@ * option. This file may not be copied, modified, or distributed except * according to those terms. */ +#![allow(non_local_definitions)] use core::marker::PhantomData; use core::ops::Range; pub mod raw; @@ -41,34 +42,31 @@ pub trait Type { pub enum TraditionalNoIv {} impl Type for TraditionalNoIv { fn is_valid_mode(mode: raw::CipherMode) -> bool { - match mode { - raw::CipherMode::ECB => true, - _ => false, - } + matches!(mode, raw::CipherMode::ECB) } } 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, - _ => false, - } + matches!( + mode, + raw::CipherMode::CBC | raw::CipherMode::CFB | raw::CipherMode::OFB | raw::CipherMode::CTR + ) } } pub enum Authenticated {} impl Type for Authenticated { fn is_valid_mode(mode: raw::CipherMode) -> bool { - match mode { + matches!( + mode, raw::CipherMode::GCM - | raw::CipherMode::CCM - | raw::CipherMode::KW - | raw::CipherMode::KWP - | raw::CipherMode::CHACHAPOLY => true, - _ => false, - } + | raw::CipherMode::CCM + | raw::CipherMode::KW + | raw::CipherMode::KWP + | raw::CipherMode::CHACHAPOLY + ) } } @@ -112,14 +110,17 @@ impl Cipher { } } + #[must_use] pub fn block_size(&self) -> usize { self.raw_cipher.block_size() } + #[must_use] pub fn iv_size(&self) -> usize { self.raw_cipher.iv_size() } + #[must_use] pub fn tag_size(&self) -> Option> { if self.raw_cipher.is_authenticated() { Some(32..129) @@ -128,21 +129,22 @@ impl Cipher { } } + #[must_use] pub fn cipher_mode(&self) -> raw::CipherMode { self.raw_cipher.cipher_mode() } } 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 let raw_cipher = raw::Cipher::setup(cipher_id, cipher_mode, key_bit_len)?; // Put together the structure to return - Ok(Cipher { - raw_cipher: raw_cipher, + Ok(Self { + raw_cipher, padding: raw::CipherPadding::Pkcs7, _op: PhantomData, _type: PhantomData, @@ -308,7 +310,7 @@ impl Cipher { } 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, Self)> { // Call the wrapper function to do update operation (multi part) let len = self.raw_cipher.update(in_data, out_data)?; @@ -326,14 +328,14 @@ impl Cipher { } impl Cipher { - pub fn write_tag(mut self, out_tag: &mut [u8]) -> Result> { + pub fn write_tag(mut self, out_tag: &mut [u8]) -> Result { self.raw_cipher.write_tag(out_tag)?; // Put together the structure to return Ok(self.change_state()) } - pub fn check_tag(mut self, tag: &[u8]) -> Result> { + pub fn check_tag(mut self, tag: &[u8]) -> Result { self.raw_cipher.check_tag(tag)?; // Put together the structure to return diff --git a/mbedtls/src/cipher/raw/mod.rs b/mbedtls/src/cipher/raw/mod.rs index 2a25e3435..7930c504d 100644 --- a/mbedtls/src/cipher/raw/mod.rs +++ b/mbedtls/src/cipher/raw/mod.rs @@ -32,16 +32,16 @@ define!( impl From for CipherId { fn from(inner: cipher_id_t) -> Self { match inner { - CIPHER_ID_NONE => CipherId::None, - CIPHER_ID_NULL => CipherId::Null, - CIPHER_ID_AES => CipherId::Aes, - CIPHER_ID_DES => CipherId::Des, - CIPHER_ID_3DES => CipherId::Des3, - CIPHER_ID_CAMELLIA => CipherId::Camellia, - CIPHER_ID_BLOWFISH => CipherId::Blowfish, - CIPHER_ID_ARC4 => CipherId::Arc4, - CIPHER_ID_ARIA => CipherId::Aria, - CIPHER_ID_CHACHA20 => CipherId::Chacha20, + CIPHER_ID_NONE => Self::None, + CIPHER_ID_NULL => Self::Null, + CIPHER_ID_AES => Self::Aes, + CIPHER_ID_DES => Self::Des, + CIPHER_ID_3DES => Self::Des3, + CIPHER_ID_CAMELLIA => Self::Camellia, + CIPHER_ID_BLOWFISH => Self::Blowfish, + CIPHER_ID_ARC4 => Self::Arc4, + CIPHER_ID_ARIA => Self::Aria, + CIPHER_ID_CHACHA20 => Self::Chacha20, // This should be replaced with TryFrom once it is stable. _ => panic!("Invalid cipher_id_t"), } @@ -71,19 +71,19 @@ define!( impl From for CipherMode { fn from(inner: cipher_mode_t) -> Self { match inner { - MODE_NONE => CipherMode::None, - MODE_ECB => CipherMode::ECB, - MODE_CBC => CipherMode::CBC, - MODE_CFB => CipherMode::CFB, - MODE_OFB => CipherMode::OFB, - MODE_CTR => CipherMode::CTR, - MODE_GCM => CipherMode::GCM, - MODE_STREAM => CipherMode::STREAM, - MODE_CCM => CipherMode::CCM, - MODE_XTS => CipherMode::XTS, - MODE_CHACHAPOLY => CipherMode::CHACHAPOLY, - MODE_KW => CipherMode::KW, - MODE_KWP => CipherMode::KWP, + MODE_NONE => Self::None, + MODE_ECB => Self::ECB, + MODE_CBC => Self::CBC, + MODE_CFB => Self::CFB, + MODE_OFB => Self::OFB, + MODE_CTR => Self::CTR, + MODE_GCM => Self::GCM, + MODE_STREAM => Self::STREAM, + MODE_CCM => Self::CCM, + MODE_XTS => Self::XTS, + MODE_CHACHAPOLY => Self::CHACHAPOLY, + MODE_KW => Self::KW, + MODE_KWP => Self::KWP, // This should be replaced with TryFrom once it is stable. _ => panic!("Invalid cipher_mode_t"), } @@ -210,7 +210,7 @@ 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 @@ -293,28 +293,26 @@ impl Cipher { } // Utility function to get block size for the selected / setup cipher_info + #[must_use] pub fn block_size(&self) -> usize { unsafe { (*self.inner.cipher_info).block_size as usize } } // Utility function to get IV size for the selected / setup cipher_info + #[must_use] pub fn iv_size(&self) -> usize { unsafe { (*self.inner.cipher_info).iv_size as usize } } + #[must_use] pub fn cipher_mode(&self) -> CipherMode { unsafe { (*self.inner.cipher_info).mode.into() } } // Utility function to get mode for the selected / setup cipher_info + #[must_use] pub fn is_authenticated(&self) -> bool { - unsafe { - if (*self.inner.cipher_info).mode == MODE_GCM || (*self.inner.cipher_info).mode == MODE_CCM { - return true; - } else { - return false; - } - } + unsafe { (*self.inner.cipher_info).mode == MODE_GCM || (*self.inner.cipher_info).mode == MODE_CCM } } // Utility function to set odd parity - used for DES keys diff --git a/mbedtls/src/cipher/raw/serde.rs b/mbedtls/src/cipher/raw/serde.rs index 987f9920d..b9a842c9f 100644 --- a/mbedtls/src/cipher/raw/serde.rs +++ b/mbedtls/src/cipher/raw/serde.rs @@ -64,9 +64,10 @@ impl Serialize for Cipher { serialize_raw_cipher(cipher_context).map_err(ser::Error::custom)? }; - match Op::is_encrypt() { - true => SavedCipher::Encryption(saved_raw_cipher, self.padding).serialize(s), - false => SavedCipher::Decryption(saved_raw_cipher, self.padding).serialize(s), + if Op::is_encrypt() { + SavedCipher::Encryption(saved_raw_cipher, self.padding).serialize(s) + } else { + SavedCipher::Decryption(saved_raw_cipher, self.padding).serialize(s) } } } @@ -82,23 +83,19 @@ unsafe fn serialize_raw_cipher(mut cipher_context: cipher_context_t) -> Result { + let algorithm_context = match (cipher_id, cipher_mode) { + (CIPHER_ID_AES, MODE_CBC | MODE_CTR | MODE_OFB | MODE_CFB | MODE_ECB) => { let mut aes_context = *(cipher_context.cipher_ctx as *const aes_context); 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 | MODE_CTR | MODE_CFB | 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 | MODE_CTR | MODE_OFB | 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) => { + (CIPHER_ID_3DES, MODE_CBC | MODE_CTR | MODE_OFB | MODE_CFB) => { AlgorithmContext::Des3(Bytes(*(cipher_context.cipher_ctx as *const des3_context))) } (CIPHER_ID_AES, MODE_GCM) => { @@ -117,6 +114,7 @@ unsafe fn serialize_raw_cipher(mut cipher_context: cipher_context_t) -> Result Result Deserialize<'de> for Cipher { - fn deserialize(d: D) -> Result, D::Error> + fn deserialize(d: D) -> Result where D: Deserializer<'de>, { @@ -160,9 +158,9 @@ impl<'de, Op: Operation, T: Type> Deserialize<'de> for Cipher unsafe { let raw_cipher = deserialize_raw_cipher(raw, padding) .map_err(|(e1, e2)| de::Error::invalid_value(Unexpected::Other(e1), &e2))?; - Ok(Cipher { - raw_cipher: raw_cipher, - padding: padding, + Ok(Self { + raw_cipher, + padding, _op: PhantomData, _type: PhantomData, _state: PhantomData, @@ -171,6 +169,7 @@ impl<'de, Op: Operation, T: Type> Deserialize<'de> for Cipher } } +#[allow(clippy::manual_let_else)] unsafe fn deserialize_raw_cipher( raw: SavedRawCipher, padding: raw::CipherPadding, @@ -200,11 +199,11 @@ unsafe fn deserialize_raw_cipher( (*ret_aes_ctx).rk = &mut (*ret_aes_ctx).buf[0]; } (CIPHER_ID_ARIA, AlgorithmContext::Aria(Bytes(aria_ctx))) => { - *(cipher_context.cipher_ctx as *mut aria_context) = 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_3DES, AlgorithmContext::Des3(Bytes(des3_ctx))) => { - *(cipher_context.cipher_ctx as *mut des3_context) = des3_ctx + *(cipher_context.cipher_ctx as *mut des3_context) = des3_ctx; } ( CIPHER_ID_AES, @@ -267,7 +266,11 @@ unsafe trait BytesSerde: Sized { } fn as_slice(&self) -> &[u8] { - unsafe { from_raw_parts(self as *const Self as *const u8, size_of::()) } + unsafe { + // allow ref_as_prt because of no_std + #[allow(clippy::ref_as_ptr)] + from_raw_parts(self as *const Self as *const u8, size_of::()) + } } } @@ -281,7 +284,7 @@ impl Serialize for Bytes { } impl<'de, T: BytesSerde> Deserialize<'de> for Bytes { - fn deserialize(d: D) -> Result, D::Error> + fn deserialize(d: D) -> Result where D: Deserializer<'de>, { @@ -340,6 +343,8 @@ unsafe fn _check_cipher_context_t_size(ctx: cipher_context_t) -> [u8; _SIZE_OF_C ::core::mem::transmute(ctx) } +// I don't know if this should be ignored or not +#[allow(clippy::large_types_passed_by_value)] unsafe fn _check_aes_context_size(ctx: aes_context) -> [u8; _SIZE_OF_AES_CONTEXT] { ::core::mem::transmute(ctx) } @@ -348,10 +353,14 @@ unsafe fn _check_des_context_size(ctx: des_context) -> [u8; _SIZE_OF_DES_CONTEXT ::core::mem::transmute(ctx) } +// I don't know if this should be ignored or not +#[allow(clippy::large_types_passed_by_value)] unsafe fn _check_des3_context_size(ctx: des3_context) -> [u8; _SIZE_OF_DES3_CONTEXT] { ::core::mem::transmute(ctx) } +// I don't know if this should be ignored or not +#[allow(clippy::large_types_passed_by_value)] 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 6b6fffd7c..7657acfed 100644 --- a/mbedtls/src/ecp/mod.rs +++ b/mbedtls/src/ecp/mod.rs @@ -31,11 +31,7 @@ impl Clone for EcGroup { ecp_group_copy only works for named groups, for custom groups we must perform the copy manually. */ - if group.group_id()? != EcGroupId::None { - let mut ret = EcGroup::init(); - unsafe { ecp_group_copy(ret.handle_mut(), group.handle()) }.into_result()?; - Ok(ret) - } else { + if group.group_id()? == EcGroupId::None { let generator = group.generator()?; EcGroup::from_parameters( group.p()?, @@ -45,6 +41,10 @@ impl Clone for EcGroup { generator.y()?, group.order()?, ) + } else { + let mut ret = EcGroup::init(); + unsafe { ecp_group_copy(ret.handle_mut(), group.handle()) }.into_result()?; + Ok(ret) } } @@ -53,7 +53,7 @@ impl Clone for EcGroup { } impl PartialEq for EcGroup { - fn eq(&self, other: &EcGroup) -> bool { + fn eq(&self, other: &Self) -> bool { self.p() == other.p() && self.a() == other.a() && self.b() == other.b() @@ -67,26 +67,26 @@ impl Eq for EcGroup {} impl TryFrom for EcGroup { type Error = Error; - fn try_from(id: EcGroupId) -> Result { - EcGroup::new(id) + fn try_from(id: EcGroupId) -> Result { + Self::new(id) } } impl EcGroup { - pub fn new(group: EcGroupId) -> Result { + pub fn new(group: EcGroupId) -> Result { let mut ret = Self::init(); unsafe { ecp_group_load(&mut ret.inner, group.into()) }.into_result()?; Ok(ret) } - /// Initialize an EcGroup with custom group parameters. + /// Initialize an `EcGroup` with custom group parameters. /// /// HAZMAT: This function DOES NOT perform a full check on parameters /// against all known attacks. The caller MUST make sure that parameters are /// 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 { + /// 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 { let mut ret = Self::init(); ret.inner.pbits = p.bit_length()?; @@ -96,16 +96,16 @@ impl EcGroup { let zero = Mpi::new(0)?; // basic bounds checking - if &a < &zero - || &a >= &p - || &b < &zero - || &b >= &p - || &g_x < &zero - || &g_x >= &p - || &g_y < &zero - || &g_y >= &p - || &order <= &zero - || (&a == &zero && &b == &zero) + if a < zero + || a >= p + || b < zero + || b >= p + || g_x < zero + || g_x >= p + || g_y < zero + || g_y >= p + || order <= zero + || (a == zero && b == zero) { return Err(Error::EcpBadInputData); } @@ -171,7 +171,8 @@ impl EcGroup { pub fn a(&self) -> Result { // Mbedtls uses A == NULL to indicate -3 mod p - if self.inner.A.p == ::core::ptr::null_mut() { + if self.inner.A.p.is_null() { + //if self.inner.A.p == ::core::ptr::null_mut() { let mut neg3 = self.p()?; neg3 -= 3; Ok(neg3) @@ -230,30 +231,30 @@ impl Clone for EcPoint { } impl PartialEq for EcPoint { - fn eq(&self, other: &EcPoint) -> bool { + fn eq(&self, other: &Self) -> bool { self.eq(other).unwrap() } } impl EcPoint { - pub fn new() -> Result { + pub fn new() -> Result { let mut ret = Self::init(); unsafe { ecp_set_zero(&mut ret.inner) }.into_result()?; Ok(ret) } - pub(crate) fn copy(other: &ecp_point) -> Result { + pub(crate) fn copy(other: &ecp_point) -> Result { let mut ret = Self::init(); unsafe { ecp_copy(&mut ret.inner, other) }.into_result()?; Ok(ret) } - pub fn from_binary(group: &EcGroup, bin: &[u8]) -> Result { - let prefix = *bin.get(0).ok_or(Error::EcpBadInputData)?; + pub fn from_binary(group: &EcGroup, bin: &[u8]) -> Result { + let prefix = *bin.first().ok_or(Error::EcpBadInputData)?; if prefix == 0x02 || prefix == 0x03 { // Compressed point, which mbedtls does not understand - let y_mod_2 = if prefix == 0x03 { true } else { false }; + let y_mod_2 = prefix == 0x03; let p = group.p()?; let a = group.a()?; @@ -275,7 +276,7 @@ impl EcPoint { if y.get_bit(0) != y_mod_2 { y = (&p - &y)?; } - EcPoint::from_components(x, y) + Self::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()?; @@ -283,13 +284,13 @@ impl EcPoint { } } - pub fn from_binary_no_compress(group: &EcGroup, bin: &[u8]) -> Result { + pub fn from_binary_no_compress(group: &EcGroup, bin: &[u8]) -> Result { let mut ret = Self::init(); unsafe { ecp_point_read_binary(&group.inner, &mut ret.inner, bin.as_ptr(), bin.len()) }.into_result()?; Ok(ret) } - pub fn from_components(x: Mpi, y: Mpi) -> Result { + pub fn from_components(x: Mpi, y: Mpi) -> Result { let mut ret = Self::init(); unsafe { @@ -329,7 +330,7 @@ impl EcPoint { note = "This function does not accept an RNG so it's vulnerable to side channel attacks. Please use `mul_with_rng` instead." )] - pub fn mul(&self, group: &mut EcGroup, k: &Mpi) -> Result { + pub fn mul(&self, group: &mut EcGroup, k: &Mpi) -> Result { // Note: mbedtls_ecp_mul performs point validation itself so we skip that here let mut ret = Self::init(); @@ -377,7 +378,7 @@ Please use `mul_with_rng` instead." /// [`mbedtls_ecp_check_pubkey`]: https://github.com/fortanix/rust-mbedtls/blob/main/mbedtls-sys/vendor/include/mbedtls/ecp.h#L1115-L1143 /// [`mbedtls_ecp_check_privkey`]: https://github.com/fortanix/rust-mbedtls/blob/main/mbedtls-sys/vendor/include/mbedtls/ecp.h#L1145-L1165 /// [`mbedtls_ecp_mul`]: https://github.com/fortanix/rust-mbedtls/blob/main/mbedtls-sys/vendor/include/mbedtls/ecp.h#L933-L971 - pub fn mul_with_rng(&self, group: &mut EcGroup, k: &Mpi, rng: &mut F) -> Result { + pub fn mul_with_rng(&self, group: &mut EcGroup, k: &Mpi, rng: &mut F) -> Result { // Note: mbedtls_ecp_mul performs point validation itself so we skip that here let mut ret = Self::init(); @@ -398,14 +399,14 @@ Please use `mul_with_rng` instead." } /// 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: &Self, k1: &Mpi, pt2: &Self, k2: &Mpi) -> Result { let mut ret = Self::init(); - if group.contains_point(&pt1)? == false { + if !group.contains_point(pt1)? { return Err(Error::EcpInvalidKey); } - if group.contains_point(&pt2)? == false { + if !group.contains_point(pt2)? { return Err(Error::EcpInvalidKey); } @@ -424,7 +425,7 @@ Please use `mul_with_rng` instead." Ok(ret) } - pub fn eq(&self, other: &EcPoint) -> Result { + pub fn eq(&self, other: &Self) -> Result { let r = unsafe { ecp_point_cmp(&self.inner, &other.inner) }; match r { @@ -440,10 +441,12 @@ Please use `mul_with_rng` instead." /// This new implementation ensures there is no shortcut when any of `x, y ,z` fields of two points is not equal. /// /// [`mbedtls_ecp_point_cmp`]: https://github.com/fortanix/rust-mbedtls/blob/main/mbedtls-sys/vendor/library/ecp.c#L809-L825 - pub fn eq_const_time(&self, other: &EcPoint) -> Result { + pub fn eq_const_time(&self, other: &Self) -> Result { let x = crate::bignum::mpi_inner_eq_const_time(&self.inner.X, &other.inner.X); let y = crate::bignum::mpi_inner_eq_const_time(&self.inner.Y, &other.inner.Y); let z = crate::bignum::mpi_inner_eq_const_time(&self.inner.Z, &other.inner.Z); + // allow for constant time + #[allow(clippy::match_same_arms)] match (x, y, z) { (Ok(true), Ok(true), Ok(true)) => Ok(true), (Ok(_), Ok(_), Ok(_)) => Ok(false), diff --git a/mbedtls/src/error.rs b/mbedtls/src/error.rs index 690a7804e..dc60497b1 100644 --- a/mbedtls/src/error.rs +++ b/mbedtls/src/error.rs @@ -36,10 +36,6 @@ macro_rules! error_enum { $($rust,)* Other(c_int), Utf8Error(Option), - // Stable-Rust equivalent of `#[non_exhaustive]` attribute. This - // value should never be used by users of this crate! - #[doc(hidden)] - __Nonexhaustive, } impl IntoResult for c_int { @@ -55,28 +51,29 @@ macro_rules! error_enum { } impl $n { - pub fn from_mbedtls_code(code: c_int) -> Self { + #[must_use] + pub const fn from_mbedtls_code(code: c_int) -> Self { match code { $(::mbedtls_sys::$c => $n::$rust),*, _ => $n::Other(code) } } - pub fn as_str(&self) -> &'static str { + #[must_use] + pub const fn as_str(&self) -> &'static str { match self { $(&$n::$rust => concat!("mbedTLS error ",stringify!($n::$rust)),)* &$n::Other(_) => "mbedTLS unknown error", &$n::Utf8Error(_) => "error converting to UTF-8", - &$n::__Nonexhaustive => unreachable!("__Nonexhaustive value should not be instantiated"), } } - pub fn to_int(&self) -> c_int { + #[must_use] + pub const fn to_int(&self) -> c_int { match *self { $($n::$rust => ::mbedtls_sys::$c,)* $n::Other(code) => code, $n::Utf8Error(_) => ERR_UTF8_INVALID, - $n::__Nonexhaustive => unreachable!("__Nonexhaustive value should not be instantiated"), } } } @@ -84,13 +81,13 @@ macro_rules! error_enum { } impl From for Error { - fn from(e: Utf8Error) -> Error { - Error::Utf8Error(Some(e)) + fn from(e: Utf8Error) -> Self { + Self::Utf8Error(Some(e)) } } impl From for Error { - fn from(x: Infallible) -> Error { + fn from(x: Infallible) -> Self { match x {} } } @@ -98,11 +95,10 @@ 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(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"), - e @ _ => f.write_fmt(format_args!("mbedTLS error {:?}", e)), + &Self::Utf8Error(Some(ref e)) => f.write_fmt(format_args!("Error converting to UTF-8: {e}")), + &Self::Utf8Error(None) => f.write_fmt(format_args!("Error converting to UTF-8")), + &Self::Other(i) => f.write_fmt(format_args!("mbedTLS unknown error ({i})")), + e => f.write_fmt(format_args!("mbedTLS error {e:?}")), } } } diff --git a/mbedtls/src/hash/mod.rs b/mbedtls/src/hash/mod.rs index c50f09911..c4a961691 100644 --- a/mbedtls/src/hash/mod.rs +++ b/mbedtls/src/hash/mod.rs @@ -11,7 +11,7 @@ use mbedtls_sys::*; define!( #[c_ty(md_type_t)] - #[derive(Copy, Clone, PartialEq, Debug)] + #[derive(Copy, Clone, PartialEq, Eq, Debug)] enum Type { None = MD_NONE, Md2 = MD_MD2, @@ -26,19 +26,20 @@ define!( } ); +#[allow(clippy::fallible_impl_from)] impl From for Type { - fn from(inner: md_type_t) -> Type { + fn from(inner: md_type_t) -> Self { match inner { - MD_NONE => Type::None, - MD_MD2 => Type::Md2, - MD_MD4 => Type::Md4, - MD_MD5 => Type::Md5, - MD_SHA1 => Type::Sha1, - MD_SHA224 => Type::Sha224, - MD_SHA256 => Type::Sha256, - MD_SHA384 => Type::Sha384, - MD_SHA512 => Type::Sha512, - MD_RIPEMD160 => Type::Ripemd, + MD_NONE => Self::None, + MD_MD2 => Self::Md2, + MD_MD4 => Self::Md4, + MD_MD5 => Self::Md5, + MD_SHA1 => Self::Sha1, + MD_SHA224 => Self::Sha224, + MD_SHA256 => Self::Sha256, + MD_SHA384 => Self::Sha384, + MD_SHA512 => Self::Sha512, + MD_RIPEMD160 => Self::Ripemd, _ => panic!("Invalid Md type"), } } @@ -49,15 +50,15 @@ pub struct MdInfo { inner: &'static md_info_t, } -impl Into> for Type { - fn into(self) -> Option { - unsafe { md_info_from_type(self.into()).as_ref() }.map(|r| MdInfo { inner: r }) +impl From for Option { + fn from(val: Type) -> Self { + unsafe { md_info_from_type(val.into()).as_ref() }.map(|r| MdInfo { inner: r }) } } -impl Into<*const md_info_t> for MdInfo { - fn into(self) -> *const md_info_t { - self.inner +impl From for *const md_info_t { + fn from(val: MdInfo) -> Self { + val.inner } } @@ -70,9 +71,11 @@ define!( ); impl MdInfo { + #[must_use] pub fn size(&self) -> usize { unsafe { md_get_size(self.inner).into() } } + #[must_use] pub fn get_type(&self) -> Type { unsafe { md_get_type(self.inner).into() } } @@ -94,13 +97,13 @@ impl Clone for Md { } impl Md { - pub fn new(md: Type) -> Result { + pub fn new(md: Type) -> Result { let md: MdInfo = match md.into() { Some(md) => md, None => return Err(Error::MdBadInputData), }; - let mut ctx = Md::init(); + let mut ctx = Self::init(); unsafe { md_setup(&mut ctx.inner, md.into(), 0).into_result()?; md_starts(&mut ctx.inner).into_result()?; @@ -147,7 +150,7 @@ pub struct Hmac { } impl Hmac { - pub fn new(md: Type, key: &[u8]) -> Result { + pub fn new(md: Type, key: &[u8]) -> Result { let md: MdInfo = match md.into() { Some(md) => md, None => return Err(Error::MdBadInputData), @@ -158,7 +161,7 @@ impl Hmac { md_setup(&mut ctx.inner, md.into(), 1).into_result()?; md_hmac_starts(&mut ctx.inner, key.as_ptr(), key.len()).into_result()?; } - Ok(Hmac { ctx }) + Ok(Self { ctx }) } pub fn update(&mut self, data: &[u8]) -> Result<()> { @@ -271,8 +274,8 @@ impl Hkdf { unsafe { hkdf( md.inner, - maybe_salt.map_or(::core::ptr::null(), |salt| salt.as_ptr()), - maybe_salt.map_or(0, |salt| salt.len()), + maybe_salt.map_or(::core::ptr::null(), <[u8]>::as_ptr), + maybe_salt.map_or(0, <[u8]>::len), ikm.as_ptr(), ikm.len(), info.as_ptr(), @@ -320,8 +323,8 @@ impl Hkdf { unsafe { hkdf_extract( md.inner, - maybe_salt.map_or(::core::ptr::null(), |salt| salt.as_ptr()), - maybe_salt.map_or(0, |salt| salt.len()), + maybe_salt.map_or(::core::ptr::null(), <[u8]>::as_ptr), + maybe_salt.map_or(0, <[u8]>::len), ikm.as_ptr(), ikm.len(), prk.as_mut_ptr(), @@ -413,8 +416,8 @@ pub fn pbkdf_pkcs12(md: Type, password: &[u8], salt: &[u8], id: u8, iterations: salt.as_ptr(), salt.len(), md.into(), - id as i32, - iterations as i32, + core::ffi::c_int::from(id), + iterations as core::ffi::c_int, ) .into_result()?; Ok(()) diff --git a/mbedtls/src/lib.rs b/mbedtls/src/lib.rs index 7a8620528..e9b9a0fa8 100644 --- a/mbedtls/src/lib.rs +++ b/mbedtls/src/lib.rs @@ -7,7 +7,35 @@ * according to those terms. */ #![deny(warnings)] -#![allow(unused_doc_comments)] +#![allow(unused_doc_comments, unexpected_cfgs)] +#![allow( + clippy::missing_safety_doc, + clippy::missing_errors_doc, + clippy::missing_panics_doc, + clippy::many_single_char_names, + clippy::wildcard_imports, + clippy::ptr_as_ptr, + clippy::non_send_fields_in_send_ty +)] +// FIXME: these allows should probably be removed +#![allow( + clippy::cast_sign_loss, + clippy::must_use_candidate, + clippy::semicolon_if_nothing_returned, + clippy::manual_let_else, + clippy::ref_as_ptr, + clippy::ptr_cast_constness, + clippy::cast_possible_wrap, + clippy::manual_c_str_literals, + clippy::cast_lossless, + clippy::cast_possible_truncation, + clippy::match_same_arms, + clippy::module_name_repetitions, + clippy::needless_pass_by_value, + clippy::match_bool, + clippy::redundant_closure_for_method_calls, + clippy::items_after_statements +)] #![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(nightly, feature(doc_auto_cfg))] diff --git a/mbedtls/src/pk/dhparam.rs b/mbedtls/src/pk/dhparam.rs index 8f98b9d08..501cecd2d 100644 --- a/mbedtls/src/pk/dhparam.rs +++ b/mbedtls/src/pk/dhparam.rs @@ -22,7 +22,7 @@ impl Dhm { /// Takes both DER and PEM forms of FFDH parameters in `DHParams` format. /// /// When calling on PEM-encoded data, `params` must be NULL-terminated - pub fn from_params(params: &[u8]) -> Result { + pub fn from_params(params: &[u8]) -> Result { let mut ret = Self::init(); unsafe { dhm_parse_dhm(&mut ret.inner, params.as_ptr(), params.len()) }.into_result()?; Ok(ret) diff --git a/mbedtls/src/pk/dsa/mod.rs b/mbedtls/src/pk/dsa/mod.rs index 1fc1d82e8..bec363345 100644 --- a/mbedtls/src/pk/dsa/mod.rs +++ b/mbedtls/src/pk/dsa/mod.rs @@ -183,7 +183,7 @@ impl DsaPublicKey { } pub fn key_size(&self) -> Result<(usize, usize)> { - return self.params.key_size(); + self.params.key_size() } pub fn parameters(&self) -> &DsaParams { @@ -312,7 +312,7 @@ impl DsaPrivateKey { Some(md) => md, None => panic!("no such digest"), }; - let rfc6979_nonce = generate_rfc6979_nonce(&md, &self.x, &self.params.q, pre_hashed_message)?; + let rfc6979_nonce = generate_rfc6979_nonce(md, &self.x, &self.params.q, pre_hashed_message)?; let k = Mpi::from_binary(&rfc6979_nonce)?; self.sign_with_explicit_nonce(pre_hashed_message, k, rng) } @@ -351,7 +351,7 @@ impl DsaPrivateKey { } pub fn key_size(&self) -> Result<(usize, usize)> { - return self.params.key_size(); + self.params.key_size() } pub fn parameters(&self) -> &DsaParams { diff --git a/mbedtls/src/pk/ec.rs b/mbedtls/src/pk/ec.rs index 2cc8a0151..b8fd4e568 100644 --- a/mbedtls/src/pk/ec.rs +++ b/mbedtls/src/pk/ec.rs @@ -33,22 +33,22 @@ define!( ); impl From for EcGroupId { - fn from(inner: ecp_group_id) -> EcGroupId { + fn from(inner: ecp_group_id) -> Self { match inner { - ECP_DP_NONE => EcGroupId::None, - ECP_DP_SECP192R1 => EcGroupId::SecP192R1, - ECP_DP_SECP224R1 => EcGroupId::SecP224R1, - ECP_DP_SECP256R1 => EcGroupId::SecP256R1, - ECP_DP_SECP384R1 => EcGroupId::SecP384R1, - ECP_DP_SECP521R1 => EcGroupId::SecP521R1, - ECP_DP_BP256R1 => EcGroupId::Bp256R1, - ECP_DP_BP384R1 => EcGroupId::Bp384R1, - ECP_DP_BP512R1 => EcGroupId::Bp512R1, - ECP_DP_CURVE25519 => EcGroupId::Curve25519, - ECP_DP_SECP192K1 => EcGroupId::SecP192K1, - ECP_DP_SECP224K1 => EcGroupId::SecP224K1, - ECP_DP_SECP256K1 => EcGroupId::SecP256K1, - ECP_DP_CURVE448 => EcGroupId::Curve448, + ECP_DP_NONE => Self::None, + ECP_DP_SECP192R1 => Self::SecP192R1, + ECP_DP_SECP224R1 => Self::SecP224R1, + ECP_DP_SECP256R1 => Self::SecP256R1, + ECP_DP_SECP384R1 => Self::SecP384R1, + ECP_DP_SECP521R1 => Self::SecP521R1, + ECP_DP_BP256R1 => Self::Bp256R1, + ECP_DP_BP384R1 => Self::Bp384R1, + ECP_DP_BP512R1 => Self::Bp512R1, + ECP_DP_CURVE25519 => Self::Curve25519, + ECP_DP_SECP192K1 => Self::SecP192K1, + ECP_DP_SECP224K1 => Self::SecP224K1, + ECP_DP_SECP256K1 => Self::SecP256K1, + ECP_DP_CURVE448 => Self::Curve448, _ => panic!("Invalid EC group ID"), } } @@ -78,7 +78,7 @@ define!( ); impl Ecdh { - pub fn from_keys(private: &EcpKeypair, public: &EcpKeypair) -> Result { + pub fn from_keys(private: &EcpKeypair, public: &EcpKeypair) -> Result { if public.inner.grp.id == ECP_DP_NONE || public.inner.grp.id != private.inner.grp.id { return Err(Error::EcpBadInputData); } diff --git a/mbedtls/src/pk/mod.rs b/mbedtls/src/pk/mod.rs index 63c77575e..80d7c6109 100644 --- a/mbedtls/src/pk/mod.rs +++ b/mbedtls/src/pk/mod.rs @@ -42,13 +42,13 @@ pub use crate::ecp::EcGroup; pub use dhparam::Dhm; // SHA-256("Fortanix")[:4] -const CUSTOM_PK_TYPE: pk_type_t = 0x8b205408u32 as pk_type_t; +const CUSTOM_PK_TYPE: pk_type_t = 0x8b20_5408_u32 as pk_type_t; -const RAW_RSA_DECRYPT: i32 = 1040451858; +const RAW_RSA_DECRYPT: i32 = 1_040_451_858; define!( #[c_ty(pk_type_t)] - #[derive(Copy, Clone, PartialEq, Debug)] + #[derive(Copy, Clone, PartialEq, Eq, Debug)] enum Type { None = PK_NONE, Rsa = PK_RSA, @@ -63,16 +63,16 @@ define!( ); impl From for Type { - fn from(inner: pk_type_t) -> Type { + fn from(inner: pk_type_t) -> Self { match inner { - PK_NONE => Type::None, - PK_RSA => Type::Rsa, - PK_ECKEY => Type::Eckey, - PK_ECKEY_DH => Type::EckeyDh, - PK_ECDSA => Type::Ecdsa, - PK_RSA_ALT => Type::RsaAlt, - PK_RSASSA_PSS => Type::RsassaPss, - CUSTOM_PK_TYPE => Type::Custom, + PK_NONE => Self::None, + PK_RSA => Self::Rsa, + PK_ECKEY => Self::Eckey, + PK_ECKEY_DH => Self::EckeyDh, + PK_ECDSA => Self::Ecdsa, + PK_RSA_ALT => Self::RsaAlt, + PK_RSASSA_PSS => Self::RsassaPss, + CUSTOM_PK_TYPE => Self::Custom, _ => panic!("Invalid PK type"), } } @@ -99,8 +99,8 @@ struct CustomPkContext { } impl CustomPkContext { - fn new() -> CustomPkContext { - CustomPkContext { + fn new() -> Self { + Self { algo_id: Vec::new(), pk: Vec::new(), sk: Vec::new(), @@ -117,7 +117,7 @@ unsafe extern "C" fn free_custom_pk_ctx(p: *mut c_void) { let _ = Box::from_raw(p as *mut CustomPkContext); } -unsafe extern "C" fn custom_pk_can_do(_t: pk_type_t) -> types::raw_types::c_int { +const unsafe extern "C" fn custom_pk_can_do(_t: pk_type_t) -> types::raw_types::c_int { 0 } @@ -288,31 +288,31 @@ impl Pk { /// Takes both DER and PEM forms of PKCS#1 or PKCS#8 encoded keys. /// /// When calling on PEM-encoded data, `key` must be NULL-terminated - pub fn from_private_key(key: &[u8], password: Option<&[u8]>) -> Result { + pub fn from_private_key(key: &[u8], password: Option<&[u8]>) -> Result { let mut ret = Self::init(); unsafe { pk_parse_key( &mut ret.inner, key.as_ptr(), key.len(), - password.map(<[_]>::as_ptr).unwrap_or(::core::ptr::null()), - password.map(<[_]>::len).unwrap_or(0), + password.map_or(::core::ptr::null(), <[_]>::as_ptr), + password.map_or(0, <[_]>::len), ) .into_result()?; }; Ok(ret) } - /// Takes both DER and PEM encoded SubjectPublicKeyInfo keys. + /// Takes both DER and PEM encoded `SubjectPublicKeyInfo` keys. /// /// When calling on PEM-encoded data, `key` must be NULL-terminated - pub fn from_public_key(key: &[u8]) -> Result { + pub fn from_public_key(key: &[u8]) -> Result { let mut ret = Self::init(); unsafe { pk_parse_public_key(&mut ret.inner, key.as_ptr(), key.len()).into_result()? }; Ok(ret) } - pub fn generate_rsa(rng: &mut F, bits: u32, exponent: u32) -> Result { + pub fn generate_rsa(rng: &mut F, bits: u32, exponent: u32) -> Result { let mut ret = Self::init(); unsafe { pk_setup(&mut ret.inner, pk_info_from_type(Type::Rsa.into())).into_result()?; @@ -321,12 +321,15 @@ impl Pk { Ok(ret) } - pub fn generate_ec>>(rng: &mut F, curve: C) -> Result { + pub fn generate_ec>>(rng: &mut F, curve: C) -> Result { let mut ret = Self::init(); unsafe { + // allow redundant closure because of no_std + #[allow(clippy::redundant_closure)] 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; + //FIXME: why is this .clone() here? (*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()?; } @@ -338,7 +341,7 @@ impl Pk { note = "This function does not accept an RNG so it's vulnerable to side channel attacks. Please use `private_from_ec_scalar_with_rng` instead." )] - pub fn private_from_ec_components(mut curve: EcGroup, private_key: Mpi) -> Result { + pub fn private_from_ec_components(mut curve: EcGroup, private_key: Mpi) -> Result { let mut ret = Self::init(); let curve_generator = curve.generator()?; #[allow(deprecated)] @@ -376,10 +379,10 @@ Please use `private_from_ec_scalar_with_rng` instead." /// /// This function will return an error if: /// - /// * Fails to generate `EcPoint` from given EcGroup in `curve`. + /// * Fails to generate `EcPoint` from given `EcGroup` in `curve`. /// * The underlying C `mbedtls_pk_setup` function fails to set up the `Pk` context. /// * The `EcPoint::mul_with_rng` function fails to generate the public key point. - pub fn private_from_ec_scalar_with_rng(mut curve: EcGroup, private_key: Mpi, rng: &mut F) -> Result { + pub fn private_from_ec_scalar_with_rng(mut curve: EcGroup, private_key: Mpi, rng: &mut F) -> Result { let mut ret = Self::init(); let curve_generator = curve.generator()?; let public_point = curve_generator.mul_with_rng(&mut curve, &private_key, rng)?; @@ -393,7 +396,7 @@ Please use `private_from_ec_scalar_with_rng` instead." Ok(ret) } - pub fn public_from_ec_components(curve: EcGroup, public_point: EcPoint) -> Result { + pub fn public_from_ec_components(curve: EcGroup, public_point: EcPoint) -> Result { let mut ret = Self::init(); unsafe { pk_setup(&mut ret.inner, pk_info_from_type(Type::Eckey.into())).into_result()?; @@ -405,7 +408,7 @@ Please use `private_from_ec_scalar_with_rng` instead." } /// Construct a private key from RSA components. - pub fn private_from_rsa_components(components: RsaPrivateComponents<'_>) -> Result { + pub fn private_from_rsa_components(components: RsaPrivateComponents<'_>) -> Result { let mut ret = Self::init(); let (n, p, q, d, e) = match components { RsaPrivateComponents::WithPrimes { p, q, e } => (None, Some(p), Some(q), None, Some(e)), @@ -426,7 +429,7 @@ Please use `private_from_ec_scalar_with_rng` instead." } /// Construct a public key from RSA components. - pub fn public_from_rsa_components(components: RsaPublicComponents<'_>) -> Result { + pub fn public_from_rsa_components(components: RsaPublicComponents<'_>) -> Result { let mut ret = Self::init(); let RsaPublicComponents { n, e } = components; unsafe { @@ -438,25 +441,25 @@ Please use `private_from_ec_scalar_with_rng` instead." Ok(ret) } - pub fn public_custom_algo(algo_id: &[u64], pk: &[u8]) -> Result { + pub fn public_custom_algo(algo_id: &[u64], pk: &[u8]) -> Result { let mut ret = Self::init(); unsafe { pk_setup(&mut ret.inner, &CUSTOM_PK_INFO).into_result()?; let ctx = ret.inner.pk_ctx as *mut CustomPkContext; - (*ctx).algo_id = algo_id.to_owned(); - (*ctx).pk = pk.to_owned(); + algo_id.clone_into(&mut (*ctx).algo_id); + pk.clone_into(&mut (*ctx).pk); } Ok(ret) } - pub fn private_custom_algo(algo_id: &[u64], pk: &[u8], sk: &[u8]) -> Result { + pub fn private_custom_algo(algo_id: &[u64], pk: &[u8], sk: &[u8]) -> Result { let mut ret = Self::init(); unsafe { pk_setup(&mut ret.inner, &CUSTOM_PK_INFO).into_result()?; let ctx = ret.inner.pk_ctx as *mut CustomPkContext; - (*ctx).algo_id = algo_id.to_owned(); - (*ctx).pk = pk.to_owned(); - (*ctx).sk = sk.to_owned(); + algo_id.clone_into(&mut (*ctx).algo_id); + pk.clone_into(&mut (*ctx).pk); + sk.clone_into(&mut (*ctx).sk); } Ok(ret) } @@ -488,7 +491,7 @@ Please use `private_from_ec_scalar_with_rng` instead." let ctx = self.inner.pk_ctx as *const CustomPkContext; unsafe { - if (*ctx).sk.len() == 0 { + if (*ctx).sk.is_empty() { return Err(Error::PkTypeMismatch); } Ok(&(*ctx).sk) @@ -499,7 +502,7 @@ Please use `private_from_ec_scalar_with_rng` instead." 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 | 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()), @@ -516,20 +519,19 @@ Please use `private_from_ec_scalar_with_rng` instead." } } + #[must_use] pub fn can_do(&self, t: Type) -> bool { - if unsafe { pk_can_do(&self.inner, t.into()) } == 0 { - false - } else { - true - } + (unsafe { pk_can_do(&self.inner, t.into()) } != 0) } + #[must_use] pub fn check_pair(public: &Self, private: &Self) -> bool { unsafe { pk_check_pair(&public.inner, &private.inner) }.into_result().is_ok() } getter!( /// Key length in bits + #[allow(clippy::len_without_is_empty)] len() -> usize = fn pk_get_bitlen ); getter!(pk_type() -> Type = fn pk_get_type); @@ -834,14 +836,8 @@ Please use `private_from_ec_scalar_with_rng` instead." /// Decrypt using a custom label. /// /// 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], - plain: &mut [u8], - rng: &mut F, - label: &[u8], - ) -> Result { + /// `RSA_PKCS_V21`. + pub fn decrypt_with_label(&self, cipher: &[u8], plain: &mut [u8], rng: &mut F, label: &[u8]) -> Result { if self.pk_type() != Type::Rsa { return Err(Error::PkTypeMismatch); } @@ -890,14 +886,8 @@ Please use `private_from_ec_scalar_with_rng` instead." /// Encrypt using a custom label. /// /// 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], - cipher: &mut [u8], - rng: &mut F, - label: &[u8], - ) -> Result { + /// `RSA_PKCS_V21`. + pub fn encrypt_with_label(&self, plain: &[u8], cipher: &mut [u8], rng: &mut F, label: &[u8]) -> Result { if self.pk_type() != Type::Rsa { return Err(Error::PkTypeMismatch); } @@ -942,7 +932,7 @@ Please use `private_from_ec_scalar_with_rng` instead." 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 { + if hash.is_empty() || sig.is_empty() { return Err(Error::PkBadInputData); } @@ -979,7 +969,7 @@ Please use `private_from_ec_scalar_with_rng` instead." 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 { + if hash.is_empty() || sig.is_empty() { return Err(Error::PkBadInputData); } @@ -1032,7 +1022,7 @@ Please use `private_from_ec_scalar_with_rng` instead." 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.len() == 0 || sig.len() == 0 { + if hash.is_empty() || sig.is_empty() { return Err(Error::PkBadInputData); } @@ -1044,19 +1034,16 @@ Please use `private_from_ec_scalar_with_rng` instead." } /// 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: &Self, shared: &mut [u8], rng: &mut F) -> Result { match (self.pk_type(), other.pk_type()) { - (Type::Eckey, Type::Eckey) - | (Type::EckeyDh, Type::Eckey) - | (Type::Eckey, Type::EckeyDh) - | (Type::EckeyDh, Type::EckeyDh) => unsafe { + (Type::Eckey | Type::EckeyDh, Type::Eckey | Type::EckeyDh) => unsafe { let mut ecdh = ec::Ecdh::from_keys( UnsafeFrom::from(self.inner.pk_ctx as *const _).unwrap(), UnsafeFrom::from(other.inner.pk_ctx as *const _).unwrap(), )?; ecdh.calc_secret(shared, rng) }, - _ => return Err(Error::PkTypeMismatch), + _ => Err(Error::PkTypeMismatch), } } @@ -1112,7 +1099,7 @@ Please use `private_from_ec_scalar_with_rng` instead." pub fn write_public_pem_string(&mut self) -> Result { crate::private::alloc_string_repeat(|buf, size| unsafe { match pk_write_pubkey_pem(&mut self.inner, buf as _, size) { - 0 => crate::private::cstr_to_slice(buf as _).len() as _, + 0 => crate::private::cstr_to_slice(buf.cast_const()).len() as _, r => r, } }) diff --git a/mbedtls/src/pk/rfc6979.rs b/mbedtls/src/pk/rfc6979.rs index d18b41bda..49151a7fd 100644 --- a/mbedtls/src/pk/rfc6979.rs +++ b/mbedtls/src/pk/rfc6979.rs @@ -18,11 +18,11 @@ 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> { +pub(crate) fn generate_rfc6979_nonce(md: MdInfo, x: &Mpi, q: &Mpi, digest_bytes: &[u8]) -> Result> { let q_bits = q.bit_length()?; let q_bytes = q.byte_length()?; - let mut digest = Mpi::from_binary(&digest_bytes)?; + let mut digest = Mpi::from_binary(digest_bytes)?; if 8 * md.size() > q_bits { let shift_needed = 8 * md.size() - q_bits; @@ -37,7 +37,7 @@ pub(crate) fn generate_rfc6979_nonce(md: &MdInfo, x: &Mpi, q: &Mpi, digest_bytes let mut d = digest.to_binary_padded(q_bytes)?; x.append(&mut d); - let mut drbg = HmacDrbg::from_buf(*md, &x).unwrap(); + let mut drbg = HmacDrbg::from_buf(md, &x).unwrap(); let mut output = vec![0; q_bytes]; @@ -72,16 +72,16 @@ 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"), }; - let k = generate_rfc6979_nonce(&md, x, q, digest_bytes)?; + let k = generate_rfc6979_nonce(md, x, q, digest_bytes)?; - Ok(Rfc6979Rng { - k: k, + Ok(Self { + k, k_read: 0, rng: HmacDrbg::from_buf(md, random_seed)?, }) @@ -106,7 +106,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 { - let rng: &mut Rfc6979Rng = (user_data as *mut Rfc6979Rng).as_mut().unwrap(); + let rng: &mut Self = (user_data as *mut Self).as_mut().unwrap(); let slice = ::core::slice::from_raw_parts_mut(data_ptr, len); let result = rng.random_callback(slice); if let Err(r) = result { diff --git a/mbedtls/src/pkcs12/mod.rs b/mbedtls/src/pkcs12/mod.rs index 54e5a82fa..d06a7749e 100644 --- a/mbedtls/src/pkcs12/mod.rs +++ b/mbedtls/src/pkcs12/mod.rs @@ -86,7 +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))?) + String::from_utf8(bytes).map_err(|_| ASN1Error::new(ASN1ErrorKind::Invalid)) }) } @@ -115,12 +115,12 @@ fn read_seq_of(der: &[u8]) -> ASN1Result(der: &[u8]) -> ASN1Result fmt::Result { - match self { - &Pkcs12Error::ASN1(ref e) => f.write_fmt(format_args!("Error parsing ASN.1: {}", e)), - &Pkcs12Error::Crypto(ref e) => f.write_fmt(format_args!("Cryptographic error {}", e)), - &Pkcs12Error::Custom(ref s) => f.write_fmt(format_args!("{}", s)), + match *self { + Pkcs12Error::ASN1(ref e) => f.write_fmt(format_args!("Error parsing ASN.1: {}", e)), + Pkcs12Error::Crypto(ref e) => f.write_fmt(format_args!("Cryptographic error {}", e)), + Pkcs12Error::Custom(ref s) => f.write_fmt(format_args!("{}", s)), } } } @@ -165,10 +165,10 @@ impl fmt::Display for Pkcs12Error { #[cfg(feature = "std")] impl StdError for Pkcs12Error { fn description(&self) -> &str { - match self { - &Pkcs12Error::ASN1(_) => "Error parsing ASN.1", - &Pkcs12Error::Crypto(_) => "Cryptographic error", - &Pkcs12Error::Custom(_) => "Format problem", + match *self { + Pkcs12Error::ASN1(_) => "Error parsing ASN.1", + Pkcs12Error::Crypto(_) => "Cryptographic error", + Pkcs12Error::Custom(_) => "Format problem", } } } @@ -208,7 +208,7 @@ impl BERDecodable for AlgorithmIdentifier { fn decode_ber(reader: BERReader) -> ASN1Result { reader.read_sequence(|reader| { let algo = reader.next().read_oid()?; - let params = reader.next().read_der().ok().unwrap_or(Vec::new()); + let params = reader.next().read_der().ok().unwrap_or_default(); Ok(AlgorithmIdentifier { algo, params }) }) @@ -393,9 +393,9 @@ impl BERDecodable for CertBag { let pkcs12cert = read_struct_from_bytes::(&blob)?; if pkcs12cert.cert_type == ObjectIdentifier::from_slice(PKCS9_X509_CERT) { - return Ok(CertBag(Some(pkcs12cert.cert_blob.to_vec()))); + Ok(CertBag(Some(pkcs12cert.cert_blob.to_vec()))) } else { - return Ok(CertBag(None)); + Ok(CertBag(None)) } } } @@ -543,7 +543,7 @@ fn decrypt_contents(data: &EncryptedData, passphrase: &[u8]) -> Pkcs12Result(&pt)?; - return Ok(sc); + Ok(sc) } fn decrypt_pkcs8(pkcs8: &[u8], passphrase: &[u8]) -> Pkcs12Result> { @@ -562,11 +562,11 @@ 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.set_key_iv(&key, &iv)?; + let cipher = cipher.set_key_iv(key, iv)?; let mut plaintext = vec![0; ciphertext.len() + 8]; - let len = cipher.decrypt(&ciphertext, &mut plaintext)?; + let len = cipher.decrypt(ciphertext, &mut plaintext)?; plaintext.truncate(len.0); - return Ok(plaintext); + Ok(plaintext) } #[cfg(feature = "pkcs12_rc2")] @@ -644,7 +644,7 @@ fn decrypt_data( &mut cipher_iv, )?; - return match cipher_algo { + match cipher_algo { Pkcs12EncryptionAlgo::TDES_168_SHA | Pkcs12EncryptionAlgo::TDES_112_SHA => { decrypt_3des(ciphertext, &cipher_key, &cipher_iv) } @@ -652,7 +652,7 @@ fn decrypt_data( Pkcs12EncryptionAlgo::RC2_128_SHA | Pkcs12EncryptionAlgo::RC2_40_SHA => { decrypt_rc2(ciphertext, &cipher_key, &cipher_iv) } - }; + } } impl Pfx { @@ -682,7 +682,7 @@ impl Pfx { let md = map_oid_to_mbedtls_digest(&mac.digest.algo.algo)?; let stored_mac = &mac.digest.digest; let salt = &mac.salt; - let iterations = mac.iterations.clone().unwrap_or(1); + let iterations = mac.iterations.unwrap_or(1); let md_info: MdInfo = match md.into() { Some(md) => md, @@ -710,7 +710,7 @@ impl Pfx { } } - return Ok(()); + Ok(()) } /// Decrypt an encrypted Pfx If mac_passphrase is None, it is assumed to be @@ -719,7 +719,7 @@ impl Pfx { /// using openssl with the -twopass option. pub fn decrypt(&self, passphrase: &str, mac_passphrase: Option<&str>) -> Pkcs12Result { // Test if this object is already decrypted - if self.raw_data.len() == 0 { + if self.raw_data.is_empty() { return Ok(self.clone()); } @@ -733,31 +733,31 @@ impl Pfx { } fn decrypt_pkcs8_sb(sb: &SafeBag, passphrase: &[u8]) -> Pkcs12Result { - if let &Pkcs12BagSet::EncryptedPkcs8(ref p8) = &sb.bag_value { - let decrypted_p8 = decrypt_pkcs8(&p8, passphrase)?; - return Ok(SafeBag { + if let Pkcs12BagSet::EncryptedPkcs8(p8) = &sb.bag_value { + let decrypted_p8 = decrypt_pkcs8(p8, passphrase)?; + Ok(SafeBag { bag_id: ObjectIdentifier::from_slice(PKCS12_BAG_KEY), bag_value: Pkcs12BagSet::Pkcs8(decrypted_p8), bag_attributes: sb.bag_attributes.clone(), - }); + }) } else { - return Ok(sb.clone()); + Ok(sb.clone()) } } fn decrypt_data(data: &AuthenticatedSafe, passphrase: &[u8]) -> Pkcs12Result { match data { - &AuthenticatedSafe::Data(ref sc) => { + AuthenticatedSafe::Data(sc) => { let mut contents = Vec::new(); for item in &sc.0 { - contents.push(decrypt_pkcs8_sb(&item, passphrase)?); + contents.push(decrypt_pkcs8_sb(item, passphrase)?); } Ok(AuthenticatedSafe::Data(SafeContents(contents))) } - &AuthenticatedSafe::EncryptedData(ref ed) => { - let decrypted = decrypt_contents(&ed, &passphrase)?; + AuthenticatedSafe::EncryptedData(ed) => { + let decrypted = decrypt_contents(ed, passphrase)?; Ok(AuthenticatedSafe::Data(decrypted)) } } @@ -766,7 +766,7 @@ impl Pfx { let mut new_authsafe = Vec::new(); for c in &self.authsafe.contents { - let d = decrypt_data(&c, &passphrase)?; + let d = decrypt_data(c, &passphrase)?; new_authsafe.push(d); } @@ -796,9 +796,7 @@ impl Pfx { /// 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 { + pub fn certificates(&self) -> impl Iterator, crate::Error>, Vec)> + '_ { 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())) @@ -810,7 +808,7 @@ impl Pfx { /// 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 { + pub fn private_keys(&self) -> impl Iterator, Vec)> + '_ { 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())) @@ -849,8 +847,8 @@ impl BERDecodable for Pfx { })?; Ok(Pfx { - raw_data: raw_data, - version: version, + raw_data, + version, authsafe: safe, macdata: mac.ok(), }) diff --git a/mbedtls/src/private.rs b/mbedtls/src/private.rs index 33df9b6f9..f4e827930 100644 --- a/mbedtls/src/private.rs +++ b/mbedtls/src/private.rs @@ -36,18 +36,18 @@ where let mut vec = Vec::with_capacity(2048 /* big because of bug in x509write */); loop { match f(vec.as_mut_ptr(), vec.capacity()).into_result() { - Err(Error::Asn1BufTooSmall) - | Err(Error::Base64BufferTooSmall) - | Err(Error::EcpBufferTooSmall) - | Err(Error::MpiBufferTooSmall) - | Err(Error::NetBufferTooSmall) - | Err(Error::OidBufTooSmall) - | Err(Error::SslBufferTooSmall) - | Err(Error::X509BufferTooSmall) - if vec.capacity() < MAX_VECTOR_ALLOCATION => - { + Err( + Error::Asn1BufTooSmall + | Error::Base64BufferTooSmall + | Error::EcpBufferTooSmall + | Error::MpiBufferTooSmall + | Error::NetBufferTooSmall + | Error::OidBufTooSmall + | Error::SslBufferTooSmall + | Error::X509BufferTooSmall, + ) if vec.capacity() < MAX_VECTOR_ALLOCATION => { let cap = vec.capacity(); - vec.reserve(cap * 2) + vec.reserve(cap * 2); } Err(e) => return Err(e), Ok(n) => { @@ -93,6 +93,6 @@ use std::io::{Error as IoError, ErrorKind as IoErrorKind}; #[cfg(feature = "std")] #[allow(dead_code)] -pub fn error_to_io_error(e: Error) -> IoError { +pub fn error_to_io_error(e: &Error) -> IoError { IoError::new(IoErrorKind::Other, e.to_string()) } diff --git a/mbedtls/src/rng/ctr_drbg.rs b/mbedtls/src/rng/ctr_drbg.rs index e0e250a91..5fd513775 100644 --- a/mbedtls/src/rng/ctr_drbg.rs +++ b/mbedtls/src/rng/ctr_drbg.rs @@ -64,13 +64,13 @@ impl CtrDrbg { &mut *inner, Some(T::call), entropy.data_ptr(), - additional_entropy.map(<[_]>::as_ptr).unwrap_or(::core::ptr::null()), - additional_entropy.map(<[_]>::len).unwrap_or(0), + additional_entropy.map_or(::core::ptr::null(), <[_]>::as_ptr), + additional_entropy.map_or(0, <[_]>::len), ) .into_result()?; } - Ok(CtrDrbg { + Ok(Self { inner, entropy: EntropyHolder::Shared(entropy), }) @@ -87,24 +87,21 @@ impl CtrDrbg { &mut *inner, 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), + additional_entropy.map_or(::core::ptr::null(), <[_]>::as_ptr), + additional_entropy.map_or(0, <[_]>::len), ) .into_result()?; } - Ok(CtrDrbg { + Ok(Self { inner, entropy: EntropyHolder::Unique(entropy), }) } + #[must_use] pub fn prediction_resistance(&self) -> bool { - if self.inner.prediction_resistance == CTR_DRBG_PR_OFF { - false - } else { - true - } + self.inner.prediction_resistance != CTR_DRBG_PR_OFF } pub fn set_prediction_resistance(&mut self, pr: bool) { @@ -120,8 +117,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_or(::core::ptr::null(), <[_]>::as_ptr), + additional_entropy.map_or(0, <[_]>::len), ) .into_result()? }; @@ -141,6 +138,7 @@ impl CtrDrbg { } impl RngCallbackMut for CtrDrbg { + #[allow(clippy::inline_always)] #[inline(always)] unsafe extern "C" fn call_mut(user_data: *mut c_void, data: *mut c_uchar, len: size_t) -> c_int where @@ -157,6 +155,7 @@ impl RngCallbackMut for CtrDrbg { } impl RngCallback for CtrDrbg { + #[allow(clippy::inline_always)] #[inline(always)] unsafe extern "C" fn call(user_data: *mut c_void, data: *mut c_uchar, len: size_t) -> c_int where diff --git a/mbedtls/src/rng/hmac_drbg.rs b/mbedtls/src/rng/hmac_drbg.rs index 27d5688eb..a2b4458f2 100644 --- a/mbedtls/src/rng/hmac_drbg.rs +++ b/mbedtls/src/rng/hmac_drbg.rs @@ -36,8 +36,8 @@ impl HmacDrbg { md_info: MdInfo, entropy: Arc, additional_entropy: Option<&[u8]>, - ) -> Result { - let mut ret = HmacDrbg { + ) -> Result { + let mut ret = Self { inner: hmac_drbg_context::default(), entropy: Some(entropy), }; @@ -49,16 +49,16 @@ impl HmacDrbg { md_info.into(), 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_or(::core::ptr::null(), <[_]>::as_ptr), + additional_entropy.map_or(0, <[_]>::len), ) .into_result()? }; Ok(ret) } - pub fn from_buf(md_info: MdInfo, entropy: &[u8]) -> Result { - let mut ret = HmacDrbg { + pub fn from_buf(md_info: MdInfo, entropy: &[u8]) -> Result { + let mut ret = Self { inner: hmac_drbg_context::default(), entropy: None, }; @@ -70,12 +70,9 @@ impl HmacDrbg { Ok(ret) } - pub fn prediction_resistance(&self) -> bool { - if self.inner.prediction_resistance == HMAC_DRBG_PR_OFF { - false - } else { - true - } + #[must_use] + pub const fn prediction_resistance(&self) -> bool { + self.inner.prediction_resistance != HMAC_DRBG_PR_OFF } pub fn set_prediction_resistance(&mut self, pr: bool) { @@ -91,8 +88,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_or(::core::ptr::null(), <[_]>::as_ptr), + additional_entropy.map_or(0, <[_]>::len), ) .into_result()? }; @@ -112,6 +109,7 @@ impl HmacDrbg { } impl RngCallbackMut for HmacDrbg { + #[allow(clippy::inline_always)] #[inline(always)] unsafe extern "C" fn call_mut(user_data: *mut c_void, data: *mut c_uchar, len: size_t) -> c_int { hmac_drbg_random(user_data, data, len) @@ -123,6 +121,7 @@ impl RngCallbackMut for HmacDrbg { } impl RngCallback for HmacDrbg { + #[allow(clippy::inline_always)] #[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: diff --git a/mbedtls/src/rng/mod.rs b/mbedtls/src/rng/mod.rs index f60d49316..ade847ae4 100644 --- a/mbedtls/src/rng/mod.rs +++ b/mbedtls/src/rng/mod.rs @@ -40,4 +40,4 @@ pub trait Random: RngCallback { } } -impl<'r, F: RngCallback> Random for F {} +impl Random for F {} diff --git a/mbedtls/src/rng/os_entropy.rs b/mbedtls/src/rng/os_entropy.rs index 924234a30..45dc1471c 100644 --- a/mbedtls/src/rng/os_entropy.rs +++ b/mbedtls/src/rng/os_entropy.rs @@ -88,6 +88,7 @@ impl OsEntropy { } impl EntropyCallback for OsEntropy { + #[allow(clippy::inline_always)] #[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: @@ -103,6 +104,7 @@ impl EntropyCallback for OsEntropy { } impl EntropyCallbackMut for OsEntropy { + #[allow(clippy::inline_always)] #[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: diff --git a/mbedtls/src/rng/rdrand.rs b/mbedtls/src/rng/rdrand.rs index 1e2092946..e211ed8d0 100644 --- a/mbedtls/src/rng/rdrand.rs +++ b/mbedtls/src/rng/rdrand.rs @@ -72,8 +72,8 @@ pub struct Entropy; impl EntropyCallback for Entropy { unsafe extern "C" fn call(_: *mut c_void, data: *mut c_uchar, len: size_t) -> c_int { - let mut outbuf = from_raw_parts_mut(data, len); - write_rng_to_slice(&mut outbuf, rdseed) + let outbuf = from_raw_parts_mut(data, len); + write_rng_to_slice(outbuf, rdseed) } fn data_ptr(&self) -> *mut c_void { @@ -83,8 +83,8 @@ impl EntropyCallback for Entropy { impl EntropyCallbackMut for Entropy { unsafe extern "C" fn call_mut(_: *mut c_void, data: *mut c_uchar, len: size_t) -> c_int { - let mut outbuf = from_raw_parts_mut(data, len); - write_rng_to_slice(&mut outbuf, rdseed) + let outbuf = from_raw_parts_mut(data, len); + write_rng_to_slice(outbuf, rdseed) } fn data_ptr_mut(&mut self) -> *mut c_void { @@ -97,10 +97,10 @@ pub struct Nrbg; 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); + let outbuf = from_raw_parts_mut(data, len); // rdrand function is thread safe - write_rng_to_slice(&mut outbuf, rdrand) + write_rng_to_slice(outbuf, rdrand) } fn data_ptr_mut(&mut self) -> *mut c_void { @@ -111,10 +111,10 @@ impl RngCallbackMut for Nrbg { 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); + let outbuf = from_raw_parts_mut(data, len); // rdrand function is thread safe - write_rng_to_slice(&mut outbuf, rdrand) + write_rng_to_slice(outbuf, rdrand) } fn data_ptr(&self) -> *mut c_void { diff --git a/mbedtls/src/ssl/async_io.rs b/mbedtls/src/ssl/async_io.rs index eca3d84ae..2ef521cc5 100644 --- a/mbedtls/src/ssl/async_io.rs +++ b/mbedtls/src/ssl/async_io.rs @@ -102,13 +102,13 @@ where self.with_bio_async(cx, |ssl_ctx| match ssl_ctx.recv(buf.initialize_unfilled()) { Err(Error::SslPeerCloseNotify) => Poll::Ready(Ok(())), Err(Error::SslWantRead) => Poll::Pending, - Err(e) => Poll::Ready(Err(crate::private::error_to_io_error(e))), + Err(e) => Poll::Ready(Err(crate::private::error_to_io_error(&e))), Ok(i) => { buf.advance(i); Poll::Ready(Ok(())) } }) - .unwrap_or_else(|| Poll::Ready(Err(crate::private::error_to_io_error(Error::NetRecvFailed)))) + .unwrap_or_else(|| Poll::Ready(Err(crate::private::error_to_io_error(&Error::NetRecvFailed)))) } } @@ -124,10 +124,10 @@ where 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))), + 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)))) + .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> { @@ -140,7 +140,7 @@ where .unwrap_or(Err(Error::NetSendFailed)) { Err(Error::SslWantWrite) => Poll::Pending, - Err(e) => Poll::Ready(Err(crate::private::error_to_io_error(e))), + Err(e) => Poll::Ready(Err(crate::private::error_to_io_error(&e))), Ok(()) => Poll::Ready(Ok(())), } } @@ -157,7 +157,7 @@ where Err(Error::SslWantRead) | Err(Error::SslWantWrite) => Poll::Pending, Err(e) => { self.drop_io(); - Poll::Ready(Err(crate::private::error_to_io_error(e))) + Poll::Ready(Err(crate::private::error_to_io_error(&e))) } Ok(()) => { self.drop_io(); diff --git a/mbedtls/src/ssl/config.rs b/mbedtls/src/ssl/config.rs index 4b6ab4cb2..1854271c7 100644 --- a/mbedtls/src/ssl/config.rs +++ b/mbedtls/src/ssl/config.rs @@ -32,13 +32,12 @@ use crate::x509::{self, Certificate, Crl, Profile, VerifyCallback}; #[allow(non_camel_case_types)] #[derive(Eq, PartialEq, PartialOrd, Ord, Debug, Copy, Clone)] +#[non_exhaustive] pub enum Version { Ssl3, Tls1_0, Tls1_1, Tls1_2, - #[doc(hidden)] - __NonExhaustive, } define!( @@ -97,7 +96,7 @@ define!( ); #[cfg(feature = "std")] -callback!(DbgCallback: Fn(i32, Cow<'_, str>, i32, Cow<'_, str>) -> ()); +callback!(DbgCallback: Fn(i32, Cow<'_, str>, i32, Cow<'_, str>)); callback!(SniCallback: Fn(&mut HandshakeContext, &[u8]) -> Result<()>); callback!(CaCallback: Fn(&MbedtlsList) -> Result>); @@ -112,7 +111,7 @@ unsafe impl Sync for NullTerminatedStrList {} impl NullTerminatedStrList { #[cfg(feature = "std")] pub fn new(list: &[&str]) -> Result { - let mut ret = NullTerminatedStrList { + let mut ret = Self { c: Vec::with_capacity(list.len() + 1), }; @@ -128,6 +127,7 @@ impl NullTerminatedStrList { Ok(ret) } + #[must_use] pub fn as_ptr(&self) -> *const *const c_char { self.c.as_ptr() as *const _ } @@ -136,7 +136,7 @@ impl NullTerminatedStrList { #[cfg(feature = "std")] impl Drop for NullTerminatedStrList { fn drop(&mut self) { - for i in self.c.iter() { + for i in &self.c { unsafe { if !(*i).is_null() { let _ = ::std::ffi::CString::from_raw(*i); @@ -179,6 +179,7 @@ define!( unsafe impl Sync for Config {} impl Config { + #[must_use] pub fn new(e: Endpoint, t: Transport, p: Preset) -> Self { let mut inner = ssl_config::default(); @@ -191,7 +192,7 @@ impl Config { ssl_config_defaults(&mut inner, e as c_int, t as c_int, p as c_int); }; - Config { + Self { inner, own_cert: vec![], own_pk: vec![], @@ -266,9 +267,6 @@ impl Config { Version::Tls1_0 => 1, Version::Tls1_1 => 2, Version::Tls1_2 => 3, - _ => { - return Err(Error::SslBadHsProtocolVersion); - } }; unsafe { ssl_conf_min_version(self.into(), 3, minor) }; @@ -281,9 +279,6 @@ impl Config { Version::Tls1_0 => 1, Version::Tls1_1 => 2, Version::Tls1_2 => 3, - _ => { - return Err(Error::SslBadHsProtocolVersion); - } }; unsafe { ssl_conf_max_version(self.into(), 3, minor) }; Ok(()) @@ -313,7 +308,7 @@ impl Config { 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()), + crl.as_ref().map_or(::core::ptr::null_mut(), |crl| crl.inner_ffi_mut()), ); } @@ -400,7 +395,7 @@ impl Config { self.into(), Some(sni_callback::), &**self.sni_callback.as_mut().unwrap() as *const _ as *mut c_void, - ) + ); } } @@ -418,7 +413,7 @@ impl Config { self.into(), Some(x509::verify_callback::), &**self.verify_callback.as_ref().unwrap() as *const _ as *mut c_void, - ) + ); } } @@ -440,7 +435,7 @@ impl Config { let cb = &mut *(closure as *mut F); let crt: &MbedtlsList = UnsafeFrom::from(&child as *const *const x509_crt).expect("valid certificate"); - match cb(&crt) { + match cb(crt) { Ok(list) => { // This does not leak due to mbedtls taking ownership from us and freeing the // certificates itself. (logic is in: @@ -458,7 +453,7 @@ impl Config { self.into(), Some(ca_callback::), &**self.ca_callback.as_mut().unwrap() as *const _ as *mut c_void, - ) + ); } } @@ -474,8 +469,7 @@ impl Config { file: *const c_char, line: c_int, message: *const c_char, - ) -> () - where + ) where F: DbgCallback + 'static, { let cb = &mut *(closure as *mut F); @@ -499,7 +493,7 @@ impl Config { self.into(), Some(dbg_callback::), &**self.dbg_callback.as_mut().unwrap() as *const _ as *mut c_void, - ) + ); } } @@ -531,7 +525,7 @@ impl Config { 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 349a34e99..cc4199920 100644 --- a/mbedtls/src/ssl/context.rs +++ b/mbedtls/src/ssl/context.rs @@ -43,10 +43,18 @@ pub struct Timer { timer_fin_ms: u32, } +#[cfg(feature = "std")] +impl Default for Timer { + fn default() -> Self { + Self::new() + } +} + #[cfg(feature = "std")] impl Timer { + #[must_use] pub fn new() -> Self { - Timer { + Self { timer_start: std::time::Instant::now(), timer_int_ms: 0, timer_fin_ms: 0, @@ -60,7 +68,7 @@ impl TimerCallback for Timer { where Self: Sized, { - let slf = (p_timer as *mut Timer).as_mut().unwrap(); + let slf = (p_timer as *mut Self).as_mut().unwrap(); slf.timer_start = std::time::Instant::now(); slf.timer_int_ms = int_ms; slf.timer_fin_ms = fin_ms; @@ -70,22 +78,20 @@ impl TimerCallback for Timer { where Self: Sized, { - let slf = (p_timer as *mut Timer).as_mut().unwrap(); + let slf = (p_timer as *mut Self).as_mut().unwrap(); if slf.timer_int_ms == 0 || slf.timer_fin_ms == 0 { return 0; } - let passed = std::time::Instant::now() - slf.timer_start; + let passed = slf.timer_start.elapsed(); if passed.as_millis() >= slf.timer_fin_ms.into() { 2 - } else if passed.as_millis() >= slf.timer_int_ms.into() { - 1 } else { - 0 + i32::from(passed.as_millis() >= slf.timer_int_ms.into()) } } fn data_ptr(&mut self) -> *mut mbedtls_sys::types::raw_types::c_void { - self as *mut _ as *mut _ + std::ptr::from_mut(self) as *mut _ } } @@ -133,19 +139,20 @@ pub struct Context { // should be reviewed whether they don't result in any side-effect. unsafe impl Sync for Context {} -impl<'a, T> Into<*const ssl_context> for &'a Context { - fn into(self) -> *const ssl_context { - self.handle() +impl<'a, T> From<&'a Context> for *const ssl_context { + fn from(val: &'a Context) -> Self { + val.handle() } } -impl<'a, T> Into<*mut ssl_context> for &'a mut Context { - fn into(self) -> *mut ssl_context { - self.handle_mut() +impl<'a, T> From<&'a mut Context> for *mut ssl_context { + fn from(val: &'a mut Context) -> Self { + val.handle_mut() } } impl Context { + #[must_use] pub fn new(config: Arc) -> Self { let mut inner = ssl_context::default(); @@ -154,7 +161,7 @@ impl Context { ssl_setup(&mut inner, (&*config).into()); }; - Context { + Self { inner: HandshakeContext { inner, handshake_ca_cert: None, @@ -163,14 +170,14 @@ impl Context { handshake_cert: vec![], handshake_pk: vec![], }, - config: config.clone(), + config, io: None, timer_callback: None, client_transport_id: None, } } - pub(crate) fn handle(&self) -> &::mbedtls_sys::ssl_context { + pub(crate) const fn handle(&self) -> &::mbedtls_sys::ssl_context { self.inner.handle() } @@ -297,11 +304,11 @@ impl Context { /// completed successfully in `establish`, i.e.: /// - If using non-blocking operation and `establish` failed with /// [`Error::SslWantRead`] or - /// [`Error::SslWantWrite`] + /// [`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`] + /// `HelloVerifyRequest`, i.e. `establish` failed with + /// [`Error::SslHelloVerifyRequired`] pub fn handshake(&mut self) -> Result<()> { match self.inner_handshake() { Ok(()) => Ok(()), @@ -313,13 +320,12 @@ impl Context { // again in this case and the client ID is required for a DTLS connection setup // on the server side. So we extract it before and set it after // `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( + let mut client_transport_id = (!self.inner.handle().cli_id.is_null()).then(|| { + 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() { self.set_client_transport_id(&client_id)?; @@ -371,6 +377,7 @@ impl Context { } } + #[must_use] pub fn config(&self) -> &Arc { &self.config } @@ -398,30 +405,35 @@ impl Context { self.io = None; } + #[must_use] pub fn io(&self) -> Option<&T> { - self.io.as_ref().map(|v| &**v) + self.io.as_deref() } pub fn io_mut(&mut self) -> Option<&mut T> { - self.io.as_mut().map(|v| &mut **v) + self.io.as_deref_mut() } /// Return the minor number of the negotiated TLS version + #[must_use] pub fn minor_version(&self) -> i32 { self.handle().minor_ver } /// Return the major number of the negotiated TLS version - pub fn major_version(&self) -> i32 { + #[must_use] + pub const fn major_version(&self) -> i32 { self.handle().major_ver } /// Return the number of bytes currently available to read that /// are stored in the Session's internal read buffer + #[must_use] pub fn bytes_available(&self) -> usize { unsafe { ssl_get_bytes_avail(self.into()) } } + #[must_use] pub fn version(&self) -> Version { let major = self.major_version(); assert_eq!(major, 3); @@ -558,7 +570,8 @@ impl HandshakeContext { } pub fn set_authmode(&mut self, am: AuthMode) -> Result<()> { - if self.inner.handshake as *const _ == ::core::ptr::null() { + if self.inner.handshake.is_null() { + //if self.inner.handshake as *const _ == ::core::ptr::null() { return Err(Error::SslBadInputData); } @@ -568,7 +581,8 @@ impl HandshakeContext { 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() { + if self.inner.handshake.is_null() { + //if self.inner.handshake as *const _ == ::core::ptr::null() { return Err(Error::SslBadInputData); } @@ -576,11 +590,8 @@ 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()), - crl.as_ref().map(|crl| crl.inner_ffi_mut()).unwrap_or(::core::ptr::null_mut()), + chain.as_ref().map_or(::core::ptr::null_mut(), |chain| chain.inner_ffi_mut()), + crl.as_ref().map_or(::core::ptr::null_mut(), |crl| crl.inner_ffi_mut()), ); } @@ -595,7 +606,8 @@ impl HandshakeContext { /// specified using this function is used. 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() { + if self.inner.handshake.is_null() || chain.is_empty() { + //if self.inner.handshake as *const _ == ::core::ptr::null() || chain.is_empty() { return Err(Error::SslBadInputData); } diff --git a/mbedtls/src/ssl/io.rs b/mbedtls/src/ssl/io.rs index 237468e6d..24893a849 100644 --- a/mbedtls/src/ssl/io.rs +++ b/mbedtls/src/ssl/io.rs @@ -5,7 +5,7 @@ * 2.0 , at your * option. This file may not be copied, modified, or distributed except * according to those terms. */ -//! Various I/O abstractions for use with MbedTLS's TLS sessions. +//! Various I/O abstractions for use with `MbedTLS`'s TLS sessions. //! //! If you are using `std::net::TcpStream` or any `std::io::Read` and //! `std::io::Write` streams, you probably don't need to look at any of this. @@ -14,6 +14,7 @@ //! you are implementing your own communication types or traits, consider //! implementing `Io` for them. If all else fails, implement `IoCallback`. +#![allow(clippy::module_name_repetitions)] #[cfg(feature = "std")] use std::{ io::{Error as IoError, ErrorKind as IoErrorKind, Read, Result as IoResult, Write}, @@ -56,24 +57,24 @@ pub trait IoCallback { impl, T> IoCallbackUnsafe for IO { unsafe extern "C" fn call_recv(user_data: *mut c_void, data: *mut c_uchar, len: size_t) -> c_int { - let len = if len > (c_int::max_value() as size_t) { - c_int::max_value() as size_t + let len = if len > (c_int::MAX as size_t) { + c_int::MAX as size_t } else { len }; - match (&mut *(user_data as *mut IO)).recv(::core::slice::from_raw_parts_mut(data, len)) { + match (*(user_data as *mut IO)).recv(::core::slice::from_raw_parts_mut(data, len)) { Ok(i) => i as c_int, Err(e) => e.to_int(), } } unsafe extern "C" fn call_send(user_data: *mut c_void, data: *const c_uchar, len: size_t) -> c_int { - let len = if len > (c_int::max_value() as size_t) { - c_int::max_value() as size_t + let len = if len > (c_int::MAX as size_t) { + c_int::MAX as size_t } else { len }; - match (&mut *(user_data as *mut IO)).send(::core::slice::from_raw_parts(data, len)) { + match (*(user_data as *mut IO)).send(::core::slice::from_raw_parts(data, len)) { Ok(i) => i as c_int, Err(e) => e.to_int(), } @@ -147,11 +148,12 @@ pub struct ConnectedUdpSocket { impl ConnectedUdpSocket { pub fn connect(socket: UdpSocket, addr: A) -> StdResult { match socket.connect(addr) { - Ok(_) => Ok(ConnectedUdpSocket { socket }), + Ok(()) => Ok(Self { socket }), Err(e) => Err((e, socket)), } } + #[must_use] pub fn into_socket(self) -> UdpSocket { self.socket } @@ -174,11 +176,11 @@ impl Io for ConnectedUdpSocket { impl> Io for Context { fn recv(&mut self, buf: &mut [u8]) -> Result { - Context::recv(self, buf) + Self::recv(self, buf) } fn send(&mut self, buf: &[u8]) -> Result { - Context::send(self, buf) + Self::send(self, buf) } } @@ -192,8 +194,8 @@ impl> Read for Context { fn read(&mut self, buf: &mut [u8]) -> IoResult { match self.recv(buf) { Err(Error::SslPeerCloseNotify) => Ok(0), - Err(Error::SslWantRead) | Err(Error::SslWantWrite) => Err(IoErrorKind::WouldBlock.into()), - Err(e) => Err(crate::private::error_to_io_error(e)), + Err(Error::SslWantRead | Error::SslWantWrite) => Err(IoErrorKind::WouldBlock.into()), + Err(e) => Err(crate::private::error_to_io_error(&e)), Ok(i) => Ok(i), } } @@ -209,8 +211,8 @@ impl> Write for Context { fn write(&mut self, buf: &[u8]) -> IoResult { match self.send(buf) { Err(Error::SslPeerCloseNotify) => Ok(0), - Err(Error::SslWantRead) | Err(Error::SslWantWrite) => Err(IoErrorKind::WouldBlock.into()), - Err(e) => Err(crate::private::error_to_io_error(e)), + Err(Error::SslWantRead | Error::SslWantWrite) => Err(IoErrorKind::WouldBlock.into()), + Err(e) => Err(crate::private::error_to_io_error(&e)), Ok(i) => Ok(i), } } diff --git a/mbedtls/src/wrapper_macros.rs b/mbedtls/src/wrapper_macros.rs index 29219d0dd..d6afb1bb2 100644 --- a/mbedtls/src/wrapper_macros.rs +++ b/mbedtls/src/wrapper_macros.rs @@ -73,7 +73,7 @@ macro_rules! define { { #[c_ty($raw:ty)] $(#[$m:meta])* enum $n:ident { $(#[$doc:meta] $rust:ident = $c:ident,)* } } => { define_enum!( $(#[$m])* enum $n ty $raw : $(doc ($doc) rust $rust c $c),*); }; { #[c_ty($raw:ty)] $(#[$m:meta])* enum $n:ident { $( $rust:ident = $c:ident,)* } } => { define_enum!( $(#[$m])* enum $n ty $raw : $(doc ( ) rust $rust c $c),*); }; { #[non_exhaustive] #[c_ty($raw:ty)] $(#[$m:meta])* enum $n:ident { $(#[$doc:meta] $rust:ident = $c:ident,)* } } => { define_enum!(#[non_exhaustive] $(#[$m])* enum $n ty $raw : $(doc ($doc) rust $rust c $c),*); }; - { #[non_exhaustive] #[c_ty($raw:ty)] $(#[$m:meta])* enum $n:ident { $( $rust:ident = $c:ident,)* } } => { define_enum!(#[non_exhaustive] $(#[$m])* enum $n ty $raw : $(doc ( ) rust $rust c $c),*); }; + { #[non_exhaustive] #[c_ty($raw:ty)] $(#[$m:meta])* enum $n:ident { $( $rust:ident = $c:ident,)* } } => { define_enum!(#[non_exhaustive] $(#[$m])* enum $n ty $raw : $(doc ( ) rust $rust c $c),*); } } macro_rules! define_enum { @@ -81,17 +81,12 @@ macro_rules! define_enum { $(#[$m])* pub enum $n { $($(#[$doc])* $rust,)* - // Stable-Rust equivalent of `#[non_exhaustive]` attribute. This - // value should never be used by users of this crate! - #[doc(hidden)] - __Nonexhaustive, } - impl Into<$raw> for $n { - fn into(self) -> $raw { - match self { + impl From<$n> for $raw { + fn from(item: $n) -> Self { + match item { $($n::$rust => $c,)* - $n::__Nonexhaustive => unreachable!("__Nonexhaustive value should not be instantiated"), } } } @@ -102,9 +97,9 @@ macro_rules! define_enum { $($(#[$doc])* $rust,)* } - impl Into<$raw> for $n { - fn into(self) -> $raw { - match self { + impl From<$n> for $raw { + fn from(item: $n) -> Self { + match item { $($n::$rust => $c,)* } } @@ -127,13 +122,15 @@ macro_rules! define_struct { as_item!( #[allow(dead_code)] impl<$($l)*> $name<$($l)*> { - pub(crate) fn into_inner(self) -> ::mbedtls_sys::$inner { + pub(crate) const fn into_inner(self) -> ::mbedtls_sys::$inner { let inner = self.inner; + // We don't know if self has drop, so we have to forget + #[allow(clippy::forget_non_drop)] ::core::mem::forget(self); inner } - pub(crate) fn handle(&self) -> &::mbedtls_sys::$inner { + pub(crate) const fn handle(&self) -> &::mbedtls_sys::$inner { &self.inner } @@ -162,7 +159,7 @@ macro_rules! define_struct { as_item!( #[allow(dead_code)] impl<$($l)*> $name<$($l)*> { - pub(crate) fn handle(&self) -> &::mbedtls_sys::$inner { + pub(crate) const fn handle(&self) -> &::mbedtls_sys::$inner { &*self.inner } @@ -182,7 +179,12 @@ macro_rules! define_struct { define_struct!(<< $name $(lifetime $l)* inner $inner >> $($defs)*); }; { << $name:ident $(lifetime $l:tt)* inner $inner:ident >> pub const new: fn() -> Self = $ctor:ident $({ $($member:ident: $member_init:expr,)* })?; $($defs:tt)* } => { - define_struct!(init $name (pub) new $ctor $(lifetime $l)* members $($($member: $member_init,)*)* ); + define_struct!(init $name (#[must_use] pub) new $ctor $(lifetime $l)* members $($($member: $member_init,)*)* ); + impl<$($l)*> Default for $name<$($l)*> { + fn default() -> Self { + Self::new() + } + } define_struct!(<< $name $(lifetime $l)* inner $inner >> $($defs)*); }; { init $name:ident ($($vis:tt)*) $new:ident $ctor:ident $(lifetime $l:tt)* members $($member:ident: $member_init:expr,)* } => { @@ -196,7 +198,7 @@ macro_rules! define_struct { inner.assume_init() }; $name{ - inner:inner, + inner, $(r: ::core::marker::PhantomData::<&$l _>,)* $($member: $member_init,)* } @@ -225,17 +227,17 @@ macro_rules! define_struct { }; { into $name:ident inner $inner:ident $(lifetime $l:tt)* lifetime2 $l2:tt } => { as_item!( - impl<$l2,$($l),*> Into<*const $inner> for &$l2 $name<$($l)*> { - fn into(self) -> *const $inner { - self.handle() + impl<$l2,$($l),*> From<&$l2 $name<$($l)*>> for *const $inner { + fn from(item: &$l2 $name<$($l)*>) -> Self { + item.handle() } } ); as_item!( - impl<$l2,$($l),*> Into<*mut $inner> for &$l2 mut $name<$($l)*> { - fn into(self) -> *mut $inner { - self.handle_mut() + impl<$l2,$($l),*> From<&$l2 mut $name<$($l)*>> for *mut $inner { + fn from(item: &$l2 mut $name<$($l)*>) -> Self { + item.handle_mut() } } ); @@ -244,7 +246,7 @@ macro_rules! define_struct { /// Needed for compatibility with mbedtls - where we could pass /// `*const` but function signature requires `*mut` #[allow(dead_code)] - pub(crate) unsafe fn inner_ffi_mut(&self) -> *mut $inner { + pub(crate) const unsafe fn inner_ffi_mut(&self) -> *mut $inner { self.handle() as *const _ as *mut $inner } } @@ -289,12 +291,14 @@ macro_rules! setter { macro_rules! getter { { $(#[$m:meta])* $rfn:ident() -> $rty:ty = .$cfield:ident } => { $(#[$m])* + #[must_use] pub fn $rfn(&self) -> $rty { self.inner.$cfield.into() } }; { $(#[$m:meta])* $rfn:ident() -> $rty:ty = fn $cfn:ident } => { $(#[$m])* + #[must_use] pub fn $rfn(&self) -> $rty { unsafe{::mbedtls_sys::$cfn(self.into()).into()} } diff --git a/mbedtls/src/x509/certificate.rs b/mbedtls/src/x509/certificate.rs index 80cb94754..75f0fee99 100644 --- a/mbedtls/src/x509/certificate.rs +++ b/mbedtls/src/x509/certificate.rs @@ -50,7 +50,7 @@ impl BERDecodable for Extension { let oid = reader.next().read_oid()?; let critical = reader.read_optional(|r| r.read_bool())?.unwrap_or(false); let value = reader.next().read_bytes()?; - Ok(Extension { oid, critical, value }) + Ok(Self { oid, critical, value }) }) } } @@ -93,15 +93,15 @@ fn x509_time_to_time(tm: &x509_time) -> Result