Skip to content

Commit

Permalink
Merge #259
Browse files Browse the repository at this point in the history
259: [v0.8] Move `self test, threading, time` code to crate `mbedtls-platform-support` r=arai-fortanix a=Taowyoo

This PR back-port changes in

- #254

into `v0.8` branch

2. Bump `rust-mbedtls` version to `0.8.3`

The patch in root `Cargo.toml` file will be removed once #254 is merged and new crates have been published to crates.io 

Co-authored-by: bors[bot] <26634292+bors[bot]@users.noreply.github.com>
Co-authored-by: Yuxiang Cao <[email protected]>
  • Loading branch information
bors[bot] and Taowyoo authored May 12, 2023
2 parents fa98271 + ac84a02 commit 551110f
Show file tree
Hide file tree
Showing 12 changed files with 176 additions and 337 deletions.
51 changes: 45 additions & 6 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[workspace]
members = ["mbedtls", "mbedtls-sys"]
members = ["mbedtls"]
21 changes: 11 additions & 10 deletions mbedtls/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "mbedtls"
version = "0.8.2"
version = "0.8.3"
authors = ["Jethro Beekman <[email protected]>"]
build = "build.rs"
edition = "2018"
Expand All @@ -20,7 +20,6 @@ keywords = ["MbedTLS","mbed","TLS","SSL","cryptography"]
[dependencies]
bitflags = "1"
core_io = { version = "0.1", features = ["collections"], optional = true }
spin = { version = "0.4.0", default-features = false, optional = true }
serde = { version = "1.0.7", default-features = false }
serde_derive = "1.0.7"
byteorder = "1.0.0"
Expand All @@ -33,13 +32,14 @@ cfg-if = "1.0.0"

[target.x86_64-fortanix-unknown-sgx.dependencies]
rs-libc = "0.2.0"
chrono = "0.4"

[dependencies.mbedtls-sys-auto]
version = "2.25.0"
default-features = false
features = ["custom_printf", "trusted_cert_callback", "threading"]
path = "../mbedtls-sys"
features = ["trusted_cert_callback", "threading"]

[dependencies.mbedtls-platform-support]
version = "0.1"

[dev-dependencies]
libc = "0.2.0"
Expand All @@ -51,19 +51,20 @@ hyper = { version = "0.10.16", default-features = false }

[build-dependencies]
cc = "1.0"
rustc_version = "0.2"

[features]
# Features are documented in the README
default = ["std", "aesni", "time", "padlock"]
std = ["mbedtls-sys-auto/std", "serde/std", "yasna"]
std = ["mbedtls-sys-auto/std", "serde/std", "yasna", "mbedtls-platform-support/std"]
debug = ["mbedtls-sys-auto/debug"]
no_std_deps = ["core_io", "spin"]
force_aesni_support = ["mbedtls-sys-auto/custom_has_support", "mbedtls-sys-auto/aes_alt", "aesni"]
no_std_deps = ["core_io", "mbedtls-platform-support/spin"]
force_aesni_support = ["mbedtls-platform-support/force_aesni_support", "mbedtls-sys-auto/custom_has_support", "mbedtls-sys-auto/aes_alt", "aesni"]
mpi_force_c_code = ["mbedtls-sys-auto/mpi_force_c_code"]
rdrand = []
aesni = ["mbedtls-sys-auto/aesni"]
aesni = ["mbedtls-platform-support/aesni"]
zlib = ["mbedtls-sys-auto/zlib"]
time = ["mbedtls-sys-auto/time"]
time = ["mbedtls-platform-support/time"]
padlock = ["mbedtls-sys-auto/padlock"]
dsa = ["std", "yasna", "num-bigint", "bit-vec"]
pkcs12 = ["std", "yasna"]
Expand Down
36 changes: 31 additions & 5 deletions mbedtls/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,40 @@
* option. This file may not be copied, modified, or distributed except
* according to those terms. */

use rustc_version::{version, Version};
use std::collections::{HashMap, HashSet};
use std::env;

/// Return the crate hash that Cargo will be passing to `rustc -C metadata=`.
// If there's a panic in this code block, that means Cargo's way of running the
// build script has changed, and this code should be updated to handle the new
// case.
fn get_compilation_metadata_hash() -> String {
let out_dir: std::path::PathBuf = std::env::var_os("OUT_DIR").unwrap().into();
let mut out_dir_it = out_dir.iter().rev();
assert_eq!(out_dir_it.next().unwrap(), "out");
let crate_ = out_dir_it.next().unwrap().to_string_lossy();
assert!(crate_.starts_with("mbedtls-"));
crate_[8..].to_owned()
}

