Skip to content

Commit 0929b81

Browse files
authored
Merge branch 'master' into master
2 parents 3332d50 + 2879a2a commit 0929b81

File tree

9 files changed

+105
-101
lines changed

9 files changed

+105
-101
lines changed

Cargo.lock

Lines changed: 1 addition & 26 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

mbedtls-sys/build/cmake.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,18 @@ impl super::BuildConfig {
2626
cmk.define("CMAKE_C_COMPILER_FORCED", "TRUE");
2727
}
2828

29+
let target = std::env::var("TARGET").expect("TARGET environment variable should be set in build scripts");
30+
// thumbv6m-none-eabi, thumbv7em-none-eabi, thumbv7em-none-eabihf, thumbv7m-none-eabi
31+
// probably use arm-none-eabi-gcc which can cause the cmake compiler test to fail.
32+
if target.starts_with("thumbv") && target.contains("none-eabi") {
33+
// When building on Linux, -rdynamic flag is added automatically. Changing the
34+
// CMAKE_SYSTEM_NAME to Generic avoids this.
35+
cmk.define("CMAKE_SYSTEM_NAME", "Generic");
36+
// The compiler test requires _exit which is not available. By just trying to compile
37+
// a library, we can fix it.
38+
cmk.define("CMAKE_TRY_COMPILE_TARGET_TYPE", "STATIC_LIBRARY");
39+
}
40+
2941
let mut dst = cmk.build();
3042

3143
dst.push("build");

mbedtls/Cargo.toml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ keywords = ["MbedTLS","mbed","TLS","SSL","cryptography"]
1919

2020
[dependencies]
2121
bitflags = "1"
22-
core_io = { version = "0.1", features = ["collections"], optional = true }
2322
spin = { version = "0.4.0", default-features = false, optional = true }
2423
serde = { version = "1.0.7", default-features = false, features = ["alloc"] }
2524
serde_derive = "1.0.7"
@@ -57,7 +56,7 @@ cc = "1.0"
5756
default = ["std", "aesni", "time", "padlock"]
5857
std = ["byteorder/std", "mbedtls-sys-auto/std", "serde/std", "yasna"]
5958
debug = ["mbedtls-sys-auto/debug"]
60-
no_std_deps = ["core_io", "spin", "serde/alloc"]
59+
no_std_deps = ["spin", "serde/alloc"]
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"]
6362
rdrand = []

mbedtls/examples/client_dtls.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
// needed to have common code for `mod support` in unit and integrations tests
1010
extern crate mbedtls;
1111

12-
use std::io::{self, stdin, stdout, Write};
12+
use std::io::stdin;
1313
use std::net::UdpSocket;
1414
use std::sync::Arc;
1515

@@ -40,8 +40,14 @@ fn result_main(addr: &str) -> TlsResult<()> {
4040

4141
let mut line = String::new();
4242
stdin().read_line(&mut line).unwrap();
43-
ctx.write_all(line.as_bytes()).unwrap();
44-
io::copy(&mut ctx, &mut stdout()).unwrap();
43+
ctx.send(line.as_bytes()).unwrap();
44+
let mut resp = Vec::with_capacity(100);
45+
let len = ctx.recv(&mut resp).unwrap();
46+
if let Ok(s) = std::str::from_utf8(&resp[..len]) {
47+
println!("{}", s);
48+
} else {
49+
eprintln!("Invalid UTF-8 received");
50+
}
4551
Ok(())
4652
}
4753

mbedtls/src/cipher/raw/serde.rs

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -339,22 +339,34 @@ unsafe impl BytesSerde for des_context {}
339339
unsafe impl BytesSerde for des3_context {}
340340
unsafe impl BytesSerde for gcm_context {}
341341

342-
// If the C API changes, the serde implementation needs to be reviewed for correctness.
342+
// If the C API changes, the serde implementation needs to be reviewed for correctness. The
343+
// following (unused) functions will most probably fail to compile when this happens so a
344+
// compilation failure here reminds us of reviewing the serde impl.
343345

