Giter Site home page Giter Site logo

rust-mbedtls's Issues

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.

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

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.

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";

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.

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.

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?

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.

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.

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 🙂

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.

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

[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?

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.

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

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"

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?

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

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)

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.

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?

Check Send/Sync

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

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.

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.

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.

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).

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.

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.

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

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.

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

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```

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

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.