Skip to content

Commit 6685817

Browse files
Adrian CruceruTaowyoo
authored andcommitted
Preparation for porting async branch
1 parent 7f1d694 commit 6685817

File tree

12 files changed

+79
-56
lines changed

12 files changed

+79
-56
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 & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ rs-libc = "0.2.0"
3535
chrono = "0.4"
3636

3737
[dependencies.mbedtls-sys-auto]
38-
version = "2.25.0"
38+
version = "2.26.0"
3939
default-features = false
4040
features = ["custom_printf", "trusted_cert_callback", "threading"]
4141
path = "../mbedtls-sys"
@@ -68,6 +68,7 @@ dsa = ["std", "yasna", "num-bigint", "bit-vec"]
6868
pkcs12 = ["std", "yasna"]
6969
pkcs12_rc2 = ["pkcs12", "rc2", "block-modes"]
7070
legacy_protocols = ["mbedtls-sys-auto/legacy_protocols"]
71+
migration_mode=[]
7172

7273
[[example]]
7374
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: 6 additions & 34 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],
@@ -853,7 +826,7 @@ impl Pk {
853826
let mut ret = 0usize;
854827
unsafe {
855828
pk_sign(
856-
&mut self.inner,
829+
&self.inner as *const _ as *mut _,
857830
md.into(),
858831
hash.as_ptr(),
859832
hash.len(),
@@ -922,15 +895,14 @@ impl Pk {
922895
}
923896
}
924897

925-
pub fn verify(&mut self, md: MdType, hash: &[u8], sig: &[u8]) -> Result<()> {
926-
// If hash or sig are allowed with size 0 (&[]) then mbedtls will attempt to auto-detect size and cause an invalid write.
898+
pub fn verify(&self, md: MdType, hash: &[u8], sig: &[u8]) -> Result<()> {
927899
if hash.len() == 0 || sig.len() == 0 {
928900
return Err(Error::PkBadInputData)
929901
}
930902

931903
unsafe {
932904
pk_verify(
933-
&mut self.inner,
905+
&self.inner as *const _ as *mut _,
934906
md.into(),
935907
hash.as_ptr(),
936908
hash.len(),
@@ -1255,7 +1227,7 @@ iy6KC991zzvaWY/Ys+q/84Afqa+0qJKQnPuy/7F5GkVdQA/lfbhi
12551227

12561228
#[test]
12571229
fn rsa_sign_verify_pkcs1v15() {
1258-
let mut pk =
1230+
let pk =
12591231
Pk::generate_rsa(&mut crate::test_support::rand::test_rng(), 2048, 0x10001).unwrap();
12601232
let data = b"SIGNATURE TEST SIGNATURE TEST SIGNATURE TEST SIGNATURE TEST SIGN";
12611233
let mut signature = vec![0u8; (pk.len() + 7) / 8];

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;

mbedtls/src/ssl/context.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,7 @@ impl<T> Context<T> {
251251
client_transport_id: None,
252252
}
253253
}
254+
}
254255

255256
pub(crate) fn handle(&self) -> &::mbedtls_sys::ssl_context {
256257
self.inner.handle()
@@ -541,7 +542,6 @@ impl<T: IoCallback + Write> Write for Context<T> {
541542
Ok(())
542543
}
543544
}
544-
545545
//
546546
// Class exists only during SNI callback that is configured from Config.
547547
// SNI Callback must provide input whose lifetime exceeds the SNI closure to avoid memory corruptions.
@@ -555,7 +555,7 @@ impl<T: IoCallback + Write> Write for Context<T> {
555555
// - no reasonable way to obtain a storage within the sni callback tied to the handshake or to the rust Context. (without resorting to a unscalable map or pointer magic that mbedtls may invalidate)
556556
//
557557
impl HandshakeContext {
558-
fn reset_handshake(&mut self) {
558+
pub fn reset_handshake(&mut self) {
559559
self.handshake_cert.clear();
560560
self.handshake_pk.clear();
561561
self.handshake_ca_cert = None;

mbedtls/src/wrapper_macros.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@ macro_rules! define {
6161
define_struct!(define $(#[$m])* struct $name $(lifetime $l)* inner $inner members $($($(#[$mm])* $member: $member_type,)*)*);
6262
define_struct!(<< $name $(lifetime $l)* inner $inner >> $($defs)*);
6363
};
64+
{ #[c_custom_ty($inner:ident)] $(#[$m:meta])* struct $name:ident$(<$l:tt>)* $({ $($(#[$mm:meta])* $member:ident: $member_type:ty,)* })?; $($defs:tt)* } => {
65+
define_struct!(define_custom $(#[$m])* struct $name $(lifetime $l)* inner $inner members $($($(#[$mm])* $member: $member_type,)*)*);
66+
define_struct!(<< $name $(lifetime $l)* inner $inner >> $($defs)*);
67+
};
6468
// Do not use UnsafeFrom with 'c_box_ty'. That is currently not supported as its not needed anywhere, support may be added in the future if needed anywhere.
6569
{ #[c_box_ty($inner:ident)] $(#[$m:meta])* struct $name:ident$(<$l:tt>)* $({ $($(#[$mm:meta])* $member:ident: $member_type:ty,)* })?; $($defs:tt)* } => {
6670
define_struct!(define_box $(#[$m])* struct $name $(lifetime $l)* inner $inner members $($($(#[$mm])* $member: $member_type,)*)*);
@@ -109,6 +113,32 @@ macro_rules! define_enum {
109113
}
110114

111115
macro_rules! define_struct {
116+
{ define_custom $(#[$m:meta])* struct $name:ident $(lifetime $l:tt)* inner $inner:ident members $($(#[$mm:meta])* $member:ident: $member_type:ty,)* } => {
117+
as_item!(
118+
#[allow(dead_code)]
119+
$(#[$m])*
120+
pub struct $name<$($l)*> {
121+
$($(#[$mm])* $member: $member_type,)*
122+
}
123+
);
124+
125+
as_item!(
126+
#[allow(dead_code)]
127+
impl<$($l)*> $name<$($l)*> {
128+
pub(crate) fn handle(&self) -> &::mbedtls_sys::$inner {
129+
self.inner.handle()
130+
}
131+
132+
pub(crate) fn handle_mut(&mut self) -> &mut ::mbedtls_sys::$inner {
133+
self.inner.handle_mut()
134+
}
135+
}
136+
);
137+
138+
as_item!(
139+
unsafe impl<$($l)*> Send for $name<$($l)*> {}
140+
);
141+
};
112142
{ define $(#[$m:meta])* struct $name:ident $(lifetime $l:tt)* inner $inner:ident members $($(#[$mm:meta])* $member:ident: $member_type:ty,)* } => {
113143
as_item!(
114144
#[allow(dead_code)]

mbedtls/tests/ec.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ wvkbR/h/+CNU1mMPdGoooNsldBtbNKgoAIsirMI/kk+q+9TTP4HqZpVt/qor/fz1
4444

4545
#[test]
4646
fn sign_verify() {
47-
let mut k = Pk::from_private_key(TEST_KEY_PEM.as_bytes(), None).unwrap();
47+
let k = Pk::from_private_key(TEST_KEY_PEM.as_bytes(), None).unwrap();
4848

4949
let data = b"SIGNATURE TEST SIGNATURE TEST SI";
5050
let mut signature1 = [0u8; ECDSA_MAX_LEN];
@@ -67,7 +67,7 @@ fn sign_verify() {
6767

6868
#[test]
6969
fn verify_failure() {
70-
let mut k = Pk::from_private_key(TEST_KEY_PEM.as_bytes(), None).unwrap();
70+
let k = Pk::from_private_key(TEST_KEY_PEM.as_bytes(), None).unwrap();
7171

7272
let data = b"SIGNATURE TEST SIGNATURE TEST SI";
7373
let mut signature = [0u8; ECDSA_MAX_LEN];
@@ -150,7 +150,7 @@ fn sign_verify_rfc6979_sig() {
150150

151151
#[test]
152152
fn buffer_too_small() {
153-
let mut k = Pk::from_private_key(TEST_KEY_PEM.as_bytes(), None).unwrap();
153+
let k = Pk::from_private_key(TEST_KEY_PEM.as_bytes(), None).unwrap();
154154

155155
let data = b"SIGNATURE TEST SIGNATURE TEST SI";
156156
let mut signature = [0u8; ECDSA_MAX_LEN - 1];

0 commit comments

Comments
 (0)