diff --git a/.cargo/config.toml b/.cargo/config.toml index 4d9defd..e162b88 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,3 +1,17 @@ +[build] +# Build on host +#target = "x86_64-unknown-linux-gnu" +# Build on target firmware with baremetal +#target = "xtensa-esp32-none-elf" +#target = "xtensa-esp32s2-none-elf" +#target = "xtensa-esp32s3-none-elf" +#target = "riscv32imc-unknown-none-elf" +# Build on target firmware with ESP IDF +#target = "xtensa-esp32-espidf" +#target = "xtensa-esp32s2-espidf" +#target = "xtensa-esp32s3-espidf" +#target = "riscv32imc-esp-espidf" + [target.xtensa-esp32-none-elf] runner = "espflash flash --monitor --baud 921600" @@ -37,8 +51,16 @@ rustflags = [ "-C", "link-arg=-Trom_functions.x", ] +[target.'cfg(target_os = "espidf")'] +linker = "ldproxy" +runner = "espflash flash --monitor" +rustflags = [ "--cfg", "espidf_time64"] + [unstable] +# Enable this when building for baremetal build-std = ["core", "alloc"] +# Enable this when building on the host machine or for ESP-IDF +#build-std = ["std", "panic_abort"] [alias] xtask = "run --manifest-path ./xtask/Cargo.toml --" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 426e3fc..9c64a2e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,12 +32,15 @@ jobs: components: rust-src,rustfmt - uses: esp-rs/xtensa-toolchain@v1.5 with: - ldproxy: false + ldproxy: true override: false - uses: Swatinem/rust-cache@v2 - uses: extractions/setup-just@v1 with: just-version: 1.13.0 + - name: mbedtls init + run: git submodule update --init --recursive + - name: check run: just diff --git a/.gitignore b/.gitignore index 17940b0..fa4960e 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,6 @@ Cargo.lock # You should copy the template and not modify `settings.json` .vscode/settings.json +.embuild + tmpsrc diff --git a/.gitmodules b/.gitmodules index a939eb3..4343758 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ [submodule "mbedtls"] - path = mbedtls + path = esp-mbedtls-sys/mbedtls url = https://github.com/espressif/mbedtls diff --git a/Cargo.toml b/Cargo.toml index 06f0722..01a0cf1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" authors = ["bjoernQ "] edition = "2021" license = "MIT OR Apache-2.0" -rust-version = "1.75" +rust-version = "1.82" [profile.release] debug = true @@ -16,19 +16,21 @@ opt-level = "s" opt-level = 3 [profile.dev] +debug = true lto = "fat" +opt-level = "z" [profile.dev.package.esp-wifi] opt-level = 3 [dependencies] -esp-hal = { version = "0.21.0" } -esp-backtrace = { version = "0.14.0", features = [ +esp-hal = { version = "0.21.0", optional = true } +esp-backtrace = { version = "0.14.0", optional = true, features = [ "panic-handler", "println", "exception-handler", ] } -esp-println = { version = "0.12.0", features = ["log"] } +esp-println = { version = "0.12.0", optional = true, features = ["log"] } esp-hal-embassy = { version = "0.4.0", optional = true } embassy-time = { version = "0.3.0", optional = true } @@ -43,9 +45,8 @@ embassy-net = { version = "0.4.0", features = [ "medium-ethernet", ], optional = true } - -esp-wifi = { version = "0.10.1", features = ["phy-enable-usb", "wifi-default"] } -smoltcp = { version = "0.11.0", default-features = false, features = [ +esp-wifi = { version = "0.10.1", optional = true, features = ["phy-enable-usb", "wifi-default", "sys-logs"] } +smoltcp = { version = "0.11.0", optional = true, default-features = false, features = [ "proto-igmp", "proto-ipv4", "socket-tcp", @@ -58,7 +59,7 @@ smoltcp = { version = "0.11.0", default-features = false, features = [ ] } log = "0.4.16" embedded-io = "0.6.1" -embedded-io-async = { version = "0.6.0", optional = true } +embedded-io-async = "0.6.0" heapless = "0.8.0" critical-section = "1.0.1" static_cell = { version = "2.1", features = ["nightly"] } @@ -69,91 +70,90 @@ edge-http = { version = "0.3.0", optional = true } edge-nal = { version = "0.3.0", optional = true } edge-nal-embassy = { version = "0.3.0", optional = true } cfg-if = "1.0.0" -esp-alloc = "0.5.0" +esp-alloc = { version = "0.5.0", optional = true} +enumset = { version = "1", default-features = false } + +[target.'cfg(target_os = "espidf")'.dependencies] +esp-idf-svc = { version = "0.49.1", features = ["binstart"] } [[example]] name = "crypto_self_test" -required-features = ["esp-wifi/sys-logs"] +required-features = ["examples"] + +[[example]] +name = "crypto_self_test_std" [[example]] name = "async_client" -required-features = ["async"] +required-features = ["examples-async"] [[example]] name = "async_client_mTLS" -required-features = ["async"] +required-features = ["examples-async"] [[example]] name = "async_server" -required-features = ["async"] +required-features = ["examples-async"] [[example]] name = "async_server_mTLS" -required-features = ["async"] +required-features = ["examples-async"] [[example]] name = "edge_server" -required-features = ["async", "edge-server"] +required-features = ["examples-async", "edge-http"] [features] +examples = ["esp-hal", "esp-backtrace", "esp-println", "esp-wifi", "smoltcp", "esp-alloc"] +examples-async = ["examples", "esp-hal-embassy", "embassy-time", "embassy-executor", "embassy-net", "edge-http", "edge-nal", "edge-nal-embassy", "esp-wifi/async", "esp-wifi/embassy-net", "esp-mbedtls/async", "esp-mbedtls/edge-nal"] +examples-std = ["critical-section/std"] + esp32 = [ - "esp-hal/esp32", + "esp-hal?/esp32", "esp-hal-embassy?/esp32", - "esp-backtrace/esp32", - "esp-println/esp32", - "esp-wifi/esp32", + "esp-backtrace?/esp32", + "esp-println?/esp32", + "esp-wifi?/esp32", "esp-mbedtls/esp32", ] esp32c3 = [ - "esp-hal/esp32c3", + "esp-hal?/esp32c3", "esp-hal-embassy?/esp32c3", - "esp-backtrace/esp32c3", - "esp-println/esp32c3", - "esp-wifi/esp32c3", + "esp-backtrace?/esp32c3", + "esp-println?/esp32c3", + "esp-wifi?/esp32c3", "esp-mbedtls/esp32c3", ] esp32s2 = [ - "esp-hal/esp32s2", + "esp-hal?/esp32s2", "esp-hal-embassy?/esp32s2", - "esp-backtrace/esp32s2", - "esp-println/esp32s2", - "esp-wifi/esp32s2", + "esp-backtrace?/esp32s2", + "esp-println?/esp32s2", + "esp-wifi?/esp32s2", "esp-mbedtls/esp32s2", ] esp32s3 = [ - "esp-hal/esp32s3", + "esp-hal?/esp32s3", "esp-hal-embassy?/esp32s3", - "esp-backtrace/esp32s3", - "esp-println/esp32s3", - "esp-wifi/esp32s3", + "esp-backtrace?/esp32s3", + "esp-println?/esp32s3", + "esp-wifi?/esp32s3", "esp-mbedtls/esp32s3", ] -async = [ - "esp-wifi/async", - "esp-wifi/embassy-net", - "embassy-executor", - "embassy-net", - "embassy-time", - "dep:embedded-io-async", - "esp-mbedtls/async", - "esp-hal-embassy", -] -# Helper feature to enable all dependencies required for edge-net -edge-server = [ - "edge-nal", - "edge-nal-embassy", - "edge-http", - "esp-mbedtls/edge-nal", -] +[build-dependencies] +embuild = { version = "0.32", features = ["espidf"] } # Patch until new release [patch.crates-io] -edge-http = { git = "https://github.com/ivmarkov/edge-net", rev = "722f92ac0fffd0cb1e1ce76086cca58df6eb49ee" } -edge-nal = { git = "https://github.com/ivmarkov/edge-net", rev = "722f92ac0fffd0cb1e1ce76086cca58df6eb49ee" } -edge-nal-embassy = { git = "https://github.com/ivmarkov/edge-net", rev = "722f92ac0fffd0cb1e1ce76086cca58df6eb49ee" } +edge-http = { git = "https://github.com/ivmarkov/edge-net" } +edge-nal = { git = "https://github.com/ivmarkov/edge-net" } +edge-nal-embassy = { git = "https://github.com/ivmarkov/edge-net" } +esp-idf-svc = { git = "https://github.com/esp-rs/esp-idf-svc" } +esp-idf-hal = { git = "https://github.com/esp-rs/esp-idf-hal" } +esp-idf-sys = { git = "https://github.com/esp-rs/esp-idf-sys" } # Patch before 0.6.0 got yanked embassy-executor = { git = "https://github.com/embassy-rs/embassy", rev = "886580179ff250e15b0fad6448e8ebed6cdabf2b" } embassy-time-driver = { git = "https://github.com/embassy-rs/embassy", rev = "886580179ff250e15b0fad6448e8ebed6cdabf2b" } -embassy-time-queue-driver = { git = "https://github.com/embassy-rs/embassy", rev = "886580179ff250e15b0fad6448e8ebed6cdabf2b" } +embassy-time-queue-driver = { git = "https://github.com/embassy-rs/embassy", rev = "886580179ff250e15b0fad6448e8ebed6cdabf2b" } \ No newline at end of file diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..7919712 --- /dev/null +++ b/build.rs @@ -0,0 +1,5 @@ +fn main() { + if std::env::var("CARGO_CFG_TARGET_OS").unwrap().as_str() == "espidf" { + embuild::espidf::sysenv::output(); + } +} diff --git a/esp-mbedtls-sys/Cargo.toml b/esp-mbedtls-sys/Cargo.toml index fa332c6..5ba76c0 100644 --- a/esp-mbedtls-sys/Cargo.toml +++ b/esp-mbedtls-sys/Cargo.toml @@ -2,17 +2,36 @@ name = "esp-mbedtls-sys" version = "0.1.0" edition = "2021" +links = "mbedtls" +license = "MIT OR Apache-2.0" +rust-version = "1.82" [build-dependencies] -anyhow = "1.0.68" +anyhow = "1.0.68" +bindgen = "0.68.1" +env_logger = "0.10.0" +log = "0.4.17" +cmake = "0.1.52" +fs_extra = "1.3.0" +embuild = "0.32" [dependencies] +# For malloc/free +# TODO: Replace with `esp-alloc` once `esp-alloc` starts to provide `malloc` and `free` in future +# ... or switch to our own `mbedtls_malloc/free` +esp-wifi = { version = "0.10.1", default-features = false, optional = true } + +# ESP-IDF: The mbedtls lib distributed with ESP-IDF is used +[target.'cfg(target_os = "espidf")'.dependencies] +esp-idf-sys = { version = "0.35", default-features = false } + +# All other platforms: mbedtls libs and bindings are created on the fly [features] default = [] -# Exactly *one* chip MUST be selected via its feature: -esp32 = [] -esp32c3 = [] -esp32s2 = [] -esp32s3 = [] +# ESP-HAL: Exactly *one* chip MUST be selected via its feature: +esp32 = ["esp-wifi/esp32"] +esp32c3 = ["esp-wifi/esp32c3"] +esp32s2 = ["esp-wifi/esp32s2"] +esp32s3 = ["esp-wifi/esp32s3"] diff --git a/esp-mbedtls-sys/LICENSE-APACHE b/esp-mbedtls-sys/LICENSE-APACHE new file mode 100644 index 0000000..976d1fa --- /dev/null +++ b/esp-mbedtls-sys/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2022 esp-rs + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/esp-mbedtls-sys/LICENSE-MIT b/esp-mbedtls-sys/LICENSE-MIT new file mode 100644 index 0000000..898d0b5 --- /dev/null +++ b/esp-mbedtls-sys/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 esp-rs + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/esp-mbedtls-sys/build.rs b/esp-mbedtls-sys/build.rs index 0418f64..576773d 100644 --- a/esp-mbedtls-sys/build.rs +++ b/esp-mbedtls-sys/build.rs @@ -1,100 +1,85 @@ -use std::{ - env, - fs::{self, File}, - io::Write, - path::PathBuf, -}; +use std::{env, path::PathBuf}; use anyhow::Result; +#[path = "gen/builder.rs"] +mod builder; + fn main() -> Result<()> { - // Put the linker script somewhere the linker can find it - let out = PathBuf::from(env::var_os("OUT_DIR").unwrap()); - let target = env::var_os("TARGET").unwrap(); + let crate_root_path = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()); - if target == "riscv32imc-unknown-none-elf" || target == "riscv32imac-unknown-none-elf" { - copy_file( - &out, - "../libs/riscv32imc-unknown-none-elf/libmbedcrypto.a", - "libmbedcrypto.a", - )?; - copy_file( - &out, - "../libs/riscv32imc-unknown-none-elf/libmbedtls.a", - "libmbedtls.a", - )?; - copy_file( - &out, - "../libs/riscv32imc-unknown-none-elf/libmbedx509.a", - "libmbedx509.a", - )?; - } + builder::MbedtlsBuilder::track(&crate_root_path.join("gen")); + builder::MbedtlsBuilder::track(&crate_root_path.join("mbedtls")); - if target == "xtensa-esp32-none-elf" { - copy_file( - &out, - "../libs/xtensa-esp32-none-elf/libmbedcrypto.a", - "libmbedcrypto.a", - )?; - copy_file( - &out, - "../libs/xtensa-esp32-none-elf/libmbedtls.a", - "libmbedtls.a", - )?; - copy_file( - &out, - "../libs/xtensa-esp32-none-elf/libmbedx509.a", - "libmbedx509.a", - )?; - } + // If any one of these features is selected, we don't build anything + // and just use the pre-generated baremetal ESP bindings and libraries + let esp32 = env::var("CARGO_FEATURE_ESP32").is_ok(); + let esp32c3 = env::var("CARGO_FEATURE_ESP32C3").is_ok(); + let esp32s2 = env::var("CARGO_FEATURE_ESP32S2").is_ok(); + let esp32s3 = env::var("CARGO_FEATURE_ESP32S3").is_ok(); - if target == "xtensa-esp32s2-none-elf" { - copy_file( - &out, - "../libs/xtensa-esp32s2-none-elf/libmbedcrypto.a", - "libmbedcrypto.a", - )?; - copy_file( - &out, - "../libs/xtensa-esp32s2-none-elf/libmbedtls.a", - "libmbedtls.a", - )?; - copy_file( - &out, - "../libs/xtensa-esp32s2-none-elf/libmbedx509.a", - "libmbedx509.a", - )?; - } + let host = env::var("HOST").unwrap(); + let target = env::var("TARGET").unwrap(); - if target == "xtensa-esp32s3-none-elf" { - copy_file( - &out, - "../libs/xtensa-esp32s3-none-elf/libmbedcrypto.a", - "libmbedcrypto.a", - )?; - copy_file( - &out, - "../libs/xtensa-esp32s3-none-elf/libmbedtls.a", - "libmbedtls.a", - )?; - copy_file( - &out, - "../libs/xtensa-esp32s3-none-elf/libmbedx509.a", - "libmbedx509.a", - )?; - } + // If we're building for ESP32, ESP32C3, ESP32S2, or ESP32S3, we don't need to do anything + // Just link against the pre-built libraries and use the pre-generated bindings + let bindings_dir = crate_root_path.join("src").join("include"); + let libs_dir = crate_root_path.join("libs"); - println!("cargo:rustc-link-lib={}", "mbedtls"); - println!("cargo:rustc-link-lib={}", "mbedx509"); - println!("cargo:rustc-link-lib={}", "mbedcrypto"); - println!("cargo:rustc-link-search={}", out.display()); - println!("cargo:rerun-if-changed=../libs"); - Ok(()) -} + let dirs = if esp32 { + Some(( + bindings_dir.join("esp32.rs"), + libs_dir.join("xtensa-esp32-none-elf"), + )) + } else if esp32c3 { + Some(( + bindings_dir.join("esp32c3.rs"), + libs_dir.join("riscv32imc-unknown-none-elf"), + )) + } else if esp32s2 { + Some(( + bindings_dir.join("esp32s2.rs"), + libs_dir.join("xtensa-esp32s2-none-elf"), + )) + } else if esp32s3 { + Some(( + bindings_dir.join("esp32s3.rs"), + libs_dir.join("xtensa-esp32s3-none-elf"), + )) + } else if target.ends_with("-espidf") { + // Nothing to do for ESP-IDF, `esp-idf-sys` will do everything for us + None + } else { + // Need to do on-the-fly build and bindings' generation + let out = PathBuf::from(env::var_os("OUT_DIR").unwrap()); + + let builder = builder::MbedtlsBuilder::new( + crate_root_path.clone(), + "generic".to_string(), + None, + None, + None, + Some(target), + Some(host), + ); + + let libs_dir = builder.compile(&out, None)?; + let bindings = builder.generate_bindings(&out, None)?; -fn copy_file(out: &PathBuf, from: &str, to: &str) -> Result<()> { - let mut file = File::create(out.join(to))?; - file.write_all(&fs::read(from)?)?; + Some((bindings, libs_dir)) + }; + + if let Some((bindings, libs_dir)) = dirs { + println!( + "cargo::rustc-env=ESP_MBEDTLS_SYS_GENERATED_BINDINGS_FILE={}", + bindings.display() + ); + + println!("cargo:rustc-link-lib=static={}", "mbedtls"); + println!("cargo:rustc-link-lib=static={}", "mbedx509"); + println!("cargo:rustc-link-lib=static={}", "mbedcrypto"); + println!("cargo:rustc-link-search={}", libs_dir.display()); + } Ok(()) } diff --git a/esp-mbedtls-sys/gen/builder.rs b/esp-mbedtls-sys/gen/builder.rs new file mode 100644 index 0000000..51e9e7a --- /dev/null +++ b/esp-mbedtls-sys/gen/builder.rs @@ -0,0 +1,229 @@ +use std::{ + path::{Path, PathBuf}, + process::Command, +}; + +use anyhow::{anyhow, Result}; +use bindgen::Builder; +use cmake::Config; + +pub struct MbedtlsBuilder { + crate_root_path: PathBuf, + soc_config: String, + clang_path: Option, + sysroot_path: Option, + cmake_target: Option, + clang_target: Option, + host: Option, +} + +impl MbedtlsBuilder { + /// Create a new MbedtlsBuilder + /// + /// Arguments: + /// - `crate_root_path`: Path to the root of the crate + /// - `soc_config`: The name of the SoC configuration in the `headers/` directory. Use `generic` for a generic, software-only build + /// - `clang_path`: Optional path to the Clang compiler. If not specified, the system Clang will be used for generating bindings, + /// and the system compiler (likely GCC) would be used for building the MbedTLS C code itself + /// - `sysroot_path`: Optional path to the compiler sysroot directory. If not specified, the host sysroot will be used + /// - `cmake_target`: Optional target for CMake when building MbedTLS, with Rust target-triple syntax. If not specified, the "TARGET" env variable will be used + /// - `clang_target`: Optional target for Clang when generating bindings. If not specified, the host target will be used + /// - `host`: Optional host target for the build + pub const fn new( + crate_root_path: PathBuf, + soc_config: String, + clang_path: Option, + sysroot_path: Option, + cmake_target: Option, + clang_target: Option, + host: Option, + ) -> Self { + Self { + crate_root_path, + soc_config, + clang_path, + sysroot_path, + cmake_target, + clang_target, + host, + } + } + + /// Generate bindings for esp-mbedtls-sys + /// + /// Arguments: + /// - `out_path`: Path to write the bindings to + pub fn generate_bindings( + &self, + out_path: &Path, + copy_file_path: Option<&Path>, + ) -> Result { + if let Some(clang_path) = &self.clang_path { + std::env::set_var("CLANG_PATH", clang_path); + } + + let canon = |path: &Path| { + // TODO: Is this really necessary? + path.display() + .to_string() + .replace('\\', "/") + .replace("//?/C:", "") + }; + + // Generate the bindings using `bindgen`: + log::info!("Generating bindings"); + let mut builder = Builder::default().clang_args([ + &format!( + "-I{}", + canon(&self.crate_root_path.join("mbedtls").join("include")) + ), + &format!( + "-I{}", + canon( + &self + .crate_root_path + .join("gen") + .join("include") + .join("soc") + .join(&self.soc_config) + ) + ), + ]); + + if let Some(sysroot_path) = &self.sysroot_path { + builder = builder.clang_args([ + &format!("-I{}", canon(&sysroot_path.join("include"))), + &format!("--sysroot={}", canon(sysroot_path)), + ]); + } + + if let Some(target) = &self.clang_target { + builder = builder.clang_arg(&format!("--target={target}")); + } + + let bindings = builder + .ctypes_prefix("crate::c_types") + .derive_debug(false) + .header( + self.crate_root_path + .join("gen") + .join("include") + .join("include.h") + .to_string_lossy(), + ) + .layout_tests(false) + .use_core() + .generate() + .map_err(|_| anyhow!("Failed to generate bindings"))?; + + let bindings_file = out_path.join("bindings.rs"); + + // Write out the bindings to the appropriate path: + log::info!("Writing out bindings to: {}", bindings_file.display()); + bindings.write_to_file(&bindings_file)?; + + // Format the bindings: + Command::new("rustfmt") + .arg(bindings_file.to_string_lossy().to_string()) + .arg("--config") + .arg("normalize_doc_attributes=true") + .output()?; + + if let Some(copy_file_path) = copy_file_path { + log::info!("Copying bindings to {}", copy_file_path.display()); + std::fs::copy(&bindings_file, copy_file_path)?; + } + + Ok(bindings_file) + } + + /// Compile mbedtls + /// + /// Arguments: + /// - `out_path`: Path to write the compiled libraries to + pub fn compile(&self, out_path: &Path, copy_path: Option<&Path>) -> Result { + if let Some(clang_path) = &self.clang_path { + std::env::set_var("CLANG_PATH", clang_path); + } + + log::info!("Compiling for {} SOC", self.soc_config); + let mbedtls_path = self.crate_root_path.join("mbedtls"); + + let target_dir = out_path.join("mbedtls").join("build"); + + std::fs::create_dir_all(&target_dir)?; + + // Compile mbedtls and generate libraries to link against + log::info!("Compiling mbedtls"); + let mut config = Config::new(&mbedtls_path); + + config + .define("USE_SHARED_MBEDTLS_LIBRARY", "OFF") + .define("USE_STATIC_MBEDTLS_LIBRARY", "ON") + .define("ENABLE_PROGRAMS", "OFF") + .define("ENABLE_TESTING", "OFF") + .define("CMAKE_EXPORT_COMPILE_COMMANDS", "ON") + // Clang will complain about some documentation formatting in mbedtls + .define("MBEDTLS_FATAL_WARNINGS", "OFF") + .define( + "MBEDTLS_CONFIG_FILE", + &self + .crate_root_path + .join("gen") + .join("include") + .join("soc") + .join(&self.soc_config) + .join("config.h"), + ) + .define( + "CMAKE_TOOLCHAIN_FILE", + &self + .crate_root_path + .join("gen") + .join("toolchains") + .join(format!("toolchain-clang-{}.cmake", self.soc_config)), + ) + .cflag(&format!( + "-I{}", + self.crate_root_path + .join("gen") + .join("include") + .join("soc") + .join(&self.soc_config) + .display() + )) + .cflag(&format!("-DMBEDTLS_CONFIG_FILE=''")) + .cxxflag(&format!("-DMBEDTLS_CONFIG_FILE=''")) + .profile("Release") + .out_dir(&target_dir); + + if let Some(target) = &self.cmake_target { + config.target(target); + } + + if let Some(host) = &self.host { + config.host(host); + } + + config.build(); + + let lib_dir = target_dir.join("lib"); + + if let Some(copy_path) = copy_path { + log::info!("Copying mbedtls libraries to {}", copy_path.display()); + std::fs::create_dir_all(copy_path)?; + + for file in ["libmbedcrypto.a", "libmbedx509.a", "libmbedtls.a"] { + std::fs::copy(lib_dir.join(file), copy_path.join(file))?; + } + } + + Ok(lib_dir) + } + + /// Re-run the build script if the file or directory has changed. + #[allow(unused)] + pub fn track(file_or_dir: &Path) { + println!("cargo:rerun-if-changed={}", file_or_dir.display()) + } +} diff --git a/esp-mbedtls-sys/include/include.h b/esp-mbedtls-sys/gen/include/include.h similarity index 94% rename from esp-mbedtls-sys/include/include.h rename to esp-mbedtls-sys/gen/include/include.h index 3dd7dde..dce42e6 100644 --- a/esp-mbedtls-sys/include/include.h +++ b/esp-mbedtls-sys/gen/include/include.h @@ -1,6 +1,6 @@ #define MBEDTLS_CONFIG_FILE "config.h" -#include "config.h" +#include MBEDTLS_CONFIG_FILE #include "mbedtls/ssl.h" #include "mbedtls/x509.h" diff --git a/esp-mbedtls-sys/headers/esp32/config.h b/esp-mbedtls-sys/gen/include/soc/esp32/config.h similarity index 99% rename from esp-mbedtls-sys/headers/esp32/config.h rename to esp-mbedtls-sys/gen/include/soc/esp32/config.h index e686129..4236b79 100644 --- a/esp-mbedtls-sys/headers/esp32/config.h +++ b/esp-mbedtls-sys/gen/include/soc/esp32/config.h @@ -2430,7 +2430,7 @@ * * This module provides debugging functions. */ -//#define MBEDTLS_DEBUG_C +#define MBEDTLS_DEBUG_C /** * \def MBEDTLS_DES_C diff --git a/esp-mbedtls-sys/headers/esp32c3/config.h b/esp-mbedtls-sys/gen/include/soc/esp32c3/config.h similarity index 100% rename from esp-mbedtls-sys/headers/esp32c3/config.h rename to esp-mbedtls-sys/gen/include/soc/esp32c3/config.h diff --git a/esp-mbedtls-sys/headers/esp32c3/sha1_alt.h b/esp-mbedtls-sys/gen/include/soc/esp32c3/sha1_alt.h similarity index 100% rename from esp-mbedtls-sys/headers/esp32c3/sha1_alt.h rename to esp-mbedtls-sys/gen/include/soc/esp32c3/sha1_alt.h diff --git a/esp-mbedtls-sys/headers/esp32s2/config.h b/esp-mbedtls-sys/gen/include/soc/esp32s2/config.h similarity index 99% rename from esp-mbedtls-sys/headers/esp32s2/config.h rename to esp-mbedtls-sys/gen/include/soc/esp32s2/config.h index 43022cd..ffabff8 100644 --- a/esp-mbedtls-sys/headers/esp32s2/config.h +++ b/esp-mbedtls-sys/gen/include/soc/esp32s2/config.h @@ -2431,7 +2431,7 @@ * * This module provides debugging functions. */ -//#define MBEDTLS_DEBUG_C +#define MBEDTLS_DEBUG_C /** * \def MBEDTLS_DES_C diff --git a/esp-mbedtls-sys/headers/esp32s2/sha1_alt.h b/esp-mbedtls-sys/gen/include/soc/esp32s2/sha1_alt.h similarity index 100% rename from esp-mbedtls-sys/headers/esp32s2/sha1_alt.h rename to esp-mbedtls-sys/gen/include/soc/esp32s2/sha1_alt.h diff --git a/esp-mbedtls-sys/headers/esp32s2/sha256_alt.h b/esp-mbedtls-sys/gen/include/soc/esp32s2/sha256_alt.h similarity index 100% rename from esp-mbedtls-sys/headers/esp32s2/sha256_alt.h rename to esp-mbedtls-sys/gen/include/soc/esp32s2/sha256_alt.h diff --git a/esp-mbedtls-sys/headers/esp32s2/sha512_alt.h b/esp-mbedtls-sys/gen/include/soc/esp32s2/sha512_alt.h similarity index 100% rename from esp-mbedtls-sys/headers/esp32s2/sha512_alt.h rename to esp-mbedtls-sys/gen/include/soc/esp32s2/sha512_alt.h diff --git a/esp-mbedtls-sys/headers/esp32s3/config.h b/esp-mbedtls-sys/gen/include/soc/esp32s3/config.h similarity index 99% rename from esp-mbedtls-sys/headers/esp32s3/config.h rename to esp-mbedtls-sys/gen/include/soc/esp32s3/config.h index 43022cd..ffabff8 100644 --- a/esp-mbedtls-sys/headers/esp32s3/config.h +++ b/esp-mbedtls-sys/gen/include/soc/esp32s3/config.h @@ -2431,7 +2431,7 @@ * * This module provides debugging functions. */ -//#define MBEDTLS_DEBUG_C +#define MBEDTLS_DEBUG_C /** * \def MBEDTLS_DES_C diff --git a/esp-mbedtls-sys/headers/esp32s3/sha1_alt.h b/esp-mbedtls-sys/gen/include/soc/esp32s3/sha1_alt.h similarity index 100% rename from esp-mbedtls-sys/headers/esp32s3/sha1_alt.h rename to esp-mbedtls-sys/gen/include/soc/esp32s3/sha1_alt.h diff --git a/esp-mbedtls-sys/headers/esp32s3/sha256_alt.h b/esp-mbedtls-sys/gen/include/soc/esp32s3/sha256_alt.h similarity index 100% rename from esp-mbedtls-sys/headers/esp32s3/sha256_alt.h rename to esp-mbedtls-sys/gen/include/soc/esp32s3/sha256_alt.h diff --git a/esp-mbedtls-sys/headers/esp32s3/sha512_alt.h b/esp-mbedtls-sys/gen/include/soc/esp32s3/sha512_alt.h similarity index 100% rename from esp-mbedtls-sys/headers/esp32s3/sha512_alt.h rename to esp-mbedtls-sys/gen/include/soc/esp32s3/sha512_alt.h diff --git a/esp-mbedtls-sys/gen/include/soc/generic/config.h b/esp-mbedtls-sys/gen/include/soc/generic/config.h new file mode 100644 index 0000000..569c796 --- /dev/null +++ b/esp-mbedtls-sys/gen/include/soc/generic/config.h @@ -0,0 +1,3921 @@ +/** + * \file mbedtls_config.h + * + * \brief Configuration options (set of defines) + * + * This set of compile-time options may be used to enable + * or disable features selectively, and reduce the global + * memory footprint. + */ +/* + * Copyright The Mbed TLS Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * This is an optional version symbol that enables compatibility handling of + * config files. + * + * It is equal to the #MBEDTLS_VERSION_NUMBER of the Mbed TLS version that + * introduced the config format we want to be compatible with. + */ +//#define MBEDTLS_CONFIG_VERSION 0x03000000 + +/** + * \name SECTION: System support + * + * This section sets system specific settings. + * \{ + */ + +/** + * \def MBEDTLS_HAVE_ASM + * + * The compiler has support for asm(). + * + * Requires support for asm() in compiler. + * + * Used in: + * library/aesni.h + * library/aria.c + * library/bn_mul.h + * library/constant_time.c + * library/padlock.h + * + * Required by: + * MBEDTLS_AESCE_C + * MBEDTLS_AESNI_C (on some platforms) + * MBEDTLS_PADLOCK_C + * + * Comment to disable the use of assembly code. + */ +#define MBEDTLS_HAVE_ASM + +/** + * \def MBEDTLS_NO_UDBL_DIVISION + * + * The platform lacks support for double-width integer division (64-bit + * division on a 32-bit platform, 128-bit division on a 64-bit platform). + * + * Used in: + * include/mbedtls/bignum.h + * library/bignum.c + * + * The bignum code uses double-width division to speed up some operations. + * Double-width division is often implemented in software that needs to + * be linked with the program. The presence of a double-width integer + * type is usually detected automatically through preprocessor macros, + * but the automatic detection cannot know whether the code needs to + * and can be linked with an implementation of division for that type. + * By default division is assumed to be usable if the type is present. + * Uncomment this option to prevent the use of double-width division. + * + * Note that division for the native integer type is always required. + * Furthermore, a 64-bit type is always required even on a 32-bit + * platform, but it need not support multiplication or division. In some + * cases it is also desirable to disable some double-width operations. For + * example, if double-width division is implemented in software, disabling + * it can reduce code size in some embedded targets. + */ +//#define MBEDTLS_NO_UDBL_DIVISION + +/** + * \def MBEDTLS_NO_64BIT_MULTIPLICATION + * + * The platform lacks support for 32x32 -> 64-bit multiplication. + * + * Used in: + * library/poly1305.c + * + * Some parts of the library may use multiplication of two unsigned 32-bit + * operands with a 64-bit result in order to speed up computations. On some + * platforms, this is not available in hardware and has to be implemented in + * software, usually in a library provided by the toolchain. + * + * Sometimes it is not desirable to have to link to that library. This option + * removes the dependency of that library on platforms that lack a hardware + * 64-bit multiplier by embedding a software implementation in Mbed TLS. + * + * Note that depending on the compiler, this may decrease performance compared + * to using the library function provided by the toolchain. + */ +//#define MBEDTLS_NO_64BIT_MULTIPLICATION + +/** + * \def MBEDTLS_HAVE_SSE2 + * + * CPU supports SSE2 instruction set. + * + * Uncomment if the CPU supports SSE2 (IA-32 specific). + */ +//#define MBEDTLS_HAVE_SSE2 + +/** + * \def MBEDTLS_HAVE_TIME + * + * System has time.h and time(). + * The time does not need to be correct, only time differences are used, + * by contrast with MBEDTLS_HAVE_TIME_DATE + * + * Defining MBEDTLS_HAVE_TIME allows you to specify MBEDTLS_PLATFORM_TIME_ALT, + * MBEDTLS_PLATFORM_TIME_MACRO, MBEDTLS_PLATFORM_TIME_TYPE_MACRO and + * MBEDTLS_PLATFORM_STD_TIME. + * + * Comment if your system does not support time functions. + * + * \note If MBEDTLS_TIMING_C is set - to enable the semi-portable timing + * interface - timing.c will include time.h on suitable platforms + * regardless of the setting of MBEDTLS_HAVE_TIME, unless + * MBEDTLS_TIMING_ALT is used. See timing.c for more information. + */ +//#define MBEDTLS_HAVE_TIME + +/** + * \def MBEDTLS_HAVE_TIME_DATE + * + * System has time.h, time(), and an implementation for + * mbedtls_platform_gmtime_r() (see below). + * The time needs to be correct (not necessarily very accurate, but at least + * the date should be correct). This is used to verify the validity period of + * X.509 certificates. + * + * Comment if your system does not have a correct clock. + * + * \note mbedtls_platform_gmtime_r() is an abstraction in platform_util.h that + * behaves similarly to the gmtime_r() function from the C standard. Refer to + * the documentation for mbedtls_platform_gmtime_r() for more information. + * + * \note It is possible to configure an implementation for + * mbedtls_platform_gmtime_r() at compile-time by using the macro + * MBEDTLS_PLATFORM_GMTIME_R_ALT. + */ +//#define MBEDTLS_HAVE_TIME_DATE + +/** + * \def MBEDTLS_PLATFORM_MEMORY + * + * Enable the memory allocation layer. + * + * By default mbed TLS uses the system-provided calloc() and free(). + * This allows different allocators (self-implemented or provided) to be + * provided to the platform abstraction layer. + * + * Enabling MBEDTLS_PLATFORM_MEMORY without the + * MBEDTLS_PLATFORM_{FREE,CALLOC}_MACROs will provide + * "mbedtls_platform_set_calloc_free()" allowing you to set an alternative calloc() and + * free() function pointer at runtime. + * + * Enabling MBEDTLS_PLATFORM_MEMORY and specifying + * MBEDTLS_PLATFORM_{CALLOC,FREE}_MACROs will allow you to specify the + * alternate function at compile time. + * + * Requires: MBEDTLS_PLATFORM_C + * + * Enable this layer to allow use of alternative memory allocators. + */ +//#define MBEDTLS_PLATFORM_MEMORY + +/** + * \def MBEDTLS_PLATFORM_NO_STD_FUNCTIONS + * + * Do not assign standard functions in the platform layer (e.g. calloc() to + * MBEDTLS_PLATFORM_STD_CALLOC and printf() to MBEDTLS_PLATFORM_STD_PRINTF) + * + * This makes sure there are no linking errors on platforms that do not support + * these functions. You will HAVE to provide alternatives, either at runtime + * via the platform_set_xxx() functions or at compile time by setting + * the MBEDTLS_PLATFORM_STD_XXX defines, or enabling a + * MBEDTLS_PLATFORM_XXX_MACRO. + * + * Requires: MBEDTLS_PLATFORM_C + * + * Uncomment to prevent default assignment of standard functions in the + * platform layer. + */ +//#define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS + +/** + * \def MBEDTLS_PLATFORM_EXIT_ALT + * + * MBEDTLS_PLATFORM_XXX_ALT: Uncomment a macro to let mbed TLS support the + * function in the platform abstraction layer. + * + * Example: In case you uncomment MBEDTLS_PLATFORM_PRINTF_ALT, mbed TLS will + * provide a function "mbedtls_platform_set_printf()" that allows you to set an + * alternative printf function pointer. + * + * All these define require MBEDTLS_PLATFORM_C to be defined! + * + * \note MBEDTLS_PLATFORM_SNPRINTF_ALT is required on Windows; + * it will be enabled automatically by check_config.h + * + * \warning MBEDTLS_PLATFORM_XXX_ALT cannot be defined at the same time as + * MBEDTLS_PLATFORM_XXX_MACRO! + * + * Requires: MBEDTLS_PLATFORM_TIME_ALT requires MBEDTLS_HAVE_TIME + * + * Uncomment a macro to enable alternate implementation of specific base + * platform function + */ +//#define MBEDTLS_PLATFORM_SETBUF_ALT +//#define MBEDTLS_PLATFORM_EXIT_ALT +//#define MBEDTLS_PLATFORM_TIME_ALT +//#define MBEDTLS_PLATFORM_FPRINTF_ALT +//#define MBEDTLS_PLATFORM_PRINTF_ALT +//#define MBEDTLS_PLATFORM_SNPRINTF_ALT +//#define MBEDTLS_PLATFORM_VSNPRINTF_ALT +//#define MBEDTLS_PLATFORM_NV_SEED_ALT +//#define MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT + +/** + * \def MBEDTLS_DEPRECATED_WARNING + * + * Mark deprecated functions and features so that they generate a warning if + * used. Functionality deprecated in one version will usually be removed in the + * next version. You can enable this to help you prepare the transition to a + * new major version by making sure your code is not using this functionality. + * + * This only works with GCC and Clang. With other compilers, you may want to + * use MBEDTLS_DEPRECATED_REMOVED + * + * Uncomment to get warnings on using deprecated functions and features. + */ +//#define MBEDTLS_DEPRECATED_WARNING + +/** + * \def MBEDTLS_DEPRECATED_REMOVED + * + * Remove deprecated functions and features so that they generate an error if + * used. Functionality deprecated in one version will usually be removed in the + * next version. You can enable this to help you prepare the transition to a + * new major version by making sure your code is not using this functionality. + * + * Uncomment to get errors on using deprecated functions and features. + */ +//#define MBEDTLS_DEPRECATED_REMOVED + +/** \} name SECTION: System support */ + +/** + * \name SECTION: mbed TLS feature support + * + * This section sets support for features that are or are not needed + * within the modules that are enabled. + * \{ + */ + +/** + * \def MBEDTLS_TIMING_ALT + * + * Uncomment to provide your own alternate implementation for + * mbedtls_timing_get_timer(), mbedtls_set_alarm(), mbedtls_set/get_delay() + * + * Only works if you have MBEDTLS_TIMING_C enabled. + * + * You will need to provide a header "timing_alt.h" and an implementation at + * compile time. + */ +//#define MBEDTLS_TIMING_ALT + +/** + * \def MBEDTLS_AES_ALT + * + * MBEDTLS__MODULE_NAME__ALT: Uncomment a macro to let mbed TLS use your + * alternate core implementation of a symmetric crypto, an arithmetic or hash + * module (e.g. platform specific assembly optimized implementations). Keep + * in mind that the function prototypes should remain the same. + * + * This replaces the whole module. If you only want to replace one of the + * functions, use one of the MBEDTLS__FUNCTION_NAME__ALT flags. + * + * Example: In case you uncomment MBEDTLS_AES_ALT, mbed TLS will no longer + * provide the "struct mbedtls_aes_context" definition and omit the base + * function declarations and implementations. "aes_alt.h" will be included from + * "aes.h" to include the new function definitions. + * + * Uncomment a macro to enable alternate implementation of the corresponding + * module. + * + * \warning MD5, DES and SHA-1 are considered weak and their + * use constitutes a security risk. If possible, we recommend + * avoiding dependencies on them, and considering stronger message + * digests and ciphers instead. + * + */ +//#define MBEDTLS_AES_ALT +//#define MBEDTLS_ARIA_ALT +//#define MBEDTLS_CAMELLIA_ALT +//#define MBEDTLS_CCM_ALT +//#define MBEDTLS_CHACHA20_ALT +//#define MBEDTLS_CHACHAPOLY_ALT +//#define MBEDTLS_CMAC_ALT +//#define MBEDTLS_DES_ALT +//#define MBEDTLS_DHM_ALT +//#define MBEDTLS_ECJPAKE_ALT +//#define MBEDTLS_GCM_ALT +//#define MBEDTLS_NIST_KW_ALT +//#define MBEDTLS_MPI_EXP_MOD_ALT_FALLBACK +//#define MBEDTLS_MD5_ALT +//#define MBEDTLS_POLY1305_ALT +//#define MBEDTLS_RIPEMD160_ALT +//#define MBEDTLS_RSA_ALT +//#define MBEDTLS_SHA1_ALT +//#define MBEDTLS_SHA256_ALT +//#define MBEDTLS_SHA512_ALT + +/* + * When replacing the elliptic curve module, please consider, that it is + * implemented with two .c files: + * - ecp.c + * - ecp_curves.c + * You can replace them very much like all the other MBEDTLS__MODULE_NAME__ALT + * macros as described above. The only difference is that you have to make sure + * that you provide functionality for both .c files. + */ +//#define MBEDTLS_ECP_ALT + +/** + * \def MBEDTLS_SHA256_PROCESS_ALT + * + * MBEDTLS__FUNCTION_NAME__ALT: Uncomment a macro to let mbed TLS use you + * alternate core implementation of symmetric crypto or hash function. Keep in + * mind that function prototypes should remain the same. + * + * This replaces only one function. The header file from mbed TLS is still + * used, in contrast to the MBEDTLS__MODULE_NAME__ALT flags. + * + * Example: In case you uncomment MBEDTLS_SHA256_PROCESS_ALT, mbed TLS will + * no longer provide the mbedtls_sha1_process() function, but it will still provide + * the other function (using your mbedtls_sha1_process() function) and the definition + * of mbedtls_sha1_context, so your implementation of mbedtls_sha1_process must be compatible + * with this definition. + * + * \note If you use the AES_xxx_ALT macros, then it is recommended to also set + * MBEDTLS_AES_ROM_TABLES in order to help the linker garbage-collect the AES + * tables. + * + * Uncomment a macro to enable alternate implementation of the corresponding + * function. + * + * \warning MD5, DES and SHA-1 are considered weak and their use + * constitutes a security risk. If possible, we recommend avoiding + * dependencies on them, and considering stronger message digests + * and ciphers instead. + * + * \warning If both MBEDTLS_ECDSA_SIGN_ALT and MBEDTLS_ECDSA_DETERMINISTIC are + * enabled, then the deterministic ECDH signature functions pass the + * the static HMAC-DRBG as RNG to mbedtls_ecdsa_sign(). Therefore + * alternative implementations should use the RNG only for generating + * the ephemeral key and nothing else. If this is not possible, then + * MBEDTLS_ECDSA_DETERMINISTIC should be disabled and an alternative + * implementation should be provided for mbedtls_ecdsa_sign_det_ext(). + * + */ +//#define MBEDTLS_MD5_PROCESS_ALT +//#define MBEDTLS_RIPEMD160_PROCESS_ALT +//#define MBEDTLS_SHA1_PROCESS_ALT +//#define MBEDTLS_SHA256_PROCESS_ALT +//#define MBEDTLS_SHA512_PROCESS_ALT +//#define MBEDTLS_DES_SETKEY_ALT +//#define MBEDTLS_DES_CRYPT_ECB_ALT +//#define MBEDTLS_DES3_CRYPT_ECB_ALT +//#define MBEDTLS_AES_SETKEY_ENC_ALT +//#define MBEDTLS_AES_SETKEY_DEC_ALT +//#define MBEDTLS_AES_ENCRYPT_ALT +//#define MBEDTLS_AES_DECRYPT_ALT +//#define MBEDTLS_ECDH_GEN_PUBLIC_ALT +//#define MBEDTLS_ECDH_COMPUTE_SHARED_ALT +//#define MBEDTLS_ECDSA_VERIFY_ALT +//#define MBEDTLS_ECDSA_SIGN_ALT +//#define MBEDTLS_ECDSA_GENKEY_ALT + +/** + * \def MBEDTLS_ECP_INTERNAL_ALT + * + * Expose a part of the internal interface of the Elliptic Curve Point module. + * + * MBEDTLS_ECP__FUNCTION_NAME__ALT: Uncomment a macro to let mbed TLS use your + * alternative core implementation of elliptic curve arithmetic. Keep in mind + * that function prototypes should remain the same. + * + * This partially replaces one function. The header file from mbed TLS is still + * used, in contrast to the MBEDTLS_ECP_ALT flag. The original implementation + * is still present and it is used for group structures not supported by the + * alternative. + * + * The original implementation can in addition be removed by setting the + * MBEDTLS_ECP_NO_FALLBACK option, in which case any function for which the + * corresponding MBEDTLS_ECP__FUNCTION_NAME__ALT macro is defined will not be + * able to fallback to curves not supported by the alternative implementation. + * + * Any of these options become available by defining MBEDTLS_ECP_INTERNAL_ALT + * and implementing the following functions: + * unsigned char mbedtls_internal_ecp_grp_capable( + * const mbedtls_ecp_group *grp ) + * int mbedtls_internal_ecp_init( const mbedtls_ecp_group *grp ) + * void mbedtls_internal_ecp_free( const mbedtls_ecp_group *grp ) + * The mbedtls_internal_ecp_grp_capable function should return 1 if the + * replacement functions implement arithmetic for the given group and 0 + * otherwise. + * The functions mbedtls_internal_ecp_init and mbedtls_internal_ecp_free are + * called before and after each point operation and provide an opportunity to + * implement optimized set up and tear down instructions. + * + * Example: In case you set MBEDTLS_ECP_INTERNAL_ALT and + * MBEDTLS_ECP_DOUBLE_JAC_ALT, mbed TLS will still provide the ecp_double_jac() + * function, but will use your mbedtls_internal_ecp_double_jac() if the group + * for the operation is supported by your implementation (i.e. your + * mbedtls_internal_ecp_grp_capable() function returns 1 for this group). If the + * group is not supported by your implementation, then the original mbed TLS + * implementation of ecp_double_jac() is used instead, unless this fallback + * behaviour is disabled by setting MBEDTLS_ECP_NO_FALLBACK (in which case + * ecp_double_jac() will return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE). + * + * The function prototypes and the definition of mbedtls_ecp_group and + * mbedtls_ecp_point will not change based on MBEDTLS_ECP_INTERNAL_ALT, so your + * implementation of mbedtls_internal_ecp__function_name__ must be compatible + * with their definitions. + * + * Uncomment a macro to enable alternate implementation of the corresponding + * function. + */ +/* Required for all the functions in this section */ +//#define MBEDTLS_ECP_INTERNAL_ALT +/* Turn off software fallback for curves not supported in hardware */ +//#define MBEDTLS_ECP_NO_FALLBACK +/* Support for Weierstrass curves with Jacobi representation */ +//#define MBEDTLS_ECP_RANDOMIZE_JAC_ALT +//#define MBEDTLS_ECP_ADD_MIXED_ALT +//#define MBEDTLS_ECP_DOUBLE_JAC_ALT +//#define MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT +//#define MBEDTLS_ECP_NORMALIZE_JAC_ALT +/* Support for curves with Montgomery arithmetic */ +//#define MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT +//#define MBEDTLS_ECP_RANDOMIZE_MXZ_ALT +//#define MBEDTLS_ECP_NORMALIZE_MXZ_ALT + +/** + * \def MBEDTLS_ENTROPY_HARDWARE_ALT + * + * Uncomment this macro to let mbed TLS use your own implementation of a + * hardware entropy collector. + * + * Your function must be called \c mbedtls_hardware_poll(), have the same + * prototype as declared in library/entropy_poll.h, and accept NULL as first + * argument. + * + * Uncomment to use your own hardware entropy collector. + */ +//#define MBEDTLS_ENTROPY_HARDWARE_ALT + +/** + * \def MBEDTLS_AES_ROM_TABLES + * + * Use precomputed AES tables stored in ROM. + * + * Uncomment this macro to use precomputed AES tables stored in ROM. + * Comment this macro to generate AES tables in RAM at runtime. + * + * Tradeoff: Using precomputed ROM tables reduces RAM usage by ~8kb + * (or ~2kb if \c MBEDTLS_AES_FEWER_TABLES is used) and reduces the + * initialization time before the first AES operation can be performed. + * It comes at the cost of additional ~8kb ROM use (resp. ~2kb if \c + * MBEDTLS_AES_FEWER_TABLES below is used), and potentially degraded + * performance if ROM access is slower than RAM access. + * + * This option is independent of \c MBEDTLS_AES_FEWER_TABLES. + * + */ +#define MBEDTLS_AES_ROM_TABLES + +/** + * \def MBEDTLS_AES_FEWER_TABLES + * + * Use less ROM/RAM for AES tables. + * + * Uncommenting this macro omits 75% of the AES tables from + * ROM / RAM (depending on the value of \c MBEDTLS_AES_ROM_TABLES) + * by computing their values on the fly during operations + * (the tables are entry-wise rotations of one another). + * + * Tradeoff: Uncommenting this reduces the RAM / ROM footprint + * by ~6kb but at the cost of more arithmetic operations during + * runtime. Specifically, one has to compare 4 accesses within + * different tables to 4 accesses with additional arithmetic + * operations within the same table. The performance gain/loss + * depends on the system and memory details. + * + * This option is independent of \c MBEDTLS_AES_ROM_TABLES. + * + */ +//#define MBEDTLS_AES_FEWER_TABLES + +/** + * \def MBEDTLS_CAMELLIA_SMALL_MEMORY + * + * Use less ROM for the Camellia implementation (saves about 768 bytes). + * + * Uncomment this macro to use less memory for Camellia. + */ +//#define MBEDTLS_CAMELLIA_SMALL_MEMORY + +/** + * \def MBEDTLS_CHECK_RETURN_WARNING + * + * If this macro is defined, emit a compile-time warning if application code + * calls a function without checking its return value, but the return value + * should generally be checked in portable applications. + * + * This is only supported on platforms where #MBEDTLS_CHECK_RETURN is + * implemented. Otherwise this option has no effect. + * + * Uncomment to get warnings on using fallible functions without checking + * their return value. + * + * \note This feature is a work in progress. + * Warnings will be added to more functions in the future. + * + * \note A few functions are considered critical, and ignoring the return + * value of these functions will trigger a warning even if this + * macro is not defined. To completely disable return value check + * warnings, define #MBEDTLS_CHECK_RETURN with an empty expansion. + */ +//#define MBEDTLS_CHECK_RETURN_WARNING + +/** + * \def MBEDTLS_CIPHER_MODE_CBC + * + * Enable Cipher Block Chaining mode (CBC) for symmetric ciphers. + */ +#define MBEDTLS_CIPHER_MODE_CBC + +/** + * \def MBEDTLS_CIPHER_MODE_CFB + * + * Enable Cipher Feedback mode (CFB) for symmetric ciphers. + */ +#define MBEDTLS_CIPHER_MODE_CFB + +/** + * \def MBEDTLS_CIPHER_MODE_CTR + * + * Enable Counter Block Cipher mode (CTR) for symmetric ciphers. + */ +#define MBEDTLS_CIPHER_MODE_CTR + +/** + * \def MBEDTLS_CIPHER_MODE_OFB + * + * Enable Output Feedback mode (OFB) for symmetric ciphers. + */ +#define MBEDTLS_CIPHER_MODE_OFB + +/** + * \def MBEDTLS_CIPHER_MODE_XTS + * + * Enable Xor-encrypt-xor with ciphertext stealing mode (XTS) for AES. + */ +#define MBEDTLS_CIPHER_MODE_XTS + +/** + * \def MBEDTLS_CIPHER_NULL_CIPHER + * + * Enable NULL cipher. + * Warning: Only do so when you know what you are doing. This allows for + * encryption or channels without any security! + * + * To enable the following ciphersuites: + * MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA + * MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA + * MBEDTLS_TLS_RSA_WITH_NULL_SHA256 + * MBEDTLS_TLS_RSA_WITH_NULL_SHA + * MBEDTLS_TLS_RSA_WITH_NULL_MD5 + * MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA + * MBEDTLS_TLS_PSK_WITH_NULL_SHA384 + * MBEDTLS_TLS_PSK_WITH_NULL_SHA256 + * MBEDTLS_TLS_PSK_WITH_NULL_SHA + * + * Uncomment this macro to enable the NULL cipher and ciphersuites + */ +//#define MBEDTLS_CIPHER_NULL_CIPHER + +/** + * \def MBEDTLS_CIPHER_PADDING_PKCS7 + * + * MBEDTLS_CIPHER_PADDING_XXX: Uncomment or comment macros to add support for + * specific padding modes in the cipher layer with cipher modes that support + * padding (e.g. CBC) + * + * If you disable all padding modes, only full blocks can be used with CBC. + * + * Enable padding modes in the cipher layer. + */ +#define MBEDTLS_CIPHER_PADDING_PKCS7 +#define MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS +#define MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN +#define MBEDTLS_CIPHER_PADDING_ZEROS + +/** \def MBEDTLS_CTR_DRBG_USE_128_BIT_KEY + * + * Uncomment this macro to use a 128-bit key in the CTR_DRBG module. + * By default, CTR_DRBG uses a 256-bit key. + */ +//#define MBEDTLS_CTR_DRBG_USE_128_BIT_KEY + +/** + * \def MBEDTLS_ECP_DP_SECP192R1_ENABLED + * + * MBEDTLS_ECP_XXXX_ENABLED: Enables specific curves within the Elliptic Curve + * module. By default all supported curves are enabled. + * + * Comment macros to disable the curve and functions for it + */ +/* Short Weierstrass curves (supporting ECP, ECDH, ECDSA) */ +#define MBEDTLS_ECP_DP_SECP192R1_ENABLED +#define MBEDTLS_ECP_DP_SECP224R1_ENABLED +#define MBEDTLS_ECP_DP_SECP256R1_ENABLED +#define MBEDTLS_ECP_DP_SECP384R1_ENABLED +#define MBEDTLS_ECP_DP_SECP521R1_ENABLED +#define MBEDTLS_ECP_DP_SECP192K1_ENABLED +#define MBEDTLS_ECP_DP_SECP224K1_ENABLED +#define MBEDTLS_ECP_DP_SECP256K1_ENABLED +#define MBEDTLS_ECP_DP_BP256R1_ENABLED +#define MBEDTLS_ECP_DP_BP384R1_ENABLED +#define MBEDTLS_ECP_DP_BP512R1_ENABLED +/* Montgomery curves (supporting ECP) */ +#define MBEDTLS_ECP_DP_CURVE25519_ENABLED +#define MBEDTLS_ECP_DP_CURVE448_ENABLED + +/** + * \def MBEDTLS_ECP_NIST_OPTIM + * + * Enable specific 'modulo p' routines for each NIST prime. + * Depending on the prime and architecture, makes operations 4 to 8 times + * faster on the corresponding curve. + * + * Comment this macro to disable NIST curves optimisation. + */ +#define MBEDTLS_ECP_NIST_OPTIM + +/** + * \def MBEDTLS_ECP_RESTARTABLE + * + * Enable "non-blocking" ECC operations that can return early and be resumed. + * + * This allows various functions to pause by returning + * #MBEDTLS_ERR_ECP_IN_PROGRESS (or, for functions in the SSL module, + * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) and then be called later again in + * order to further progress and eventually complete their operation. This is + * controlled through mbedtls_ecp_set_max_ops() which limits the maximum + * number of ECC operations a function may perform before pausing; see + * mbedtls_ecp_set_max_ops() for more information. + * + * This is useful in non-threaded environments if you want to avoid blocking + * for too long on ECC (and, hence, X.509 or SSL/TLS) operations. + * + * This option: + * - Adds xxx_restartable() variants of existing operations in the + * following modules, with corresponding restart context types: + * - ECP (for Short Weierstrass curves only): scalar multiplication (mul), + * linear combination (muladd); + * - ECDSA: signature generation & verification; + * - PK: signature generation & verification; + * - X509: certificate chain verification. + * - Adds mbedtls_ecdh_enable_restart() in the ECDH module. + * - Changes the behaviour of TLS 1.2 clients (not servers) when using the + * ECDHE-ECDSA key exchange (not other key exchanges) to make all ECC + * computations restartable: + * - ECDH operations from the key exchange, only for Short Weierstrass + * curves, only when MBEDTLS_USE_PSA_CRYPTO is not enabled. + * - verification of the server's key exchange signature; + * - verification of the server's certificate chain; + * - generation of the client's signature if client authentication is used, + * with an ECC key/certificate. + * + * \note In the cases above, the usual SSL/TLS functions, such as + * mbedtls_ssl_handshake(), can now return + * MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS. + * + * \note When this option and MBEDTLS_USE_PSA_CRYPTO are both enabled, + * restartable operations in PK, X.509 and TLS (see above) are not + * using PSA. On the other hand, ECDH computations in TLS are using + * PSA, and are not restartable. These are temporary limitations that + * should be lifted in the future. + * + * \note This option only works with the default software implementation of + * elliptic curve functionality. It is incompatible with + * MBEDTLS_ECP_ALT, MBEDTLS_ECDH_XXX_ALT, MBEDTLS_ECDSA_XXX_ALT. + * + * Requires: MBEDTLS_ECP_C + * + * Uncomment this macro to enable restartable ECC computations. + */ +//#define MBEDTLS_ECP_RESTARTABLE + +/** + * \def MBEDTLS_ECDSA_DETERMINISTIC + * + * Enable deterministic ECDSA (RFC 6979). + * Standard ECDSA is "fragile" in the sense that lack of entropy when signing + * may result in a compromise of the long-term signing key. This is avoided by + * the deterministic variant. + * + * Requires: MBEDTLS_HMAC_DRBG_C, MBEDTLS_ECDSA_C + * + * Comment this macro to disable deterministic ECDSA. + */ +#define MBEDTLS_ECDSA_DETERMINISTIC + +/** + * \def MBEDTLS_KEY_EXCHANGE_PSK_ENABLED + * + * Enable the PSK based ciphersuite modes in SSL / TLS. + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 + */ +#define MBEDTLS_KEY_EXCHANGE_PSK_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED + * + * Enable the DHE-PSK based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_DHM_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 + * + * \warning Using DHE constitutes a security risk as it + * is not possible to validate custom DH parameters. + * If possible, it is recommended users should consider + * preferring other methods of key exchange. + * See dhm.h for more details. + * + */ +#define MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED + * + * Enable the ECDHE-PSK based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_ECDH_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 + */ +#define MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED + * + * Enable the RSA-PSK based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, + * MBEDTLS_X509_CRT_PARSE_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 + */ +#define MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_RSA_ENABLED + * + * Enable the RSA-only based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, + * MBEDTLS_X509_CRT_PARSE_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA + */ +#define MBEDTLS_KEY_EXCHANGE_RSA_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED + * + * Enable the DHE-RSA based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_DHM_C, MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, + * MBEDTLS_X509_CRT_PARSE_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA + * + * \warning Using DHE constitutes a security risk as it + * is not possible to validate custom DH parameters. + * If possible, it is recommended users should consider + * preferring other methods of key exchange. + * See dhm.h for more details. + * + */ +#define MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED + * + * Enable the ECDHE-RSA based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_ECDH_C, MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, + * MBEDTLS_X509_CRT_PARSE_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 + */ +#define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED + * + * Enable the ECDHE-ECDSA based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_ECDH_C, MBEDTLS_ECDSA_C, MBEDTLS_X509_CRT_PARSE_C, + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 + */ +#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED + * + * Enable the ECDH-ECDSA based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_ECDH_C, MBEDTLS_ECDSA_C, MBEDTLS_X509_CRT_PARSE_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 + */ +#define MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED + * + * Enable the ECDH-RSA based ciphersuite modes in SSL / TLS. + * + * Requires: MBEDTLS_ECDH_C, MBEDTLS_RSA_C, MBEDTLS_X509_CRT_PARSE_C + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 + */ +#define MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED + +/** + * \def MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED + * + * Enable the ECJPAKE based ciphersuite modes in SSL / TLS. + * + * \warning This is currently experimental. EC J-PAKE support is based on the + * Thread v1.0.0 specification; incompatible changes to the specification + * might still happen. For this reason, this is disabled by default. + * + * Requires: MBEDTLS_ECJPAKE_C + * SHA-256 (via MD if present, or via PSA, see MBEDTLS_ECJPAKE_C) + * MBEDTLS_ECP_DP_SECP256R1_ENABLED + * + * This enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8 + */ +//#define MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED + +/** + * \def MBEDTLS_PK_PARSE_EC_EXTENDED + * + * Enhance support for reading EC keys using variants of SEC1 not allowed by + * RFC 5915 and RFC 5480. + * + * Currently this means parsing the SpecifiedECDomain choice of EC + * parameters (only known groups are supported, not arbitrary domains, to + * avoid validation issues). + * + * Disable if you only need to support RFC 5915 + 5480 key formats. + */ +#define MBEDTLS_PK_PARSE_EC_EXTENDED + +/** + * \def MBEDTLS_ERROR_STRERROR_DUMMY + * + * Enable a dummy error function to make use of mbedtls_strerror() in + * third party libraries easier when MBEDTLS_ERROR_C is disabled + * (no effect when MBEDTLS_ERROR_C is enabled). + * + * You can safely disable this if MBEDTLS_ERROR_C is enabled, or if you're + * not using mbedtls_strerror() or error_strerror() in your application. + * + * Disable if you run into name conflicts and want to really remove the + * mbedtls_strerror() + */ +#define MBEDTLS_ERROR_STRERROR_DUMMY + +/** + * \def MBEDTLS_GENPRIME + * + * Enable the prime-number generation code. + * + * Requires: MBEDTLS_BIGNUM_C + */ +//#define MBEDTLS_GENPRIME + +/** + * \def MBEDTLS_FS_IO + * + * Enable functions that use the filesystem. + */ +//#define MBEDTLS_FS_IO + +/** + * \def MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES + * + * Do not add default entropy sources in mbedtls_entropy_init(). + * + * This is useful to have more control over the added entropy sources in an + * application. + * + * Uncomment this macro to prevent loading of default entropy functions. + */ +//#define MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES + +/** + * \def MBEDTLS_NO_PLATFORM_ENTROPY + * + * Do not use built-in platform entropy functions. + * This is useful if your platform does not support + * standards like the /dev/urandom or Windows CryptoAPI. + * + * Uncomment this macro to disable the built-in platform entropy functions. + */ +#define MBEDTLS_NO_PLATFORM_ENTROPY + +/** + * \def MBEDTLS_ENTROPY_FORCE_SHA256 + * + * Force the entropy accumulator to use a SHA-256 accumulator instead of the + * default SHA-512 based one (if both are available). + * + * Requires: MBEDTLS_SHA256_C + * + * On 32-bit systems SHA-256 can be much faster than SHA-512. Use this option + * if you have performance concerns. + * + * This option is only useful if both MBEDTLS_SHA256_C and + * MBEDTLS_SHA512_C are defined. Otherwise the available hash module is used. + */ +//#define MBEDTLS_ENTROPY_FORCE_SHA256 + +/** + * \def MBEDTLS_ENTROPY_NV_SEED + * + * Enable the non-volatile (NV) seed file-based entropy source. + * (Also enables the NV seed read/write functions in the platform layer) + * + * This is crucial (if not required) on systems that do not have a + * cryptographic entropy source (in hardware or kernel) available. + * + * Requires: MBEDTLS_ENTROPY_C, MBEDTLS_PLATFORM_C + * + * \note The read/write functions that are used by the entropy source are + * determined in the platform layer, and can be modified at runtime and/or + * compile-time depending on the flags (MBEDTLS_PLATFORM_NV_SEED_*) used. + * + * \note If you use the default implementation functions that read a seedfile + * with regular fopen(), please make sure you make a seedfile with the + * proper name (defined in MBEDTLS_PLATFORM_STD_NV_SEED_FILE) and at + * least MBEDTLS_ENTROPY_BLOCK_SIZE bytes in size that can be read from + * and written to or you will get an entropy source error! The default + * implementation will only use the first MBEDTLS_ENTROPY_BLOCK_SIZE + * bytes from the file. + * + * \note The entropy collector will write to the seed file before entropy is + * given to an external source, to update it. + */ +//#define MBEDTLS_ENTROPY_NV_SEED + +/* MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER + * + * Enable key identifiers that encode a key owner identifier. + * + * The owner of a key is identified by a value of type ::mbedtls_key_owner_id_t + * which is currently hard-coded to be int32_t. + * + * Note that this option is meant for internal use only and may be removed + * without notice. + */ +//#define MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER + +/** + * \def MBEDTLS_MEMORY_DEBUG + * + * Enable debugging of buffer allocator memory issues. Automatically prints + * (to stderr) all (fatal) messages on memory allocation issues. Enables + * function for 'debug output' of allocated memory. + * + * Requires: MBEDTLS_MEMORY_BUFFER_ALLOC_C + * + * Uncomment this macro to let the buffer allocator print out error messages. + */ +//#define MBEDTLS_MEMORY_DEBUG + +/** + * \def MBEDTLS_MEMORY_BACKTRACE + * + * Include backtrace information with each allocated block. + * + * Requires: MBEDTLS_MEMORY_BUFFER_ALLOC_C + * GLIBC-compatible backtrace() and backtrace_symbols() support + * + * Uncomment this macro to include backtrace information + */ +//#define MBEDTLS_MEMORY_BACKTRACE + +/** + * \def MBEDTLS_PK_RSA_ALT_SUPPORT + * + * Support external private RSA keys (eg from a HSM) in the PK layer. + * + * Comment this macro to disable support for external private RSA keys. + */ +#define MBEDTLS_PK_RSA_ALT_SUPPORT + +/** + * \def MBEDTLS_PKCS1_V15 + * + * Enable support for PKCS#1 v1.5 encoding. + * + * Requires: MBEDTLS_RSA_C + * + * This enables support for PKCS#1 v1.5 operations. + */ +#define MBEDTLS_PKCS1_V15 + +/** + * \def MBEDTLS_PKCS1_V21 + * + * Enable support for PKCS#1 v2.1 encoding. + * + * Requires: MBEDTLS_RSA_C and (MBEDTLS_MD_C or MBEDTLS_PSA_CRYPTO_C). + * + * \warning If building without MBEDTLS_MD_C, you must call psa_crypto_init() + * before doing any PKCS#1 v2.1 operation. + * + * \warning When building with MBEDTLS_MD_C, all hashes used with this + * need to be available as built-ins (that is, for SHA-256, MBEDTLS_SHA256_C, + * etc.) as opposed to just PSA drivers. So far, PSA drivers are only used by + * this module in builds where MBEDTLS_MD_C is disabled. + * + * This enables support for RSAES-OAEP and RSASSA-PSS operations. + */ +#define MBEDTLS_PKCS1_V21 + +/** \def MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS + * + * Enable support for platform built-in keys. If you enable this feature, + * you must implement the function mbedtls_psa_platform_get_builtin_key(). + * See the documentation of that function for more information. + * + * Built-in keys are typically derived from a hardware unique key or + * stored in a secure element. + * + * Requires: MBEDTLS_PSA_CRYPTO_C. + * + * \warning This interface is experimental and may change or be removed + * without notice. + */ +//#define MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS + +/** \def MBEDTLS_PSA_CRYPTO_CLIENT + * + * Enable support for PSA crypto client. + * + * \note This option allows to include the code necessary for a PSA + * crypto client when the PSA crypto implementation is not included in + * the library (MBEDTLS_PSA_CRYPTO_C disabled). The code included is the + * code to set and get PSA key attributes. + * The development of PSA drivers partially relying on the library to + * fulfill the hardware gaps is another possible usage of this option. + * + * \warning This interface is experimental and may change or be removed + * without notice. + */ +//#define MBEDTLS_PSA_CRYPTO_CLIENT + +/** \def MBEDTLS_PSA_CRYPTO_DRIVERS + * + * Enable support for the experimental PSA crypto driver interface. + * + * Requires: MBEDTLS_PSA_CRYPTO_C + * + * \warning This interface is experimental. We intend to maintain backward + * compatibility with application code that relies on drivers, + * but the driver interfaces may change without notice. + */ +//#define MBEDTLS_PSA_CRYPTO_DRIVERS + +/** \def MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG + * + * Make the PSA Crypto module use an external random generator provided + * by a driver, instead of Mbed TLS's entropy and DRBG modules. + * + * \note This random generator must deliver random numbers with cryptographic + * quality and high performance. It must supply unpredictable numbers + * with a uniform distribution. The implementation of this function + * is responsible for ensuring that the random generator is seeded + * with sufficient entropy. If you have a hardware TRNG which is slow + * or delivers non-uniform output, declare it as an entropy source + * with mbedtls_entropy_add_source() instead of enabling this option. + * + * If you enable this option, you must configure the type + * ::mbedtls_psa_external_random_context_t in psa/crypto_platform.h + * and define a function called mbedtls_psa_external_get_random() + * with the following prototype: + * ``` + * psa_status_t mbedtls_psa_external_get_random( + * mbedtls_psa_external_random_context_t *context, + * uint8_t *output, size_t output_size, size_t *output_length); + * ); + * ``` + * The \c context value is initialized to 0 before the first call. + * The function must fill the \c output buffer with \p output_size bytes + * of random data and set \c *output_length to \p output_size. + * + * Requires: MBEDTLS_PSA_CRYPTO_C + * + * \warning If you enable this option, code that uses the PSA cryptography + * interface will not use any of the entropy sources set up for + * the entropy module, nor the NV seed that MBEDTLS_ENTROPY_NV_SEED + * enables. + * + * \note This option is experimental and may be removed without notice. + */ +#define MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG + +/** + * \def MBEDTLS_PSA_CRYPTO_SPM + * + * When MBEDTLS_PSA_CRYPTO_SPM is defined, the code is built for SPM (Secure + * Partition Manager) integration which separates the code into two parts: a + * NSPE (Non-Secure Process Environment) and an SPE (Secure Process + * Environment). + * + * Module: library/psa_crypto.c + * Requires: MBEDTLS_PSA_CRYPTO_C + * + */ +//#define MBEDTLS_PSA_CRYPTO_SPM + +/** + * \def MBEDTLS_PSA_INJECT_ENTROPY + * + * Enable support for entropy injection at first boot. This feature is + * required on systems that do not have a built-in entropy source (TRNG). + * This feature is currently not supported on systems that have a built-in + * entropy source. + * + * Requires: MBEDTLS_PSA_CRYPTO_STORAGE_C, MBEDTLS_ENTROPY_NV_SEED + * + */ +//#define MBEDTLS_PSA_INJECT_ENTROPY + +/** + * \def MBEDTLS_RSA_NO_CRT + * + * Do not use the Chinese Remainder Theorem + * for the RSA private operation. + * + * Uncomment this macro to disable the use of CRT in RSA. + * + */ +//#define MBEDTLS_RSA_NO_CRT + +/** + * \def MBEDTLS_SELF_TEST + * + * Enable the checkup functions (*_self_test). + */ +#define MBEDTLS_SELF_TEST + +/** + * \def MBEDTLS_SHA256_SMALLER + * + * Enable an implementation of SHA-256 that has lower ROM footprint but also + * lower performance. + * + * The default implementation is meant to be a reasonable compromise between + * performance and size. This version optimizes more aggressively for size at + * the expense of performance. Eg on Cortex-M4 it reduces the size of + * mbedtls_sha256_process() from ~2KB to ~0.5KB for a performance hit of about + * 30%. + * + * Uncomment to enable the smaller implementation of SHA256. + */ +//#define MBEDTLS_SHA256_SMALLER + +/** + * \def MBEDTLS_SHA512_SMALLER + * + * Enable an implementation of SHA-512 that has lower ROM footprint but also + * lower performance. + * + * Uncomment to enable the smaller implementation of SHA512. + */ +//#define MBEDTLS_SHA512_SMALLER + +/** + * \def MBEDTLS_SSL_ALL_ALERT_MESSAGES + * + * Enable sending of alert messages in case of encountered errors as per RFC. + * If you choose not to send the alert messages, mbed TLS can still communicate + * with other servers, only debugging of failures is harder. + * + * The advantage of not sending alert messages, is that no information is given + * about reasons for failures thus preventing adversaries of gaining intel. + * + * Enable sending of all alert messages + */ +#define MBEDTLS_SSL_ALL_ALERT_MESSAGES + +/** + * \def MBEDTLS_SSL_DTLS_CONNECTION_ID + * + * Enable support for the DTLS Connection ID (CID) extension, + * which allows to identify DTLS connections across changes + * in the underlying transport. The CID functionality is described + * in RFC 9146. + * + * Setting this option enables the SSL APIs `mbedtls_ssl_set_cid()`, + * mbedtls_ssl_get_own_cid()`, `mbedtls_ssl_get_peer_cid()` and + * `mbedtls_ssl_conf_cid()`. See the corresponding documentation for + * more information. + * + * The maximum lengths of outgoing and incoming CIDs can be configured + * through the options + * - MBEDTLS_SSL_CID_OUT_LEN_MAX + * - MBEDTLS_SSL_CID_IN_LEN_MAX. + * + * Requires: MBEDTLS_SSL_PROTO_DTLS + * + * Uncomment to enable the Connection ID extension. + */ +#define MBEDTLS_SSL_DTLS_CONNECTION_ID + + +/** + * \def MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT + * + * Defines whether RFC 9146 (default) or the legacy version + * (version draft-ietf-tls-dtls-connection-id-05, + * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05) + * is used. + * + * Set the value to 0 for the standard version, and + * 1 for the legacy draft version. + * + * \deprecated Support for the legacy version of the DTLS + * Connection ID feature is deprecated. Please + * switch to the standardized version defined + * in RFC 9146 enabled by utilizing + * MBEDTLS_SSL_DTLS_CONNECTION_ID without use + * of MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT. + * + * Requires: MBEDTLS_SSL_DTLS_CONNECTION_ID + */ +#define MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT 0 + +/** + * \def MBEDTLS_SSL_ASYNC_PRIVATE + * + * Enable asynchronous external private key operations in SSL. This allows + * you to configure an SSL connection to call an external cryptographic + * module to perform private key operations instead of performing the + * operation inside the library. + * + * Requires: MBEDTLS_X509_CRT_PARSE_C + */ +//#define MBEDTLS_SSL_ASYNC_PRIVATE + +/** + * \def MBEDTLS_SSL_CONTEXT_SERIALIZATION + * + * Enable serialization of the TLS context structures, through use of the + * functions mbedtls_ssl_context_save() and mbedtls_ssl_context_load(). + * + * This pair of functions allows one side of a connection to serialize the + * context associated with the connection, then free or re-use that context + * while the serialized state is persisted elsewhere, and finally deserialize + * that state to a live context for resuming read/write operations on the + * connection. From a protocol perspective, the state of the connection is + * unaffected, in particular this is entirely transparent to the peer. + * + * Note: this is distinct from TLS session resumption, which is part of the + * protocol and fully visible by the peer. TLS session resumption enables + * establishing new connections associated to a saved session with shorter, + * lighter handshakes, while context serialization is a local optimization in + * handling a single, potentially long-lived connection. + * + * Enabling these APIs makes some SSL structures larger, as 64 extra bytes are + * saved after the handshake to allow for more efficient serialization, so if + * you don't need this feature you'll save RAM by disabling it. + * + * Requires: MBEDTLS_GCM_C or MBEDTLS_CCM_C or MBEDTLS_CHACHAPOLY_C + * + * Comment to disable the context serialization APIs. + */ +#define MBEDTLS_SSL_CONTEXT_SERIALIZATION + +/** + * \def MBEDTLS_SSL_DEBUG_ALL + * + * Enable the debug messages in SSL module for all issues. + * Debug messages have been disabled in some places to prevent timing + * attacks due to (unbalanced) debugging function calls. + * + * If you need all error reporting you should enable this during debugging, + * but remove this for production servers that should log as well. + * + * Uncomment this macro to report all debug messages on errors introducing + * a timing side-channel. + * + */ +//#define MBEDTLS_SSL_DEBUG_ALL + +/** \def MBEDTLS_SSL_ENCRYPT_THEN_MAC + * + * Enable support for Encrypt-then-MAC, RFC 7366. + * + * This allows peers that both support it to use a more robust protection for + * ciphersuites using CBC, providing deep resistance against timing attacks + * on the padding or underlying cipher. + * + * This only affects CBC ciphersuites, and is useless if none is defined. + * + * Requires: MBEDTLS_SSL_PROTO_TLS1_2 + * + * Comment this macro to disable support for Encrypt-then-MAC + */ +#define MBEDTLS_SSL_ENCRYPT_THEN_MAC + +/** \def MBEDTLS_SSL_EXTENDED_MASTER_SECRET + * + * Enable support for RFC 7627: Session Hash and Extended Master Secret + * Extension. + * + * This was introduced as "the proper fix" to the Triple Handshake family of + * attacks, but it is recommended to always use it (even if you disable + * renegotiation), since it actually fixes a more fundamental issue in the + * original SSL/TLS design, and has implications beyond Triple Handshake. + * + * Requires: MBEDTLS_SSL_PROTO_TLS1_2 + * + * Comment this macro to disable support for Extended Master Secret. + */ +#define MBEDTLS_SSL_EXTENDED_MASTER_SECRET + +/** + * \def MBEDTLS_SSL_KEEP_PEER_CERTIFICATE + * + * This option controls the availability of the API mbedtls_ssl_get_peer_cert() + * giving access to the peer's certificate after completion of the handshake. + * + * Unless you need mbedtls_ssl_peer_cert() in your application, it is + * recommended to disable this option for reduced RAM usage. + * + * \note If this option is disabled, mbedtls_ssl_get_peer_cert() is still + * defined, but always returns \c NULL. + * + * \note This option has no influence on the protection against the + * triple handshake attack. Even if it is disabled, Mbed TLS will + * still ensure that certificates do not change during renegotiation, + * for example by keeping a hash of the peer's certificate. + * + * \note This option is required if MBEDTLS_SSL_PROTO_TLS1_3 is set. + * + * Comment this macro to disable storing the peer's certificate + * after the handshake. + */ +#define MBEDTLS_SSL_KEEP_PEER_CERTIFICATE + +/** + * \def MBEDTLS_SSL_RENEGOTIATION + * + * Enable support for TLS renegotiation. + * + * The two main uses of renegotiation are (1) refresh keys on long-lived + * connections and (2) client authentication after the initial handshake. + * If you don't need renegotiation, it's probably better to disable it, since + * it has been associated with security issues in the past and is easy to + * misuse/misunderstand. + * + * Comment this to disable support for renegotiation. + * + * \note Even if this option is disabled, both client and server are aware + * of the Renegotiation Indication Extension (RFC 5746) used to + * prevent the SSL renegotiation attack (see RFC 5746 Sect. 1). + * (See \c mbedtls_ssl_conf_legacy_renegotiation for the + * configuration of this extension). + * + */ +#define MBEDTLS_SSL_RENEGOTIATION + +/** + * \def MBEDTLS_SSL_MAX_FRAGMENT_LENGTH + * + * Enable support for RFC 6066 max_fragment_length extension in SSL. + * + * Comment this macro to disable support for the max_fragment_length extension + */ +#define MBEDTLS_SSL_MAX_FRAGMENT_LENGTH + +/** + * \def MBEDTLS_SSL_RECORD_SIZE_LIMIT + * + * Enable support for RFC 8449 record_size_limit extension in SSL (TLS 1.3 only). + * + * \warning This extension is currently in development and must NOT be used except + * for testing purposes. + * + * Requires: MBEDTLS_SSL_PROTO_TLS1_3 + * + * Uncomment this macro to enable support for the record_size_limit extension + */ +//#define MBEDTLS_SSL_RECORD_SIZE_LIMIT + +/** + * \def MBEDTLS_SSL_PROTO_TLS1_2 + * + * Enable support for TLS 1.2 (and DTLS 1.2 if DTLS is enabled). + * + * Requires: Without MBEDTLS_USE_PSA_CRYPTO: MBEDTLS_MD_C and + * (MBEDTLS_SHA1_C or MBEDTLS_SHA256_C or MBEDTLS_SHA512_C) + * With MBEDTLS_USE_PSA_CRYPTO: + * PSA_WANT_ALG_SHA_1 or PSA_WANT_ALG_SHA_256 or + * PSA_WANT_ALG_SHA_512 + * + * \warning If building with MBEDTLS_USE_PSA_CRYPTO, you must call + * psa_crypto_init() before doing any TLS operations. + * + * Comment this macro to disable support for TLS 1.2 / DTLS 1.2 + */ +#define MBEDTLS_SSL_PROTO_TLS1_2 + +/** + * \def MBEDTLS_SSL_PROTO_TLS1_3 + * + * Enable support for TLS 1.3. + * + * \note The support for TLS 1.3 is not comprehensive yet, in particular + * pre-shared keys are not supported. + * See docs/architecture/tls13-support.md for a description of the TLS + * 1.3 support that this option enables. + * + * Requires: MBEDTLS_SSL_KEEP_PEER_CERTIFICATE + * Requires: MBEDTLS_PSA_CRYPTO_C + * + * \note TLS 1.3 uses PSA crypto for cryptographic operations that are + * directly performed by TLS 1.3 code. As a consequence, you must + * call psa_crypto_init() before the first TLS 1.3 handshake. + * + * \note Cryptographic operations performed indirectly via another module + * (X.509, PK) or by code shared with TLS 1.2 (record protection, + * running handshake hash) only use PSA crypto if + * #MBEDTLS_USE_PSA_CRYPTO is enabled. + * + * Uncomment this macro to enable the support for TLS 1.3. + */ +#define MBEDTLS_SSL_PROTO_TLS1_3 + +/** + * \def MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE + * + * Enable TLS 1.3 middlebox compatibility mode. + * + * As specified in Section D.4 of RFC 8446, TLS 1.3 offers a compatibility + * mode to make a TLS 1.3 connection more likely to pass through middle boxes + * expecting TLS 1.2 traffic. + * + * Turning on the compatibility mode comes at the cost of a few added bytes + * on the wire, but it doesn't affect compatibility with TLS 1.3 implementations + * that don't use it. Therefore, unless transmission bandwidth is critical and + * you know that middlebox compatibility issues won't occur, it is therefore + * recommended to set this option. + * + * Comment to disable compatibility mode for TLS 1.3. If + * MBEDTLS_SSL_PROTO_TLS1_3 is not enabled, this option does not have any + * effect on the build. + * + */ +#define MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE + +/** + * \def MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED + * + * Enable TLS 1.3 PSK key exchange mode. + * + * Comment to disable support for the PSK key exchange mode in TLS 1.3. If + * MBEDTLS_SSL_PROTO_TLS1_3 is not enabled, this option does not have any + * effect on the build. + * + */ +#define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED + +/** + * \def MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED + * + * Enable TLS 1.3 ephemeral key exchange mode. + * + * Requires: MBEDTLS_ECDH_C, MBEDTLS_X509_CRT_PARSE_C, MBEDTLS_ECDSA_C or + * MBEDTLS_PKCS1_V21 + * + * Comment to disable support for the ephemeral key exchange mode in TLS 1.3. + * If MBEDTLS_SSL_PROTO_TLS1_3 is not enabled, this option does not have any + * effect on the build. + * + */ +#define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED + +/** + * \def MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED + * + * Enable TLS 1.3 PSK ephemeral key exchange mode. + * + * Requires: MBEDTLS_ECDH_C + * + * Comment to disable support for the PSK ephemeral key exchange mode in + * TLS 1.3. If MBEDTLS_SSL_PROTO_TLS1_3 is not enabled, this option does not + * have any effect on the build. + * + */ +#define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED + +/** + * \def MBEDTLS_SSL_EARLY_DATA + * + * Enable support for RFC 8446 TLS 1.3 early data. + * + * Requires: MBEDTLS_SSL_SESSION_TICKETS and either + * MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED or + * MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED + * + * Comment this to disable support for early data. If MBEDTLS_SSL_PROTO_TLS1_3 + * is not enabled, this option does not have any effect on the build. + * + * This feature is experimental, not completed and thus not ready for + * production. + * + */ +//#define MBEDTLS_SSL_EARLY_DATA + +/** + * \def MBEDTLS_SSL_MAX_EARLY_DATA_SIZE + * + * The default maximum amount of 0-RTT data. See the documentation of + * \c mbedtls_ssl_tls13_conf_max_early_data_size() for more information. + * + * It must be positive and smaller than UINT32_MAX. + * + * If MBEDTLS_SSL_EARLY_DATA is not defined, this default value does not + * have any impact on the build. + * + * This feature is experimental, not completed and thus not ready for + * production. + * + */ +#define MBEDTLS_SSL_MAX_EARLY_DATA_SIZE 1024 + +/** + * \def MBEDTLS_SSL_PROTO_DTLS + * + * Enable support for DTLS (all available versions). + * + * Enable this and MBEDTLS_SSL_PROTO_TLS1_2 to enable DTLS 1.2. + * + * Requires: MBEDTLS_SSL_PROTO_TLS1_2 + * + * Comment this macro to disable support for DTLS + */ +#define MBEDTLS_SSL_PROTO_DTLS + +/** + * \def MBEDTLS_SSL_ALPN + * + * Enable support for RFC 7301 Application Layer Protocol Negotiation. + * + * Comment this macro to disable support for ALPN. + */ +#define MBEDTLS_SSL_ALPN + +/** + * \def MBEDTLS_SSL_DTLS_ANTI_REPLAY + * + * Enable support for the anti-replay mechanism in DTLS. + * + * Requires: MBEDTLS_SSL_TLS_C + * MBEDTLS_SSL_PROTO_DTLS + * + * \warning Disabling this is often a security risk! + * See mbedtls_ssl_conf_dtls_anti_replay() for details. + * + * Comment this to disable anti-replay in DTLS. + */ +#define MBEDTLS_SSL_DTLS_ANTI_REPLAY + +/** + * \def MBEDTLS_SSL_DTLS_HELLO_VERIFY + * + * Enable support for HelloVerifyRequest on DTLS servers. + * + * This feature is highly recommended to prevent DTLS servers being used as + * amplifiers in DoS attacks against other hosts. It should always be enabled + * unless you know for sure amplification cannot be a problem in the + * environment in which your server operates. + * + * \warning Disabling this can be a security risk! (see above) + * + * Requires: MBEDTLS_SSL_PROTO_DTLS + * + * Comment this to disable support for HelloVerifyRequest. + */ +#define MBEDTLS_SSL_DTLS_HELLO_VERIFY + +/** + * \def MBEDTLS_SSL_DTLS_SRTP + * + * Enable support for negotiation of DTLS-SRTP (RFC 5764) + * through the use_srtp extension. + * + * \note This feature provides the minimum functionality required + * to negotiate the use of DTLS-SRTP and to allow the derivation of + * the associated SRTP packet protection key material. + * In particular, the SRTP packet protection itself, as well as the + * demultiplexing of RTP and DTLS packets at the datagram layer + * (see Section 5 of RFC 5764), are not handled by this feature. + * Instead, after successful completion of a handshake negotiating + * the use of DTLS-SRTP, the extended key exporter API + * mbedtls_ssl_conf_export_keys_cb() should be used to implement + * the key exporter described in Section 4.2 of RFC 5764 and RFC 5705 + * (this is implemented in the SSL example programs). + * The resulting key should then be passed to an SRTP stack. + * + * Setting this option enables the runtime API + * mbedtls_ssl_conf_dtls_srtp_protection_profiles() + * through which the supported DTLS-SRTP protection + * profiles can be configured. You must call this API at + * runtime if you wish to negotiate the use of DTLS-SRTP. + * + * Requires: MBEDTLS_SSL_PROTO_DTLS + * + * Uncomment this to enable support for use_srtp extension. + */ +//#define MBEDTLS_SSL_DTLS_SRTP + +/** + * \def MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE + * + * Enable server-side support for clients that reconnect from the same port. + * + * Some clients unexpectedly close the connection and try to reconnect using the + * same source port. This needs special support from the server to handle the + * new connection securely, as described in section 4.2.8 of RFC 6347. This + * flag enables that support. + * + * Requires: MBEDTLS_SSL_DTLS_HELLO_VERIFY + * + * Comment this to disable support for clients reusing the source port. + */ +#define MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE + +/** + * \def MBEDTLS_SSL_SESSION_TICKETS + * + * Enable support for RFC 5077 session tickets in SSL. + * Client-side, provides full support for session tickets (maintenance of a + * session store remains the responsibility of the application, though). + * Server-side, you also need to provide callbacks for writing and parsing + * tickets, including authenticated encryption and key management. Example + * callbacks are provided by MBEDTLS_SSL_TICKET_C. + * + * Comment this macro to disable support for SSL session tickets + */ +#define MBEDTLS_SSL_SESSION_TICKETS + +/** + * \def MBEDTLS_SSL_SERVER_NAME_INDICATION + * + * Enable support for RFC 6066 server name indication (SNI) in SSL. + * + * Requires: MBEDTLS_X509_CRT_PARSE_C + * + * Comment this macro to disable support for server name indication in SSL + */ +#define MBEDTLS_SSL_SERVER_NAME_INDICATION + +/** + * \def MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH + * + * When this option is enabled, the SSL buffer will be resized automatically + * based on the negotiated maximum fragment length in each direction. + * + * Requires: MBEDTLS_SSL_MAX_FRAGMENT_LENGTH + */ +//#define MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH + +/** + * \def MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN + * + * Enable testing of the constant-flow nature of some sensitive functions with + * clang's MemorySanitizer. This causes some existing tests to also test + * this non-functional property of the code under test. + * + * This setting requires compiling with clang -fsanitize=memory. The test + * suites can then be run normally. + * + * \warning This macro is only used for extended testing; it is not considered + * part of the library's API, so it may change or disappear at any time. + * + * Uncomment to enable testing of the constant-flow nature of selected code. + */ +//#define MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN + +/** + * \def MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND + * + * Enable testing of the constant-flow nature of some sensitive functions with + * valgrind's memcheck tool. This causes some existing tests to also test + * this non-functional property of the code under test. + * + * This setting requires valgrind headers for building, and is only useful for + * testing if the tests suites are run with valgrind's memcheck. This can be + * done for an individual test suite with 'valgrind ./test_suite_xxx', or when + * using CMake, this can be done for all test suites with 'make memcheck'. + * + * \warning This macro is only used for extended testing; it is not considered + * part of the library's API, so it may change or disappear at any time. + * + * Uncomment to enable testing of the constant-flow nature of selected code. + */ +//#define MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND + +/** + * \def MBEDTLS_TEST_HOOKS + * + * Enable features for invasive testing such as introspection functions and + * hooks for fault injection. This enables additional unit tests. + * + * Merely enabling this feature should not change the behavior of the product. + * It only adds new code, and new branching points where the default behavior + * is the same as when this feature is disabled. + * However, this feature increases the attack surface: there is an added + * risk of vulnerabilities, and more gadgets that can make exploits easier. + * Therefore this feature must never be enabled in production. + * + * See `docs/architecture/testing/mbed-crypto-invasive-testing.md` for more + * information. + * + * Uncomment to enable invasive tests. + */ +//#define MBEDTLS_TEST_HOOKS + +/** + * \def MBEDTLS_THREADING_ALT + * + * Provide your own alternate threading implementation. + * + * Requires: MBEDTLS_THREADING_C + * + * Uncomment this to allow your own alternate threading implementation. + */ +//#define MBEDTLS_THREADING_ALT + +/** + * \def MBEDTLS_THREADING_PTHREAD + * + * Enable the pthread wrapper layer for the threading layer. + * + * Requires: MBEDTLS_THREADING_C + * + * Uncomment this to enable pthread mutexes. + */ +//#define MBEDTLS_THREADING_PTHREAD + +/** + * \def MBEDTLS_USE_PSA_CRYPTO + * + * Make the X.509 and TLS library use PSA for cryptographic operations, and + * enable new APIs for using keys handled by PSA Crypto. + * + * \note Development of this option is currently in progress, and parts of Mbed + * TLS's X.509 and TLS modules are not ported to PSA yet. However, these parts + * will still continue to work as usual, so enabling this option should not + * break backwards compatibility. + * + * \note See docs/use-psa-crypto.md for a complete description of what this + * option currently does, and of parts that are not affected by it so far. + * + * \warning If you enable this option, you need to call `psa_crypto_init()` + * before calling any function from the SSL/TLS, X.509 or PK modules. + * + * Requires: MBEDTLS_PSA_CRYPTO_C. + * + * Uncomment this to enable internal use of PSA Crypto and new associated APIs. + */ +//#define MBEDTLS_USE_PSA_CRYPTO + +/** + * \def MBEDTLS_PSA_CRYPTO_CONFIG + * + * This setting allows support for cryptographic mechanisms through the PSA + * API to be configured separately from support through the mbedtls API. + * + * When this option is disabled, the PSA API exposes the cryptographic + * mechanisms that can be implemented on top of the `mbedtls_xxx` API + * configured with `MBEDTLS_XXX` symbols. + * + * When this option is enabled, the PSA API exposes the cryptographic + * mechanisms requested by the `PSA_WANT_XXX` symbols defined in + * include/psa/crypto_config.h. The corresponding `MBEDTLS_XXX` settings are + * automatically enabled if required (i.e. if no PSA driver provides the + * mechanism). You may still freely enable additional `MBEDTLS_XXX` symbols + * in mbedtls_config.h. + * + * If the symbol #MBEDTLS_PSA_CRYPTO_CONFIG_FILE is defined, it specifies + * an alternative header to include instead of include/psa/crypto_config.h. + * + * This feature is still experimental and is not ready for production since + * it is not completed. + */ +//#define MBEDTLS_PSA_CRYPTO_CONFIG + +/** + * \def MBEDTLS_VERSION_FEATURES + * + * Allow run-time checking of compile-time enabled features. Thus allowing users + * to check at run-time if the library is for instance compiled with threading + * support via mbedtls_version_check_feature(). + * + * Requires: MBEDTLS_VERSION_C + * + * Comment this to disable run-time checking and save ROM space + */ +#define MBEDTLS_VERSION_FEATURES + +/** + * \def MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK + * + * If set, this enables the X.509 API `mbedtls_x509_crt_verify_with_ca_cb()` + * and the SSL API `mbedtls_ssl_conf_ca_cb()` which allow users to configure + * the set of trusted certificates through a callback instead of a linked + * list. + * + * This is useful for example in environments where a large number of trusted + * certificates is present and storing them in a linked list isn't efficient + * enough, or when the set of trusted certificates changes frequently. + * + * See the documentation of `mbedtls_x509_crt_verify_with_ca_cb()` and + * `mbedtls_ssl_conf_ca_cb()` for more information. + * + * Requires: MBEDTLS_X509_CRT_PARSE_C + * + * Uncomment to enable trusted certificate callbacks. + */ +//#define MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK + +/** + * \def MBEDTLS_X509_REMOVE_INFO + * + * Disable mbedtls_x509_*_info() and related APIs. + * + * Uncomment to omit mbedtls_x509_*_info(), as well as mbedtls_debug_print_crt() + * and other functions/constants only used by these functions, thus reducing + * the code footprint by several KB. + */ +//#define MBEDTLS_X509_REMOVE_INFO + +/** + * \def MBEDTLS_X509_RSASSA_PSS_SUPPORT + * + * Enable parsing and verification of X.509 certificates, CRLs and CSRS + * signed with RSASSA-PSS (aka PKCS#1 v2.1). + * + * Comment this macro to disallow using RSASSA-PSS in certificates. + */ +#define MBEDTLS_X509_RSASSA_PSS_SUPPORT +/** \} name SECTION: mbed TLS feature support */ + +/** + * \name SECTION: mbed TLS modules + * + * This section enables or disables entire modules in mbed TLS + * \{ + */ + +/** + * \def MBEDTLS_AESNI_C + * + * Enable AES-NI support on x86-64 or x86-32. + * + * \note AESNI is only supported with certain compilers and target options: + * - Visual Studio 2013: supported. + * - GCC, x86-64, target not explicitly supporting AESNI: + * requires MBEDTLS_HAVE_ASM. + * - GCC, x86-32, target not explicitly supporting AESNI: + * not supported. + * - GCC, x86-64 or x86-32, target supporting AESNI: supported. + * For this assembly-less implementation, you must currently compile + * `library/aesni.c` and `library/aes.c` with machine options to enable + * SSE2 and AESNI instructions: `gcc -msse2 -maes -mpclmul` or + * `clang -maes -mpclmul`. + * - Non-x86 targets: this option is silently ignored. + * - Other compilers: this option is silently ignored. + * + * \note + * Above, "GCC" includes compatible compilers such as Clang. + * The limitations on target support are likely to be relaxed in the future. + * + * Module: library/aesni.c + * Caller: library/aes.c + * + * Requires: MBEDTLS_HAVE_ASM (on some platforms, see note) + * + * This modules adds support for the AES-NI instructions on x86. + */ +//#define MBEDTLS_AESNI_C + +/** + * \def MBEDTLS_AESCE_C + * + * Enable AES cryptographic extension support on 64-bit Arm. + * + * Module: library/aesce.c + * Caller: library/aes.c + * + * Requires: MBEDTLS_HAVE_ASM, MBEDTLS_AES_C + * + * \warning Runtime detection only works on Linux. For non-Linux operating + * system, Armv8-A Cryptographic Extensions must be supported by + * the CPU when this option is enabled. + * + * This module adds support for the AES Armv8-A Cryptographic Extensions on Aarch64 systems. + */ +//#define MBEDTLS_AESCE_C + +/** + * \def MBEDTLS_AES_C + * + * Enable the AES block cipher. + * + * Module: library/aes.c + * Caller: library/cipher.c + * library/pem.c + * library/ctr_drbg.c + * + * This module enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA + * MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384 + * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384 + * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA + * MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256 + * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256 + * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA + * + * PEM_PARSE uses AES for decrypting encrypted keys. + */ +#define MBEDTLS_AES_C + +/** + * \def MBEDTLS_ASN1_PARSE_C + * + * Enable the generic ASN1 parser. + * + * Module: library/asn1.c + * Caller: library/x509.c + * library/dhm.c + * library/pkcs12.c + * library/pkcs5.c + * library/pkparse.c + */ +#define MBEDTLS_ASN1_PARSE_C + +/** + * \def MBEDTLS_ASN1_WRITE_C + * + * Enable the generic ASN1 writer. + * + * Module: library/asn1write.c + * Caller: library/ecdsa.c + * library/pkwrite.c + * library/x509_create.c + * library/x509write_crt.c + * library/x509write_csr.c + */ +#define MBEDTLS_ASN1_WRITE_C + +/** + * \def MBEDTLS_BASE64_C + * + * Enable the Base64 module. + * + * Module: library/base64.c + * Caller: library/pem.c + * + * This module is required for PEM support (required by X.509). + */ +#define MBEDTLS_BASE64_C + +/** + * \def MBEDTLS_BIGNUM_C + * + * Enable the multi-precision integer library. + * + * Module: library/bignum.c + * library/bignum_core.c + * library/bignum_mod.c + * library/bignum_mod_raw.c + * Caller: library/dhm.c + * library/ecp.c + * library/ecdsa.c + * library/rsa.c + * library/rsa_alt_helpers.c + * library/ssl_tls.c + * + * This module is required for RSA, DHM and ECC (ECDH, ECDSA) support. + */ +#define MBEDTLS_BIGNUM_C + +/** + * \def MBEDTLS_CAMELLIA_C + * + * Enable the Camellia block cipher. + * + * Module: library/camellia.c + * Caller: library/cipher.c + * + * This module enables the following ciphersuites (if other requisites are + * enabled as well): + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 + * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 + */ +#define MBEDTLS_CAMELLIA_C + +/** + * \def MBEDTLS_ARIA_C + * + * Enable the ARIA block cipher. + * + * Module: library/aria.c + * Caller: library/cipher.c + * + * This module enables the following ciphersuites (if other requisites are + * enabled as well): + * + * MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 + */ +#define MBEDTLS_ARIA_C + +/** + * \def MBEDTLS_CCM_C + * + * Enable the Counter with CBC-MAC (CCM) mode for 128-bit block cipher. + * + * Module: library/ccm.c + * + * Requires: MBEDTLS_CIPHER_C, MBEDTLS_AES_C or MBEDTLS_CAMELLIA_C or + * MBEDTLS_ARIA_C + * + * This module enables the AES-CCM ciphersuites, if other requisites are + * enabled as well. + */ +#define MBEDTLS_CCM_C + +/** + * \def MBEDTLS_CHACHA20_C + * + * Enable the ChaCha20 stream cipher. + * + * Module: library/chacha20.c + */ +#define MBEDTLS_CHACHA20_C + +/** + * \def MBEDTLS_CHACHAPOLY_C + * + * Enable the ChaCha20-Poly1305 AEAD algorithm. + * + * Module: library/chachapoly.c + * + * This module requires: MBEDTLS_CHACHA20_C, MBEDTLS_POLY1305_C + */ +#define MBEDTLS_CHACHAPOLY_C + +/** + * \def MBEDTLS_CIPHER_C + * + * Enable the generic cipher layer. + * + * Module: library/cipher.c + * Caller: library/ccm.c + * library/cmac.c + * library/gcm.c + * library/nist_kw.c + * library/pkcs12.c + * library/pkcs5.c + * library/psa_crypto_aead.c + * library/psa_crypto_mac.c + * library/ssl_ciphersuites.c + * library/ssl_msg.c + * library/ssl_ticket.c (unless MBEDTLS_USE_PSA_CRYPTO is enabled) + * + * Uncomment to enable generic cipher wrappers. + */ +#define MBEDTLS_CIPHER_C + +/** + * \def MBEDTLS_CMAC_C + * + * Enable the CMAC (Cipher-based Message Authentication Code) mode for block + * ciphers. + * + * \note When #MBEDTLS_CMAC_ALT is active, meaning that the underlying + * implementation of the CMAC algorithm is provided by an alternate + * implementation, that alternate implementation may opt to not support + * AES-192 or 3DES as underlying block ciphers for the CMAC operation. + * + * Module: library/cmac.c + * + * Requires: MBEDTLS_CIPHER_C, MBEDTLS_AES_C or MBEDTLS_DES_C + * + */ +#define MBEDTLS_CMAC_C + +/** + * \def MBEDTLS_CTR_DRBG_C + * + * Enable the CTR_DRBG AES-based random generator. + * The CTR_DRBG generator uses AES-256 by default. + * To use AES-128 instead, enable \c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY above. + * + * \note To achieve a 256-bit security strength with CTR_DRBG, + * you must use AES-256 *and* use sufficient entropy. + * See ctr_drbg.h for more details. + * + * Module: library/ctr_drbg.c + * Caller: + * + * Requires: MBEDTLS_AES_C + * + * This module provides the CTR_DRBG AES random number generator. + */ +#define MBEDTLS_CTR_DRBG_C + +/** + * \def MBEDTLS_DEBUG_C + * + * Enable the debug functions. + * + * Module: library/debug.c + * Caller: library/ssl_msg.c + * library/ssl_tls.c + * library/ssl_tls12_*.c + * library/ssl_tls13_*.c + * + * This module provides debugging functions. + */ +#define MBEDTLS_DEBUG_C + +/** + * \def MBEDTLS_DES_C + * + * Enable the DES block cipher. + * + * Module: library/des.c + * Caller: library/pem.c + * library/cipher.c + * + * PEM_PARSE uses DES/3DES for decrypting encrypted keys. + * + * \warning DES/3DES are considered weak ciphers and their use constitutes a + * security risk. We recommend considering stronger ciphers instead. + */ +#define MBEDTLS_DES_C + +/** + * \def MBEDTLS_DHM_C + * + * Enable the Diffie-Hellman-Merkle module. + * + * Module: library/dhm.c + * Caller: library/ssl_tls.c + * library/ssl*_client.c + * library/ssl*_server.c + * + * This module is used by the following key exchanges: + * DHE-RSA, DHE-PSK + * + * \warning Using DHE constitutes a security risk as it + * is not possible to validate custom DH parameters. + * If possible, it is recommended users should consider + * preferring other methods of key exchange. + * See dhm.h for more details. + * + */ +#define MBEDTLS_DHM_C + +/** + * \def MBEDTLS_ECDH_C + * + * Enable the elliptic curve Diffie-Hellman library. + * + * Module: library/ecdh.c + * Caller: library/psa_crypto.c + * library/ssl_tls.c + * library/ssl*_client.c + * library/ssl*_server.c + * + * This module is used by the following key exchanges: + * ECDHE-ECDSA, ECDHE-RSA, DHE-PSK + * + * Requires: MBEDTLS_ECP_C + */ +#define MBEDTLS_ECDH_C + +/** + * \def MBEDTLS_ECDSA_C + * + * Enable the elliptic curve DSA library. + * + * Module: library/ecdsa.c + * Caller: + * + * This module is used by the following key exchanges: + * ECDHE-ECDSA + * + * Requires: MBEDTLS_ECP_C, MBEDTLS_ASN1_WRITE_C, MBEDTLS_ASN1_PARSE_C, + * and at least one MBEDTLS_ECP_DP_XXX_ENABLED for a + * short Weierstrass curve. + */ +#define MBEDTLS_ECDSA_C + +/** + * \def MBEDTLS_ECJPAKE_C + * + * Enable the elliptic curve J-PAKE library. + * + * \note EC J-PAKE support is based on the Thread v1.0.0 specification. + * It has not been reviewed for compliance with newer standards such as + * Thread v1.1 or RFC 8236. + * + * Module: library/ecjpake.c + * Caller: + * + * This module is used by the following key exchanges: + * ECJPAKE + * + * Requires: MBEDTLS_ECP_C and either MBEDTLS_MD_C or MBEDTLS_PSA_CRYPTO_C + * + * \warning If building without MBEDTLS_MD_C, you must call psa_crypto_init() + * before doing any EC J-PAKE operations. + * + * \warning When building with MBEDTLS_MD_C, all hashes used with this + * need to be available as built-ins (that is, for SHA-256, MBEDTLS_SHA256_C, + * etc.) as opposed to just PSA drivers. So far, PSA drivers are only used by + * this module in builds where MBEDTLS_MD_C is disabled. + */ +#define MBEDTLS_ECJPAKE_C + +/** + * \def MBEDTLS_ECP_C + * + * Enable the elliptic curve over GF(p) library. + * + * Module: library/ecp.c + * Caller: library/ecdh.c + * library/ecdsa.c + * library/ecjpake.c + * + * Requires: MBEDTLS_BIGNUM_C and at least one MBEDTLS_ECP_DP_XXX_ENABLED + */ +#define MBEDTLS_ECP_C + +/** + * \def MBEDTLS_ENTROPY_C + * + * Enable the platform-specific entropy code. + * + * Module: library/entropy.c + * Caller: + * + * Requires: MBEDTLS_SHA512_C or MBEDTLS_SHA256_C + * + * This module provides a generic entropy pool + */ +#define MBEDTLS_ENTROPY_C + +/** + * \def MBEDTLS_ERROR_C + * + * Enable error code to error string conversion. + * + * Module: library/error.c + * Caller: + * + * This module enables mbedtls_strerror(). + */ +#define MBEDTLS_ERROR_C + +/** + * \def MBEDTLS_GCM_C + * + * Enable the Galois/Counter Mode (GCM). + * + * Module: library/gcm.c + * + * Requires: MBEDTLS_CIPHER_C, MBEDTLS_AES_C or MBEDTLS_CAMELLIA_C or + * MBEDTLS_ARIA_C + * + * This module enables the AES-GCM and CAMELLIA-GCM ciphersuites, if other + * requisites are enabled as well. + */ +#define MBEDTLS_GCM_C + +/** + * \def MBEDTLS_HKDF_C + * + * Enable the HKDF algorithm (RFC 5869). + * + * Module: library/hkdf.c + * Caller: + * + * Requires: MBEDTLS_MD_C + * + * This module adds support for the Hashed Message Authentication Code + * (HMAC)-based key derivation function (HKDF). + */ +#define MBEDTLS_HKDF_C + +/** + * \def MBEDTLS_HMAC_DRBG_C + * + * Enable the HMAC_DRBG random generator. + * + * Module: library/hmac_drbg.c + * Caller: + * + * Requires: MBEDTLS_MD_C + * + * Uncomment to enable the HMAC_DRBG random number generator. + */ +#define MBEDTLS_HMAC_DRBG_C + +/** + * \def MBEDTLS_LMS_C + * + * Enable the LMS stateful-hash asymmetric signature algorithm. + * + * Module: library/lms.c + * Caller: + * + * Requires: MBEDTLS_PSA_CRYPTO_C + * + * Uncomment to enable the LMS verification algorithm and public key operations. + */ +#define MBEDTLS_LMS_C + +/** + * \def MBEDTLS_LMS_PRIVATE + * + * Enable LMS private-key operations and signing code. Functions enabled by this + * option are experimental, and should not be used in production. + * + * Requires: MBEDTLS_LMS_C + * + * Uncomment to enable the LMS signature algorithm and private key operations. + */ +//#define MBEDTLS_LMS_PRIVATE + +/** + * \def MBEDTLS_NIST_KW_C + * + * Enable the Key Wrapping mode for 128-bit block ciphers, + * as defined in NIST SP 800-38F. Only KW and KWP modes + * are supported. At the moment, only AES is approved by NIST. + * + * Module: library/nist_kw.c + * + * Requires: MBEDTLS_AES_C and MBEDTLS_CIPHER_C + */ +#define MBEDTLS_NIST_KW_C + +/** + * \def MBEDTLS_MD_C + * + * Enable the generic layer for message digest (hashing) and HMAC. + * + * Requires: one of: MBEDTLS_MD5_C, MBEDTLS_RIPEMD160_C, MBEDTLS_SHA1_C, + * MBEDTLS_SHA224_C, MBEDTLS_SHA256_C, MBEDTLS_SHA384_C, + * MBEDTLS_SHA512_C. + * Module: library/md.c + * Caller: library/constant_time.c + * library/ecdsa.c + * library/ecjpake.c + * library/hkdf.c + * library/hmac_drbg.c + * library/pk.c + * library/pkcs5.c + * library/pkcs12.c + * library/psa_crypto_ecp.c + * library/psa_crypto_rsa.c + * library/rsa.c + * library/ssl_cookie.c + * library/ssl_msg.c + * library/ssl_tls.c + * library/x509.c + * library/x509_crt.c + * library/x509write_crt.c + * library/x509write_csr.c + * + * Uncomment to enable generic message digest wrappers. + */ +#define MBEDTLS_MD_C + +/** + * \def MBEDTLS_MD5_C + * + * Enable the MD5 hash algorithm. + * + * Module: library/md5.c + * Caller: library/md.c + * library/pem.c + * library/ssl_tls.c + * + * This module is required for TLS 1.2 depending on the handshake parameters. + * Further, it is used for checking MD5-signed certificates, and for PBKDF1 + * when decrypting PEM-encoded encrypted keys. + * + * \warning MD5 is considered a weak message digest and its use constitutes a + * security risk. If possible, we recommend avoiding dependencies on + * it, and considering stronger message digests instead. + * + */ +#define MBEDTLS_MD5_C + +/** + * \def MBEDTLS_MEMORY_BUFFER_ALLOC_C + * + * Enable the buffer allocator implementation that makes use of a (stack) + * based buffer to 'allocate' dynamic memory. (replaces calloc() and free() + * calls) + * + * Module: library/memory_buffer_alloc.c + * + * Requires: MBEDTLS_PLATFORM_C + * MBEDTLS_PLATFORM_MEMORY (to use it within mbed TLS) + * + * Enable this module to enable the buffer memory allocator. + */ +//#define MBEDTLS_MEMORY_BUFFER_ALLOC_C + +/** + * \def MBEDTLS_NET_C + * + * Enable the TCP and UDP over IPv6/IPv4 networking routines. + * + * \note This module only works on POSIX/Unix (including Linux, BSD and OS X) + * and Windows. For other platforms, you'll want to disable it, and write your + * own networking callbacks to be passed to \c mbedtls_ssl_set_bio(). + * + * \note See also our Knowledge Base article about porting to a new + * environment: + * https://mbed-tls.readthedocs.io/en/latest/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS + * + * Module: library/net_sockets.c + * + * This module provides networking routines. + */ +//#define MBEDTLS_NET_C + +/** + * \def MBEDTLS_OID_C + * + * Enable the OID database. + * + * Module: library/oid.c + * Caller: library/asn1write.c + * library/pkcs5.c + * library/pkparse.c + * library/pkwrite.c + * library/rsa.c + * library/x509.c + * library/x509_create.c + * library/x509_crl.c + * library/x509_crt.c + * library/x509_csr.c + * library/x509write_crt.c + * library/x509write_csr.c + * + * This modules translates between OIDs and internal values. + */ +#define MBEDTLS_OID_C + +/** + * \def MBEDTLS_PADLOCK_C + * + * Enable VIA Padlock support on x86. + * + * Module: library/padlock.c + * Caller: library/aes.c + * + * Requires: MBEDTLS_HAVE_ASM + * + * This modules adds support for the VIA PadLock on x86. + */ +#define MBEDTLS_PADLOCK_C + +/** + * \def MBEDTLS_PEM_PARSE_C + * + * Enable PEM decoding / parsing. + * + * Module: library/pem.c + * Caller: library/dhm.c + * library/pkparse.c + * library/x509_crl.c + * library/x509_crt.c + * library/x509_csr.c + * + * Requires: MBEDTLS_BASE64_C + * + * This modules adds support for decoding / parsing PEM files. + */ +#define MBEDTLS_PEM_PARSE_C + +/** + * \def MBEDTLS_PEM_WRITE_C + * + * Enable PEM encoding / writing. + * + * Module: library/pem.c + * Caller: library/pkwrite.c + * library/x509write_crt.c + * library/x509write_csr.c + * + * Requires: MBEDTLS_BASE64_C + * + * This modules adds support for encoding / writing PEM files. + */ +#define MBEDTLS_PEM_WRITE_C + +/** + * \def MBEDTLS_PK_C + * + * Enable the generic public (asymmetric) key layer. + * + * Module: library/pk.c + * Caller: library/psa_crypto_rsa.c + * library/ssl_tls.c + * library/ssl*_client.c + * library/ssl*_server.c + * library/x509.c + * + * Requires: MBEDTLS_MD_C, MBEDTLS_RSA_C or MBEDTLS_ECP_C + * + * Uncomment to enable generic public key wrappers. + */ +#define MBEDTLS_PK_C + +/** + * \def MBEDTLS_PK_PARSE_C + * + * Enable the generic public (asymmetric) key parser. + * + * Module: library/pkparse.c + * Caller: library/x509_crt.c + * library/x509_csr.c + * + * Requires: MBEDTLS_PK_C + * + * Uncomment to enable generic public key parse functions. + */ +#define MBEDTLS_PK_PARSE_C + +/** + * \def MBEDTLS_PK_WRITE_C + * + * Enable the generic public (asymmetric) key writer. + * + * Module: library/pkwrite.c + * Caller: library/x509write.c + * + * Requires: MBEDTLS_PK_C + * + * Uncomment to enable generic public key write functions. + */ +#define MBEDTLS_PK_WRITE_C + +/** + * \def MBEDTLS_PKCS5_C + * + * Enable PKCS#5 functions. + * + * Module: library/pkcs5.c + * + * Requires: MBEDTLS_CIPHER_C and either MBEDTLS_MD_C or MBEDTLS_PSA_CRYPTO_C. + * + * \warning If building without MBEDTLS_MD_C, you must call psa_crypto_init() + * before doing any PKCS5 operation. + * + * \warning When building with MBEDTLS_MD_C, all hashes used with this + * need to be available as built-ins (that is, for SHA-256, MBEDTLS_SHA256_C, + * etc.) as opposed to just PSA drivers. So far, PSA drivers are only used by + * this module in builds where MBEDTLS_MD_C is disabled. + * + * This module adds support for the PKCS#5 functions. + */ +#define MBEDTLS_PKCS5_C + +/** + * \def MBEDTLS_PKCS7_C + * + * Enable PKCS #7 core for using PKCS #7-formatted signatures. + * RFC Link - https://tools.ietf.org/html/rfc2315 + * + * Module: library/pkcs7.c + * + * Requires: MBEDTLS_ASN1_PARSE_C, MBEDTLS_OID_C, MBEDTLS_PK_PARSE_C, + * MBEDTLS_X509_CRT_PARSE_C MBEDTLS_X509_CRL_PARSE_C, + * MBEDTLS_BIGNUM_C, MBEDTLS_MD_C + * + * This module is required for the PKCS #7 parsing modules. + */ +#define MBEDTLS_PKCS7_C + +/** + * \def MBEDTLS_PKCS12_C + * + * Enable PKCS#12 PBE functions. + * Adds algorithms for parsing PKCS#8 encrypted private keys + * + * Module: library/pkcs12.c + * Caller: library/pkparse.c + * + * Requires: MBEDTLS_ASN1_PARSE_C, MBEDTLS_CIPHER_C and either + * MBEDTLS_MD_C or MBEDTLS_PSA_CRYPTO_C. + * + * \warning If building without MBEDTLS_MD_C, you must call psa_crypto_init() + * before doing any PKCS12 operation. + * + * \warning When building with MBEDTLS_MD_C, all hashes used with this + * need to be available as built-ins (that is, for SHA-256, MBEDTLS_SHA256_C, + * etc.) as opposed to just PSA drivers. So far, PSA drivers are only used by + * this module in builds where MBEDTLS_MD_C is disabled. + * + * This module enables PKCS#12 functions. + */ +#define MBEDTLS_PKCS12_C + +/** + * \def MBEDTLS_PLATFORM_C + * + * Enable the platform abstraction layer that allows you to re-assign + * functions like calloc(), free(), snprintf(), printf(), fprintf(), exit(). + * + * Enabling MBEDTLS_PLATFORM_C enables to use of MBEDTLS_PLATFORM_XXX_ALT + * or MBEDTLS_PLATFORM_XXX_MACRO directives, allowing the functions mentioned + * above to be specified at runtime or compile time respectively. + * + * \note This abstraction layer must be enabled on Windows (including MSYS2) + * as other modules rely on it for a fixed snprintf implementation. + * + * Module: library/platform.c + * Caller: Most other .c files + * + * This module enables abstraction of common (libc) functions. + */ +#define MBEDTLS_PLATFORM_C + +/** + * \def MBEDTLS_POLY1305_C + * + * Enable the Poly1305 MAC algorithm. + * + * Module: library/poly1305.c + * Caller: library/chachapoly.c + */ +#define MBEDTLS_POLY1305_C + +/** + * \def MBEDTLS_PSA_CRYPTO_C + * + * Enable the Platform Security Architecture cryptography API. + * + * Module: library/psa_crypto.c + * + * Requires: MBEDTLS_CIPHER_C, + * either MBEDTLS_CTR_DRBG_C and MBEDTLS_ENTROPY_C, + * or MBEDTLS_HMAC_DRBG_C and MBEDTLS_ENTROPY_C, + * or MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG. + * + */ +#define MBEDTLS_PSA_CRYPTO_C + +/** + * \def MBEDTLS_PSA_CRYPTO_SE_C + * + * Enable dynamic secure element support in the Platform Security Architecture + * cryptography API. + * + * \deprecated This feature is deprecated. Please switch to the driver + * interface enabled by #MBEDTLS_PSA_CRYPTO_DRIVERS. + * + * Module: library/psa_crypto_se.c + * + * Requires: MBEDTLS_PSA_CRYPTO_C, MBEDTLS_PSA_CRYPTO_STORAGE_C + * + */ +//#define MBEDTLS_PSA_CRYPTO_SE_C + +/** + * \def MBEDTLS_PSA_CRYPTO_STORAGE_C + * + * Enable the Platform Security Architecture persistent key storage. + * + * Module: library/psa_crypto_storage.c + * + * Requires: MBEDTLS_PSA_CRYPTO_C, + * either MBEDTLS_PSA_ITS_FILE_C or a native implementation of + * the PSA ITS interface + */ +//#define MBEDTLS_PSA_CRYPTO_STORAGE_C + +/** + * \def MBEDTLS_PSA_ITS_FILE_C + * + * Enable the emulation of the Platform Security Architecture + * Internal Trusted Storage (PSA ITS) over files. + * + * Module: library/psa_its_file.c + * + * Requires: MBEDTLS_FS_IO + */ +//#define MBEDTLS_PSA_ITS_FILE_C + +/** + * \def MBEDTLS_RIPEMD160_C + * + * Enable the RIPEMD-160 hash algorithm. + * + * Module: library/ripemd160.c + * Caller: library/md.c + * + */ +#define MBEDTLS_RIPEMD160_C + +/** + * \def MBEDTLS_RSA_C + * + * Enable the RSA public-key cryptosystem. + * + * Module: library/rsa.c + * library/rsa_alt_helpers.c + * Caller: library/pk.c + * library/psa_crypto.c + * library/ssl_tls.c + * library/ssl*_client.c + * library/ssl*_server.c + * + * This module is used by the following key exchanges: + * RSA, DHE-RSA, ECDHE-RSA, RSA-PSK + * + * Requires: MBEDTLS_BIGNUM_C, MBEDTLS_OID_C + */ +#define MBEDTLS_RSA_C + +/** + * \def MBEDTLS_SHA1_C + * + * Enable the SHA1 cryptographic hash algorithm. + * + * Module: library/sha1.c + * Caller: library/md.c + * library/psa_crypto_hash.c + * + * This module is required for TLS 1.2 depending on the handshake parameters, + * and for SHA1-signed certificates. + * + * \warning SHA-1 is considered a weak message digest and its use constitutes + * a security risk. If possible, we recommend avoiding dependencies + * on it, and considering stronger message digests instead. + * + */ +#define MBEDTLS_SHA1_C + +/** + * \def MBEDTLS_SHA224_C + * + * Enable the SHA-224 cryptographic hash algorithm. + * + * Module: library/sha256.c + * Caller: library/md.c + * library/ssl_cookie.c + * + * This module adds support for SHA-224. + */ +#define MBEDTLS_SHA224_C + +/** + * \def MBEDTLS_SHA256_C + * + * Enable the SHA-256 cryptographic hash algorithm. + * + * Module: library/sha256.c + * Caller: library/entropy.c + * library/md.c + * library/ssl_tls.c + * library/ssl*_client.c + * library/ssl*_server.c + * + * This module adds support for SHA-256. + * This module is required for the SSL/TLS 1.2 PRF function. + */ +#define MBEDTLS_SHA256_C + +/** + * \def MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT + * + * Enable acceleration of the SHA-256 and SHA-224 cryptographic hash algorithms + * with the ARMv8 cryptographic extensions if they are available at runtime. + * If not, the library will fall back to the C implementation. + * + * \note If MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT is defined when building + * for a non-Aarch64 build it will be silently ignored. + * + * \warning MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT cannot be defined at the + * same time as MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY. + * + * Requires: MBEDTLS_SHA256_C. + * + * Module: library/sha256.c + * + * Uncomment to have the library check for the A64 SHA-256 crypto extensions + * and use them if available. + */ +//#define MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT + +/** + * \def MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY + * + * Enable acceleration of the SHA-256 and SHA-224 cryptographic hash algorithms + * with the ARMv8 cryptographic extensions, which must be available at runtime + * or else an illegal instruction fault will occur. + * + * \note This allows builds with a smaller code size than with + * MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT + * + * \warning MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY cannot be defined at the same + * time as MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT. + * + * Requires: MBEDTLS_SHA256_C. + * + * Module: library/sha256.c + * + * Uncomment to have the library use the A64 SHA-256 crypto extensions + * unconditionally. + */ +//#define MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY + +/** + * \def MBEDTLS_SHA384_C + * + * Enable the SHA-384 cryptographic hash algorithm. + * + * Module: library/sha512.c + * Caller: library/md.c + * library/psa_crypto_hash.c + * library/ssl_tls.c + * library/ssl*_client.c + * library/ssl*_server.c + * + * Comment to disable SHA-384 + */ +#define MBEDTLS_SHA384_C + +/** + * \def MBEDTLS_SHA512_C + * + * Enable SHA-512 cryptographic hash algorithms. + * + * Module: library/sha512.c + * Caller: library/entropy.c + * library/md.c + * library/ssl_tls.c + * library/ssl_cookie.c + * + * This module adds support for SHA-512. + */ +#define MBEDTLS_SHA512_C + +/** + * \def MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT + * + * Enable acceleration of the SHA-512 and SHA-384 cryptographic hash algorithms + * with the ARMv8 cryptographic extensions if they are available at runtime. + * If not, the library will fall back to the C implementation. + * + * \note If MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT is defined when building + * for a non-Aarch64 build it will be silently ignored. + * + * \note The code uses the SHA-512 Neon intrinsics, so requires GCC >= 8 or + * Clang >= 7. + * + * \warning MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT cannot be defined at the + * same time as MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY. + * + * Requires: MBEDTLS_SHA512_C. + * + * Module: library/sha512.c + * + * Uncomment to have the library check for the A64 SHA-512 crypto extensions + * and use them if available. + */ +//#define MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT + +/** + * \def MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY + * + * Enable acceleration of the SHA-512 and SHA-384 cryptographic hash algorithms + * with the ARMv8 cryptographic extensions, which must be available at runtime + * or else an illegal instruction fault will occur. + * + * \note This allows builds with a smaller code size than with + * MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT + * + * \note The code uses the SHA-512 Neon intrinsics, so requires GCC >= 8 or + * Clang >= 7. + * + * \warning MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY cannot be defined at the same + * time as MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT. + * + * Requires: MBEDTLS_SHA512_C. + * + * Module: library/sha512.c + * + * Uncomment to have the library use the A64 SHA-512 crypto extensions + * unconditionally. + */ +//#define MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY + +/** + * \def MBEDTLS_SSL_CACHE_C + * + * Enable simple SSL cache implementation. + * + * Module: library/ssl_cache.c + * Caller: + * + * Requires: MBEDTLS_SSL_CACHE_C + */ +#define MBEDTLS_SSL_CACHE_C + +/** + * \def MBEDTLS_SSL_COOKIE_C + * + * Enable basic implementation of DTLS cookies for hello verification. + * + * Module: library/ssl_cookie.c + * Caller: + */ +#define MBEDTLS_SSL_COOKIE_C + +/** + * \def MBEDTLS_SSL_TICKET_C + * + * Enable an implementation of TLS server-side callbacks for session tickets. + * + * Module: library/ssl_ticket.c + * Caller: + * + * Requires: (MBEDTLS_CIPHER_C || MBEDTLS_USE_PSA_CRYPTO) && + * (MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C) + */ +#define MBEDTLS_SSL_TICKET_C + +/** + * \def MBEDTLS_SSL_CLI_C + * + * Enable the SSL/TLS client code. + * + * Module: library/ssl*_client.c + * Caller: + * + * Requires: MBEDTLS_SSL_TLS_C + * + * This module is required for SSL/TLS client support. + */ +#define MBEDTLS_SSL_CLI_C + +/** + * \def MBEDTLS_SSL_SRV_C + * + * Enable the SSL/TLS server code. + * + * Module: library/ssl*_server.c + * Caller: + * + * Requires: MBEDTLS_SSL_TLS_C + * + * This module is required for SSL/TLS server support. + */ +#define MBEDTLS_SSL_SRV_C + +/** + * \def MBEDTLS_SSL_TLS_C + * + * Enable the generic SSL/TLS code. + * + * Module: library/ssl_tls.c + * Caller: library/ssl*_client.c + * library/ssl*_server.c + * + * Requires: MBEDTLS_CIPHER_C, MBEDTLS_MD_C + * and at least one of the MBEDTLS_SSL_PROTO_XXX defines + * + * This module is required for SSL/TLS. + */ +#define MBEDTLS_SSL_TLS_C + +/** + * \def MBEDTLS_THREADING_C + * + * Enable the threading abstraction layer. + * By default mbed TLS assumes it is used in a non-threaded environment or that + * contexts are not shared between threads. If you do intend to use contexts + * between threads, you will need to enable this layer to prevent race + * conditions. See also our Knowledge Base article about threading: + * https://mbed-tls.readthedocs.io/en/latest/kb/development/thread-safety-and-multi-threading + * + * Module: library/threading.c + * + * This allows different threading implementations (self-implemented or + * provided). + * + * You will have to enable either MBEDTLS_THREADING_ALT or + * MBEDTLS_THREADING_PTHREAD. + * + * Enable this layer to allow use of mutexes within mbed TLS + */ +//#define MBEDTLS_THREADING_C + +/** + * \def MBEDTLS_TIMING_C + * + * Enable the semi-portable timing interface. + * + * \note The provided implementation only works on POSIX/Unix (including Linux, + * BSD and OS X) and Windows. On other platforms, you can either disable that + * module and provide your own implementations of the callbacks needed by + * \c mbedtls_ssl_set_timer_cb() for DTLS, or leave it enabled and provide + * your own implementation of the whole module by setting + * \c MBEDTLS_TIMING_ALT in the current file. + * + * \note The timing module will include time.h on suitable platforms + * regardless of the setting of MBEDTLS_HAVE_TIME, unless + * MBEDTLS_TIMING_ALT is used. See timing.c for more information. + * + * \note See also our Knowledge Base article about porting to a new + * environment: + * https://mbed-tls.readthedocs.io/en/latest/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS + * + * Module: library/timing.c + */ +//#define MBEDTLS_TIMING_C + +/** + * \def MBEDTLS_VERSION_C + * + * Enable run-time version information. + * + * Module: library/version.c + * + * This module provides run-time version information. + */ +#define MBEDTLS_VERSION_C + +/** + * \def MBEDTLS_X509_USE_C + * + * Enable X.509 core for using certificates. + * + * Module: library/x509.c + * Caller: library/x509_crl.c + * library/x509_crt.c + * library/x509_csr.c + * + * Requires: MBEDTLS_ASN1_PARSE_C, MBEDTLS_BIGNUM_C, MBEDTLS_OID_C, MBEDTLS_PK_PARSE_C, + * (MBEDTLS_MD_C or MBEDTLS_USE_PSA_CRYPTO) + * + * \warning If building with MBEDTLS_USE_PSA_CRYPTO, you must call + * psa_crypto_init() before doing any X.509 operation. + * + * This module is required for the X.509 parsing modules. + */ +#define MBEDTLS_X509_USE_C + +/** + * \def MBEDTLS_X509_CRT_PARSE_C + * + * Enable X.509 certificate parsing. + * + * Module: library/x509_crt.c + * Caller: library/ssl_tls.c + * library/ssl*_client.c + * library/ssl*_server.c + * + * Requires: MBEDTLS_X509_USE_C + * + * This module is required for X.509 certificate parsing. + */ +#define MBEDTLS_X509_CRT_PARSE_C + +/** + * \def MBEDTLS_X509_CRL_PARSE_C + * + * Enable X.509 CRL parsing. + * + * Module: library/x509_crl.c + * Caller: library/x509_crt.c + * + * Requires: MBEDTLS_X509_USE_C + * + * This module is required for X.509 CRL parsing. + */ +#define MBEDTLS_X509_CRL_PARSE_C + +/** + * \def MBEDTLS_X509_CSR_PARSE_C + * + * Enable X.509 Certificate Signing Request (CSR) parsing. + * + * Module: library/x509_csr.c + * Caller: library/x509_crt_write.c + * + * Requires: MBEDTLS_X509_USE_C + * + * This module is used for reading X.509 certificate request. + */ +#define MBEDTLS_X509_CSR_PARSE_C + +/** + * \def MBEDTLS_X509_CREATE_C + * + * Enable X.509 core for creating certificates. + * + * Module: library/x509_create.c + * + * Requires: MBEDTLS_BIGNUM_C, MBEDTLS_OID_C, MBEDTLS_PK_PARSE_C, + * (MBEDTLS_MD_C or MBEDTLS_USE_PSA_CRYPTO) + * + * \warning If building with MBEDTLS_USE_PSA_CRYPTO, you must call + * psa_crypto_init() before doing any X.509 create operation. + * + * This module is the basis for creating X.509 certificates and CSRs. + */ +#define MBEDTLS_X509_CREATE_C + +/** + * \def MBEDTLS_X509_CRT_WRITE_C + * + * Enable creating X.509 certificates. + * + * Module: library/x509_crt_write.c + * + * Requires: MBEDTLS_X509_CREATE_C + * + * This module is required for X.509 certificate creation. + */ +#define MBEDTLS_X509_CRT_WRITE_C + +/** + * \def MBEDTLS_X509_CSR_WRITE_C + * + * Enable creating X.509 Certificate Signing Requests (CSR). + * + * Module: library/x509_csr_write.c + * + * Requires: MBEDTLS_X509_CREATE_C + * + * This module is required for X.509 certificate request writing. + */ +#define MBEDTLS_X509_CSR_WRITE_C + +/** \} name SECTION: mbed TLS modules */ + +/** + * \name SECTION: General configuration options + * + * This section contains Mbed TLS build settings that are not associated + * with a particular module. + * + * \{ + */ + +/** + * \def MBEDTLS_CONFIG_FILE + * + * If defined, this is a header which will be included instead of + * `"mbedtls/mbedtls_config.h"`. + * This header file specifies the compile-time configuration of Mbed TLS. + * Unlike other configuration options, this one must be defined on the + * compiler command line: a definition in `mbedtls_config.h` would have + * no effect. + * + * This macro is expanded after an \#include directive. This is a popular but + * non-standard feature of the C language, so this feature is only available + * with compilers that perform macro expansion on an \#include line. + * + * The value of this symbol is typically a path in double quotes, either + * absolute or relative to a directory on the include search path. + */ +//#define MBEDTLS_CONFIG_FILE "mbedtls/mbedtls_config.h" + +/** + * \def MBEDTLS_USER_CONFIG_FILE + * + * If defined, this is a header which will be included after + * `"mbedtls/mbedtls_config.h"` or #MBEDTLS_CONFIG_FILE. + * This allows you to modify the default configuration, including the ability + * to undefine options that are enabled by default. + * + * This macro is expanded after an \#include directive. This is a popular but + * non-standard feature of the C language, so this feature is only available + * with compilers that perform macro expansion on an \#include line. + * + * The value of this symbol is typically a path in double quotes, either + * absolute or relative to a directory on the include search path. + */ +//#define MBEDTLS_USER_CONFIG_FILE "/dev/null" + +/** + * \def MBEDTLS_PSA_CRYPTO_CONFIG_FILE + * + * If defined, this is a header which will be included instead of + * `"psa/crypto_config.h"`. + * This header file specifies which cryptographic mechanisms are available + * through the PSA API when #MBEDTLS_PSA_CRYPTO_CONFIG is enabled, and + * is not used when #MBEDTLS_PSA_CRYPTO_CONFIG is disabled. + * + * This macro is expanded after an \#include directive. This is a popular but + * non-standard feature of the C language, so this feature is only available + * with compilers that perform macro expansion on an \#include line. + * + * The value of this symbol is typically a path in double quotes, either + * absolute or relative to a directory on the include search path. + */ +//#define MBEDTLS_PSA_CRYPTO_CONFIG_FILE "psa/crypto_config.h" + +/** + * \def MBEDTLS_PSA_CRYPTO_USER_CONFIG_FILE + * + * If defined, this is a header which will be included after + * `"psa/crypto_config.h"` or #MBEDTLS_PSA_CRYPTO_CONFIG_FILE. + * This allows you to modify the default configuration, including the ability + * to undefine options that are enabled by default. + * + * This macro is expanded after an \#include directive. This is a popular but + * non-standard feature of the C language, so this feature is only available + * with compilers that perform macro expansion on an \#include line. + * + * The value of this symbol is typically a path in double quotes, either + * absolute or relative to a directory on the include search path. + */ +//#define MBEDTLS_PSA_CRYPTO_USER_CONFIG_FILE "/dev/null" + +/** + * \def MBEDTLS_PSA_CRYPTO_PLATFORM_FILE + * + * If defined, this is a header which will be included instead of + * `"psa/crypto_platform.h"`. This file should declare the same identifiers + * as the one in Mbed TLS, but with definitions adapted to the platform on + * which the library code will run. + * + * \note The required content of this header can vary from one version of + * Mbed TLS to the next. Integrators who provide an alternative file + * should review the changes in the original file whenever they + * upgrade Mbed TLS. + * + * This macro is expanded after an \#include directive. This is a popular but + * non-standard feature of the C language, so this feature is only available + * with compilers that perform macro expansion on an \#include line. + * + * The value of this symbol is typically a path in double quotes, either + * absolute or relative to a directory on the include search path. + */ +//#define MBEDTLS_PSA_CRYPTO_PLATFORM_FILE "psa/crypto_platform_alt.h" + +/** + * \def MBEDTLS_PSA_CRYPTO_STRUCT_FILE + * + * If defined, this is a header which will be included instead of + * `"psa/crypto_struct.h"`. This file should declare the same identifiers + * as the one in Mbed TLS, but with definitions adapted to the environment + * in which the library code will run. The typical use for this feature + * is to provide alternative type definitions on the client side in + * client-server integrations of PSA crypto, where operation structures + * contain handles instead of cryptographic data. + * + * \note The required content of this header can vary from one version of + * Mbed TLS to the next. Integrators who provide an alternative file + * should review the changes in the original file whenever they + * upgrade Mbed TLS. + * + * This macro is expanded after an \#include directive. This is a popular but + * non-standard feature of the C language, so this feature is only available + * with compilers that perform macro expansion on an \#include line. + * + * The value of this symbol is typically a path in double quotes, either + * absolute or relative to a directory on the include search path. + */ +//#define MBEDTLS_PSA_CRYPTO_STRUCT_FILE "psa/crypto_struct_alt.h" + +/** \} name SECTION: General configuration options */ + +/** + * \name SECTION: Module configuration options + * + * This section allows for the setting of module specific sizes and + * configuration options. The default values are already present in the + * relevant header files and should suffice for the regular use cases. + * + * Our advice is to enable options and change their values here + * only if you have a good reason and know the consequences. + * \{ + */ +/* The Doxygen documentation here is used when a user comments out a + * setting and runs doxygen themselves. On the other hand, when we typeset + * the full documentation including disabled settings, the documentation + * in specific modules' header files is used if present. When editing this + * file, make sure that each option is documented in exactly one place, + * plus optionally a same-line Doxygen comment here if there is a Doxygen + * comment in the specific module. */ + +/* MPI / BIGNUM options */ +//#define MBEDTLS_MPI_WINDOW_SIZE 2 /**< Maximum window size used. */ +//#define MBEDTLS_MPI_MAX_SIZE 1024 /**< Maximum number of bytes for usable MPIs. */ + +/* CTR_DRBG options */ +//#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 48 /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with SHA-256) */ +//#define MBEDTLS_CTR_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */ +//#define MBEDTLS_CTR_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */ +//#define MBEDTLS_CTR_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */ +//#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */ + +/* HMAC_DRBG options */ +//#define MBEDTLS_HMAC_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */ +//#define MBEDTLS_HMAC_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */ +//#define MBEDTLS_HMAC_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */ +//#define MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */ + +/* ECP options */ +//#define MBEDTLS_ECP_WINDOW_SIZE 4 /**< Maximum window size used */ +//#define MBEDTLS_ECP_FIXED_POINT_OPTIM 1 /**< Enable fixed-point speed-up */ + +/* Entropy options */ +//#define MBEDTLS_ENTROPY_MAX_SOURCES 20 /**< Maximum number of sources supported */ +//#define MBEDTLS_ENTROPY_MAX_GATHER 128 /**< Maximum amount requested from entropy sources */ +//#define MBEDTLS_ENTROPY_MIN_HARDWARE 32 /**< Default minimum number of bytes required for the hardware entropy source mbedtls_hardware_poll() before entropy is released */ + +/* Memory buffer allocator options */ +//#define MBEDTLS_MEMORY_ALIGN_MULTIPLE 4 /**< Align on multiples of this value */ + +/* Platform options */ +//#define MBEDTLS_PLATFORM_STD_MEM_HDR /**< Header to include if MBEDTLS_PLATFORM_NO_STD_FUNCTIONS is defined. Don't define if no header is needed. */ +//#define MBEDTLS_PLATFORM_STD_CALLOC calloc /**< Default allocator to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_FREE free /**< Default free to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_SETBUF setbuf /**< Default setbuf to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_EXIT exit /**< Default exit to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_TIME time /**< Default time to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */ +//#define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< Default fprintf to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_PRINTF printf /**< Default printf to use, can be undefined */ +/* Note: your snprintf must correctly zero-terminate the buffer! */ +//#define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf /**< Default snprintf to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS 0 /**< Default exit value to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_EXIT_FAILURE 1 /**< Default exit value to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_NV_SEED_READ mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_NV_SEED_WRITE mbedtls_platform_std_nv_seed_write /**< Default nv_seed_write function to use, can be undefined */ +//#define MBEDTLS_PLATFORM_STD_NV_SEED_FILE "seedfile" /**< Seed file to read/write with default implementation */ + +/* To Use Function Macros MBEDTLS_PLATFORM_C must be enabled */ +/* MBEDTLS_PLATFORM_XXX_MACRO and MBEDTLS_PLATFORM_XXX_ALT cannot both be defined */ +//#define MBEDTLS_PLATFORM_CALLOC_MACRO calloc /**< Default allocator macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_FREE_MACRO free /**< Default free macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_EXIT_MACRO exit /**< Default exit macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_SETBUF_MACRO setbuf /**< Default setbuf macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_TIME_MACRO time /**< Default time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */ +//#define MBEDTLS_PLATFORM_TIME_TYPE_MACRO time_t /**< Default time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */ +//#define MBEDTLS_PLATFORM_FPRINTF_MACRO fprintf /**< Default fprintf macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_PRINTF_MACRO printf /**< Default printf macro to use, can be undefined */ +/* Note: your snprintf must correctly zero-terminate the buffer! */ +//#define MBEDTLS_PLATFORM_SNPRINTF_MACRO snprintf /**< Default snprintf macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_VSNPRINTF_MACRO vsnprintf /**< Default vsnprintf macro to use, can be undefined */ +//#define MBEDTLS_PLATFORM_NV_SEED_READ_MACRO mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to use, can be undefined */ +//#define MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO mbedtls_platform_std_nv_seed_write /**< Default nv_seed_write function to use, can be undefined */ + +/** \def MBEDTLS_CHECK_RETURN + * + * This macro is used at the beginning of the declaration of a function + * to indicate that its return value should be checked. It should + * instruct the compiler to emit a warning or an error if the function + * is called without checking its return value. + * + * There is a default implementation for popular compilers in platform_util.h. + * You can override the default implementation by defining your own here. + * + * If the implementation here is empty, this will effectively disable the + * checking of functions' return values. + */ +//#define MBEDTLS_CHECK_RETURN __attribute__((__warn_unused_result__)) + +/** \def MBEDTLS_IGNORE_RETURN + * + * This macro requires one argument, which should be a C function call. + * If that function call would cause a #MBEDTLS_CHECK_RETURN warning, this + * warning is suppressed. + */ +//#define MBEDTLS_IGNORE_RETURN( result ) ((void) !(result)) + +/* PSA options */ +/** + * Use HMAC_DRBG with the specified hash algorithm for HMAC_DRBG for the + * PSA crypto subsystem. + * + * If this option is unset: + * - If CTR_DRBG is available, the PSA subsystem uses it rather than HMAC_DRBG. + * - Otherwise, the PSA subsystem uses HMAC_DRBG with either + * #MBEDTLS_MD_SHA512 or #MBEDTLS_MD_SHA256 based on availability and + * on unspecified heuristics. + */ +//#define MBEDTLS_PSA_HMAC_DRBG_MD_TYPE MBEDTLS_MD_SHA256 + +/** \def MBEDTLS_PSA_KEY_SLOT_COUNT + * Restrict the PSA library to supporting a maximum amount of simultaneously + * loaded keys. A loaded key is a key stored by the PSA Crypto core as a + * volatile key, or a persistent key which is loaded temporarily by the + * library as part of a crypto operation in flight. + * + * If this option is unset, the library will fall back to a default value of + * 32 keys. + */ +//#define MBEDTLS_PSA_KEY_SLOT_COUNT 32 + +/* SSL Cache options */ +//#define MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT 86400 /**< 1 day */ +//#define MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES 50 /**< Maximum entries in cache */ + +/* SSL options */ + +/** \def MBEDTLS_SSL_IN_CONTENT_LEN + * + * Maximum length (in bytes) of incoming plaintext fragments. + * + * This determines the size of the incoming TLS I/O buffer in such a way + * that it is capable of holding the specified amount of plaintext data, + * regardless of the protection mechanism used. + * + * \note When using a value less than the default of 16KB on the client, it is + * recommended to use the Maximum Fragment Length (MFL) extension to + * inform the server about this limitation. On the server, there + * is no supported, standardized way of informing the client about + * restriction on the maximum size of incoming messages, and unless + * the limitation has been communicated by other means, it is recommended + * to only change the outgoing buffer size #MBEDTLS_SSL_OUT_CONTENT_LEN + * while keeping the default value of 16KB for the incoming buffer. + * + * Uncomment to set the maximum plaintext size of the incoming I/O buffer. + */ +//#define MBEDTLS_SSL_IN_CONTENT_LEN 16384 + +/** \def MBEDTLS_SSL_CID_IN_LEN_MAX + * + * The maximum length of CIDs used for incoming DTLS messages. + * + */ +//#define MBEDTLS_SSL_CID_IN_LEN_MAX 32 + +/** \def MBEDTLS_SSL_CID_OUT_LEN_MAX + * + * The maximum length of CIDs used for outgoing DTLS messages. + * + */ +//#define MBEDTLS_SSL_CID_OUT_LEN_MAX 32 + +/** \def MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY + * + * This option controls the use of record plaintext padding + * in TLS 1.3 and when using the Connection ID extension in DTLS 1.2. + * + * The padding will always be chosen so that the length of the + * padded plaintext is a multiple of the value of this option. + * + * Note: A value of \c 1 means that no padding will be used + * for outgoing records. + * + * Note: On systems lacking division instructions, + * a power of two should be preferred. + */ +//#define MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY 16 + +/** \def MBEDTLS_SSL_OUT_CONTENT_LEN + * + * Maximum length (in bytes) of outgoing plaintext fragments. + * + * This determines the size of the outgoing TLS I/O buffer in such a way + * that it is capable of holding the specified amount of plaintext data, + * regardless of the protection mechanism used. + * + * It is possible to save RAM by setting a smaller outward buffer, while keeping + * the default inward 16384 byte buffer to conform to the TLS specification. + * + * The minimum required outward buffer size is determined by the handshake + * protocol's usage. Handshaking will fail if the outward buffer is too small. + * The specific size requirement depends on the configured ciphers and any + * certificate data which is sent during the handshake. + * + * Uncomment to set the maximum plaintext size of the outgoing I/O buffer. + */ +//#define MBEDTLS_SSL_OUT_CONTENT_LEN 16384 + +/** \def MBEDTLS_SSL_DTLS_MAX_BUFFERING + * + * Maximum number of heap-allocated bytes for the purpose of + * DTLS handshake message reassembly and future message buffering. + * + * This should be at least 9/8 * MBEDTLS_SSL_IN_CONTENT_LEN + * to account for a reassembled handshake message of maximum size, + * together with its reassembly bitmap. + * + * A value of 2 * MBEDTLS_SSL_IN_CONTENT_LEN (32768 by default) + * should be sufficient for all practical situations as it allows + * to reassembly a large handshake message (such as a certificate) + * while buffering multiple smaller handshake messages. + * + */ +//#define MBEDTLS_SSL_DTLS_MAX_BUFFERING 32768 + +//#define MBEDTLS_PSK_MAX_LEN 32 /**< Max size of TLS pre-shared keys, in bytes (default 256 or 384 bits) */ +//#define MBEDTLS_SSL_COOKIE_TIMEOUT 60 /**< Default expiration delay of DTLS cookies, in seconds if HAVE_TIME, or in number of cookies issued */ + +/** + * Complete list of ciphersuites to use, in order of preference. + * + * \warning No dependency checking is done on that field! This option can only + * be used to restrict the set of available ciphersuites. It is your + * responsibility to make sure the needed modules are active. + * + * Use this to save a few hundred bytes of ROM (default ordering of all + * available ciphersuites) and a few to a few hundred bytes of RAM. + * + * The value below is only an example, not the default. + */ +//#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 + +/** + * \def MBEDTLS_SSL_TLS1_3_TICKET_AGE_TOLERANCE + * + * Maximum time difference in milliseconds tolerated between the age of a + * ticket from the server and client point of view. + * From the client point of view, the age of a ticket is the time difference + * between the time when the client proposes to the server to use the ticket + * (time of writing of the Pre-Shared Key Extension including the ticket) and + * the time the client received the ticket from the server. + * From the server point of view, the age of a ticket is the time difference + * between the time when the server receives a proposition from the client + * to use the ticket and the time when the ticket was created by the server. + * The server age is expected to be always greater than the client one and + * MBEDTLS_SSL_TLS1_3_TICKET_AGE_TOLERANCE defines the + * maximum difference tolerated for the server to accept the ticket. + * This is not used in TLS 1.2. + * + */ +#define MBEDTLS_SSL_TLS1_3_TICKET_AGE_TOLERANCE 6000 + +/** + * \def MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH + * + * Size in bytes of a ticket nonce. This is not used in TLS 1.2. + * + * This must be less than 256. + */ +#define MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH 32 + +/** + * \def MBEDTLS_SSL_TLS1_3_DEFAULT_NEW_SESSION_TICKETS + * + * Default number of NewSessionTicket messages to be sent by a TLS 1.3 server + * after handshake completion. This is not used in TLS 1.2 and relevant only if + * the MBEDTLS_SSL_SESSION_TICKETS option is enabled. + * + */ +#define MBEDTLS_SSL_TLS1_3_DEFAULT_NEW_SESSION_TICKETS 1 + +/* X509 options */ +//#define MBEDTLS_X509_MAX_INTERMEDIATE_CA 8 /**< Maximum number of intermediate CAs in a verification chain. */ +//#define MBEDTLS_X509_MAX_FILE_PATH_LEN 512 /**< Maximum length of a path/filename string in bytes including the null terminator character ('\0'). */ + +/** + * Uncomment the macro to let mbed TLS use your alternate implementation of + * mbedtls_platform_zeroize(). This replaces the default implementation in + * platform_util.c. + * + * mbedtls_platform_zeroize() is a widely used function across the library to + * zero a block of memory. The implementation is expected to be secure in the + * sense that it has been written to prevent the compiler from removing calls + * to mbedtls_platform_zeroize() as part of redundant code elimination + * optimizations. However, it is difficult to guarantee that calls to + * mbedtls_platform_zeroize() will not be optimized by the compiler as older + * versions of the C language standards do not provide a secure implementation + * of memset(). Therefore, MBEDTLS_PLATFORM_ZEROIZE_ALT enables users to + * configure their own implementation of mbedtls_platform_zeroize(), for + * example by using directives specific to their compiler, features from newer + * C standards (e.g using memset_s() in C11) or calling a secure memset() from + * their system (e.g explicit_bzero() in BSD). + */ +#define MBEDTLS_PLATFORM_ZEROIZE_ALT + +/** + * Uncomment the macro to let Mbed TLS use your alternate implementation of + * mbedtls_platform_gmtime_r(). This replaces the default implementation in + * platform_util.c. + * + * gmtime() is not a thread-safe function as defined in the C standard. The + * library will try to use safer implementations of this function, such as + * gmtime_r() when available. However, if Mbed TLS cannot identify the target + * system, the implementation of mbedtls_platform_gmtime_r() will default to + * using the standard gmtime(). In this case, calls from the library to + * gmtime() will be guarded by the global mutex mbedtls_threading_gmtime_mutex + * if MBEDTLS_THREADING_C is enabled. We recommend that calls from outside the + * library are also guarded with this mutex to avoid race conditions. However, + * if the macro MBEDTLS_PLATFORM_GMTIME_R_ALT is defined, Mbed TLS will + * unconditionally use the implementation for mbedtls_platform_gmtime_r() + * supplied at compile time. + */ +//#define MBEDTLS_PLATFORM_GMTIME_R_ALT + +/** + * Enable the verified implementations of ECDH primitives from Project Everest + * (currently only Curve25519). This feature changes the layout of ECDH + * contexts and therefore is a compatibility break for applications that access + * fields of a mbedtls_ecdh_context structure directly. See also + * MBEDTLS_ECDH_LEGACY_CONTEXT in include/mbedtls/ecdh.h. + */ +//#define MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED + +/** \} name SECTION: Module configuration options */ diff --git a/esp-mbedtls-sys/gen/toolchains/toolchain-clang-esp32.cmake b/esp-mbedtls-sys/gen/toolchains/toolchain-clang-esp32.cmake new file mode 100644 index 0000000..adb6755 --- /dev/null +++ b/esp-mbedtls-sys/gen/toolchains/toolchain-clang-esp32.cmake @@ -0,0 +1,23 @@ +set(CMAKE_SYSTEM_NAME Generic) + +# Install with `espup install --extended-llvm` +set(CMAKE_C_COMPILER "$ENV{CLANG_PATH}") + +set(CLANG_DIR_PATH "${CMAKE_C_COMPILER}") +cmake_path(REMOVE_FILENAME CLANG_DIR_PATH) + +set(CMAKE_AR "${CLANG_DIR_PATH}/llvm-ar") +set(CMAKE_RANLIB "${CLANG_DIR_PATH}/llvm-ranlib") +set(CMAKE_OBJDUMP xtensa-esp32s3-elf-objdump) + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --target=xtensa-esp-elf -mcpu=esp32" + CACHE STRING "C Compiler Base Flags" + FORCE) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --target=xtensa-esp-elf -mcpu=esp32" + CACHE STRING "C++ Compiler Base Flags" + FORCE) + +set(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} --target=xtensa-esp-elf -mcpu=esp32 -Xassembler --longcalls" + CACHE STRING "Assembler Base Flags" + FORCE) diff --git a/esp-mbedtls-sys/gen/toolchains/toolchain-clang-esp32c3.cmake b/esp-mbedtls-sys/gen/toolchains/toolchain-clang-esp32c3.cmake new file mode 100644 index 0000000..bc79313 --- /dev/null +++ b/esp-mbedtls-sys/gen/toolchains/toolchain-clang-esp32c3.cmake @@ -0,0 +1,23 @@ +set(CMAKE_SYSTEM_NAME Generic) + +# Install with `espup install --extended-llvm` +set(CMAKE_C_COMPILER "$ENV{CLANG_PATH}") + +set(CLANG_DIR_PATH "${CMAKE_C_COMPILER}") +cmake_path(REMOVE_FILENAME CLANG_DIR_PATH) + +set(CMAKE_AR "${CLANG_DIR_PATH}/llvm-ar") +set(CMAKE_RANLIB "${CLANG_DIR_PATH}/llvm-ranlib") +set(CMAKE_OBJDUMP xtensa-esp32s3-elf-objdump) + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --target=riscv32-esp-elf -march=rv32imc -mabi=ilp32" + CACHE STRING "C Compiler Base Flags" + FORCE) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --target=riscv32-esp-elf -march=rv32imc -mabi=ilp32" + CACHE STRING "C++ Compiler Base Flags" + FORCE) + +set(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} --target=riscv32-esp-elf -march=rv32imc -mabi=ilp32" + CACHE STRING "Assembler Base Flags" + FORCE) diff --git a/esp-mbedtls-sys/gen/toolchains/toolchain-clang-esp32s2.cmake b/esp-mbedtls-sys/gen/toolchains/toolchain-clang-esp32s2.cmake new file mode 100644 index 0000000..f27365b --- /dev/null +++ b/esp-mbedtls-sys/gen/toolchains/toolchain-clang-esp32s2.cmake @@ -0,0 +1,23 @@ +set(CMAKE_SYSTEM_NAME Generic) + +# Install with `espup install --extended-llvm` +set(CMAKE_C_COMPILER "$ENV{CLANG_PATH}") + +set(CLANG_DIR_PATH "${CMAKE_C_COMPILER}") +cmake_path(REMOVE_FILENAME CLANG_DIR_PATH) + +set(CMAKE_AR "${CLANG_DIR_PATH}/llvm-ar") +set(CMAKE_RANLIB "${CLANG_DIR_PATH}/llvm-ranlib") +set(CMAKE_OBJDUMP xtensa-esp32s3-elf-objdump) + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --target=xtensa-esp-elf -mcpu=esp32s2" + CACHE STRING "C Compiler Base Flags" + FORCE) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --target=xtensa-esp-elf -mcpu=esp32s2" + CACHE STRING "C++ Compiler Base Flags" + FORCE) + +set(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} --target=xtensa-esp-elf -mcpu=esp32s2 -Xassembler --longcalls" + CACHE STRING "Assembler Base Flags" + FORCE) diff --git a/esp-mbedtls-sys/gen/toolchains/toolchain-clang-esp32s3.cmake b/esp-mbedtls-sys/gen/toolchains/toolchain-clang-esp32s3.cmake new file mode 100644 index 0000000..91c4719 --- /dev/null +++ b/esp-mbedtls-sys/gen/toolchains/toolchain-clang-esp32s3.cmake @@ -0,0 +1,23 @@ +set(CMAKE_SYSTEM_NAME Generic) + +# Install with `espup install --extended-llvm` +set(CMAKE_C_COMPILER "$ENV{CLANG_PATH}") + +set(CLANG_DIR_PATH "${CMAKE_C_COMPILER}") +cmake_path(REMOVE_FILENAME CLANG_DIR_PATH) + +set(CMAKE_AR "${CLANG_DIR_PATH}/llvm-ar") +set(CMAKE_RANLIB "${CLANG_DIR_PATH}/llvm-ranlib") +set(CMAKE_OBJDUMP xtensa-esp32s3-elf-objdump) + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --target=xtensa-esp-elf -mcpu=esp32s3" + CACHE STRING "C Compiler Base Flags" + FORCE) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --target=xtensa-esp-elf -mcpu=esp32s3" + CACHE STRING "C++ Compiler Base Flags" + FORCE) + +set(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} --target=xtensa-esp-elf -mcpu=esp32s3 -Xassembler --longcalls" + CACHE STRING "Assembler Base Flags" + FORCE) diff --git a/esp-mbedtls-sys/gen/toolchains/toolchain-clang-generic.cmake b/esp-mbedtls-sys/gen/toolchains/toolchain-clang-generic.cmake new file mode 100644 index 0000000..f40e789 --- /dev/null +++ b/esp-mbedtls-sys/gen/toolchains/toolchain-clang-generic.cmake @@ -0,0 +1,3 @@ +set(CMAKE_SYSTEM_NAME Generic) + +# For generic targets, just use the C compiler and utilities user should have in their PATH already diff --git a/esp-mbedtls-sys/libs/riscv32imc-unknown-none-elf/libmbedcrypto.a b/esp-mbedtls-sys/libs/riscv32imc-unknown-none-elf/libmbedcrypto.a new file mode 100644 index 0000000..9037841 Binary files /dev/null and b/esp-mbedtls-sys/libs/riscv32imc-unknown-none-elf/libmbedcrypto.a differ diff --git a/esp-mbedtls-sys/libs/riscv32imc-unknown-none-elf/libmbedtls.a b/esp-mbedtls-sys/libs/riscv32imc-unknown-none-elf/libmbedtls.a new file mode 100644 index 0000000..7669983 Binary files /dev/null and b/esp-mbedtls-sys/libs/riscv32imc-unknown-none-elf/libmbedtls.a differ diff --git a/esp-mbedtls-sys/libs/riscv32imc-unknown-none-elf/libmbedx509.a b/esp-mbedtls-sys/libs/riscv32imc-unknown-none-elf/libmbedx509.a new file mode 100644 index 0000000..9cafe28 Binary files /dev/null and b/esp-mbedtls-sys/libs/riscv32imc-unknown-none-elf/libmbedx509.a differ diff --git a/esp-mbedtls-sys/libs/xtensa-esp32-none-elf/libmbedcrypto.a b/esp-mbedtls-sys/libs/xtensa-esp32-none-elf/libmbedcrypto.a new file mode 100644 index 0000000..abf178a Binary files /dev/null and b/esp-mbedtls-sys/libs/xtensa-esp32-none-elf/libmbedcrypto.a differ diff --git a/esp-mbedtls-sys/libs/xtensa-esp32-none-elf/libmbedtls.a b/esp-mbedtls-sys/libs/xtensa-esp32-none-elf/libmbedtls.a new file mode 100644 index 0000000..1e6e53d Binary files /dev/null and b/esp-mbedtls-sys/libs/xtensa-esp32-none-elf/libmbedtls.a differ diff --git a/esp-mbedtls-sys/libs/xtensa-esp32-none-elf/libmbedx509.a b/esp-mbedtls-sys/libs/xtensa-esp32-none-elf/libmbedx509.a new file mode 100644 index 0000000..bb731ec Binary files /dev/null and b/esp-mbedtls-sys/libs/xtensa-esp32-none-elf/libmbedx509.a differ diff --git a/esp-mbedtls-sys/libs/xtensa-esp32s2-none-elf/libmbedcrypto.a b/esp-mbedtls-sys/libs/xtensa-esp32s2-none-elf/libmbedcrypto.a new file mode 100644 index 0000000..884c37d Binary files /dev/null and b/esp-mbedtls-sys/libs/xtensa-esp32s2-none-elf/libmbedcrypto.a differ diff --git a/esp-mbedtls-sys/libs/xtensa-esp32s2-none-elf/libmbedtls.a b/esp-mbedtls-sys/libs/xtensa-esp32s2-none-elf/libmbedtls.a new file mode 100644 index 0000000..8255e78 Binary files /dev/null and b/esp-mbedtls-sys/libs/xtensa-esp32s2-none-elf/libmbedtls.a differ diff --git a/esp-mbedtls-sys/libs/xtensa-esp32s2-none-elf/libmbedx509.a b/esp-mbedtls-sys/libs/xtensa-esp32s2-none-elf/libmbedx509.a new file mode 100644 index 0000000..bb731ec Binary files /dev/null and b/esp-mbedtls-sys/libs/xtensa-esp32s2-none-elf/libmbedx509.a differ diff --git a/esp-mbedtls-sys/libs/xtensa-esp32s3-none-elf/libmbedcrypto.a b/esp-mbedtls-sys/libs/xtensa-esp32s3-none-elf/libmbedcrypto.a new file mode 100644 index 0000000..884c37d Binary files /dev/null and b/esp-mbedtls-sys/libs/xtensa-esp32s3-none-elf/libmbedcrypto.a differ diff --git a/esp-mbedtls-sys/libs/xtensa-esp32s3-none-elf/libmbedtls.a b/esp-mbedtls-sys/libs/xtensa-esp32s3-none-elf/libmbedtls.a new file mode 100644 index 0000000..8255e78 Binary files /dev/null and b/esp-mbedtls-sys/libs/xtensa-esp32s3-none-elf/libmbedtls.a differ diff --git a/esp-mbedtls-sys/libs/xtensa-esp32s3-none-elf/libmbedx509.a b/esp-mbedtls-sys/libs/xtensa-esp32s3-none-elf/libmbedx509.a new file mode 100644 index 0000000..bb731ec Binary files /dev/null and b/esp-mbedtls-sys/libs/xtensa-esp32s3-none-elf/libmbedx509.a differ diff --git a/mbedtls b/esp-mbedtls-sys/mbedtls similarity index 100% rename from mbedtls rename to esp-mbedtls-sys/mbedtls diff --git a/esp-mbedtls-sys/src/c_types.rs b/esp-mbedtls-sys/src/c_types.rs index 48681fc..629d9f9 100644 --- a/esp-mbedtls-sys/src/c_types.rs +++ b/esp-mbedtls-sys/src/c_types.rs @@ -1,21 +1 @@ -#![allow( - non_camel_case_types, - non_snake_case, - non_upper_case_globals, - dead_code -)] - -pub type c_uint = core::ffi::c_uint; -pub type c_int = core::ffi::c_int; -pub type c_ulonglong = core::ffi::c_ulonglong; -pub type c_longlong = core::ffi::c_longlong; -pub type c_uchar = core::ffi::c_uchar; - -pub type c_short = core::ffi::c_short; -pub type c_ushort = core::ffi::c_ushort; -pub type c_schar = core::ffi::c_schar; -pub type c_char = core::ffi::c_char; -pub type c_long = core::ffi::c_long; -pub type c_ulong = core::ffi::c_ulong; - -pub type c_void = core::ffi::c_void; +pub use core::ffi::*; diff --git a/esp-mbedtls-sys/src/include/esp32.rs b/esp-mbedtls-sys/src/include/esp32.rs index 3ee6c9f..de8bfb9 100644 --- a/esp-mbedtls-sys/src/include/esp32.rs +++ b/esp-mbedtls-sys/src/include/esp32.rs @@ -1,12 +1,5 @@ /* automatically generated by rust-bindgen 0.68.1 */ -#![allow( - non_camel_case_types, - non_snake_case, - non_upper_case_globals, - dead_code -)] - #[repr(C)] #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct __BindgenBitfieldUnit { @@ -206,7 +199,127 @@ pub const PSA_WANT_KEY_TYPE_DERIVE: u32 = 1; pub const PSA_WANT_KEY_TYPE_PASSWORD: u32 = 1; pub const PSA_WANT_KEY_TYPE_PASSWORD_HASH: u32 = 1; pub const PSA_WANT_KEY_TYPE_RAW_DATA: u32 = 1; +pub const _LIBC_LIMITS_H_: u32 = 1; +pub const __NEWLIB_H__: u32 = 1; +pub const _NEWLIB_VERSION_H__: u32 = 1; +pub const _NEWLIB_VERSION: &[u8; 6] = b"4.3.0\0"; +pub const __NEWLIB__: u32 = 4; +pub const __NEWLIB_MINOR__: u32 = 3; +pub const __NEWLIB_PATCHLEVEL__: u32 = 0; +pub const _ATEXIT_DYNAMIC_ALLOC: u32 = 1; +pub const _FSEEK_OPTIMIZATION: u32 = 1; +pub const _FVWRITE_IN_STREAMIO: u32 = 1; +pub const _HAVE_CC_INHIBIT_LOOP_TO_LIBCALL: u32 = 1; +pub const _HAVE_INITFINI_ARRAY: u32 = 1; +pub const _HAVE_LONG_DOUBLE: u32 = 1; +pub const _ICONV_ENABLED: u32 = 1; +pub const _LDBL_EQ_DBL: u32 = 1; +pub const _MB_LEN_MAX: u32 = 1; +pub const _NANO_MALLOC: u32 = 1; +pub const _REENT_CHECK_VERIFY: u32 = 1; +pub const _RETARGETABLE_LOCKING: u32 = 1; +pub const _UNBUF_STREAM_OPT: u32 = 1; +pub const _WANT_IO_C99_FORMATS: u32 = 1; +pub const _WANT_IO_LONG_LONG: u32 = 1; +pub const _WANT_IO_POS_ARGS: u32 = 1; +pub const _WANT_REENT_BACKWARD_BINARY_COMPAT: u32 = 1; +pub const _WANT_REENT_SMALL: u32 = 1; +pub const _WANT_USE_GDTOA: u32 = 1; +pub const _DEFAULT_SOURCE: u32 = 1; +pub const _POSIX_SOURCE: u32 = 1; +pub const _POSIX_C_SOURCE: u32 = 200809; +pub const _ATFILE_SOURCE: u32 = 1; +pub const __ATFILE_VISIBLE: u32 = 1; +pub const __BSD_VISIBLE: u32 = 1; +pub const __GNU_VISIBLE: u32 = 0; +pub const __ISO_C_VISIBLE: u32 = 2011; +pub const __LARGEFILE_VISIBLE: u32 = 0; +pub const __MISC_VISIBLE: u32 = 1; +pub const __POSIX_VISIBLE: u32 = 200809; +pub const __SVID_VISIBLE: u32 = 1; +pub const __XSI_VISIBLE: u32 = 0; +pub const __SSP_FORTIFY_LEVEL: u32 = 0; +pub const _POSIX_THREADS: u32 = 1; +pub const _POSIX_TIMEOUTS: u32 = 1; +pub const _POSIX_TIMERS: u32 = 1; +pub const _POSIX_MONOTONIC_CLOCK: u32 = 200112; +pub const _POSIX_CLOCK_SELECTION: u32 = 200112; +pub const _UNIX98_THREAD_MUTEX_ATTRIBUTES: u32 = 1; +pub const _POSIX_READER_WRITER_LOCKS: u32 = 200112; +pub const __have_longlong64: u32 = 1; +pub const __have_long32: u32 = 1; +pub const ___int8_t_defined: u32 = 1; +pub const ___int16_t_defined: u32 = 1; +pub const ___int32_t_defined: u32 = 1; +pub const ___int64_t_defined: u32 = 1; +pub const ___int_least8_t_defined: u32 = 1; +pub const ___int_least16_t_defined: u32 = 1; +pub const ___int_least32_t_defined: u32 = 1; +pub const ___int_least64_t_defined: u32 = 1; +pub const __GNUCLIKE_ASM: u32 = 3; +pub const __GNUCLIKE___TYPEOF: u32 = 1; +pub const __GNUCLIKE___SECTION: u32 = 1; +pub const __GNUCLIKE_CTOR_SECTION_HANDLING: u32 = 1; +pub const __GNUCLIKE_BUILTIN_CONSTANT_P: u32 = 1; +pub const __GNUCLIKE_BUILTIN_VARARGS: u32 = 1; +pub const __GNUCLIKE_BUILTIN_STDARG: u32 = 1; +pub const __GNUCLIKE_BUILTIN_VAALIST: u32 = 1; +pub const __GNUC_VA_LIST_COMPATIBILITY: u32 = 1; +pub const __GNUCLIKE_BUILTIN_NEXT_ARG: u32 = 1; +pub const __GNUCLIKE_BUILTIN_MEMCPY: u32 = 1; +pub const __CC_SUPPORTS_INLINE: u32 = 1; +pub const __CC_SUPPORTS___INLINE: u32 = 1; +pub const __CC_SUPPORTS___INLINE__: u32 = 1; +pub const __CC_SUPPORTS___FUNC__: u32 = 1; +pub const __CC_SUPPORTS_WARNING: u32 = 1; +pub const __CC_SUPPORTS_VARADIC_XXX: u32 = 1; +pub const __CC_SUPPORTS_DYNAMIC_ARRAY_INIT: u32 = 1; +pub const ARG_MAX: u32 = 65536; +pub const CHILD_MAX: u32 = 40; +pub const LINK_MAX: u32 = 32767; +pub const MAX_CANON: u32 = 255; +pub const MAX_INPUT: u32 = 255; +pub const NAME_MAX: u32 = 255; +pub const NGROUPS_MAX: u32 = 16; +pub const OPEN_MAX: u32 = 64; +pub const PATH_MAX: u32 = 1024; +pub const PIPE_BUF: u32 = 512; +pub const IOV_MAX: u32 = 1024; +pub const BC_BASE_MAX: u32 = 99; +pub const BC_DIM_MAX: u32 = 2048; +pub const BC_SCALE_MAX: u32 = 99; +pub const BC_STRING_MAX: u32 = 1000; +pub const COLL_WEIGHTS_MAX: u32 = 0; +pub const EXPR_NEST_MAX: u32 = 32; +pub const LINE_MAX: u32 = 2048; +pub const RE_DUP_MAX: u32 = 255; pub const MB_LEN_MAX: u32 = 1; +pub const NL_ARGMAX: u32 = 32; +pub const _POSIX2_RE_DUP_MAX: u32 = 255; +pub const __int20: u32 = 2; +pub const __int20__: u32 = 2; +pub const __INT8: &[u8; 3] = b"hh\0"; +pub const __INT16: &[u8; 2] = b"h\0"; +pub const __INT64: &[u8; 3] = b"ll\0"; +pub const __FAST8: &[u8; 3] = b"hh\0"; +pub const __FAST16: &[u8; 2] = b"h\0"; +pub const __FAST64: &[u8; 3] = b"ll\0"; +pub const __LEAST8: &[u8; 3] = b"hh\0"; +pub const __LEAST16: &[u8; 2] = b"h\0"; +pub const __LEAST64: &[u8; 3] = b"ll\0"; +pub const __int8_t_defined: u32 = 1; +pub const __int16_t_defined: u32 = 1; +pub const __int32_t_defined: u32 = 1; +pub const __int64_t_defined: u32 = 1; +pub const __int_least8_t_defined: u32 = 1; +pub const __int_least16_t_defined: u32 = 1; +pub const __int_least32_t_defined: u32 = 1; +pub const __int_least64_t_defined: u32 = 1; +pub const __int_fast8_t_defined: u32 = 1; +pub const __int_fast16_t_defined: u32 = 1; +pub const __int_fast32_t_defined: u32 = 1; +pub const __int_fast64_t_defined: u32 = 1; +pub const WINT_MIN: u32 = 0; pub const MBEDTLS_ERR_MPI_FILE_IO_ERROR: i32 = -2; pub const MBEDTLS_ERR_MPI_BAD_INPUT_DATA: i32 = -4; pub const MBEDTLS_ERR_MPI_INVALID_CHARACTER: i32 = -6; @@ -949,25 +1062,26 @@ pub const MBEDTLS_CTR_DRBG_MAX_SEED_INPUT: u32 = 384; pub const MBEDTLS_CTR_DRBG_PR_OFF: u32 = 0; pub const MBEDTLS_CTR_DRBG_PR_ON: u32 = 1; pub const MBEDTLS_CTR_DRBG_ENTROPY_NONCE_LEN: u32 = 0; -pub type int_least64_t = i64; -pub type uint_least64_t = u64; -pub type int_fast64_t = i64; -pub type uint_fast64_t = u64; -pub type int_least32_t = i32; -pub type uint_least32_t = u32; -pub type int_fast32_t = i32; -pub type uint_fast32_t = u32; -pub type int_least16_t = i16; -pub type uint_least16_t = u16; -pub type int_fast16_t = i16; -pub type uint_fast16_t = u16; -pub type int_least8_t = i8; -pub type uint_least8_t = u8; -pub type int_fast8_t = i8; -pub type uint_fast8_t = u8; -pub type intmax_t = crate::c_types::c_longlong; -pub type uintmax_t = crate::c_types::c_ulonglong; -pub type mbedtls_iso_c_forbids_empty_translation_units = crate::c_types::c_int; +pub type __int8_t = crate::c_types::c_schar; +pub type __uint8_t = crate::c_types::c_uchar; +pub type __int16_t = crate::c_types::c_short; +pub type __uint16_t = crate::c_types::c_ushort; +pub type __int32_t = crate::c_types::c_int; +pub type __uint32_t = crate::c_types::c_uint; +pub type __int64_t = crate::c_types::c_longlong; +pub type __uint64_t = crate::c_types::c_ulonglong; +pub type __int_least8_t = crate::c_types::c_schar; +pub type __uint_least8_t = crate::c_types::c_uchar; +pub type __int_least16_t = crate::c_types::c_short; +pub type __uint_least16_t = crate::c_types::c_ushort; +pub type __int_least32_t = crate::c_types::c_int; +pub type __uint_least32_t = crate::c_types::c_uint; +pub type __int_least64_t = crate::c_types::c_longlong; +pub type __uint_least64_t = crate::c_types::c_ulonglong; +pub type __intmax_t = crate::c_types::c_longlong; +pub type __uintmax_t = crate::c_types::c_ulonglong; +pub type __intptr_t = crate::c_types::c_int; +pub type __uintptr_t = crate::c_types::c_uint; pub type wchar_t = crate::c_types::c_int; #[repr(C)] #[derive(Copy, Clone)] @@ -975,6 +1089,25 @@ pub struct max_align_t { pub __clang_max_align_nonce1: crate::c_types::c_longlong, pub __clang_max_align_nonce2: f64, } +pub type intmax_t = __intmax_t; +pub type uintmax_t = __uintmax_t; +pub type int_least8_t = __int_least8_t; +pub type uint_least8_t = __uint_least8_t; +pub type int_least16_t = __int_least16_t; +pub type uint_least16_t = __uint_least16_t; +pub type int_least32_t = __int_least32_t; +pub type uint_least32_t = __uint_least32_t; +pub type int_least64_t = __int_least64_t; +pub type uint_least64_t = __uint_least64_t; +pub type int_fast8_t = crate::c_types::c_schar; +pub type uint_fast8_t = crate::c_types::c_uchar; +pub type int_fast16_t = crate::c_types::c_short; +pub type uint_fast16_t = crate::c_types::c_ushort; +pub type int_fast32_t = crate::c_types::c_int; +pub type uint_fast32_t = crate::c_types::c_uint; +pub type int_fast64_t = crate::c_types::c_longlong; +pub type uint_fast64_t = crate::c_types::c_ulonglong; +pub type mbedtls_iso_c_forbids_empty_translation_units = crate::c_types::c_int; extern "C" { /// \brief Securely zeroize a buffer /// @@ -18028,6 +18161,9 @@ pub struct mbedtls_ecdh_context { pub private_grp_id: mbedtls_ecp_group_id, ///< The ECDH implementation/structure used. pub private_var: mbedtls_ecdh_variant, + ///< Implementation-specific context. The + ///context in use is specified by the \c var + ///field. pub private_ctx: mbedtls_ecdh_context__bindgen_ty_1, } #[repr(C)] diff --git a/esp-mbedtls-sys/src/include/esp32c3.rs b/esp-mbedtls-sys/src/include/esp32c3.rs index 45489aa..564a1d4 100644 --- a/esp-mbedtls-sys/src/include/esp32c3.rs +++ b/esp-mbedtls-sys/src/include/esp32c3.rs @@ -1,12 +1,5 @@ /* automatically generated by rust-bindgen 0.68.1 */ -#![allow( - non_camel_case_types, - non_snake_case, - non_upper_case_globals, - dead_code -)] - #[repr(C)] #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct __BindgenBitfieldUnit { @@ -209,26 +202,28 @@ pub const PSA_WANT_KEY_TYPE_RAW_DATA: u32 = 1; pub const _LIBC_LIMITS_H_: u32 = 1; pub const __NEWLIB_H__: u32 = 1; pub const _NEWLIB_VERSION_H__: u32 = 1; -pub const _NEWLIB_VERSION: &[u8; 6] = b"3.3.0\0"; -pub const __NEWLIB__: u32 = 3; +pub const _NEWLIB_VERSION: &[u8; 6] = b"4.3.0\0"; +pub const __NEWLIB__: u32 = 4; pub const __NEWLIB_MINOR__: u32 = 3; pub const __NEWLIB_PATCHLEVEL__: u32 = 0; +pub const _ATEXIT_DYNAMIC_ALLOC: u32 = 1; +pub const _FSEEK_OPTIMIZATION: u32 = 1; +pub const _FVWRITE_IN_STREAMIO: u32 = 1; +pub const _HAVE_CC_INHIBIT_LOOP_TO_LIBCALL: u32 = 1; +pub const _HAVE_INITFINI_ARRAY: u32 = 1; +pub const _HAVE_LONG_DOUBLE: u32 = 1; +pub const _ICONV_ENABLED: u32 = 1; +pub const _MB_LEN_MAX: u32 = 1; +pub const _NANO_MALLOC: u32 = 1; +pub const _REENT_CHECK_VERIFY: u32 = 1; +pub const _RETARGETABLE_LOCKING: u32 = 1; +pub const _UNBUF_STREAM_OPT: u32 = 1; pub const _WANT_IO_C99_FORMATS: u32 = 1; pub const _WANT_IO_LONG_LONG: u32 = 1; pub const _WANT_IO_POS_ARGS: u32 = 1; +pub const _WANT_REENT_BACKWARD_BINARY_COMPAT: u32 = 1; pub const _WANT_REENT_SMALL: u32 = 1; -pub const _REENT_CHECK_VERIFY: u32 = 1; -pub const _MB_LEN_MAX: u32 = 1; -pub const _ICONV_ENABLED: u32 = 1; -pub const HAVE_INITFINI_ARRAY: u32 = 1; -pub const _ATEXIT_DYNAMIC_ALLOC: u32 = 1; -pub const _HAVE_LONG_DOUBLE: u32 = 1; -pub const _HAVE_CC_INHIBIT_LOOP_TO_LIBCALL: u32 = 1; -pub const _FVWRITE_IN_STREAMIO: u32 = 1; -pub const _FSEEK_OPTIMIZATION: u32 = 1; -pub const _UNBUF_STREAM_OPT: u32 = 1; -pub const _RETARGETABLE_LOCKING: u32 = 1; -pub const _WANT_USE_LONG_TIME_T: u32 = 1; +pub const _WANT_USE_GDTOA: u32 = 1; pub const _DEFAULT_SOURCE: u32 = 1; pub const _POSIX_SOURCE: u32 = 1; pub const _POSIX_C_SOURCE: u32 = 200809; @@ -249,6 +244,7 @@ pub const _POSIX_TIMERS: u32 = 1; pub const _POSIX_MONOTONIC_CLOCK: u32 = 200112; pub const _POSIX_CLOCK_SELECTION: u32 = 200112; pub const _UNIX98_THREAD_MUTEX_ATTRIBUTES: u32 = 1; +pub const _POSIX_READER_WRITER_LOCKS: u32 = 200112; pub const __have_longlong64: u32 = 1; pub const __have_long32: u32 = 1; pub const ___int8_t_defined: u32 = 1; @@ -261,7 +257,6 @@ pub const ___int_least32_t_defined: u32 = 1; pub const ___int_least64_t_defined: u32 = 1; pub const __GNUCLIKE_ASM: u32 = 3; pub const __GNUCLIKE___TYPEOF: u32 = 1; -pub const __GNUCLIKE___OFFSETOF: u32 = 1; pub const __GNUCLIKE___SECTION: u32 = 1; pub const __GNUCLIKE_CTOR_SECTION_HANDLING: u32 = 1; pub const __GNUCLIKE_BUILTIN_CONSTANT_P: u32 = 1; @@ -278,7 +273,7 @@ pub const __CC_SUPPORTS___FUNC__: u32 = 1; pub const __CC_SUPPORTS_WARNING: u32 = 1; pub const __CC_SUPPORTS_VARADIC_XXX: u32 = 1; pub const __CC_SUPPORTS_DYNAMIC_ARRAY_INIT: u32 = 1; -pub const ARG_MAX: u32 = 4096; +pub const ARG_MAX: u32 = 65536; pub const CHILD_MAX: u32 = 40; pub const LINK_MAX: u32 = 32767; pub const MAX_CANON: u32 = 255; @@ -18158,6 +18153,9 @@ pub struct mbedtls_ecdh_context { pub private_grp_id: mbedtls_ecp_group_id, ///< The ECDH implementation/structure used. pub private_var: mbedtls_ecdh_variant, + ///< Implementation-specific context. The + ///context in use is specified by the \c var + ///field. pub private_ctx: mbedtls_ecdh_context__bindgen_ty_1, } #[repr(C)] diff --git a/esp-mbedtls-sys/src/include/esp32s2.rs b/esp-mbedtls-sys/src/include/esp32s2.rs index 681c798..7a0f825 100644 --- a/esp-mbedtls-sys/src/include/esp32s2.rs +++ b/esp-mbedtls-sys/src/include/esp32s2.rs @@ -1,12 +1,5 @@ /* automatically generated by rust-bindgen 0.68.1 */ -#![allow( - non_camel_case_types, - non_snake_case, - non_upper_case_globals, - dead_code -)] - #[repr(C)] #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct __BindgenBitfieldUnit { @@ -206,7 +199,127 @@ pub const PSA_WANT_KEY_TYPE_DERIVE: u32 = 1; pub const PSA_WANT_KEY_TYPE_PASSWORD: u32 = 1; pub const PSA_WANT_KEY_TYPE_PASSWORD_HASH: u32 = 1; pub const PSA_WANT_KEY_TYPE_RAW_DATA: u32 = 1; +pub const _LIBC_LIMITS_H_: u32 = 1; +pub const __NEWLIB_H__: u32 = 1; +pub const _NEWLIB_VERSION_H__: u32 = 1; +pub const _NEWLIB_VERSION: &[u8; 6] = b"4.3.0\0"; +pub const __NEWLIB__: u32 = 4; +pub const __NEWLIB_MINOR__: u32 = 3; +pub const __NEWLIB_PATCHLEVEL__: u32 = 0; +pub const _ATEXIT_DYNAMIC_ALLOC: u32 = 1; +pub const _FSEEK_OPTIMIZATION: u32 = 1; +pub const _FVWRITE_IN_STREAMIO: u32 = 1; +pub const _HAVE_CC_INHIBIT_LOOP_TO_LIBCALL: u32 = 1; +pub const _HAVE_INITFINI_ARRAY: u32 = 1; +pub const _HAVE_LONG_DOUBLE: u32 = 1; +pub const _ICONV_ENABLED: u32 = 1; +pub const _LDBL_EQ_DBL: u32 = 1; +pub const _MB_LEN_MAX: u32 = 1; +pub const _NANO_MALLOC: u32 = 1; +pub const _REENT_CHECK_VERIFY: u32 = 1; +pub const _RETARGETABLE_LOCKING: u32 = 1; +pub const _UNBUF_STREAM_OPT: u32 = 1; +pub const _WANT_IO_C99_FORMATS: u32 = 1; +pub const _WANT_IO_LONG_LONG: u32 = 1; +pub const _WANT_IO_POS_ARGS: u32 = 1; +pub const _WANT_REENT_BACKWARD_BINARY_COMPAT: u32 = 1; +pub const _WANT_REENT_SMALL: u32 = 1; +pub const _WANT_USE_GDTOA: u32 = 1; +pub const _DEFAULT_SOURCE: u32 = 1; +pub const _POSIX_SOURCE: u32 = 1; +pub const _POSIX_C_SOURCE: u32 = 200809; +pub const _ATFILE_SOURCE: u32 = 1; +pub const __ATFILE_VISIBLE: u32 = 1; +pub const __BSD_VISIBLE: u32 = 1; +pub const __GNU_VISIBLE: u32 = 0; +pub const __ISO_C_VISIBLE: u32 = 2011; +pub const __LARGEFILE_VISIBLE: u32 = 0; +pub const __MISC_VISIBLE: u32 = 1; +pub const __POSIX_VISIBLE: u32 = 200809; +pub const __SVID_VISIBLE: u32 = 1; +pub const __XSI_VISIBLE: u32 = 0; +pub const __SSP_FORTIFY_LEVEL: u32 = 0; +pub const _POSIX_THREADS: u32 = 1; +pub const _POSIX_TIMEOUTS: u32 = 1; +pub const _POSIX_TIMERS: u32 = 1; +pub const _POSIX_MONOTONIC_CLOCK: u32 = 200112; +pub const _POSIX_CLOCK_SELECTION: u32 = 200112; +pub const _UNIX98_THREAD_MUTEX_ATTRIBUTES: u32 = 1; +pub const _POSIX_READER_WRITER_LOCKS: u32 = 200112; +pub const __have_longlong64: u32 = 1; +pub const __have_long32: u32 = 1; +pub const ___int8_t_defined: u32 = 1; +pub const ___int16_t_defined: u32 = 1; +pub const ___int32_t_defined: u32 = 1; +pub const ___int64_t_defined: u32 = 1; +pub const ___int_least8_t_defined: u32 = 1; +pub const ___int_least16_t_defined: u32 = 1; +pub const ___int_least32_t_defined: u32 = 1; +pub const ___int_least64_t_defined: u32 = 1; +pub const __GNUCLIKE_ASM: u32 = 3; +pub const __GNUCLIKE___TYPEOF: u32 = 1; +pub const __GNUCLIKE___SECTION: u32 = 1; +pub const __GNUCLIKE_CTOR_SECTION_HANDLING: u32 = 1; +pub const __GNUCLIKE_BUILTIN_CONSTANT_P: u32 = 1; +pub const __GNUCLIKE_BUILTIN_VARARGS: u32 = 1; +pub const __GNUCLIKE_BUILTIN_STDARG: u32 = 1; +pub const __GNUCLIKE_BUILTIN_VAALIST: u32 = 1; +pub const __GNUC_VA_LIST_COMPATIBILITY: u32 = 1; +pub const __GNUCLIKE_BUILTIN_NEXT_ARG: u32 = 1; +pub const __GNUCLIKE_BUILTIN_MEMCPY: u32 = 1; +pub const __CC_SUPPORTS_INLINE: u32 = 1; +pub const __CC_SUPPORTS___INLINE: u32 = 1; +pub const __CC_SUPPORTS___INLINE__: u32 = 1; +pub const __CC_SUPPORTS___FUNC__: u32 = 1; +pub const __CC_SUPPORTS_WARNING: u32 = 1; +pub const __CC_SUPPORTS_VARADIC_XXX: u32 = 1; +pub const __CC_SUPPORTS_DYNAMIC_ARRAY_INIT: u32 = 1; +pub const ARG_MAX: u32 = 65536; +pub const CHILD_MAX: u32 = 40; +pub const LINK_MAX: u32 = 32767; +pub const MAX_CANON: u32 = 255; +pub const MAX_INPUT: u32 = 255; +pub const NAME_MAX: u32 = 255; +pub const NGROUPS_MAX: u32 = 16; +pub const OPEN_MAX: u32 = 64; +pub const PATH_MAX: u32 = 1024; +pub const PIPE_BUF: u32 = 512; +pub const IOV_MAX: u32 = 1024; +pub const BC_BASE_MAX: u32 = 99; +pub const BC_DIM_MAX: u32 = 2048; +pub const BC_SCALE_MAX: u32 = 99; +pub const BC_STRING_MAX: u32 = 1000; +pub const COLL_WEIGHTS_MAX: u32 = 0; +pub const EXPR_NEST_MAX: u32 = 32; +pub const LINE_MAX: u32 = 2048; +pub const RE_DUP_MAX: u32 = 255; pub const MB_LEN_MAX: u32 = 1; +pub const NL_ARGMAX: u32 = 32; +pub const _POSIX2_RE_DUP_MAX: u32 = 255; +pub const __int20: u32 = 2; +pub const __int20__: u32 = 2; +pub const __INT8: &[u8; 3] = b"hh\0"; +pub const __INT16: &[u8; 2] = b"h\0"; +pub const __INT64: &[u8; 3] = b"ll\0"; +pub const __FAST8: &[u8; 3] = b"hh\0"; +pub const __FAST16: &[u8; 2] = b"h\0"; +pub const __FAST64: &[u8; 3] = b"ll\0"; +pub const __LEAST8: &[u8; 3] = b"hh\0"; +pub const __LEAST16: &[u8; 2] = b"h\0"; +pub const __LEAST64: &[u8; 3] = b"ll\0"; +pub const __int8_t_defined: u32 = 1; +pub const __int16_t_defined: u32 = 1; +pub const __int32_t_defined: u32 = 1; +pub const __int64_t_defined: u32 = 1; +pub const __int_least8_t_defined: u32 = 1; +pub const __int_least16_t_defined: u32 = 1; +pub const __int_least32_t_defined: u32 = 1; +pub const __int_least64_t_defined: u32 = 1; +pub const __int_fast8_t_defined: u32 = 1; +pub const __int_fast16_t_defined: u32 = 1; +pub const __int_fast32_t_defined: u32 = 1; +pub const __int_fast64_t_defined: u32 = 1; +pub const WINT_MIN: u32 = 0; pub const MBEDTLS_ERR_MPI_FILE_IO_ERROR: i32 = -2; pub const MBEDTLS_ERR_MPI_BAD_INPUT_DATA: i32 = -4; pub const MBEDTLS_ERR_MPI_INVALID_CHARACTER: i32 = -6; @@ -949,25 +1062,26 @@ pub const MBEDTLS_CTR_DRBG_MAX_SEED_INPUT: u32 = 384; pub const MBEDTLS_CTR_DRBG_PR_OFF: u32 = 0; pub const MBEDTLS_CTR_DRBG_PR_ON: u32 = 1; pub const MBEDTLS_CTR_DRBG_ENTROPY_NONCE_LEN: u32 = 0; -pub type int_least64_t = i64; -pub type uint_least64_t = u64; -pub type int_fast64_t = i64; -pub type uint_fast64_t = u64; -pub type int_least32_t = i32; -pub type uint_least32_t = u32; -pub type int_fast32_t = i32; -pub type uint_fast32_t = u32; -pub type int_least16_t = i16; -pub type uint_least16_t = u16; -pub type int_fast16_t = i16; -pub type uint_fast16_t = u16; -pub type int_least8_t = i8; -pub type uint_least8_t = u8; -pub type int_fast8_t = i8; -pub type uint_fast8_t = u8; -pub type intmax_t = crate::c_types::c_longlong; -pub type uintmax_t = crate::c_types::c_ulonglong; -pub type mbedtls_iso_c_forbids_empty_translation_units = crate::c_types::c_int; +pub type __int8_t = crate::c_types::c_schar; +pub type __uint8_t = crate::c_types::c_uchar; +pub type __int16_t = crate::c_types::c_short; +pub type __uint16_t = crate::c_types::c_ushort; +pub type __int32_t = crate::c_types::c_int; +pub type __uint32_t = crate::c_types::c_uint; +pub type __int64_t = crate::c_types::c_longlong; +pub type __uint64_t = crate::c_types::c_ulonglong; +pub type __int_least8_t = crate::c_types::c_schar; +pub type __uint_least8_t = crate::c_types::c_uchar; +pub type __int_least16_t = crate::c_types::c_short; +pub type __uint_least16_t = crate::c_types::c_ushort; +pub type __int_least32_t = crate::c_types::c_int; +pub type __uint_least32_t = crate::c_types::c_uint; +pub type __int_least64_t = crate::c_types::c_longlong; +pub type __uint_least64_t = crate::c_types::c_ulonglong; +pub type __intmax_t = crate::c_types::c_longlong; +pub type __uintmax_t = crate::c_types::c_ulonglong; +pub type __intptr_t = crate::c_types::c_int; +pub type __uintptr_t = crate::c_types::c_uint; pub type wchar_t = crate::c_types::c_int; #[repr(C)] #[derive(Copy, Clone)] @@ -975,6 +1089,25 @@ pub struct max_align_t { pub __clang_max_align_nonce1: crate::c_types::c_longlong, pub __clang_max_align_nonce2: f64, } +pub type intmax_t = __intmax_t; +pub type uintmax_t = __uintmax_t; +pub type int_least8_t = __int_least8_t; +pub type uint_least8_t = __uint_least8_t; +pub type int_least16_t = __int_least16_t; +pub type uint_least16_t = __uint_least16_t; +pub type int_least32_t = __int_least32_t; +pub type uint_least32_t = __uint_least32_t; +pub type int_least64_t = __int_least64_t; +pub type uint_least64_t = __uint_least64_t; +pub type int_fast8_t = crate::c_types::c_schar; +pub type uint_fast8_t = crate::c_types::c_uchar; +pub type int_fast16_t = crate::c_types::c_short; +pub type uint_fast16_t = crate::c_types::c_ushort; +pub type int_fast32_t = crate::c_types::c_int; +pub type uint_fast32_t = crate::c_types::c_uint; +pub type int_fast64_t = crate::c_types::c_longlong; +pub type uint_fast64_t = crate::c_types::c_ulonglong; +pub type mbedtls_iso_c_forbids_empty_translation_units = crate::c_types::c_int; extern "C" { /// \brief Securely zeroize a buffer /// @@ -17996,6 +18129,9 @@ pub struct mbedtls_ecdh_context { pub private_grp_id: mbedtls_ecp_group_id, ///< The ECDH implementation/structure used. pub private_var: mbedtls_ecdh_variant, + ///< Implementation-specific context. The + ///context in use is specified by the \c var + ///field. pub private_ctx: mbedtls_ecdh_context__bindgen_ty_1, } #[repr(C)] diff --git a/esp-mbedtls-sys/src/include/esp32s3.rs b/esp-mbedtls-sys/src/include/esp32s3.rs index 681c798..7a0f825 100644 --- a/esp-mbedtls-sys/src/include/esp32s3.rs +++ b/esp-mbedtls-sys/src/include/esp32s3.rs @@ -1,12 +1,5 @@ /* automatically generated by rust-bindgen 0.68.1 */ -#![allow( - non_camel_case_types, - non_snake_case, - non_upper_case_globals, - dead_code -)] - #[repr(C)] #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct __BindgenBitfieldUnit { @@ -206,7 +199,127 @@ pub const PSA_WANT_KEY_TYPE_DERIVE: u32 = 1; pub const PSA_WANT_KEY_TYPE_PASSWORD: u32 = 1; pub const PSA_WANT_KEY_TYPE_PASSWORD_HASH: u32 = 1; pub const PSA_WANT_KEY_TYPE_RAW_DATA: u32 = 1; +pub const _LIBC_LIMITS_H_: u32 = 1; +pub const __NEWLIB_H__: u32 = 1; +pub const _NEWLIB_VERSION_H__: u32 = 1; +pub const _NEWLIB_VERSION: &[u8; 6] = b"4.3.0\0"; +pub const __NEWLIB__: u32 = 4; +pub const __NEWLIB_MINOR__: u32 = 3; +pub const __NEWLIB_PATCHLEVEL__: u32 = 0; +pub const _ATEXIT_DYNAMIC_ALLOC: u32 = 1; +pub const _FSEEK_OPTIMIZATION: u32 = 1; +pub const _FVWRITE_IN_STREAMIO: u32 = 1; +pub const _HAVE_CC_INHIBIT_LOOP_TO_LIBCALL: u32 = 1; +pub const _HAVE_INITFINI_ARRAY: u32 = 1; +pub const _HAVE_LONG_DOUBLE: u32 = 1; +pub const _ICONV_ENABLED: u32 = 1; +pub const _LDBL_EQ_DBL: u32 = 1; +pub const _MB_LEN_MAX: u32 = 1; +pub const _NANO_MALLOC: u32 = 1; +pub const _REENT_CHECK_VERIFY: u32 = 1; +pub const _RETARGETABLE_LOCKING: u32 = 1; +pub const _UNBUF_STREAM_OPT: u32 = 1; +pub const _WANT_IO_C99_FORMATS: u32 = 1; +pub const _WANT_IO_LONG_LONG: u32 = 1; +pub const _WANT_IO_POS_ARGS: u32 = 1; +pub const _WANT_REENT_BACKWARD_BINARY_COMPAT: u32 = 1; +pub const _WANT_REENT_SMALL: u32 = 1; +pub const _WANT_USE_GDTOA: u32 = 1; +pub const _DEFAULT_SOURCE: u32 = 1; +pub const _POSIX_SOURCE: u32 = 1; +pub const _POSIX_C_SOURCE: u32 = 200809; +pub const _ATFILE_SOURCE: u32 = 1; +pub const __ATFILE_VISIBLE: u32 = 1; +pub const __BSD_VISIBLE: u32 = 1; +pub const __GNU_VISIBLE: u32 = 0; +pub const __ISO_C_VISIBLE: u32 = 2011; +pub const __LARGEFILE_VISIBLE: u32 = 0; +pub const __MISC_VISIBLE: u32 = 1; +pub const __POSIX_VISIBLE: u32 = 200809; +pub const __SVID_VISIBLE: u32 = 1; +pub const __XSI_VISIBLE: u32 = 0; +pub const __SSP_FORTIFY_LEVEL: u32 = 0; +pub const _POSIX_THREADS: u32 = 1; +pub const _POSIX_TIMEOUTS: u32 = 1; +pub const _POSIX_TIMERS: u32 = 1; +pub const _POSIX_MONOTONIC_CLOCK: u32 = 200112; +pub const _POSIX_CLOCK_SELECTION: u32 = 200112; +pub const _UNIX98_THREAD_MUTEX_ATTRIBUTES: u32 = 1; +pub const _POSIX_READER_WRITER_LOCKS: u32 = 200112; +pub const __have_longlong64: u32 = 1; +pub const __have_long32: u32 = 1; +pub const ___int8_t_defined: u32 = 1; +pub const ___int16_t_defined: u32 = 1; +pub const ___int32_t_defined: u32 = 1; +pub const ___int64_t_defined: u32 = 1; +pub const ___int_least8_t_defined: u32 = 1; +pub const ___int_least16_t_defined: u32 = 1; +pub const ___int_least32_t_defined: u32 = 1; +pub const ___int_least64_t_defined: u32 = 1; +pub const __GNUCLIKE_ASM: u32 = 3; +pub const __GNUCLIKE___TYPEOF: u32 = 1; +pub const __GNUCLIKE___SECTION: u32 = 1; +pub const __GNUCLIKE_CTOR_SECTION_HANDLING: u32 = 1; +pub const __GNUCLIKE_BUILTIN_CONSTANT_P: u32 = 1; +pub const __GNUCLIKE_BUILTIN_VARARGS: u32 = 1; +pub const __GNUCLIKE_BUILTIN_STDARG: u32 = 1; +pub const __GNUCLIKE_BUILTIN_VAALIST: u32 = 1; +pub const __GNUC_VA_LIST_COMPATIBILITY: u32 = 1; +pub const __GNUCLIKE_BUILTIN_NEXT_ARG: u32 = 1; +pub const __GNUCLIKE_BUILTIN_MEMCPY: u32 = 1; +pub const __CC_SUPPORTS_INLINE: u32 = 1; +pub const __CC_SUPPORTS___INLINE: u32 = 1; +pub const __CC_SUPPORTS___INLINE__: u32 = 1; +pub const __CC_SUPPORTS___FUNC__: u32 = 1; +pub const __CC_SUPPORTS_WARNING: u32 = 1; +pub const __CC_SUPPORTS_VARADIC_XXX: u32 = 1; +pub const __CC_SUPPORTS_DYNAMIC_ARRAY_INIT: u32 = 1; +pub const ARG_MAX: u32 = 65536; +pub const CHILD_MAX: u32 = 40; +pub const LINK_MAX: u32 = 32767; +pub const MAX_CANON: u32 = 255; +pub const MAX_INPUT: u32 = 255; +pub const NAME_MAX: u32 = 255; +pub const NGROUPS_MAX: u32 = 16; +pub const OPEN_MAX: u32 = 64; +pub const PATH_MAX: u32 = 1024; +pub const PIPE_BUF: u32 = 512; +pub const IOV_MAX: u32 = 1024; +pub const BC_BASE_MAX: u32 = 99; +pub const BC_DIM_MAX: u32 = 2048; +pub const BC_SCALE_MAX: u32 = 99; +pub const BC_STRING_MAX: u32 = 1000; +pub const COLL_WEIGHTS_MAX: u32 = 0; +pub const EXPR_NEST_MAX: u32 = 32; +pub const LINE_MAX: u32 = 2048; +pub const RE_DUP_MAX: u32 = 255; pub const MB_LEN_MAX: u32 = 1; +pub const NL_ARGMAX: u32 = 32; +pub const _POSIX2_RE_DUP_MAX: u32 = 255; +pub const __int20: u32 = 2; +pub const __int20__: u32 = 2; +pub const __INT8: &[u8; 3] = b"hh\0"; +pub const __INT16: &[u8; 2] = b"h\0"; +pub const __INT64: &[u8; 3] = b"ll\0"; +pub const __FAST8: &[u8; 3] = b"hh\0"; +pub const __FAST16: &[u8; 2] = b"h\0"; +pub const __FAST64: &[u8; 3] = b"ll\0"; +pub const __LEAST8: &[u8; 3] = b"hh\0"; +pub const __LEAST16: &[u8; 2] = b"h\0"; +pub const __LEAST64: &[u8; 3] = b"ll\0"; +pub const __int8_t_defined: u32 = 1; +pub const __int16_t_defined: u32 = 1; +pub const __int32_t_defined: u32 = 1; +pub const __int64_t_defined: u32 = 1; +pub const __int_least8_t_defined: u32 = 1; +pub const __int_least16_t_defined: u32 = 1; +pub const __int_least32_t_defined: u32 = 1; +pub const __int_least64_t_defined: u32 = 1; +pub const __int_fast8_t_defined: u32 = 1; +pub const __int_fast16_t_defined: u32 = 1; +pub const __int_fast32_t_defined: u32 = 1; +pub const __int_fast64_t_defined: u32 = 1; +pub const WINT_MIN: u32 = 0; pub const MBEDTLS_ERR_MPI_FILE_IO_ERROR: i32 = -2; pub const MBEDTLS_ERR_MPI_BAD_INPUT_DATA: i32 = -4; pub const MBEDTLS_ERR_MPI_INVALID_CHARACTER: i32 = -6; @@ -949,25 +1062,26 @@ pub const MBEDTLS_CTR_DRBG_MAX_SEED_INPUT: u32 = 384; pub const MBEDTLS_CTR_DRBG_PR_OFF: u32 = 0; pub const MBEDTLS_CTR_DRBG_PR_ON: u32 = 1; pub const MBEDTLS_CTR_DRBG_ENTROPY_NONCE_LEN: u32 = 0; -pub type int_least64_t = i64; -pub type uint_least64_t = u64; -pub type int_fast64_t = i64; -pub type uint_fast64_t = u64; -pub type int_least32_t = i32; -pub type uint_least32_t = u32; -pub type int_fast32_t = i32; -pub type uint_fast32_t = u32; -pub type int_least16_t = i16; -pub type uint_least16_t = u16; -pub type int_fast16_t = i16; -pub type uint_fast16_t = u16; -pub type int_least8_t = i8; -pub type uint_least8_t = u8; -pub type int_fast8_t = i8; -pub type uint_fast8_t = u8; -pub type intmax_t = crate::c_types::c_longlong; -pub type uintmax_t = crate::c_types::c_ulonglong; -pub type mbedtls_iso_c_forbids_empty_translation_units = crate::c_types::c_int; +pub type __int8_t = crate::c_types::c_schar; +pub type __uint8_t = crate::c_types::c_uchar; +pub type __int16_t = crate::c_types::c_short; +pub type __uint16_t = crate::c_types::c_ushort; +pub type __int32_t = crate::c_types::c_int; +pub type __uint32_t = crate::c_types::c_uint; +pub type __int64_t = crate::c_types::c_longlong; +pub type __uint64_t = crate::c_types::c_ulonglong; +pub type __int_least8_t = crate::c_types::c_schar; +pub type __uint_least8_t = crate::c_types::c_uchar; +pub type __int_least16_t = crate::c_types::c_short; +pub type __uint_least16_t = crate::c_types::c_ushort; +pub type __int_least32_t = crate::c_types::c_int; +pub type __uint_least32_t = crate::c_types::c_uint; +pub type __int_least64_t = crate::c_types::c_longlong; +pub type __uint_least64_t = crate::c_types::c_ulonglong; +pub type __intmax_t = crate::c_types::c_longlong; +pub type __uintmax_t = crate::c_types::c_ulonglong; +pub type __intptr_t = crate::c_types::c_int; +pub type __uintptr_t = crate::c_types::c_uint; pub type wchar_t = crate::c_types::c_int; #[repr(C)] #[derive(Copy, Clone)] @@ -975,6 +1089,25 @@ pub struct max_align_t { pub __clang_max_align_nonce1: crate::c_types::c_longlong, pub __clang_max_align_nonce2: f64, } +pub type intmax_t = __intmax_t; +pub type uintmax_t = __uintmax_t; +pub type int_least8_t = __int_least8_t; +pub type uint_least8_t = __uint_least8_t; +pub type int_least16_t = __int_least16_t; +pub type uint_least16_t = __uint_least16_t; +pub type int_least32_t = __int_least32_t; +pub type uint_least32_t = __uint_least32_t; +pub type int_least64_t = __int_least64_t; +pub type uint_least64_t = __uint_least64_t; +pub type int_fast8_t = crate::c_types::c_schar; +pub type uint_fast8_t = crate::c_types::c_uchar; +pub type int_fast16_t = crate::c_types::c_short; +pub type uint_fast16_t = crate::c_types::c_ushort; +pub type int_fast32_t = crate::c_types::c_int; +pub type uint_fast32_t = crate::c_types::c_uint; +pub type int_fast64_t = crate::c_types::c_longlong; +pub type uint_fast64_t = crate::c_types::c_ulonglong; +pub type mbedtls_iso_c_forbids_empty_translation_units = crate::c_types::c_int; extern "C" { /// \brief Securely zeroize a buffer /// @@ -17996,6 +18129,9 @@ pub struct mbedtls_ecdh_context { pub private_grp_id: mbedtls_ecp_group_id, ///< The ECDH implementation/structure used. pub private_var: mbedtls_ecdh_variant, + ///< Implementation-specific context. The + ///context in use is specified by the \c var + ///field. pub private_ctx: mbedtls_ecdh_context__bindgen_ty_1, } #[repr(C)] diff --git a/esp-mbedtls-sys/src/lib.rs b/esp-mbedtls-sys/src/lib.rs index bf1f67a..58c5ce7 100644 --- a/esp-mbedtls-sys/src/lib.rs +++ b/esp-mbedtls-sys/src/lib.rs @@ -1,9 +1,48 @@ #![no_std] -pub mod c_types; +// For `malloc`, `calloc` and `free` which are provided by `esp-wifi` on baremetal +#[cfg(any( + feature = "esp32", + feature = "esp32c3", + feature = "esp32s2", + feature = "esp32s3" +))] +use esp_wifi as _; -#[cfg_attr(feature = "esp32", path = "include/esp32.rs")] -#[cfg_attr(feature = "esp32c3", path = "include/esp32c3.rs")] -#[cfg_attr(feature = "esp32s2", path = "include/esp32s2.rs")] -#[cfg_attr(feature = "esp32s3", path = "include/esp32s3.rs")] -pub mod bindings; +#[cfg(not(target_os = "espidf"))] +mod c_types; + +#[allow( + non_camel_case_types, + non_snake_case, + non_upper_case_globals, + dead_code +)] +pub mod bindings { + #[cfg(all( + not(target_os = "espidf"), + not(any( + feature = "esp32", + feature = "esp32c3", + feature = "esp32s2", + feature = "esp32s3" + )) + ))] + include!(env!("ESP_MBEDTLS_SYS_GENERATED_BINDINGS_FILE")); + + // This and below are necessary because of https://github.com/rust-lang/cargo/issues/10358 + #[cfg(feature = "esp32")] + include!("include/esp32.rs"); + + #[cfg(feature = "esp32c3")] + include!("include/esp32c3.rs"); + + #[cfg(feature = "esp32s2")] + include!("include/esp32s2.rs"); + + #[cfg(feature = "esp32s3")] + include!("include/esp32s3.rs"); + + #[cfg(target_os = "espidf")] + pub use esp_idf_sys::*; +} diff --git a/esp-mbedtls/Cargo.toml b/esp-mbedtls/Cargo.toml index 35e3645..7c81255 100644 --- a/esp-mbedtls/Cargo.toml +++ b/esp-mbedtls/Cargo.toml @@ -2,27 +2,35 @@ name = "esp-mbedtls" version = "0.1.0" edition = "2021" -rust-version = "1.74" +license = "MIT OR Apache-2.0" +rust-version = "1.82" + +[lib] +harness = false [dependencies] esp-mbedtls-sys = { path = "../esp-mbedtls-sys" } -log = "0.4.17" +log = { version = "0.4.17", default-features = false } +enumset = { version = "1", default-features = false } embedded-io = { version = "0.6.1" } embedded-io-async = { version = "0.6.0", optional = true } -crypto-bigint = { version = "0.5.3", default-features = false, features = ["extra-sizes"] } -esp-hal = { version = "0.21.0" } +esp-hal = { version = "0.21.0", optional = true } +# For malloc/free +# TODO: Replace with `esp-alloc` once `esp-alloc` starts to provide `malloc` and `free` in future +# ... or switch to our own `mbedtls_malloc/free` +esp-wifi = { version = "0.10.1", default-features = false, optional = true } cfg-if = "1.0.0" edge-nal = { version = "0.3.0", optional = true } -edge-nal-embassy = { version = "0.3.0", optional = true } -embassy-net = { version = "0.4", features = [ "tcp", "medium-ethernet"], optional = true } critical-section = "1.1.3" +crypto-bigint = { version = "0.5.3", optional = true, default-features = false, features = ["extra-sizes"] } [features] +default = ["edge-nal"] async = ["dep:embedded-io-async"] -esp32 = ["esp-hal/esp32", "esp-mbedtls-sys/esp32"] -esp32c3 = ["esp-hal/esp32c3", "esp-mbedtls-sys/esp32c3"] -esp32s2 = ["esp-hal/esp32s2", "esp-mbedtls-sys/esp32s2"] -esp32s3 = ["esp-hal/esp32s3", "esp-mbedtls-sys/esp32s3"] +esp32 = ["esp-hal/esp32", "esp-wifi/esp32", "esp-mbedtls-sys/esp32", "crypto-bigint"] +esp32c3 = ["esp-hal/esp32c3", "esp-wifi/esp32c3", "esp-mbedtls-sys/esp32c3", "crypto-bigint"] +esp32s2 = ["esp-hal/esp32s2", "esp-wifi/esp32s2", "esp-mbedtls-sys/esp32s2", "crypto-bigint"] +esp32s3 = ["esp-hal/esp32s3", "esp-wifi/esp32s3", "esp-mbedtls-sys/esp32s3", "crypto-bigint"] # Implement the traits defined in the latest HEAD of `edge-nal` -edge-nal = ["dep:edge-nal", "dep:edge-nal-embassy", "dep:embassy-net"] +edge-nal = ["dep:edge-nal", "async"] diff --git a/esp-mbedtls/LICENSE-APACHE b/esp-mbedtls/LICENSE-APACHE new file mode 100644 index 0000000..976d1fa --- /dev/null +++ b/esp-mbedtls/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2022 esp-rs + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/esp-mbedtls/LICENSE-MIT b/esp-mbedtls/LICENSE-MIT new file mode 100644 index 0000000..898d0b5 --- /dev/null +++ b/esp-mbedtls/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 esp-rs + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/esp-mbedtls/src/compat/edge_nal_compat.rs b/esp-mbedtls/src/compat/edge_nal_compat.rs deleted file mode 100644 index ccba3f6..0000000 --- a/esp-mbedtls/src/compat/edge_nal_compat.rs +++ /dev/null @@ -1,216 +0,0 @@ -use crate::asynch::{AsyncConnectedSession, Session}; -use crate::{Certificates, Mode, Peripheral, Rsa, TlsError, TlsVersion, RSA, RSA_REF}; -use core::{ - cell::{Cell, RefCell, UnsafeCell}, - mem::MaybeUninit, - net::{Ipv4Addr, SocketAddr, SocketAddrV4}, - ops::DerefMut, - ptr::NonNull, -}; - -use crate::{hal::peripheral::PeripheralRef, SHA}; -use edge_nal::{Close, TcpBind}; - -use edge_nal_embassy::{Tcp, TcpAccept, TcpSocket}; - -pub struct TlsAcceptor< - 'd, - D: embassy_net::driver::Driver, - const N: usize, - const RX_SZ: usize, - const TX_SZ: usize, -> { - acceptor: TcpAccept<'d, D, N, TX_SZ, RX_SZ>, - version: TlsVersion, - certificates: Certificates<'d>, - owns_rsa: bool, - tls_buffers: &'d TlsBuffers, - tls_buffers_ptr: RefCell>, - sha: RefCell>, -} - -impl<'d, D, const N: usize, const RX_SZ: usize, const TX_SZ: usize> Drop - for TlsAcceptor<'d, D, N, RX_SZ, TX_SZ> -where - D: embassy_net::driver::Driver, -{ - fn drop(&mut self) { - unsafe { - // If the struct that owns the RSA reference is dropped - // we remove RSA in static for safety - if self.owns_rsa { - log::debug!("Freeing RSA from acceptor"); - RSA_REF = core::mem::transmute(None::); - } - - self.tls_buffers.pool.free(*self.tls_buffers_ptr.get_mut()); - } - } -} - -impl<'d, D, const N: usize, const RX_SZ: usize, const TX_SZ: usize> - TlsAcceptor<'d, D, N, RX_SZ, TX_SZ> -where - D: embassy_net::driver::Driver, -{ - pub async fn new( - tcp: &'d Tcp<'d, D, N, TX_SZ, RX_SZ>, - tls_buffers: &'d TlsBuffers, - port: u16, - version: TlsVersion, - certificates: Certificates<'d>, - sha: impl Peripheral

+ 'd, - ) -> Self { - let acceptor = tcp - .bind(SocketAddr::V4(SocketAddrV4::new( - Ipv4Addr::new(0, 0, 0, 0), - port, - ))) - .await - .unwrap(); - - let socket_buffers = tls_buffers.pool.alloc().unwrap(); - - Self { - acceptor, - version, - certificates, - owns_rsa: false, - tls_buffers, - tls_buffers_ptr: RefCell::new(socket_buffers), - sha: sha.into_ref().into(), - } - } - - /// Enable the use of the hardware accelerated RSA peripheral for the lifetime of - /// [TlsAcceptor]. - /// - /// # Arguments - /// - /// * `rsa` - The RSA peripheral from the HAL - pub fn with_hardware_rsa(mut self, rsa: impl Peripheral

) -> Self { - unsafe { RSA_REF = core::mem::transmute(Some(Rsa::new(rsa))) } - self.owns_rsa = true; - self - } -} - -impl<'a, T, const RX_SIZE: usize, const TX_SIZE: usize> edge_nal::Readable - for AsyncConnectedSession<'a, T, RX_SIZE, TX_SIZE> -where - T: embedded_io_async::Read + embedded_io_async::Write, -{ - async fn readable(&mut self) -> Result<(), Self::Error> { - unimplemented!(); - } -} - -impl<'a, T, const RX_SIZE: usize, const TX_SIZE: usize> edge_nal::TcpShutdown - for AsyncConnectedSession<'a, T, RX_SIZE, TX_SIZE> -where - T: embedded_io_async::Read + embedded_io_async::Write + edge_nal::TcpShutdown, - TlsError: From<::Error>, -{ - async fn close(&mut self, what: Close) -> Result<(), Self::Error> { - self.session - .stream - .close(what) - .await - .map_err(TlsError::from) - } - - async fn abort(&mut self) -> Result<(), Self::Error> { - self.session.stream.abort().await.map_err(TlsError::from) - } -} - -impl<'d, D, const N: usize, const RX_SZ: usize, const TX_SZ: usize> edge_nal::TcpAccept - for TlsAcceptor<'d, D, N, RX_SZ, TX_SZ> -where - D: embassy_net::driver::Driver, -{ - type Error = TlsError; - type Socket<'a> = AsyncConnectedSession<'a, TcpSocket<'a, N, TX_SZ, RX_SZ>, RX_SZ, TX_SZ> where Self: 'a; - - async fn accept( - &self, - ) -> Result<(SocketAddr, Self::Socket<'_>), ::Error> { - let (addr, socket) = self - .acceptor - .accept() - .await - .map_err(|e| TlsError::TcpError(e))?; - log::debug!("Accepted new connection on socket"); - - let (rx, tx) = unsafe { self.tls_buffers_ptr.borrow_mut().as_mut() }; - - let session: Session<_, RX_SZ, TX_SZ> = Session::new( - socket, - "", - Mode::Server, - self.version, - self.certificates, - rx, - tx, - self.sha.borrow_mut().reborrow().deref_mut(), - )?; - - log::debug!("Establishing SSL connection"); - let connected_session = session.connect().await?; - - Ok((addr, connected_session)) - } -} - -/// A struct that holds a pool of TLS buffers -pub struct TlsBuffers { - pool: Pool<([u8; RX_SZ], [u8; TX_SZ]), 1>, -} - -impl TlsBuffers { - /// Create a new `TlsBuffers` instance - pub const fn new() -> Self { - Self { pool: Pool::new() } - } -} - -pub(crate) struct Pool { - used: [Cell; N], - data: [UnsafeCell>; N], -} - -impl Pool { - #[allow(clippy::declare_interior_mutable_const)] - const VALUE: Cell = Cell::new(false); - const UNINIT: UnsafeCell> = UnsafeCell::new(MaybeUninit::uninit()); - - const fn new() -> Self { - Self { - used: [Self::VALUE; N], - data: [Self::UNINIT; N], - } - } -} - -impl Pool { - fn alloc(&self) -> Option> { - for n in 0..N { - // this can't race because Pool is not Sync. - if !self.used[n].get() { - self.used[n].set(true); - let p = self.data[n].get() as *mut T; - return Some(unsafe { NonNull::new_unchecked(p) }); - } - } - None - } - - /// safety: p must be a pointer obtained from self.alloc that hasn't been freed yet. - unsafe fn free(&self, p: NonNull) { - let origin = self.data.as_ptr() as *mut T; - let n = p.as_ptr().offset_from(origin); - assert!(n >= 0); - assert!((n as usize) < N); - self.used[n as usize].set(false); - } -} diff --git a/esp-mbedtls/src/compat/mod.rs b/esp-mbedtls/src/compat/mod.rs deleted file mode 100644 index d05b33c..0000000 --- a/esp-mbedtls/src/compat/mod.rs +++ /dev/null @@ -1,49 +0,0 @@ -/// Implements edge-nal traits -#[cfg(feature = "edge-nal")] -pub mod edge_nal_compat; - -#[no_mangle] -extern "C" fn rand() -> crate::c_ulong { - unsafe { crate::random() } -} - -pub struct StrBuf { - buffer: [u8; 512], - len: usize, -} - -impl StrBuf { - pub fn new() -> StrBuf { - StrBuf { - buffer: [0u8; 512], - len: 0, - } - } - - pub fn append(&mut self, s: &str) { - let mut idx: usize = self.len; - s.chars().for_each(|c| { - self.buffer[idx] = c as u8; - idx += 1; - }); - self.len = idx; - } - - pub fn append_char(&mut self, c: char) { - let mut idx: usize = self.len; - self.buffer[idx] = c as u8; - idx += 1; - self.len = idx; - } - - pub unsafe fn as_str_ref(&self) -> &str { - core::str::from_utf8_unchecked(&self.buffer[..self.len]) - } -} - -impl core::fmt::Write for StrBuf { - fn write_str(&mut self, s: &str) -> Result<(), core::fmt::Error> { - self.append(s); - Ok(()) - } -} diff --git a/esp-mbedtls/src/edge_nal.rs b/esp-mbedtls/src/edge_nal.rs new file mode 100644 index 0000000..5e6540a --- /dev/null +++ b/esp-mbedtls/src/edge_nal.rs @@ -0,0 +1,173 @@ +use core::ffi::CStr; +use core::net::SocketAddr; + +use embedded_io::Error; + +use crate::asynch::Session; +use crate::{Certificates, Mode, TlsError, TlsReference, TlsVersion}; + +/// An implementation of `edge-nal`'s `TcpAccept` trait over TLS. +pub struct TlsAcceptor<'d, T> { + acceptor: T, + min_version: TlsVersion, + certificates: Certificates<'d>, + tls_ref: TlsReference<'d>, +} + +impl<'d, T> TlsAcceptor<'d, T> +where + T: edge_nal::TcpAccept, +{ + /// Create a new instance of the `TlsAcceptor` type. + /// + /// Arguments: + /// + /// * `acceptor` - The underlying TCP acceptor + /// * `min_version` - The minimum TLS version to support + /// * `certificates` - The certificates to use for each accepted TLS connection + /// * `tls_ref` - A reference to the active `Tls` instance + pub const fn new( + acceptor: T, + min_version: TlsVersion, + certificates: Certificates<'d>, + tls_ref: TlsReference<'d>, + ) -> Self { + Self { + acceptor, + min_version, + certificates, + tls_ref, + } + } +} + +impl edge_nal::TcpAccept for TlsAcceptor<'_, T> +where + T: edge_nal::TcpAccept, +{ + type Error = TlsError; + type Socket<'a> = Session<'a, T::Socket<'a>> where Self: 'a; + + async fn accept( + &self, + ) -> Result<(SocketAddr, Self::Socket<'_>), ::Error> { + let (addr, socket) = self + .acceptor + .accept() + .await + .map_err(|e| TlsError::Io(e.kind()))?; + log::debug!("Accepted new connection on socket"); + + let session = Session::new( + socket, + Mode::Server, + self.min_version, + self.certificates, + self.tls_ref, + )?; + + Ok((addr, session)) + } +} + +/// An implementation of `edge-nal`'s `TcpConnect` trait over TLS. +pub struct TlsConnector<'d, T> { + connector: T, + servername: &'d CStr, + min_version: TlsVersion, + certificates: Certificates<'d>, + tls_ref: TlsReference<'d>, +} + +impl<'d, T> TlsConnector<'d, T> +where + T: edge_nal::TcpConnect, +{ + /// Create a new instance of the `TlsConnector` type. + /// + /// Arguments: + /// + /// * `connector` - The underlying TCP connector + /// * `servername` - The server name to check against the certificate presented by the server + /// * `min_version` - The minimum TLS version to support + /// * `certificates` - The certificates to use for each established TLS connection + /// * `tls_ref` - A reference to the active `Tls` instance + pub const fn new( + connector: T, + servername: &'d CStr, + min_version: TlsVersion, + certificates: Certificates<'d>, + tls_ref: TlsReference<'d>, + ) -> Self { + Self { + connector, + servername, + min_version, + certificates, + tls_ref, + } + } +} + +impl edge_nal::TcpConnect for TlsConnector<'_, T> +where + T: edge_nal::TcpConnect, +{ + type Error = TlsError; + + type Socket<'a> = Session<'a, T::Socket<'a>> where Self: 'a; + + async fn connect(&self, remote: SocketAddr) -> Result, Self::Error> { + let socket = self + .connector + .connect(remote) + .await + .map_err(|e| TlsError::Io(e.kind()))?; + log::debug!("Connected to {remote}"); + + let session = Session::new( + socket, + Mode::Client { + servername: self.servername, + }, + self.min_version, + self.certificates, + self.tls_ref, + )?; + + Ok(session) + } +} + +impl edge_nal::Readable for Session<'_, T> +where + T: edge_nal::Readable, +{ + async fn readable(&mut self) -> Result<(), Self::Error> { + // ... 1- because it is difficult to figure out - with the MbedTLS API - if `Session::read` would return without blocking + // For this, we need support for that in MbedTLS itself, which is not available at the moment. + // 2- because `Readable` currently throws exception with `edge-nal-embassy` + Ok(()) + } +} + +impl edge_nal::TcpShutdown for Session<'_, T> +where + T: embedded_io_async::Read + embedded_io_async::Write + edge_nal::TcpShutdown, +{ + async fn close(&mut self, what: edge_nal::Close) -> Result<(), Self::Error> { + Session::close(self).await?; + + self.stream + .close(what) + .await + .map_err(|e| TlsError::Io(e.kind())) + } + + async fn abort(&mut self) -> Result<(), Self::Error> { + self.stream + .abort() + .await + .map_err(|e| TlsError::Io(e.kind())) + } +} diff --git a/esp-mbedtls/src/esp_hal.rs b/esp-mbedtls/src/esp_hal.rs new file mode 100644 index 0000000..c688fa5 --- /dev/null +++ b/esp-mbedtls/src/esp_hal.rs @@ -0,0 +1,68 @@ +#[doc(hidden)] +use core::cell::RefCell; +use critical_section::Mutex; + +use esp_hal::peripheral::Peripheral; +use esp_hal::peripherals::{RSA, SHA}; +use esp_hal::rsa::Rsa; +use esp_hal::sha::Sha; + +use crate::{Tls, TlsError}; + +#[cfg(any(feature = "esp32c3", feature = "esp32s2", feature = "esp32s3"))] +mod bignum; +#[cfg(not(feature = "esp32"))] +mod sha; + +/// Hold the RSA peripheral for cryptographic operations. +/// +/// This is initialized when `with_hardware_rsa()` is called on a [Session] and is set back to None +/// when the session that called `with_hardware_rsa()` is dropped. +/// +/// Note: Due to implementation constraints, this session and every other session will use the +/// hardware accelerated RSA driver until the session called with this function is dropped. +static mut RSA_REF: Option> = None; + +/// Hold the SHA peripheral for cryptographic operations. +static SHARED_SHA: Mutex>>> = Mutex::new(RefCell::new(None)); + +impl<'d> Tls<'d> { + /// Create a new instance of the `Tls` type. + /// + /// Note that there could be only one active `Tls` instance at any point in time, + /// and the function will return an error if there is already an active instance. + /// + /// Arguments: + /// + /// * `sha` - The SHA peripheral from the HAL + pub fn new(sha: impl Peripheral

+ 'd) -> Result { + let this = Self::create()?; + + critical_section::with(|cs| { + SHARED_SHA + .borrow_ref_mut(cs) + .replace(unsafe { core::mem::transmute(Sha::new(sha)) }) + }); + + Ok(this) + } + + /// Enable the use of the hardware accelerated RSA peripheral for the `Tls` singleton. + /// + /// # Arguments + /// + /// * `rsa` - The RSA peripheral from the HAL + pub fn with_hardware_rsa(self, rsa: impl Peripheral

+ 'd) -> Self { + unsafe { RSA_REF = core::mem::transmute(Some(Rsa::new(rsa))) } + self + } +} + +impl Drop for Tls<'_> { + fn drop(&mut self) { + unsafe { + RSA_REF = core::mem::transmute(None::); + } + critical_section::with(|cs| SHARED_SHA.borrow_ref_mut(cs).take()); + } +} diff --git a/esp-mbedtls/src/bignum.rs b/esp-mbedtls/src/esp_hal/bignum.rs similarity index 98% rename from esp-mbedtls/src/bignum.rs rename to esp-mbedtls/src/esp_hal/bignum.rs index 9622da7..7f0d9b2 100644 --- a/esp-mbedtls/src/bignum.rs +++ b/esp-mbedtls/src/esp_hal/bignum.rs @@ -1,12 +1,15 @@ #![allow(non_snake_case)] -use crate::hal::prelude::nb; -use crate::hal::rsa::{operand_sizes, RsaModularExponentiation}; +use core::ffi::c_int; + +use esp_hal::prelude::nb; +use esp_hal::rsa::{operand_sizes, RsaModularExponentiation}; use crypto_bigint::*; use esp_mbedtls_sys::bindings::*; -use esp_mbedtls_sys::c_types::*; + +use crate::esp_hal::RSA_REF; macro_rules! error_checked { ($block:expr) => {{ @@ -47,8 +50,10 @@ const fn calculate_hw_words(words: usize) -> usize { /// Return the number of words actually used to represent an mpi number. fn mpi_words(X: &mbedtls_mpi) -> usize { for i in (0..=X.private_n).rev() { - if unsafe { X.private_p.add(i - 1).read() } != 0 { - return i; + let index = i as usize; + + if unsafe { X.private_p.add(index - 1).read() } != 0 { + return index; } } 0 @@ -118,7 +123,7 @@ pub unsafe extern "C" fn mbedtls_mpi_exp_mod( M: &mbedtls_mpi, prec_RR: *mut mbedtls_mpi, ) -> c_int { - match crate::RSA_REF { + match RSA_REF { None => return unsafe { mbedtls_mpi_exp_mod_soft(Z, X, Y, M, prec_RR) }, Some(ref mut rsa) => { let x_words = mpi_words(X); diff --git a/esp-mbedtls/src/sha/mod.rs b/esp-mbedtls/src/esp_hal/sha/mod.rs similarity index 67% rename from esp-mbedtls/src/sha/mod.rs rename to esp-mbedtls/src/esp_hal/sha/mod.rs index 9c74698..07dc6ef 100644 --- a/esp-mbedtls/src/sha/mod.rs +++ b/esp-mbedtls/src/esp_hal/sha/mod.rs @@ -1,7 +1,5 @@ -use crate::hal::{ - prelude::nb, - sha::{Context, ShaDigest}, -}; +use esp_hal::prelude::nb; +use esp_hal::sha::{Context, ShaDigest}; mod sha1; #[cfg(any(feature = "esp32s2", feature = "esp32s3"))] diff --git a/esp-mbedtls/src/sha/sha1.rs b/esp-mbedtls/src/esp_hal/sha/sha1.rs similarity index 85% rename from esp-mbedtls/src/sha/sha1.rs rename to esp-mbedtls/src/esp_hal/sha/sha1.rs index e1203a4..ea1ceaf 100644 --- a/esp-mbedtls/src/sha/sha1.rs +++ b/esp-mbedtls/src/esp_hal/sha/sha1.rs @@ -1,8 +1,12 @@ -use core::ffi::{c_int, c_uchar}; +use core::ffi::{c_int, c_uchar, c_void}; + +use esp_hal::sha::Sha1; + +use crate::esp_hal::SHARED_SHA; use super::{nb, Context, ShaDigest}; -use crate::{hal::sha::Sha1, SHARED_SHA}; +#[allow(non_camel_case_types)] #[repr(C)] pub struct mbedtls_sha1_context { hasher: *mut Context, @@ -10,8 +14,10 @@ pub struct mbedtls_sha1_context { #[no_mangle] pub unsafe extern "C" fn mbedtls_sha1_init(ctx: *mut mbedtls_sha1_context) { - let hasher_mem = - crate::calloc(1, core::mem::size_of::>() as u32) as *mut Context; + let hasher_mem = crate::aligned_calloc( + core::mem::align_of::>(), + core::mem::size_of::>(), + ) as *mut Context; core::ptr::write(hasher_mem, Context::::new()); (*ctx).hasher = hasher_mem; } @@ -19,7 +25,7 @@ pub unsafe extern "C" fn mbedtls_sha1_init(ctx: *mut mbedtls_sha1_context) { #[no_mangle] pub unsafe extern "C" fn mbedtls_sha1_free(ctx: *mut mbedtls_sha1_context) { if !ctx.is_null() && !(*ctx).hasher.is_null() { - crate::free((*ctx).hasher as *const u8); + crate::free((*ctx).hasher as *const c_void); (*ctx).hasher = core::ptr::null_mut(); } } diff --git a/esp-mbedtls/src/sha/sha256.rs b/esp-mbedtls/src/esp_hal/sha/sha256.rs similarity index 85% rename from esp-mbedtls/src/sha/sha256.rs rename to esp-mbedtls/src/esp_hal/sha/sha256.rs index 0c6848d..023641e 100644 --- a/esp-mbedtls/src/sha/sha256.rs +++ b/esp-mbedtls/src/esp_hal/sha/sha256.rs @@ -1,11 +1,12 @@ -use core::ffi::{c_int, c_uchar}; +use core::ffi::{c_int, c_uchar, c_void}; + +use esp_hal::sha::{Sha224, Sha256}; + +use crate::esp_hal::SHARED_SHA; use super::{nb, Context, ShaDigest}; -use crate::{ - hal::sha::{Sha224, Sha256}, - SHARED_SHA, -}; +#[allow(non_camel_case_types)] #[repr(C)] pub struct mbedtls_sha256_context { sha224_hasher: *mut Context, @@ -15,10 +16,14 @@ pub struct mbedtls_sha256_context { #[no_mangle] pub unsafe extern "C" fn mbedtls_sha256_init(ctx: *mut mbedtls_sha256_context) { - let sha224_mem = - crate::calloc(1, core::mem::size_of::>() as u32) as *mut Context; - let sha256_mem = - crate::calloc(1, core::mem::size_of::>() as u32) as *mut Context; + let sha224_mem = crate::aligned_calloc( + core::mem::align_of::>(), + core::mem::size_of::>(), + ) as *mut Context; + let sha256_mem = crate::aligned_calloc( + core::mem::align_of::>(), + core::mem::size_of::>(), + ) as *mut Context; (*ctx).sha224_hasher = sha224_mem; (*ctx).sha256_hasher = sha256_mem; } @@ -27,11 +32,11 @@ pub unsafe extern "C" fn mbedtls_sha256_init(ctx: *mut mbedtls_sha256_context) { pub unsafe extern "C" fn mbedtls_sha256_free(ctx: *mut mbedtls_sha256_context) { if !ctx.is_null() { if !(*ctx).sha224_hasher.is_null() { - crate::free((*ctx).sha224_hasher as *const u8); + crate::free((*ctx).sha224_hasher as *const c_void); (*ctx).sha224_hasher = core::ptr::null_mut(); } if !(*ctx).sha256_hasher.is_null() { - crate::free((*ctx).sha256_hasher as *const u8); + crate::free((*ctx).sha256_hasher as *const c_void); (*ctx).sha256_hasher = core::ptr::null_mut(); } } diff --git a/esp-mbedtls/src/sha/sha512.rs b/esp-mbedtls/src/esp_hal/sha/sha512.rs similarity index 85% rename from esp-mbedtls/src/sha/sha512.rs rename to esp-mbedtls/src/esp_hal/sha/sha512.rs index d4d0a39..e1cc4c9 100644 --- a/esp-mbedtls/src/sha/sha512.rs +++ b/esp-mbedtls/src/esp_hal/sha/sha512.rs @@ -1,11 +1,12 @@ -use core::ffi::{c_int, c_uchar}; +use core::ffi::{c_int, c_uchar, c_void}; + +use esp_hal::sha::{Sha384, Sha512}; + +use crate::esp_hal::SHARED_SHA; use super::{nb, Context, ShaDigest}; -use crate::{ - hal::sha::{Sha384, Sha512}, - SHARED_SHA, -}; +#[allow(non_camel_case_types)] #[repr(C)] pub struct mbedtls_sha512_context { sha384_hasher: *mut Context, @@ -15,10 +16,14 @@ pub struct mbedtls_sha512_context { #[no_mangle] pub unsafe extern "C" fn mbedtls_sha512_init(ctx: *mut mbedtls_sha512_context) { - let sha384_mem = - crate::calloc(1, core::mem::size_of::>() as u32) as *mut Context; - let sha512_mem = - crate::calloc(1, core::mem::size_of::>() as u32) as *mut Context; + let sha384_mem = crate::aligned_calloc( + core::mem::align_of::>(), + core::mem::size_of::>(), + ) as *mut Context; + let sha512_mem = crate::aligned_calloc( + core::mem::align_of::>(), + core::mem::size_of::>(), + ) as *mut Context; (*ctx).sha384_hasher = sha384_mem; (*ctx).sha512_hasher = sha512_mem; } @@ -27,11 +32,11 @@ pub unsafe extern "C" fn mbedtls_sha512_init(ctx: *mut mbedtls_sha512_context) { pub unsafe extern "C" fn mbedtls_sha512_free(ctx: *mut mbedtls_sha512_context) { if !ctx.is_null() { if !(*ctx).sha384_hasher.is_null() { - crate::free((*ctx).sha384_hasher as *const u8); + crate::free((*ctx).sha384_hasher as *const c_void); (*ctx).sha384_hasher = core::ptr::null_mut(); } if !(*ctx).sha512_hasher.is_null() { - crate::free((*ctx).sha512_hasher as *const u8); + crate::free((*ctx).sha512_hasher as *const c_void); (*ctx).sha512_hasher = core::ptr::null_mut(); } } diff --git a/esp-mbedtls/src/lib.rs b/esp-mbedtls/src/lib.rs index 578d4d2..fd8e358 100644 --- a/esp-mbedtls/src/lib.rs +++ b/esp-mbedtls/src/lib.rs @@ -1,67 +1,63 @@ #![no_std] -#![feature(c_variadic)] -#![allow(incomplete_features)] - -use embedded_io::ErrorType; -#[doc(hidden)] -pub use esp_hal as hal; -use hal::{ - peripheral::Peripheral, - peripherals::{RSA, SHA}, - rsa::Rsa, - sha::Sha, -}; - -mod compat; - -#[cfg(any(feature = "esp32c3", feature = "esp32s2", feature = "esp32s3"))] -mod bignum; -#[cfg(not(feature = "esp32"))] -mod sha; - -use core::cell::RefCell; -use core::ffi::CStr; + +use core::cell::Cell; +use core::ffi::{c_int, c_uchar, c_ulong, c_void, CStr}; +use core::fmt; +use core::marker::PhantomData; use core::mem::size_of; + use critical_section::Mutex; -use compat::StrBuf; +use embedded_io::{ErrorKind, ErrorType}; + +use log::Level; + use embedded_io::Read; use embedded_io::Write; + use esp_mbedtls_sys::bindings::*; -/// Re-export self-tests -pub use esp_mbedtls_sys::bindings::{ - // Bignum - mbedtls_mpi_self_test, - // RSA - mbedtls_rsa_self_test, - // SHA, - mbedtls_sha1_self_test, - mbedtls_sha224_self_test, - mbedtls_sha256_self_test, - mbedtls_sha384_self_test, - mbedtls_sha512_self_test, -}; -use esp_mbedtls_sys::c_types::*; - -/// Hold the RSA peripheral for cryptographic operations. -/// -/// This is initialized when `with_hardware_rsa()` is called on a [Session] and is set back to None -/// when the session that called `with_hardware_rsa()` is dropped. -/// -/// Note: Due to implementation constraints, this session and every other session will use the -/// hardware accelerated RSA driver until the session called with this function is dropped. -static mut RSA_REF: Option> = None; -/// Hold the SHA peripheral for cryptographic operations. -static SHARED_SHA: Mutex>>> = Mutex::new(RefCell::new(None)); +// For `malloc`, `calloc` and `free` which are provided by `esp-wifi` on baremetal +#[cfg(any( + feature = "esp32", + feature = "esp32c3", + feature = "esp32s2", + feature = "esp32s3" +))] +use esp_wifi as _; + +#[cfg(feature = "edge-nal")] +mod edge_nal; +#[cfg(any( + feature = "esp32", + feature = "esp32c3", + feature = "esp32s2", + feature = "esp32s3" +))] +mod esp_hal; + +/// Re-export of the `embedded-io` crate so that users don't have to explicitly depend on it +/// to use e.g. `write_all` or `read_exact`. +pub mod io { + pub use embedded_io::*; +} + +unsafe fn aligned_calloc(_align: usize, size: usize) -> *const c_void { + // if _align > 4 { + // panic!("Cannot allocate with alignment > 4 bytes: {_align}"); + // } -// these will come from esp-wifi (i.e. this can only be used together with esp-wifi) + calloc(1, size) +} + +// Baremetal: these will come from `esp-wifi` (i.e. this can only be used together with esp-wifi) +// STD: these will come from `libc` indirectly via the Rust standard library extern "C" { - fn free(ptr: *const u8); + fn free(ptr: *const c_void); - fn calloc(number: u32, size: u32) -> *const u8; + fn calloc(number: usize, size: usize) -> *const c_void; - fn random() -> u32; + fn random() -> c_ulong; } macro_rules! error_checked { @@ -84,68 +80,89 @@ macro_rules! error_checked { }}; } -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum Mode { - Client, +/// The mode of operation of a TLS `Session` instance +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Mode<'a> { + /// Client mode + Client { + /// The server name to check against the received server certificate. + servername: &'a CStr, + }, + /// Server mode Server, } -impl Mode { +impl Mode<'_> { fn to_mbed_tls(&self) -> i32 { match self { - Mode::Client => MBEDTLS_SSL_IS_CLIENT as i32, + Mode::Client { .. } => MBEDTLS_SSL_IS_CLIENT as i32, Mode::Server => MBEDTLS_SSL_IS_SERVER as i32, } } } -#[derive(Debug, Clone, Copy, PartialEq)] +/// The minimum TLS version that will be supported by a particular `Session` instance +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum TlsVersion { + /// TLS 1.2 Tls1_2, + /// TLS 1.3 Tls1_3, } impl TlsVersion { - fn to_mbed_tls_minor(&self) -> i32 { + fn to_mbed_tls_version(&self) -> u32 { match self { - TlsVersion::Tls1_2 => MBEDTLS_SSL_MINOR_VERSION_3 as i32, - TlsVersion::Tls1_3 => MBEDTLS_SSL_MINOR_VERSION_4 as i32, + TlsVersion::Tls1_2 => 0x303, + TlsVersion::Tls1_3 => 0x304, } } } -#[derive(Debug, Clone, Copy, PartialEq)] +/// Error type for TLS operations +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TlsError { + /// A `Tls` instance has already been created + AlreadyCreated, + /// An unknown error occurred Unknown, + /// Out of heap OutOfMemory, + /// MBedTLS error MbedTlsError(i32), + /// End of stream Eof, + /// X509 certificate missing null terminator X509MissingNullTerminator, /// The client has given no certificates for the request NoClientCertificate, - /// Errors from the edge-nal-embassy crate - #[cfg(feature = "edge-nal")] - TcpError(edge_nal_embassy::TcpError), + /// IO error + Io(ErrorKind), } -impl embedded_io::Error for TlsError { - fn kind(&self) -> embedded_io::ErrorKind { - embedded_io::ErrorKind::Other - } -} - -#[cfg(feature = "edge-nal")] -impl From for TlsError { - fn from(value: edge_nal_embassy::TcpError) -> Self { - TlsError::TcpError(value) +impl fmt::Display for TlsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::AlreadyCreated => write!(f, "TLS already created"), + Self::Unknown => write!(f, "Unknown error"), + Self::OutOfMemory => write!(f, "Out of memory"), + Self::MbedTlsError(e) => write!(f, "MbedTLS error: {e}"), + Self::Eof => write!(f, "End of stream"), + Self::X509MissingNullTerminator => { + write!(f, "X509 certificate missing null terminator") + } + Self::NoClientCertificate => write!(f, "No client certificate"), + Self::Io(e) => write!(f, "IO error: {e:?}"), + } } } -#[allow(unused)] -pub fn set_debug(level: u32) { - #[cfg(not(target_arch = "xtensa"))] - unsafe { - mbedtls_debug_set_threshold(level as c_int); +impl embedded_io::Error for TlsError { + fn kind(&self) -> embedded_io::ErrorKind { + match self { + Self::Io(e) => *e, + _ => embedded_io::ErrorKind::Other, + } } } @@ -275,20 +292,24 @@ pub struct Certificates<'a> { impl<'a> Default for Certificates<'a> { fn default() -> Self { - Self { - ca_chain: Default::default(), - certificate: Default::default(), - private_key: Default::default(), - password: Default::default(), - } + Self::new() } } impl<'a> Certificates<'a> { + /// Create a new instance of [Certificates] with no certificates whatsoever + pub const fn new() -> Self { + Self { + ca_chain: None, + certificate: None, + private_key: None, + password: None, + } + } + // Initialize the SSL using this set of certificates fn init_ssl( &self, - servername: &str, mode: Mode, min_version: TlsVersion, ) -> Result< @@ -309,31 +330,50 @@ impl<'a> Certificates<'a> { "Both certificate and private_key must be Some() or None" ); + // TODO: Allocate a lot of these things: + // - In one chunk + // - With a `Box`, which is safer + // - Consider reconfiguring mbedtls with the custom malloc/free + // callbacks that we can actually redirect to `Box` + // + // This way the lib would become completely independent from `esp-wifi` + // and would simply requre a Rust global allocator to be set. + // (Or we can even implement a mode of operation of the lib where + // it uses a fixed memory pool, and then we layer on top our own little allocator) unsafe { error_checked!(psa_crypto_init())?; - let drbg_context = calloc(1, size_of::() as u32) - as *mut mbedtls_ctr_drbg_context; + let drbg_context = aligned_calloc( + align_of::(), + size_of::(), + ) as *mut mbedtls_ctr_drbg_context; if drbg_context.is_null() { return Err(TlsError::OutOfMemory); } - let ssl_context = - calloc(1, size_of::() as u32) as *mut mbedtls_ssl_context; + let ssl_context = aligned_calloc( + align_of::(), + size_of::(), + ) as *mut mbedtls_ssl_context; if ssl_context.is_null() { free(drbg_context as *const _); return Err(TlsError::OutOfMemory); } - let ssl_config = - calloc(1, size_of::() as u32) as *mut mbedtls_ssl_config; + let ssl_config = aligned_calloc( + align_of::(), + size_of::(), + ) as *mut mbedtls_ssl_config; if ssl_config.is_null() { free(drbg_context as *const _); free(ssl_context as *const _); return Err(TlsError::OutOfMemory); } - let crt = calloc(1, size_of::() as u32) as *mut mbedtls_x509_crt; + let crt = aligned_calloc( + align_of::(), + size_of::(), + ) as *mut mbedtls_x509_crt; if crt.is_null() { free(drbg_context as *const _); free(ssl_context as *const _); @@ -341,8 +381,10 @@ impl<'a> Certificates<'a> { return Err(TlsError::OutOfMemory); } - let certificate = - calloc(1, size_of::() as u32) as *mut mbedtls_x509_crt; + let certificate = aligned_calloc( + align_of::(), + size_of::(), + ) as *mut mbedtls_x509_crt; if certificate.is_null() { free(drbg_context as *const _); free(ssl_context as *const _); @@ -351,8 +393,10 @@ impl<'a> Certificates<'a> { return Err(TlsError::OutOfMemory); } - let private_key = - calloc(1, size_of::() as u32) as *mut mbedtls_pk_context; + let private_key = aligned_calloc( + align_of::(), + size_of::(), + ) as *mut mbedtls_pk_context; if private_key.is_null() { free(drbg_context as *const _); free(ssl_context as *const _); @@ -370,13 +414,17 @@ impl<'a> Certificates<'a> { mbedtls_x509_crt_init(certificate); // Initialize private key mbedtls_pk_init(private_key); - (*ssl_config).private_f_dbg = Some(dbg_print); - // Init RNG + + //(*ssl_config).private_f_dbg = Some(dbg_print); + mbedtls_ssl_conf_dbg(ssl_config, Some(dbg_print), core::ptr::null_mut()); + mbedtls_ctr_drbg_init(drbg_context); + + // Init RNG mbedtls_ssl_conf_rng(ssl_config, Some(rng), drbg_context as *mut c_void); // Closure to free all allocated resources in case of an error. - let cleanup = || { + let cleanup = move || { mbedtls_ctr_drbg_free(drbg_context); mbedtls_ssl_config_free(ssl_config); mbedtls_ssl_free(ssl_context); @@ -401,11 +449,9 @@ impl<'a> Certificates<'a> { cleanup )?; - mbedtls_ssl_conf_min_version( - ssl_config, - MBEDTLS_SSL_MAJOR_VERSION_3 as i32, - min_version.to_mbed_tls_minor(), - ); + // Set the minimum TLS version + // Use a ddirect field modified for compatibility with the `esp-idf-svc` mbedtls + (*ssl_config).private_min_tls_version = min_version.to_mbed_tls_version(); mbedtls_ssl_conf_authmode( ssl_config, @@ -418,15 +464,9 @@ impl<'a> Certificates<'a> { }, ); - if mode == Mode::Client { - let mut hostname = StrBuf::new(); - hostname.append(servername); - hostname.append_char('\0'); + if let Mode::Client { servername } = mode { error_checked!( - mbedtls_ssl_set_hostname( - ssl_context, - hostname.as_str_ref().as_ptr() as *const c_char - ), + mbedtls_ssl_set_hostname(ssl_context, servername.as_ptr(),), cleanup )?; } @@ -495,7 +535,138 @@ impl<'a> Certificates<'a> { } } -pub struct Session { +/// A TLS self-test type +#[derive(enumset::EnumSetType, Debug)] +pub enum TlsTest { + Mpi, + Rsa, + Sha1, + Sha224, + Sha256, + Sha384, + Sha512, + Aes, + Md5, +} + +impl fmt::Display for TlsTest { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + TlsTest::Mpi => write!(f, "MPI"), + TlsTest::Rsa => write!(f, "RSA"), + TlsTest::Sha1 => write!(f, "SHA1"), + TlsTest::Sha224 => write!(f, "SHA224"), + TlsTest::Sha256 => write!(f, "SHA256"), + TlsTest::Sha384 => write!(f, "SHA384"), + TlsTest::Sha512 => write!(f, "SHA512"), + TlsTest::Aes => write!(f, "AES"), + TlsTest::Md5 => write!(f, "MD5"), + } + } +} + +static TLS_CREATED: Mutex> = Mutex::new(Cell::new(false)); + +/// A TLS instance +/// +/// Represents an instance of the MbedTLS library. +/// Only one such instance can be active at any point in time. +pub struct Tls<'d>(PhantomData<&'d mut ()>); + +impl<'d> Tls<'d> { + /// Create a new instance of the `Tls` type. + /// + /// Note that there could be only one active `Tls` instance at any point in time, + /// and the function will return an error if there is already an active instance. + #[cfg(not(any( + feature = "esp32", + feature = "esp32c3", + feature = "esp32s2", + feature = "esp32s3" + )))] + pub fn new() -> Result { + Self::create() + } + + pub(crate) fn create() -> Result { + critical_section::with(|cs| { + let created = TLS_CREATED.borrow(cs).get(); + + if created { + return Err(TlsError::AlreadyCreated); + } + + TLS_CREATED.borrow(cs).set(true); + + Ok(Self(PhantomData)) + }) + } + + /// Set the MbedTLS debug level (0 - 5) + #[allow(unused)] + pub fn set_debug(&mut self, level: u32) { + #[cfg(not(target_os = "espidf"))] + unsafe { + mbedtls_debug_set_threshold(level as c_int); + } + } + + /// Run a self-test on the MbedTLS library + /// + /// # Arguments + /// + /// * `test` - The test to run + /// * `verbose` - Whether to run the test in verbose mode + pub fn self_test(&mut self, test: TlsTest, verbose: bool) -> bool { + let verbose = verbose as _; + + let result = unsafe { + match test { + TlsTest::Mpi => mbedtls_mpi_self_test(verbose), + TlsTest::Rsa => mbedtls_rsa_self_test(verbose), + TlsTest::Sha1 => mbedtls_sha1_self_test(verbose), + TlsTest::Sha224 => mbedtls_sha224_self_test(verbose), + TlsTest::Sha256 => mbedtls_sha256_self_test(verbose), + TlsTest::Sha384 => mbedtls_sha384_self_test(verbose), + TlsTest::Sha512 => mbedtls_sha512_self_test(verbose), + TlsTest::Aes => mbedtls_aes_self_test(verbose), + TlsTest::Md5 => mbedtls_md5_self_test(verbose), + } + }; + + result != 0 + } + + /// Get a reference to the `Tls` instance + /// + /// Each `Session` needs a reference to (the) active `Tls` instance + /// throughout its lifetime. + pub fn reference(&self) -> TlsReference<'_> { + TlsReference(PhantomData) + } +} + +/// A reference to (the) active `Tls` instance +/// +/// Used instead of just `&'a Tls` so that the invariant `'d` lifetime of the `Tls` instance +/// is not exposed in the `Session` type. +#[allow(unused)] +#[derive(Debug, Copy, Clone)] +pub struct TlsReference<'a>(PhantomData<&'a ()>); + +/// A TLS session state +#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] +enum SessionState { + /// Initial state (TLS handshake not started yet) + Initial, + /// Handshake complete + Connected, + /// End of stream reached + Eof, +} + +/// A blocking TLS session over a stream represented by `embedded-io`'s `Read` and `Write` traits. +pub struct Session<'a, T> { stream: T, drbg_context: *mut mbedtls_ctr_drbg_context, ssl_context: *mut mbedtls_ssl_context, @@ -503,22 +674,22 @@ pub struct Session { crt: *mut mbedtls_x509_crt, client_crt: *mut mbedtls_x509_crt, private_key: *mut mbedtls_pk_context, - // Indicate if this session is the one holding the RSA ref - owns_rsa: bool, + state: SessionState, + _tls_ref: TlsReference<'a>, } -impl Session { +impl<'a, T> Session<'a, T> { /// Create a session for a TLS stream. /// /// # Arguments /// /// * `stream` - The stream for the connection. - /// * `servername` - The hostname to check against the received server certificate. It sets the ServerName TLS extension, too, if that extension is enabled. (client-side only) /// * `mode` - Use [Mode::Client] if you are running a client. [Mode::Server] if you are - /// running a server. + /// running a server. /// * `min_version` - The minimum TLS version for the connection, that will be accepted. /// * `certificates` - Certificate chain for the connection. Will play a different role - /// depending on if running as client or server. See [Certificates] for more information. + /// depending on if running as client or server. See [Certificates] for more information. + /// * `tls_ref` - A reference to the active `Tls` instance. /// /// # Errors /// @@ -527,20 +698,13 @@ impl Session { /// invalid format. pub fn new( stream: T, - servername: &str, mode: Mode, min_version: TlsVersion, certificates: Certificates, - sha: impl Peripheral

, + tls_ref: TlsReference<'a>, ) -> Result { - critical_section::with(|cs| { - SHARED_SHA - .borrow_ref_mut(cs) - .replace(unsafe { core::mem::transmute(Sha::new(sha)) }) - }); - let (drbg_context, ssl_context, ssl_config, crt, client_crt, private_key) = - certificates.init_ssl(servername, mode, min_version)?; + certificates.init_ssl(mode, min_version)?; return Ok(Self { stream, drbg_context, @@ -549,34 +713,33 @@ impl Session { crt, client_crt, private_key, - owns_rsa: false, + state: SessionState::Initial, + _tls_ref: tls_ref, }); } - - /// Enable the use of the hardware accelerated RSA peripheral for the [Session]. - /// - /// Note: Due to implementation constraints, this session and every other session will use the - /// hardware accelerated RSA driver until the session called with this function is dropped. - /// - /// # Arguments - /// - /// * `rsa` - The RSA peripheral from the HAL - pub fn with_hardware_rsa(mut self, rsa: impl Peripheral

) -> Self { - unsafe { RSA_REF = core::mem::transmute(Some(Rsa::new(rsa))) } - self.owns_rsa = true; - self - } } -impl Session +impl<'a, T> Session<'a, T> where T: Read + Write, { - pub fn connect<'b>(self) -> Result, TlsError> { + /// Negotiate the TLS connection + /// + /// This function will perform the TLS handshake with the server. + /// + /// Note that calling it is not mandatory, because the TLS session is anyway + /// negotiated during the first read or write operation. + pub fn connect(&mut self) -> Result<(), TlsError> { + if matches!(self.state, SessionState::Connected) { + return Ok(()); + } else if matches!(self.state, SessionState::Eof) { + return Err(TlsError::Eof); + } + unsafe { mbedtls_ssl_set_bio( self.ssl_context, - core::ptr::addr_of!(self) as *mut c_void, + self as *mut _ as *mut c_void, Some(Self::send), Some(Self::receive), None, @@ -584,15 +747,19 @@ where loop { let res = mbedtls_ssl_handshake(self.ssl_context); + log::debug!("mbedtls_ssl_handshake: {res:x}"); if res == 0 { // success break; } if res < 0 && res != MBEDTLS_ERR_SSL_WANT_READ && res != MBEDTLS_ERR_SSL_WANT_WRITE + // See https://github.com/Mbed-TLS/mbedtls/issues/8749 + && res != MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET { // real error // Reference: https://os.mbed.com/teams/sandbox/code/mbedtls/docs/tip/ssl_8h.html#a4a37e497cd08c896870a42b1b618186e mbedtls_ssl_session_reset(self.ssl_context); + #[allow(non_snake_case)] return Err(match res { MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE => TlsError::NoClientCertificate, _ => TlsError::MbedTlsError(res), @@ -602,10 +769,75 @@ where // try again immediately } - Ok(ConnectedSession { session: self }) + self.state = SessionState::Connected; + + Ok(()) + } + } + + /// Read unencrypted data from the TLS connection + /// + /// # Arguments + /// + /// * `buf` - The buffer to read the data into + /// + /// # Returns + /// + /// The number of bytes read or an error + pub fn read(&mut self, buf: &mut [u8]) -> Result { + self.connect()?; + + loop { + let res = self.internal_read(buf); + #[allow(non_snake_case)] + match res { + // See https://github.com/Mbed-TLS/mbedtls/issues/8749 + MBEDTLS_ERR_SSL_WANT_READ | MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET => continue, // no data + 0_i32..=i32::MAX => return Ok(res as usize), // data + i32::MIN..=-1_i32 => return Err(TlsError::MbedTlsError(res)), // error + } + } + } + + /// Write unencrypted data to the TLS connection + /// + /// Arguments: + /// + /// * `data` - The data to write + /// + /// Returns: + /// + /// The number of bytes written or an error + pub fn write(&mut self, data: &[u8]) -> Result { + self.connect()?; + + loop { + let res = self.internal_write(data); + #[allow(non_snake_case)] + match res { + // See https://github.com/Mbed-TLS/mbedtls/issues/8749 + MBEDTLS_ERR_SSL_WANT_WRITE | MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET => { + continue + } // no data + 0_i32..=i32::MAX => return Ok(res as usize), // data + i32::MIN..=-1_i32 => return Err(TlsError::MbedTlsError(res)), // error + } } } + /// Flush the TLS connection + /// + /// This function will flush the TLS connection, ensuring that all data is sent. + /// + /// Returns: + /// + /// An error if the flush failed + pub fn flush(&mut self) -> Result<(), TlsError> { + self.connect()?; + + self.stream.flush().map_err(|_| TlsError::Unknown) + } + fn internal_write(&mut self, buf: &[u8]) -> i32 { unsafe { mbedtls_ssl_set_bio( @@ -671,16 +903,10 @@ where } } -impl Drop for Session { +impl Drop for Session<'_, T> { fn drop(&mut self) { log::debug!("session dropped - freeing memory"); unsafe { - // If the struct that owns the RSA reference is dropped - // we remove RSA in static for safety - if self.owns_rsa { - RSA_REF = core::mem::transmute(None::); - } - critical_section::with(|cs| SHARED_SHA.borrow_ref_mut(cs).take()); mbedtls_ssl_close_notify(self.ssl_context); mbedtls_ctr_drbg_free(self.drbg_context); mbedtls_ssl_config_free(self.ssl_config); @@ -698,59 +924,63 @@ impl Drop for Session { } } -pub struct ConnectedSession -where - T: Read + Write, -{ - session: Session, -} - -impl ErrorType for ConnectedSession +impl ErrorType for Session<'_, T> where T: Read + Write, { type Error = TlsError; } -impl Read for ConnectedSession +impl Read for Session<'_, T> where T: Read + Write, { fn read(&mut self, buf: &mut [u8]) -> Result { - loop { - let res = self.session.internal_read(buf); - match res { - MBEDTLS_ERR_SSL_WANT_READ | MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET => continue, // no data - 0_i32..=i32::MAX => return Ok(res as usize), // data - i32::MIN..=-1_i32 => return Err(TlsError::MbedTlsError(res)), // error - } - } + Session::read(self, buf) } } -impl Write for ConnectedSession +impl Write for Session<'_, T> where T: Read + Write, { fn write(&mut self, buf: &[u8]) -> Result { - let res = self.session.internal_write(buf); - Ok(res as usize) + Session::write(self, buf) } fn flush(&mut self) -> Result<(), Self::Error> { - self.session.stream.flush().map_err(|_| TlsError::Unknown) + Session::flush(self) } } #[cfg(feature = "async")] pub mod asynch { + use core::future::Future; + use core::pin::pin; + use core::task::{Context, Poll}; + + use embedded_io::Error; + use super::*; - /// Implements edge-nal traits + /// Re-export of the `embedded-io-async` crate so that users don't have to explicitly depend on it + /// to use e.g. `write_all` or `read_exact`. + pub mod io { + pub use embedded_io_async::*; + } + + /// Re-export of the `edge-nal` crate so that users don't have to explicitly depend on it + /// to use e.g. `TlsAccept` and `TlsConnect` methods. + #[cfg(feature = "edge-nal")] + pub mod nal { + pub use crate::edge_nal::*; + } + #[cfg(feature = "edge-nal")] - pub use crate::compat::edge_nal_compat::*; + pub use super::edge_nal::*; - pub struct Session<'a, T, const RX_SIZE: usize = 4096, const TX_SIZE: usize = 4096> { + /// An async TLS session over a stream represented by `embedded-io-async`'s `Read` and `Write` traits. + pub struct Session<'a, T> { pub(crate) stream: T, drbg_context: *mut mbedtls_ctr_drbg_context, ssl_context: *mut mbedtls_ssl_context, @@ -758,24 +988,24 @@ pub mod asynch { crt: *mut mbedtls_x509_crt, client_crt: *mut mbedtls_x509_crt, private_key: *mut mbedtls_pk_context, - eof: bool, - rx_buffer: BufferedBytes<'a, RX_SIZE>, - tx_buffer: BufferedBytes<'a, TX_SIZE>, - owns_rsa: bool, + state: SessionState, + read_byte: Option, + write_byte: Option, + _token: TlsReference<'a>, } - impl<'a, T, const RX_SIZE: usize, const TX_SIZE: usize> Session<'a, T, RX_SIZE, TX_SIZE> { + impl<'a, T> Session<'a, T> { /// Create a session for a TLS stream. /// /// # Arguments /// /// * `stream` - The stream for the connection. - /// * `servername` - The hostname to check against the received server certificate. It sets the ServerName TLS extension, too, if that extension is enabled. (client-side only) /// * `mode` - Use [Mode::Client] if you are running a client. [Mode::Server] if you are - /// running a server. + /// running a server. /// * `min_version` - The minimum TLS version for the connection, that will be accepted. /// * `certificates` - Certificate chain for the connection. Will play a different role - /// depending on if running as client or server. See [Certificates] for more information. + /// depending on if running as client or server. See [Certificates] for more information. + /// * `tls_ref` - A reference to the active `Tls` instance. /// /// # Errors /// @@ -784,23 +1014,13 @@ pub mod asynch { /// invalid format. pub fn new( stream: T, - servername: &str, mode: Mode, min_version: TlsVersion, certificates: Certificates, - - rx_buffer: &'a mut [u8; RX_SIZE], - tx_buffer: &'a mut [u8; TX_SIZE], - sha: impl Peripheral

, + tls_ref: TlsReference<'a>, ) -> Result { - critical_section::with(|cs| { - SHARED_SHA - .borrow_ref_mut(cs) - .replace(unsafe { core::mem::transmute(Sha::new(sha)) }) - }); - let (drbg_context, ssl_context, ssl_config, crt, client_crt, private_key) = - certificates.init_ssl(servername, mode, min_version)?; + certificates.init_ssl(mode, min_version)?; return Ok(Self { stream, drbg_context, @@ -809,38 +1029,18 @@ pub mod asynch { crt, client_crt, private_key, - eof: false, - rx_buffer: BufferedBytes::new(rx_buffer), - tx_buffer: BufferedBytes::new(tx_buffer), - owns_rsa: false, + state: SessionState::Initial, + read_byte: None, + write_byte: None, + _token: tls_ref, }); } - - /// Enable the use of the hardware accelerated RSA peripheral for the [Session]. - /// - /// Note: Due to implementation constraints, this session and every other session will use the - /// hardware accelerated RSA driver until the session called with this function is dropped. - /// - /// # Arguments - /// - /// * `rsa` - The RSA peripheral from the HAL - pub fn with_hardware_rsa(mut self, rsa: impl Peripheral

) -> Self { - unsafe { RSA_REF = core::mem::transmute(Some(Rsa::new(rsa))) } - self.owns_rsa = true; - self - } } - impl Drop for Session<'_, T, RX_SIZE, TX_SIZE> { + impl Drop for Session<'_, T> { fn drop(&mut self) { log::debug!("session dropped - freeing memory"); unsafe { - // If the struct that owns the RSA reference is dropped - // we remove RSA in static for safety - if self.owns_rsa { - RSA_REF = core::mem::transmute(None::); - } - critical_section::with(|cs| SHARED_SHA.borrow_ref_mut(cs).take()); mbedtls_ssl_close_notify(self.ssl_context); mbedtls_ctr_drbg_free(self.drbg_context); mbedtls_ssl_config_free(self.ssl_config); @@ -858,337 +1058,467 @@ pub mod asynch { } } - impl<'a, T, const RX_SIZE: usize, const TX_SIZE: usize> Session<'a, T, RX_SIZE, TX_SIZE> + impl<'a, T> Session<'a, T> where T: embedded_io_async::Read + embedded_io_async::Write, { - pub async fn connect( - mut self, - ) -> Result, TlsError> { - unsafe { - mbedtls_ssl_set_bio( - self.ssl_context, - core::ptr::addr_of!(self) as *mut c_void, - Some(Self::sync_send), - Some(Self::sync_receive), - None, - ); - - loop { - let res = mbedtls_ssl_handshake(self.ssl_context); - log::debug!("mbedtls_ssl_handshake: {res}"); - if res == 0 { - // success - break; + /// Negotiate the TLS connection + /// + /// This function will perform the TLS handshake with the server. + /// + /// Note that calling it is not mandatory, because the TLS session is anyway + /// negotiated during the first read or write operation. + pub async fn connect(&mut self) -> Result<(), TlsError> { + match self.state { + SessionState::Initial => { + log::debug!("Establishing SSL connection"); + + self.io(|ssl| unsafe { mbedtls_ssl_handshake(ssl) }).await?; + if matches!(self.state, SessionState::Eof) { + return Err(TlsError::Eof); } - if res < 0 - && res != MBEDTLS_ERR_SSL_WANT_READ - && res != MBEDTLS_ERR_SSL_WANT_WRITE - { - // real error - // Reference: https://os.mbed.com/teams/sandbox/code/mbedtls/docs/tip/ssl_8h.html#a4a37e497cd08c896870a42b1b618186e - mbedtls_ssl_session_reset(self.ssl_context); - return Err(match res { - MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE => TlsError::NoClientCertificate, - _ => TlsError::MbedTlsError(res), - }); - } else { - if !self.tx_buffer.empty() { - log::debug!("Having data to send to stream"); - let data = self.tx_buffer.pull(TX_SIZE); - log::debug!( - "pulled {} bytes from tx_buffer ... send to stream", - data.len() - ); - self.stream - .write(data) - .await - .map_err(|_| TlsError::Unknown)?; - } - if res == MBEDTLS_ERR_SSL_WANT_READ { - let mut buf = [0u8; RX_SIZE]; - let res = self - .stream - .read(&mut buf[..self.rx_buffer.remaining()]) - .await - .map_err(|_| TlsError::Unknown)?; - if res > 0 { - log::debug!("push {} bytes to rx-buffer", res); - self.rx_buffer.push(&buf[..res]).ok(); - } - } - } - } - self.drain_tx_buffer().await?; + self.state = SessionState::Connected; - Ok(AsyncConnectedSession { session: self }) + Ok(()) + } + SessionState::Connected => Ok(()), + SessionState::Eof => Err(TlsError::Eof), } } - async fn drain_tx_buffer(&mut self) -> Result<(), TlsError> { - unsafe { - mbedtls_ssl_set_bio( - self.ssl_context, - self as *mut _ as *mut c_void, - Some(Self::sync_send), - Some(Self::sync_receive), - None, - ); - if !self.tx_buffer.empty() { - log::debug!("Drain tx buffer"); - let data = self.tx_buffer.pull(TX_SIZE); - log::debug!( - "pulled {} bytes from tx_buffer ... send to stream", - data.len() - ); - log::debug!("{:02x?}", &data); - let res = self - .stream - .write(data) - .await - .map_err(|_| TlsError::Unknown)?; - log::debug!("wrote {res} bytes to stream"); - self.stream.flush().await.map_err(|_| TlsError::Unknown)?; - } - } + /// Read unencrypted data from the TLS connection + /// + /// # Arguments + /// + /// * `buf` - The buffer to read the data into + /// + /// # Returns + /// + /// The number of bytes read or an error + pub async fn read(&mut self, buf: &mut [u8]) -> Result { + self.connect().await?; - Ok(()) + let len = self + .io(|ssl| unsafe { + mbedtls_ssl_read(ssl, buf.as_mut_ptr() as *mut _, buf.len() as _) + }) + .await?; + + Ok(len as _) } - async fn async_internal_write(&mut self, buf: &[u8]) -> Result { - unsafe { - mbedtls_ssl_set_bio( - self.ssl_context, - self as *mut _ as *mut c_void, - Some(Self::sync_send), - Some(Self::sync_receive), - None, - ); - self.drain_tx_buffer().await?; + /// Write unencrypted data to the TLS connection + /// + /// Arguments: + /// + /// * `data` - The data to write + /// + /// Returns: + /// + /// The number of bytes written or an error + pub async fn write(&mut self, data: &[u8]) -> Result { + self.connect().await?; - let len = mbedtls_ssl_write(self.ssl_context, buf.as_ptr(), buf.len()); - self.drain_tx_buffer().await?; + let len = self + .io(|ssl| unsafe { + mbedtls_ssl_write(ssl, data.as_ptr() as *const _, data.len() as _) + }) + .await?; - Ok(len) - } + Ok(len as _) } - async fn async_internal_read(&mut self, buf: &mut [u8]) -> Result { - unsafe { - mbedtls_ssl_set_bio( - self.ssl_context, - self as *mut _ as *mut c_void, - Some(Self::sync_send), - Some(Self::sync_receive), - None, - ); - self.drain_tx_buffer().await?; - - if !self.rx_buffer.can_read() && mbedtls_ssl_check_pending(self.ssl_context) == 0 { - let mut buffer = [0u8; RX_SIZE]; - let from_socket = self - .stream - .read(&mut buffer[..self.rx_buffer.remaining()]) - .await - .map_err(|_| TlsError::Unknown)?; - if from_socket > 0 { - log::debug!("<<< got {} bytes from socket", from_socket); - self.rx_buffer.push(&buffer[..from_socket]).ok(); - } else { - // the socket is in EOF state but there might be still data to process - self.eof = true; - } - } + /// Flush the TLS connection + /// + /// This function will flush the TLS connection, ensuring that all data is sent. + /// + /// Returns: + /// + /// An error if the flush failed + pub async fn flush(&mut self) -> Result<(), TlsError> { + self.connect().await?; - if !self.rx_buffer.empty() - || mbedtls_ssl_check_pending(self.ssl_context) == 1 - || mbedtls_ssl_get_bytes_avail(self.ssl_context) > 0 - { - log::debug!("<<< read data from mbedtls"); - let res = mbedtls_ssl_read(self.ssl_context, buf.as_mut_ptr(), buf.len()); - log::debug!("<<< mbedtls returned {res}"); + self.flush_write().await?; + self.stream + .flush() + .await + .map_err(|e| TlsError::Io(e.kind()))?; - if res == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY { - self.eof = true; - return Ok(0); - } - Ok(res) - } else { - Ok(0) - } - } + Ok(()) } - unsafe extern "C" fn sync_send(ctx: *mut c_void, buf: *const c_uchar, len: usize) -> c_int { - log::debug!("*** sync send called, bytes={len}"); - let session = ctx as *mut Session; - let slice = core::ptr::slice_from_raw_parts( - buf as *const u8, - usize::min(len as usize, (*session).tx_buffer.remaining()), - ); - (*session).tx_buffer.push(&*slice).ok(); - let written = (&*slice).len(); - log::debug!("*** put {} bytes into tx_buffer", written); + /// Close the TLS connection + /// + /// This function will close the TLS connection, sending the TLS "close notify" info the the peer. + /// + /// Returns: + /// + /// An error if the close failed + pub async fn close(&mut self) -> Result<(), TlsError> { + self.connect().await?; - if written == 0 { - MBEDTLS_ERR_SSL_WANT_WRITE - } else { - written as c_int - } + self.io(|ssl| unsafe { mbedtls_ssl_close_notify(ssl) }) + .await?; + self.flush().await?; + + self.state = SessionState::Eof; + + Ok(()) } - unsafe extern "C" fn sync_receive( - ctx: *mut c_void, - buf: *mut c_uchar, - len: usize, - ) -> c_int { - log::debug!("*** sync rcv, len={}", len); - let session = ctx as *mut Session; - - if (*session).rx_buffer.empty() { - log::debug!("*** buffer empty - want read"); - return MBEDTLS_ERR_SSL_WANT_READ; + /// Perform an async IO operation on the TLS connection, by calling the + /// provided MbedTLS function. + /// + /// The MbedTLS function is usually either `mbedtls_ssl_read`, `mbedtls_ssl_write` or `mbedtls_ssl_handshake`. + async fn io(&mut self, mut f: F) -> Result + where + F: FnMut(*mut mbedtls_ssl_context) -> i32, + { + loop { + let outcome = + core::future::poll_fn(|cx| PollCtx::poll(self, cx, |ssl| f(ssl))).await?; + + self.flush_write().await?; + + match outcome { + PollOutcome::Success(res) => break Ok(res), + PollOutcome::Retry => continue, + PollOutcome::WantRead => self.wait_read().await?, + PollOutcome::WantWrite => self.flush_write().await?, + PollOutcome::Eof => { + self.state = SessionState::Eof; + break Ok(0); + } + } } + } - let buffer = core::slice::from_raw_parts_mut(buf as *mut u8, len as usize); - let max_len = usize::min(len as usize, (*session).rx_buffer.remaining()); - let data = (*session).rx_buffer.pull(max_len); - buffer[0..data.len()].copy_from_slice(data); + /// Wait for the stream to be readable + /// + /// Since the `Session` is implemented purely with the `Read` trait, this method + /// will read a single byte from the stream, so that the `Read` trait can be polled + async fn wait_read(&mut self) -> Result<(), TlsError> { + if self.read_byte.is_none() { + let mut buf = [0]; + + let len = self + .stream + .read(&mut buf) + .await + .map_err(|e| TlsError::Io(e.kind()))?; + if len > 0 { + self.read_byte = Some(buf[0]); + } + } - log::debug!("*** pulled {} bytes from rx-buffer", data.len()); + Ok(()) + } - if data.len() == 0 { - MBEDTLS_ERR_SSL_WANT_READ - } else { - data.len() as c_int + /// Wait for the stream to be writable + /// + /// Since the `Session` is implemented purely with the `Write` trait, this method + /// will write a single byte to the stream (provided by the "mbio" MbedTLS callbacks), + /// so that the `Write` trait can be polled + async fn flush_write(&mut self) -> Result<(), TlsError> { + if let Some(byte) = self.write_byte.as_ref().copied() { + let data = [byte]; + let len = self + .stream + .write(&data) + .await + .map_err(|e| TlsError::Io(e.kind()))?; + if len > 0 { + self.write_byte.take(); + } } - } - } - pub struct AsyncConnectedSession<'a, T, const RX_SIZE: usize, const TX_SIZE: usize> - where - T: embedded_io_async::Read + embedded_io_async::Write, - { - pub(crate) session: Session<'a, T, RX_SIZE, TX_SIZE>, + Ok(()) + } } - impl embedded_io_async::ErrorType - for AsyncConnectedSession<'_, T, RX_SIZE, TX_SIZE> + impl embedded_io_async::ErrorType for Session<'_, T> where - T: embedded_io_async::Read + embedded_io_async::Write, + T: embedded_io_async::ErrorType, { type Error = TlsError; } - impl embedded_io_async::Read - for AsyncConnectedSession<'_, T, RX_SIZE, TX_SIZE> + impl embedded_io_async::Read for Session<'_, T> where T: embedded_io_async::Read + embedded_io_async::Write, { async fn read(&mut self, buf: &mut [u8]) -> Result { - log::debug!("async read called"); - loop { - if self.session.eof && self.session.rx_buffer.empty() { - return Err(TlsError::Eof); - } - let res = self.session.async_internal_read(buf).await?; - match res { - MBEDTLS_ERR_SSL_WANT_READ | MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET => { - continue - } // no data - 0..=i32::MAX => return Ok(res as usize), // data - i32::MIN..=-1_i32 => return Err(TlsError::MbedTlsError(res)), // error - } - } + self.read(buf).await } } - impl embedded_io_async::Write - for AsyncConnectedSession<'_, T, RX_SIZE, TX_SIZE> + impl embedded_io_async::Write for Session<'_, T> where T: embedded_io_async::Read + embedded_io_async::Write, { async fn write(&mut self, buf: &[u8]) -> Result { - let res = self.session.async_internal_write(buf).await?; - Ok(res as usize) + self.write(buf).await } async fn flush(&mut self) -> Result<(), Self::Error> { - self.session - .drain_tx_buffer() - .await - .map_err(|_| TlsError::Unknown)?; - - self.session - .stream - .flush() - .await - .map_err(|_| TlsError::Unknown) + self.flush().await } } - pub(crate) struct BufferedBytes<'a, const BUFFER_SIZE: usize> { - buffer: &'a mut [u8; BUFFER_SIZE], - write_idx: usize, - read_idx: usize, + + /// Poll outcome for the `PollCtx` type + #[derive(Copy, Clone, Debug)] + pub enum PollOutcome { + /// The operation was successful + /// + /// The returned value would be either 0, or how many bytes were read/written + Success(i32), + /// The IO layer needs to read more data asynchronously + WantRead, + /// The IO layer needs to write more data asynchronously + WantWrite, + /// Operation needs to be retried + Retry, + /// End of stream reached + Eof, + } + + /// A context for using the async `Read` and `Write` traits from within the synchronous MbedTLS "mbio" callbacks + /// **without any additional buffers** / memory. + /// + /// Using the MbedTLS callback-based IO metaphor is a bit of a challenge with the async `Read` and `Write` traits, + /// in that these cannot be `await`-ed from within the MbedTLS mbio callbacks, as the latter are synchronous callback + /// functions. + /// + /// What the `PollCtx` type implements therefore is the following trick: + /// - While we cannot `await` on the `Read` and `Write` traits directly from within the "mbio" callbacks, we can still + /// poll them (with `Future::poll`). This is because the `poll` method is synchronous in that it either resolves the + /// future immediately (`Poll::Ready`), or returns `Poll::Pending` if the future needs to be polled again. + /// - Because of the `Read` and `Write` traits' semantics, polling them MUST return immediately, if there is even one + /// byte available for reading from the networking stack buffers (or - correspondingly - if there is space to write + /// even one byte in the networking stack buffers). + /// - Since the network stack usually does not operate byte-by-byte, what this means is that by just calling `Future::poll` + /// on the `Read` / `Write` trait, we can efficiently transfer the incoming/outgoing data from/to the network stack, without + /// any additional network buffers. + /// - Of course, if the network read buffers are empty (or write buffers are full), we still need to `await` outside the + /// MbedTLS callbacks, in the `Session::read` / `Session::write` / `Session::connect` methods. + /// + /// Note also, that the implementation of `PollCtx` is a tad more complex, because it is implemented purely in terms of the + /// `Read` and `Write` traits, rather than `edge-nal`'s `Readable` and (future) `Writable`, so we need to shuffle single bytes + /// between the "mbio" callbacks and the `Session` asunc context to make it work. + /// + /// On the other hand, this enables `Session` to be used over any streaming transport that implements the `Read` and `Write` traits + /// (i.e. UART and others). + struct PollCtx<'s, 'a, 'c, 'q, T> { + /// The session + session: &'s mut Session<'a, T>, + /// The async context with which `Session::read` / `Session::write` / `Session::connect` are called. + /// Necessary so that we can invoke `Future::poll` + context: &'c mut Context<'q>, + /// The result from `Future::poll`, if it returned `Poll::Ready` + io_result: Option>, } - impl<'a, const BUFFER_SIZE: usize> BufferedBytes<'a, BUFFER_SIZE> { - pub fn new(buffer: &'a mut [u8; BUFFER_SIZE]) -> Self { + impl<'s, 'a, 'c, 'q, T> PollCtx<'s, 'a, 'c, 'q, T> + where + T: embedded_io_async::Read + embedded_io_async::Write, + { + fn poll( + session: &'s mut Session<'a, T>, + context: &'c mut Context<'q>, + f: F, + ) -> Poll> + where + F: FnOnce(*mut mbedtls_ssl_context) -> i32, + { + Self::new(session, context).poll_mut(f) + } + + /// Create a new `PollCtx` instance + fn new(session: &'s mut Session<'a, T>, context: &'c mut Context<'q>) -> Self { Self { - buffer, - write_idx: 0, - read_idx: 0, + session, + context, + io_result: None, } } - pub fn pull(&mut self, max: usize) -> &[u8] { - if self.read_idx == self.write_idx { - self.read_idx = 0; - self.write_idx = 0; + /// Call `Future::poll` on the `Read` or `Write` traits + fn poll_mut(&mut self, f: F) -> Poll> + where + F: FnOnce(*mut mbedtls_ssl_context) -> i32, + { + unsafe { + mbedtls_ssl_set_bio( + self.session.ssl_context, + self as *mut _ as *mut c_void, + Some(Self::raw_send), + Some(Self::raw_receive), + None, + ); + } + + let res = f(self.session.ssl_context); + + // Remove the callbacks so that we get a warning from MbedTLS in case + // it needs to invoke them when we don't anticipate so (for bugs detection) + unsafe { + mbedtls_ssl_set_bio( + self.session.ssl_context, + core::ptr::null_mut(), + None, + None, + None, + ); } - let len = usize::min(max, self.write_idx - self.read_idx); - let res = &self.buffer[self.read_idx..][..len]; - self.read_idx += len; - res + if let Some(Err(e)) = self.io_result.take() { + Err(e)?; + } + + #[allow(non_snake_case)] + Poll::Ready(match res { + MBEDTLS_ERR_SSL_WANT_READ => Ok(PollOutcome::WantRead), + MBEDTLS_ERR_SSL_WANT_WRITE => Ok(PollOutcome::WantWrite), + // See https://github.com/Mbed-TLS/mbedtls/issues/8749 + MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET => Ok(PollOutcome::Retry), + MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY => Ok(PollOutcome::Eof), + res if res < 0 => { + ::log::warn!("MbedTLS error: {res} / {res:x}"); + Err(TlsError::MbedTlsError(res)) + } + len => Ok(PollOutcome::Success(len)), + }) } - pub fn push(&mut self, data: &[u8]) -> Result<(), ()> { - if self.read_idx == self.write_idx { - self.read_idx = 0; - self.write_idx = 0; + fn send(&mut self, buf: &[u8]) -> i32 { + ::log::debug!("Send {}B", buf.len()); + + if buf.is_empty() { + // MbedTLS does not want us to read anything + return 0; } - if self.buffer.len() - self.write_idx < data.len() { - return Err(()); + if self.session.write_byte.is_some() { + // We have a byte to write from the previous call + // Indicate to the `Session` instance that it needs to write it + return MBEDTLS_ERR_SSL_WANT_WRITE; } - self.buffer[self.write_idx..][..data.len()].copy_from_slice(data); - self.write_idx += data.len(); + // Poll the `write` future by trying to immediately send (part of) the MbedTLS write data + // into the network stack buffers + let fut = pin!(self.session.stream.write(buf)); + + if let Poll::Ready(result) = fut.poll(self.context) { + match result { + Ok(len) => { + // Success! + + if len == 0 { + // The stream has reached EOF + self.session.state = SessionState::Eof; + self.io_result = Some(Err(TlsError::Eof)); + ::log::warn!("IO error: EOF"); + } else { + // The write was successful, indicate so + self.io_result = Some(Ok(())); + } - Ok(()) + len as _ + } + Err(err) => { + // MbedTLS error + ::log::warn!("TCP error: {:?}", err.kind()); + self.io_result = Some(Err(TlsError::Io(err.kind()))); + MBEDTLS_ERR_SSL_WANT_WRITE + } + } + } else { + // Network write buffers are full, indicate to the `Session` instance that + // it needs to write-await + // Also give it one byte of the TLS data so that it can call `Write::write` on something + self.session.write_byte = Some(buf[0]); + 1 + } } - pub fn remaining(&self) -> usize { - self.buffer.len() - self.write_idx + fn receive(&mut self, buf: &mut [u8]) -> i32 { + ::log::debug!("Recv {}B", buf.len()); + + if buf.is_empty() { + // MbedTLS does not want us to read anything + return 0; + } + + let offset = if let Some(byte) = self.session.read_byte.take() { + // We have one byte read from the `Session` async context, give it + // to MbedTLS + buf[0] = byte; + 1 + } else { + 0 + }; + + if buf.len() == offset { + // MbedTLS requested only one byte anyway + return offset as _; + } + + let fut = pin!(self.session.stream.read(&mut buf[offset..])); + + if let Poll::Ready(result) = fut.poll(self.context) { + match result { + Ok(len) => { + // Success! + + let len = len + offset; + + if len == 0 { + // The stream has reached EOF + self.session.state = SessionState::Eof; + self.io_result = Some(Err(TlsError::Eof)); + ::log::warn!("IO error: EOF"); + } else { + // The read was successful, indicate so + self.io_result = Some(Ok(())); + } + + len as _ + } + Err(err) => { + // MbedTLS error + ::log::warn!("TCP error: {:?}", err.kind()); + self.io_result = Some(Err(TlsError::Io(err.kind()))); + MBEDTLS_ERR_SSL_WANT_READ + } + } + } else { + // Network read buffers are empty, either return the single byte we have + // or indicate to the `Session` async context, that it needs to invoke `read` on the + // `Read` trait + if offset == 0 { + MBEDTLS_ERR_SSL_WANT_READ + } else { + offset as _ + } + } } - pub fn can_read(&self) -> bool { - self.read_idx < self.write_idx + unsafe extern "C" fn raw_send(ctx: *mut c_void, buf: *const c_uchar, len: usize) -> c_int { + let ctx = (ctx as *mut PollCtx<'s, 'a, 'c, 'q, T>).as_mut().unwrap(); + + ctx.send(core::slice::from_raw_parts(buf as *const _, len)) } - pub fn empty(&mut self) -> bool { - if self.read_idx == self.write_idx { - self.read_idx = 0; - self.write_idx = 0; - } + unsafe extern "C" fn raw_receive(ctx: *mut c_void, buf: *mut c_uchar, len: usize) -> c_int { + let ctx = (ctx as *mut PollCtx<'s, 'a, 'c, 'q, T>).as_mut().unwrap(); - self.read_idx == self.write_idx + ctx.receive(core::slice::from_raw_parts_mut(buf as *mut _, len)) } } } +/// Outputs the MbedTLS debug messages to the log unsafe extern "C" fn dbg_print( _arg: *mut c_void, lvl: i32, @@ -1196,15 +1526,25 @@ unsafe extern "C" fn dbg_print( line: i32, msg: *const i8, ) { - let msg = CStr::from_ptr(msg as *const i8); let file = CStr::from_ptr(file as *const i8); - log::info!( - "{} {}:{} {}", - lvl, - file.to_str().unwrap_or(""), - line, - msg.to_str().unwrap_or("") - ); + let msg = CStr::from_ptr(msg as *const i8); + + let file = file.to_str().unwrap_or("???").trim(); + let msg = msg.to_str().unwrap_or("???").trim(); + + let level = match lvl { + 0 => Level::Error, + 1 => Level::Warn, + 2 => Level::Debug, + _ => Level::Trace, + }; + + log::log!(level, "{} ({}:{}) {}", lvl, file, line, msg); +} + +#[no_mangle] +extern "C" fn rand() -> crate::c_ulong { + unsafe { crate::random() } } unsafe extern "C" fn rng(_param: *mut c_void, buffer: *mut c_uchar, len: usize) -> c_int { @@ -1217,6 +1557,7 @@ unsafe extern "C" fn rng(_param: *mut c_void, buffer: *mut c_uchar, len: usize) 0 } +#[cfg(not(target_os = "espidf"))] #[no_mangle] unsafe extern "C" fn mbedtls_platform_zeroize(dst: *mut u8, len: u32) { for i in 0..len as isize { diff --git a/examples/async_client.rs b/examples/async_client.rs index 8d52926..8721473 100644 --- a/examples/async_client.rs +++ b/examples/async_client.rs @@ -14,8 +14,8 @@ use embassy_net::{Config, Ipv4Address, Stack, StackResources}; use embassy_executor::Spawner; use embassy_time::{Duration, Timer}; use esp_backtrace as _; -use esp_mbedtls::X509; -use esp_mbedtls::{asynch::Session, set_debug, Certificates, Mode, TlsVersion}; +use esp_mbedtls::{asynch::Session, Certificates, Mode, TlsVersion}; +use esp_mbedtls::{Tls, X509}; use esp_println::logger::init_logger; use esp_println::{print, println}; use esp_wifi::wifi::{ @@ -124,12 +124,17 @@ async fn main(spawner: Spawner) -> ! { loop {} } - set_debug(0); + let mut tls = Tls::new(peripherals.SHA) + .unwrap() + .with_hardware_rsa(peripherals.RSA); - let tls = Session::new( + tls.set_debug(0); + + let mut session = Session::new( &mut socket, - "www.google.com", - Mode::Client, + Mode::Client { + servername: c"www.google.com", + }, TlsVersion::Tls1_3, Certificates { ca_chain: X509::pem( @@ -138,23 +143,19 @@ async fn main(spawner: Spawner) -> ! { .ok(), ..Default::default() }, - mk_static!([u8; 4096], [0; 4096]), - mk_static!([u8; 4096], [0; 4096]), - peripherals.SHA, + tls.reference(), ) - .unwrap() - .with_hardware_rsa(peripherals.RSA); + .unwrap(); println!("Start tls connect"); - let mut tls = tls.connect().await.unwrap(); + session.connect().await.unwrap(); println!("connected!"); let mut buf = [0; 1024]; - use embedded_io_async::Read; use embedded_io_async::Write; - let r = tls + let r = session .write_all(b"GET /notfound HTTP/1.0\r\nHost: www.google.com\r\n\r\n") .await; if let Err(e) = r { @@ -163,7 +164,7 @@ async fn main(spawner: Spawner) -> ! { } loop { - let n = match tls.read(&mut buf).await { + let n = match session.read(&mut buf).await { Ok(n) => n, Err(esp_mbedtls::TlsError::Eof) => { break; diff --git a/examples/async_client_mTLS.rs b/examples/async_client_mTLS.rs index e553564..2f0da30 100644 --- a/examples/async_client_mTLS.rs +++ b/examples/async_client_mTLS.rs @@ -14,8 +14,8 @@ use embassy_net::{Config, Ipv4Address, Stack, StackResources}; use embassy_time::{Duration, Timer}; use esp_backtrace as _; -use esp_mbedtls::{asynch::Session, set_debug, Mode, TlsVersion}; -use esp_mbedtls::{Certificates, X509}; +use esp_mbedtls::{asynch::Session, Mode, TlsVersion}; +use esp_mbedtls::{Certificates, Tls, X509}; use esp_println::logger::init_logger; use esp_println::{print, println}; use esp_wifi::wifi::{ @@ -40,7 +40,7 @@ const PASSWORD: &str = env!("PASSWORD"); #[esp_hal_embassy::main] async fn main(spawner: Spawner) -> ! { - init_logger(log::LevelFilter::Info); + init_logger(log::LevelFilter::Debug); let peripherals = esp_hal::init({ let mut config = esp_hal::Config::default(); @@ -124,8 +124,6 @@ async fn main(spawner: Spawner) -> ! { loop {} } - set_debug(0); - let certificates = Certificates { ca_chain: X509::pem( concat!(include_str!("./certs/certauth.cryptomix.com.pem"), "\0").as_bytes(), @@ -138,29 +136,32 @@ async fn main(spawner: Spawner) -> ! { password: None, }; - let tls = Session::new( + let mut tls = Tls::new(peripherals.SHA) + .unwrap() + .with_hardware_rsa(peripherals.RSA); + + tls.set_debug(5); + + let mut session = Session::new( &mut socket, - "certauth.cryptomix.com", - Mode::Client, + Mode::Client { + servername: c"certauth.cryptomix.com", + }, TlsVersion::Tls1_3, certificates, - mk_static!([u8; 4096], [0; 4096]), - mk_static!([u8; 4096], [0; 4096]), - peripherals.SHA, + tls.reference(), ) - .unwrap() - .with_hardware_rsa(peripherals.RSA); + .unwrap(); println!("Start tls connect"); - let mut tls = tls.connect().await.unwrap(); + session.connect().await.unwrap(); println!("connected!"); let mut buf = [0; 1024]; - use embedded_io_async::Read; use embedded_io_async::Write; - let r = tls + let r = session .write_all(b"GET /json/ HTTP/1.0\r\nHost: certauth.cryptomix.com\r\n\r\n") .await; if let Err(e) = r { @@ -169,7 +170,7 @@ async fn main(spawner: Spawner) -> ! { } loop { - let n = match tls.read(&mut buf).await { + let n = match session.read(&mut buf).await { Ok(n) => n, Err(esp_mbedtls::TlsError::Eof) => { break; diff --git a/examples/async_server.rs b/examples/async_server.rs index 97a0c51..eab03eb 100644 --- a/examples/async_server.rs +++ b/examples/async_server.rs @@ -18,8 +18,8 @@ use embassy_executor::Spawner; use embassy_time::{Duration, Timer}; use esp_alloc as _; use esp_backtrace as _; -use esp_mbedtls::{asynch::Session, set_debug, Certificates, Mode, TlsVersion}; -use esp_mbedtls::{TlsError, X509}; +use esp_mbedtls::{asynch::Session, Certificates, Mode, TlsVersion}; +use esp_mbedtls::{Tls, TlsError, X509}; use esp_println::logger::init_logger; use esp_println::{print, println}; use esp_wifi::wifi::{ @@ -46,7 +46,7 @@ const PASSWORD: &str = env!("PASSWORD"); async fn main(spawner: Spawner) -> ! { init_logger(log::LevelFilter::Info); - let mut peripherals = esp_hal::init({ + let peripherals = esp_hal::init({ let mut config = esp_hal::Config::default(); config.cpu_clock = CpuClock::max(); config @@ -97,10 +97,14 @@ async fn main(spawner: Spawner) -> ! { spawner.spawn(connection(controller)).ok(); spawner.spawn(net_task(&stack)).ok(); + let mut tls = Tls::new(peripherals.SHA) + .unwrap() + .with_hardware_rsa(peripherals.RSA); + + tls.set_debug(0); + let mut rx_buffer = [0; 4096]; let mut tx_buffer = [0; 4096]; - let tls_rx_buffer = mk_static!([u8; 4096], [0; 4096]); - let tls_tx_buffer = mk_static!([u8; 2048], [0; 2048]); loop { if stack.is_link_up() { @@ -139,15 +143,12 @@ async fn main(spawner: Spawner) -> ! { continue; } - set_debug(0); - use embedded_io_async::Read; use embedded_io_async::Write; let mut buffer = [0u8; 1024]; let mut pos = 0; - let tls = Session::new( + let mut session = Session::new( &mut socket, - "", Mode::Server, TlsVersion::Tls1_2, Certificates { @@ -162,19 +163,16 @@ async fn main(spawner: Spawner) -> ! { .ok(), ..Default::default() }, - tls_rx_buffer, - tls_tx_buffer, - &mut peripherals.SHA, + tls.reference(), ) - .unwrap() - .with_hardware_rsa(&mut peripherals.RSA); + .unwrap(); println!("Start tls connect"); - match tls.connect().await { - Ok(mut connected_session) => { + match session.connect().await { + Ok(_) => { log::info!("Got session"); loop { - match connected_session.read(&mut buffer).await { + match session.read(&mut buffer).await { Ok(0) => { println!("read EOF"); break; @@ -198,7 +196,7 @@ async fn main(spawner: Spawner) -> ! { }; } - let r = connected_session + let r = session .write_all( b"HTTP/1.0 200 OK\r\n\r\n\ \ @@ -214,8 +212,6 @@ async fn main(spawner: Spawner) -> ! { } Timer::after(Duration::from_millis(1000)).await; - - drop(connected_session); } Err(TlsError::MbedTlsError(-30592)) => { println!("Fatal message: Please enable the exception for a self-signed certificate in your browser"); @@ -225,6 +221,7 @@ async fn main(spawner: Spawner) -> ! { } } println!("Closing socket"); + drop(session); socket.close(); Timer::after(Duration::from_millis(1000)).await; diff --git a/examples/async_server_mTLS.rs b/examples/async_server_mTLS.rs index 0953ba6..7652aa7 100644 --- a/examples/async_server_mTLS.rs +++ b/examples/async_server_mTLS.rs @@ -34,8 +34,8 @@ use embassy_net::{Config, IpListenEndpoint, Stack, StackResources}; use embassy_executor::Spawner; use embassy_time::{Duration, Timer}; use esp_backtrace as _; -use esp_mbedtls::{asynch::Session, set_debug, Certificates, Mode, TlsVersion}; -use esp_mbedtls::{TlsError, X509}; +use esp_mbedtls::{asynch::Session, Certificates, Mode, TlsVersion}; +use esp_mbedtls::{Tls, TlsError, X509}; use esp_println::logger::init_logger; use esp_println::{print, println}; use esp_wifi::wifi::{ @@ -62,7 +62,7 @@ const PASSWORD: &str = env!("PASSWORD"); async fn main(spawner: Spawner) -> ! { init_logger(log::LevelFilter::Info); - let mut peripherals = esp_hal::init({ + let peripherals = esp_hal::init({ let mut config = esp_hal::Config::default(); config.cpu_clock = CpuClock::max(); config @@ -113,10 +113,14 @@ async fn main(spawner: Spawner) -> ! { spawner.spawn(connection(controller)).ok(); spawner.spawn(net_task(&stack)).ok(); + let mut tls = Tls::new(peripherals.SHA) + .unwrap() + .with_hardware_rsa(peripherals.RSA); + + tls.set_debug(0); + let mut rx_buffer = [0; 4096]; let mut tx_buffer = [0; 4096]; - let tls_rx_buffer = mk_static!([u8; 4096], [0; 4096]); - let tls_tx_buffer = mk_static!([u8; 2048], [0; 2048]); loop { if stack.is_link_up() { @@ -155,15 +159,12 @@ async fn main(spawner: Spawner) -> ! { continue; } - set_debug(0); - use embedded_io_async::Read; use embedded_io_async::Write; let mut buffer = [0u8; 1024]; let mut pos = 0; - let tls = Session::new( + let mut session = Session::new( &mut socket, - "", Mode::Server, TlsVersion::Tls1_2, Certificates { @@ -180,19 +181,16 @@ async fn main(spawner: Spawner) -> ! { .ok(), ..Default::default() }, - tls_rx_buffer, - tls_tx_buffer, - &mut peripherals.SHA, + tls.reference(), ) - .unwrap() - .with_hardware_rsa(&mut peripherals.RSA); + .unwrap(); println!("Start tls connect"); - match tls.connect().await { - Ok(mut connected_session) => { + match session.connect().await { + Ok(()) => { log::info!("Got session"); loop { - match connected_session.read(&mut buffer).await { + match session.read(&mut buffer).await { Ok(0) => { println!("read EOF"); break; @@ -216,7 +214,7 @@ async fn main(spawner: Spawner) -> ! { }; } - let r = connected_session + let r = session .write_all( b"HTTP/1.0 200 OK\r\n\r\n\ \ @@ -232,8 +230,6 @@ async fn main(spawner: Spawner) -> ! { } Timer::after(Duration::from_millis(1000)).await; - - drop(connected_session); } Err(TlsError::NoClientCertificate) => { println!("Error: No client certificates given. Please provide client certificates during your request"); @@ -245,6 +241,7 @@ async fn main(spawner: Spawner) -> ! { panic!("{:?}", error); } } + drop(session); println!("Closing socket"); socket.close(); Timer::after(Duration::from_millis(1000)).await; diff --git a/examples/crypto_self_test.rs b/examples/crypto_self_test.rs index a7d015a..89f0277 100644 --- a/examples/crypto_self_test.rs +++ b/examples/crypto_self_test.rs @@ -7,7 +7,7 @@ pub use esp_hal as hal; use esp_alloc as _; use esp_backtrace as _; -use esp_mbedtls::set_debug; +use esp_mbedtls::Tls; use esp_println::{logger::init_logger, println}; /// Only used for ROM functions @@ -15,15 +15,13 @@ use esp_println::{logger::init_logger, println}; use esp_wifi::{init, EspWifiInitFor}; use hal::{prelude::*, rng::Rng, timer::timg::TimerGroup}; -use log::warn; - pub fn cycles() -> u64 { - #[cfg(feature = "esp32")] + #[cfg(any(feature = "esp32", feature = "esp32s2", feature = "esp32s3"))] { esp_hal::xtensa_lx::timer::get_cycle_count() as u64 } - #[cfg(not(feature = "esp32"))] + #[cfg(not(any(feature = "esp32", feature = "esp32s2", feature = "esp32s3")))] { esp_hal::timer::systimer::SystemTimer::now() } @@ -44,7 +42,7 @@ fn main() -> ! { let timg0 = TimerGroup::new(peripherals.TIMG0); - let init = init( + let _init = init( EspWifiInitFor::Wifi, timg0.timer0, Rng::new(peripherals.RNG), @@ -52,21 +50,11 @@ fn main() -> ! { ) .unwrap(); - set_debug(1); - - // println!("Testing AES"); - // unsafe { - // esp_mbedtls::mbedtls_aes_self_test(1i32); - // } - // println!("Testing MD5"); - // unsafe { - // esp_mbedtls::mbedtls_md5_self_test(1i32); - // } - println!("Testing RSA"); - unsafe { - esp_mbedtls::mbedtls_rsa_self_test(1i32); - } - println!("Testing SHA"); + let mut tls = Tls::new(peripherals.SHA) + .unwrap() + .with_hardware_rsa(peripherals.RSA); + + tls.set_debug(1); // | Hash Algorithm | Software (cycles) | Hardware (cycles) | Hardware Faster (x times) | // |----------------|-------------------|-------------------|---------------------------| @@ -76,90 +64,76 @@ fn main() -> ! { // | SHA-384 | 13,605,806 | 799,532 | 17.02 | // | SHA-512 | 13,588,104 | 801,556 | 16.95 | - unsafe { - let before = cycles(); - esp_mbedtls::mbedtls_sha1_self_test(1i32); - let after = cycles(); - warn!("SHA 1 took {} cycles", after - before); - #[cfg(not(feature = "esp32"))] - let before = cycles(); - esp_mbedtls::mbedtls_sha224_self_test(1i32); - let after = cycles(); - warn!("SHA 224 took {} cycles", after - before); - let before = cycles(); - esp_mbedtls::mbedtls_sha256_self_test(1i32); - let after = cycles(); - warn!("SHA 256 took {} cycles", after - before); - let before = cycles(); - esp_mbedtls::mbedtls_sha384_self_test(1i32); - let after = cycles(); - warn!("SHA 384 took {} cycles", after - before); + for test in enumset::EnumSet::all() { + println!("Testing {:?}", test); + let before = cycles(); - esp_mbedtls::mbedtls_sha512_self_test(1i32); + + tls.self_test(test, true); + let after = cycles(); - warn!("SHA 512 took {} cycles", after - before); - - // HW Crypto: - // Testing RSA - // INFO - RSA key validation: - // INFO - passed - // PKCS#1 encryption : - // INFO - passed - // PKCS#1 decryption : - // INFO - passed - // INFO - PKCS#1 data sign : - // INFO - passed - // PKCS#1 sig. verify: - // INFO - passed - // INFO - 10 - // INFO - pre_cal 16377170 - // INFO - MPI test #1 (mul_mpi): - // INFO - passed - // INFO - MPI test #2 (div_mpi): - // INFO - passed - // INFO - MPI test #3 (exp_mod): - // INFO - passed - // INFO - MPI test #4 (inv_mod): - // INFO - passed - // INFO - MPI test #5 (simple gcd): - // INFO - passed - // INFO - 10 - // INFO - post_cal 17338357 - // Took 961187 cycles - // Done - - // SW Crypto: - // Testing RSA - // INFO - RSA key validation: - // INFO - passed - // PKCS#1 encryption : - // INFO - passed - // PKCS#1 decryption : - // INFO - passed - // INFO - PKCS#1 data sign : - // INFO - passed - // PKCS#1 sig. verify: - // INFO - passed - // INFO - 10 - // INFO - pre_cal 19067376 - // INFO - MPI test #1 (mul_mpi): - // INFO - passed - // INFO - MPI test #2 (div_mpi): - // INFO - passed - // INFO - MPI test #3 (exp_mod): - // INFO - passed - // INFO - MPI test #4 (inv_mod): - // INFO - passed - // INFO - MPI test #5 (simple gcd): - // INFO - passed - // INFO - 10 - // INFO - post_cal 20393146 - // Took 1325770 cycles - // Done - - // esp_mbedtls::mbedtls_mpi_self_test(1i32); + + println!("Took {:?} cycles", after.checked_sub(before)); } + // HW Crypto: + // Testing RSA + // INFO - RSA key validation: + // INFO - passed + // PKCS#1 encryption : + // INFO - passed + // PKCS#1 decryption : + // INFO - passed + // INFO - PKCS#1 data sign : + // INFO - passed + // PKCS#1 sig. verify: + // INFO - passed + // INFO - 10 + // INFO - pre_cal 16377170 + // INFO - MPI test #1 (mul_mpi): + // INFO - passed + // INFO - MPI test #2 (div_mpi): + // INFO - passed + // INFO - MPI test #3 (exp_mod): + // INFO - passed + // INFO - MPI test #4 (inv_mod): + // INFO - passed + // INFO - MPI test #5 (simple gcd): + // INFO - passed + // INFO - 10 + // INFO - post_cal 17338357 + // Took 961187 cycles + // Done + + // SW Crypto: + // Testing RSA + // INFO - RSA key validation: + // INFO - passed + // PKCS#1 encryption : + // INFO - passed + // PKCS#1 decryption : + // INFO - passed + // INFO - PKCS#1 data sign : + // INFO - passed + // PKCS#1 sig. verify: + // INFO - passed + // INFO - 10 + // INFO - pre_cal 19067376 + // INFO - MPI test #1 (mul_mpi): + // INFO - passed + // INFO - MPI test #2 (div_mpi): + // INFO - passed + // INFO - MPI test #3 (exp_mod): + // INFO - passed + // INFO - MPI test #4 (inv_mod): + // INFO - passed + // INFO - MPI test #5 (simple gcd): + // INFO - passed + // INFO - 10 + // INFO - post_cal 20393146 + // Took 1325770 cycles + // Done + println!("Done"); loop {} diff --git a/examples/crypto_self_test_std.rs b/examples/crypto_self_test_std.rs new file mode 100644 index 0000000..b561cd8 --- /dev/null +++ b/examples/crypto_self_test_std.rs @@ -0,0 +1,91 @@ +//! Run crypto self tests to ensure their functionnality + +use esp_mbedtls::Tls; + +fn cycles() -> std::time::Instant { + std::time::Instant::now() +} + +fn main() { + let mut tls = Tls::new().unwrap(); + + tls.set_debug(1); + + // | Hash Algorithm | Software (cycles) | Hardware (cycles) | Hardware Faster (x times) | + // |----------------|-------------------|-------------------|---------------------------| + // | SHA-1 | 3,390,785 | 896,889 | 3.78 | + // | SHA-224 | 8,251,799 | 898,344 | 9.19 | + // | SHA-256 | 8,237,932 | 901,709 | 9.14 | + // | SHA-384 | 13,605,806 | 799,532 | 17.02 | + // | SHA-512 | 13,588,104 | 801,556 | 16.95 | + + for test in enumset::EnumSet::all() { + println!("Testing {:?}", test); + + let before = cycles(); + + tls.self_test(test, true); + + println!("Took {:?}", before.elapsed()); + } + + // HW Crypto: + // Testing RSA + // INFO - RSA key validation: + // INFO - passed + // PKCS#1 encryption : + // INFO - passed + // PKCS#1 decryption : + // INFO - passed + // INFO - PKCS#1 data sign : + // INFO - passed + // PKCS#1 sig. verify: + // INFO - passed + // INFO - 10 + // INFO - pre_cal 16377170 + // INFO - MPI test #1 (mul_mpi): + // INFO - passed + // INFO - MPI test #2 (div_mpi): + // INFO - passed + // INFO - MPI test #3 (exp_mod): + // INFO - passed + // INFO - MPI test #4 (inv_mod): + // INFO - passed + // INFO - MPI test #5 (simple gcd): + // INFO - passed + // INFO - 10 + // INFO - post_cal 17338357 + // Took 961187 cycles + // Done + + // SW Crypto: + // Testing RSA + // INFO - RSA key validation: + // INFO - passed + // PKCS#1 encryption : + // INFO - passed + // PKCS#1 decryption : + // INFO - passed + // INFO - PKCS#1 data sign : + // INFO - passed + // PKCS#1 sig. verify: + // INFO - passed + // INFO - 10 + // INFO - pre_cal 19067376 + // INFO - MPI test #1 (mul_mpi): + // INFO - passed + // INFO - MPI test #2 (div_mpi): + // INFO - passed + // INFO - MPI test #3 (exp_mod): + // INFO - passed + // INFO - MPI test #4 (inv_mod): + // INFO - passed + // INFO - MPI test #5 (simple gcd): + // INFO - passed + // INFO - 10 + // INFO - post_cal 20393146 + // Took 1325770 cycles + // Done + + println!("Done"); +} diff --git a/examples/edge_server.rs b/examples/edge_server.rs index e5c1fd4..bbb7200 100644 --- a/examples/edge_server.rs +++ b/examples/edge_server.rs @@ -10,6 +10,8 @@ #![feature(type_alias_impl_trait)] #![feature(impl_trait_in_assoc_type)] +use core::net::{IpAddr, Ipv4Addr, SocketAddr}; + #[doc(hidden)] pub use esp_hal as hal; @@ -25,7 +27,7 @@ use embassy_net::{Config, Stack, StackResources}; use embassy_executor::Spawner; use embassy_time::{Duration, Timer}; use esp_backtrace as _; -use esp_mbedtls::{set_debug, Certificates, TlsVersion}; +use esp_mbedtls::{Certificates, Tls, TlsVersion}; use esp_mbedtls::{TlsError, X509}; use esp_println::logger::init_logger; use esp_println::println; @@ -68,7 +70,7 @@ pub type HttpsServer = Server; async fn main(spawner: Spawner) -> ! { init_logger(log::LevelFilter::Info); - let mut peripherals = esp_hal::init({ + let peripherals = esp_hal::init({ let mut config = esp_hal::Config::default(); config.cpu_clock = CpuClock::max(); config @@ -142,13 +144,17 @@ async fn main(spawner: Spawner) -> ! { Timer::after(Duration::from_millis(500)).await; } - set_debug(0); - let mut server = HttpsServer::new(); let buffers = TcpBuffers::::new(); - let tls_buffers = esp_mbedtls::asynch::TlsBuffers::::new(); let tcp = Tcp::new(stack, &buffers); + use edge_nal::TcpBind; + + let acceptor = tcp + .bind(SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 443)) + .await + .unwrap(); + let certificates = Certificates { // Use self-signed certificates certificate: X509::pem(concat!(include_str!("./certs/certificate.pem"), "\0").as_bytes()) @@ -158,19 +164,22 @@ async fn main(spawner: Spawner) -> ! { ..Default::default() }; + let mut tls = Tls::new(peripherals.SHA) + .unwrap() + .with_hardware_rsa(peripherals.RSA); + + tls.set_debug(0); + loop { let tls_acceptor = esp_mbedtls::asynch::TlsAcceptor::new( - &tcp, - &tls_buffers, - 443, + &acceptor, TlsVersion::Tls1_2, certificates, - &mut peripherals.SHA, - ) - .await - .with_hardware_rsa(&mut peripherals.RSA); + tls.reference(), + ); match server .run( + Some(15 * 1000), edge_nal::WithTimeout::new(15_000, tls_acceptor), HttpHandler, ) diff --git a/examples/sync_client.rs b/examples/sync_client.rs index 5ac9e37..a637404 100644 --- a/examples/sync_client.rs +++ b/examples/sync_client.rs @@ -6,11 +6,10 @@ #[doc(hidden)] pub use esp_hal as hal; -use embedded_io::*; use esp_alloc as _; use esp_backtrace as _; -use esp_mbedtls::{set_debug, Mode, TlsVersion, X509}; use esp_mbedtls::{Certificates, Session}; +use esp_mbedtls::{Mode, Tls, TlsVersion, X509}; use esp_println::{logger::init_logger, print, println}; use esp_wifi::{ init, @@ -102,12 +101,17 @@ fn main() -> ! { .open(IpAddress::v4(142, 250, 185, 68), 443) // google.com .unwrap(); - set_debug(0); + let mut tls = Tls::new(peripherals.SHA) + .unwrap() + .with_hardware_rsa(peripherals.RSA); - let tls = Session::new( + tls.set_debug(0); + + let mut session = Session::new( &mut socket, - "www.google.com", - Mode::Client, + Mode::Client { + servername: c"www.google.com", + }, TlsVersion::Tls1_3, Certificates { ca_chain: X509::pem( @@ -116,22 +120,22 @@ fn main() -> ! { .ok(), ..Default::default() }, - peripherals.SHA, + tls.reference(), ) - .unwrap() - .with_hardware_rsa(peripherals.RSA); + .unwrap(); println!("Start tls connect"); - let mut tls = tls.connect().unwrap(); + session.connect().unwrap(); println!("Write to connection"); - tls.write(b"GET /notfound HTTP/1.0\r\nHost: www.google.com\r\n\r\n") + session + .write(b"GET /notfound HTTP/1.0\r\nHost: www.google.com\r\n\r\n") .unwrap(); println!("Read from connection"); let mut buffer = [0u8; 4096]; loop { - match tls.read(&mut buffer) { + match session.read(&mut buffer) { Ok(len) => { print!("{}", unsafe { core::str::from_utf8_unchecked(&buffer[..len as usize]) diff --git a/examples/sync_client_mTLS.rs b/examples/sync_client_mTLS.rs index 2161c5c..db3b2b5 100644 --- a/examples/sync_client_mTLS.rs +++ b/examples/sync_client_mTLS.rs @@ -6,11 +6,10 @@ #[doc(hidden)] pub use esp_hal as hal; -use embedded_io::*; use esp_alloc as _; use esp_backtrace as _; -use esp_mbedtls::{set_debug, Mode, TlsVersion, X509}; use esp_mbedtls::{Certificates, Session}; +use esp_mbedtls::{Mode, Tls, TlsVersion, X509}; use esp_println::{logger::init_logger, print, println}; use esp_wifi::{ init, @@ -103,8 +102,6 @@ fn main() -> ! { .open(IpAddress::v4(62, 210, 201, 125), 443) // certauth.cryptomix.com .unwrap(); - set_debug(0); - let certificates = Certificates { ca_chain: X509::pem( concat!(include_str!("./certs/certauth.cryptomix.com.pem"), "\0").as_bytes(), @@ -117,28 +114,35 @@ fn main() -> ! { password: None, }; - let tls = Session::new( + let mut tls = Tls::new(peripherals.SHA) + .unwrap() + .with_hardware_rsa(peripherals.RSA); + + tls.set_debug(0); + + let mut session = Session::new( &mut socket, - "certauth.cryptomix.com", - Mode::Client, + Mode::Client { + servername: c"certauth.cryptomix.com", + }, TlsVersion::Tls1_3, certificates, - peripherals.SHA, + tls.reference(), ) - .unwrap() - .with_hardware_rsa(peripherals.RSA); + .unwrap(); println!("Start tls connect"); - let mut tls = tls.connect().unwrap(); + session.connect().unwrap(); println!("Write to connection"); - tls.write(b"GET /json/ HTTP/1.0\r\nHost: certauth.cryptomix.com\r\n\r\n") + session + .write(b"GET /json/ HTTP/1.0\r\nHost: certauth.cryptomix.com\r\n\r\n") .unwrap(); println!("Read from connection"); let mut buffer = [0u8; 4096]; loop { - match tls.read(&mut buffer) { + match session.read(&mut buffer) { Ok(len) => { print!("{}", unsafe { core::str::from_utf8_unchecked(&buffer[..len as usize]) diff --git a/examples/sync_server.rs b/examples/sync_server.rs index ac45e2f..e6dd11b 100644 --- a/examples/sync_server.rs +++ b/examples/sync_server.rs @@ -11,8 +11,8 @@ pub use esp_hal as hal; use embedded_io::*; use esp_backtrace as _; -use esp_mbedtls::{set_debug, Mode, TlsError, TlsVersion, X509}; use esp_mbedtls::{Certificates, Session}; +use esp_mbedtls::{Mode, Tls, TlsError, TlsVersion, X509}; use esp_println::{logger::init_logger, print, println}; use esp_wifi::{ init, @@ -30,7 +30,7 @@ const PASSWORD: &str = env!("PASSWORD"); fn main() -> ! { init_logger(log::LevelFilter::Info); - let mut peripherals = esp_hal::init({ + let peripherals = esp_hal::init({ let mut config = esp_hal::Config::default(); config.cpu_clock = CpuClock::max(); config @@ -103,7 +103,12 @@ fn main() -> ! { let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); socket.listen(443).unwrap(); - set_debug(0); + + let mut tls = Tls::new(peripherals.SHA) + .unwrap() + .with_hardware_rsa(peripherals.RSA); + + tls.set_debug(0); loop { socket.work(); @@ -120,9 +125,8 @@ fn main() -> ! { let mut buffer = [0u8; 1024]; let mut pos = 0; - let tls = Session::new( + let mut session = Session::new( &mut socket, - "", Mode::Server, TlsVersion::Tls1_2, Certificates { @@ -137,15 +141,14 @@ fn main() -> ! { .ok(), ..Default::default() }, - &mut peripherals.SHA, + tls.reference(), ) - .unwrap() - .with_hardware_rsa(&mut peripherals.RSA); + .unwrap(); - match tls.connect() { - Ok(mut connected_session) => { + match session.connect() { + Ok(_) => { loop { - if let Ok(len) = connected_session.read(&mut buffer[pos..]) { + if let Ok(len) = session.read(&mut buffer[pos..]) { let to_print = unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; @@ -168,7 +171,7 @@ fn main() -> ! { } if !time_out { - connected_session + session .write_all( b"HTTP/1.0 200 OK\r\n\r\n\ \ @@ -180,8 +183,6 @@ fn main() -> ! { ) .unwrap(); } - - drop(connected_session); } Err(TlsError::MbedTlsError(-30592)) => { println!("Fatal message: Please enable the exception for a self-signed certificate in your browser"); @@ -191,6 +192,7 @@ fn main() -> ! { } } + drop(session); socket.close(); println!("Done\n"); diff --git a/examples/sync_server_mTLS.rs b/examples/sync_server_mTLS.rs index 6f0d9f7..03ec14f 100644 --- a/examples/sync_server_mTLS.rs +++ b/examples/sync_server_mTLS.rs @@ -28,8 +28,8 @@ pub use esp_hal as hal; use embedded_io::*; use esp_backtrace as _; -use esp_mbedtls::{set_debug, Mode, TlsError, TlsVersion, X509}; use esp_mbedtls::{Certificates, Session}; +use esp_mbedtls::{Mode, Tls, TlsError, TlsVersion, X509}; use esp_println::{logger::init_logger, print, println}; use esp_wifi::{ init, @@ -47,7 +47,7 @@ const PASSWORD: &str = env!("PASSWORD"); fn main() -> ! { init_logger(log::LevelFilter::Info); - let mut peripherals = esp_hal::init({ + let peripherals = esp_hal::init({ let mut config = esp_hal::Config::default(); config.cpu_clock = CpuClock::max(); config @@ -120,7 +120,12 @@ fn main() -> ! { let mut socket = wifi_stack.get_socket(&mut rx_buffer, &mut tx_buffer); socket.listen(443).unwrap(); - set_debug(0); + + let mut tls = Tls::new(peripherals.SHA) + .unwrap() + .with_hardware_rsa(peripherals.RSA); + + tls.set_debug(0); loop { socket.work(); @@ -137,9 +142,8 @@ fn main() -> ! { let mut buffer = [0u8; 1024]; let mut pos = 0; - let tls = Session::new( + let mut session = Session::new( &mut socket, - "", Mode::Server, TlsVersion::Tls1_2, Certificates { @@ -158,15 +162,14 @@ fn main() -> ! { .ok(), ..Default::default() }, - &mut peripherals.SHA, + tls.reference(), ) - .unwrap() - .with_hardware_rsa(&mut peripherals.RSA); + .unwrap(); - match tls.connect() { - Ok(mut connected_session) => { + match session.connect() { + Ok(_) => { loop { - if let Ok(len) = connected_session.read(&mut buffer[pos..]) { + if let Ok(len) = session.read(&mut buffer[pos..]) { let to_print = unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; @@ -189,7 +192,7 @@ fn main() -> ! { } if !time_out { - connected_session + session .write_all( b"HTTP/1.0 200 OK\r\n\r\n\ \ @@ -201,8 +204,6 @@ fn main() -> ! { ) .unwrap(); } - - drop(connected_session); } Err(TlsError::NoClientCertificate) => { println!("Error: No client certificates given. Please provide client certificates during your request"); @@ -215,6 +216,7 @@ fn main() -> ! { } } + drop(session); socket.close(); println!("Done\n"); diff --git a/justfile b/justfile index b51fef2..bec88b0 100644 --- a/justfile +++ b/justfile @@ -6,13 +6,15 @@ all: (check "esp32" "esp") (check "esp32s3" "esp") (check "esp32c3" "nightly-202 [private] check arch toolchain: - cargo +{{ toolchain }} b{{ arch }} --example sync_client - cargo +{{ toolchain }} b{{ arch }} --example sync_client_mTLS - cargo +{{ toolchain }} b{{ arch }} --example async_client --features="async" - cargo +{{ toolchain }} b{{ arch }} --example async_client_mTLS --features="async" - cargo +{{ toolchain }} b{{ arch }} --example sync_server - cargo +{{ toolchain }} b{{ arch }} --example sync_server_mTLS - cargo +{{ toolchain }} b{{ arch }} --example async_server --features="async" - cargo +{{ toolchain }} b{{ arch }} --example async_server_mTLS --features="async" - cargo +{{ toolchain }} b{{ arch }} --example edge_server --features="async,edge-server" + cargo +{{ toolchain }} b{{ arch }} --example sync_client --features="examples" + cargo +{{ toolchain }} b{{ arch }} --example sync_client_mTLS --features="examples" + cargo +{{ toolchain }} b{{ arch }} --example async_client --features="examples-async" + cargo +{{ toolchain }} b{{ arch }} --example async_client_mTLS --features="examples-async" + cargo +{{ toolchain }} b{{ arch }} --example sync_server --features="examples" + cargo +{{ toolchain }} b{{ arch }} --example sync_server_mTLS --features="examples" + cargo +{{ toolchain }} b{{ arch }} --example async_server --features="examples-async" + cargo +{{ toolchain }} b{{ arch }} --example async_server_mTLS --features="examples-async" + cargo +{{ toolchain }} b{{ arch }} --example edge_server --features="examples-async" + cargo +{{ toolchain }} b{{ arch }} --example crypto_self_test --features="examples" + cargo +{{ toolchain }} b --example crypto_self_test_std --features="examples-std" --target x86_64-unknown-linux-gnu -Z build-std=std,panic_abort cargo +{{ toolchain }} fmt --all -- --check diff --git a/libs/riscv32imc-unknown-none-elf/libmbedcrypto.a b/libs/riscv32imc-unknown-none-elf/libmbedcrypto.a deleted file mode 100644 index a75b035..0000000 Binary files a/libs/riscv32imc-unknown-none-elf/libmbedcrypto.a and /dev/null differ diff --git a/libs/riscv32imc-unknown-none-elf/libmbedtls.a b/libs/riscv32imc-unknown-none-elf/libmbedtls.a deleted file mode 100644 index b68011e..0000000 Binary files a/libs/riscv32imc-unknown-none-elf/libmbedtls.a and /dev/null differ diff --git a/libs/riscv32imc-unknown-none-elf/libmbedx509.a b/libs/riscv32imc-unknown-none-elf/libmbedx509.a deleted file mode 100644 index a131650..0000000 Binary files a/libs/riscv32imc-unknown-none-elf/libmbedx509.a and /dev/null differ diff --git a/libs/xtensa-esp32-none-elf/libmbedcrypto.a b/libs/xtensa-esp32-none-elf/libmbedcrypto.a deleted file mode 100644 index 16df9b0..0000000 Binary files a/libs/xtensa-esp32-none-elf/libmbedcrypto.a and /dev/null differ diff --git a/libs/xtensa-esp32-none-elf/libmbedtls.a b/libs/xtensa-esp32-none-elf/libmbedtls.a deleted file mode 100644 index e4ba2fd..0000000 Binary files a/libs/xtensa-esp32-none-elf/libmbedtls.a and /dev/null differ diff --git a/libs/xtensa-esp32-none-elf/libmbedx509.a b/libs/xtensa-esp32-none-elf/libmbedx509.a deleted file mode 100644 index 8172984..0000000 Binary files a/libs/xtensa-esp32-none-elf/libmbedx509.a and /dev/null differ diff --git a/libs/xtensa-esp32s2-none-elf/libmbedcrypto.a b/libs/xtensa-esp32s2-none-elf/libmbedcrypto.a deleted file mode 100644 index d1775d8..0000000 Binary files a/libs/xtensa-esp32s2-none-elf/libmbedcrypto.a and /dev/null differ diff --git a/libs/xtensa-esp32s2-none-elf/libmbedtls.a b/libs/xtensa-esp32s2-none-elf/libmbedtls.a deleted file mode 100644 index 95a9a82..0000000 Binary files a/libs/xtensa-esp32s2-none-elf/libmbedtls.a and /dev/null differ diff --git a/libs/xtensa-esp32s2-none-elf/libmbedx509.a b/libs/xtensa-esp32s2-none-elf/libmbedx509.a deleted file mode 100644 index 8172984..0000000 Binary files a/libs/xtensa-esp32s2-none-elf/libmbedx509.a and /dev/null differ diff --git a/libs/xtensa-esp32s3-none-elf/libmbedcrypto.a b/libs/xtensa-esp32s3-none-elf/libmbedcrypto.a deleted file mode 100644 index d1775d8..0000000 Binary files a/libs/xtensa-esp32s3-none-elf/libmbedcrypto.a and /dev/null differ diff --git a/libs/xtensa-esp32s3-none-elf/libmbedtls.a b/libs/xtensa-esp32s3-none-elf/libmbedtls.a deleted file mode 100644 index 95a9a82..0000000 Binary files a/libs/xtensa-esp32s3-none-elf/libmbedtls.a and /dev/null differ diff --git a/libs/xtensa-esp32s3-none-elf/libmbedx509.a b/libs/xtensa-esp32s3-none-elf/libmbedx509.a deleted file mode 100644 index 8172984..0000000 Binary files a/libs/xtensa-esp32s3-none-elf/libmbedx509.a and /dev/null differ diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 17cbadd..c532b6c 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -9,7 +9,7 @@ bindgen = "0.68.1" directories = "4.0.1" env_logger = "0.10.0" log = "0.4.17" -cmake = "0.1.50" +cmake = "0.1.52" tempdir = "0.3.7" fs_extra = "1.3.0" clap = { version = "4.4.2", features = ["derive"] } diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 91c7916..a5faf0e 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,20 +1,17 @@ use std::{ env, - fs::{self, rename}, - io::{Read, Write}, path::{Path, PathBuf}, - process::Command, }; -use anyhow::{anyhow, Result}; -use bindgen::Builder; +use anyhow::Result; use clap::{Parser, Subcommand, ValueEnum}; -use cmake::Config; use directories::UserDirs; -use fs_extra::dir::{copy, CopyOptions}; use log::LevelFilter; use tempdir::TempDir; +#[path = "../../esp-mbedtls-sys/gen/builder.rs"] +mod builder; + // Arguments #[derive(Parser, Debug)] #[command(author, version, about = "Compile and generate bindings for mbedtls to be used in Rust.", long_about = None, subcommand_required = true)] @@ -25,6 +22,11 @@ struct Args { #[derive(Subcommand, Debug)] enum Commands { + /// Generate Rust bindings for mbedtls and generate .a libraries + Gen { + #[arg(long, value_name = "TARGET", value_enum)] + chip: Option, + }, /// Generate Rust bindings for mbedtls Bindings { #[arg(long, value_name = "TARGET", value_enum)] @@ -63,6 +65,28 @@ enum Arch { Xtensa, } +impl Arch { + pub const fn clang(&self) -> Option<&str> { + const ESP_XTENSA_CLANG_PATH: &str = "xtensa-esp32-elf-clang/esp-18.1.2_20240912/esp-clang/bin/clang"; + + match self { + Arch::Xtensa => Some(ESP_XTENSA_CLANG_PATH), + // Clang is a cross-compiler + _ => Some(ESP_XTENSA_CLANG_PATH), + } + } + + pub const fn sysroot(&self) -> &str { + const ESP_XTENSA_SYSROOT_PATH: &str = "xtensa-esp-elf/esp-14.2.0_20240906/xtensa-esp-elf/xtensa-esp-elf"; + const ESP_RISCV_SYSROOT_PATH: &str = "riscv32-esp-elf/esp-14.2.0_20240906/riscv32-esp-elf/riscv32-esp-elf"; + + match self { + Arch::RiscV => ESP_RISCV_SYSROOT_PATH, + Arch::Xtensa => ESP_XTENSA_SYSROOT_PATH, + } + } +} + /// Data for binding compiling on a target struct CompilationTarget<'a> { /// Chip of the target @@ -71,19 +95,101 @@ struct CompilationTarget<'a> { /// The chip architecture arch: Arch, - /// Target triple + /// Rust target triple target: &'a str, - /// cmake toolchain file - toolchain_file: PathBuf, + /// Clang target + clang_target: &'a str, +} + +impl CompilationTarget<'_> { + pub fn gen(&self, sys_crate_root_path: PathBuf, toolchain_dir: &Path) -> Result<()> { + self.build(sys_crate_root_path.clone(), toolchain_dir)?; + self.generate_bindings(sys_crate_root_path, toolchain_dir)?; - /// Path for headers files for compiling (where mbedtls_config.h is stored) - compile_include_path: PathBuf, + Ok(()) + } - /// Sysroot path for bindings - sysroot_path: PathBuf, + pub fn build(&self, sys_crate_root_path: PathBuf, toolchain_dir: &Path) -> Result<()> { + let builder = builder::MbedtlsBuilder::new( + sys_crate_root_path.clone(), + format!("{}", self.soc), + self.arch.clang().map(|clang| toolchain_dir.join(clang)), + None, + Some(self.target.into()), + Some(self.clang_target.into()), + // Fake host, but we do need to pass something to CMake + Some("x86_64-unknown-linux-gnu".into()), + ); + + let out = TempDir::new("esp-mbedtls-sys")?; + + builder.compile( + out.path(), + Some(&sys_crate_root_path.join("libs").join(self.target)), + )?; + + Ok(()) + } + + pub fn generate_bindings( + &self, + sys_crate_root_path: PathBuf, + toolchain_dir: &Path, + ) -> Result<()> { + let builder = builder::MbedtlsBuilder::new( + sys_crate_root_path.clone(), + format!("{}", self.soc), + self.arch.clang().map(|clang| toolchain_dir.join(clang)), + Some(toolchain_dir.join(self.arch.sysroot())), + Some(self.target.into()), + Some(self.clang_target.into()), + None, + ); + + let out = TempDir::new("esp-mbedtls-sys")?; + + builder.generate_bindings( + out.path(), + Some( + &sys_crate_root_path + .join("src") + .join("include") + .join(format!("{}.rs", self.soc)), + ), + )?; + + Ok(()) + } } +static COMPILATION_TARGETS: &[CompilationTarget] = &[ + CompilationTarget { + soc: Soc::ESP32, + arch: Arch::Xtensa, + clang_target: "xtensa-esp32-none-elf", + target: "xtensa-esp32-none-elf", + }, + CompilationTarget { + soc: Soc::ESP32C3, + arch: Arch::RiscV, + clang_target: "riscv32-esp-elf", + target: "riscv32imc-unknown-none-elf", + }, + CompilationTarget { + soc: Soc::ESP32S2, + arch: Arch::Xtensa, + clang_target: "xtensa-esp32s2-none-elf", + target: "xtensa-esp32s2-none-elf", + }, + CompilationTarget { + soc: Soc::ESP32S3, + arch: Arch::Xtensa, + clang_target: "xtensa-esp32s3-none-elf", + target: "xtensa-esp32s3-none-elf", + }, +]; + fn main() -> Result<()> { env_logger::Builder::new() .filter_module("xtask", LevelFilter::Info) @@ -94,97 +200,50 @@ fn main() -> Result<()> { let workspace = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let workspace = workspace.parent().unwrap().canonicalize()?; + let sys_crate_root_path = workspace.join("esp-mbedtls-sys"); + // Determine the $HOME directory, and subsequently the Espressif tools // directory: let home = UserDirs::new().unwrap().home_dir().to_path_buf(); // We use the tools that come installed with the toolchain + // Note that the RiscV toolchain is not installed by default and needs the `-r` `espup` flag let toolchain_dir = home.join(".rustup").join("toolchains").join("esp"); - let compilation_targets: Vec = vec![ - CompilationTarget { - soc: Soc::ESP32, - arch: Arch::Xtensa, - target: "xtensa-esp32-none-elf", - toolchain_file: workspace - .join("xtask/toolchains/toolchain-clang-esp32.cmake") - .canonicalize() - .unwrap(), - compile_include_path: workspace.join("esp-mbedtls-sys").join("headers/esp32/"), - sysroot_path: toolchain_dir.join( - "xtensa-esp32-elf/esp-2021r2-patch5-8_4_0/xtensa-esp32-elf/xtensa-esp32-elf/", - ), - }, - CompilationTarget { - soc: Soc::ESP32C3, - arch: Arch::RiscV, - target: "riscv32imc-unknown-none-elf", - toolchain_file: workspace - .join("xtask/toolchains/toolchain-clang-esp32c3.cmake") - .canonicalize() - .unwrap(), - compile_include_path: workspace.join("esp-mbedtls-sys").join("headers/esp32c3/"), - sysroot_path: toolchain_dir - .join("riscv32-esp-elf/esp-2021r2-patch5-8_4_0/riscv32-esp-elf/riscv32-esp-elf/"), - }, - CompilationTarget { - soc: Soc::ESP32S2, - arch: Arch::Xtensa, - target: "xtensa-esp32s2-none-elf", - toolchain_file: workspace - .join("xtask/toolchains/toolchain-clang-esp32s2.cmake") - .canonicalize() - .unwrap(), - compile_include_path: workspace.join("esp-mbedtls-sys").join("headers/esp32s2/"), - sysroot_path: toolchain_dir.join( - "xtensa-esp32s2-elf/esp-2021r2-patch5-8_4_0/xtensa-esp32s2-elf/xtensa-esp32s2-elf/", - ), - }, - CompilationTarget { - soc: Soc::ESP32S3, - arch: Arch::Xtensa, - target: "xtensa-esp32s3-none-elf", - toolchain_file: workspace - .join("xtask/toolchains/toolchain-clang-esp32s3.cmake") - .canonicalize() - .unwrap(), - compile_include_path: workspace.join("esp-mbedtls-sys").join("headers/esp32s3/"), - sysroot_path: toolchain_dir.join( - "xtensa-esp32s3-elf/esp-2021r2-patch5-8_4_0/xtensa-esp32s3-elf/xtensa-esp32s3-elf/", - ), - }, - ]; let args = Args::parse(); + let target = |chip| COMPILATION_TARGETS + .iter() + .find(|&target| target.soc == chip) + .expect("Compilation target {chip} not found"); + match args.command { + Some(Commands::Gen { chip }) => match chip { + Some(chip) => { + target(chip).gen(sys_crate_root_path.clone(), &toolchain_dir)?; + } + None => { + for target in COMPILATION_TARGETS { + target.gen(sys_crate_root_path.clone(), &toolchain_dir)?; + } + } + }, Some(Commands::Compile { chip }) => match chip { Some(chip) => { - compile( - &workspace, - compilation_targets - .iter() - .find(|&target| target.soc == chip) - .expect("Compilation target not found"), - )?; + target(chip).build(sys_crate_root_path.clone(), &toolchain_dir)?; } None => { - for target in compilation_targets { - compile(&workspace, &target)?; + for target in COMPILATION_TARGETS { + target.build(sys_crate_root_path.clone(), &toolchain_dir)?; } } }, Some(Commands::Bindings { chip }) => match chip { Some(chip) => { - generate_bindings( - &workspace, - compilation_targets - .iter() - .find(|&target| target.soc == chip) - .expect("Compilation target not found"), - )?; + target(chip).generate_bindings(sys_crate_root_path.clone(), &toolchain_dir)?; } None => { - for target in compilation_targets { - generate_bindings(&workspace, &target)?; + for target in COMPILATION_TARGETS { + target.generate_bindings(sys_crate_root_path.clone(), &toolchain_dir)?; } } }, @@ -195,218 +254,3 @@ fn main() -> Result<()> { Ok(()) } - -/// Generate bindings for esp-mbedtls-sys -fn generate_bindings(workspace: &Path, compilation_target: &CompilationTarget) -> Result<()> { - let sys_path = workspace.join("esp-mbedtls-sys"); - - // Generate the bindings using `bindgen`: - log::info!("Generating bindings"); - let bindings = Builder::default() - .clang_args([ - &format!( - "-I{}", - &compilation_target - .compile_include_path - .display() - .to_string() - .replace('\\', "/") - .replace("//?/C:", "") - ), - &format!( - "-I{}", - sys_path - .join("../mbedtls/include/") - .display() - .to_string() - .replace('\\', "/") - .replace("//?/C:", "") - ), - &format!( - "-I{}", - sys_path - .join("include") - .display() - .to_string() - .replace('\\', "/") - .replace("//?/C:", "") - ), - &format!( - "-I{}", - compilation_target - .sysroot_path - .join("include") - .display() - .to_string() - .replace('\\', "/") - .replace("//?/C:", "") - ), - &format!( - "--sysroot={}", - compilation_target - .sysroot_path - .display() - .to_string() - .replace('\\', "/") - .replace("//?/C:", "") - ), - &format!( - "--target={}", - if compilation_target.arch == Arch::Xtensa { - "xtensa" - } else { - "riscv32" - } - ), - ]) - .ctypes_prefix("crate::c_types") - .derive_debug(false) - .header(sys_path.join("include/include.h").to_string_lossy()) - .layout_tests(false) - .raw_line("#![allow(non_camel_case_types,non_snake_case,non_upper_case_globals,dead_code)]") - .use_core() - .generate() - .map_err(|_| anyhow!("Failed to generate bindings"))?; - - // Write out the bindings to the appropriate path: - let path = sys_path - .join("src") - .join("include") - .join(format!("{}.rs", compilation_target.soc.to_string())); - log::info!("Writing out bindings to: {}", path.display()); - bindings.write_to_file(&path)?; - - // Format the bindings: - Command::new("rustfmt") - .arg(path.to_string_lossy().to_string()) - .arg("--config") - .arg("normalize_doc_attributes=true") - .output()?; - - Ok(()) -} - -/// Compile mbedtls for the given target and copy the libraries into /libs/ -fn compile(workspace: &Path, compilation_target: &CompilationTarget) -> Result<()> { - log::info!( - "Initializing directory for compiling {:?}", - compilation_target.soc - ); - let mbedtls_path = workspace.join("mbedtls"); - let tmp = TempDir::new("tmp").expect("Failed to create tmp directory for building"); - - let tmpsrc = TempDir::new_in(tmp.path(), "tmpsrc") - .expect("Failed to create tmpsrc directory for building"); - let target_dir = TempDir::new_in(tmp.path(), "target") - .expect("Failed to create target directory for building"); - let copy_options = CopyOptions::new().overwrite(true); //Initialize default values for CopyOptions - - // Copy mbedtls into the building directory - copy(mbedtls_path, tmpsrc.path(), ©_options)?; - // Copy header files for building - copy( - &compilation_target.compile_include_path, - tmpsrc - .path() - .join("mbedtls") - .join("include") - .join("mbedtls"), - ©_options.content_only(true), - )?; - // Move config.h back to mbedtls_config.h - rename( - tmpsrc - .path() - .join("mbedtls") - .join("include") - .join("mbedtls") - .join("config.h"), - tmpsrc - .path() - .join("mbedtls") - .join("include") - .join("mbedtls") - .join("mbedtls_config.h"), - )?; - - // Remove "-Wdocumentation" since Clang will complain - let mut file = fs::File::open( - tmpsrc - .path() - .join("mbedtls") - .join("library") - .join("CMakeLists.txt"), - )?; - let mut content = String::new(); - file.read_to_string(&mut content)?; - let mut file = fs::File::create( - tmpsrc - .path() - .join("mbedtls") - .join("library") - .join("CMakeLists.txt"), - )?; - file.write_all(content.replace("-Wdocumentation", "").as_bytes())?; - - // This add the function prototype for `mbedtls_mpi_exp_mod_soft()` since it - // is not provided in the espressif fork of mbedtls. - if let Err(error) = writeln!( - fs::OpenOptions::new().write(true).append(true).open( - tmpsrc - .path() - .join("mbedtls") - .join("include") - .join("mbedtls") - .join("bignum.h"), - )?, - "int mbedtls_mpi_exp_mod_soft( - mbedtls_mpi *X, - const mbedtls_mpi *A, - const mbedtls_mpi *E, - const mbedtls_mpi *N, - mbedtls_mpi *prec_RR - );" - ) { - eprintln!("Could not write function prototype to bignum.h"); - eprintln!("{error}"); - } - - // Compile mbedtls and generate libraries to link against - log::info!("Compiling mbedtls"); - let dst = Config::new(tmpsrc.path().join("mbedtls")) - .define("USE_SHARED_MBEDTLS_LIBRARY", "OFF") - .define("USE_STATIC_MBEDTLS_LIBRARY", "ON") - .define("ENABLE_PROGRAMS", "OFF") - .define("ENABLE_TESTING", "OFF") - .define("CMAKE_EXPORT_COMPILE_COMMANDS", "ON") - .define("CMAKE_TOOLCHAIN_FILE", &compilation_target.toolchain_file) - .target(compilation_target.target) - .host("riscv32") - .profile("Release") - .out_dir(target_dir) - .build(); - - log::info!("Copying libraries into workspace"); - fs::copy( - dst.join("lib").join("libmbedcrypto.a"), - workspace - .join("libs") - .join(compilation_target.target) - .join("libmbedcrypto.a"), - )?; - fs::copy( - dst.join("lib").join("libmbedx509.a"), - workspace - .join("libs") - .join(compilation_target.target) - .join("libmbedx509.a"), - )?; - fs::copy( - dst.join("lib").join("libmbedtls.a"), - workspace - .join("libs") - .join(compilation_target.target) - .join("libmbedtls.a"), - )?; - Ok(()) -} diff --git a/xtask/toolchains/toolchain-clang-esp32.cmake b/xtask/toolchains/toolchain-clang-esp32.cmake deleted file mode 100644 index 1147fae..0000000 --- a/xtask/toolchains/toolchain-clang-esp32.cmake +++ /dev/null @@ -1,20 +0,0 @@ -set(CMAKE_SYSTEM_NAME Generic) - -# Install with `espup install --extended-llvm` -set(CMAKE_C_COMPILER "$ENV{CLANG_PATH}") - -set(CMAKE_AR llvm-ar) -set(CMAKE_RANLIB llvm-ranlib) -set(CMAKE_OBJDUMP xtensa-esp32-elf-objdump) - -set(CMAKE_C_FLAGS "--target=xtensa-esp-elf -mcpu=esp32" - CACHE STRING "C Compiler Base Flags" - FORCE) - -set(CMAKE_CXX_FLAGS "--target=xtensa-esp-elf -mcpu=esp32 " - CACHE STRING "C++ Compiler Base Flags" - FORCE) - -set(CMAKE_ASM_FLAGS "--target=xtensa-esp-elf -mcpu=esp32 -Xassembler --longcalls" - CACHE STRING "Assembler Base Flags" - FORCE) diff --git a/xtask/toolchains/toolchain-clang-esp32c3.cmake b/xtask/toolchains/toolchain-clang-esp32c3.cmake deleted file mode 100644 index e8da1d9..0000000 --- a/xtask/toolchains/toolchain-clang-esp32c3.cmake +++ /dev/null @@ -1,20 +0,0 @@ -set(CMAKE_SYSTEM_NAME Generic) - -# Install with `espup install --extended-llvm` -set(CMAKE_C_COMPILER "$ENV{CLANG_PATH}") - -set(CMAKE_AR llvm-ar) -set(CMAKE_RANLIB llvm-ranlib) -set(CMAKE_OBJDUMP riscv32-esp-elf-objdump) - -set(CMAKE_C_FLAGS "--target=riscv32-esp-elf -march=rv32imc -mabi=ilp32" - CACHE STRING "C Compiler Base Flags" - FORCE) - -set(CMAKE_CXX_FLAGS "--target=riscv32-esp-elf -march=rv32imc -mabi=ilp32" - CACHE STRING "C++ Compiler Base Flags" - FORCE) - -set(CMAKE_ASM_FLAGS "--target=riscv32-esp-elf -march=rv32imc -mabi=ilp32 " - CACHE STRING "Assembler Base Flags" - FORCE) diff --git a/xtask/toolchains/toolchain-clang-esp32s2.cmake b/xtask/toolchains/toolchain-clang-esp32s2.cmake deleted file mode 100644 index de6b659..0000000 --- a/xtask/toolchains/toolchain-clang-esp32s2.cmake +++ /dev/null @@ -1,20 +0,0 @@ -set(CMAKE_SYSTEM_NAME Generic) - -# Install with `espup install --extended-llvm` -set(CMAKE_C_COMPILER "$ENV{CLANG_PATH}") - -set(CMAKE_AR llvm-ar) -set(CMAKE_RANLIB llvm-ranlib) -set(CMAKE_OBJDUMP xtensa-esp32s2-elf-objdump) - -set(CMAKE_C_FLAGS "--target=xtensa-esp-elf -mcpu=esp32s2 " - CACHE STRING "C Compiler Base Flags" - FORCE) - -set(CMAKE_CXX_FLAGS "--target=xtensa-esp-elf -mcpu=esp32s2" - CACHE STRING "C++ Compiler Base Flags" - FORCE) - -set(CMAKE_ASM_FLAGS "--target=xtensa-esp-elf -mcpu=esp32s2 -Xassembler --longcalls" - CACHE STRING "Assembler Base Flags" - FORCE) diff --git a/xtask/toolchains/toolchain-clang-esp32s3.cmake b/xtask/toolchains/toolchain-clang-esp32s3.cmake deleted file mode 100644 index 65278ed..0000000 --- a/xtask/toolchains/toolchain-clang-esp32s3.cmake +++ /dev/null @@ -1,12 +0,0 @@ -set(CMAKE_SYSTEM_NAME Generic) - -# Install with `espup install --extended-llvm` -set(CMAKE_C_COMPILER "$ENV{CLANG_PATH}") - -set(CMAKE_AR llvm-ar) -set(CMAKE_RANLIB llvm-ranlib) -set(CMAKE_OBJDUMP xtensa-esp32s3-elf-objdump) - -set(CMAKE_C_FLAGS "--target=xtensa-esp-elf -mcpu=esp32s3" CACHE STRING "C Compiler Base Flags" FORCE) -set(CMAKE_CXX_FLAGS "--target=xtensa-esp-elf -mcpu=esp32s3" CACHE STRING "C++ Compiler Base Flags" FORCE) -set(CMAKE_ASM_FLAGS "--target=xtensa-esp-elf -mcpu=esp32s3 -Xassembler --longcalls " CACHE STRING "Assembler Base Flags" FORCE)