Skip to content

Commit f8a03da

Browse files
author
Adrian Cruceru
committed
Preparation for porting async branch
1 parent e482ea5 commit f8a03da

17 files changed

+424
-187
lines changed

mbedtls-sys/Cargo.toml

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,8 @@ quote = "1.0.9"
4242
# * strstr/strlen/strncpy/strncmp/strcmp/snprintf
4343
# * memmove/memcpy/memcmp/memset
4444
# * rand/printf (used only for self tests. optionally use custom_printf)
45-
default = ["std", "debug", "threading", "zlib", "time", "aesni", "padlock", "legacy_protocols"]
46-
std = ["debug"] # deprecated automatic enabling of debug, can be removed on major version bump
47-
debug = []
45+
default = ["std", "threading", "zlib", "time", "aesni", "padlock", "legacy_protocols"]
46+
std = [] # deprecated automatic enabling of debug, can be removed on major version bump
4847
custom_printf = []
4948
custom_has_support = []
5049
aes_alt = []

mbedtls/Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ rs-libc = "0.2.0"
3636
chrono = "0.4"
3737

3838
[dependencies.mbedtls-sys-auto]
39-
version = "2.25.0"
39+
version = "2.26.0"
4040
default-features = false
4141
features = ["custom_printf", "trusted_cert_callback", "threading"]
4242
path = "../mbedtls-sys"
@@ -56,7 +56,6 @@ cc = "1.0"
5656
# Features are documented in the README
5757
default = ["std", "aesni", "time", "padlock"]
5858
std = ["mbedtls-sys-auto/std", "serde/std", "yasna"]
59-
debug = ["mbedtls-sys-auto/debug"]
6059
no_std_deps = ["core_io", "spin"]
6160
force_aesni_support = ["mbedtls-sys-auto/custom_has_support", "mbedtls-sys-auto/aes_alt", "aesni"]
6261
mpi_force_c_code = ["mbedtls-sys-auto/mpi_force_c_code"]
@@ -68,6 +67,7 @@ padlock = ["mbedtls-sys-auto/padlock"]
6867
dsa = ["std", "yasna", "num-bigint", "bit-vec"]
6968
pkcs12 = ["std", "yasna"]
7069
pkcs12_rc2 = ["pkcs12", "rc2", "block-modes"]
70+
migration_mode=[]
7171

7272
[[example]]
7373
name = "client"

mbedtls/src/lib.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,11 @@ mod private;
5353

5454
// needs to be pub for global visiblity
5555
#[doc(hidden)]
56-
#[cfg(sys_threading_component = "custom")]
56+
57+
#[cfg(all(sys_threading_component = "custom", not(feature = "migration_mode")))]
5758
pub mod threading;
5859

