Giter Site home page Giter Site logo

rust-mbedtls's Introduction

Warning

The state of this repertory is changed to maintenance. We will not accept any more feature requests. Please check Change of status for details

mbedtls

Build Status

This is an idiomatic Rust wrapper for MbedTLS, allowing you to use MbedTLS with only safe code while being able to use such great Rust features like error handling and closures.

Additionally, building on MbedTLS's focus on embedded use, this crate can be used in a no_std environment.

Change of status

We discovered that mbedtls 3.4.X is not thread safe and will not work properly with multiple threads. This problem will not be fixed in short time. And the new PSA approach does not match our needs.

So we now decided to stay on mbedtls 2.28.X; and the state of this repertory is changed to maintenance. We will not accept any more feature requests.

Old code of mbedtls 3.X on master branch has been moved to branch mbedtls-3.

Related issue: #320

Reference links:

Building

This crate depends on the mbedtls-sys-auto crate, see below for build details.

Features

This is a list of the Cargo features available for mbedtls. Features in

  • x509 Enable PKI functionality. The main code enabled by this feature is in the x509 module.

  • ssl Enable ssl/tls functionality. The main code enabled by this feature is in the ssl module.

Note: The above features were introduced so that this crate could be used as a crypto (or PKI) only library.

bold are enabled by default.

  • aesni Enable support for the AES-NI instructions. On SGX, this feature is enabled automatically.
  • debug Enable debug printing to stdout. You need to configure the debug threshold at runtime.
  • dsa Enable support for DSA signatures
  • force_aesni_support MbedTLS normally uses runtime detection of AES-NI support. With this feature, always use AES-NI. This will result in undefined instruction exceptions on unsupported processors. On SGX, this feature is enabled automatically.
  • mpi_force_c_code Enables the mpi_force_c_code feature in mbedtls-sys
  • legacy_protocols Enable support for SSLv3, TLSv1.0 and TLSv1.1. Implies ssl.
  • no_std_deps On no_std, you must enable this feature. It enables optional dependencies needed on no_std. If the std feature is enabled, this feature is ignored.
  • padlock Enable support for VIA padlock.
  • pkcs12 Enable code to parse PKCS12 files using yasna. Implies x509.
  • pkcs12_rc2 Enable use of RC2 crate to decrypt RC2-encrypted PKCS12 files
  • rdrand Enable the RDRAND random number generator. On SGX, this feature is enabled automatically.
  • std If this feature is not enabled, this crate is a no_std crate. (An allocator is required) The necessary C functions to make MbedTLS work without libc will be provided.
  • time Enable time support in mbedtls-sys.
  • zlib Enable zlib support in mbedtls-sys.
  • async-rt Enable async support for SSL.
  • chrono Enable chrono support (e.g., implementation of conversion traits between x509::Time and chrono types)

mbedtls-sys-auto

Unfortunately, the mbedtls-sys crate on crates.io is claimed by another, apparently inactive, project.

To use this crate, you will need to have clang and cmake installed, see below for details.

Configuring and linking MbedTLS

MbedTLS has a plethora of compile-time configuration options that significantly impact what functionality is available. To make sure Rust's view of MbedTLS matches up with what's built in C, MbedTLS must be configured using Cargo features (see next section) and built using mbedtls-sys's build script.

The mbedtls-sys crate includes the MbedTLS source code, the MbedTLS version will have the same major.minor version as the crate. Instead of using the provided source, you can specify the path to your own source tree using the RUST_MBEDTLS_SYS_SOURCE environment variable. It is not recommended to use a custom source that is based on a different version of MbedTLS than the one provided in the crate.

The build script will perform the following steps:

  1. generate an appropriate config.h (any existing config.h is ignored),
  2. compile a statically-linked MbedTLS, this requires cmake to be installed,
  3. generate Rust bindings based on the configuration, this requires clang to be installed.

Features

This is a list of the Cargo features available for mbedtls-sys. Features in bold are enabled by default.

  • aesni Enable support for the AES-NI instructions. On SGX, this feature is enabled automatically.
  • aes_alt Allow an alternative implementation of AES, replacing the T-tables code.
  • custom_has_support Override runtime feature detection. In a dependent crate, you must define the functions mbedtls_aesni_has_support and mbedtls_padlock_has_support following the MbedTLS function signatures. On SGX, this feature is enabled automatically.
  • custom_printf Provide a custom printf implementation. printf is only used for the self tests. In a dependent crate, you must define the mbedtls_printf function with the standard printf signature.
  • debug Enable debug callbacks.
  • havege Enable the Hardware Volatile Entropy Gathering and Expansion (HAVEGE) algorithm.
  • legacy_protocols Enable support for SSLv3, TLSv1.0 and TLSv1.1
  • mpi_force_c_code MbedTLS uses assembly code for MPI functions, when available. In some situations we may prefer C code instead. This is in particular the case on x86 platforms where compile-time mitigation for speculative execution is required (e.g., LVI). Letting the compiler insert the required lfences during C-code compilation may result in faster code than letting the compiler apply mitigations on assembly code.
  • padlock Enable support for VIA padlock.
  • pkcs11 Enable PKCS#11 support. This requires pkcs11-helper to be installed.
  • std If this feature is not enabled, this crate is a no_std crate. In a no_std configuration without libc, you need to provide your own versions of the following standard C functions: calloc()/free(), and strstr()/strlen()/strncpy()/strncmp()/strcmp()/ snprintf(), and memmove()/memcpy()/memcmp()/memset(), and rand()/printf(). For printf(), you can optionally use the custom_printf feature. rand() is only needed for the selftests. On UNIX platforms, this also enables networking, filesystems and OS entropy.
  • threading Enable threading support. On cfg(unix) platforms, this uses pthreads. On other platforms, you need to provide a custom threading implementation. In a dependent crate, you must define the functions mbedtls_mutex_init(), mbedtls_mutex_free(), mbedtls_mutex_lock(), and mbedtls_mutex_unlock() following the MbedTLS function signatures.
  • time Enable time support. On cfg(unix) platforms, this uses libc. On other platforms, you need to provide your own implementations of mbedtls_platform_gmtime_r(const long long*, struct tm*) and mbedtls_time(long long*).
  • trusted_cert_callback Enable trusted certificate callback support.
  • zlib Enable zlib support.

