Skip to content

Commit

Permalink
Merge pull request #20 from hug-dev/various-improvements
Browse files Browse the repository at this point in the history
Add various improvements
  • Loading branch information
hug-dev authored Jun 2, 2020
2 parents 47f389b + 94bbb52 commit c81f67a
Show file tree
Hide file tree
Showing 8 changed files with 91 additions and 54 deletions.
2 changes: 1 addition & 1 deletion psa-crypto-sys/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ repository = "https://github.com/parallaxsecond/rust-psa-crypto"
links = "mbedcrypto"

[build-dependencies]
bindgen = "0.50.0"
bindgen = "0.54.0"
cc = "1.0.54"
cmake = "0.1.44"

Expand Down
12 changes: 6 additions & 6 deletions psa-crypto-sys/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ links to libraries that expose this interface. The expected name
of the library is derived from the reference implementation of the
API - `mbedcrypto`.

If the library and its headers folder are already installed locally you
can specify their location using the `MBEDTLS_LIB_DIR` and `MBEDTLS_INCLUDE_DIR`
environment variables at build time. By default dynamic linking is
attempted - if you wish to link statically you can enable the `static`
feature.
If the library and its headers folder are already installed locally you can
specify their location (the full absolute path) using the `MBEDTLS_LIB_DIR` and
`MBEDTLS_INCLUDE_DIR` environment variables at build time. By default dynamic
linking is attempted - if you wish to link statically you can enable the
`static` feature.

Alternatively, the crate will attempt to build the library from scratch and
link against it statically. In this use case enabling the `static` feature
Expand All @@ -24,4 +24,4 @@ requirements for configuring and building MbedTLS can be found

Currently the version of MbedTLS built is based on the `development` branch
of their repository, as the Mbed Crypto functionality has not yet been included in
a standard release.
a standard release.
53 changes: 33 additions & 20 deletions psa-crypto-sys/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ use std::env;
use std::io::{Error, ErrorKind, Result};
use std::path::PathBuf;