60+
#[cfg(not(feature = "migration_mode"))]
5961
cfg_if::cfg_if! {
6062
if #[cfg(any(feature = "force_aesni_support", target_env = "sgx"))] {
6163
// needs to be pub for global visiblity
@@ -105,6 +107,7 @@ mod alloc_prelude {
105107
pub(crate) use rust_alloc::borrow::Cow;
106108
}
107109

110+
#[cfg(not(feature = "migration_mode"))]
108111
cfg_if::cfg_if! {
109112
if #[cfg(sys_time_component = "custom")] {
110113
use mbedtls_sys::types::{time_t, tm};
@@ -154,7 +157,7 @@ cfg_if::cfg_if! {
154157
///
155158
/// The caller must ensure no other MbedTLS code is running when calling this
156159
/// function.
157-
#[cfg(feature = "debug")]
160+
#[cfg(all(feature = "debug", not(feature = "migration_mode")))]
158161
pub unsafe fn set_global_debug_threshold(threshold: i32) {
159162
mbedtls_sys::debug_set_threshold(threshold);
160163
}

mbedtls/src/pk/dsa/mod.rs

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -217,9 +217,13 @@ fn sample_secret_value<F: Random>(upper_bound: &Mpi, rng: &mut F) -> Result<Mpi>
217217
Ok(c)
218218
}
219219

220-
fn encode_dsa_signature(r: &Mpi, s: &Mpi) -> Result<Vec<u8>> {
221-
let r = BigUint::from_bytes_be(&r.to_binary()?);
222-
let s = BigUint::from_bytes_be(&s.to_binary()?);
220+
pub fn encode_dsa_signature(r: &Mpi, s: &Mpi) -> Result<Vec<u8>> {
221+
serialize_signature(&r.to_binary()?, &s.to_binary()?)
222+
}
223+
224+
pub fn serialize_signature(r: &[u8], s: &[u8]) -> Result<Vec<u8>> {
225+
let r = BigUint::from_bytes_be(r);
226+
let s = BigUint::from_bytes_be(s);
223227

224228
Ok(yasna::construct_der(|w| {
225229
w.write_sequence(|w| {
@@ -229,6 +233,18 @@ fn encode_dsa_signature(r: &Mpi, s: &Mpi) -> Result<Vec<u8>> {
229233
}))
230234
}
231235

236+
pub fn deserialize_signature(signature: &Vec<u8>) -> Result<(Vec<u8>, Vec<u8>)> {
237+
let (r,s) = yasna::parse_der(signature, |r| {
238+
r.read_sequence(|rdr| {
239+
let r = rdr.next().read_biguint()?;
240+
let s = rdr.next().read_biguint()?;
241+
Ok((r,s))
242+
})
243+
}).map_err(|_| Error::X509InvalidSignature)?;
244+
245+
Ok((r.to_bytes_be(), s.to_bytes_be()))
246+
}
247+
232248
impl DsaPrivateKey {
233249
pub fn from_components(params: DsaParams, x: Mpi) -> Result<Self> {
234250
if x <= Mpi::new(1)? || x >= params.q {

mbedtls/src/pk/mod.rs

Lines changed: 10 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -201,34 +201,7 @@ define!(
201201
//
202202
// - Only used when creating/freeing - which is safe by design - eckey_alloc_wrap / eckey_free_wrap
203203
//
204-
// 3. ECDSA: mbedtls_ecdsa_info at ../../../mbedtls-sys/vendor/crypto/library/pk_wrap.c:729
205-
// This does not use internal locks but avoids interior mutability.
206-
//
207-
// - Const access / copies context to stack based variables:
208-
// ecdsa_verify_wrap: ../../../mbedtls-sys/vendor/crypto/library/pk_wrap.c:544
209-
// This copies the public key on the stack - in buf[] and copies the group id and nbits.
210-
// That is done via: mbedtls_pk_write_pubkey( &p, buf, &key ) where key.pk_ctx = ctx;
211-
// And the key is a const parameter to mbedtls_pk_write_pubkey - ../../../mbedtls-sys/vendor/crypto/library/pkwrite.c:158
212-
//
213-
// - Const access with additional notes due to call stacks involved.
214-
//
215-
// ecdsa_sign_wrap: ../../../mbedtls-sys/vendor/crypto/library/pk_wrap.c:657
216-
// mbedtls_ecdsa_write_signature ../../../mbedtls-sys/vendor/crypto/library/ecdsa.c:688
217-
// mbedtls_ecdsa_write_signature_restartable ../../../mbedtls-sys/vendor/crypto/library/ecdsa.c:640
218-
// MBEDTLS_ECDSA_DETERMINISTIC is not defined.
219-
// MBEDTLS_ECDSA_SIGN_ALT is not defined.
220-
// Passes grp to: ecdsa_sign_restartable: ../../../mbedtls-sys/vendor/crypto/library/ecdsa.c:253
221-
// Const access to group - reads parameters, passed as const to mbedtls_ecp_gen_privkey,
222-
// mbedtls_ecp_mul_restartable: ../../../mbedtls-sys/vendor/crypto/library/ecp.c:2351
223-
// MBEDTLS_ECP_INTERNAL_ALT is not defined. (otherwise it might not be safe depending on ecp_init/ecp_free) ../../../mbedtls-sys/build/config.rs:131
224-
// Passes as const to: mbedtls_ecp_check_privkey / mbedtls_ecp_check_pubkey / mbedtls_ecp_get_type( grp
225-
//
226-
// - Ignored due to not defined: ecdsa_verify_rs_wrap, ecdsa_sign_rs_wrap, ecdsa_rs_alloc, ecdsa_rs_free
227-
// (Undefined - MBEDTLS_ECP_RESTARTABLE - ../../../mbedtls-sys/build/config.rs:173)
228-
//
229-
// - Only const access to context: eckey_check_pair
230-
//
231-
// - Only used when creating/freeing - which is safe by design: ecdsa_alloc_wrap, ecdsa_free_wrap
204+
// 3. ECDSA - code uses mbedtls_pk wrappers. In this case code goes through ECKEY logic above. (mbedtls_pk_parse_key intentionally never calls mbedtls_pk_info_from_type with MBEDTLS_PK_ECDSA)
232205
//
233206
unsafe impl Sync for Pk {}
234207

@@ -826,7 +799,7 @@ impl Pk {
826799
///
827800
/// On success, returns the actual number of bytes written to `sig`.
828801
pub fn sign<F: Random>(
829-
&mut self,
802+
&self,
830803
md: MdType,
831804
hash: &[u8],
832805
sig: &mut [u8],
@@ -848,7 +821,7 @@ impl Pk {
848821
let mut ret = 0usize;
849822
unsafe {
850823
pk_sign(
851-
&mut self.inner,
824+
&self.inner as *const _ as *mut _,
852825
md.into(),
853826
hash.as_ptr(),
854827
hash.len(),
@@ -912,10 +885,14 @@ impl Pk {
912885
}
913886
}
914887

915-
pub fn verify(&mut self, md: MdType, hash: &[u8], sig: &[u8]) -> Result<()> {
888+
pub fn verify(&self, md: MdType, hash: &[u8], sig: &[u8]) -> Result<()> {
889+
if hash.len() == 0 || sig.len() == 0 {
890+
return Err(Error::PkBadInputData)
891+
}
892+
916893
unsafe {
917894
pk_verify(
918-
&mut self.inner,
895+
&self.inner as *const _ as *mut _,
919896
md.into(),
920897
hash.as_ptr(),
921898
hash.len(),
@@ -1240,7 +1217,7 @@ iy6KC991zzvaWY/Ys+q/84Afqa+0qJKQnPuy/7F5GkVdQA/lfbhi
12401217

12411218
#[test]
12421219
fn rsa_sign_verify_pkcs1v15() {
1243-
let mut pk =
1220+
let pk =
12441221
Pk::generate_rsa(&mut crate::test_support::rand::test_rng(), 2048, 0x10001).unwrap();
12451222
let data = b"SIGNATURE TEST SIGNATURE TEST SI";
12461223
let mut signature = vec![0u8; (pk.len() + 7) / 8];

mbedtls/src/rng/ctr_drbg.rs

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,12 @@ use mbedtls_sys::types::size_t;
1717
#[cfg(not(feature = "std"))]
1818
use crate::alloc_prelude::*;
1919
use crate::error::{IntoResult, Result};
20-
use crate::rng::{EntropyCallback, RngCallback, RngCallbackMut};
20+
use crate::rng::{EntropyCallback, EntropyCallbackMut, RngCallback, RngCallbackMut};
21+
22+
enum EntropyHolder {
23+
Shared(Arc<dyn EntropyCallback + 'static>),
24+
Unique(Box<dyn EntropyCallbackMut + 'static>),
25+
}
2126

2227
define!(
2328
// `ctr_drbg_context` inlines an `aes_context`, which is immovable. See
@@ -30,7 +35,7 @@ define!(
3035
#[c_box_ty(ctr_drbg_context)]
3136
#[repr(C)]
3237
struct CtrDrbg {
33-
entropy: Arc<dyn EntropyCallback + 'static>,
38+
entropy: EntropyHolder,
3439
};
3540
const drop: fn(&mut Self) = ctr_drbg_free;
3641
impl<'a> Into<ptr> {}
@@ -63,8 +68,28 @@ impl CtrDrbg {
6368
).into_result()?;
6469
}
6570

66-
Ok(CtrDrbg { inner, entropy })
71+
Ok(CtrDrbg { inner, entropy: EntropyHolder::Shared(entropy) })
72+
}
73+
74+
pub fn new_mut<T: EntropyCallbackMut + 'static>(entropy: T, additional_entropy: Option<&[u8]>) -> Result<Self> {
75+
let mut inner = Box::new(ctr_drbg_context::default());
76+
77+
// We take sole ownership of entropy, all access is guarded via mutexes.
78+
let mut entropy = Box::new(entropy);
79+
unsafe {
80+
ctr_drbg_init(&mut *inner);
81+
ctr_drbg_seed(
82+
&mut *inner,
83+
Some(T::call_mut),
84+
entropy.data_ptr_mut(),
85+
additional_entropy.map(<[_]>::as_ptr).unwrap_or(::core::ptr::null()),
86+
additional_entropy.map(<[_]>::len).unwrap_or(0)
87+
).into_result()?;
88+
}
89+
90+
Ok(CtrDrbg { inner, entropy: EntropyHolder::Unique(entropy) })
6791
}
92+
6893

6994
pub fn prediction_resistance(&self) -> bool {
7095
if self.inner.prediction_resistance == CTR_DRBG_PR_OFF {

mbedtls/src/rust_printf.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
#include <stdio.h>
1010
#include <stdarg.h>
1111

12-
extern void mbedtls_log(const char* msg);
12+
extern void mbedtls8_log(const char* msg);
1313

1414
extern int mbedtls_printf(const char *fmt, ...) {
1515
va_list ap;
@@ -31,7 +31,7 @@ extern int mbedtls_printf(const char *fmt, ...) {
3131
if (n<0)
3232
return -1;
3333

34-
mbedtls_log(p);
34+
mbedtls8_log(p);
3535

3636
return n;
3737
}

mbedtls/src/self_test.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ cfg_if::cfg_if! {
2525
// needs to be pub for global visiblity
2626
#[doc(hidden)]
2727
#[no_mangle]
28-
pub unsafe extern "C" fn mbedtls_log(msg: *const std::os::raw::c_char) {
28+
pub unsafe extern "C" fn mbedtls8_log(msg: *const std::os::raw::c_char) {
2929
print!("{}", std::ffi::CStr::from_ptr(msg).to_string_lossy());
3030
}
3131
} else {
@@ -35,11 +35,13 @@ cfg_if::cfg_if! {
3535
// needs to be pub for global visiblity
3636
#[doc(hidden)]
3737
#[no_mangle]
38-
pub unsafe extern "C" fn mbedtls_log(msg: *const c_char) {
38+
pub unsafe extern "C" fn mbedtls8_log(msg: *const c_char) {
3939
log_f.expect("Called self-test log without enabling self-test")(msg)
4040
}
4141
}
4242
}
43+
44+
#[cfg(not(feature = "migration_mode"))]
4345
cfg_if::cfg_if! {
4446
if #[cfg(any(not(feature = "std"), target_env = "sgx"))] {
4547
#[allow(non_upper_case_globals)]
@@ -66,6 +68,7 @@ cfg_if::cfg_if! {
6668
/// The caller needs to ensure this function is not called while any other
6769
/// function in this module is called.
6870
#[allow(unused)]
71+
#[cfg(not(feature = "migration_mode"))]
6972
pub unsafe fn enable(rand: fn() -> c_int, log: Option<unsafe fn(*const c_char)>) {
7073
#[cfg(any(not(feature = "std"), target_env = "sgx"))] {
7174
rand_f = Some(rand);
@@ -79,6 +82,7 @@ pub unsafe fn enable(rand: fn() -> c_int, log: Option<unsafe fn(*const c_char)>)
7982
///
8083
/// The caller needs to ensure this function is not called while any other
8184
/// function in this module is called.
85+
#[cfg(not(feature = "migration_mode"))]
8286
pub unsafe fn disable() {
8387
#[cfg(any(not(feature = "std"), target_env = "sgx"))] {
8488
rand_f = None;

0 commit comments

Comments
 (0)