For the complete mapping of features to config.h defines, see [mbedtls-sys/build/config.rs]. PRs adding new features are encouraged.

MbedTLS version updates

Instructions for updating to new MbedTLS source code releases in mbedtls-sys/:

  1. Wipe out vendor/ and replace it with the contents of the distribution tarball.
  2. Cherry-pick any local changes from the previous version.
  3. Use the command in build/headers.rs to generate the list of headers, and update that file as appropriate.
  4. Check build/config.rs vs. vendor/include/mbedtls/config.h.
  5. Update Cargo.toml version number.

mbedtls-selftest

This Rust crate is designed for separating self-test code that needs to export Rust functions and define C functions to be used by C mbedtls. By separating this code, different versions of Rust mbedtls crates can be used within a single crate, which helps to solve link name conflict errors.

Note: Although multiple versions of Rust mbedtls crates can be used within a single crate, only one mbedtls-selftest and one mbedtls-sys-auto crate can be used since they are built as native libraries.

Contributing

We gratefully accept bug reports and contributions from the community. By participating in this community, you agree to abide by Code of Conduct. All contributions are covered under the Developer's Certificate of Origin (DCO).

Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or

(b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or

(c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it.

(d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved.

License

This project is primarily distributed under the terms of the Apache License version 2.0 and the GNU General Public License version 2, see LICENSE-APACHE and LICENSE-GPL for details.

A note about licensing

MbedTLS is dual-licensed Apache-2.0 / GPL-2.0+, and so are the mbedtls and mbedtls-sys-auto crates. However, the sources are distributed in two different single-licensed tarballs. The authors of the mbedtls and mbedtls-sys-auto crates do not warrant that the two versions of the MbedTLS code are exactly the same. This repository includes the Apache-2.0 version. Since Apache-2.0 is compatible with GPL-3.0+ this is probably not an issue for people whishing to use mbedtls-sys in a GPL-3.0+-licensed project, but if you want to use it in a GPL-2.0-licensed project, you should probably manually specify the GPL-2.0 source when building.

rust-mbedtls's People

Contributors

adriancx avatar bors[bot] avatar bradyjoestar avatar dependabot[bot] avatar drtobe avatar gaojiaqi7 avatar goirad avatar jack-fortanix avatar jethrogb avatar jonas-schievink avatar kedars avatar landhb avatar masterawesome avatar mihirluthra avatar mzohreva avatar nickedes avatar pagten avatar paul-elliott-arm avatar randombit avatar raoulstrackx avatar s-arash avatar sburton84 avatar sduquette-devolutions avatar taowyoo avatar weibin159 avatar xiaoyuxlu avatar zugzwang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

rust-mbedtls's Issues

Bindgen ERROR: unsupported type `CXTypeKind(119)`

$ clang --version

clang version 8.0.1 (tags/RELEASE_801/final)
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin

Is there a specific version of clang required to build this project?

Improve CI flow

As @kwakkel1000 suggested, we need to add more check to the CI of this project.
Here are some points that we could add:

Here is some example CI piplines:

[Optional] I am also wondering if it's better to also replace Travis with GitHub Actions:

  • developer will be able to run CI locally to check before push
  • more tools could be used: build cache ...
  • easier control of CI jobs: I cannot stop/cancel jobs in Travis
  • more example CI setup we could reference since we do not have devops engineer for this repo : rust, rust-analyser ...

But these could be done in future, since it's not a must

Upgrade bindgen

This crate is currently using an old version of bindgen which requires LLVM 3.8 and no newer. The API and behavior has changed significantly since then, so it'll be a bit of work to upgrade.

AES KW/KWP don't support IVs

Currently we require you to set an IV for KW/KWP but this is ignored by the code as the spec defines an IV to use.

Decrypting with CBC+PKCS7 requires an extra block on the output buffer

Let c be a N+1-block ciphertext encrypting a plaintext of N blocks (i.e. with one full-block padding).
When calling decrypt on c, the output buffer needs N+2 blocks for decryption to be carried correctly (if it has less than (N+2) * blocksize bytes, it errors with CipherFullBlockExpected).

This is because here

indata.len() + self.block_size()

indata is already N+1 blocks - the space necessary to process the ciphertext. The additional block length needs to be added only when encrypting.

Add an aarch64 build to CI

Travis recently added support for aarch64 builds. Having this would help prevent regressions related to non-x86 behavior, like the cipher obj size issues seen in #67

Project Maintenance

Hey there,
I found these bindings just yesterday and am happy to see they exist. However, I'm wondering if you're still interested in maintaining the project, considering it hasn't been updated in a while.

There are a few things I would love to do, including

  • Bumping dependencies to newer versions
  • Adding CI for the testing
  • Working towards the crate getting a 1.0 release to signal stability and usability to people who are interested

I just tried to build the crate and got some weird build errors, but mostly I'm wondering if you're still around and interested in merging PRs that come up ๐Ÿ™‚

Upgrade rust-mbedtls to use 3.X mbedtls

Upgrade is required to enable TLS 1.3 support.

Here is the change list when upgrading mbedtls from 2.X to 3.X:

Change list

Changes in mbedtls-sys

Cargo.toml change

  • features
    • zlib: support for TLS record-level compression is removed in mbedtls 3.X

      • Related options removed: MBEDTLS_ZLIB_SUPPORT
    • legacy_protocols: all protocal early than TLS 1.2 is removed in mbedtls 3.X

      • Related options removed: MBEDTLS_SSL_PROTO_SSL3, MBEDTLS_SSL_PROTO_TLS1, MBEDTLS_SSL_PROTO_TLS1_1, MBEDTLS_SSL_CBC_RECORD_SPLITTING
    • pkcs11: wrapper for libpkcs11-helper is removed in mbedtls 3.X

    • mpi_force_c_code: just removed, seems something specific to our usage

  • dependencies
    • A lot of version upgrade

Config/defines change

According to 3.0-migration-guide.md:

  • Output config file name changed from config.h to mbedtls_config.h

  • Do not define MBEDTLS_CONFIG_H in mbedtls_config.h

  • Do not #include <mbedtls/check_config.h>

Changes unchecked

  • MBEDTLS_CUSTOM_HAS_AESNI and MBEDTLS_CUSTOM_HAS_PADLOCK removed in mbedtls 3.X code base

Changes in mbedtls

Cargo.toml change

  • features
    • mpi_force_c_code, zlib, legacy_protocols removed to sync with changes in mbedtls-sys
  • dependencies
    • A lot of version upgrade

Code changes

  • Add prefix private_ to a lot of fields of mbedtls types
  • Removed and added some options in Error, self_tests, CipherType, CipherMode and CipherSuite to sync with changes in mbedtls 3.X
  • Provide random number generator for fn EcPoint::mul
  • Removed Md2 and Md4 since they are no longer supported in mbedtls 3.X
  • Remove CustomPk
  • Add TLS1_3SignatureAlgorithms, since TLS 1.3 need to explicitly config Signature Algorithms when building with both TLS1.2 and TLS 1.3 flags
  • Update tests accordingly

Building for x86_64-unknown-linux-gnu fails

cargo build on an x86_64-unknown-linux-gnu target works correctly, but running cargo build --target x86_64-unknown-linux-gnu causes the following error:

/home/dario/.cargo/registry/src/github.com-1ecc6299db9ec823/mbedtls-sys-auto-2.18.4/vendor/crypto/library/aes.c:31:10: fatal error: '/home/dario/work/roche/server/target/x86_64-unknown-1-gnu/debug/build/mbedtls-sys-auto-9b28b4beb79db467/out/config.h' file not found
#include MBEDTLS_CONFIG_FILE
         ^
<command line>:1:29: note: expanded from here
#define MBEDTLS_CONFIG_FILE </home/dario/work/roche/server/target/x86_64-unknown-linux-gnu/debug/build/mbedtls-sys-auto-9b28b4beb79db467/out/config.h>

In particular, it tries to include a file from a x86_64-unknown-1-gnu target for some reason.
What is especially strange is that the error helpfully shows that the definition being expanded is in fact correct.

using cipher as i32 results in invalid value

Code:

    #[test]
    fn test_cipher_request() {
        let cipher_suites : Vec<i32> = vec![RsaWithAes128GcmSha256.into()];        
        let other_cipher_suites : Vec<i32> = vec![RsaWithAes128GcmSha256 as i32];

        println!("{:?} {:?}", cipher_suites, other_cipher_suites);
    }

Result:

     Running target/debug/deps/mbedtls_hyper-8203c142faadc4d2

running 1 test
[156] [36]

Values should match 156

The certificate used for unit testing has expired

Expired certificates:

  • mbedtls/tests/data/chain-int1.crt
  • mbedtls/tests/data/chain-int2.crt
  • mbedtls/tests/data/chain-leaf.crt
  • mbedtls/tests/data/chain-root.crt
openssl x509 -in chain-int1.crt -text -noout

Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            28:52:6a:1d:a9:65:93:d3:45:58:b6:64:a3:21:ca:a8:38:c1:57:77
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=NL, O=Staat der Nederlanden, CN=Staat der Nederlanden Domein Server CA 2020
        Validity
            Not Before: Jul 29 18:30:06 2020 GMT
            Not After : Dec  5 00:00:00 2022 GMT
        Subject: C=NL, O=QuoVadis Trustlink B.V., CN=QuoVadis PKIoverheid Server CA 2020

Improve Config/Context API

Currently the Config/Context types really only work well when you're able to put everything on a stack somewhere. Using Box/Arc requires lots of unsafe.

See also #3.

Add Windows support

Windows support is blocked on #5

after bindgen is updated:
TODO:

  1. use alloca in rust_printf.c
  2. disable multithreading, pthreads, zlib support

sys crate fails to cross compile for RISC-V

error: failed to run custom build command for `mbedtls-sys-auto v2.26.1`

Caused by:
  process didn't exit successfully: `$CARGO_TARGET_DIR/debug/build/mbedtls-sys-auto-bddc03c70d5cf91d/build-script-build` (exit status: 101)
  --- stdout
  cargo:rustc-cfg=c_compiler_component="freestanding"
  cargo:platform-components=c_compiler_component=freestanding
  cargo:rerun-if-env-changed=RUST_MBEDTLS_SYS_SOURCE
  cargo:rerun-if-changed=vendor/[a lot of files]
  OPT_LEVEL = Some("z")
  TARGET = Some("riscv32im-unknown-none-elf")
  HOST = Some("x86_64-unknown-linux-gnu")
  CC_riscv32im-unknown-none-elf = None
  CC_riscv32im_unknown_none_elf = None
  TARGET_CC = None
  CC = Some("gcc")
  CFLAGS_riscv32im-unknown-none-elf = None
  CFLAGS_riscv32im_unknown_none_elf = None
  TARGET_CFLAGS = None
  CFLAGS = None
  CRATE_CC_NO_DEFAULTS = None
  DEBUG = Some("true")
  CARGO_CFG_TARGET_FEATURE = Some("m")
  CMAKE_TOOLCHAIN_FILE_riscv32im-unknown-none-elf = None
  CMAKE_TOOLCHAIN_FILE_riscv32im_unknown_none_elf = None
  TARGET_CMAKE_TOOLCHAIN_FILE = None
  CMAKE_TOOLCHAIN_FILE = None
  CMAKE_GENERATOR_riscv32im-unknown-none-elf = None
  CMAKE_GENERATOR_riscv32im_unknown_none_elf = None
  TARGET_CMAKE_GENERATOR = None
  CMAKE_GENERATOR = None
  CMAKE_PREFIX_PATH_riscv32im-unknown-none-elf = None
  CMAKE_PREFIX_PATH_riscv32im_unknown_none_elf = None
  TARGET_CMAKE_PREFIX_PATH = None
  CMAKE_PREFIX_PATH = None
  CMAKE_riscv32im-unknown-none-elf = None
  CMAKE_riscv32im_unknown_none_elf = None
  TARGET_CMAKE = None
  CMAKE = None
  running: "cmake" "$CARGO_HOME/registry/src/github.com-1ecc6299db9ec823/mbedtls-sys-auto-2.26.1/vendor" "-DENABLE_PROGRAMS=OFF" "-DENABLE_TESTING=OFF" "-DCMAKE_INSTALL_PREFIX=$CARGO_TARGET_DIR/riscv32im-unknown-none-elf/debug/build/mbedtls-sys-auto-77187c1c28e778b3/out" "-DCMAKE_C_FLAGS= -DMBEDTLS_CONFIG_FILE=\"\\\"$CARGO_TARGET_DIR/riscv32im-unknown-none-elf/debug/build/mbedtls-sys-auto-77187c1c28e778b3/out/config.h\\\"\" -fno-builtin -D_FORTIFY_SOURCE=0 -fno-stack-protector -ffunction-sections -fdata-sections -march=rv32im -mabi=ilp32 -mcmodel=medany" "-DCMAKE_C_COMPILER=/nix/store/n5vkys6wvrfnkd381d39y5926rpqpk4w-gcc-wrapper-10.3.0/bin/gcc" "-DCMAKE_CXX_FLAGS= -ffunction-sections -fdata-sections -march=rv32im -mabi=ilp32 -mcmodel=medany" "-DCMAKE_CXX_COMPILER=/nix/store/n5vkys6wvrfnkd381d39y5926rpqpk4w-gcc-wrapper-10.3.0/bin/g++" "-DCMAKE_ASM_FLAGS= -ffunction-sections -fdata-sections -march=rv32im -mabi=ilp32 -mcmodel=medany" "-DCMAKE_ASM_COMPILER=/nix/store/n5vkys6wvrfnkd381d39y5926rpqpk4w-gcc-wrapper-10.3.0/bin/gcc" "-DCMAKE_BUILD_TYPE=MinSizeRel"
  -- The C compiler identification is GNU 10.3.0
  -- Detecting C compiler ABI info
  -- Detecting C compiler ABI info - failed
  -- Check for working C compiler: /nix/store/n5vkys6wvrfnkd381d39y5926rpqpk4w-gcc-wrapper-10.3.0/bin/gcc
  -- Check for working C compiler: /nix/store/n5vkys6wvrfnkd381d39y5926rpqpk4w-gcc-wrapper-10.3.0/bin/gcc - broken
  -- Configuring incomplete, errors occurred!
  See also "$CARGO_TARGET_DIR/riscv32im-unknown-none-elf/debug/build/mbedtls-sys-auto-77187c1c28e778b3/out/build/CMakeFiles/CMakeOutput.log".
  See also "$CARGO_TARGET_DIR/riscv32im-unknown-none-elf/debug/build/mbedtls-sys-auto-77187c1c28e778b3/out/build/CMakeFiles/CMakeError.log".

  --- stderr
  CMake Error at /nix/store/mnq9fvg9yqan4g1pgis01l0mqfkihpqs-cmake-3.21.2/share/cmake-3.21/Modules/CMakeTestCCompiler.cmake:69 (message):
    The C compiler

      "/nix/store/n5vkys6wvrfnkd381d39y5926rpqpk4w-gcc-wrapper-10.3.0/bin/gcc"

    is not able to compile a simple test program.

    It fails with the following output:

      Change Dir: $CARGO_TARGET_DIR/riscv32im-unknown-none-elf/debug/build/mbedtls-sys-auto-77187c1c28e778b3/out/build/CMakeFiles/CMakeTmp
      
      Run Build Command(s):/nix/store/h4iwyl9sq4myqdji0lbfb91gv44psvyl-gnumake-4.3/bin/make -f Makefile cmTC_7f784/fast && /nix/store/h4iwyl9sq4myqdji0lbfb91gv44psvyl-gnumake-4.3/bin/make  -f CMakeFiles/cmTC_7f784.dir/build.make CMakeFiles/cmTC_7f784.dir/build
      make[1]: Entering directory '$CARGO_TARGET_DIR/riscv32im-unknown-none-elf/debug/build/mbedtls-sys-auto-77187c1c28e778b3/out/build/CMakeFiles/CMakeTmp'
      Building C object CMakeFiles/cmTC_7f784.dir/testCCompiler.c.o
      /nix/store/n5vkys6wvrfnkd381d39y5926rpqpk4w-gcc-wrapper-10.3.0/bin/gcc   -DMBEDTLS_CONFIG_FILE="\"$CARGO_TARGET_DIR/riscv32im-unknown-none-elf/debug/build/mbedtls-sys-auto-77187c1c28e778b3/out/config.h\"" -fno-builtin -D_FORTIFY_SOURCE=0 -fno-stack-protector -ffunction-sections -fdata-sections -march=rv32im -mabi=ilp32 -mcmodel=medany  -o CMakeFiles/cmTC_7f784.dir/testCCompiler.c.o -c $CARGO_TARGET_DIR/riscv32im-unknown-none-elf/debug/build/mbedtls-sys-auto-77187c1c28e778b3/out/build/CMakeFiles/CMakeTmp/testCCompiler.c
      gcc: error: unrecognized argument in option โ€˜-mabi=ilp32โ€™
      gcc: note: valid arguments to โ€˜-mabi=โ€™ are: ms sysv
      gcc: error: unrecognized argument in option โ€˜-mcmodel=medanyโ€™
      gcc: note: valid arguments to โ€˜-mcmodel=โ€™ are: 32 kernel large medium small
      make[1]: *** [CMakeFiles/cmTC_7f784.dir/build.make:78: CMakeFiles/cmTC_7f784.dir/testCCompiler.c.o] Error 1
      make[1]: Leaving directory '$CARGO_TARGET_DIR/riscv32im-unknown-none-elf/debug/build/mbedtls-sys-auto-77187c1c28e778b3/out/build/CMakeFiles/CMakeTmp'
      make: *** [Makefile:127: cmTC_7f784/fast] Error 2
      
      

    

    CMake will not be able to correctly generate this project.
  Call Stack (most recent call first):
    CMakeLists.txt:39 (project)


  thread 'main' panicked at '
  command did not execute successfully, got: exit status: 1

  build script failed, must exit now', $CARGO_HOME/registry/src/github.com-1ecc6299db9ec823/cmake-0.1.48/src/lib.rs:975:5
  note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Other crates compile just fine, I also have the respective required cross GCCs in PATH. I know that the one time when I had an assembly file I had to add .compiler("riscv32-none-elf-gcc") in the build script to make it work. But I wouldn't know how to do this on a global scale for all dependencies.

Build failing on new nightly

Worked before, failing since at least last Thursdays's nightly. @jethrogb any ideas?

  Compiling mbedtls-sys-auto v2.18.4 (/home/travis/build/fortanix/rust-mbedtls/mbedtls-sys)

error[E0583]: file not found for module `bindings`

 --> /home/travis/build/fortanix/rust-mbedtls/target/debug/build/mbedtls-sys-auto-301cba2e8dc3f51e/out/mod-bindings.rs:1:1

  |

1 | mod bindings;

  | ^^^^^^^^^^^^^

  |

  = help: to create the module `bindings`, create file "mbedtls-sys/src/bindings.rs"

error: aborting due to previous error```

cipher.encrypt requires an excessive buffer for PKCS#7 padding.

PKCS#7 padding aligns plain data to block size.
Therefore, for a 16-byte block, the output result will be 16, 32, 48... whichever closest boundary size to the input.

However, the following code will result in CipherFullBlockExpected error.

let input: [u8; 47] = [0; 47];
let mut output: [u8; 48] = [0; 48];
let r = cipher.encrypt(&input, &mut output)?;

The following case is ok.

let input: [u8; 47] = [0; 47];
let mut output: [u8; 47+16] = [0; 47+16];
let r = cipher.encrypt(&input, &mut output)?;

So it seems that it simply adds up the block size regardless of the input length.

I can truncate result by the size of Result as a workaround, but this is an unnecessary process.

how can establish() and io() preserve more of lifetime and type for io argument?

I am trying to connect MbedTls to the ureq's newest TLSConnector.
My WIP (does not compile) is at:
https://github.com/AnimaGUS-minerva/ureq/tree/mbedtls-2/examples/mbedtls-req

I pass the desired tcp_stream into establish(), and return a Box that has the dyn ReadWrite trait:

impl TlsConnector for MbedTlsConnector {
    fn connect(
        &self,
        dns_name: &str,
        tcp_stream: TcpStream,
    ) -> Result<Box<dyn ReadWrite>, Error> {

        let ctx = self.context.lock().unwrap();

        match ctx.establish(tcp_stream, None) {

I need to implement a socket routine for this, returning the same tcp_stream as before, but the obvious method of calling context.io() isn't going to work, because it return dyn Any, and I think that I need a dyn ReadWrite.

impl ReadWrite for MbedTlsConnector {
    fn socket(&self) -> Option<&TcpStream> {
        let ctx = self.context.lock().unwrap();
        Some(&(ctx.io() as TcpStream))
    }
}

Looking for advice here. Maybe the wrapper establish()/io() should change?
Or what?

[Un]intended build dependency on clang 10?

When trying to build the crate out of the box, I run into the following:

     Running `rust-mbedtls/target/debug/build/mbedtls-sys-auto-73e3f3822172cf1c/build-script-build`
[mbedtls-sys-auto 2.18.5] rust-mbedtls/target/debug/build/mbedtls-sys-auto-73e3f3822172cf1c/
build-script-build: error while loading shared libraries: libclang.so.10svn: cannot open shared object file: No such file or directory

error: failed to run custom build command for `mbedtls-sys-auto v2.18.5 (rust-mbedtls/mbedtls-sys)`

Is the dependency on Clang 10 (released end of March 2020) expected?

fix wrong cert use in example/client.rs

#122

I was trying to run the demo in the example.

The client report the following error:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: X509CertVerifyFailed', src/main.rs:44:10
stack backtrace:
   0: rust_begin_unwind
             at /rustc/576d27c5a6c80cd39ef57d7398831d8e177573cc/library/std/src/panicking.rs:475
   1: core::panicking::panic_fmt
             at /rustc/576d27c5a6c80cd39ef57d7398831d8e177573cc/library/core/src/panicking.rs:85
   2: core::option::expect_none_failed
             at /rustc/576d27c5a6c80cd39ef57d7398831d8e177573cc/library/core/src/option.rs:1274
   3: core::result::Result<T,E>::unwrap
             at /root/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/result.rs:1005
   4: client_tls::main
             at ./src/main.rs:39
   5: core::ops::function::FnOnce::call_once
             at /root/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:233
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.

Build failed without standard library

Hi,

I am trying to use mbedtls in no_std environment with x86_64-unknown-none target without standard library built-in, but I met the following errors when compiling mbedtls:

error[E0277]: the trait bound `rust_alloc::boxed::Box<SavedRawCipher>: Deserialize<'_>` is not satisfied
    --> mbedtls/src/cipher/raw/serde.rs:52:9
     |
52   |         inner_cipher_ctx: Box<SavedRawCipher>
     |         ^^^^^^^^^^^^^^^^ the trait `Deserialize<'_>` is not implemented for `rust_alloc::boxed::Box<SavedRawCipher>`
     |
     = help: the following other types implement trait `Deserialize<'de>`:
               &'a [u8]
               &'a str
               ()
               (T0, T1)
               (T0, T1, T2)
               (T0, T1, T2, T3)
               (T0, T1, T2, T3, T4)
               (T0, T1, T2, T3, T4, T5)
             and 102 others
note: required by a bound in `next_value`
    --> /home/tdvf/.cargo/registry/src/github.com-1ecc6299db9ec823/serde-1.0.101/src/de/mod.rs:1845:12
     |
1845 |         V: Deserialize<'de>,
     |            ^^^^^^^^^^^^^^^^ required by this bound in `next_value`

Some errors have detailed explanations: E0277, E0407.
For more information about an error, try `rustc --explain E0277`.
error: could not compile `mbedtls` due to 4 previous errors
error[E0405]: cannot find trait `Default` in this scope
    --> /home/tdvf/.cargo/registry/src/github.com-1ecc6299db9ec823/byteorder-1.3.2/src/lib.rs:1831:6
     |
1831 | impl Default for LittleEndian {
     |      ^^^^^^^ not found in this scope
     |
help: consider importing this trait
     |
83   | use core::default::Default;
     |

Some errors have detailed explanations: E0405, E0425, E0463.
For more information about an error, try `rustc --explain E0405`.
error: could not compile `byteorder` due to 173 previous errors

The error message is too long, so I only pasted part of it here.
The build command I'm using is:

cargo build -p mbedtls -Zbuild-std=core,alloc,compiler_builtins --target=x86_64-unknown-none --no-default-features --features="no_std_deps,rdrand"

The same result applies to:

cargo build -p mbedtls -Zbuild-std=core,alloc,compiler_builtins --target=x86_64-unknown-linux-gnu--no-default-features --features="no_std_deps,rdrand"

Implement native-tls compatible APIs

To make sure it's easy for people to swap in MbedTLS where they were using some other TLS library before, we need to make sure native-tls could be implemented in terms of MbedTLS.

Enable os_entropy on SGX + std

If you compile for the x86_64-fortanix-unknown-sgx target, the public API looks differently in that os_entropy is not available. This should be fixed.

Check Send/Sync

We currently only implement Send on most structs when threading is enabled, but perhaps that restriction is unnecessary?

How to link rust-mbedtls to a no_std project?

Hey,

After reading the doc, I am still pretty confused about how to add this crate to a no_std project.

Could someone provide me with some hints?

Besides adding mbedtls = "0.8.1" to Cargo.toml, what should I do?

And where is the build script, sorry I didn't find any script call "build*.sh"

Sorry I am a beginner in rust and I am super confused

Best,
Yaoxin

no_std compilation

I'm having alot of trouble building this crate on a truly no_std platform (thumbv7m).

cargo build --no-default-features --features core_io --target=thumbv7m-none-eabi -j1

Initial findings are that yasna uses std, but beyond that there seems to be a whole heap of other issues like dev dependencies attempting to build and failing for that target (which I think it actually a cargo issue).

Edit: Looks like its mainly a cargo issue rust-lang/cargo#5730.

Invalid free in from_pem_multiple when loading invalid certificates

When mbedtls_x509_crt_parse parses multiple certificates, and it finds an invalid certificate (e.g. with unrecognized critical extensions), it will free the current certificate pointer. This means our strategy of calling once to determine the linked list size and then again to fill a pre-allocated linked list fails with an invalid cert in the input because mbedTLS will try to free the pre-allocated certificate.

Check &self/&mut self

There's a lot of *mut pointer usage in the MbedTLS C API but perhaps some of those usages should be *const, especially with regards to callbacks.

Implement Rust API Guidelines

  • Naming (crate aligns with Rust naming conventions)
    • Casing conforms to RFC 430 (C-CASE)
    • Ad-hoc conversions follow as_, to_, into_ conventions (C-CONV)
    • Getter names follow Rust convention (C-GETTER)
    • Methods on collections that produce iterators follow iter, iter_mut, into_iter (C-ITER)
    • Iterator type names match the methods that produce them (C-ITER-TY)
    • Feature names are free of placeholder words (C-FEATURE)
    • Names use a consistent word order (C-WORD-ORDER)
  • Interoperability (crate interacts nicely with other library functionality)
    • Types eagerly implement common traits (C-COMMON-TRAITS)
      • Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug,
        Display, Default
    • Conversions use the standard traits From, AsRef, AsMut (C-CONV-TRAITS)
    • Collections implement FromIterator and Extend (C-COLLECT)
    • Data structures implement Serde's Serialize, Deserialize (C-SERDE)
    • Types are Send and Sync where possible (C-SEND-SYNC)
    • Error types are meaningful and well-behaved (C-GOOD-ERR)
    • Binary number types provide Hex, Octal, Binary formatting (C-NUM-FMT)
    • Generic reader/writer functions take R: Read and W: Write by value (C-RW-VALUE)
  • Macros (crate presents well-behaved macros)
  • Documentation (crate is abundantly documented)
    • Crate level docs are thorough and include examples (C-CRATE-DOC)
    • All items have a rustdoc example (C-EXAMPLE)
    • Examples use ?, not try!, not unwrap (C-QUESTION-MARK)
    • Function docs include error, panic, and safety considerations (C-FAILURE)
    • Prose contains hyperlinks to relevant things (C-LINK)
    • Cargo.toml includes all common metadata (C-METADATA)
      • authors, description, license, homepage, documentation, repository,
        readme, keywords, categories
    • Crate sets html_root_url attribute "https://docs.rs/CRATE/X.Y.Z" (C-HTML-ROOT)
    • Release notes document all significant changes (C-RELNOTES)
    • Rustdoc does not show unhelpful implementation details (C-HIDDEN)
  • Predictability (crate enables legible code that acts how it looks)
    • Smart pointers do not add inherent methods (C-SMART-PTR)
    • Conversions live on the most specific type involved (C-CONV-SPECIFIC)
    • Functions with a clear receiver are methods (C-METHOD)
    • Functions do not take out-parameters (C-NO-OUT)
    • Operator overloads are unsurprising (C-OVERLOAD)
    • Only smart pointers implement Deref and DerefMut (C-DEREF)
    • Constructors are static, inherent methods (C-CTOR)
  • Flexibility (crate supports diverse real-world use cases)
    • Functions expose intermediate results to avoid duplicate work (C-INTERMEDIATE)
    • Caller decides where to copy and place data (C-CALLER-CONTROL)
    • Functions minimize assumptions about parameters by using generics (C-GENERIC)
    • Traits are object-safe if they may be useful as a trait object (C-OBJECT)
  • Type safety (crate leverages the type system effectively)
    • Newtypes provide static distinctions (C-NEWTYPE)
    • Arguments convey meaning through types, not bool or Option (C-CUSTOM-TYPE)
    • Types for a set of flags are bitflags, not enums (C-BITFLAG)
    • Builders enable construction of complex values (C-BUILDER)
  • Dependability (crate is unlikely to do the wrong thing)
  • Debuggability (crate is conducive to easy debugging)
  • Future proofing (crate is free to improve without breaking users' code)
  • Necessities (to whom they matter, they really matter)
    • Public dependencies of a stable crate are stable (C-STABLE)
    • Crate and its dependencies have a permissive license (C-PERMISSIVE)

PkKeyInvalidFormat Err, could you provide an example for x509 key/cert example?

Hi,

I saw PEM_SELF_SIGNED_CERT and PEM_SELF_SIGNED_KEY under keys.rs. But no example using them.
Could you provide one? because my code show err "PkKeyInvalidFormat", which I modified on top of mbedtls/examples/client.rs

fn result_main(addr: &str) -> TlsResult<()> {
    let entropy = Arc::new(entropy_new());
    let rng = Arc::new(CtrDrbg::new(entropy, None)?);
    let ca = Arc::new(Certificate::from_pem_multiple(keys::PEM_CERT.as_bytes())?);
    let cert = Arc::new(Certificate::from_pem_multiple(keys::PEM_SELF_SIGNED_CERT)?);
    let key = Arc::new(Pk::from_private_key(keys::PEM_SELF_SIGNED_CERT, None)?);
    let mut config = Config::new(Endpoint::Client, Transport::Stream, Preset::Default);
    config.set_rng(rng);
    config.set_ca_list(ca, None);
    config.push_cert(cert, key)?;
    let mut ctx = Context::new(Arc::new(config));

    let conn = TcpStream::connect(addr).unwrap();
    ctx.establish(conn, None)?;

    let mut line = String::new();
    stdin().read_line(&mut line).unwrap();
    ctx.write_all(line.as_bytes()).unwrap();
    io::copy(&mut ctx, &mut stdout()).unwrap();
    Ok(())
}

My private key:

pub const PEM_SELF_SIGNED_KEY: &'static [u8] = b"-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAzPZODVbGeK8NDivz+UsaClRKt90kT5lo7riFfSUUEB7s29mm
...
...
...
+PDU6Ar6LQqU8WS5IzMXOFZ+oRidKY/jljXLzjRTnUjnf//ip7OV
-----END RSA PRIVATE KEY-----\0";

How to wrap types not implementing the Copy trait?

NB: The problem detailed here does not cause any issue in the current state of rust-mbedtls.

bindgen exposes types from the vendor implementation, then some of them are "wrapped" in another type, for instance ssl_config types can be accessed through Config types:

define!(
#[c_ty(ssl_config)]
struct Config<'c>;
const init: fn() -> Self = ssl_config_init;
const drop: fn(&mut Self) = ssl_config_free;
impl<'q> Into<ptr> {}
impl<'q> UnsafeFrom<ptr> {}
);

However this mapping mechanism doesn't seem to work for types that don't implement the Copy trait. The reason for that is the into_inner() function:

pub(crate) fn into_inner(self) -> ::mbedtls_sys::$inner {
let inner = self.inner;
::core::mem::forget(self);
inner

As you can see, self.inner is moved, which is not allowed for types not implementing Copy.

How would you support such types?
What's the rationale behind wrapping the types exposed by bindgen?

Don't return cofactor for custom curves

If a curve is instantiated with custom parameters, then EcGroup::cofactor() always returns 1. This is not the case for generic curves, e.g., BLS12-381 with a cofactor of 0x396C8C005555E1568C00AAAB0000AAAB.

Supporting this would need to implement a point counting algorithm such as SEA, therefore, don't support the cofactor for custom curves (e.g. return Unsupported error).

Build fails with bindgen errors

I've been trying to use this library in a no_std project, but the build of mbedtls-sys-auto always fails with a large number of Bindgen ERROR: unsupported type `CXTypeKind(119)` errors. I tried to make sure it wasn't the result of cross-compilation or a wrong selection of features by trying to include mbedtls as a dependency in an otherwise empty project (not no_std), but the build still fails with this same bindgen error.

sgx feature includes libc deps

Currently, the sgx Cargo feature requires the std Cargo feature, which in turn requires the sys std Cargo feature, which then sets the following defines:

  • MBEDTLS_NET_C
  • MBEDTLS_FS_IO
  • MBEDTLS_NO_PLATFORM_ENTROPY
  • MBEDTLS_DEBUG_C
  • MBEDTLS_ENTROPY_C

This seems wrong, as it generates undefined symbols to libc:

$ objdump -t libmbedcrypto.a |grep fopen
0000000000000000         *UND*	0000000000000000 fopen
0000000000000000         *UND*	0000000000000000 fopen
0000000000000000         *UND*	0000000000000000 fopen
0000000000000000         *UND*	0000000000000000 fopen
0000000000000000         *UND*	0000000000000000 fopen
0000000000000000         *UND*	0000000000000000 fopen
0000000000000000         *UND*	0000000000000000 fopen
$ objdump -t libmbedtls.a |grep recvfrom
0000000000000000         *UND*	0000000000000000 recvfrom

MBEDTLS_DEBUG_C might be ok? Besides, the setting of the std feature is correct for mbedtls, as it influences conditional compilation.

Any ETA for Crate Update

Hi, it's been a while since the crate is updated on https://crates.io/crates/mbedtls, any ETA for when an update is planned?

I wish to publish a crate that depends on rust-mbedtls, and it appears I can't publish it with dependencies referring to git repositories.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.