344-
unsafe fn _check_cipher_context_t_size(ctx: cipher_context_t) -> [u8; 96] {
346+
// The sizes of usize and isize as well as all pointer types will be dependent on the architecture
347+
// we are building for. So to be platform independent, the expected sizes are calculated from the
348+
// fixed-sized fields, the number and size of pointer-sized fields and some alignment bytes.
349+
350+
const _SIZE_OF_CIPHER_CONTEXT: usize = size_of::<usize>() + 2 * 4 + 2 * size_of::<usize>() + 16 + size_of::<usize>() + 16 + 3 * size_of::<usize>();
351+
const _SIZE_OF_AES_CONTEXT: usize = 2 * size_of::<usize>() + 4 * 68;
352+
const _SIZE_OF_DES_CONTEXT: usize = 4 * 32;
353+
const _SIZE_OF_DES3_CONTEXT: usize = 4 * 96;
354+
const _SIZE_OF_GCM_CONTEXT: usize = (_SIZE_OF_CIPHER_CONTEXT+7)/8*8 + 8 * 16 + 8 * 16 + 8 + 8 + 16 + 16 + 16 + 8; // first summand: cipher_context 8-byte aligned
355+
356+
unsafe fn _check_cipher_context_t_size(ctx: cipher_context_t) -> [u8; _SIZE_OF_CIPHER_CONTEXT] {
345357
::core::mem::transmute(ctx)
346358
}
347359

348-
unsafe fn _check_aes_context_size(ctx: aes_context) -> [u8; 288] {
360+
unsafe fn _check_aes_context_size(ctx: aes_context) -> [u8; _SIZE_OF_AES_CONTEXT] {
349361
::core::mem::transmute(ctx)
350362
}
351363

352-
unsafe fn _check_des_context_size(ctx: des_context) -> [u8; 128] {
364+
unsafe fn _check_des_context_size(ctx: des_context) -> [u8; _SIZE_OF_DES_CONTEXT] {
353365
::core::mem::transmute(ctx)
354366
}
355367

356-
unsafe fn _check_des3_context_size(ctx: des3_context) -> [u8; 384] {
368+
unsafe fn _check_des3_context_size(ctx: des3_context) -> [u8; _SIZE_OF_DES3_CONTEXT] {
357369
::core::mem::transmute(ctx)
358370
}
359371

360-
unsafe fn _check_gcm_context_size(ctx: gcm_context) -> [u8; 424] { ::core::mem::transmute(ctx) }
372+
unsafe fn _check_gcm_context_size(ctx: gcm_context) -> [u8; _SIZE_OF_GCM_CONTEXT] { ::core::mem::transmute(ctx) }

mbedtls/src/private.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,11 +88,10 @@ pub unsafe fn cstr_to_slice<'a>(ptr: *const c_char) -> &'a [u8] {
8888
::core::slice::from_raw_parts(ptr as *const _, strlen(ptr))
8989
}
9090

91-
#[cfg(not(feature = "std"))]
92-
use core_io::{Error as IoError, ErrorKind as IoErrorKind};
9391
#[cfg(feature = "std")]
9492
use std::io::{Error as IoError, ErrorKind as IoErrorKind};
9593

94+
#[cfg(feature = "std")]
9695
pub fn error_to_io_error(e: Error) -> IoError {
9796
IoError::new(IoErrorKind::Other, e.to_string())
9897
}

mbedtls/src/ssl/context.rs

Lines changed: 36 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,6 @@ use {
1414
std::sync::Arc,
1515
};
1616

17-
#[cfg(not(feature = "std"))]
18-
use core_io::{Read, Write, Result as IoResult};
19-
20-
2117
use mbedtls_sys::types::raw_types::{c_int, c_uchar, c_void};
2218
use mbedtls_sys::types::size_t;
2319
use mbedtls_sys::*;
@@ -37,6 +33,7 @@ pub trait IoCallback {
3733
fn data_ptr(&mut self) -> *mut c_void;
3834
}
3935

36+
#[cfg(feature = "std")]
4037
impl<IO: Read + Write> IoCallback for IO {
4138
unsafe extern "C" fn call_recv(user_data: *mut c_void, data: *mut c_uchar, len: size_t) -> c_int {
4239
let len = if len > (c_int::max_value() as size_t) {
@@ -488,6 +485,20 @@ impl<T> Context<T> {
488485
}
489486
}
490487

488+
impl<T: IoCallback> Context<T> {
489+
pub fn recv(&mut self, buf: &mut [u8]) -> Result<usize> {
490+
unsafe {
491+
ssl_read(self.into(), buf.as_mut_ptr(), buf.len()).into_result().map(|r| r as usize)
492+
}
493+
}
494+
495+
pub fn send(&mut self, buf: &[u8]) -> Result<usize> {
496+
unsafe {
497+
ssl_write(self.into(), buf.as_ptr(), buf.len()).into_result().map(|w| w as usize)
498+
}
499+
}
500+
}
501+
491502
impl<T> Drop for Context<T> {
492503
fn drop(&mut self) {
493504
unsafe {
@@ -497,29 +508,40 @@ impl<T> Drop for Context<T> {
497508
}
498509
}
499510

500-
impl<T: IoCallback> Read for Context<T> {
511+
#[cfg(feature = "std")]
512+
/// Implements [`std::io::Read`] whenever T implements `Read`, too. This ensures that
513+
/// `Read`, which is designated for byte-oriented sources, is only implemented when the
514+
/// underlying [`IoCallback`] is byte-oriented, too. Specifically, this means that it is implemented
515+
/// for `Context<TcpStream>`, i.e. TLS connections but not for DTLS connections.
516+
impl<T: IoCallback + Read> Read for Context<T> {
501517
fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
502-
match unsafe { ssl_read(self.into(), buf.as_mut_ptr(), buf.len()).into_result() } {
518+
match self.recv(buf) {
503519
Err(Error::SslPeerCloseNotify) => Ok(0),
504520
Err(e) => Err(crate::private::error_to_io_error(e)),
505-
Ok(i) => Ok(i as usize),
521+
Ok(i) => Ok(i),
506522
}
507523
}
508524
}
509525

510-
impl<T: IoCallback> Write for Context<T> {
526+
#[cfg(feature = "std")]
527+
/// Implements [`std::io::Write`] whenever T implements `Write`, too. This ensures that
528+
/// `Write`, which is designated for byte-oriented sinks, is only implemented when the
529+
/// underlying [`IoCallback`] is byte-oriented, too. Specifically, this means that it is implemented
530+
/// for `Context<TcpStream>`, i.e. TLS connections but not for DTLS connections.
531+
impl<T: IoCallback + Write> Write for Context<T> {
511532
fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
512-
match unsafe { ssl_write(self.into(), buf.as_ptr(), buf.len()).into_result() } {
533+
match self.send(buf) {
513534
Err(Error::SslPeerCloseNotify) => Ok(0),
514535
Err(e) => Err(crate::private::error_to_io_error(e)),
515-
Ok(i) => Ok(i as usize),
536+
Ok(i) => Ok(i),
516537
}
517538
}
518539

519540
fn flush(&mut self) -> IoResult<()> {
520541
Ok(())
521542
}
522543
}
544+
523545
//
524546
// Class exists only during SNI callback that is configured from Config.
525547
// SNI Callback must provide input whose lifetime exceeds the SNI closure to avoid memory corruptions.
@@ -603,9 +625,6 @@ mod tests {
603625
#[cfg(feature = "std")]
604626
use std::io::{Read,Write, Result as IoResult};
605627

606-
#[cfg(not(feature = "std"))]
607-
use core_io::{Read, Write, Result as IoResult};
608-
609628
use crate::ssl::context::{HandshakeContext, Context};
610629
use crate::tests::TestTrait;
611630

@@ -618,12 +637,14 @@ mod tests {
618637
_buffer: core::ptr::NonNull<u8>,
619638
}
620639

640+
#[cfg(feature = "std")]
621641
impl Read for NonSendStream {
622642
fn read(&mut self, _: &mut [u8]) -> IoResult<usize> {
623643
unimplemented!()
624644
}
625645
}
626646

647+
#[cfg(feature = "std")]
627648
impl Write for NonSendStream {
628649
fn write(&mut self, _: &[u8]) -> IoResult<usize> {
629650
unimplemented!()
@@ -638,12 +659,14 @@ mod tests {
638659
_buffer: u8,
639660
}
640661

662+
#[cfg(feature = "std")]
641663
impl Read for SendStream {
642664
fn read(&mut self, _: &mut [u8]) -> IoResult<usize> {
643665
unimplemented!()
644666
}
645667
}
646668

669+
#[cfg(feature = "std")]
647670
impl Write for SendStream {
648671
fn write(&mut self, _: &[u8]) -> IoResult<usize> {
649672
unimplemented!()

mbedtls/src/x509/certificate.rs

Lines changed: 21 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1012,58 +1012,35 @@ cYp0bH/RcPTC0Z+ZaqSWMtfxRrk63MJQF9EXpDCdvQRcTMD9D85DJrMKn8aumq0M
10121012
let c_int2 = Certificate::from_pem(C_INT2.as_bytes()).unwrap();
10131013
let mut c_root = Certificate::from_pem_multiple(C_ROOT.as_bytes()).unwrap();
10141014

1015-
{
1016-
let mut chain = MbedtlsList::<Certificate>::new();
1017-
chain.push(c_leaf.clone());
1018-
chain.push(c_int1.clone());
1019-
1020-
let err = Certificate::verify(&chain, &mut c_root, None, None).unwrap_err();
1021-
assert_eq!(err, Error::X509CertVerifyFailed);
1022-
1023-
// try again after fixing the chain
1024-
chain.push(c_int2.clone());
1025-
1026-
1027-
let mut err_str = String::new();
1028-
1029-
let verify_callback = |_crt: &Certificate, _depth: i32, verify_flags: &mut VerifyError| {
1030-
verify_flags.remove(VerifyError::CERT_EXPIRED);
1031-
Ok(())
1032-
};
1015+
// Certificate C_INT2 is missing at the beginning so the verification should fail at first
1016+
let mut chain = MbedtlsList::<Certificate>::new();
1017+
chain.push(c_leaf.clone());
1018+
chain.push(c_int1.clone());
10331019

1034-
Certificate::verify(&chain, &mut c_root, None, None).unwrap();
1035-
let res = Certificate::verify_with_callback(&chain, &mut c_root, None, Some(&mut err_str), verify_callback);
1020+
// The certificates used for this test are expired so we remove the CERT_EXPIRED flag with the callback
1021+
let verify_callback = |_crt: &Certificate, _depth: i32, verify_flags: &mut VerifyError| {
1022+
verify_flags.remove(VerifyError::CERT_EXPIRED);
1023+
Ok(())
1024+
};
10361025

1037-
match res {
1038-
Ok(()) => (),
1039-
Err(e) => assert!(false, "Failed to verify, error: {}, err_str: {}", e, err_str),
1040-
};
1026+
let res = Certificate::verify_with_callback(&chain, &mut c_root, None, None, verify_callback);
1027+
match res {
1028+
Ok(_) => panic!("Certificate chain verification should have failed, but it succeeded"),
1029+
Err(err) => assert_eq!(err, Error::X509CertVerifyFailed),
10411030
}
10421031

1043-
{
1044-
let mut chain = MbedtlsList::<Certificate>::new();
1045-
chain.push(c_leaf.clone());
1046-
chain.push(c_int1.clone());
1047-
chain.push(c_int2.clone());
1048-
1049-
Certificate::verify(&chain, &mut c_root, None, None).unwrap();
1032+
// try again after fixing the chain
1033+
chain.push(c_int2.clone());
10501034

1051-
let verify_callback = |_crt: &Certificate, _depth: i32, verify_flags: &mut VerifyError| {
1052-
verify_flags.remove(VerifyError::CERT_EXPIRED);
1053-
Ok(())
1054-
};
1035+
let mut err_str = String::new();
10551036

1056-
let mut err_str = String::new();
1057-
let res = Certificate::verify_with_callback(&chain, &mut c_root, None, Some(&mut err_str), verify_callback);
1037+
let res = Certificate::verify_with_callback(&chain, &mut c_root, None, Some(&mut err_str), verify_callback);
10581038

1059-
match res {
1060-
Ok(()) => (),
1061-
Err(e) => assert!(false, "Failed to verify, error: {}, err_str: {}", e, err_str),
1062-
};
1063-
}
1039+
match res {
1040+
Ok(()) => (),
1041+
Err(e) => panic!("Failed to verify, error: {}, err_str: {}", e, err_str),
1042+
};
10641043
}
1065-
1066-
10671044

10681045
#[test]
10691046
fn clone_test() {

0 commit comments

Comments
 (0)