/// Set cfg attribute to enable unstable feature based on `rustc`'s version.
/// Some of code needs feature that is unstable when compiling with rust version
/// that needed by `core-io`.
fn check_and_enable_feature() {
let min_version_with_feature = Version::parse("1.54.0").unwrap();
let rustc_version = version().unwrap();
if rustc_version < min_version_with_feature {
println!("cargo:rustc-cfg=enable_extended_key_value_attributes");
}
}

fn main() {
check_and_enable_feature();

let metadata_hash = get_compilation_metadata_hash();
println!("cargo:rustc-env=RUST_MBEDTLS_METADATA_HASH={}", metadata_hash);

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, "=")) {
Expand All @@ -24,17 +54,13 @@ fn main() {
let config_file = format!(r#""{}""#, env::var("DEP_MBEDTLS_CONFIG_H").unwrap());
b.define("MBEDTLS_CONFIG_FILE",
Some(config_file.as_str()));
b.define("RUST_MBEDTLS_METADATA_HASH", Some(metadata_hash.as_str()));

b.file("src/mbedtls_malloc.c");
b.file("src/rust_printf.c");
if sys_platform_components.get("c_compiler").map_or(false, |comps| comps.contains("freestanding")) {
b.flag("-U_FORTIFY_SOURCE")
.define("_FORTIFY_SOURCE", Some("0"))
.flag("-ffreestanding");
}
b.compile("librust-mbedtls.a");
// Force correct link order for mbedtls_printf
println!("cargo:rustc-link-lib=static=mbedtls");
println!("cargo:rustc-link-lib=static=mbedx509");
println!("cargo:rustc-link-lib=static=mbedcrypto");
}
7 changes: 5 additions & 2 deletions mbedtls/src/alloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ use core::mem::ManuallyDrop;
use mbedtls_sys::types::raw_types::c_void;

extern "C" {
pub(crate) fn forward_mbedtls_free(n: *mut mbedtls_sys::types::raw_types::c_void);
#[link_name = concat!("\u{1}forward_mbedtls_free_", env!("RUST_MBEDTLS_METADATA_HASH"))]
pub(crate) fn mbedtls_free(n: *mut mbedtls_sys::types::raw_types::c_void);
#[link_name = concat!("\u{1}forward_mbedtls_calloc_", env!("RUST_MBEDTLS_METADATA_HASH"))]
pub(crate) fn mbedtls_calloc(n: mbedtls_sys::types::size_t, size: mbedtls_sys::types::size_t) -> *mut mbedtls_sys::types::raw_types::c_void;
}

#[repr(transparent)]
Expand Down Expand Up @@ -53,7 +56,7 @@ impl<T> Drop for Box<T> {
fn drop(&mut self) {
unsafe {
drop_in_place(self.inner.as_ptr());
forward_mbedtls_free(self.inner.as_ptr() as *mut c_void)
mbedtls_free(self.inner.as_ptr() as *mut c_void)
}
}
}
Expand Down
78 changes: 18 additions & 60 deletions mbedtls/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,12 @@
#![deny(warnings)]
#![allow(unused_doc_comments)]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(enable_extended_key_value_attributes, feature(extended_key_value_attributes))]

#[cfg(not(any(feature = "std", feature = "no_std_deps")))]
compile_error!("Either the `std` or `no_std_deps` feature needs to be enabled");

#[cfg(not(feature = "std"))]
#[macro_use]
extern crate alloc as rust_alloc;

#[macro_use]
extern crate bitflags;
#[macro_use]
Expand All @@ -38,7 +37,7 @@ pub mod ecp;
pub mod hash;
pub mod pk;
pub mod rng;
pub mod self_test;
pub use mbedtls_platform_support::self_test as self_test;
pub mod ssl;
pub mod x509;
pub mod alloc;
Expand All @@ -51,37 +50,24 @@ pub mod pkcs12;
// ==============
mod private;

// needs to be pub for global visiblity
// needs to be pub for global visibility
#[doc(hidden)]
#[cfg(sys_threading_component = "custom")]
pub mod threading;

cfg_if::cfg_if! {
if #[cfg(any(feature = "force_aesni_support", target_env = "sgx"))] {
// needs to be pub for global visiblity
// needs to be pub for global visibility
#[doc(hidden)]
#[no_mangle]
pub extern "C" fn mbedtls_aesni_has_support(_what: u32) -> i32 {
return 1;
}
pub use mbedtls_platform_support::mbedtls_aesni_has_support;

// needs to be pub for global visiblity
// needs to be pub for global visibility
#[doc(hidden)]
#[no_mangle]
pub extern "C" fn mbedtls_internal_aes_encrypt(_ctx: *mut mbedtls_sys::types::raw_types::c_void,
_input: *const u8,
_output: *mut u8) -> i32 {
panic!("AES-NI support is forced but the T-tables code was invoked")
}
pub use mbedtls_platform_support::mbedtls_internal_aes_encrypt;

// needs to be pub for global visiblity
// needs to be pub for global visibility
#[doc(hidden)]
#[no_mangle]
pub extern "C" fn mbedtls_internal_aes_decrypt(_ctx: *mut mbedtls_sys::types::raw_types::c_void,
_input: *const u8,
_output: *mut u8) -> i32 {
panic!("AES-NI support is forced but the T-tables code was invoked")
}
pub use mbedtls_platform_support::mbedtls_internal_aes_decrypt;
}
}

Expand All @@ -93,6 +79,10 @@ mod mbedtls {
pub use super::*;
}

#[cfg(not(feature = "std"))]
#[macro_use]
extern crate alloc as rust_alloc;

#[cfg(not(feature = "std"))]
mod alloc_prelude {
#![allow(unused)]
Expand All @@ -107,46 +97,14 @@ mod alloc_prelude {

cfg_if::cfg_if! {
if #[cfg(sys_time_component = "custom")] {
use mbedtls_sys::types::{time_t, tm};

// needs to be pub for global visiblity
// needs to be pub for global visibility
#[doc(hidden)]
#[no_mangle]
pub unsafe extern "C" fn mbedtls_platform_gmtime_r(tt: *const time_t, tp: *mut tm) -> *mut tm {
use chrono::prelude::*;

//0 means no TZ offset
let naive = if tp.is_null() {
return core::ptr::null_mut()
} else {
NaiveDateTime::from_timestamp(*tt, 0)
};
let utc = DateTime::<Utc>::from_utc(naive, Utc);

let tp = &mut *tp;
tp.tm_sec = utc.second() as i32;
tp.tm_min = utc.minute() as i32;
tp.tm_hour = utc.hour() as i32;
tp.tm_mday = utc.day() as i32;
tp.tm_mon = utc.month0() as i32;
tp.tm_year = utc.year() as i32 - 1900;
tp.tm_wday = utc.weekday().num_days_from_monday() as i32;
tp.tm_yday = utc.ordinal0() as i32;
tp.tm_isdst = 0;

tp
}
pub use mbedtls_platform_support::mbedtls_platform_gmtime_r;

// needs to be pub for global visiblity
// needs to be pub for global visibility
#[doc(hidden)]
#[no_mangle]
pub unsafe extern "C" fn mbedtls_time(tp: *mut time_t) -> time_t {
let timestamp = chrono::Utc::now().timestamp() as time_t;
if !tp.is_null() {
*tp = timestamp;
}
timestamp
}
pub use mbedtls_platform_support::mbedtls_time;
}
}

Expand Down
10 changes: 7 additions & 3 deletions mbedtls/src/mbedtls_malloc.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,15 @@
#define mbedtls_free free
#endif

extern void *forward_mbedtls_calloc( size_t n, size_t size ) {
// Use several macros to get the preprocessor to actually replace RUST_MBEDTLS_METADATA_HASH
#define append_macro_inner(a, b) a##_##b
#define append_macro(a, b) append_macro_inner(a, b)
#define APPEND_METADATA_HASH(f) append_macro(f, RUST_MBEDTLS_METADATA_HASH)

extern void *APPEND_METADATA_HASH(forward_mbedtls_calloc)( size_t n, size_t size ) {
return mbedtls_calloc(n, size);
}

extern void forward_mbedtls_free( void *ptr ) {
extern void APPEND_METADATA_HASH(forward_mbedtls_free)( void *ptr ) {
mbedtls_free(ptr);
}

Loading

0 comments on commit 551110f

Please sign in to comment.