fn setup_mbed_crypto() -> Result<PathBuf> {
fn compile_mbed_crypto() -> Result<PathBuf> {
let mbedtls_dir = String::from("./vendor");
println!("cargo:rerun-if-changed={}", "src/c/shim.c");
println!("cargo:rerun-if-changed={}", "src/c/shim.h");
Expand Down Expand Up @@ -62,20 +62,10 @@ fn setup_mbed_crypto() -> Result<PathBuf> {
.cflag("-DMBEDTLS_CONFIG_FILE='<config.h>'")
.build();

// Compile and package the shim library
cc::Build::new()
.include(mbed_build_path.to_str().unwrap().to_owned() + "/include")
.file("./src/c/shim.c")
.warnings(true)
.flag("-Werror")
.opt_level(2)
.try_compile("libshim.a")
.or_else(|_| Err(Error::new(ErrorKind::Other, "compiling shim.c failed")))?;

Ok(mbed_build_path)
}

fn generate_mbed_bindings(mbed_include_dir: String) -> Result<()> {
fn generate_mbed_crypto_bindings(mbed_include_dir: String) -> Result<()> {
let header = mbed_include_dir.clone() + "/psa/crypto.h";

println!("cargo:rerun-if-changed={}", header);
Expand All @@ -85,6 +75,7 @@ fn generate_mbed_bindings(mbed_include_dir: String) -> Result<()> {
.rustfmt_bindings(true)
.header("src/c/shim.h")
.generate_comments(false)
.size_t_is_usize(true)
.generate()
.or_else(|_| {
Err(Error::new(
Expand All @@ -98,6 +89,18 @@ fn generate_mbed_bindings(mbed_include_dir: String) -> Result<()> {
Ok(())
}

fn compile_shim_library(include_dir: String) -> Result<()> {
// Compile and package the shim library
cc::Build::new()
.include(include_dir)
.file("./src/c/shim.c")
.warnings(true)
.flag("-Werror")
.opt_level(2)
.try_compile("libshim.a")
.or_else(|_| Err(Error::new(ErrorKind::Other, "compiling shim.c failed")))
}

fn link_to_lib(lib_path: String, link_statically: bool) -> Result<()> {
let link_type = if link_statically { "static" } else { "dylib" };

Expand All @@ -116,21 +119,31 @@ fn link_to_lib(lib_path: String, link_statically: bool) -> Result<()> {
}

fn main() -> Result<()> {
let lib_dir = env::var("MBEDTLS_LIB_DIR");
let include_dir = env::var("MBEDTLS_INCLUDE_DIR");
let lib;
let include;
let statically;

if let (Ok(lib_dir), Ok(include_dir)) = (lib_dir, include_dir) {
generate_mbed_bindings(include_dir)?;
link_to_lib(lib_dir, cfg!(feature = "static"))?;
if let (Ok(lib_dir), Ok(include_dir)) =
(env::var("MBEDTLS_LIB_DIR"), env::var("MBEDTLS_INCLUDE_DIR"))
{
lib = lib_dir;
include = include_dir;
statically = cfg!(feature = "static");
} else {
println!("Did not find environment variables, building MbedTLS!");
let mut mbed_lib_dir = setup_mbed_crypto()?;
let mut mbed_lib_dir = compile_mbed_crypto()?;
let mut mbed_include_dir = mbed_lib_dir.clone();
mbed_lib_dir.push("lib");
mbed_include_dir.push("include");
generate_mbed_bindings(mbed_include_dir.to_str().unwrap().to_owned())?;
link_to_lib(mbed_lib_dir.to_str().unwrap().to_owned(), true)?;

lib = mbed_lib_dir.to_str().unwrap().to_owned();
include = mbed_include_dir.to_str().unwrap().to_owned();
statically = true;
}

compile_shim_library(include.clone())?;
generate_mbed_crypto_bindings(include)?;
link_to_lib(lib, statically)?;

Ok(())
}
6 changes: 6 additions & 0 deletions psa-crypto-sys/src/c/shim.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@

#include "shim.h"

psa_key_id_t
shim_get_key_id(const psa_key_attributes_t *attributes)
{
return psa_get_key_id(attributes);
}

size_t
shim_get_key_bits(const psa_key_attributes_t *attributes)
{
Expand Down
3 changes: 3 additions & 0 deletions psa-crypto-sys/src/c/shim.h
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,9 @@ const psa_key_usage_t shim_PSA_KEY_USAGE_SIGN = PSA_KEY_USAGE_SIGN;
const psa_key_usage_t shim_PSA_KEY_USAGE_VERIFY = PSA_KEY_USAGE_VERIFY;
const psa_key_usage_t shim_PSA_KEY_USAGE_DERIVE = PSA_KEY_USAGE_DERIVE;

psa_key_id_t
shim_get_key_id(const psa_key_attributes_t *attributes);

size_t
shim_get_key_bits(const psa_key_attributes_t *attributes);

Expand Down
5 changes: 5 additions & 0 deletions psa-crypto-sys/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,14 @@ pub use psa_crypto_binding::psa_drv_se_asymmetric_t;
pub use psa_crypto_binding::psa_drv_se_context_t;
pub use psa_crypto_binding::psa_drv_se_key_management_t;
pub use psa_crypto_binding::psa_drv_se_t;
pub use psa_crypto_binding::psa_key_creation_method_t;
pub use psa_crypto_binding::psa_key_slot_number_t;
pub use psa_crypto_binding::PSA_DRV_SE_HAL_VERSION;

pub unsafe fn psa_get_key_id(attributes: *const psa_key_attributes_t) -> psa_key_id_t {
psa_crypto_binding::shim_get_key_id(attributes)
}

pub unsafe fn psa_get_key_bits(attributes: *const psa_key_attributes_t) -> usize {
psa_crypto_binding::shim_get_key_bits(attributes)
}
Expand Down
3 changes: 3 additions & 0 deletions psa-crypto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@
pub mod operations;
pub mod types;

#[cfg(feature = "with-mbed-crypto")]
pub use psa_crypto_sys as ffi;

#[cfg(feature = "with-mbed-crypto")]
use core::sync::atomic::{AtomicBool, Ordering};
#[cfg(feature = "with-mbed-crypto")]
Expand Down
61 changes: 34 additions & 27 deletions psa-crypto/src/types/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,33 +201,40 @@ impl From<Status> for psa_crypto_sys::psa_status_t {
fn from(status: Status) -> psa_crypto_sys::psa_status_t {
match status {
Status::Success => psa_crypto_sys::PSA_SUCCESS,
Status::Error(error) => match error {
Error::GenericError => psa_crypto_sys::PSA_ERROR_GENERIC_ERROR,
Error::NotSupported => psa_crypto_sys::PSA_ERROR_NOT_SUPPORTED,
Error::NotPermitted => psa_crypto_sys::PSA_ERROR_NOT_PERMITTED,
Error::BufferTooSmall => psa_crypto_sys::PSA_ERROR_BUFFER_TOO_SMALL,
Error::AlreadyExists => psa_crypto_sys::PSA_ERROR_ALREADY_EXISTS,
Error::DoesNotExist => psa_crypto_sys::PSA_ERROR_DOES_NOT_EXIST,
Error::BadState => psa_crypto_sys::PSA_ERROR_BAD_STATE,
Error::InvalidArgument => psa_crypto_sys::PSA_ERROR_INVALID_ARGUMENT,
Error::InsufficientMemory => psa_crypto_sys::PSA_ERROR_INSUFFICIENT_MEMORY,
Error::InsufficientStorage => psa_crypto_sys::PSA_ERROR_INSUFFICIENT_STORAGE,
Error::CommunicationFailure => psa_crypto_sys::PSA_ERROR_COMMUNICATION_FAILURE,
Error::StorageFailure => psa_crypto_sys::PSA_ERROR_STORAGE_FAILURE,
//Error::DataCorrupt => psa_crypto_sys::PSA_ERROR_DATA_CORRUPT,
//Error::DataInvalid => psa_crypto_sys::PSA_ERROR_DATA_INVALID,
Error::HardwareFailure => psa_crypto_sys::PSA_ERROR_HARDWARE_FAILURE,
//Error::CorruptionDetected => psa_crypto_sys::PSA_ERROR_CORRUPTION_DETECTED,
Error::InsufficientEntropy => psa_crypto_sys::PSA_ERROR_INSUFFICIENT_ENTROPY,
Error::InvalidSignature => psa_crypto_sys::PSA_ERROR_INVALID_SIGNATURE,
Error::InvalidPadding => psa_crypto_sys::PSA_ERROR_INVALID_PADDING,
Error::InsufficientData => psa_crypto_sys::PSA_ERROR_INSUFFICIENT_DATA,
Error::InvalidHandle => psa_crypto_sys::PSA_ERROR_INVALID_HANDLE,
e => {
error!("No equivalent of {:?} to a psa_status_t.", e);
psa_crypto_sys::PSA_ERROR_GENERIC_ERROR
}
},
Status::Error(error) => error.into(),
}
}
}

#[cfg(feature = "with-mbed-crypto")]
impl From<Error> for psa_crypto_sys::psa_status_t {
fn from(error: Error) -> psa_crypto_sys::psa_status_t {
match error {
Error::GenericError => psa_crypto_sys::PSA_ERROR_GENERIC_ERROR,
Error::NotSupported => psa_crypto_sys::PSA_ERROR_NOT_SUPPORTED,
Error::NotPermitted => psa_crypto_sys::PSA_ERROR_NOT_PERMITTED,
Error::BufferTooSmall => psa_crypto_sys::PSA_ERROR_BUFFER_TOO_SMALL,
Error::AlreadyExists => psa_crypto_sys::PSA_ERROR_ALREADY_EXISTS,
Error::DoesNotExist => psa_crypto_sys::PSA_ERROR_DOES_NOT_EXIST,
Error::BadState => psa_crypto_sys::PSA_ERROR_BAD_STATE,
Error::InvalidArgument => psa_crypto_sys::PSA_ERROR_INVALID_ARGUMENT,
Error::InsufficientMemory => psa_crypto_sys::PSA_ERROR_INSUFFICIENT_MEMORY,
Error::InsufficientStorage => psa_crypto_sys::PSA_ERROR_INSUFFICIENT_STORAGE,
Error::CommunicationFailure => psa_crypto_sys::PSA_ERROR_COMMUNICATION_FAILURE,
Error::StorageFailure => psa_crypto_sys::PSA_ERROR_STORAGE_FAILURE,
//Error::DataCorrupt => psa_crypto_sys::PSA_ERROR_DATA_CORRUPT,
//Error::DataInvalid => psa_crypto_sys::PSA_ERROR_DATA_INVALID,
Error::HardwareFailure => psa_crypto_sys::PSA_ERROR_HARDWARE_FAILURE,
//Error::CorruptionDetected => psa_crypto_sys::PSA_ERROR_CORRUPTION_DETECTED,
Error::InsufficientEntropy => psa_crypto_sys::PSA_ERROR_INSUFFICIENT_ENTROPY,
Error::InvalidSignature => psa_crypto_sys::PSA_ERROR_INVALID_SIGNATURE,
Error::InvalidPadding => psa_crypto_sys::PSA_ERROR_INVALID_PADDING,
Error::InsufficientData => psa_crypto_sys::PSA_ERROR_INSUFFICIENT_DATA,
Error::InvalidHandle => psa_crypto_sys::PSA_ERROR_INVALID_HANDLE,
e => {
error!("No equivalent of {:?} to a psa_status_t.", e);
psa_crypto_sys::PSA_ERROR_GENERIC_ERROR
}
}
}
}
Expand Down

0 comments on commit c81f67a

Please sign in to comment.