├── requirements.in ├── tools ├── test │ └── .gitignore ├── zsh │ ├── _test-ref-configs.pl │ ├── _all.sh │ ├── _ssl-opt.sh │ └── _config.pl ├── README.md ├── bin │ ├── mbedtls-check-missing-changelog │ ├── asn1_indent │ ├── mbedtls-size-dwim │ └── mbedtls-test-language-server └── emacs │ └── mbedtls-autoloads.el ├── kb ├── attacks │ └── index.md ├── generic │ ├── index.md │ ├── ftp-folder-for-automatic-downloads.md │ ├── export-control-eccn-number-for-mbedtls.md │ ├── mbedtls-philosophy.md │ ├── is-mbedtls-fips-certified.md │ ├── rsassa-pss.md │ └── abstraction-layers.md ├── how-to │ ├── index.md │ ├── increasing_ssl_performance_and_tls_performance.md │ ├── uncrustify.md │ ├── generate-an-aes-key.md │ ├── encrypt-with-aes-cbc.md │ ├── code-size.md │ ├── add-a-random-generator.md │ ├── using-static-memory-instead-of-the-heap.md │ └── add-entropy-sources-to-entropy-pool.md ├── assets │ ├── mbedtls-stack.png │ ├── mbedtls-tutorial-eclipse-static-lib-1.png │ ├── mbedtls-tutorial-eclipse-static-lib-2.png │ ├── mbedtls-tutorial-eclipse-static-lib-3.png │ └── mbedtls-tutorial-eclipse-static-lib-4.png ├── index.md ├── licensing │ ├── index.md │ ├── copyright-and-contributions.md │ ├── using-mbedtls-in-a-non-apache-or-gpl-project.md │ └── how-is-mbedtls-protected.md ├── cryptography │ ├── index.md │ ├── rsa-encryption-maximum-data-size.md │ ├── use-external-rsa-private-key.md │ ├── ephemeral-diffie-hellman.md │ ├── providing-diffie-hellman-or-dhm-parameters.md │ ├── elliptic-curve-performance-nist-vs-brainpool.md │ └── rsa-key-pair-generator.md ├── development │ ├── index.md │ ├── generating-mbedtls-api-documentation-locally.md │ ├── tool-versions-lts-distributions.md │ ├── how-to-fill-rsa-context-from-n-e-p-and-q.md │ ├── debugging-tls.md │ ├── entropy-collection-and-random-generation-in-threaded-environment.md │ ├── how-are-error-codes-defined.md │ ├── thread-safety-and-multi-threading.md │ └── deprecation.md ├── testing │ ├── index.md │ ├── jenkins-blueocean-go-to-classic.png │ └── testing-qemu.md └── compiling-and-building │ ├── index.md │ ├── mbedtls-failed-to-compile.md │ ├── mbedtls-on-solaris.md │ ├── setup-eclipse-cdt-environment-on-windows.md │ └── how-do-i-configure-mbedtls.md ├── project ├── 20251125-psa-spec-vs-implementation.pdf ├── index.md ├── external-trusted-reviewers.md ├── vulnerabilities.md └── roadmap.md ├── reviews ├── How to be an effective Mbed TLS reviewer.pdf ├── index.md └── review-priorities.md ├── getting_started ├── index.md ├── downloading.md └── building.md ├── security-advisories ├── index.md ├── mbedtls-security-advisory-2024-01-2.md ├── mbedtls-security-advisory-2024-01-1.md ├── mbedtls-security-advisory-2021-07-1.md ├── mbedtls-security-advisory-2021-12.md ├── mbedtls-security-advisory-2019-12.md ├── mbedtls-security-advisory-2025-03-2.md ├── mbedtls-security-advisory-2025-06-4.md ├── mbedtls-security-advisory-2025-06-2.md ├── mbedtls-security-advisory-2021-07-2.md ├── polarssl-security-advisory-2014-03-poodle-attack-on-ssl-v3.md ├── mbedtls-security-advisory-2017-02.md ├── mbedtls-security-advisory-2024-08-1.md ├── mbedtls-security-advisory-2023-10-2.md ├── polarssl-security-advisory-2013-05.md ├── mbedtls-security-advisory-2019-10.md ├── polarssl-security-advisory-2013-04.md ├── polarssl-security-advisory-2013-02.md ├── polarssl-security-advisory-2014-01.md ├── mbedtls-security-advisory-2020-04.md ├── polarssl-security-advisory-2014-02.md ├── mbedtls-security-advisory-2020-02.md ├── mbedtls-security-advisory-2024-08-2.md ├── mbedtls-security-advisory-2025-06-7.md ├── polarssl-security-advisory-2011-02.md ├── mbedtls-security-advisory-2020-09-1.md ├── polarssl-security-advisory-2014-04.md ├── mbedtls-security-advisory-2020-09-2.md ├── mbedtls-security-advisory-2025-06-5.md ├── mbedtls-security-advisory-2022-07.md ├── mbedtls-security-advisory-2025-06-3.md ├── mbedtls-security-advisory-2020-07.md ├── mbedtls-security-advisory-2020-09-3.md ├── mbedtls-security-advisory-2024-10-1.md ├── mbedtls-security-advisory-2023-10-1.md ├── polarssl-security-advisory-2013-01.md ├── mbedtls-security-advisory-2024-08-3.md ├── mbedtls-security-advisory-2015-01.md ├── mbedtls-security-advisory-2025-03-1.md └── mbedtls-security-advisory-2025-06-6.md ├── README.md ├── Makefile ├── redirects.yaml ├── .readthedocs.yaml ├── make.bat ├── CONTRIBUTING.md ├── dco.txt ├── index.md ├── conf.py └── requirements.txt /requirements.in: -------------------------------------------------------------------------------- 1 | myst-parser 2 | readthedocs-cli 3 | sphinx-rtd-theme 4 | -------------------------------------------------------------------------------- /tools/test/.gitignore: -------------------------------------------------------------------------------- 1 | /clone-for-test 2 | /worktree-for-test-* 3 | /tmp-*-* 4 | -------------------------------------------------------------------------------- /kb/attacks/index.md: -------------------------------------------------------------------------------- 1 | # Attacks 2 | ```{toctree} 3 | --- 4 | glob: 5 | maxdepth: 1 6 | --- 7 | * 8 | ``` 9 | -------------------------------------------------------------------------------- /kb/generic/index.md: -------------------------------------------------------------------------------- 1 | # Generic 2 | ```{toctree} 3 | --- 4 | glob: 5 | maxdepth: 1 6 | --- 7 | * 8 | ``` 9 | -------------------------------------------------------------------------------- /kb/how-to/index.md: -------------------------------------------------------------------------------- 1 | # How to 2 | ```{toctree} 3 | --- 4 | glob: 5 | maxdepth: 1 6 | --- 7 | * 8 | ``` 9 | -------------------------------------------------------------------------------- /kb/assets/mbedtls-stack.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mbed-TLS/mbedtls-docs/HEAD/kb/assets/mbedtls-stack.png -------------------------------------------------------------------------------- /kb/index.md: -------------------------------------------------------------------------------- 1 | # Knowledge Base 2 | ```{toctree} 3 | --- 4 | glob: 5 | maxdepth: 2 6 | --- 7 | */index 8 | ``` 9 | -------------------------------------------------------------------------------- /kb/licensing/index.md: -------------------------------------------------------------------------------- 1 | # Licensing 2 | ```{toctree} 3 | --- 4 | glob: 5 | maxdepth: 1 6 | --- 7 | * 8 | ``` 9 | -------------------------------------------------------------------------------- /kb/cryptography/index.md: -------------------------------------------------------------------------------- 1 | # Cryptography 2 | ```{toctree} 3 | --- 4 | glob: 5 | maxdepth: 1 6 | --- 7 | * 8 | ``` 9 | -------------------------------------------------------------------------------- /kb/development/index.md: -------------------------------------------------------------------------------- 1 | # Development 2 | ```{toctree} 3 | --- 4 | glob: 5 | maxdepth: 1 6 | --- 7 | * 8 | ``` 9 | -------------------------------------------------------------------------------- /kb/testing/index.md: -------------------------------------------------------------------------------- 1 | # Testing Mbed TLS 2 | ```{toctree} 3 | --- 4 | glob: 5 | maxdepth: 1 6 | --- 7 | * 8 | ``` 9 | -------------------------------------------------------------------------------- /kb/compiling-and-building/index.md: -------------------------------------------------------------------------------- 1 | # Compiling and Building 2 | ```{toctree} 3 | --- 4 | glob: 5 | maxdepth: 1 6 | --- 7 | * 8 | ``` 9 | -------------------------------------------------------------------------------- /kb/testing/jenkins-blueocean-go-to-classic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mbed-TLS/mbedtls-docs/HEAD/kb/testing/jenkins-blueocean-go-to-classic.png -------------------------------------------------------------------------------- /project/20251125-psa-spec-vs-implementation.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mbed-TLS/mbedtls-docs/HEAD/project/20251125-psa-spec-vs-implementation.pdf -------------------------------------------------------------------------------- /kb/assets/mbedtls-tutorial-eclipse-static-lib-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mbed-TLS/mbedtls-docs/HEAD/kb/assets/mbedtls-tutorial-eclipse-static-lib-1.png -------------------------------------------------------------------------------- /kb/assets/mbedtls-tutorial-eclipse-static-lib-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mbed-TLS/mbedtls-docs/HEAD/kb/assets/mbedtls-tutorial-eclipse-static-lib-2.png -------------------------------------------------------------------------------- /kb/assets/mbedtls-tutorial-eclipse-static-lib-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mbed-TLS/mbedtls-docs/HEAD/kb/assets/mbedtls-tutorial-eclipse-static-lib-3.png -------------------------------------------------------------------------------- /kb/assets/mbedtls-tutorial-eclipse-static-lib-4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mbed-TLS/mbedtls-docs/HEAD/kb/assets/mbedtls-tutorial-eclipse-static-lib-4.png -------------------------------------------------------------------------------- /reviews/How to be an effective Mbed TLS reviewer.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mbed-TLS/mbedtls-docs/HEAD/reviews/How to be an effective Mbed TLS reviewer.pdf -------------------------------------------------------------------------------- /reviews/index.md: -------------------------------------------------------------------------------- 1 | # Reviews 2 | ```{toctree} 3 | review-for-contributors.md 4 | review_guidelines.md 5 | review-priorities.md 6 | review-for-gatekeepers.md 7 | ``` 8 | -------------------------------------------------------------------------------- /getting_started/index.md: -------------------------------------------------------------------------------- 1 | # Getting Started 2 | ```{toctree} 3 | --- 4 | glob: 5 | maxdepth: 2 6 | --- 7 | downloading.md 8 | building.md 9 | psa.md 10 | ``` 11 | -------------------------------------------------------------------------------- /security-advisories/index.md: -------------------------------------------------------------------------------- 1 | # Security Advisories 2 | 3 | ```{toctree} 4 | --- 5 | maxdepth: 1 6 | glob: 7 | reversed: 8 | --- 9 | polarssl-* 10 | * 11 | ``` 12 | -------------------------------------------------------------------------------- /getting_started/downloading.md: -------------------------------------------------------------------------------- 1 | # Downloading 2 | 3 | Mbed TLS releases are available in the [public GitHub repository](https://github.com/Mbed-TLS/mbedtls). 4 | To download directly, use the following Git command: 5 | 6 | ```sh 7 | git clone https://github.com/Mbed-TLS/mbedtls.git 8 | ``` 9 | -------------------------------------------------------------------------------- /project/index.md: -------------------------------------------------------------------------------- 1 | # Project 2 | 3 | ```{toctree} 4 | --- 5 | maxdepth: 2 6 | --- 7 | roadmap.md 8 | long-term-plans.md 9 | external-trusted-reviewers.md 10 | vulnerabilities.md 11 | ``` 12 | 13 | * [TF-PSA-Crypto 1.0 vs PSA Crypto API specification](20251125-psa-spec-vs-implementation.pdf): the main differences, with a few words on drivers. 14 | -------------------------------------------------------------------------------- /tools/zsh/_test-ref-configs.pl: -------------------------------------------------------------------------------- 1 | #compdef test-ref-configs.pl 2 | ## Completion for tests/test-ref-configs.pl in Mbed TLS. 3 | 4 | _test_ref_configs_pl () { 5 | compadd $(sed -n '/%configs *=/,/;/ s/^ *'\''\([^'\'']*\)'\'' => {$/\1/p' $words[1]) 6 | } 7 | 8 | _test_ref_configs_pl "%@" 9 | 10 | # Local Variables: 11 | # mode: sh 12 | # sh-shell: zsh 13 | # End: 14 | 15 | -------------------------------------------------------------------------------- /tools/README.md: -------------------------------------------------------------------------------- 1 | This directory contains various tools that may be of interest to 2 | developers who contribute to Mbed TLS. 3 | 4 | Most files in this directory were originally written for the author's 5 | personal use and have only had a very small amount of review. They might 6 | not work for other people, or behave strangely. They may change in 7 | incompatible ways at any time. Use at your own risk. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This repository hosts documentation related to Mbed TLS. 2 | 3 | * [Most Mbed TLS documentation is available via ReadTheDocs](https://mbed-tls.readthedocs.io/). 4 | * Information is also available on the [Mbed TLS website](https://www.trustedfirmware.org/projects/mbed-tls/). 5 | 6 | Unless otherwise indicated, all the content of this repository is distributed 7 | under the [Apache License 2.0](LICENSE). 8 | -------------------------------------------------------------------------------- /kb/development/generating-mbedtls-api-documentation-locally.md: -------------------------------------------------------------------------------- 1 | # Generating the API documentation locally 2 | 3 | ## Generating doxygen 4 | 5 | Mbed TLS has full doxygen documentation in the source code which is also available on the site in the [API documentation page](/api). 6 | 7 | To generate the documentation locally, [download](/download) and extract the latest Mbed TLS tarball and run: 8 | 9 | make apidoc 10 | 11 | This generates the doxygen documentation in the `apidoc` subdirectory. 12 | -------------------------------------------------------------------------------- /kb/licensing/copyright-and-contributions.md: -------------------------------------------------------------------------------- 1 | # Copyright and contributions 2 | 3 | ## Can I contribute? 4 | 5 | Yes, you can! We welcome all contributions that improve Mbed TLS. This can range from bug fixes, typo fixes and better platform support to new features and modules. 6 | 7 | It may be wise to [contact us](/contact) beforehand if you intend to contribute a larger feature. We might already be working on it internally and we don't like telling you: "*Ok. Thanks. But........ We already did it ourselves.*" 8 | -------------------------------------------------------------------------------- /project/external-trusted-reviewers.md: -------------------------------------------------------------------------------- 1 | # External Trusted Reviewers 2 | 3 | Mbed TLS welcomes contributors from the wider community who would be interested in helping with review. Especially active contributors may be granted Trusted Reviewer status. Trusted reviewers can approve a PR, and their approval will count towards the two that are normally required before the PR can be merged. 4 | 5 | We are grateful for the contribution of our current trusted reviewers: 6 | 7 | [David Brown](https://github.com/d3zd3z) 8 | 9 | [Demi Marie Obenour](https://github.com/DemiMarie) 10 | -------------------------------------------------------------------------------- /kb/cryptography/rsa-encryption-maximum-data-size.md: -------------------------------------------------------------------------------- 1 | # RSA encryption maximum data size 2 | 3 | RSA is only able to encrypt data to a maximum amount equal to your key size (2048 bits = 256 bytes), minus any padding and header data (11 bytes for PKCS#1 v1.5 padding). 4 | 5 | As a result, it is often not possible to encrypt files with RSA directly (and RSA is not designed for this). If you want to encrypt more data, you can do something like: 6 | 7 | 1. Generate a 256-bit random keystring K. 8 | 1. Encrypt your data with AES-CBC with K. 9 | 1. Encrypt K with RSA. 10 | 1. Send both to the other side. 11 | 12 | Of course you can also use another key-size, symmetric algorithm and cipher mode - but you get the gist. 13 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /redirects.yaml: -------------------------------------------------------------------------------- 1 | # Readthedocs redirects 2 | # See https://docs.readthedocs.io/en/stable/user-defined-redirects.html 3 | # 4 | # In order to prevent exposing the API token, PR jobs do not update the 5 | # redirects - changes to this file are only applied when they are merged 6 | # into the main branch. 7 | 8 | - type: html_to_clean_url 9 | from_url: / 10 | to_url: / 11 | 12 | - type: page 13 | from_url: /tech-updates/security-advisories 14 | to_url: /security-advisories/ 15 | 16 | - type: page 17 | from_url: /security-advisories/security-advisories 18 | to_url: /security-advisories/ 19 | 20 | - type: page 21 | from_url: /security-advisories/advisories/* 22 | to_url: /security-advisories/:splat 23 | 24 | - type: page 25 | from_url: /roadmap 26 | to_url: /project/roadmap/ 27 | -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | # .readthedocs.yaml 2 | # Read the Docs configuration file 3 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 4 | 5 | # Required 6 | version: 2 7 | 8 | # Set the version of Python and other tools you might need 9 | build: 10 | os: ubuntu-20.04 11 | tools: 12 | python: "3.9" 13 | jobs: 14 | post_build: 15 | - '[ "$READTHEDOCS_VERSION" != "latest" ] || "$READTHEDOCS_VIRTUALENV_PATH/bin/rtd" projects "Mbed TLS" redirects sync --wet-run -f redirects.yaml' 16 | 17 | # Build documentation in the docs/ directory with Sphinx 18 | sphinx: 19 | builder: dirhtml 20 | configuration: conf.py 21 | 22 | # Optionally declare the Python requirements required to build your docs 23 | python: 24 | install: 25 | - requirements: requirements.txt 26 | -------------------------------------------------------------------------------- /kb/licensing/using-mbedtls-in-a-non-apache-or-gpl-project.md: -------------------------------------------------------------------------------- 1 | # Using Mbed TLS in a non-Apache or GPL project 2 | 3 | ## Who should read this? 4 | 5 | Anyone maintaining a Free Open Source Software (FOSS) project who needs either a cryptographic library or a TLS library and who wants to use or integrate Mbed TLS in the software. 6 | 7 | ## Can I use Mbed TLS in my Open Source project? 8 | 9 | In short: Yes, you can. However, there are a few rules. As a result, a lot of Open Source projects worldwide already use Mbed TLS. 10 | 11 | We encourage and support the use of the Mbed TLS library in Open Source projects. You may be able to use Mbed TLS even if your project does not use the Apache 2.0 or GPL licenses. 12 | 13 | ## How does using Mbed TLS in a non-Apache project work? 14 | 15 | You should check if the license you use is compatible with the Apache 2.0 or GPL licenses. 16 | -------------------------------------------------------------------------------- /tools/bin/mbedtls-check-missing-changelog: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | help () { 5 | cat <&2 20 | exit 120 21 | fi 22 | if [[ "$1" == '--help' ]]; then 23 | help 24 | exit 25 | fi 26 | 27 | revision_range=$1 28 | merge_commits=$(git log --merges --first-parent --format=%H $revision_range) 29 | for c in $merge_commits; do 30 | if git diff --name-only $c~1 $c | grep -q ChangeLog; then 31 | continue 32 | fi 33 | git show -s --oneline $c | grep . 34 | done 35 | -------------------------------------------------------------------------------- /kb/compiling-and-building/mbedtls-failed-to-compile.md: -------------------------------------------------------------------------------- 1 | # Mbed TLS failed to compile on XXXX 2 | 3 | This can happen. We cannot anticipate all interactions between software version and platforms. 4 | 5 | We have an ever-expanding set of hardware and OS platforms on which Mbed TLS is automatically built. Please [open a discussion or file a ticket on Github](https://github.com/Mbed-TLS/mbedtls/issues), or [contact us directly](/contact). 6 | 7 | Please provide us with as much information as possible on: 8 | 9 | * The compilation error you encounter. 10 | * The compiler (type and version) you use. 11 | * The chipset of your system. 12 | * The operating system you use. 13 | 14 | 16 | -------------------------------------------------------------------------------- /make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | 13 | if "%1" == "" goto help 14 | 15 | %SPHINXBUILD% >NUL 2>NUL 16 | if errorlevel 9009 ( 17 | echo. 18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 19 | echo.installed, then set the SPHINXBUILD environment variable to point 20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 21 | echo.may add the Sphinx directory to PATH. 22 | echo. 23 | echo.If you don't have Sphinx installed, grab it from 24 | echo.http://sphinx-doc.org/ 25 | exit /b 1 26 | ) 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /kb/generic/ftp-folder-for-automatic-downloads.md: -------------------------------------------------------------------------------- 1 | # FTP folder for automatic downloads 2 | 3 | When automatically checking for newer versions of Arm Mbed TLS, it is helpful to have an FTP-like folder of HTTP-indices for automatic downloads, rather than a website to parse. 4 | 5 | We have two endpoints that provide you with more direct access: 6 | 7 | ## Current downloads 8 | 9 | See the [list of the current versions of the stable branches of Mbed TLS](/download-archive). 10 | 11 | ## Download archive 12 | 13 | See the [full archive of all versions of Mbed TLS](/code/releases). 14 | 15 | 16 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2024-01-2.md: -------------------------------------------------------------------------------- 1 | # Buffer overflow in mbedtls_x509_set_extension() 2 | 3 | **Title** | Buffer overflow in mbedtls_x509_set_extension(). 4 | ---|--- 5 | **CVE** | CVE-2024-23775 6 | **Date** | 09 January 2024 7 | **Affects** | All versions of Mbed TLS up to and including 2.28.6 and 3.5.1 8 | **Impact** | Potential DOS 9 | **Severity** | Low 10 | **Credit** | Jonathan Winzig (Hilscher Gesellschaft für Systemautomation mbH) 11 | 12 | ## Vulnerability 13 | 14 | When writing x509 extensions we failed to validate inputs passed in to 15 | mbedtls_x509_set_extension(), which could result in an integer overflow, causing 16 | a zero-length buffer to be allocated to hold the extension. The extension would 17 | then be copied into the buffer, causing a heap buffer overflow. 18 | 19 | ## Impact 20 | 21 | Potential segfault resulting from the buffer overflow, thus potential DOS. 22 | 23 | ## Resolution 24 | 25 | Affected users will want to upgrade to Mbed TLS 3.5.2 or 2.28.7 depending on the 26 | branch they're currently using. 27 | 28 | ## Work-around 29 | 30 | Ensure that a length of SIZE_MAX cannot be passed into 31 | mbedtls_x509_set_extension() 32 | -------------------------------------------------------------------------------- /kb/how-to/increasing_ssl_performance_and_tls_performance.md: -------------------------------------------------------------------------------- 1 | # Increasing SSL and TLS performance 2 | 3 | ## Situation 4 | 5 | If you use a specific cipher suite, like **TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA256** on your embedded platform, when you benchmark the individual cipher and hash speeds, the performance may be: 6 | 7 | * AES-128-CBC: 321 Kb/s 8 | * SHA256-HMAC: 441 Kb/s 9 | 10 | You expect a reasonable performance speed for your SSL connection as well. However, when you benchmark the sent and received SSL/TLS data, the performance is only about 9 Kb/s. 11 | 12 | ## Explanation 13 | 14 | The overhead of the SSL debug module should be negligible when `mbedtls_debug_set_threshold( 0 );` is called. You may still want to [disable **MBEDTLS_DEBUG_C** in `mbedtls_config.h`](../compiling-and-building/how-do-i-configure-mbedtls.md) in order to reduce the footprint and get the last few percent of performance improvement. 15 | 16 | 18 | -------------------------------------------------------------------------------- /kb/cryptography/use-external-rsa-private-key.md: -------------------------------------------------------------------------------- 1 | # Using an external RSA private key 2 | 3 | ## Use case 4 | 5 | The RSA private key is not available in exported form. It is located inside a smartcard or in a secure hardware module. Therefore, you are not able to load it the usual way. 6 | 7 | ## Providing your own functions 8 | 9 | Mbed TLS is designed for this, and allows you to set your own functions to be used for RSA decryption and signing during the SSL handshake. 10 | 11 | Set these functions by using `mbedtls_pk_setup_rsa_alt()`. This allows your application to provide an arbitrary blob as your RSA private key, accept function pointers performing decryption and signature, and return the key size, as above. 12 | 13 | You can then use the normal `mbedtls_set_own_cert()` function. From the perspective of the SSL module, the external RSA private key is just another PK context. 14 | 15 | ## PKCS#11 16 | 17 | If you are using a smartcard, you don't have to write your own logic. You can use the `libpkcs11-helper` library. 18 | 19 | Mbed TLS includes a helper class for using the `libpkcs11-helper` when you enable `MBEDTLS_PKCS11_C` in `config.h`. See [How do I configure Mbed TLS](../compiling-and-building/how-do-i-configure-mbedtls.md). 20 | -------------------------------------------------------------------------------- /tools/zsh/_all.sh: -------------------------------------------------------------------------------- 1 | #compdef all.sh tests_all 2 | ## Completion for tests/scripts/all.sh in Mbed TLS. 3 | 4 | _all_sh () { 5 | local components line opt spec specs 6 | components=() 7 | specs=() 8 | for line in "${(@M)${(@f)$(_call_program help $words[1] --help)}:# #-*}"; do 9 | line=${line##[ ]##} 10 | opt=(${(s:|:)${line%%[= ]*}}) 11 | spec= 12 | line=${line#"${line%%[= ]*}"} 13 | if [[ $line == \=* ]]; then 14 | spec=":${${line#\=}%% *}:" 15 | if [[ $spec == ":<"*">:" ]]; then 16 | spec=":${${spec#??}%??}:" 17 | fi 18 | case $spec in 19 | *_dir_path:) spec="${spec}_dirs";; 20 | *_path:) spec="${spec}_files -g \"*(.*)\"";; 21 | esac 22 | elif [[ $opt[1] == '-s' || $opt[1] == '--seed' ]]; then 23 | spec=":seed:" 24 | fi 25 | line=${line##[^ ]#[ ]##} 26 | spec="[$line]${spec}" 27 | specs+=($^opt$spec) 28 | if ((${#${(M)opt:#--list-components}})); then 29 | components=("${(@M)${(@f)$(_call_program list-components $words[1] --list-components)}}") 30 | fi 31 | done 32 | if (($#components)); then 33 | specs+=("*:component:($components)") 34 | fi 35 | _arguments : $specs 36 | } 37 | 38 | _all_sh "%@" 39 | 40 | # Local Variables: 41 | # mode: sh 42 | # sh-shell: zsh 43 | # End: 44 | 45 | -------------------------------------------------------------------------------- /kb/licensing/how-is-mbedtls-protected.md: -------------------------------------------------------------------------------- 1 | # How is Mbed TLS (formerly PolarSSL) protected legally? 2 | 3 | ## Copyright 4 | 5 | Mbed TLS (formerly known as PolarSSL) is, like most software, protected by copyright. It is licensed for use under a dual open-source Apache 2.0 OR GPL 2.0-or-later license. The *project* is owned by TrustedFirmware.org, and the code is owned by all the people and companies who have contributed to it, collectively known as *The Mbed TLS Contributors*. (Note: some files in the 3rdparty directory, not used in the default build, have a different copyright as noted in the file headers, and are licensed under only the Apache 2.0 license). 6 | 7 | When contributing code to us, the author is required to sign off all commits with a [Developer Certificate of Origin](../../dco.txt) line, confirming that the code submitted can (legally) become part of the project, and be subject to the same Apache 2.0 or GPL 2.0-or-later license. 8 | 9 | ## Trademark 10 | 11 | The PolarSSL brand name is trademarked in the US. You can see the trademark at USPTO for yourself. 12 | 13 | You can also find more information about using the Mbed trademark. 14 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2024-01-1.md: -------------------------------------------------------------------------------- 1 | # Timing side channel in private key RSA operations. 2 | 3 | **Title** | Timing side channel in private key RSA operations. 4 | ---|--- 5 | **CVE** | CVE-2024-23170 6 | **Date** | 10 January 2024 7 | **Affects** | All versions of Mbed TLS up to and including 2.28.6 and 3.5.1 8 | **Impact** | Potential recovery of plaintext 9 | **Severity** | Medium 10 | **Credit** | Hubert Kario (Red Hat) 11 | 12 | ## Vulnerability 13 | 14 | Mbed TLS is vulnerable to a timing side channel in private key RSA operations. 15 | This side channel could be sufficient for an attacker to recover the plaintext. 16 | A local attacker or a remote attacker who is close to the victim on the network 17 | might have precise enough timing measurements to exploit this. It requires the 18 | attacker to send a large number of messages for decryption. For details, 19 | see [Everlasting ROBOT: the Marvin Attack](https://eprint.iacr.org/2023/1442.pdf), Hubert Kario (Red Hat). 20 | 21 | ## Impact 22 | 23 | An attacker meeting the conditions above could potentially recover the 24 | plaintext. 25 | 26 | ## Resolution 27 | 28 | Affected users will want to upgrade to Mbed TLS 3.5.2 or 2.28.7 depending on the 29 | branch they're currently using. 30 | 31 | ## Work-around 32 | 33 | There is no known work-around. Affected users need to upgrade. -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Contributing to This Documentation 2 | ================================== 3 | 4 | We gratefully accept contributions from the community. 5 | 6 | As with any open source project, contributions will be reviewed by the project team and community and may need some modifications to be accepted. 7 | 8 | The documentation in this repository only undergoes a light review. Please contribute any documentation that you think could be useful, even if it's incomplete. We encourage quick, iterative improvements. 9 | 10 | Making a Contribution 11 | --------------------- 12 | 13 | For quick merging, the contribution should be short, and concentrated on a single topic. The larger the contribution is, the longer it would take to review it and merge it. 14 | 15 | All contributions are made under the [Apache License 2.0](LICENSE). 16 | 17 | 1. Fork the [Mbed TLS documentation repository on GitHub](https://github.com/Mbed-TLS/mbedtls-docs) to start making your changes. 18 | 1. Ensure that each commit has at least one `Signed-off-by:` line from the committer. If anyone else contributes to the commit, they should also add their own `Signed-off-by:` line. By adding this line, contributor(s) certify that the contribution is made under the terms of the [Developer Certificate of Origin](dco.txt). 19 | 1. Send a pull request (PR) and work with us until it gets merged and published. 20 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2021-07-1.md: -------------------------------------------------------------------------------- 1 | # Local side channel attack on RSA 2 | 3 | **Title** | Local side channel attack on RSA 4 | ---|--- 5 | **CVE** | (none) 6 | **Date** | 7th of July, 2021 7 | **Affects** | All versions of Mbed TLS 8 | **Impact** | A powerful local attacker can extract the private key 9 | **Severity** | High 10 | **Credit** | Zili Kou, Wenjian He, Sharad Sinha, and Wei Zhang 11 | 12 | ## Vulnerability 13 | 14 | The modular exponentiation operation in RSA uses a sliding window algorithm, 15 | with a memory access pattern that depends on the bits of the secret key. 16 | 17 | Exponent blinding is used as a counter-measure: it prevents an attacker from 18 | correlating informations gathered on successive operation, but researchers 19 | found a way to recover enough information by observing a single operation, 20 | therefore by-passing this counter-measure. 21 | 22 | ## Impact 23 | 24 | An attacker with access to precise enough timing and memory access information 25 | (typically an untrusted operating system attacking a secure enclave such as 26 | SGX or the TrustZone secure world) can recover the private keys used in RSA. 27 | 28 | ## Resolution 29 | 30 | Affected users will want to upgrade to Mbed TLS 3.0.0, 2.27.0 or 2.16.11 31 | depending on the branch they're currently using. 32 | 33 | ## Work-around 34 | 35 | None. 36 | -------------------------------------------------------------------------------- /tools/zsh/_ssl-opt.sh: -------------------------------------------------------------------------------- 1 | #compdef ssl-opt.sh compat.sh 2 | ## Completion for tests/ssl-opt.sh and tests/compat.sh in Mbed TLS. 3 | 4 | _compat_sh_set_values () { 5 | spec="$spec:$1: _values -s ' ' '$1' ${${line%'*}##*'}" 6 | } 7 | 8 | _ssl_opt_sh () { 9 | local line opt spec specs 10 | specs=() 11 | for line in "${(@M)${(@)${(@f)$(_call_program help $words[1] --help)}//$'\t'##/ }:# #-*}"; do 12 | line=${line## ##} 13 | opt=(${(s:|:)${line%%[= ]*}}) 14 | spec= 15 | line=${line#"${line%%[= ]*}"} 16 | line=${line##[^ ]# ##} 17 | spec="[$line]${spec}" 18 | case $words[1]:t:r in 19 | compat) 20 | case $opt[1] in 21 | -V) _compat_sh_set_values 'Verification modes';; 22 | -e) spec="${spec}:Exclude matching ciphersuites (BRE):";; 23 | -f) spec="${spec}:Restrict to matching ciphersuites (BRE):";; 24 | -m) _compat_sh_set_values 'Protocol versions';; 25 | -p) _compat_sh_set_values 'Peers';; 26 | -t) _compat_sh_set_values 'Key exchange types';; 27 | esac;; 28 | ssl-opt) 29 | case $opt[1] in 30 | -e|-f) spec="${spec}:BRE:";; 31 | --port|--*-port) spec="${spec}:port number:";; 32 | --seed) spec="${spec}:seed:";; 33 | esac;; 34 | esac 35 | specs+=($^opt$spec) 36 | done 37 | _arguments : $specs 38 | } 39 | 40 | _ssl_opt_sh "%@" 41 | 42 | # Local Variables: 43 | # mode: sh 44 | # sh-shell: zsh 45 | # End: 46 | 47 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2021-12.md: -------------------------------------------------------------------------------- 1 | # Double Free in `mbedtls_ssl_set_session()` in an error case. 2 | 3 | **Title** | Double Free in `mbedtls_ssl_set_session()` in an error case. 4 | ---|--- 5 | **CVE** | CVE-2021-44732 6 | **Date** | 14th of December, 2021 7 | **Affects** | All versions of Mbed TLS 8 | **Impact** | An attacker could create memory / heap corruption. 9 | **Severity** | High 10 | **Credit** | duckPowerMB 11 | 12 | ## Vulnerability 13 | If `mbedtls_ssl_set_session()` or `mbedtls_ssl_get_session()` were to fail with `MBEDTLS_ERR_SSL_ALLOC_FAILED` (in an out of memory condition), then calling `mbedtls_ssl_session_free()` and `mbedtls_ssl_free()` in the usual manner would cause an internal session buffer to be freed twice, due to two structures both having valid pointers to it after a call to `ssl_session_copy()`. 14 | 15 | ## Impact 16 | 17 | An attacker could potentially trigger the out of memory condition, and therefore use this bug to create memory corruption, which could then be further exploited or targetted. 18 | 19 | ## Resolution 20 | 21 | Affected users will want to upgrade to Mbed TLS 3.1.0, 2.28.0 or 2.16.12 depending on the branch they're currently using. 22 | 23 | ## Work-around 24 | Either do not call `mbedtls_ssl_session_free()` (which will unfortunately cause a memory leak) or set the `mbedtls_ssl_session` field `ticket` to NULL manually, in the case where either `mbedtls_ssl_set_session()` or `mbedtls_ssl_get_session()` returns `MBEDTLS_ERR_SSL_ALLOC_FAILED`. 25 | 26 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2019-12.md: -------------------------------------------------------------------------------- 1 | # Side channel attack on ECDSA 2 | 3 | **Title** | Side channel attack on ECDSA 4 | ---|--- 5 | **CVE** | CVE-2019-18222 6 | **Date** | 15th January 2020 ( **Updated on 27th January 2020** ) 7 | **Affects** | All versions of Mbed TLS and Mbed Crypto 8 | **Impact** | The private key is recoverable through side channels. 9 | **Severity** | High 10 | **Credit** | Alejandro Cabrera Aldaya and Billy Brumley 11 | 12 | ## Vulnerability 13 | 14 | Our bignum implementation is not constant time/constant trace, so side channel 15 | attacks can retrieve the blinded value, factor it (as it is smaller than RSA 16 | keys and not guaranteed to have only large prime factors), and then, by brute 17 | force, recover the key. Reported by Alejandro Cabrera Aldaya and Billy 18 | Brumley. 19 | 20 | ## Impact 21 | 22 | If the adversary is in the position to launch a cache attack, then they may be 23 | able to recover the private key. 24 | 25 | ## Resolution 26 | 27 | Affected users should upgrade to one of the most recent versions of Mbed TLS, 28 | including 2.20.0, 2.16.4 or 2.7.13 or later. Similarly, affected users should 29 | upgrade to the most recent version of Mbed Crypto, including 3.0.1 or later. 30 | 31 | **edit:** Earlier, this document falsely stated that Mbed Crypto 3.0.0 fixes 32 | this issue. This is not true, Mbed Crypto 3.0.1 is the earliest version with 33 | the fix. Users should upgrade to Mbed Crypto 3.0.1 or later. 34 | 35 | ## Workaround 36 | 37 | There are no known workarounds. 38 | -------------------------------------------------------------------------------- /tools/zsh/_config.pl: -------------------------------------------------------------------------------- 1 | #compdef config.pl config.py 2 | ## Completion for scripts/config.pl and scripts/config.pl in Mbed TLS. 3 | 4 | _config_pl_symbols () { 5 | local -a identifiers 6 | identifiers=("${(@f)$(_call_program _config_pl_symbols sed -n \''s!^/*\**#define \(MBEDTLS_[0-9A-Z_a-z][0-9A-Z_a-z]*\).*!\1!p'\' \$config_h)}") 7 | _describe -t symbols 'config.h symbols' identifiers 8 | } 9 | 10 | _config_pl () { 11 | local context state state_descr line 12 | typeset -A opt_args 13 | local ret=0 config_h 14 | config_h=($words[1]:h/../include/mbedtls/(mbedtls_|)config.h(N[1])) 15 | local -a commands_with_descriptions 16 | commands_with_descriptions=( 17 | 'baremetal:All features for bare metal platforms' 18 | 'get:Get symbol value' 19 | 'full:All features' 20 | 'realfull:Uncomment all #define'\''' 21 | 'set:Actvate symbol' 22 | 'unset:Deactivate symbol' 23 | ) 24 | _arguments \ 25 | {'-f','--file'}'[file to edit]:file to edit:_files -g "*.h"' \ 26 | {'-o','--force'}'[define symbol even if not present]' \ 27 | '1:config.pl command:->command' \ 28 | '*::config.pl commands:->param' 29 | case $state in 30 | (command) 31 | _describe -t commands 'config.pl command' commands_with_descriptions;; 32 | (param) 33 | case $words[1]:$CURRENT in 34 | ((get|set|unset):2) _call_function ret _config_pl_symbols;; 35 | esac;; 36 | esac 37 | return $ret 38 | } 39 | 40 | _config_pl "%@" 41 | 42 | # Local Variables: 43 | # mode: sh 44 | # sh-shell: zsh 45 | # End: 46 | 47 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2025-03-2.md: -------------------------------------------------------------------------------- 1 | # Potential authentication bypass in TLS handshake 2 | 3 | **Title** | Potential authentication bypass in TLS handshake 4 | --------- | ---------------------------------------------------------- 5 | **CVE** | CVE-2025-27810 6 | **Date** | 24 March 2025 7 | **Affects** | All versions of Mbed TLS 8 | **Severity** | MEDIUM 9 | 10 | ## Vulnerability 11 | 12 | During the TLS handshake, the Finished message ensures that the handshake has not been tampered with by an active attacker. If a memory allocation fails or a cryptographic hardware driver returns an error at a specific point during the handshake, the Finished message will be incorrectly calculated to be the contents of uninitialized stack memory. 13 | 14 | ## Impact 15 | 16 | An attacker with the ability to trigger memory allocation failures or cryptographic hardware failures may be able to exploit this to break the security guarantees of the TLS handshake. This may mean that they are able to tamper with the handshake through a Man in the Middle attack or replay handshake messages to impersonate a legitimate peer. 17 | 18 | ## Affected versions 19 | 20 | All versions of Mbed TLS up to 2.28.9 and all versions of Mbed TLS 3.x up to 3.6.2 are affected. 21 | 22 | ## Resolution 23 | 24 | Affected users should upgrade to Mbed TLS 3.6.3 or Mbed TLS 2.28.10 25 | 26 | ## Work-around 27 | 28 | Ensure that enough memory is available before performing a handshake and that any cryptographic hardware drivers used for hash functions cannot return errors. 29 | -------------------------------------------------------------------------------- /dco.txt: -------------------------------------------------------------------------------- 1 | Developer Certificate of Origin 2 | Version 1.1 3 | 4 | Copyright (C) 2004, 2006 The Linux Foundation and its contributors. 5 | 1 Letterman Drive 6 | Suite D4700 7 | San Francisco, CA, 94129 8 | 9 | Everyone is permitted to copy and distribute verbatim copies of this 10 | license document, but changing it is not allowed. 11 | 12 | 13 | Developer's Certificate of Origin 1.1 14 | 15 | By making a contribution to this project, I certify that: 16 | 17 | (a) The contribution was created in whole or in part by me and I 18 | have the right to submit it under the open source license 19 | indicated in the file; or 20 | 21 | (b) The contribution is based upon previous work that, to the best 22 | of my knowledge, is covered under an appropriate open source 23 | license and I have the right under that license to submit that 24 | work with modifications, whether created in whole or in part 25 | by me, under the same open source license (unless I am 26 | permitted to submit under a different license), as indicated 27 | in the file; or 28 | 29 | (c) The contribution was provided directly to me by some other 30 | person who certified (a), (b) or (c) and I have not modified 31 | it. 32 | 33 | (d) I understand and agree that this project and the contribution 34 | are public and that a record of the contribution (including all 35 | personal information I submit with it, including my sign-off) is 36 | maintained indefinitely and may be redistributed consistent with 37 | this project or the open source license(s) involved. 38 | -------------------------------------------------------------------------------- /kb/how-to/uncrustify.md: -------------------------------------------------------------------------------- 1 | # Using uncrustify in Mbed TLS 2 | 3 | ## Installing uncrustify 4 | 5 | Note that you need uncrustify 0.75.1. Older or newer versions produce different output. This section contains some tips on installing the required version of uncrustify. 6 | 7 | ### Compiling from source 8 | 9 | You need a C++ compiler, CMake, and Python 3. The following instructions work on most systems with development tools installed: 10 | 11 | ```sh 12 | git clone https://github.com/uncrustify/uncrustify 13 | git checkout uncrustify-0.75.1 14 | mkdir build 15 | cd build 16 | cmake -DCMAKE_BUILD_TYPE=Release .. 17 | ``` 18 | This creates an `uncrustify` executable in the `build` directory. Copy it somewhere on your command search `PATH`. Optionally, also install the manual page `uncrustify.1`. 19 | 20 | ### macOS: installing an older uncrustify from Homebrew 21 | 22 | ```sh 23 | brew tap-new local/for-mbedtls 24 | brew extract --version=0.75.1 uncrustify local/for-mbedtls 25 | brew install local/for-mbedtls/uncrustify@0.75.1 26 | ``` 27 | 28 | If you also have the latest uncrustify installed, the `install` command will complain that it can’t create the `uncrustify` symbolic link, but you still have uncrustify 0.75.1 available at `/opt/homebrew/Cellar/uncrustify@0.75.1/0.75.1/bin/uncrustify` (if the brew prefix is `/opt/homebrew`). Put `/opt/homebrew/Cellar/uncrustify@0.75.1/0.75.1/bin` first in your `PATH` when working on Mbed TLS. 29 | 30 | ### Windows binaries 31 | 32 | You can download [official Windows binaries hosted on Sourceforge](https://sourceforge.net/projects/uncrustify/files/uncrustify-0.75.1/). 33 | -------------------------------------------------------------------------------- /project/vulnerabilities.md: -------------------------------------------------------------------------------- 1 | # Security Vulnerability Processes 2 | 3 | ## Reporting a vulnerability 4 | 5 | If you think you have found an Mbed TLS security vulnerability, then please send an email to the security team at . For more information on the reporting and disclosure process, please see the [TrustedFirmware.org security incident handling process](https://trusted-firmware-docs.readthedocs.io/en/latest/security_center/incident_handling_process.html). There are some caveats to that process when applied to Mbed TLS, as listed below: 6 | 7 | - Mbed TLS currently does not have any registered ESSes and so there is no primary embargo period. 8 | - Mbed TLS contains strong cryptography software and to comply with export control restrictions, must only distribute software publicly. As a result, security fixes cannot be shared privately with Trusted Stakeholders, although other vulnerability information can be. 9 | - The nature of Mbed TLS often means that security fixes reveal enough information for a skilled attacker to re-construct the originally reported exploit. This combined with the previous caveat means we often expect to have to withhold security fixes until the public disclosure date. 10 | - Mbed TLS is subject to a lot of scrutiny by security researchers who often have their own disclosure timelines when reporting vulnerabilities. As a result, the default 90 days public embargo period may often not apply. 11 | 12 | ## Advisories 13 | 14 | Please see [the security advisories page](../security-advisories/index.md) for a complete list of Mbed TLS security advisories. 15 | -------------------------------------------------------------------------------- /kb/generic/export-control-eccn-number-for-mbedtls.md: -------------------------------------------------------------------------------- 1 | # What is the export control status of Mbed TLS? 2 | 3 | Mbed TLS, as supplied in the open source repository, is considered open source 4 | and publicly available for purposes of the U.S. Export Administration 5 | Regulations (EAR) and as such, is not subject to the EAR. 6 | 7 | Your usage of, or any modifications or changes you make to, Mbed TLS may affect 8 | the export control status of Mbed TLS under the EAR and any other applicable 9 | export control regimes. As noted on the 10 | [U.S. BIS website](https://www.bis.doc.gov/index.php/policy-guidance/encryption/1-encryption-items-not-subject-to-the-ear): 11 | 12 | > While open source code itself may be publicly available and not subject to 13 | the EAR, an item is not considered publicly available merely because it 14 | incorporates or calls to publicly available open source code. Rather, a new 15 | item with encryption functionality has been created which would need to be 16 | evaluated as a whole under the EAR. 17 | 18 | The information provided here is intended to assist you with your determination 19 | of the applicable export compliance requirements and does not, and is not 20 | intended to, constitute legal advice. It remains your responsibility to comply 21 | with applicable export controls and sanctions regimes, and to consult 22 | applicable government authorities and/or counsel as needed. 23 | 24 | 25 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2025-06-4.md: -------------------------------------------------------------------------------- 1 | # Out-of-bounds read in mbedtls_lms_import_public_key() 2 | 3 | **Title** | Out-of-bounds read in mbedtls_lms_import_public_key() 4 | --------- | ---------------------------------------------------------- 5 | **CVE** | CVE-2025-49601 6 | **Date** | 2025-06-30 7 | **Affects** | Mbed TLS 3.3.0 through 3.6.3 8 | **Not affected** | Mbed TLS 3.6.4 and later 3.6 versions and upcoming TF-PSA-Crypto 1.0 and later versions 9 | **Impact** | Denial of service and possible information disclosure 10 | **Severity** | MEDIUM 11 | **Credits** | Found and reported by Linh Le and Ngan Nguyen from Calif. 12 | 13 | ## Vulnerability 14 | 15 | An LMS public key starts with a 4-byte type indicator. The function `mbedtls_lms_import_public_key()` 16 | reads this type indicator before validating the size of its input. 17 | 18 | If a public key is shorted than 4 bytes, the function performs a buffer overread of up to 4 bytes, 19 | resulting in undefined behavior. In practice this can only cause a crash and, at most, 20 | leak whether those four bytes match a fixed value. No arbitrary code execution is possible. 21 | 22 | ## Impact 23 | 24 | Denial of service and possible information disclosure of a few bytes of adjacent memory. 25 | No arbitrary code execution or large‐scale memory disclosure is possible. 26 | 27 | ## Affected versions 28 | 29 | Mbed TLS 3.3.0 through 3.6.3 30 | 31 | ## Resolution 32 | 33 | Affected users should upgrade to Mbed TLS 3.6.4 or upcoming TF-PSA-Crypto 1.0 or later. 34 | 35 | ## Work-around 36 | 37 | Validate that the key provided to `mbedtls_lms_import_public_key()` is at least 4 bytes long. 38 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2025-06-2.md: -------------------------------------------------------------------------------- 1 | # Heap buffer under-read when parsing PEM-encrypted material 2 | 3 | **Title** | Heap buffer under-read when parsing PEM-encrypted material 4 | --------- | ---------------------------------------------------------- 5 | **CVE** | CVE-2025-52497 6 | **Date** | 30 June 2025 7 | **Affects** | All versions of Mbed TLS up to 3.6.3 included 8 | **Not affected** | Mbed TLS 3.6.4 and later 3.6 versions, upcoming releases of TF-PSA-Crypto (1.0 and later) 9 | **Impact** | Denial of service, or potential information disclosure (CWE-127) 10 | **Severity** | MEDIUM 11 | **Credits** | Found and reported by Linh Le and Ngan Nguyen from Calif. 12 | 13 | ## Vulnerability 14 | 15 | When parsing invalid PEM-encrypted material (with `mbedtls_pk_parse_key()`, 16 | `mbedtls_pk_parse_keyfile()` or `mbedtls_pem_read_buffer()`), the decryption 17 | code may attempt reading 1 byte before the beginning of a heap buffer (that was 18 | allocated by the same function). 19 | 20 | ## Impact 21 | 22 | This will typically result in a Denial of Service, or limited information 23 | disclosure. 24 | 25 | ## Affected versions 26 | 27 | All versions of Mbed TLS up to 3.6.3 are affected. 28 | 29 | ## Resolution 30 | 31 | Affected users should upgrade to Mbed TLS 3.6.4 or later - or TF PSA Crypto 1.0 32 | or later when it is released. 33 | 34 | ## Work-around 35 | 36 | Applications are only affected if they process untrusted PEM-encrypted material 37 | (that is, if they call one of the above functions with a non-NULL password 38 | argument and untrusted PEM input). 39 | 40 | Applications built with `MBEDTLS_PEM_C` disabled are not affected. 41 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2021-07-2.md: -------------------------------------------------------------------------------- 1 | # Local side channel attack on static Diffie-Hellman with Montgomery curves 2 | 3 | **Title** | Local side channel attack on static Diffie-Hellman with
Montgomery curves 4 | ---|--- 5 | **CVE** | (none) 6 | **Date** | 7th of July, 2021 7 | **Affects** | All versions of Mbed TLS and Mbed Crypto 8 | **Impact** | A local attacker can extract the private key 9 | **Severity** | High 10 | **Credit** | Leila Batina, Lukas Chmielewski, Björn Haase, Niels Samwel and
Peter Schwabe 11 | 12 | ## Vulnerability 13 | 14 | The Montgomery curves Curve25519 and Curve448, also known as x25519 and x448 15 | when used for Diffie-Hellman, were designed to minimize the number of checks 16 | an implementation needs to do for secure use. 17 | 18 | In particular, validity of the peer's public key needs not be checked, as long 19 | as the underlying multi-precision (bignum) arithmetic is constant-time. This 20 | is not the case in Mbed TLS, but validity checks were still skipped, so an 21 | attacker could exploit special inputs (low-order points) in order to cause 22 | variations in timing and memory access patterns that would in turn leak 23 | information about the private key. 24 | 25 | ## Impact 26 | 27 | An attacker with access to precise enough timing and memory access information 28 | (for example, able to execute arbitrary code and sharing a memory cache with 29 | the victim) can recover the private keys used in static Diffie-Hellman with 30 | x25519 and x448. 31 | 32 | ## Resolution 33 | 34 | Affected users will want to upgrade to Mbed TLS 3.0.0, 2.27.0 or 2.16.11 35 | depending on the branch they're currently using. 36 | 37 | ## Work-around 38 | 39 | None. 40 | -------------------------------------------------------------------------------- /security-advisories/polarssl-security-advisory-2014-03-poodle-attack-on-ssl-v3.md: -------------------------------------------------------------------------------- 1 | # PolarSSL Security Advisory 2014-03 2 | 3 | **Title** | POODLE attack on SSLv3 4 | ---|--- 5 | **CVE** | CVE-2014-3566 6 | **Date** | 16th of October 2014 7 | **Affects** | The SSL v3 protocol 8 | **Not affected** | TLS 1.0 and up 9 | **Impact** | Potential disclosure of information 10 | **Exploit** | Active Man-in-the-Middle required 11 | 12 | On October the 14th a paper was released on the so-called POODLE attack on 13 | SSLv3. 14 | 15 | This Security Advisory only describes the impact and workaround for the POODLE 16 | attack. A more detailed explanation can be found in our post that puts [the 17 | POODLE attack in 18 | perspective](/tech-updates/blog/sslv3-and-poodle-in-perspective). 19 | 20 | ## Impact of POODLE 21 | 22 | The POODLE attack assumes that the attacker is successful in actively 23 | manipulating the packets of the handshake between the client and the server, 24 | resulting in a downgraded SSL v3 connection. 25 | 26 | If the attacker is then able to actively manipulate packets sent during the 27 | connection, the impact can be leakage of secret information, such as the 28 | session cookie in HTTPS. 29 | 30 | For a lot of protocols other than HTTPS there is no real impact as there is 31 | nothing to reveal that is session bound and not incidental. 32 | 33 | ## Workaround and resolution 34 | 35 | PolarSSL allows you to disable SSLv3 at compile time and at runtime. 36 | 37 | If you disable `POLARSSL_SSL_PROTO_SSL3` in _config.h_ , support for SSLv3 is 38 | not compiled into your library. 39 | 40 | At runtime you can call: 41 | 42 | 43 | 44 | ssl_set_min_version( ssl, SSL_MAJOR_VERSION_3, SSL_MINOR_VERSION_1 ); 45 | 46 | 47 | This forces your SSL context to only negotiate TLS 1.0 or higher. 48 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2017-02.md: -------------------------------------------------------------------------------- 1 | # mbed TLS Security Advisory 2017-02 2 | 3 | **Title** | Bypass of authentication of peer possible when the authentication
mode is configured as 'optional' 4 | ---|--- 5 | **Date** | 28th August 2017 6 | **Affects** | All versions of mbed TLS from version 1.3.10 and up, including
all 2.1 and later releases 7 | **Not affected** | mbed TLS 1.3.9 and earlier 8 | **Impact** | Use of the 'optional' authentication mode can permit the peer to
bypass peer authentication 9 | **Severity** | High 10 | 11 | ## Vulnerability 12 | 13 | If a malicious peer supplies an X.509 certificate chain that has more than 14 | `MBEDTLS_X509_MAX_INTERMEDIATE_CA` intermediates (which by default is 8), it 15 | could bypass authentication of the certificates, when the authentication mode 16 | was set to 'optional' eg. `MBEDTLS_SSL_VERIFY_OPTIONAL`. The issue could be 17 | triggered remotely by both the client and server sides. 18 | 19 | If the authentication mode, which can be set by the function 20 | `mbedtls_ssl_conf_authmode()`, was set to 'required' eg. 21 | `MBEDTLS_SSL_VERIFY_REQUIRED` which is the default, authentication would occur 22 | normally as intended. 23 | 24 | ## Impact 25 | 26 | Depending on the platform, an attack exploiting this vulnerability could allow 27 | successful impersonation of the intended peer and permit man-in-the-middle 28 | attacks. 29 | 30 | ## Resolution 31 | 32 | Affected users should upgrade to mbed TLS 1.3.21, mbed TLS 2.1.9 or mbed TLS 33 | 2.6.0. 34 | 35 | ## Workaround 36 | 37 | Users should wherever possible upgrade to the newer version of mbed TLS. Where 38 | this is not practical, users should consider if changing the authentication to 39 | the 'required' mode `MBEDTLS_SSL_VERIFY_REQUIRED` is practical for their 40 | application. 41 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2024-08-1.md: -------------------------------------------------------------------------------- 1 | # CTR\_DRBG prioritized over HMAC\_DRBG as the PSA DRBG 2 | 3 | **Title** | CTR\_DRBG prioritized over HMAC\_DRBG as the PSA DRBG 4 | --------- | ----------------------------------------------------- 5 | **CVE** | CVE-2024-45157 6 | **Date** | 30 August 2024 7 | **Affects** | All versions of Mbed TLS since 2.26.0 8 | **Severity** | Low 9 | 10 | ## Vulnerability 11 | 12 | Mbed TLS 2.26.0 introduced the configuration option `MBEDTLS_PSA_HMAC_DRBG_MD_TYPE` and documented that enabling it explicitly would cause the PSA cryptography subsystem to use HMAC\_DRBG as its pseudorandom generator component. However, this feature was accidentally documented but not implemented. In fact, all versions of Mbed TLS and Mbed Crypto have used CTR\_DRBG in the PSA subsystem if `MBEDTLS_CTR_DRBG_C` is enabled, regardless of whether `MBEDTLS_PSA_HMAC_DRBG_MD_TYPE` is set. 13 | 14 | ## Impact 15 | 16 | Both HMAC\_DRBG (using a hash such as SHA-256 or SHA-512) and CTR\_DRBG (using AES) are generally acceptable choices as pseudorandom generators, and both are secure in terms of the quality of their output. However, they have different security postures with respect to side channels. In particular, when AES is implemented in software, it is more prone to timing and power side channels than hashes, so CTR\_DRBG is weaker against side channel attacks than HMAC\_DRBG. Hence some users may prefer to use HMAC\_DRBG. 17 | 18 | ## Resolution 19 | 20 | Starting with Mbed TLS 3.6.1 and 2.28.9, the documentation accurately represents the behavior. The behavior does not change: `MBEDTLS_PSA_HMAC_DRBG_MD_TYPE` is ignored when PSA uses CTR\_DRBG. 21 | 22 | ## Work-around 23 | 24 | To use HMAC\_DRBG as the pseudorandom generator in the PSA subsystem, make sure that the compile-time option `MBEDTLS_CTR_DRBG_C` is disabled. 25 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2023-10-2.md: -------------------------------------------------------------------------------- 1 | # Buffer overflow in TLS handshake parsing with ECDH 2 | 3 | **Title** | Buffer overflow in TLS handshake parsing with ECDH 4 | ---|--- 5 | **CVE** | CVE-2023-45199 6 | **Date** | 05 October 2023 7 | **Affects** | Mbed TLS 3.2.0 and above 8 | **Impact** | A remote attacker may cause arbitrary code execution. 9 | **Severity** | HIGH 10 | **Credit** | OSS-Fuzz 11 | 12 | ## Vulnerability 13 | 14 | A TLS 1.3 client or server configured with support for signature-based authentication (i.e. any non-PSK key exchange) is vulnerable to a heap buffer overflow. The server copies up to 65535 bytes in a buffer that is shorter. An unauthenticated malicious peer can overflow the TLS handshake structure by sending an overly long ECDH or FFDH public key. 15 | 16 | A TLS 1.2 server configured with `MBEDTLS_USE_PSA_CRYPTO` and with support for a cipher suite using ECDH and a signature is vulnerable to a heap buffer overflow. An unauthenticated malicious peer can overflow the TLS handshake structure by sending an overly long ECDH public key. The server copies up to 255 bytes into a heap buffer that is sized for a valid public key, and thus shorter unless RSA or FFDH is enabled in addition to ECDH. TLS 1.2 clients, and builds without `MBEDTLS_USE_PSA_CRYPTO` are not affected. 17 | 18 | ## Impact 19 | 20 | A malicious peer can overflow a buffer on the heap with attacker-controlled data. This can often be escalated to remote code execution. 21 | 22 | ## Resolution 23 | 24 | Affected users will want to upgrade to Mbed TLS 3.5.0. 25 | 26 | ## Work-around 27 | 28 | The default configuration is not affected. Mbed TLS 2.28 is not affected. 29 | 30 | In TLS 1.2, builds that support RSA or FFDH with keys of size at least 2048 bits in addition to ECDH are not affected. Note that the TLS 1.3 stack remains affected in that case. 31 | -------------------------------------------------------------------------------- /kb/generic/mbedtls-philosophy.md: -------------------------------------------------------------------------------- 1 | # Mbed TLS design 2 | 3 | ## The philosophy behind Mbed TLS 4 | 5 | Mbed TLS takes a lean-and-mean approach to software development. We have designed it to be easy to use by being readable, documented, tested, loosely coupled and portable. 6 | 7 | 8 | ### Documented 9 | 10 | Mbed TLS has a large amount of documentation online, including the [full doxygen API documentation](/api), the [Design Documentation for security evaluations](/high-level-design), [example applications](/source-code) and more. 11 | 12 | 13 | ### Tested 14 | 15 | The automatic test suites contain over 6000 unit tests for cryptographic validation, regression testing and code coverage, over 200 functional tests and over 2000 interoperability tests. See our [quality assurance page](what-tests-and-checks-are-run-for-polarssl.md) for more details. 16 | 17 | 18 | ### Loosely coupled 19 | 20 | The Mbed TLS modules are as loosely coupled as possible. If you want to use AES, then copy `aes.c` and `aes.h`. No other files are required and this is valid for all symmetric and hash algorithms. Other modules are as straightforward, though some require the modules that they are dependent on. All portability code is present in the modules themselves. While, in some cases, this can create duplicate defines, putting the portability code in a central header-file allows for the loose coupling that we are aiming for. 21 | 22 | 23 | ### Portable 24 | 25 | Mbed TLS is written in portable C code. As mentioned in the [coding standards article](../development/mbedtls-coding-standards.md#iso-c99), the library uses the C99 ISO standard. 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /security-advisories/polarssl-security-advisory-2013-05.md: -------------------------------------------------------------------------------- 1 | # PolarSSL Security Advisory 2013-05 2 | 3 | **Title** | Timing Attack against protected RSA-CRT implementation used in
PolarSSL 4 | ---|--- 5 | **CVE** | CVE-2013-5915 6 | **Date** | 1st of October 2013 ( **Updated on 3rd of October 2013** ) 7 | **Affects** | PolarSSL versions prior to 1.2.9 and 1.3.0 8 | **Not affected** | PolarSSL 1.3.0 and above 9 | **Impact** | Recovery of the private RSA key 10 | **Exploit** | Withheld 11 | **Solution** | Upgrade to PolarSSL 1.3.0 or 1.2.9 12 | **Credits** | Cyril Arnaud and Pierre-Alain Fouque 13 | 14 | The researchers Cyril Arnaud and Pierre-Alain Fouque investigated the PolarSSL 15 | RSA implementation and discovered a bias in the implementation of the 16 | Montgomery multiplication that we used. For which they then show that it can 17 | be used to mount an attack on the RSA key. Although their test attack is done 18 | on a local system, there seems to be enough indication that this can properly 19 | be performed from a remote system as well. 20 | 21 | The attack has been added to the known attacks in [our Security 22 | Center](../security-advisories.md). 23 | 24 | ## Impact 25 | 26 | All versions prior to PolarSSL 1.2.9 and 1.3.0 are affected if a third party 27 | can send arbitrary handshake messages to your server. 28 | 29 | If correctly executed, this attack reveals the entire private RSA key after a 30 | large number of attack messages (> 600.000 on a local machine) are sent to 31 | show the timing differences. 32 | 33 | ## Workaround 34 | 35 | Disable CRT (`#define POLARSSL_RSA_NO_CRT`) in _config.h_. Your code will be 36 | much slower, but unaffected by this attack. 37 | 38 | ## Resolution 39 | 40 | Upgrade to PolarSSL version 1.3.0 of 1.2.9. 41 | 42 | ## Advice 43 | 44 | We strongly advise you to consider upgrading to the 1.3 branch if outside 45 | parties are present or can connect to your network. 46 | -------------------------------------------------------------------------------- /kb/testing/testing-qemu.md: -------------------------------------------------------------------------------- 1 | # Testing non-native architectures with QEMU 2 | 3 | This page shows how to test Mbed TLS on Linux for CPUs you don't have, assuming the target CPU can also run Linux. 4 | 5 | ## Preparing Ubuntu for building and testing with QEMU 6 | 7 | Add other targets to your package sources in a new file `/etc/apt/sources.list.d/ubuntu-foreign.list`. Note that ordinary Ubuntu mirrors only have PC builds, so you need a `ports` mirror. For example: 8 | 9 | ``` 10 | deb [arch=arm64,armhf,ppc64,s390x] http://fr.ports.ubuntu.com/ubuntu-ports focal main restricted universe multiverse 11 | deb [arch=arm64,armhf,ppc64,s390x] http://fr.ports.ubuntu.com/ubuntu-ports focal-security main restricted universe multiverse 12 | deb [arch=arm64,armhf,ppc64,s390x] http://fr.ports.ubuntu.com/ubuntu-ports focal-updates main restricted universe multiverse 13 | ``` 14 | 15 | Then install `libc6-dev` for the desired architectures. 16 | 17 | ``` 18 | sudo apt-get update 19 | sudo apt-get install libc6-dev:arm64 libc6-dev:armhf libc6-dev:ppc64 libc6-dev:s390x 20 | ``` 21 | 22 | ## Testing with qemu-user on Linux 23 | 24 | ### Cmake build 25 | 26 | For example for aarch64: 27 | 28 | ``` 29 | mkdir build-aarch64 30 | cd build-aarch64 31 | CC=clang CFLAGS="--target=aarch64-linux-gnu" cmake -DCMAKE_BUILD_TYPE=Release .. 32 | make -j2 33 | cd tests 34 | qemu-aarch64 -L /usr/aarch64-linux-gnu ./test_suite_mpi 35 | ``` 36 | 37 | ### mtest 38 | 39 | With [mtest](https://github.com/Mbed-TLS/mbedtls-docs/blob/main/tools/bin/mtest): 40 | 41 | ``` 42 | mtest 43 | ``` 44 | 45 | e.g. 46 | 47 | ``` 48 | mtest aarch64 cmac 49 | ``` 50 | 51 | ### mbedtls-prepare-build 52 | 53 | With [mbedtls-prepare-build](https://github.com/Mbed-TLS/mbedtls-docs/blob/main/tools/bin/mbedtls-prepare-build): 54 | 55 | ``` 56 | mbedtls-prepare-build -d build-aarch64 --cc=clang --cflags='-O2 -target aarch64-linux-gnu' --qemu-ld-prefix=aarch64-linux-gnu 57 | make -C build-aarch64 test 58 | ``` 59 | 60 | -------------------------------------------------------------------------------- /index.md: -------------------------------------------------------------------------------- 1 | # Mbed TLS documentation hub 2 | 3 | Mbed TLS provides an open-source implementation of cryptographic primitives, 4 | X.509 certificate handling and the SSL/TLS and DTLS protocols. It provides a 5 | reference implementation of the [PSA Cryptography API](https://arm-software.github.io/psa-api/crypto/). 6 | The project also supports the PSA Cryptoprocessor Driver Interface which enables 7 | support for cryptoprocessor drivers. The small code footprint makes the project 8 | suitable for embedded systems. It has many users, including 9 | [TF-A](https://www.trustedfirmware.org/projects/tf-a/), 10 | [TF-M](https://www.trustedfirmware.org/projects/tf-m/) and 11 | [OP-TEE](https://www.trustedfirmware.org/projects/op-tee/). 12 | 13 | This documentation is undergoing continuous improvement over time to address 14 | gaps, etc. We welcome contributions! 15 | 16 | For more information, see the following: 17 | 18 | * [GitHub repository](https://github.com/Mbed-TLS/mbedtls) 19 | * [Documentation GitHub repository](https://github.com/Mbed-TLS/mbedtls-docs) 20 | * [Mbed TLS website](https://www.trustedfirmware.org/projects/mbed-tls/) 21 | * [PSA Crypto API specification](https://arm-software.github.io/psa-api/crypto/) 22 | 23 | For questions and discussions: 24 | 25 | * [The Mbed TLS mailing list](https://lists.trustedfirmware.org/mailman3/lists/mbed-tls.lists.trustedfirmware.org/). 26 | * The `#mbed-tls` channel on the [TrustedFirmware Discord server](https://discord.com/channels/1106321706588577904/1144310640341700739) - use the [invite link](https://discord.gg/5PpXhvda5p) to join. 27 | 28 | Security vulnerabilities: 29 | 30 | * Please see our [process for reporting vulnerabilities](project/vulnerabilities.md). 31 | 32 | ```{toctree} 33 | --- 34 | maxdepth: 2 35 | caption: Contents 36 | --- 37 | getting_started/index.md 38 | API Reference 39 | project/index.md 40 | reviews/index.md 41 | security-advisories/index.md 42 | CONTRIBUTING.md 43 | kb/index.md 44 | ``` 45 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2019-10.md: -------------------------------------------------------------------------------- 1 | # Side channel attack on deterministic ECDSA 2 | 3 | **Title** | Side channel attack on deterministic ECDSA 4 | ---|--- 5 | **CVE** | CVE-2019-16910 6 | **Date** | 6th September 2019 ( **Updated on 26th September 2019** ) 7 | **Affects** | All versions of Mbed TLS and Mbed Crypto 8 | **Impact** | If the victim can be tricked to sign the same message
repeatedly, the private key may be recoverable through side channels. 9 | **Severity** | High 10 | **Credit** | Jack Lloyd 11 | 12 | ## Vulnerability 13 | 14 | Mbed TLS does not have a constant-time/constant-trace arithmetic library and 15 | uses blinding to protect against side channel attacks. 16 | 17 | In the ECDSA signature routine previous Mbed TLS versions used the same RNG 18 | object for generating the ephemeral key pair and for generating the blinding 19 | values. The deterministic ECDSA function reused this by passing the RNG object 20 | created from the private key and the message to be signed as prescribed by RFC 21 | 6979. This meant that the same RNG object was used whenever the same message 22 | was signed, rendering the blinding ineffective. 23 | 24 | ## Impact 25 | 26 | If the victim can be tricked to sign the same message repeatedly, the blinding 27 | countermeasures are ineffective and the private key can be recovered through 28 | side channels. 29 | 30 | ## Resolution 31 | 32 | Affected users should upgrade to one of the most recent versions of Mbed TLS, 33 | including 2.19.0, 2.16.3 or 2.7.12 or later. Similarly, affected users should 34 | upgrade to the most recent version of Mbed Crypto, including 2.0.0 or later. 35 | 36 | Applications using Mbed Crypto should call `mbedtls_ecdsa_sign_det_ext()` 37 | instead of the vulnerable and now deprecated `mbedtls_ecdsa_sign_det()`. 38 | 39 | ## Workaround 40 | 41 | Where possible, we recommend all impacted users upgrade to a newer version of 42 | Mbed TLS or Mbed Crypto. 43 | 44 | If this is not possible, as a workaround, disabling deterministic ECDSA 45 | prevents this attack. 46 | -------------------------------------------------------------------------------- /kb/generic/is-mbedtls-fips-certified.md: -------------------------------------------------------------------------------- 1 | # Is Mbed TLS FIPS certified? 2 | 3 | ## What is FIPS certification 4 | When we refer to FIPS certification for cryptographic software, we actually mean FIPS PUB 140-2. 5 | 6 | To coordinate the requirements and standards for cryptographic modules, the National Institute of Standards and Technology (NIST) issued the high-level FIPS 140 Publication Series. 7 | 8 | The FIPS 140-2 standard is an official security accreditation program for cryptographic modules. As a private party, we can have our products certified for use in government departments and regulated industries. 9 | 10 | When a software or hardware product has been tested and validated, it receives a FIPS 140-2 certificate that specifies the exact module name and version numbers. This information can then be used by third parties to confirm that software has been validated. 11 | 12 | ## FIPS certification 13 | While the Mbed TLS library is not FIPS certified, a number of the NIST approved test vectors have been incorporated, taking us an important step towards FIPS certification. 14 | 15 | ## FIPS test vectors 16 | For a FIPS certification, cryptographic modules are normally tested against the Security Requirements for Cryptographic Modules requirements found in the FIPS PUB 140-2. 17 | 18 | These requirements include official NIST validating and test vectors for the algorithms. These are included and used in our test suite. 19 | 20 | The test suite that is located at `tests/` within the Mbed TLS source code often contains a subset of the available NIST test vectors. So, whenever you run the tests with `make check`, these tests will be run as well. 21 | 22 | 23 | -------------------------------------------------------------------------------- /kb/generic/rsassa-pss.md: -------------------------------------------------------------------------------- 1 | # RSASSA-PSS 2 | 3 | ## Introduction 4 | 5 | **RSASSA-PSS** is an improved probabilistic signature scheme with appendix. This means that you can use a private RSA key to sign data in combination with random input. The other side of the communication can then verify the signature with the corresponding public RSA key. Because random data is used in this signature scheme, the two signatures for the same input are different and both can be used to verify the original data. 6 | 7 | RSASSA-PSS was standardized in [PKCS#1 v2.1](https://tools.ietf.org/html/rfc3447). It can be used as an alternative to the more widespread RSASSA algorithm in PKCS#1 v1.5. 8 | 9 | ## RSASSA-PSS vs RSASSA (PKCS#1 v1.5) 10 | 11 | RSASSA-PSS is more robust than RSASSA (PKCS#1 v1.5) and you do not need to take as many precautions to use it securely as you do with the older version. However, the original RSASSA is more widely supported by existing protocols and software. For example, the SSL protocol only supports RSASSA (PKCS#1 v1.5) for RSA signatures, and does not support RSASSA-PSS. So, although RSASSA-PSS is more advantageous from a security perspective, in practice, RSASSA is still more widely used. 12 | 13 | ## Mbed TLS support of RSASSA-PSS 14 | 15 | Mbed TLS fully supports RSASSA-PSS directly in its [RSA module](/rsa-source-code). To use RSA as specified in PKCS#1 v2.1, with SHA1 as the hash method, for example, you should initialize your RSA context with: 16 | 17 | ``` 18 | mbedtls_rsainit( &rsa, RSA_PKCS_V21, MBEDTLS_MD_SHA256); 19 | ``` 20 | 21 | After loading the RSA key into that context, you can then use it to sign, with the RSASSA-PSS scheme, by using the generic `mbedtls_rsapkcs1_sign()` for signing and `mbedtls_rsapkcs1_verify()` for verification. Alternatively, you can use the more specific `mbedtls_rsarsassa_pss_sign()` and `mbedtls_rsarsassa_pss_verify()`. 22 | 23 | 24 | -------------------------------------------------------------------------------- /security-advisories/polarssl-security-advisory-2013-04.md: -------------------------------------------------------------------------------- 1 | # PolarSSL Security Advisory 2013-04 2 | 3 | **Title** | Buffer overflow in ssl_read_record() 4 | ---|--- 5 | **CVE** | CVE-2013-5914 6 | **Date** | 1st of October 2013 ( **Updated on 8th of October 2013** ) 7 | **Affects** | PolarSSL versions prior to 1.1.8 8 | **Not affected** | PolarSSL 1.2.0 and above 9 | **Impact** | Possible remote exploit 10 | **Exploit** | Withheld 11 | **Solution** | Upgrade to PolarSSL 1.1.8, or 1.2.0 and later 12 | **Credits** | independently found by both TrustInSoft and Paul Brodeur of
Leviathan Security Group 13 | 14 | When using TLS 1.1, `ssl_read_record()` omits to check the length of the 15 | incoming data. This results in a possible buffer overflow of the receive- 16 | buffer. 17 | 18 | Only versions of PolarSSL prior to 1.1.8 are affected. 19 | 20 | ## Impact 21 | 22 | A third party can remotely trigger this buffer overflow by sending a packet 23 | with more data than **SSL_BUFFER_LEN**. This results in `ssl_fetch_input()` 24 | retrieving that amount of data into the input buffer. 25 | 26 | ## Resolution 27 | 28 | Upgrade to PolarSSL version 1.1.8, 1.2.9, 1.3.0 or try to apply the following 29 | patch. 30 | 31 | 32 | 33 | ```diff 34 | diff --git a/library/ssl_tls.c b/library/ssl_tls.c 35 | index 27f2172..a5d1cb1 100644 36 | --- a/library/ssl_tls.c 37 | +++ b/library/ssl_tls.c 38 | @@ -1159,7 +1159,7 @@ int ssl_read_record( ssl_context *ssl ) 39 | /* 40 | * TLS encrypted messages can have up to 256 bytes of padding 41 | */ 42 | - if( ssl->minor_ver == SSL_MINOR_VERSION_1 && 43 | + if( ssl->minor_ver >= SSL_MINOR_VERSION_1 && 44 | ssl->in_msglen > ssl->minlen + SSL_MAX_CONTENT_LEN + 256 ) 45 | { 46 | SSL_DEBUG_MSG( 1, ( "bad message length" ) ); 47 | ``` 48 | 49 | 50 | ## Advice 51 | 52 | We strongly advise you to consider upgrading to the 1.3 branch, or otherwise 53 | apply the patch, upgrade to version 54 | [1.1.8](/tech-updates/releases/polarssl-1.1.8-released), 55 | [1.2.9](/tech-updates/releases/polarssl-1.2.9-released) if outside parties are 56 | present or can connect to your network. 57 | -------------------------------------------------------------------------------- /security-advisories/polarssl-security-advisory-2013-02.md: -------------------------------------------------------------------------------- 1 | # PolarSSL Security Advisory 2013-02 2 | 3 | **Title** | RC4 ciphersuites in SSL and TLS vulnerable 4 | ---|--- 5 | **CVE** | Unknown 6 | **Date** | 13th of March 2013 ( **Updated on 12th of July 2013** ) 7 | **Affects** | all SSL libraries including PolarSSL 8 | **Not affected** | AES-GCM-based or CBC-based ciphersuites. Servers and
clients that only communicate over a private network 9 | **Impact** | Possible (partial) recovery of plaintext 10 | **Exploit** | Withheld 11 | **Solution** | Disable RC4-based ciphersuites 12 | **Credits** | Nadhem AlFardan, Dan Bernstein, Kenny Paterson, Bertram
Poettering and Jacob Schuldt 13 | 14 | [On the Security of RC4 in TLS](http://www.isg.rhul.ac.uk/tls) describes an 15 | attack that applies to implementations of RC4-mode ciphersuites in all version 16 | of SSL and TLS. 17 | 18 | The attack is based on the fact that statistical flaws in the keystream 19 | generated by the RC4 algorithm become apparent in TLS ciphertexts when the 20 | same plaintext is repeatedly encrypted at a fixed location across many TLS 21 | sessions. 22 | 23 | ## Impact 24 | 25 | When a RC4-based ciphersuite is used and an adversary has the ability to 26 | inject packets at will into the connection between the client and the server, 27 | the adversary can potentially use statistical analysis to retrieve plaintext 28 | from ciphertext messages. 29 | 30 | ## Resolution 31 | 32 | As the flaw is inherent to the use of RC4 ciphersuites, the only resolution is 33 | to disable the use of RC4-based ciphersuites within PolarSSL. 34 | 35 | At compile-time this can be achieved by removing the define for 36 | **POLARSSL_ARC4_C** from _include/polarssl/config.h_. 37 | 38 | An alternative is to remove the ciphersuites from the list of ciphersuites 39 | provided to **ssl_set_ciphersuites()**. 40 | 41 | ## Advice 42 | 43 | We strongly advise you to consider if your application needs RC4-dependent 44 | ciphersuites and disable them if you have the option. No real action is needed 45 | if an adversary cannot gain access to (part of) the network and thus cannot 46 | inject packets between your servers and clients. 47 | -------------------------------------------------------------------------------- /security-advisories/polarssl-security-advisory-2014-01.md: -------------------------------------------------------------------------------- 1 | # PolarSSL Security Advisory 2014-01 2 | 3 | **Title** | Heartbleed Bug 4 | ---|--- 5 | **CVE** | CVE-2014-0160 6 | **Date** | 8th of April 2014 7 | **Affects** | PolarSSL not affected 8 | **Not affected** | All version of PolarSSL 9 | **Impact** | Recovery of the key material 10 | **Exploit** | None 11 | 12 | There is a lot of news about a new high-impact vulnerability called 'The 13 | Heartbleed Bug' that affects OpenSSL. This Security Advisory is to inform 14 | PolarSSL users about possible impact for them. 15 | 16 | _"The Heartbleed Bug is a serious vulnerability in the popular OpenSSL 17 | cryptographic software library. This weakness allows stealing the information 18 | protected, under normal conditions, by the SSL/TLS encryption used to secure 19 | the Internet. SSL/TLS provides communication security and privacy over the 20 | Internet for applications such as web, email, instant messaging (IM) and some 21 | virtual private networks (VPNs)._ 22 | 23 | _The Heartbleed bug allows anyone on the Internet to read the memory of the 24 | systems protected by the vulnerable versions of the OpenSSL software. This 25 | compromises the secret keys used to identify the service providers and to 26 | encrypt the traffic, the names and passwords of the users and the actual 27 | content. This allows attackers to eavesdrop communications, steal data 28 | directly from the services and users and to impersonate services and users."_ 29 | [[1]](http://heartbleed.com/) 30 | 31 | The attack has been added to the known attacks in [our Security 32 | Center](../security-advisories.md). 33 | 34 | ## Impact 35 | 36 | No versions of PolarSSL are affected. 37 | 38 | In the affected versions of OpenSSL it is possible to retrieve key material 39 | and other data from the server. 40 | 41 | ## Workaround 42 | 43 | **For PolarSSL users:** No workaround needed. 44 | 45 | **For OpenSSL users:** Switch to PolarSSL or upgrade to the latest version of 46 | OpenSSL. 47 | 48 | ## Resolution 49 | 50 | **For PolarSSL users:** No workaround needed. 51 | 52 | **For OpenSSL users:** Switch to PolarSSL or upgrade to the latest version of 53 | OpenSSL. 54 | -------------------------------------------------------------------------------- /conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # This file only contains a selection of the most common options. For a full 4 | # list see the documentation: 5 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 6 | 7 | # -- Path setup -------------------------------------------------------------- 8 | 9 | # If extensions (or modules to document with autodoc) are in another directory, 10 | # add these directories to sys.path here. If the directory is relative to the 11 | # documentation root, use os.path.abspath to make it absolute, like shown here. 12 | # 13 | # import os 14 | # import sys 15 | # sys.path.insert(0, os.path.abspath('.')) 16 | 17 | 18 | # -- Project information ----------------------------------------------------- 19 | 20 | project = 'Mbed TLS' 21 | copyright = 'The Mbed TLS Contributors' 22 | author = 'The Mbed TLS Contributors' 23 | 24 | 25 | # -- General configuration --------------------------------------------------- 26 | 27 | # Add any Sphinx extension module names here, as strings. They can be 28 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 29 | # ones. 30 | extensions = ['myst_parser'] 31 | 32 | myst_heading_anchors = 3 33 | 34 | # Add any paths that contain templates here, relative to this directory. 35 | templates_path = ['_templates'] 36 | 37 | # List of patterns, relative to source directory, that match files and 38 | # directories to ignore when looking for source files. 39 | # This pattern also affects html_static_path and html_extra_path. 40 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', 41 | 'README.md', 'tools/README.md'] 42 | 43 | 44 | # -- Options for HTML output ------------------------------------------------- 45 | 46 | # The theme to use for HTML and HTML Help pages. See the documentation for 47 | # a list of builtin themes. 48 | # 49 | html_theme = 'sphinx_rtd_theme' 50 | 51 | # Add any paths that contain custom static files (such as style sheets) here, 52 | # relative to this directory. They are copied after the builtin static files, 53 | # so a file named "default.css" will overwrite the builtin "default.css". 54 | html_static_path = ['_static'] 55 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # 2 | # This file is autogenerated by pip-compile with Python 3.9 3 | # by the following command: 4 | # 5 | # pip-compile requirements.in 6 | # 7 | alabaster==0.7.16 8 | # via sphinx 9 | babel==2.17.0 10 | # via sphinx 11 | certifi==2025.8.3 12 | # via requests 13 | charset-normalizer==3.4.3 14 | # via requests 15 | click==8.1.8 16 | # via readthedocs-cli 17 | docutils==0.21.2 18 | # via 19 | # myst-parser 20 | # sphinx 21 | # sphinx-rtd-theme 22 | idna==3.10 23 | # via requests 24 | imagesize==1.4.1 25 | # via sphinx 26 | importlib-metadata==8.7.0 27 | # via sphinx 28 | jinja2==3.1.6 29 | # via 30 | # myst-parser 31 | # sphinx 32 | markdown-it-py==3.0.0 33 | # via 34 | # mdit-py-plugins 35 | # myst-parser 36 | # rich 37 | markupsafe==3.0.2 38 | # via jinja2 39 | mdit-py-plugins==0.4.2 40 | # via myst-parser 41 | mdurl==0.1.2 42 | # via markdown-it-py 43 | myst-parser==3.0.1 44 | # via -r requirements.in 45 | packaging==25.0 46 | # via sphinx 47 | pygments==2.19.2 48 | # via 49 | # rich 50 | # sphinx 51 | pyyaml==6.0.2 52 | # via 53 | # myst-parser 54 | # readthedocs-cli 55 | readthedocs-cli==5 56 | # via -r requirements.in 57 | requests==2.32.5 58 | # via 59 | # readthedocs-cli 60 | # sphinx 61 | rich==14.1.0 62 | # via readthedocs-cli 63 | snowballstemmer==3.0.1 64 | # via sphinx 65 | sphinx==7.4.7 66 | # via 67 | # myst-parser 68 | # sphinx-rtd-theme 69 | # sphinxcontrib-jquery 70 | sphinx-rtd-theme==3.0.2 71 | # via -r requirements.in 72 | sphinxcontrib-applehelp==2.0.0 73 | # via sphinx 74 | sphinxcontrib-devhelp==2.0.0 75 | # via sphinx 76 | sphinxcontrib-htmlhelp==2.1.0 77 | # via sphinx 78 | sphinxcontrib-jquery==4.1 79 | # via sphinx-rtd-theme 80 | sphinxcontrib-jsmath==1.0.1 81 | # via sphinx 82 | sphinxcontrib-qthelp==2.0.0 83 | # via sphinx 84 | sphinxcontrib-serializinghtml==2.0.0 85 | # via sphinx 86 | tomli==2.2.1 87 | # via sphinx 88 | urllib3==2.5.0 89 | # via 90 | # readthedocs-cli 91 | # requests 92 | zipp==3.23.0 93 | # via importlib-metadata 94 | -------------------------------------------------------------------------------- /tools/bin/asn1_indent: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Usage: $0 HEXDATA 4 | ... | $0 5 | Parse HEXDATA as the hexadecimal representation of ASN.1 structured data and 6 | print the data out with indentation reflecting the ASN.1 nested structure. 7 | Whitespace in HEXDATA is ignored. 8 | """ 9 | 10 | import binascii 11 | import re 12 | import sys 13 | 14 | def process(data, offset, slice_end, level): 15 | while offset < slice_end: 16 | tag = data[offset] 17 | is_constructed = tag & 0x20 18 | content_offset = offset + 2 19 | length = data[offset + 1] 20 | if length == 0x80: 21 | raise Exception("Indefinite length is not supported at {}".format(offset)) 22 | elif length & 0x80: 23 | content_offset += length & 0x7f 24 | length_bytes = data[offset+2:content_offset] 25 | length = int(binascii.hexlify(length_bytes).decode('ascii'), 16) 26 | content_end = content_offset+length 27 | if is_constructed: 28 | maybe_content = '' 29 | else: 30 | maybe_content = binascii.hexlify(data[content_offset:content_end]).decode('ascii') 31 | if tag & 0x3f == 0x03: # BIT STRING 32 | maybe_content = maybe_content[:2] + ' ' + maybe_content[2:] 33 | print(' ' * level + 34 | binascii.hexlify(data[offset:content_offset]).decode('ascii'), 35 | maybe_content) 36 | if is_constructed: 37 | process(data, content_offset, content_offset + length, level + 1) 38 | offset = content_offset + length 39 | 40 | BLANK_RE = re.compile(r'\s+') 41 | 42 | def prepare(raw): 43 | return binascii.unhexlify(BLANK_RE.sub('', raw)) 44 | 45 | def main(args): 46 | if len(args) == 0: 47 | raw = sys.stdin.read() 48 | elif args[0] == '--help': 49 | sys.stdout.write(usage) 50 | exit(0) 51 | elif len(args) == 1: 52 | raw = args[0] 53 | else: 54 | sys.stderr.write('Too many arguments!\n') 55 | sys.stderr.write(__doc__) 56 | exit(2) 57 | data = prepare(raw) 58 | process(data, 0, len(data), 0) 59 | 60 | if __name__ == '__main__': 61 | main(sys.argv[1:]) 62 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2020-04.md: -------------------------------------------------------------------------------- 1 | # Side channel attack on ECDSA 2 | 3 | **Title** | Side channel attack on ECDSA 4 | ---|--- 5 | **CVE** | CVE-2020-10932 6 | **Date** | 14th of April, 2020 ( **Updated on 16th of April, 2020** ) 7 | **Affects** | All versions of Mbed TLS and Mbed Crypto 8 | **Impact** | A local attacker can extract the private key 9 | **Severity** | High 10 | **Credit** | Alejandro Cabrera Aldaya, Billy Brumley and Cesar Pereida Garcia 11 | 12 | ## Vulnerability 13 | 14 | The modular inverse operation as implemented in Mbed TLS is vulnerable to a 15 | single-trace side channel attack [discovered by Alejandro Cabrera Aldaya and 16 | Billy Brumley](https://eprint.iacr.org/2020/055) which may allow a local 17 | adversary to recover the full value of the operand. (Some consequences of this 18 | attack on [RSA](mbedtls-security-advisory-2020-02.md) and 19 | [ECDSA](mbedtls-security-advisory-2019-12.md) were fixed in previous releases.) 20 | 21 | Mbed TLS, like most libraries implementing ECC, uses projective coordinates to 22 | represent points internally. It is [known](https://eprint.iacr.org/2003/191) 23 | that leaking the coordinates allows an attacker to recover a few bits of the 24 | private value. The conversion back from projective coordinates involves a 25 | modular inverse operation and is therefore vulnerable to the above new attack. 26 | An attacker who is able to obtain the coordinates from several ECDSA signature 27 | operations with the same key can eventually recover the private key through a 28 | lattice attack. 29 | 30 | A complete description of the attack is available in [this 31 | paper](https://eprint.iacr.org/2020/432.pdf). 32 | 33 | ## Impact 34 | 35 | An attacker with access to precise enough timing and memory access information 36 | (typically an untrusted operating system attacking a secure enclave such as 37 | SGX or the TrustZone secure world) can fully recover an ECDSA private key 38 | after observing a number of signature operations. 39 | 40 | ## Resolution 41 | 42 | Affected users will want to upgrade to Mbed TLS 2.22.0, 2.16.6 or 2.7.15 43 | depending on the branch they're currently using. 44 | 45 | ## Work-around 46 | 47 | There is no known work-around. Affected users need to upgrade. 48 | -------------------------------------------------------------------------------- /security-advisories/polarssl-security-advisory-2014-02.md: -------------------------------------------------------------------------------- 1 | # PolarSSL Security Advisory 2014-02 2 | 3 | **Title** | Denial of Service against GCM enabled servers (and clients) 4 | ---|--- 5 | **CVE** | CVE-2014-4911 6 | **Date** | 11th of July 2014 7 | **Affects** | All PolarSSL versions before 1.2.11 and 1.3.8 8 | **Not affected** | All branches before 1.2.x and version > 1.2.10 or > 1.3.7 9 | **Impact** | Crash of server application (or clients by a malicious server) 10 | **Exploit** | Withheld 11 | 12 | A denial of service against PolarSSL servers that offer GCM ciphersuites has 13 | been found using the fuzzing techniques of the Codenomicon Defensics toolkit. 14 | Potentially clients are affected too if a malicious server decides to execute 15 | the denial of service attack against its clients. 16 | 17 | ## Impact 18 | 19 | A server or client that is targeted with this attack can be potentially 20 | crashed with a segfault. 21 | 22 | ## Workaround 23 | 24 | Disabling of the GCM ciphersuites prevents this attack. 25 | 26 | Alternatively the following patch can be applied to your current PolarSSL 27 | 1.3.7 code base: 28 | 29 | 30 | 31 | ```diff 32 | diff --git a/library/ssl_tls.c b/library/ssl_tls.c 33 | index 480c5e5..a57f3f1 100644 34 | --- a/library/ssl_tls.c 35 | +++ b/library/ssl_tls.c 36 | @@ -1416,9 +1416,15 @@ static int ssl_decrypt_buf( ssl_context *ssl ) 37 | size_t dec_msglen, olen, totlen; 38 | unsigned char add_data[13]; 39 | int ret = POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE; 40 | + size_t gcm_overhead = ssl->transform_in->ivlen + 41 | + ssl->transform_in->fixed_ivlen + 42 | + 16; /* explicit IV + tag */ 43 | + 44 | + if( ssl->in_msglen < gcm_overhead ) 45 | + return( POLARSSL_ERR_SSL_INVALID_MAC ); 46 | + 47 | + dec_msglen = ssl->in_msglen - gcm_overhead; 48 | 49 | - dec_msglen = ssl->in_msglen - ( ssl->transform_in->ivlen - 50 | - ssl->transform_in->fixed_ivlen ); 51 | - dec_msglen -= 16; 52 | dec_msg = ssl->in_msg; 53 | dec_msg_result = ssl->in_msg; 54 | ``` 55 | 56 | 57 | ## Resolution 58 | 59 | Upgrade to PolarSSL 1.3.8 for the 1.3 branch or PolarSSL 1.2.11 for the 1.2 60 | branch. 61 | -------------------------------------------------------------------------------- /tools/bin/mbedtls-size-dwim: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -eu 3 | 4 | help () { 5 | cat <&2; exit 120;; 33 | esac 34 | done 35 | shift $((OPTIND - 1)) 36 | 37 | build_dir=${1:-.} 38 | build_dir=${build_dir%/} 39 | build_name=default 40 | if [ -n "${1:+set}" ]; then 41 | build_name=${build_dir#build-} 42 | fi 43 | 44 | base_name=${0##*/} 45 | log_file=$base_name.log 46 | 47 | run_size () ( 48 | cd "$build_dir" && size library/*.o 49 | ) 50 | 51 | compare_with () { 52 | join -j 6 -o 1.1,2.1,1.6 "$1" - | 53 | awk '$1 != $2 {print $3 ": " $1 " -> " $2 " (diff: " ($1-$2) ")" }' 54 | } 55 | 56 | make -C "$build_dir" lib >"$log_file" 2>&1 || { 57 | cat "$log_file" >&2 58 | exit 2 59 | } 60 | 61 | modified=1 62 | if git diff --quiet HEAD; then 63 | modified= 64 | fi 65 | 66 | head_commit=$(git rev-parse HEAD) 67 | if [ -z "$ref_commit" ]; then 68 | if [ -n "$modified" ]; then 69 | ref_commit=$head_commit 70 | else 71 | ref_commit=$(git rev-parse 'HEAD~1') 72 | fi 73 | fi 74 | 75 | head_size=size-$build_name-$head_commit.txt 76 | ref_size=size-$build_name-$ref_commit.txt 77 | 78 | if [ -n "$modified" ]; then 79 | cat "$ref_size" >/dev/null # abort if absent 80 | run_size | compare_with "$ref_size" 81 | else 82 | run_size >"$head_size" 83 | if [ -e "$ref_size" ]; then 84 | <"$head_size" compare_with "$ref_size" 85 | fi 86 | fi 87 | -------------------------------------------------------------------------------- /kb/cryptography/ephemeral-diffie-hellman.md: -------------------------------------------------------------------------------- 1 | # Why use Ephemeral Diffie-Hellman 2 | 3 | ## Ephemeral Diffie-Hellman vs static Diffie-Hellman 4 | 5 | **Ephemeral Diffie-Hellman** (DHE in the context of TLS) differs from the **static Diffie-Hellman** (DH) in the way that static Diffie-Hellman key exchanges always use the same Diffie-Hellman private keys. So, each time the same parties do a DH key exchange, they end up with the same shared secret. 6 | 7 | When a key exchange uses Ephemeral Diffie-Hellman a temporary DH key is generated for every connection and thus the same key is never used twice. This enables **Forward Secrecy** (FS), which means that if the long-term private key of the server gets leaked, past communication is still secure. 8 | 9 | This distinction also holds for the Elliptic Curve variants ECDHE (ephemeral, provides Forward Secrecy) and ECDH (static). 10 | 11 | Due to increasing concern about pervasive surveillance, key exchanges that provide Forward Secrecy are recommended, see for example [RFC 7525, section 6.3](https://tools.ietf.org/html/rfc7525#section-6.3). 12 | 13 | ## Authentication 14 | 15 | Ephemeral Diffie-Hellman doesn't provide authentication on its own, because the key is different every time. So neither party can be sure that the key is from the intended party. 16 | 17 | Within SSL you will often use DHE as part of a key-exchange that uses an additional authentication mechanism (e.g. **RSA**, **PSK** or **ECDSA**). So the fact that the SSL server **signs** the content of its server key exchange message that contain the ephemeral public key implies to the SSL client that this Diffie-Hellman public key is from the SSL server. 18 | 19 | ## Ciphersuites supporting Ephemeral Diffie-Hellman 20 | 21 | There are a lot of ciphersuites that support Ephemeral Diffie-Hellman. The key exchange methods that use (EC)DHE in TLS are: 22 | 23 | - Ephemeral Diffie Hellman with RSA (DHE-RSA) key exchange 24 | - Elliptic Curve Ephemeral Diffie Hellman with RSA (ECDHE-RSA) key exchange 25 | - Elliptic Curve Ephemeral Diffie Hellman with ECDSA (ECDHE-ECDSA) key exchange 26 | - Pre Shared Key with Diffie Hellman (DHE-PSK) key exchange 27 | - Pre Shared Key with Elliptic Curve Diffie Hellman (ECDHE-PSK) key exchange 28 | The full list of ciphersuites can be found in our [list of supported SSL ciphersuites](/supported-ssl-ciphersuites). 29 | -------------------------------------------------------------------------------- /kb/how-to/generate-an-aes-key.md: -------------------------------------------------------------------------------- 1 | # Generating an AES key 2 | 3 | An AES key is a random bitstring of the right length. 4 | 5 | * For a 128-bit AES key you need 16 bytes. 6 | * For a 256-bit AES key you need 32 bytes. 7 | 8 | If you need to generate your own AES key for encrypting data, you should use a good random source. The strength of the key depends on the unpredictability of the random. 9 | 10 | Mbed TLS includes the [CTR-DRBG module](/ctr-drbg-source-code) and an [Entropy Collection module](/entropy-source-code) to help you with making an AES key generator for your key. 11 | 12 | To use the AES generator, you need to have the modules enabled in the `mbedtls/config.h` files (`MBEDTLS_CTR_DRBG_C` and `MBEDTLS_ENTROPY_C`), see [How do I configure Mbed TLS](../compiling-and-building/how-do-i-configure-mbedtls.md). 13 | 14 | Include the following headers in your code: 15 | 16 | #include "mbedtls/entropy.h" 17 | #include "mbedtls/ctr_drbg.h" 18 | 19 | Then add the following variable definitions to your code: 20 | 21 | mbedtls_ctr_drbg_context ctr_drbg; 22 | mbedtls_entropy_context entropy; 23 | unsigned char key[32]; 24 | 25 | char *pers = "aes generate key"; 26 | int ret; 27 | 28 | The personalization string needs to be unique to your application to add randomness to your random sources. 29 | 30 | ## Creating the AES key 31 | 32 | You need to initialize the entropy pool and the random source and extract data for your key. In this case we generate 32 bytes (256 bits) of random data. 33 | 34 | mbedtls_entropy_init( &entropy ); 35 | 36 | mbedtls_ctr_drbg_init( &ctr_drbg ); 37 | 38 | if( ( ret = mbedtls_ctr_drbg_seed( &ctr_drbg, mbedtls_entropy_func, &entropy, 39 | (unsigned char *) pers, strlen( pers ) ) ) != 0 ) 40 | { 41 | printf( " failed\n ! mbedtls_ctr_drbg_init returned -0x%04x\n", -ret ); 42 | goto exit; 43 | } 44 | 45 | if( ( ret = mbedtls_ctr_drbg_random( &ctr_drbg, key, 32 ) ) != 0 ) 46 | { 47 | printf( " failed\n ! mbedtls_ctr_drbg_random returned -0x%04x\n", -ret ); 48 | goto exit; 49 | } 50 | 51 | Now you can use the data in `key` as a 256-bit AES key. 52 | 53 | 54 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2020-02.md: -------------------------------------------------------------------------------- 1 | # Cache attack against RSA key import in SGX 2 | 3 | **Title** | Cache attack against RSA key import in SGX 4 | ---|--- 5 | **Date** | 20th February 2020 ( **Updated on 21st February 2020** ) 6 | **Affects** | All versions of Mbed TLS and Mbed Crypto 7 | **Impact** | The RSA private key is recoverable through side channels. 8 | **Severity** | Medium 9 | **Credit** | Alejandro Cabrera Aldaya and Billy Brumley 10 | 11 | ## Vulnerability 12 | 13 | If Mbed TLS is running in an SGX enclave and the adversary has control of the 14 | main operating system, they can launch a side channel attack to recover the 15 | RSA private key when it is being imported. Found by Alejandro Cabrera Aldaya 16 | and Billy Brumley and reported by Jack Lloyd. 17 | 18 | The attack only requires access to fine grained measurements to cache usage. 19 | Therefore the attack might be applicable to a scenario where Mbed TLS is 20 | running in TrustZone secure world and the attacker controls the normal world 21 | or possibly when Mbed TLS is part of a hypervisor and the adversary has full 22 | control of a guest OS. 23 | 24 | ## Impact 25 | 26 | If an adversary has fine grained measurements to cache usage at the time an 27 | RSA key is being imported, they are able to recover the private key. 28 | 29 | ## Resolution 30 | 31 | Affected users should upgrade to one of the most recent versions of Mbed TLS, 32 | including 2.21.0, 2.16.5 or 2.7.14 or later. Similarly, affected users should 33 | upgrade to the most recent version of Mbed Crypto, including 3.1.0 or later. 34 | 35 | **Warning:** Even in these versions, it is only safe to import complete RSA 36 | private keys. `mbedtls_pk_parse_key()` and `mbedtls_pk_parse_keyfile()` can 37 | only import complete private keys and therefore using them is safe. Use of 38 | lower level APIs (such as `mbedtls_rsa_import()`) or direct access to the 39 | members of the `mbedtls_rsa_context` structure for importing keys is only safe 40 | if all the needed parameters are provided; in configurations with 41 | `MBEDTLS_RSA_NO_CRT` undefined (which is the default), this means all the 42 | components prescribed by appendix A.1.2 of the PKCS#1 v2.2 standard; in 43 | configurations with `MBEDTLS_RSA_NO_CRT` enabled, this means n, e, d, p and q. 44 | 45 | ## Workaround 46 | 47 | There are no known workarounds. 48 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2024-08-2.md: -------------------------------------------------------------------------------- 1 | # Stack buffer overflow in ECDSA signature conversion functions 2 | 3 | **Title** | Stack buffer overflow in ECDSA signature conversion functions 4 | --------- | ----------------------------------------------------- 5 | **CVE** | CVE-2024-45158 6 | **Date** | 30 August 2024 7 | **Affects** | Mbed TLS 3.6.0 8 | **Severity** | High 9 | 10 | ## Vulnerability 11 | 12 | In Mbed TLS 3.6.0, the functions `mbedtls_ecdsa_der_to_raw()` and `mbedtls_ecdsa_raw_to_der()` do not correctly validate their `bits` argument. If the value of that argument is larger than the bit-length of the largest supported curve, these functions may overflow a buffer on the stack with content copied from their input parameter. 13 | 14 | When `MBEDTLS_PSA_CRYPTO_C` is enabled, the maximum safe value of `bits` is the size of the largest curve supported by the PSA API. All curves supported by the legacy API (`ecp.h`, `ecdh.h`, `ecdsa.h`, `ecjpake.h`, `pk.h`) are also supported by the PSA API, thus any curve size supported in Mbed TLS is safe. However, code that calls these functions without ensuring that `bits` corresponds to a supported curve is vulnerable. 15 | 16 | When `MBEDTLS_PSA_CRYPTO_C` is disabled, in some configurations, the functions use a 0-size buffer internally. If this is not detected at compile time, the functions would overflow their internal buffer for all correct inputs. These functions are declared in `mbedtls/psa_util.h` and were intended for use together with the PSA API, but they were not excluded from builds without PSA. 17 | 18 | All the calls to these functions made inside Mbed TLS are safe. 19 | 20 | ## Impact 21 | 22 | Applications that call `mbedtls_ecdsa_der_to_raw()` or `mbedtls_ecdsa_raw_to_der()` on attacker-controlled input are vulnerable to a stack buffer overflow with attacker-chosen content. Note that to provoke the attack, the attacker needs to control the declared curve bit-size, not just the buffer size and content. 23 | 24 | ## Resolution 25 | 26 | Affected users will want to upgrade to Mbed TLS 3.6.1. 27 | 28 | ## Work-around 29 | 30 | Code that calls `mbedtls_ecdsa_der_to_raw()` and `mbedtls_ecdsa_raw_to_der()` in Mbed TLS 3.6.0 is safe if `MBEDTLS_PSA_CRYPTO_C` is enabled and the calling code first ensures that the `bits` parameter is the bit-size of a curve that is supported in the build of Mbed TLS. 31 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2025-06-7.md: -------------------------------------------------------------------------------- 1 | # Misleading memory management in `mbedtls_x509_string_to_names()` 2 | 3 | **Title** | Misleading memory management in `mbedtls_x509_string_to_names()` 4 | --------- | ---------------------------------------------------------- 5 | **CVE** | CVE-2025-47917 6 | **Date** | 30 June 2025 7 | **Affects** | All versions of Mbed TLS up to 3.6.3 8 | **Not affected** | Mbed TLS 3.6.4 and later 3.6 versions, upcoming 4.x versions. 9 | **Impact** | Possible use-after-free or double-free leading to arbitrary code execution. 10 | **Severity** | HIGH 11 | **Credits** | Found by Linh Le and Ngan Nguyen from Calif. 12 | 13 | ## Vulnerability 14 | 15 | The function `mbedtls_x509_string_to_names()` takes a `head` argument that is 16 | documented as an output argument. The documentation does not suggest the 17 | function will free that pointer, however the function does call 18 | `mbedtls_asn1_free_named_data_list()` on that argument, which performs a deep 19 | `free()`. 20 | 21 | As a result, application code that uses this function relying only on documented 22 | behaviour is likely to still hold pointers to the memory blocks that were 23 | `free()`d, resulting in high risk of user-after-free or double-free. 24 | 25 | In particular, the two sample programs x509/cert_write and x509/cert_req 26 | were affected (use-after-free if the `san` string contains more than one DN). 27 | 28 | ## Impact 29 | 30 | Depending on the application code, a use-after-free and/or double-free is 31 | likely. Depending on the malloc() implementation, this is likely to lead to 32 | arbitrary code execution. 33 | 34 | ## Affected versions 35 | 36 | All versions of Mbed TLS up to 3.6.3 are affected. 37 | 38 | ## Resolution 39 | 40 | Affected users should upgrade to Mbed TLS 3.6.4 and/or apply the workaround 41 | below (which is enforced in 3.6.4: passing something other than a pointer-to-NULL 42 | will result in the function immediately returning an error). 43 | 44 | ## Work-around 45 | 46 | Always passing a pointer-to-NULL as the `head` argument to 47 | `mbedtls_x509_string_to_names()` avoids the problem. Moreover, this approach will continue to work in version 3.6.4 and later. 48 | 49 | Applications that do not call `mbedtls_x509_string_to_names()` directly are not 50 | affected. Internal uses of this function do not lead to memory management 51 | errors. 52 | -------------------------------------------------------------------------------- /kb/development/tool-versions-lts-distributions.md: -------------------------------------------------------------------------------- 1 | ## Open-source tools in popular long-term support distributions 2 | 3 | Mbed TLS' minimum tool version requirements are usually set based on the versions shipped in long-term support releases of major operating systems. The table below lists versions of relevant software in distributions that are in support. 4 | 5 | [RHEL](https://access.redhat.com/support/policy/updates/errata#Life_Cycle_Dates) 6 is on extended lifecycle support until June 2024. The list of packages is identical to [CentOS 6](http://vault.centos.org/6.10/os/Source/SPackages/), and in RHEL 7 to [CentOS 7](http://vault.centos.org/7.8.2003/os/Source/SPackages/). 6 | 7 | Ubuntu 16.04 is on extended security maintenance (ESM) until April 2024. Debian long-time support lasts less long, so the oldest versions of software that are supported in a Debian release are slightly less old than for Ubuntu, therefore we don't need to look at Debian versions. 8 | 9 | [pkgs.org](https://pkgs.org/) indexes the software versions in many currently-supported distributions. This includes Ubuntu LTS and CentOS, but not RHEL ELS. 10 | 11 | | Software | [Ubuntu 16.04](https://packages.ubuntu.com/xenial/devel/) | [RHEL 6](http://vault.centos.org/6.10/os/Source/SPackages/) | [CentOS 8](https://centos.pkgs.org/8/centos-baseos-x86_64/) + [appstream](https://centos.pkgs.org/8/centos-appstream-x86_64/) | [Ubuntu 18.04](https://packages.ubuntu.com/bionic/devel/) | [RHEL 7](http://vault.centos.org/7.8.2003/os/Source/SPackages/) | [SLES 12](https://scc.suse.com/packages?name=SUSE%20Linux%20Enterprise%20Server&version=12.5&arch=x86_64) | [SLES 15](https://scc.suse.com/packages?name=SUSE%20Linux%20Enterprise%20Server&version=15&arch=x86_64) | 12 | | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | 13 | | End-of-life | Apr 2021 | Nov 2020 | Dec 2021 | Apr 2023 | Jun 2024 | Oct 2024 | Jul 2028 | 14 | | Security EOL | Apr 2024 | Jun 2024 | N/A | Apr 2028 | N/C | Oct 2027 | Jul 2031 | 15 | | Clang | 3.8 | N/A | 10.0.1 | 6.0 | N/A | N/A | 5.0.1 | 16 | | CMake | 3.5.1 | 2.8.12.2 | ≥3.18.2 | 3.10.2 | 2.8.12.2 | 3.5.2 | 3.10.2 | 17 | | GCC | 5.3 | 4.4.7 | 8.3 | 7.4 | 4.8.5 | 4.8.5 | 7.5.0 | 18 | | GNU make | 4.1 | 3.81 | 4.2.1 | 4.1 | 3.82 | 4.0 | 4.2.1 | 19 | | Python 3 | 3.5.2 | N/A | 3.6.8 | 3.6.5 | 3.6.8 | 3.4.10 (+3.6) | 3.6.5 | 20 | | Doxygen | 1.8.11 | 1.6.1 | 1.8.14 | 1.8.13 | 1.8.5 | 1.8.6 | 1.8.14 | 21 | -------------------------------------------------------------------------------- /security-advisories/polarssl-security-advisory-2011-02.md: -------------------------------------------------------------------------------- 1 | # PolarSSL Security Advisory 2011-02 2 | 3 | **Title** | Weak random number generation within virtualized environments 4 | ---|--- 5 | **CVE** | CVE-2011-4574 6 | **Date** | 15th of December 2011 ( **Updated on 12th of July 2013** ) 7 | **Affects** | All version of PolarSSL prior to 1.1.0 8 | **Not affected** | Instances not running in virtualized environments 9 | **Impact** | Key retrieval possible 10 | **Exploit** | Withheld 11 | **Solution** | Upgrade to PolarSSL 1.1.0 and move to CTR_DRBG random
generator 12 | **Workaround** | Provide another random source to the SSL layer 13 | **Credits** | Jacob Appelbaum, Marsh Ray, and Oscar Koeroo 14 | 15 | Feedback from the security community has triggered an investigation into the 16 | quality of PolarSSL's random number generation within virtualized 17 | environments. 18 | 19 | PolarSSL versions prior to v1.1 use the 20 | [HAVEGE](http://www.irisa.fr/caps/projects/hipsor/publi.php) random number 21 | generation algorithm. At its heart, this uses timing information based on the 22 | processor's high resolution timer (the RDTSC instruction). This instruction 23 | can be virtualized, and some virtual machine hosts have chosen to disable this 24 | instruction, returning 0s or predictable results. 25 | 26 | Further concerns have been raised on the HAVEGE implementation's sole 27 | dependence on timing data. 28 | 29 | ## Impact 30 | 31 | This issue affects machines running within environments where the RDTSC call 32 | has been disabled or handicapped. Currently, the problem seems to be limited 33 | to some commercial cloud server providers. 34 | 35 | If affected, this means the RNG produces predictable random and as such 36 | security is severely compromised. 37 | 38 | ## Resolution 39 | 40 | PolarSSL version 1.1.0 contains a new random number generator based on the 41 | CTR_DRBG algorithm specified in [NIST- 42 | SP800-90](http://csrc.nist.gov/publications/nistpubs/800-90A/SP800-90A.pdf). 43 | The entropy used by this algorithm is accumulated from multiple sources, 44 | including the existing HAVEGE RNG, platform-specific entropy sources and 45 | timing sources. This increases the quality of the entropy pool, and makes it 46 | less vulnerable to problems within a single source. 47 | 48 | ## Advice 49 | 50 | We advise everyone to move to the new CTR_DRBG algorithm and entropy pool if 51 | possible. 52 | -------------------------------------------------------------------------------- /kb/compiling-and-building/mbedtls-on-solaris.md: -------------------------------------------------------------------------------- 1 | # Mbed TLS on Solaris 2 | 3 | When compiling Mbed TLS on Solaris, you might encounter some known issues. The default `Makefile` tries to manage as many systems as possible, but you must do some changes manually. 4 | 5 | ## Linking error 6 | 7 | If you run `make`, you may get an error during linking similar to: 8 | 9 | ``` 10 | $ make 11 | ... 12 | CC pkey/dh_client.c 13 | Undefined first referenced 14 | symbol in file 15 | bind ../library/libmbedtls.a(net.o) 16 | accept ../library/libmbedtls.a(net.o) 17 | listen ../library/libmbedtls.a(net.o) 18 | gethostbyname ../library/libmbedtls.a(net.o) 19 | socket ../library/libmbedtls.a(net.o) 20 | setsockopt ../library/libmbedtls.a(net.o) 21 | connect ../library/libmbedtls.a(net.o) 22 | shutdown ../library/libmbedtls.a(net.o) 23 | ld: fatal: symbol referencing errors. No output written to pkey/dh_client 24 | collect2: ld returned 1 exit status 25 | make[1]: *** [pkey/dh_client] Error 1 26 | make: *** [all] Error 2 27 | ``` 28 | 29 | This is because under Solaris, you must to instruct GCC to include `libsocket` and `libnsl` during linking. 30 | 31 | Define `LDFLAGS` to include `-lsocket -lnsl` when running `make` on Solaris 10. 32 | 33 | ## Ar error 34 | 35 | If you run `make` and receive the following error: 36 | 37 | ``` 38 | $ make 39 | .... 40 | AR libmbedtls.a 41 | ar: creating libmbedtls.a 42 | RL libmbedtls.a 43 | ar: one of [drqtpmx] must be specified 44 | make[1]: *** [libmbedtls.a] Error 1 45 | make: *** [all] Error 2 46 | ``` 47 | 48 | ### Workaround 49 | 50 | Install the package `SUNWbinutils`, then run: 51 | 52 | ``` 53 | export AR=gar 54 | ``` 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /tools/emacs/mbedtls-autoloads.el: -------------------------------------------------------------------------------- 1 | ;;; mbedtls-autoloads -- definitions for Mbed TLS development 2 | 3 | ;; Add the directory containing this file to your `load-path` and 4 | ;; put (require 'mbedtls-autoloads) in your Emacs init file. 5 | 6 | ;;; Code: 7 | 8 | ;; Mbed TLS test data mode 9 | (add-to-list 'auto-mode-alist 10 | '("mbedtls.*/.*\\.data\\'" . mbedtls-test-data-mode)) 11 | (autoload 'mbedtls-test-data-mode "mbedtls-test-data-mode" 12 | "Major mode to edit Mbed TLS test data files." 13 | t) 14 | 15 | ;; .function files are C code 16 | (add-to-list 'auto-mode-alist '("/suites/[^/]+\\.function\\'" . c-mode)) 17 | 18 | ;; Mbed TLS indentation style 19 | 20 | (defun cc-style-lineup-if-with-else (context) 21 | "When there is a newline in else/if, indent if like else. 22 | That is, indent like this: 23 | if (...) 24 | ... 25 | else 26 | if (...) 27 | ... 28 | instead of this: 29 | if (...) 30 | ... 31 | else 32 | if (...) 33 | ... 34 | To achieve this, add `(substatement cc-style-lineup-if-with-else +)' 35 | to `c-offsets-alist'." 36 | ;; https://emacs.stackexchange.com/questions/31038/stop-reindenting-if-after-else/31041#31041 37 | (pcase context 38 | (`(substatement . ,anchor) 39 | (save-excursion 40 | (back-to-indentation) 41 | (when (looking-at-p "if\\_>") 42 | (goto-char anchor) 43 | (when (looking-at-p "\\(else\\|switch\\)\\_>") 44 | 0)))))) 45 | 46 | (defun cc-style-make-mbedtls () 47 | (let ((entry (assoc "mbedtls" c-style-alist))) 48 | (unless entry 49 | (setq entry (cons "mbedtls" nil)) 50 | (setq c-style-alist (cons entry c-style-alist))) 51 | (setcdr entry '((c-basic-offset . 4) 52 | (c-hanging-braces-alist 53 | (arglist-cont before after) 54 | (arglist-cont-nonempty before after) 55 | (substatement-open before after)) 56 | (c-offsets-alist 57 | (case-label . +) 58 | (inextern-lang . 0) 59 | (label . 0) 60 | (substatement cc-style-lineup-if-with-else +) 61 | (substatement-open . 0) 62 | (substatement-label . 0) 63 | ))))) 64 | (eval-after-load "cc-styles" '(cc-style-make-mbedtls)) 65 | 66 | (provide 'mbedtls-autoloads) 67 | 68 | ;;; That's all. 69 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2020-09-1.md: -------------------------------------------------------------------------------- 1 | # Local side channel attack on classical CBC decryption in (D)TLS 2 | 3 | **Title** | Local side channel attack on classical CBC decryption in (D)TLS 4 | ---|--- 5 | **CVE** | CVE-2020-16150 6 | **Date** | 1st of September, 2020 7 | **Affects** | All versions of Mbed TLS 8 | **Impact** | A local attacker can extract portions of the plaintext 9 | **Severity** | High 10 | **Credit** | Tuba Yavuz, Farhaan Fowze, Ken (Yihan) Bai, Grant Hernandez,
Kevin Butler and Dave Tian. 11 | 12 | ## Vulnerability 13 | 14 | When decrypting/authenticating (D)TLS record in a connection using a CBC 15 | ciphersuite without the Encrypt-then-Mac extension [RFC 16 | 7366](https://tools.ietf.org/html/rfc7366), Mbed TLS used dummy rounds of the 17 | compression function associated with the hash used for HMAC in order to hide 18 | the length of the padding to remote attackers, as recommended in the [original 19 | Lucky Thirteen paper](http://www.isg.rhul.ac.uk/tls/TLStiming.pdf). 20 | 21 | A local attacker who is able to observe the state of the cache could monitor 22 | the presence of `mbedtls_md_process()` in the cache in order to determine when 23 | the actual computation ends and when the dummy rounds start. This is a 24 | reliable target as it's always called at least once, in response to a 25 | [previous 26 | attack](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.700.1952&rep=rep1&type=pdf). 27 | The attacker can then continue with one of many well-documented Lucky 13 28 | variants. 29 | 30 | In order to fix this, as well as future variants of Lucky 13 relying on a 31 | local attacker's abilities, the implementation was changed to compute the 32 | expected MAC, extract the transmitted MAC and compare them, using constant 33 | memory access patterns and execution flow. 34 | 35 | ## Impact 36 | 37 | An local attacker with access to enough information about the state of the 38 | cache (including, but not limited to, an untrusted operating system attacking 39 | a secure enclave such as SGX or the TrustZone secure world) can recover 40 | portions of the plaintext of a (D)TLS record. 41 | 42 | ## Resolution 43 | 44 | Affected users will want to upgrade to Mbed TLS 2.24.0, 2.16.8 or 2.7.17 45 | depending on the branch they're currently using. 46 | 47 | ## Work-around 48 | 49 | Users are encouraged to use AEAD ciphersuites (CHACHA20-POLY1305, GCM, CCM) 50 | whenever possible, or it they have to use CBC, to enable use of the Encrypt- 51 | then-Mac extension on both sides of the connection. 52 | -------------------------------------------------------------------------------- /security-advisories/polarssl-security-advisory-2014-04.md: -------------------------------------------------------------------------------- 1 | # PolarSSL Security Advisory 2014-04 2 | 3 | **Title** | Remote attack using crafted certificates 4 | ---|--- 5 | **CVE** | CVE-2015-1182 6 | **Date** | 19th of January 2015 ( **Updated on 16th of February 2015** ) 7 | **Affects** | PolarSSL 1.0 and up 8 | **Not affected** | mbed TLS 1.3.10 and up, PolarSSL 1.2.13 and up and any
version with servers not asking for client certificates 9 | **Impact** | Denial of service and possible remote code execution 10 | **Severity** | High 11 | **Exploit** | Withheld 12 | 13 | PolarSSL versions starting with 1.0 and up to the PolarSSL 1.3.9 and PolarSSL 14 | 1.2.12 are affected by a remote attack in some configurations. 15 | 16 | This vulnerability was internally discovered using the Codenomicon Defensics 17 | test suite and reported externally by [Certified 18 | Secure](https://www.certifiedsecure.com/polarssl-advisory). 19 | 20 | This Security Advisory describes the vulnerability, impact and fix for the 21 | attack. 22 | 23 | ## Vulnerability 24 | 25 | During the parsing of a ASN.1 sequence, a pointer in the linked list of 26 | `asn1_sequence` is not initialized by `asn1_get_sequence_of()`. In case an 27 | error occurs during parsing of the list, a situation is created where the 28 | uninitialized pointer is passed to `polarssl_free()`. 29 | 30 | This sequence can be triggered when a PolarSSL entity is parsing a 31 | certificate. So practically this means clients when receiving a certificate 32 | from the server or servers in case they are actively asking for a client 33 | certificate. 34 | 35 | ## Impact 36 | 37 | Depending on the attackers knowledge of the system under attack, this results 38 | at the lowest into a Denial of Service, and at the most a possible Remote Code 39 | Execution. 40 | 41 | ## Fix 42 | 43 | The fix is a one-line addition to _asn1parse.c_ : 44 | 45 | 46 | 47 | ```diff 48 | diff --git a/library/asn1parse.c b/library/asn1parse.c 49 | index a3a2b56..e2117bf 100644 50 | --- a/library/asn1parse.c 51 | +++ b/library/asn1parse.c 52 | @@ -278,6 +278,8 @@ int asn1_get_sequence_of( unsigned char **p, 53 | if( cur->next == NULL ) 54 | return( POLARSSL_ERR_ASN1_MALLOC_FAILED ); 55 | 56 | + memset( cur->next, 0, sizeof( asn1_sequence ) ); 57 | + 58 | cur = cur->next; 59 | } 60 | } 61 | ``` 62 | 63 | 64 | ## Workaround and resolution 65 | 66 | Apply the above patch to your codebase, or download and use mbed TLS 1.3.10 or 67 | PolarSSL 1.2.13. 68 | -------------------------------------------------------------------------------- /kb/development/how-to-fill-rsa-context-from-n-e-p-and-q.md: -------------------------------------------------------------------------------- 1 | # How to fill an RSA context from N, E, P and Q 2 | 3 | ## Introduction 4 | 5 | In some cases, you only have the base values for RSA at your disposal and want to use those within Mbed TLS. Mbed TLS, specifically the `mbedtls_rsa_context` structure, requires more than the base values to perform optimized operations for RSA. 6 | 7 | You can deduce the other values if you have access to your **E**, **P** and **Q**. In most cases, you already have your **N**, so you can skip the next section. 8 | 9 | You can import these values to your `mbedtls_rsa_context` structure with their raw value, in Big Endian, using the `mbedtls_rsa_import_raw()` function, or as `mbedtls_mpi` structures, using the `mbedtls_rsa_import()` function. 10 | If you do not wish to set a component to the context, whether you do not know it or it is already set, you can just set it as `NULL` as the function parameter. 11 | 12 | The following example shows you how to correctly initialize the RSA context named **ctx** with the values for **P,** **Q** and **E** into `mbedtls_rsa_context`. 13 | 14 | ## Getting the modulus (N) 15 | 16 | If the modulus (**N**) is known, you should send it as parameter to `mbedtls_rsa_import()` (or `mbedtls_rsa_import_raw()`). However if it is not known, it is calculated within the `mbedtls_rsa_complete()` function, if **P** and **Q** have been imported to the context. 17 | 18 | ## Filling the context 19 | 20 | To fill the context you should use the following sequence of function calls. You will have to define and initialize the appropriate variables for `E`, `P` and `Q`. 21 | 22 | ret = mbedtls_rsa_import( &ctx, NULL, &P, &Q, NULL, &E ); 23 | if( ret != 0 ) 24 | { 25 | mbedtls_printf( " failed\n ! mbedtls_rsa_import returned %d\n\n", 26 | ret ); 27 | goto exit; 28 | } 29 | if( ( ret = mbedtls_rsa_complete( &ctx ) ) != 0 ) 30 | { 31 | mbedtls_printf( " failed\n ! mbedtls_rsa_complete returned %d\n\n", 32 | ret ); 33 | goto exit; 34 | } 35 | 36 | The function `mbedtls_rsa_complete()` deduces all the other components in the RSA context. Of course, if all components are known in advance and imported using the `mbedtls_rsa_import()` or `mbedtls_rsa_import_raw()`, the computation time of `mbedtls_rsa_complete()` will be shorter. 37 | 38 | ## Checking the RSA key consistency 39 | 40 | If you want to check the correctness of all values in your context, use `mbedtls_rsa_check_privkey()`. 41 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2020-09-2.md: -------------------------------------------------------------------------------- 1 | # Local side channel attack on RSA and static Diffie-Hellman 2 | 3 | **Title** | Local side channel attack on RSA and static Diffie-Hellman 4 | ---|--- 5 | **CVE** | (none) 6 | **Date** | 1st of September, 2020 7 | **Affects** | All versions of Mbed TLS and Mbed Crypto 8 | **Impact** | A powerful local attacker can extract the private key 9 | **Severity** | High 10 | **Credit** | (found internally following previous work from Alejandro Cabrera
Aldaya and Billy Bob Brumley) 11 | 12 | ## Vulnerability 13 | 14 | RSA and static Diffie-Hellman use a counter-measure known as base blinding 15 | (see [section 10 of this 16 | paper](https://paulkocher.com/doc/TimingAttacks.pdf#page=8)) in order to 17 | prevent (adaptative) chosen-input attacks on modular exponentiation. The 18 | counter-measure works by multiplying the base with a secret value before the 19 | modular exponentiation, then multiplying the result with a well-chosen value 20 | to recover the actual result. In order to save on computation costs, these 21 | blinding/unblinding values are not drawn at random for each operation; instead 22 | they're drawn at random the first time only, then updated in a deterministic 23 | way. It is thus crucial that those values are not leaked: otherwise the 24 | adversary could predict future blinding values and retain the ability to 25 | choose the base passed to the modular exponentiation operation. 26 | 27 | While generating the blinding/unblinding values, a modular inverse is 28 | computed, and a [recent paper](https://eprint.iacr.org/2020/055.pdf) showed 29 | that our modular inverse function (more precisely, our GCD function which it 30 | calls) is vulnerable to a single-trace side-channel attack by powerful local 31 | adversaries. Such an adversary could recover the initial blinding/unblinding 32 | values, predict future values, and then proceed to use any known chosen-input 33 | attack that base blinding was supposed to protect against, with consequences 34 | ranging up to full private key compromise. 35 | 36 | ## Impact 37 | 38 | An attacker with access to precise enough timing and memory access information 39 | (typically an untrusted operating system attacking a secure enclave such as 40 | SGX or the TrustZone secure world) can recover the private keys used in RSA or 41 | static (finite-field) Diffie-Hellman operations. 42 | 43 | ## Resolution 44 | 45 | Affected users will want to upgrade to Mbed TLS 2.24.0, 2.16.8 or 2.7.17 46 | depending on the branch they're currently using. 47 | 48 | ## Work-around 49 | 50 | None. 51 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2025-06-5.md: -------------------------------------------------------------------------------- 1 | # Timing side-channel in block cipher decryption with PKCS#7 padding 2 | 3 | **Title** | Timing side-channel in block cipher decryption with PKCS#7 padding 4 | --------- | ----------------------------------------------------------------- 5 | **CVE** | CVE-2025-49087 6 | **Date** | 30 June 2025 7 | **Affects** | All versions of Mbed TLS from 3.6.1 to 3.6.3 inclusive 8 | **Not affected** | Mbed TLS 3.6.4 and later 3.6 versions and upcoming TF-PSA-Crypto 1.0 and later versions 9 | **Impact** | Plaintext recovery 10 | **Severity** | MEDIUM 11 | **Credit** | Ka Lok Wu from Stony Brook University and Doria Tang from The Chinese University of Hong Kong 12 | 13 | ## Vulnerability 14 | 15 | Mbed TLS is vulnerable to a timing side channel attack on its implementation of PKCS#7 padding removal. An attacker with access to timing information and a decryption oracle can recover the last byte of each plaintext block. If some portion of the plaintext is controlled by the attacker as is often the case, the whole plaintext can be recovered. 16 | 17 | The function that performs PKCS#7 padding removal first checks that the last byte of the plaintext is in the range (0, BLOCKSIZE], where BLOCKSIZE is the block size of the cipher. If the last byte is outside of this range, the function exits early, creating a timing oracle. An attacker with access to timing information can use this oracle to recover the value of the last byte of the plaintext by requesting the decryption of manipulated ciphertexts. By truncating the ciphertext, they can recover the value of the last byte of an arbitrary block. 18 | 19 | Any applications using the PKCS#7 padding mode are vulnerable (when `PSA_ALG_CBC_PKCS7` or `MBEDTLS_CIPHER_PADDING_PKCS7` is enabled). 20 | 21 | ## Impact 22 | 23 | Full plaintext recovery. 24 | 25 | ## Affected versions 26 | 27 | All versions of Mbed TLS from 3.6.1 up to 3.6.3 are affected. 28 | 29 | ## Resolution 30 | 31 | Affected users should upgrade to Mbed TLS 3.6.4 or upcoming TF-PSA-Crypto 1.0 or later. 32 | 33 | ## Work-around 34 | 35 | Do not use the PKCS#7 padding scheme with block ciphers. Choose an alternative padding scheme when calling `mbedtls_cipher_set_padding_mode()`. Other possible padding schemes are as follows: 36 | 37 | * `MBEDTLS_PADDING_ONE_AND_ZEROS` - ISO/IEC 7816-4 padding 38 | * `MBEDTLS_PADDING_ZEROS_AND_LEN` - ANSI X.923 padding 39 | * `MBEDTLS_PADDING_ZEROS` - Zero padding (not reversible) 40 | * `MBEDTLS_PADDING_NONE` - Never pad (full blocks only) 41 | 42 | If using PSA, choose a different cipher to `PSA_ALG_CBC_PKCS7`, depending on your application. 43 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2022-07.md: -------------------------------------------------------------------------------- 1 | # Buffer overread in DTLS ClientHello parsing 2 | 3 | **Title** | Buffer overread in DTLS ClientHello parsing. 4 | ---|--- 5 | **CVE** | CVE-2022-35409 6 | **Date** | 2022-07-11 7 | **Affects** | All versions of Mbed TLS up to and including 2.28.0 and 3.1.0 8 | **Impact** | A remote attacker may cause a crash or information disclosure 9 | **Severity** | Medium 10 | **Credit** | Cybeats PSI Team 11 | 12 | ## Vulnerability 13 | 14 | An unauthenticated remote host can send an invalid ClientHello message in which the declared length of the cookie extends past the end of the message. A DTLS server with `MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE` enabled will read past the end of the message up to the declared length of the cookie. 15 | 16 | At this point in the parsing, the message is stored in a buffer with room for `MBEDTLS_SSL_IN_CONTENT_LEN` bytes plus headers. The data beyond the end of the message has been wiped, so there is no risk of information disclosure from the buffer. Therefore this is a vulnerability only if the purported length of the cookie extends beyond the end of the buffer. 17 | 18 | Since the length of the cookie is limited to 255 bytes, the vulnerability is only present if `MBEDTLS_SSL_IN_CONTENT_LEN` is small. The threshold depends on the exact configuration. The default value of `MBEDTLS_SSL_IN_CONTENT_LEN` is large enough to avoid the vulnerability. 19 | 20 | The default cookie check function `mbedtls_ssl_cookie_check()` does not read the cookie if its length is not the expected length (28 bytes if SHA-256 is enabled). 21 | 22 | ## Impact 23 | 24 | An unauthenticated remote host can cause a buffer overread of up to 255 bytes on the heap in vulnerable DTLS servers. This may lead to a crash or to information disclosure via the cookie check function. 25 | 26 | ## Resolution 27 | 28 | Affected users will want to upgrade to Mbed TLS 3.2.0 or 2.28.1 depending on the branch they're currently using. 29 | 30 | ## Work-around 31 | 32 | A sufficiently large value of `MBEDTLS_SSL_IN_CONTENT_LEN` avoids the vulnerability. The threshold depends on the exact configuration. For example: 33 | 34 | * With default options regarding DTLS and only support for AEAD ciphersuites, and using the default cookie check function `mbedtls_ssl_cookie_check()`, the threshold is 210 bytes. 35 | * With `MBEDTLS_SSL_DTLS_CONNECTION_ID` enabled, the threshold can be up to 258 bytes if using `mbedtls_ssl_cookie_check()`. 36 | * In the worst case, with a custom cookie check function, the threshold can be up to 571 bytes. 37 | 38 | Turning off `MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE` also avoids the vulnerability. 39 | -------------------------------------------------------------------------------- /kb/cryptography/providing-diffie-hellman-or-dhm-parameters.md: -------------------------------------------------------------------------------- 1 | # Providing Diffie-Hellman-Merkle (DHM) parameters in versions before 4.0 2 | 3 | ## Choosing DHM parameters 4 | 5 | Developers have the option to set the DHM parameters for SSL servers with `mbedtls_ssl_conf_dh_param_bin()`. This is not a requirement as the default parameters are preloaded. 6 | 7 | ## Default DHM parameters 8 | 9 | The DHM parameters that the TLS handshake uses are set by default to the 2048-bit MODP parameters from [RFC 3526](https://www.ietf.org/rfc/rfc3526.txt) (`MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN` and `MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN`). From a security perspective, it is desirable to use a larger value, unless you have clients for which this will cause interoperability issues. Larger values are provided in [dhm.h](https://github.com/Mbed-TLS/mbedtls/blob/development/include/mbedtls/dhm.h). 10 | 11 | ## Custom parameters 12 | 13 | You can set your own parameters that you have generated in a secure way. To do that, you can use the example program `programs/pkey/dh_genprime`. Just run `dh_genprime bits=`. The resulting parameters are in `dh_prime.txt`; use them as a C-array format in your application code and as arguments to `mbedtls_ssl_conf_dh_param_bin()`. 14 | 15 | ## Custom and standard parameters 16 | 17 | We used to recommend using standard parameters rather than generating your own. However, the team of researchers behind the [Logjam attack](https://weakdh.org/) also showed that a risk associated is with that if the parameters are not large enough. More precisely, they showed that the amount of computation required to break any number of MODP DHM key exchanges is close to the amount required to break just one of them, as long as they all use the same parameters. So if your parameter size is just at the limit of what an adversary can break, using standard parameters allows the adversary to amortize the cost of the initial computation, which is not what you want. 18 | 19 | 1,024 bits is considered within reach of the most powerful adversaries, and 2,048 bits safe according to public knowledge. If you absolutely must use 1,024 bit parameters for compatibility with old clients, it is highly desirable to generate your own rather than use the standard parameters, as long as you take into consideration [backdoor vulnerabilities](/tech-updates/blog/dh-backdoors). If you can use parameters of 2,048 bits or more, then you are safe either way. 20 | 21 | An alternative is to switch to Elliptic Curve Diffie-Hellman (ECDH ciphersuite), which does not have this security issue and also improves the performance, as [this article](ephemeral-diffie-hellman.md) describes. 22 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2025-06-3.md: -------------------------------------------------------------------------------- 1 | # Unchecked return value in LMS verification allows signature bypass 2 | 3 | **Title** | Unchecked return value in LMS verification allows signature bypass 4 | --------- | ---------------------------------------------------------- 5 | **CVE** | CVE-2025-49600 6 | **Date** | 2025-06-30 7 | **Affects** | Mbed TLS 3.3.0 through 3.6.3 8 | **Not affected** | Mbed TLS 3.6.4 and later 3.6 versions and upcoming TF-PSA-Crypto 1.0 and later versions 9 | **Impact** | LMS signature verification bypass 10 | **Severity** | MEDIUM 11 | **Credits** | Found and reported by Linh Le and Ngan Nguyen from Calif. 12 | 13 | ## Vulnerability 14 | 15 | In `mbedtls_lms_verify()`, the return values of the internal Merkle tree 16 | functions `create_merkle_leaf_value()` and `create_merkle_internal_value()` are 17 | not checked. These functions return an integer that indicates whether the call 18 | succeeded or not. If a failure occurs, the output buffer (`Tc_candidate_root_node`) 19 | may remain uninitialized, and the result of the signature verification is 20 | unpredictable. When the software implementation of SHA-256 is used, 21 | these functions will not fail. However, with hardware-accelerated hashing, an attacker 22 | could use fault injection against the accelerator to bypass verification. 23 | 24 | Under the following plausible scenario, an adversary could bypass signature verification: 25 | 26 | - `mbedtls_lms_verify()` is first called to verify a valid message and signature. 27 | A valid value for Tc_candidate_root_node is stored on the stack. 28 | - The adversary then injects a fault into the hash accelerator, causing all 29 | subsequent hashing operations to fail. 30 | - `mbedtls_lms_verify()` is called again with the same key and signature but a different message, 31 | without invoking other functions that would overwrite the stack. Because the `Tc_candidate_root_node` 32 | is not updated due to the failure of the hashing operations, the previous valid value remains 33 | on the stack, causing the verification to incorrectly succeed. 34 | 35 | ## Impact 36 | 37 | LMS signature verification bypass 38 | 39 | ## Affected versions 40 | 41 | Mbed TLS 3.3.0 through 3.6.3 42 | 43 | ## Resolution 44 | 45 | Affected users should upgrade to Mbed TLS 3.6.4 or upcoming TF-PSA-Crypto 1.0 or later. 46 | 47 | ## Work-around 48 | 49 | Do not use a hardware hash accelerator that can fail without 50 | halting the system. If a hardware accelerator is required, choose 51 | accelerators that are tamper-proof or include fault-injection detection. 52 | 53 | Alternatively use the built-in software implementation of SHA-256 if possible. 54 | -------------------------------------------------------------------------------- /kb/development/debugging-tls.md: -------------------------------------------------------------------------------- 1 | # Debugging TLS sessions 2 | 3 | It is important to understand why a TLS handshake has failed with Mbed TLS and this short article will guide you through ways to debug Mbed TLS within your application. Using a debugger is an important first step, but will not always assist in understanding the cause of failure for a long complex TLS handshake. If using a debugger does not help explain the issue, then we recommend the following steps to reproduce and debug the failure. 4 | 5 | ## Enable logs in Mbed TLS 6 | 7 | Mbed TLS has a feature to show the TLS handshake logs, filtering with certain debug level. In order to see the TLS logs in your terminal, you must verify that you have `MBEDTLS_DEBUG_C` defined in your configuration. 8 | 9 | Set the debug threshold for the TLS handshake: 10 | ``` 11 | mbedtls_debug_set_threshold( ) 12 | ``` 13 | Note that `debug_level` is the level of debug logs you require. Its values can be between 0 and 5, where 5 is the most logs. 14 | Set your debug log function to display in your terminal: 15 | ``` 16 | mbedtls_ssl_conf_dbg() 17 | ``` 18 | These steps will enable logs and print the logs according to your debug function. 19 | 20 | ## Use Sample applications 21 | 22 | Mbed TLS comes with a variety of sample applications that run on your desktop machine in the `programs` folder. We recommended that you first try using one of these sample applications in the `ssl` programs sub-folder to eliminate issues unrelated to your platform, such as certificate handling and configuration setup. Most of the ssl sample applications have a `debug_level` application parameter to show TLS logs. 23 | You should use the sample application to eliminate issues related to the peer, and use a known server \ client for your porting process. 24 | For example, if you are porting a TLS client and have issues connecting to a server, then you should run the following setups with debug logs enabled: 25 | 26 | 1. Run `ssl_client2` and `ssl_server2` to first understand the basic TLS connection. 27 | 1. Run `ssl_client2` with the server you are trying to connect to. This will help you understand what CA root certificate you need to set in `mbedtls_ssl_conf_ca_chain()`. 28 | 1. Run `ssl_server2` with your client application. This will have you working with a known server, and help you test your specific porting setup. 29 | 1. Run your client application with the server you are trying to connect to. Once the previous steps have been completed, you should test the final setup, to get past all the TLS related issues. 30 | 31 | If you still encounter problems after trying these steps, then it is likely that your issue is platform specific, such as a memory related issue. 32 | -------------------------------------------------------------------------------- /kb/compiling-and-building/setup-eclipse-cdt-environment-on-windows.md: -------------------------------------------------------------------------------- 1 | # Setting up the Eclipse CDT environment on Windows 2 | 3 | ## Introduction 4 | 5 | This quick start manual is intended for C/C++ developers who are interested in developing Mbed TLS-based projects in Eclipse C/C++ Development Tool (CDT) on Windows. 6 | 7 | ## Software versions used in this tutorial 8 | 9 | * Eclipse C/C++ Development Tool (CDT) Juno SR1. 10 | * Cygwin packages: 11 | * **C compiler:** `gcc-core (3.4.4-999)`. 12 | * **C++ compiler:** `gcc-g++ (3.4.4-999)`. 13 | * **GNU Debugger:** `gdb (7.5.50-1)`. 14 | * **Make utility:** `make (3.82.90-1)`. 15 | 16 | Your experience may differ based on the software versions you use. 17 | 18 | ## Install Cygwin or MinGW 19 | 20 | We recommend Cygwin, so this tutorial doesn't cover the MinGW installation. For more on MinGW, look at [Compiling Mbed TLS in MinGW](compiling-mbedtls-in-mingw.md). 21 | 22 | * Download and install Cygwin by following the first three steps in the [tutorial](http://www3.ntu.edu.sg/home/ehchua/programming/howto/cygwin_howto.html). Make sure that you select `gcc`, `g++`, `gdb`, and `make` packages under the `Devel` (Development) category, since these packages are not part of the default installation. 23 | 24 | * Add `C:\cygwin\bin` to your **PATH Environment Variables**. 25 | 26 | * If you want to check if all needed packages are installed, run the Cygwin Terminal and type `cygcheck -c`. 27 | 28 | ## Install Eclipse C/C++ Development Tool (CDT) 29 | 30 | You can either download and install a new version of Eclipse CDT, or extend the existing **Eclipse for Java Developers** on your system with a CDT plugin. 31 | 32 | **Option 1:** Clean Eclipse CDT install: 33 | * [Download](http://www.eclipse.org/downloads) **Eclipse IDE for C/C++ Developers** and unzip the downloaded file into a directory of your choice. 34 | * Run `eclipse.exe` inside the directory. 35 | 36 | **Option 2:** Extend an existing **Eclipse for Java Developers** installation: 37 | * Launch Eclipse. 38 | * Go to **Help** > **Install New Software**. 39 | * In "Work with", enter the CDT update site `http://download.eclipse.org/tools/cdt/releases/juno` (for Eclipse Juno only) > **Add** > Enter a name (such as CDT 8.1.0) > Select **all the "CDT main features"**. 40 | * You may select optional features. 41 | * Click **Finish**. 42 | * Restart Eclipse after the plugin installation is finished. 43 | 44 | 45 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2020-07.md: -------------------------------------------------------------------------------- 1 | # Side-channel attack on ECC key import and validation 2 | 3 | **Title** | Side-channel attack on ECC key import and validation 4 | ---|--- 5 | **Date** | 1st of July, 2020 6 | **Affects** | All versions of Mbed TLS and Mbed Crypto 7 | **Impact** | A local attacker can extract the private key 8 | **Severity** | High 9 | **Credit** | Alejandro Cabrera Aldaya and Billy Brumley 10 | 11 | ## Vulnerability 12 | 13 | The scalar multiplication function in Mbed TLS accepts a random number 14 | generator (RNG) as an optional argument and, if provided, uses it to protect 15 | against some attacks, including a [previous 16 | attack](mbedtls-security-advisory-2020-04.md) by the same authors. 17 | 18 | It is the caller's responsibility to provide a RNG if protection against side- 19 | channel attacks is desired; however two groups of functions in Mbed TLS itself 20 | fail to pass a RNG: 21 | 22 | 1. `mbedtls_pk_parse_key()` and `mbedtls_pk_parse_keyfile()` 23 | 2. `mbedtls_ecp_check_pub_priv()` and `mbedtls_pk_check_pair()` 24 | 25 | When those functions are called, scalar multiplication is computed without 26 | randomisation, a number of old and new attacks apply, allowing a powerful 27 | local attacker to fully recover the private key. 28 | 29 | It should be noted that the first group of function only performs a scalar 30 | multiplication if the private key being parsed doesn't include the public key, 31 | or includes the public key in compressed formats. Common tools for generating 32 | key pairs tend to include the public key in uncompressed format in the encoded 33 | private key; in that case parsing functions were safe from this attack. 34 | 35 | ## Impact 36 | 37 | An attacker with access to precise enough timing and memory access information 38 | (typically an untrusted operating system attacking a secure enclave such as 39 | SGX or the TrustZone secure world) can fully recover the private key after 40 | collecting a single trace of any of the affected functions. 41 | 42 | ## Resolution 43 | 44 | Affected users will want to upgrade to Mbed TLS 2.23.0, 2.16.7 or 2.7.16 45 | depending on the branch they're currently using. 46 | 47 | ## Workarounds 48 | 49 | For the parsing functions, making sure all keys being parsed always include 50 | the uncompressed public key avoids the vulnerability. 51 | 52 | For the pair-checking functions, there is no work-around except refraining 53 | from using them (they're never called from any other library function). 54 | 55 | If your application calls `mbedtls_ecp_mul()` or 56 | `mbedtls_ecp_mul_restartable()` directly, you want to make sure that you're 57 | always passing a non-NULL `f_rng` parameter, pointing to a well-seeded 58 | instance of a secure RNG. 59 | -------------------------------------------------------------------------------- /tools/bin/mbedtls-test-language-server: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Language server for Mbed TLS test files 3 | """ 4 | 5 | # Copyright The Mbed TLS Contributors 6 | # SPDX-License-Identifier: Apache-2.0 7 | # 8 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 9 | # not use this file except in compliance with the License. 10 | # You may obtain a copy of the License at 11 | # 12 | # http://www.apache.org/licenses/LICENSE-2.0 13 | # 14 | # Unless required by applicable law or agreed to in writing, software 15 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 16 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | # See the License for the specific language governing permissions and 18 | # limitations under the License. 19 | 20 | import re 21 | import sys 22 | from pygls.server import LanguageServer 23 | from lsprotocol import types 24 | 25 | server = LanguageServer('mbedtls-test-server', 'v1') 26 | 27 | TEST_FUNCTION = re.compile(r'void (?P[a-zA-Z_][a-zA-Z0-9_]*)\(') 28 | 29 | @server.feature(types.TEXT_DOCUMENT_DEFINITION) 30 | def data_file_goto_definition(ls: LanguageServer, params: types.DefinitionParams): 31 | # Get data file 32 | data_file = ls.workspace.get_text_document(params.text_document.uri) 33 | 34 | # Get function name under cursor (if there is one) 35 | lookup_word = data_file.word_at_position(params.position) 36 | 37 | print(f'Looking for word {lookup_word}', file=sys.stderr) 38 | 39 | # Substitute '.data' for '.function' in extension to get equivalent function file 40 | # TODO how to deal with generated data files? 41 | function_file_uri = data_file.uri[:-5] + '.function' 42 | function_file = ls.workspace.get_text_document(function_file_uri) 43 | 44 | # Look through the function file to find a match 45 | for n, line in enumerate(function_file.lines): 46 | test_fn_match = TEST_FUNCTION.match(line) 47 | if test_fn_match is not None: 48 | test_fn_name = test_fn_match.group('fn_name') 49 | if test_fn_name == lookup_word: 50 | match_start = test_fn_match.start('fn_name') 51 | match_end = test_fn_match.end('fn_name') 52 | 53 | match_range = types.Range( 54 | start=types.Position(line=n, character=match_start), 55 | end=types.Position(line=n, character=match_end) 56 | ) 57 | 58 | return types.Location( 59 | uri=function_file_uri, 60 | range=match_range 61 | ) 62 | 63 | print(f'Word {lookup_word} not found', file=sys.stderr) 64 | 65 | if __name__ == "__main__": 66 | server.start_io() 67 | 68 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2020-09-3.md: -------------------------------------------------------------------------------- 1 | # Protocol weakness in DHE-PSK key exchange 2 | 3 | **Title** | Protocol weakness in DHE-PSK key exchange 4 | ---|--- 5 | **CVE** | Unknown 6 | **Date** | 1st of September, 2020 ( **Updated on 10th of September, 2020** ) 7 | **Affects** | All versions of Mbed TLS 8 | **Impact** | An active network attacker can learn the size of the pre-shared
key 9 | **Severity** | Low 10 | **Credit** | Robert Merget, Marcus Brinkmann, Nimrod Aviram and Juraj
Somorovsky 11 | 12 | ## Vulnerability 13 | 14 | This is an advisory of a security vulnerability in the TLS specification, 15 | which has very limited impact on Mbed TLS: the Raccoon attack (for details see 16 | the [website](https://raccoon-attack.com/) and the 17 | [paper](https://raccoon-attack.com/RacoonAttack.pdf)). 18 | 19 | In the TLS protocol, the calculation of the premaster secret from the finite- 20 | field Diffie-Hellman (FFDH) shared secret strips the leading zero bytes. If 21 | the Diffie-Hellman private key is reused, side channels during this 22 | calculation may allow an adversary to recover bits of the premaster secret. 23 | Since Mbed TLS does not support static finite-field Diffie-Hellman nor the 24 | reuse of ephemeral keys, the library is not vulnerable to this class of 25 | attacks. 26 | 27 | When using Diffie-Hellman combined with a pre-shared key (DHE-PSK cipher 28 | suites), the premaster secret is constructed by concatenating the pre-shared 29 | key with other elements. Side channels during this calculation may reveal the 30 | length of the pre-shared key. Mbed TLS is vulnerable to this attack. 31 | 32 | Elliptic curve Diffie-Hellman (ECDH, including ECDHE) is not affected in the 33 | same way because the shared secret is used directly without any truncation. 34 | There is a potential implementation flaw if the calculation of the shared 35 | secret truncates leading zero digits and then pads them back, leading to the 36 | same vulnerabilities as in the FFDH case. Mbed TLS copies the shared secret 37 | directly without inspecting the leading digits, so it is not vulnerable to 38 | this class of attacks. 39 | 40 | ## Impact 41 | 42 | Adversaries may be able to learn the size of the pre-shared key in used DHE- 43 | PSK cipher suites. 44 | 45 | ## Resolution 46 | 47 | It is unusual to rely on the confidentiality of the length of a key. Even the 48 | minimum length of the key needs to be sufficiently large not to be vulnerable 49 | to brute-force attacks. As a consequence, we do not plan to mitigate this 50 | issue in Mbed TLS. 51 | 52 | ## Work-around 53 | 54 | If you use a DHE-PSK cipher suite, treat the length of the pre-shared key as a 55 | public quantity. If you have privacy concerns, always use a pre-shared key of 56 | the same length. 57 | -------------------------------------------------------------------------------- /kb/development/entropy-collection-and-random-generation-in-threaded-environment.md: -------------------------------------------------------------------------------- 1 | # Entropy collection, random generation with threads 2 | 3 | ## Entropy collection and random generation 4 | 5 | Random generators, such as the [CTR-DRBG module](/ctr-drbg-source-code), require a source of entropy to kick-start and refresh their own internal entropy state. Mbed TLS includes the [Entropy collection module](/entropy-source-code) to provide a central pool of entropy to extract entropy from. In a single-threaded application, both the entropy pool and the random generator exist within the same thread context. In case of a multi-threaded application, you can either use a central entropy pool and/or random generator or thread-specific versions. 6 | 7 | ## How does entropy collection work 8 | 9 | The entropy collector works by gathering entropy from multiple sources and integrating them into its internal entropy state. Each time entropy is collected the internal state gets better. Unless additional entropy sources have been added to the default entropy collector sources, mostly OS dependent random sources are used. Each time the entropy collector gathers entropy from the system, the entropy gets extracted and reduced. 10 | 11 | ## Random generators and entropy 12 | 13 | The random generators themselves, like CTR-DRBG, do not require new entropy every time they are called. Instead, they expand the available entropy to produce random without compromising the original entropy and being secure as long as not too much random is generated from one state. Therefore, the random generators occasionally gather entropy from the entropy collector to refresh their state. 14 | 15 | ## Advice for threaded environments 16 | 17 | Regarding entropy, our advice is to use a central entropy collector. Initialize once. This makes sure that the entropy collector gets the best entropy from its sources as it does not have to share with sibling entropy collectors. For more details, see [Thread Safety and Multi Threading](thread-safety-and-multi-threading.md). 18 | 19 | You have two options: 20 | 21 | * For each thread, use a separate CTR-DRBG or HMAC-DRBG random generator using a thread-specific value (like the thread ID) for the custom personalization string. Provide the DRBG with `mbedtls_entropy_func()` as its entropy callback. This ensures that the random generators between the different threads have the least amount of correlation possible and can thus be considered as independent as possible. 22 | 23 | * Use a central CTR-DRBG or HMAC-DRBG context initialized once in the main thread, and share in across threads. The DRBG modules are thread-safe, as they contain locks within the contexts, which are used within the modules if threading is enabled, see [Thread Safety and Multi Threading](thread-safety-and-multi-threading.md). 24 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2024-10-1.md: -------------------------------------------------------------------------------- 1 | # Buffer underrun in pkwrite when writing an opaque key pair 2 | 3 | **Title** | Buffer underrun in pkwrite when writing an opaque key pair 4 | --------- | ---------------------------------------------------------- 5 | **CVE** | CVE-2024-49195 6 | **Date** | 15 October 2024 7 | **Affects** | Mbed TLS 3.5.0 to 3.6.1 included 8 | **Severity** | HIGH 9 | 10 | ## Vulnerability 11 | 12 | The functions `mbedtls_pk_write_key_der()` and `mbedtls_pk_write_key_pem()` can cause a buffer underrun when the output buffer is too small in some cases. In all problematic cases: 13 | 14 | * The compile-time option `MBEDTLS_USE_PSA_CRYPTO` is enabled. 15 | * The PK context contains an opaque key (`MBEDTLS_PK_OPAQUE`, typically set up with `mbedtls_pk_setup_opaque()`). 16 | 17 | The following cases are problematic: 18 | 19 | * Writing an elliptic curve key pair with `mbedtls_pk_write_key_der()`, when the compile-time option `MBEDTLS_ECP_C` is enabled, with an output buffer that is smaller than the representation of the public key as an uncompressed point. 20 | * Writing an RSA key pair with `mbedtls_pk_write_key_der()`, with an output buffer that is smaller than the actual output. 21 | * Writing an RSA key pair with `mbedtls_pk_write_key_pem()`, if `MBEDTLS_MPI_MAX_SIZE <= 420`. 22 | 23 | Each of these cases trigger a code path where the output is first written safely into an intermediate buffer. The output is then copied to the destination buffer supplied by the application code, without checking that the buffer is large enough. 24 | 25 | ## Impact 26 | 27 | The consequence of the vulnerability is a buffer underrun of up to the size of the key representation. Depending on the location of the application buffer, this can result in stack or heap corruption. 28 | 29 | ## Affected versions 30 | 31 | The vulnerability is present in Mbed TLS 3.5.x, Mbed TLS 3.6.0 and Mbed TLS 3.6.1. Earlier versions had a different implementation of the problematic cases and are not affected. 32 | 33 | ## Resolution 34 | 35 | Affected users should upgrade to Mbed TLS 3.6.2. 36 | 37 | ## Work-around 38 | 39 | Calling `mbedtls_pk_write_key_der()` with a buffer that is large enough for the content is always safe. Furthermore, `PSA_EXPORT_KEY_PAIR_MAX_SIZE` is always a safe buffer size. There are no unsafe calls to `mbedtls_pk_write_key_der()` within Mbed TLS itself, except when calling `mbedtls_pk_write_key_pem()` in the configurations described below. 40 | 41 | `mbedtls_pk_write_key_pem()` is safe when `MBEDTLS_MPI_MAX_SIZE >= 421` or when `MBEDTLS_USE_PSA_CRYPTO` is disabled. 42 | 43 | These functions are only vulnerable when called on PK contexts of type `MBEDTLS_PK_OPAQUE`. Copying the key with `mbedtls_pk_copy_from_psa` and calling `mbedtls_pk_write_key_xxx()` on the resulting non-opaque key is safe. 44 | -------------------------------------------------------------------------------- /kb/generic/abstraction-layers.md: -------------------------------------------------------------------------------- 1 | # Mbed TLS abstraction layers 2 | 3 | ## Abstraction layers 4 | 5 | > Not all systems are made equal. Some are more equal than others. 6 | 7 | The Mbed TLS core allows smooth integration on a wide number of platforms. It provides a number of abstraction layers that make this possible. 8 | 9 | ## Standard function abstraction 10 | 11 | These are standard functions from libc that are always needed. However, they will have different implementations and behave differently on some platforms. 12 | 13 | Examples: `calloc()`, `free()`, `printf()` and `fprintf()`. 14 | 15 | These standard functions are abstracted in the **platform layer**. The layer core is enabled by default in `mbedtls_config.h` with `MBEDTLS_PLATFORM_C`, and allows the runtime customization of the relevant function. 16 | 17 | The `MBEDTLS_PLATFORM_XXX` defined in `mbedtls_config.h` enables support for abstracting different functions. 18 | 19 | For example, after enabling `MBEDTLS_PLATFORM_PRINTF_ALT`, you can set an alternative for `printf()` by calling `mbedtls_platform_set_printf()`. 20 | 21 | ## Additional function abstraction 22 | 23 | These are additional functions from external libraries or OS that are needed only in some circumstances, for example, threading library support. 24 | 25 | Examples: threading. 26 | 27 | These abstractions are implemented in their own module and enabled or disabled with a single define, for example, `MBEDTLS_THREADING_C` in `mbedtls_config.h`. They may also require additional configuration options. The threading library, for example, requires you to indicate which threading library you are using: pthread or an alternative. 28 | 29 | ## Implementation abstraction 30 | 31 | These are abstractions for functions that we already provide an implementation for. However, some users may want to use their own versions instead, for example, those optimized for their platforms. 32 | 33 | Examples: AES, MD5 and Timing. 34 | 35 | To enable an implementation abstraction: 36 | - You'll need to enable the relevant macro: `MBEDTLS_XXX_ALT` in `mbedtls_config.h`. 37 | - Provide a custom header, named: `xxx_alt.h`. 38 | - Provide an implementation. 39 | 40 | You can also opt to provide your own version of the `core` function of a module, rather than the whole module. 41 | 42 | Examples: AES setkey, AES block encrypt and decrypt, and SHA process. 43 | 44 | To enable an implementation abstraction, you must provide your own implementation of the relevant function with the same prototype as the default implementation. 45 | 46 | 47 | -------------------------------------------------------------------------------- /kb/how-to/encrypt-with-aes-cbc.md: -------------------------------------------------------------------------------- 1 | # Encrypt data with AES-CBC mode 2 | 3 | To encrypt data with [AES](/aes-source-code), you need a key. If you are not familiar with key generation, please check out [How to generate an AES key](generate-an-aes-key.md) for more information. 4 | 5 | **Note:** Please understand that only encrypting data with AES-CBC does not keep the data safe from modification or viewing. You still have to protect the **key** from others and the **integrity** of the data. This article only shows you how to use the [AES API](/api/aes_8h.html) to encrypt some data with the AES-CBC mode. 6 | 7 | To start using AES, add the header file for the module to your file: 8 | 9 | ``` 10 | #include "mbedtls/aes.h" 11 | ``` 12 | 13 | Declare the variables needed for AES encryption: 14 | 15 | ``` 16 | mbedtls_aes_context aes; 17 | 18 | unsigned char key[32]; 19 | unsigned char iv[16]; 20 | 21 | unsigned char input [128]; 22 | unsigned char output[128]; 23 | 24 | size_t input_len = 40; 25 | size_t output_len = 0; 26 | ``` 27 | 28 | This examples assumes you've filled the variable named **key** with the 32 bytes of the AES key (see [How to generate an AES key](generate-an-aes-key.md)), **iv** with 16 bytes of random data for use as the Initialization Vector (IV) and **input** with 40 bytes of input data, and zeroized the rest of **input**. 29 | 30 | The **CBC** mode for AES assumes that you provide data in blocks of 16 bytes. Because there are only 40 bytes of data, you have to extend the input to contain 48 bytes of data, instead. There are multiple ways to pad input data. One is to add zeroes to the end. This is only secure if you also transmit the original length of the input data (40 in this case) securely to the other side, as well. This example uses padding with zeroes. 31 | 32 | First, initialize the AES context with your **key**, and then encrypt the data (with padding) to the output buffer with your **iv**: 33 | 34 | ``` 35 | mbedtls_aes_setkey_enc( &aes, key, 256 ); 36 | mbedtls_aes_crypt_cbc( &aes, MBEDTLS_AES_ENCRYPT, 48, iv, input, output ); 37 | ``` 38 | 39 | The first 48 bytes of the **output** buffer contain the encrypted data. This data is only protected for confidentiality purposes. You need to send the length of the input data, the IV and the output buffer to the other side while protecting the integrity of those values. In addition, the other side needs the key without anybody ever knowing it. Usually this means making a hash over the length of the input data, the IV and the output buffer and encrypting this hash and the AES key with the public RSA key of the other party using the PKCS#1 encrypt function. 40 | 41 | 42 | -------------------------------------------------------------------------------- /kb/development/how-are-error-codes-defined.md: -------------------------------------------------------------------------------- 1 | # How to define error codes for new modules 2 | 3 | ## How error codes are structured 4 | 5 | The main structure for the error codes is documented in the `error.h` file. 6 | 7 | Currently, we try to keep all error codes within the negative space of 16 bit signed integers to support all 16-bit and 32-bit platforms (-0x0001 - -0x7FFF). In addition we'd like to give two layers of information on the error if possible. For example, if an X.509 certificate is not parsed correctly because of an ASN.1 error, we would like to reflect that in the error code. 8 | 9 | For that purpose we have divided the different modules into high-level and low-level modules. The low-level modules don't depend massively on anything else, such as the ASN.1 parser, the AES module, the SHA1 module or the OID database. The high-level modules are the ones that use low-level modules a lot, such as the X.509 parser, the RSA module or the main SSL module. 10 | 11 | For that purpose the 16-bit error codes are segmented in the following manner: 12 | 13 | - 1 bit Unused (sign bit) 14 | - 3 bits High level module ID 15 | - 5 bits Module-dependent error code 16 | - 7 bits Low level module errors 17 | 18 | For historical reasons, low-level error codes are divided in even and odd, even codes were assigned first, and -1 is reserved for other errors. 19 | 20 | This space-division allows one error code to propagate one low-level error and one high-level error in the same error code by just adding them together (`HIGH_LEVEL_ERROR + LOW_LEVEL_ERROR`). 21 | 22 | **Note:**: As the error codes are negative and processors use 2's complement internally for representing negative numbers, XOR'ing them together does not work. 23 | 24 | As error codes are something 'internal', the actual representation and division is not relevant for high-level users that will only use the defined values anyway. 25 | 26 | ## Adding a new low-level module to Mbed TLS 27 | 28 | Find some space within the `error.h` file to fit the number of the error codes you need. 29 | 30 | Add the name to the list of low-level modules in the `error.h` file and in `scripts/generate_errors.pl`. 31 | 32 | ## Adding a new high-level module to Mbed TLS 33 | 34 | Find some module space in the `error.h` file to fit the number of error codes you need. As all the high-level module numbers are filled, we are now also starting to use the same numbers from the top. 35 | 36 | Add the name to the list of high-level modules in the `error.h` file and in `scripts/generate_errors.pl`. 37 | 38 | ## User-friendly error strings for `mbedtls_strerror()` 39 | 40 | Add the respective error codes to your module's header file with a description, like this: 41 | 42 | ``` 43 | #define MBEDTLS_ERR_AES_INVALID_KEY_LENGTH-0x0020 /**< Invalid key length. */ 44 | ``` 45 | 46 | The doxygen description will be used as the user-friendly `mbedtls_strerror()` error message. 47 | 48 | Regenerate the `error.c` file. 49 | 50 | Now regenerate `library/error.c` with: 51 | 52 | `scripts/generate_errors.pl` 53 | -------------------------------------------------------------------------------- /kb/how-to/code-size.md: -------------------------------------------------------------------------------- 1 | # How to get code size of the library 2 | 3 | Embedded platforms have memory limitations. Deciding what library to use on your product is important, to save overall code size. Therefore, you need the code size of Mbed TLS. This article is relevant for platforms running on Cortex M3/M4. 4 | 5 | Mbed TLS is a configurable library, so its code size varies, depending on the configuration used. For more information on how to control and reduce the code size, see [Reducing Mbed TLS memory and storage footprint](reduce-polarssl-memory-and-storage-footprint.md). 6 | 7 | Obtain the code size of the library by using the `arm-none-eabi-size -t` command (when using the `arm-none-eabi` toolchain). 8 | 9 | Mbed TLS supplies a script that checks the [footprint](https://github.com/Mbed-TLS/mbedtls/blob/development/scripts/footprint.sh) of the library. The script shows the code size of the library compiled with several configuration files: 10 | 11 | * `include/mbedtls/mbedtls_config.h` (`include/mbedtls/config.h` in Mbed TLS 2.x) - The default configuration file, unless modified by the user. 12 | * `configs/config-thread.h` - A minimal configuration example of Mbed TLS using Thread networking protocol. 13 | * `configs/config-suite-b.h` - A minimal configuration example supporting NSA Suite B. 14 | * `configs/config-ccm-psk-tls1_2.h` - A minimal configuration example supporting preshared key and with AES-CCM. 15 | 16 | ## Prerequisites 17 | 18 | * `arm-none-eabi` toolchain installed and found in the `PATH` environment variable. 19 | * `make`. 20 | * POSIX shell. 21 | * Updated `include/mbedtls/mbedtls_config.h` with the required configuration. See [How do I configure Mbed TLS](../compiling-and-building/how-do-i-configure-mbedtls.md) for more information. 22 | 23 | Note: The `arm-none-eabi` toolchain may give different results than other toolchains, such as `ARMCC` or `IAR. 24 | 25 | ## Usage 26 | 27 | ./scripts/footprint.sh 28 | 29 | Output will be: 30 | > Footprint of standard configurations (minus net_sockets.c, timing.c, fs_io) 31 | > for bare-metal ARM Cortex-M3/M4 microcontrollers. 32 | > 33 | > Mbed TLS 2.4.1 (git head: af610a0baf) 34 | > arm-none-eabi-gcc (15:4.9.3+svn231177-1) 4.9.3 20150529 (prerelease) 35 | > CFLAGS=-Os -march=armv7-m -mthumb 36 | > 37 | > default (include/mbedtls/config.h): 38 | > text data bss dec hex filename 39 | > 250087 612 9360 260059 3f7db (TOTALS) 40 | > 41 | > thread (configs/config-thread.h): 42 | > text data bss dec hex filename 43 | > 58021 19 10 58050 e2c2 (TOTALS) 44 | > 45 | > suite-b (configs/config-suite-b.h): 46 | > text data bss dec hex filename 47 | > 79988 88 11 80087 138d7 (TOTALS) 48 | > 49 | > psk (configs/config-ccm-psk-tls1_2.h): 50 | > text data bss dec hex filename 51 | > 28115 12 4 28131 6de3 (TOTALS) 52 | 53 | When you use Mbed TLS as a static library, you can optimize the linker to omit any unused symbol. You can find full symbol information in `mbedtls-footprint.zip`. 54 | -------------------------------------------------------------------------------- /kb/development/thread-safety-and-multi-threading.md: -------------------------------------------------------------------------------- 1 | # Thread safety and multithreading: concurrency issues 2 | 3 | ## Thread safety 4 | 5 | You can use Arm Mbed TLS in threaded and nonthreaded environments. To keep Mbed TLS thread-safe, it is important to remember a few things. 6 | 7 | First, most `mbedtls_xxx()` functions use an explicit context. Most of the time, as long as threads do not share this context, you're safe. However, sometimes threads can share a context indirectly. For example, an SSL context can point to an RSA context (the private key). 8 | 9 | The default philosophy is that a single thread should only use or access one context at a same time, unless: 10 | 11 | - The documentation for the functions that access the shared context explicitly states the function is thread-safe, or 12 | - You perform explicit locking yourself (perhaps in a wrapper function). 13 | 14 | **Warning: [The PSA API is not thread-safe before Mbed TLS 3.6.0](https://github.com/Mbed-TLS/mbedtls/issues/3263).** Upgrade to the 3.6 LTS branch or newer if you need the PSA API or TLS 1.3 (which uses PSA under the hood) in a multithreaded application. Since Mbed TLS 3.6.0, the PSA API is thread-safe when `MBEDTLS_THREADING_C` is enabled. 15 | 16 | ## Thread safety with different versions 17 | 18 | Mbed TLS has a generic threading layer that handles default locks and mutexes for the user and abstracts the threading layer to allow easy pluging in any thread-library. 19 | 20 | Defining **MBEDTLS_THREADING_C** in `mbedtls_config.h` enables this threading layer. Please see [How do I configure Mbed TLS](../compiling-and-building/how-do-i-configure-mbedtls.md) for more information. It is not enabled by default; you also need to pick an underlying threading library. We provide built-in support for `pthread` with **MBEDTS_THREADING_PTHREAD**. You can also plug any other thread-library with **MBEDTLS_THREADING_ALT** and call `mbedtls_threading_set_alt()` at the beginning of your program and `mbedtls_threading_free_alt()` at the end. 21 | 22 | ## Status of various contexts and associated functions 23 | 24 | All contexts have associated `_init()` and `_free()` functions. For contexts that include mutexes, these functions create and initialize the mutex and then free and destroy it. If you share a context between threads, you need to call these functions only from the main thread, at the beginning and end of the context's lifetime. 25 | 26 | Mbed TLS currently provides automatic locking (when the threading layer is enabled) for relevant functions in the following modules (unless indicated otherwise): 27 | 28 | - RSA. 29 | - The SSL cache callbacks provided in `ssl_cache.c`. 30 | - Memory buffer-based allocator. 31 | - Entropy 32 | - In the X.509 module, `mbedtls_x509_crt_parse_path()` is thread-safe.. 33 | - CTR-DRBG and HMAC-DRBG. 34 | - The SSL session tickets callbacks provided in *ssl_ticket.c*. 35 | - The DTLS CLientHello cookie callbacks provided in *ssl_cookie.c*. 36 | - PSA, since Mbed TLS 3.6.0. 37 | 38 | This covers the most common cases in which you need to share a context across threads. If you have use cases in which you need to share another context across threads, please let us know. 39 | -------------------------------------------------------------------------------- /kb/how-to/add-a-random-generator.md: -------------------------------------------------------------------------------- 1 | # Random data generation 2 | 3 | When making a security application, you may require a random data generator. Arm Mbed TLS includes the [CTR-DRBG module](ctr-drbg-source-code.html) for random generation. 4 | 5 | Setting up CTR-DRBG in your code requires an entropy source and a personalization string. 6 | 7 | ## Setting up the entropy source 8 | 9 | Mbed TLS includes the [entropy collection module](entropy-source-code.html) to provide a central pool of entropy from which to extract entropy. 10 | 11 | To use the entropy collector in your code, include the header file: 12 | 13 | ``` 14 | #include "mbedtls/entropy.h" 15 | ``` 16 | 17 | Add the following somewhere in your `main()`: 18 | 19 | ```c 20 | mbedtls_entropy_context entropy; 21 | mbedtls_entropy_init( &entropy ); 22 | ``` 23 | 24 | If your platform has a hardware TRNG or PRNG in the processor or TPM, you can hook it up to the entropy collector with `entropy_add_source()` to enhance the entropy even further. Please see our article on [how to add an entropy source to the entropy pool](add-entropy-sources-to-entropy-pool.md) for more information. 25 | 26 | ## The random generator 27 | 28 | To use the CTR-DRBG module in your code, you need to include the header file: 29 | 30 | ```c 31 | #include "mbedtls/ctr_drbg.h" 32 | ``` 33 | 34 | Add: 35 | 36 | ```c 37 | mbedtls_ctr_drbg_context ctr_drbg; 38 | char *personalization = "my_app_specific_string"; 39 | 40 | mbedtls_ctr_drbg_init( &ctr_drbg ); 41 | 42 | ret = mbedtls_ctr_drbg_seed( &ctr_drbg , mbedtls_entropy_func, &entropy, 43 | (const unsigned char *) personalization, 44 | strlen( personalization ) ); 45 | if( ret != 0 ) 46 | { 47 | // ERROR HANDLING CODE FOR YOUR APP 48 | } 49 | ``` 50 | 51 | The **personalization** string is a small protection against a lack of startup entropy and ensures each application has at least a different starting point. 52 | 53 | ## Enabling prediction resistance 54 | 55 | To prevent an adversary from reading your random data, you can enable prediction resistance: 56 | 57 | ```c 58 | mbedtls_ctr_drbg_set_prediction_resistance( &ctr_drbg, MBEDTLS_CTR_DRBG_PR_ON ); 59 | ``` 60 | 61 | **Note:** If enabled, entropy is gathered before each call. Only use this if you have ample supply of good entropy. 62 | 63 | ## Loading a seed file 64 | 65 | Another way to add entropy at the start of your application is to use a seed file. The Mbed TLS random generator can read and update a seed file with `mbedtls_ctr_drbg_update_seed_file()` to increase entropy. 66 | 67 | ## Multithreaded use 68 | 69 | If you intend to use the CTR-DRBG module in multiple threads, please read our article on [entropy collection, random generation with threads](../development/entropy-collection-and-random-generation-in-threaded-environment.md). 70 | 71 | 72 | -------------------------------------------------------------------------------- /kb/how-to/using-static-memory-instead-of-the-heap.md: -------------------------------------------------------------------------------- 1 | # Alternative ways of allocating memory in Mbed TLS 2 | 3 | In several situations, like when not having an operating system on an embedded platform, there is no real availability of a heap or `calloc()`/`free()`. Mbed TLS still needs some form of dynamic memory allocation to operate the SSL stack. We could just assume the maximum sizes for all structures, but that would consume a lot of memory space. Instead we opted for letting Mbed TLS only use hooks to allocate and free dynamic memory. 4 | 5 | This currently gives you two options: 6 | 7 | 1. Provide your own allocation and freeing functions. 8 | 2. Use the buffer allocator feature in Mbed TLS. 9 | 10 | To enable the memory allocation layer, define `MBEDTLS_PLATFORM_C` and `MBEDTLS_PLATFORM_MEMORY` in the `mbedtls_config.h` file. See [How do I configure Mbed TLS](../compiling-and-building/how-do-i-configure-mbedtls.md). 11 | 12 | If you do not enable the layer, the libc standard `calloc()` and `free()` are used. 13 | 14 | ## Internals 15 | 16 | Internally, there are just two function pointers `mbedtls_calloc()` and `mbedtls_free()` that are called within Mbed TLS for each dynamic memory allocation or de-allocation. 17 | 18 | extern void * (*mbedtls_calloc)( size_t n, size_t size ); 19 | extern void (*mbedtls_free)( void *ptr ); 20 | 21 | The prototypes for these functions are identical to the `libc` standard `calloc()` and `free()`. Without any further calls, the default `libc` names are assigned to these pointers. 22 | 23 | ### No libc equivalents 24 | 25 | If your system does not have a `libc` equivalent, you will get compile errors as `calloc()` or `free()` cannot be found. 26 | 27 | Defining `MBEDTLS_PLATFORM_NO_STD_FUNCTIONS` in the `mbedtls_config.h` file prevents Mbed TLS from ever knowing about those functions. 28 | 29 | ### Providing your own hooks 30 | 31 | If your operating system already provides an alternative to the `libc` allocator functions, you can set them with: 32 | 33 | int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ), 34 | void (*free_func)( void * ) ); 35 | 36 | ## Using the Mbed TLS buffer allocator 37 | 38 | If you want Mbed TLS to allocate everything inside a static buffer, you can enable the buffer allocator by defining `MBEDTLS_MEMORY_BUFFER_ALLOC_C` in the `mbedtls_config.h` file. 39 | 40 | Before calling any other Mbed TLS functions, enable the buffer allocator as follows: 41 | 42 | unsigned char memory_buf[100000]; 43 | mbedtls_memory_buffer_alloc_init( memory_buf, sizeof(memory_buf) ); 44 | 45 | ## Security warning 46 | 47 | The buffer allocator is a straightforward approach to a dynamic memory allocator. No special heap protection mechanisms have been implemented. 48 | 49 | ## Using the buffer allocator elsewhere 50 | 51 | The buffer allocator itself has no internal dependencies on any of the rest of Mbed TLS. So you can use it within your own codebase as well. 52 | 53 | 54 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2023-10-1.md: -------------------------------------------------------------------------------- 1 | # Buffer overread in TLS stream cipher suites 2 | 3 | **Title** | Buffer overread in TLS stream cipher suites 4 | ---|--- 5 | **CVE** | CVE-2023-43615 6 | **Date** | 05 October 2023 7 | **Affects** | All versions of Mbed TLS 8 | **Impact** | A remote attacker may cause a crash or information disclosure. 9 | **Severity** | Medium 10 | **Credit** | OSS-Fuzz 11 | 12 | ## Vulnerability 13 | 14 | A peer in a (D)TLS connection using a null-cipher or RC4 cipher suite can send a malformed encrypted (or null-encrypted) record that causes a buffer overread of the vulnerable application. When the TLS parsing code calculates the MAC of the record, it subtracts the MAC length from the record length without checking if the record is large enough. As a consequence, if the payload of the record is shorter than the MAC, the code attempts to read slightly less than `SIZE_MAX` bytes to calculate the MAC of the received record. 15 | 16 | Note that only weak cipher suites are affected: cipher suites using the null cipher (`TLS_xxx_WITH_NULL_hhh`, with authentication but not encryption) or RC4 (`TLS_xxx_WITH_RC4_128_hhh`, a weak and deprecated cipher, no longer supported after Mbed TLS 3.0). Those cipher suites are disabled in the default build-time configuration. 17 | 18 | All protocol versions up to 1.2 are affected, including DTLS. TLS 1.3 is not affected. CBC and AEAD cipher suites are not affected. 19 | 20 | ## Impact 21 | 22 | A (D)TLS peer that has successfully completed a handshake using a null-cipher or RC4 cipher suite can cause a buffer overread. On many platforms, this will result in a memory access fault. On platforms without memory protection, if the address space contains memory-mapped peripherals, the read operations can cause unpredictable results. 23 | 24 | ## Resolution 25 | 26 | Affected users will want to upgrade to Mbed TLS 3.5.0 or 2.28.5 depending on the branch they're currently using. 27 | 28 | ## Work-around 29 | 30 | The vulnerability is not present in the default build of Mbed TLS. It is only present if the compile-time configuration enables the vulnerable cipher suites. If you use a custom configuration and you want to check that the vulnerable cipher suites are not included in your build: 31 | 32 | * In Mbed TLS 3.x or 2.28, make sure that `MBEDTLS_CIPHER_NULL_CIPHER` is not enabled. 33 | * In Mbed TLS 2.28, also make sure that `MBEDTLS_REMOVE_ARC4_CIPHERSUITES` is enabled, or that `MBEDTLS_ARC4_C` is not enabled. 34 | 35 | If the vulnerable cipher suites are enabled at compile time, they can be disabled at run time by calling `mbedtls_ssl_conf_ciphersuites()` with a list that does not include null-cipher or RC4 cipher suites. Alternatively, call `mbedtls_ssl_conf_ciphersuites_for_version()` for all affected protocol versions (SSLv3, TLS 1.0, TLS 1.1, TLS 1.2). 36 | 37 | Applications that only accept TLS 1.3 are not affected. 38 | 39 | The vulnerability only affects data records after a successful handshake, so if your TLS endpoint requires authentication, it can only be exploited by an authenticated client. Also, a firewall that prevents the negotiation of null-cipher or RC4 cipher suites will prevent the vulnerability from being exploited by traffic that goes through the firewall. 40 | -------------------------------------------------------------------------------- /security-advisories/polarssl-security-advisory-2013-01.md: -------------------------------------------------------------------------------- 1 | # PolarSSL Security Advisory 2013-01 2 | 3 | **Title** | Lucky thirteen - timing side channel during decryption 4 | ---|--- 5 | **CVE** | CVE-2013-0169 6 | **Date** | 4th of February 2013 ( **Updated on 12th of July 2013** ) 7 | **Affects** | all checked SSL libraries including PolarSSL versions prior to
PolarSSL 1.2.6 8 | **Not affected** | AES-GCM-based or RC4-based ciphersuites. Servers and
clients that only communicate over a private network 9 | **Impact** | Possible (partial) recovery of plaintext 10 | **Exploit** | Withheld 11 | **Solution** | Upgrade to PolarSSL 1.2.6 or PolarSSL 1.1.6 12 | **Workaround** | Only use AES-GCM-based of RC4-based ciphersuites 13 | **Credits** | Kenny Paterson and Nadhem Alfardan 14 | 15 | The paper [Lucky Thirteen: Breaking the TLS and DTLS Record 16 | Protocols](http://www.isg.rhul.ac.uk/tls) by Kenny Paterson and Nadhem 17 | Alfardan describes a family of attacks that applies to implementations of CBC- 18 | mode ciphersuites in TLS 1.1 and 1.2 / DTLS 1.0 and 1.2 (and earlier 19 | implementations). 20 | 21 | The attack is based on the fact that, when badly formatted padding is 22 | encountered during decryption, a MAC check must still be performed on some 23 | data to prevent the known timing attacks. The RFCs for TLS 1.1 and TLS 1.2 24 | recommend checking the MAC as if there was a zero-length pad. Depending on 25 | some other factors, the small timing difference introduced here can be used to 26 | perform a an attack to reveal (part of) the plaintext. 27 | 28 | ## Impact 29 | 30 | When a CBC-based ciphersuite is used and an adversary has the ability to 31 | inject packets at will into the connection between the client and the server, 32 | the adversary can potentially use statistical analysis to retrieve plaintext 33 | from ciphertext messages. 34 | 35 | All SSL libraries checked by the authors were revealed to be vulnerable in 36 | some way. 37 | 38 | This attack works better against DTLS than regular TLS. PolarSSL only uses 39 | regular TLS at this point. In addition PolarSSL does not send the alert 40 | messages required for the adversary to properly perform this attack. Keep this 41 | in mind when assessing the impact for your situation. 42 | 43 | ## Resolution 44 | 45 | PolarSSL 1.2.5 and PolarSSL 1.2.6 contain fixes in the SSL decrypt process ( 46 | **ssl_decrypt_buf()** ) that remove the timing differences that can result 47 | from malformed padding data. As a result our timing tests show that 48 | **ssl_decrypt_buf()** now returns in a semi-fixed amount of time independent 49 | of the padding length preventing an adversary to use these timing differences 50 | to attack the secured communication channel. 51 | 52 | ## Workaround 53 | 54 | As a workaround it is also possible to disable CBC-based ciphersuites and only 55 | allow AES-GCM-based or RC4-based ciphersuites. Due to the nature of these 56 | ciphersuites they are not vulnerable to the attacks described in the paper. 57 | 58 | ## Advice 59 | 60 | We strongly advise you to upgrade to PolarSSL 1.2.6 if an adversary can gain 61 | access to (part of) the network and inject packets between your servers and 62 | clients. 63 | 64 | ## Special thanks 65 | 66 | We want to thank Kenny and Nadhem for their support during the disclosure 67 | phase and the testing of our patch. 68 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2024-08-3.md: -------------------------------------------------------------------------------- 1 | # Limited authentication bypass in TLS 1.3 optional client authentication 2 | 3 | **Title** | Limited authentication bypass in TLS 1.3 optional client authentication 4 | --------- | ----------------------------------------------------- 5 | **CVE** | CVE-2024-45159 6 | **Date** | 30 August 2024 7 | **Affects** | Mbed TLS 3.2.0 to 3.6.0 included 8 | **Severity** | Medium 9 | 10 | ## Vulnerability 11 | 12 | TLS servers can use optional authentication of the client with 13 | `mbedtls_ssl_conf_authmode(..., MBEDTLS_SSL_VERIFY_OPTIONAL);`, then after the 14 | handshake has completed, call `mbedtls_ssl_get_verify_result()` to check if 15 | the client provided a certificate and if it was correct. If a certificate was 16 | not provided or it was not valid, the return value of this function should be 17 | non-zero, with particular bits set to indicate what exactly was wrong about 18 | the certificate. 19 | 20 | In particular, with TLS 1.3, if a client presents a certificate that does not 21 | have the `digitalSignature` bit set in its `keyUsage` extension, the bit 22 | `MBEDTLS_X509_BADCERT_KEY_USAGE` should be set in the return value of 23 | `mbedtls_ssl_get_verify_result()`. Similarly, if the certificate doesn't have 24 | `clientAuth` listed in its `extKeyUsage` extension, the return value should 25 | have the bit `MBEDTLS_X509_BADCERT_EXT_KEY_USAGE` set. 26 | 27 | With TLS 1.3 in Mbed TLS 3.6.0, this was not happening: those two bits were 28 | always unset, regardless of whether the `keyUsage` and `extKeyUsage` 29 | extensions were correct or not. In particular, if those were the only issues 30 | with the certificate, `mbedtls_ssl_get_verify_result()` would return `0`, 31 | incorrectly presenting the certificate as fully valid. 32 | 33 | This only impacts TLS 1.3 optional client authentication. Mandatory authentication 34 | (`MBEDTLS_SSL_VERIFY_REQUIRED`) is not affected (it will correctly abort the 35 | handshake with a fatal alert if the client certificate is absent or invalid). 36 | TLS 1.2 authentication is not affected. TLS 1.3 server authentication is not 37 | affected, as before 3.6.1 it could not be made optional. 38 | 39 | ## Impact 40 | 41 | An attacker in possession of a certificate valid for uses other than TLS 42 | client authentication was able to use it for TLS client authentication. 43 | 44 | Note that the certificate needs to be valid (in particular, signed by a CA 45 | trusted by the victim TLS server) except for the `keyUsage` and `extKeyUsage` 46 | extension values. 47 | 48 | ## Affected versions 49 | 50 | The vulnerability was present in 3.2.0 which was the first version to support 51 | client authentication in TLS 1.3. 52 | 53 | Note that until 3.6.0, support for TLS 1.3 was disabled in the default 54 | compile-time configuration, which meant the vulnerability was not present in a 55 | default build. In 3.6.0, TLS 1.3 became enabled by default, making the 56 | vulnerability present in the default configuration. 57 | 58 | ## Resolution 59 | 60 | Affected users should upgrade to Mbed TLS 3.6.1. 61 | 62 | ## Work-around 63 | 64 | The issue can be avoided by forcing use of TLS 1.2 with connections that use 65 | optional client authentication. That is, all servers that call 66 | `mbedtls_ssl_conf_authmode(..., MBEDTLS_SSL_VERIFY_OPTIONAL);` should also call 67 | `mbedtls_ssl_conf_max_tls_version(..., MBEDTLS_SSL_VERSION_TLS1_2);`. 68 | 69 | -------------------------------------------------------------------------------- /kb/cryptography/elliptic-curve-performance-nist-vs-brainpool.md: -------------------------------------------------------------------------------- 1 | # Elliptic curve performance: NIST vs. Brainpool 2 | 3 | ## Introduction 4 | Using different elliptic curves has a high impact on the performance of ECDSA, ECDHE and ECDH operations. Each type of curve was designed with a different primary goal in mind, which is reflected in the performance of the specific curves. 5 | 6 | The following numbers, measured with Mbed TLS 2.18.0 on a 3.40 GHz Core i7, are only indicative of the relative speed of the various curves. The absolute value depends on your platform. These numbers also use the default settings for speed-memory trade-offs, and you can read more about [Reducing Mbed TLS memory and storage footprint](../how-to/reduce-polarssl-memory-and-storage-footprint.md). 7 | 8 | ## ECDSA Performance 9 | 10 | ### NIST Curve Performance 11 | ``` 12 | ECDSA-secp521r1 : 1093 sign/s 13 | ECDSA-secp384r1 : 1556 sign/s 14 | ECDSA-secp256r1 : 2121 sign/s 15 | ECDSA-secp224r1 : 3103 sign/s 16 | ECDSA-secp192r1 : 4107 sign/s 17 | ECDSA-secp521r1 : 299 verify/s 18 | ECDSA-secp384r1 : 431 verify/s 19 | ECDSA-secp256r1 : 612 verify/s 20 | ECDSA-secp224r1 : 935 verify/s 21 | ECDSA-secp192r1 : 1316 verify/s 22 | ``` 23 | 24 | ### Brainpool Curve Performance 25 | ``` 26 | ECDSA-brainpoolP512r1 : 163 sign/s 27 | ECDSA-brainpoolP384r1 : 361 sign/s 28 | ECDSA-brainpoolP256r1 : 603 sign/s 29 | ECDSA-brainpoolP512r1 : 37 verify/s 30 | ECDSA-brainpoolP384r1 : 81 verify/s 31 | ECDSA-brainpoolP256r1 : 156 verify/s 32 | ``` 33 | 34 | ## ECDHE Performance 35 | 36 | ### NIST Curve Performance 37 | ``` 38 | ECDHE-secp521r1 : 323 handshake/s 39 | ECDHE-secp384r1 : 466 handshake/s 40 | ECDHE-secp256r1 : 657 handshake/s 41 | ECDHE-secp224r1 : 1017 handshake/s 42 | ECDHE-secp192r1 : 1404 handshake/s 43 | ``` 44 | 45 | ### Brainpool Curve Performance 46 | ``` 47 | ECDHE-brainpoolP512r1 : 37 handshake/s 48 | ECDHE-brainpoolP384r1 : 83 handshake/s 49 | ECDHE-brainpoolP256r1 : 158 handshake/s 50 | ``` 51 | 52 | ## Why are NIST curves faster than Brainpool curves 53 | Brainpool curves use random primes, as opposed to the quasi-Mersenne primes that NIST curves use. As a result, fast reduction is not possible for Brainpool curves, and this has major consequences for the performance of the different curves. 54 | 55 | ## Can you optimize Brainpool curves to be as fast as the NIST curves? 56 | Unfortunately, this is not possible. The design decision for Brainpool to use random primes was aimed at: 57 | 58 | * avoiding possible patent issues with fast reduction algorithms 59 | * avoiding potential security issues with non-random primes 60 | 61 | Brainpool curve performance cannot be adjusted to be equivalent to NIST curve performance. 62 | 63 | ## Curve25519 support 64 | Bernstein & al have designed high-performance alternatives, such as **Curve25519** for key exchange and **Ed25519** for signatures. Unfortunately, they use slightly different data structures and representations than the other curves, so they haven't been ported yet to TLS and PKIX in Mbed TLS. We do support basic Curve25519 arithmetic though. Their use in TLS has been standardized in [RFC 8422](https://tools.ietf.org/html/rfc8422). 65 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2015-01.md: -------------------------------------------------------------------------------- 1 | # mbed TLS Security Advisory 2015-01 2 | 3 | **Title** | Remote attack on clients using session tickets or SNI 4 | ---|--- 5 | **CVE** | CVE-2015-5291 6 | **Date** | 5th of October 2015 ( **Updated on 8th of October 2015** ) 7 | **Affects** | PolarSSL 1.0 and up 8 | **Not affected** | PolarSSL 1.2.17 and up, mbed TLS 1.3.14 and up, mbed TLS
2.1.2 and up and any version with clients not using session tickets nor
accepting hostnames from untrusted parties 9 | **Impact** | Denial of service and possible remote code execution 10 | **Severity** | High 11 | **Exploit** | Withheld 12 | 13 | PolarSSL versions starting with 1.0 and up to the PolarSSL 1.2.16, mbed TLS 14 | 1.3.13 and mbed TLS 2.1.1 releases are affected by a remote attack in their 15 | default configuration in some use cases. 16 | 17 | This vulnerability was discovered by [Guido Vranken of 18 | Intelworks](https://guidovranken.wordpress.com/2015/10/07/cve-2015-5291/). 19 | 20 | This Security Advisory describes the vulnerability, impact and fix for the 21 | attack. 22 | 23 | ## Vulnerability 24 | 25 | When the client creates its ClientHello message, due to insufficient bounds 26 | checking it can overflow the heap-based buffer containing the message while 27 | writing some extensions. Two extensions in particular could be used by a 28 | remote attacker to trigger the overflow: the session ticket extension and the 29 | server name indication (SNI) extension. 30 | 31 | Starting with PolarSSL 1.3.0 which added support for session tickets, any 32 | server the client connects to can send an overlong session ticket which will 33 | cause a buffer overflow if and when the client attempts to resume the 34 | connection with the server. Clients that disabled session tickets or never 35 | attempt to reconnect to a server using a saved session are not vulnerable to 36 | this attack vector. 37 | 38 | Starting with PolarSSL 1.0.0, this overflow could also be triggered by an 39 | attacker convincing a client to use an overlong hostname for the SNI 40 | extension. The hostname needs to be almost as long at `SSL_MAX_CONTENT_LEN`, 41 | which as 16KB by default, but could be smaller if a custom configuration is 42 | used. Clients that do not accept hostnames from unstrusted parties are not 43 | vulnerable to this attack vector. 44 | 45 | ## Impact 46 | 47 | Depending on the implementation of the memory allocator, this could result in 48 | a Denial of Service (client crash) or a possible Remote Code Execution. 49 | 50 | Servers are not affected in any version. 51 | 52 | ## Resolution 53 | 54 | Upgrade to PolarSSL 1.2.17, mbed TLS 1.3.14 or mbed TLS 2.1.2. If you can't, 55 | use the workaround below. 56 | 57 | ## Workaround 58 | 59 | To be protected against this vulnerability, you need to apply _both_ of the 60 | following work-arounds. 61 | 62 | * Do not use ticket-based session resumption. This can be achieved in two ways: (1) do not attempt to resume a saved session (do not use `mbedtls_get_session()` / `mbedtls_set_session()`), or (2) if you want to resume sessions, make sure you're not using tickets by calling `ssl_set_session_tickets( SSL_SESSION_TICKETS_DISABLED )` in 1.3.x or `mbedtls_ssl_conf_session_tickets( MBEDTLS_SSL_SESSION_TICKETS_DISABLED )` in 2.x 63 | 64 | * If you accept hostnames from unstrusted parties, validate that they are at most 255 bytes long (limit defined by RFC 1305) before passing them to `ssl_set_hostname()`. 65 | -------------------------------------------------------------------------------- /kb/cryptography/rsa-key-pair-generator.md: -------------------------------------------------------------------------------- 1 | # RSA key pair generator 2 | 3 | To use RSA with Mbed TLS or any other application, you will most likely need an RSA key pair. An RSA key pair is often stored in [either a PEM file or a DER file](asn1-key-structures-in-der-and-pem.md). 4 | 5 | ## Building the RSA key pair generator 6 | 7 | Mbed TLS ships with the source code for an RSA key pair generator application, called **gen_key**. To build the executable for the application, please check out the [building Mbed TLS](../compiling-and-building/how-do-i-build-compile-mbedtls.md). 8 | 9 | After the compilation, the executable is often located in `programs/pkey/gen_key`. 10 | 11 | The **gen_key** application has the following arguments and options: 12 | 13 | usage: gen_key param=<>... 14 | 15 | acceptable parameters: 16 | type=rsa|ec default: rsa 17 | rsa_keysize=%d default: 4096 18 | ec_curve=%s see below 19 | filename=%s default: keyfile.key 20 | format=pem|der default: pem 21 | use_dev_random=0|1 default: 0 22 | 23 | available ec_curve values: 24 | secp521r1 (default) 25 | brainpoolP512r1 26 | secp384r1 27 | brainpoolP384r1 28 | secp256r1 29 | secp256k1 30 | brainpoolP256r1 31 | secp224r1 32 | secp224k1 33 | secp192r1 34 | secp192k1 35 | 36 | ## Generating an RSA key pair 37 | 38 | To actually generate an RSA key pair, you have to decide which size your RSA key should be. Depending on your need for security, we advise you to use at least **2048** bits, and use **4096** bits or higher if you have very high security requirements. 39 | 40 | To use the RSA key pair generator to generate a 4096 bits RSA key and save that key in PEM format in private.key, use: 41 | 42 | ./gen_key type=rsa rsa_keysize=4096 filename=private.key format=pem 43 | 44 | The larger the requested keysize, the longer it will take to generate the key itself. You also need to take into account the performance of the system. 45 | 46 | The key generator also outputs the key in **human readable** format in addition to writing the key to the requested keyfile in the requested format. 47 | 48 | The output for a 1024-bit RSA key looks something like this: 49 | 50 | . Seeding the random number generator... 51 | . Generating the private key ... ok 52 | . Key information: 53 | N: 8C3A0BE5B196E6CAAEB18B53C654B59FD1F4D1B62CA3C17B4BD094582A4D94BBA9FB3A93E61B4ED0108021A6DFDB2FE89E855030310A7653DC595259501ADC48C4E8C87D78DE750FC44A3069B4F71107C50CDF2E0BD26229297C31D2CBD9C31009736D0D6503ED16D148AF3894770E084BCF56FD6290E1FF28632CB9620B105 54 | E: 010001 55 | D: 1F3728C0D818AC85BFFFBBF1493C403634A9D82942A4AD8481EB0BAAD8B7EE7D1C28D5F0688FF9AA6D91E86BDA7753A1E7EFEB5ADEFFE23966DAE76F045B0660407392B3C07DB8F1200EF70D9CA46DFD3631F455C97F087B8F678DB890AC601FD812C7A435D6826811474BDFACAB2D6AEC9C95809D28AC85DA067B9DA5E005C1 56 | P: FF96AC7E4E47FC4F153C6C5D3FE7EFC01ECDBBFC6AC861089C675191987281E18E33A731BE939B80C566199E98FDDC9F764AA5283E43FFBA260650B6E9C650D5 57 | Q: 8C73D538DBEA066F00161DCFB69921374ABBD20A96C2693E5072A0890728FE79E881EC532C8918C486C6061987EAED3350F5C6F79E30721C55E3ED72FFF47771 58 | DP: B93FEF6458BECA3C53AB08EC099EC5621DB186786CB931C3790155D8CE82E86AA09405B2036C9F4015536C6C4C7D6BC4548BC3EB483E270337FE49D059DEB8C5 59 | DQ: 61360AEE3FC7CA8C2953256F0EC30DEA671F78513BE773505DFDF87EDF25D07C30213CA094C28F11F6F63862936056AC9DEC7EBA041323E7D8CAD91E2F69D501 60 | QP: A945E282018B46EFFA11030152A42AD977FAAD439D6C482134A8BC5716F082808904C2001F9D5BBF8B1A6CF98C30FD66BA00EA86F8790552F160929CF10BF8F6 61 | -------------------------------------------------------------------------------- /kb/compiling-and-building/how-do-i-configure-mbedtls.md: -------------------------------------------------------------------------------- 1 | # How to configure Mbed TLS 2 | 3 | Mbed TLS should build out-of-the box on a large variety of platforms. However, you may need to adjust a few platform-specific settings or want to customize the set of features that will be built. You can do all of this in a single configuration file. 4 | 5 | ## The configuration file 6 | 7 | The default configuration file is located in `include/mbedtls/mbedtls_config.h` (`include/mbedtls/config.h` up to Mbed TLS 2.28). It is [fully documented](/api/config_8h.html) and contains the following sections: 8 | 9 | * Select options depending on your platform in **System support**: does your compiler support inline assembly, does your libc/network stack provide IPv6, and so on. 10 | * Select which features you want to enable for corresponding modules in **Mbed TLS feature support**: which TLS version to support, which key exchanges, which specific elliptic curves, and so on. 11 | * Select modules to build in **Mbed TLS modules**. You can, for example, completely disable RSA or MD5 if you don't need them. 12 | * Set specific options for each module, such as the maximum size of multi-precision integers, or the size of the internal I/O buffers for SSL, in **Module configuration options**. All of these options have default values. 13 | 14 | ## The configuration script 15 | 16 | You can edit the configuration file manually with a text editor of your choice. In some cases, however, it may be useful to set options in a more programmatic way. We provide a Python script `scripts/config.py` for doing so: 17 | ``` 18 | scripts/config.py unset 19 | scripts/config.py set [] 20 | ``` 21 | The `config.py` script automatically finds the `mbedtls_config.h` file when it runs this way from Mbed TLS' root directory. If you want to run it from another directory or on another configuration file (see below), you need to use the `-f` option. 22 | 23 | ## Alternative configuration files 24 | 25 | You might want to keep the custom configuration file for your application outside the Mbed TLS source tree. You can do this by defining the macro `MBEDTLS_CONFIG_FILE` for the desired filename (including the quote or angular brackets) at compile time. For example, using **make**: (Note: The angle brackets `<>` are included in the command, but they could be replaced with properly escaped double quotes `\"\"`.) 26 | ``` 27 | CFLAGS="-Ipath/to/config -DMBEDTLS_CONFIG_FILE=''" make 28 | ``` 29 | or, using **Cmake**: 30 | 31 | * If it is not the first run, **clear its cache** before running: 32 | ``` 33 | find . -iname '*cmake*' -not -name CMakeLists.txt -exec rm -rf {} + 34 | CFLAGS="-Ipath/to/config -DMBEDTLS_CONFIG_FILE=''" cmake . 35 | make 36 | ``` 37 | **Mbed TLS 2.2x only:** We provide a `check_config.h` file that checks the consistency of the configuration file. We highly recommended to `include` it at the end of your custom configuration file. If you use the above setup, you may need to adapt the `include` directive depending on your compiler. (Since Mbed TLS 3.0, `check_config.h` is included automatically.) 38 | 39 | ## Example configurations 40 | 41 | We provide example configurations in the `configs` directory. These are often minimal configurations for a specific goal, such as supporting the `NSA suite B TLS` profile. They also often include settings to [reduce resource usage](../how-to/reduce-polarssl-memory-and-storage-footprint.md). 42 | 43 | 44 | -------------------------------------------------------------------------------- /project/roadmap.md: -------------------------------------------------------------------------------- 1 | # Roadmap 2 | 3 | **Note that the quarter when a feature is expected to be completed is based on very rough estimates of the effort involved and therefore can change. Items to be delivered beyond the current quarter may be pushed back, or change in scope.** 4 | 5 | If you are interested in collaborating on any of the roadmap features or other features in the project, please mail [Mbed TLS](https://lists.trustedfirmware.org/mailman/listinfo/mbed-tls) or [PSA Crypto](https://lists.trustedfirmware.org/mailman/listinfo/psa-crypto) mailing lists. 6 | 7 | **2025 CQ4 (In Development)** 8 | * TF-PSA-Crypto CI Optimization 9 | * TF-PSA-Crypto 1.0 Follow up, Fixes 10 | * ML-DSA Investigation 11 | 12 | **2026 CQ1** 13 | * Mbed TLS 4.1, TF-PSA-Crypto 1.1 LTS release 14 | * Mbed TLS 4.x API Consolidation Investigation 15 | * ML-DSA Prototype 16 | * SPAKE2+ Implementation 17 | 18 | **2026 CQ2** 19 | * Memory Optimizations (code size) 20 | * ML-DSA - Initial support 21 | * Mbed TLS 4.x API Consolidation 22 | * PSA driver - Handle Opaque Persistent Key in Secure Element - Implementation 23 | 24 | **Future** 25 | * ML-KEM Support 26 | * Memory Optimizations (code size) 27 | * MbedTLS, TF-PSA-Crypto - Next LTS release 28 | * Bignum Improvements 29 | * PSA Client-Server Testing 30 | * PSA Crypto restartable sign enhancements 31 | * Multi-threading perf. improvements, testing 32 | * PSA Crypto 1.2 compliance 33 | * PSA Secure Element, Crypto Accelerator Support Enhancements 34 | * Raw Public Key Mode 35 | * EdDSA 36 | * Performance Optimization - ECP and Bignum 37 | 38 | **Completed** 39 | * [PSA Crypto] SHA3 40 | * [PSA Crypto] PSA Crypto 1.1 compliance 41 | * [Mbed TLS] Mbed TLS 4.0, TF-PSA-Crypto 1.0 release 42 | * [Mbed TLS4.0] Remove TLS cipher suites 43 | * [PSA Crypto] TF-PSACrypto repository becomes live 44 | * [Mbed TLS] Mbed TLS uses PSA Crypto repository 45 | * [Mbed TLS] [Mbed TLS 3.6.1, 3.6.2, 3.6.3] 46 | * [PSA Crypto] [PBKDF2 PSA SW Implementation] 47 | * [Mbed TLS] [3.6 LTS release] 48 | * [Mbed TLS] [TLS1.3 early data] 49 | * [Mbed TLS] [TLS1.3 misc] 50 | * [PSA Crypto] [PSA Crypto Thread safe] 51 | * [Mbed TLS] [Code size optimisation (driver only build - Cipher and AEAD)] 52 | * [Mbed TLS] [Code size optimisation (driver only build - ECC)] 53 | * [PSA Crypto] [Memory Optimizations (code size)] 54 | * [Mbed TLS] [Mbed TLS 3.5 Release] 55 | * [PSA Crypto] [Publish PSA Crypto prototype repository] 56 | * [Mbed TLS] [Code size optimisation (driver only build - hashes inc. HMAC)] 57 | * [Mbed TLS] [PKCS7 Parser] 58 | * [PSA Crypto] [PSA Crypto restartable sign message] 59 | * [PSA Crypto] [ECJ-PAKE PSA Implementation] 60 | * [Mbed TLS] [Connection ID DTLS 1.2] 61 | * [Mbed TLS] [Use PSA: code size optimisation via PSA_CRYPTO_CONFIG - part1: symmetric] 62 | * [Mbed TLS] [TLS/X.509 - Use PSA Long term secret isolation] 63 | * [Mbed TLS] [TLS1.3 PSK] 64 | * [Mbed TLS] [Mbed TLS3.2] 65 | * [Mbed TLS] [TLS1.3 server side] 66 | * [Mbed TLS] [TLS1.3 MVP] 67 | * [Mbed TLS] [TLS/X.509 - Use PSA Crypto APIs Fully - Phase1] 68 | * [Mbed TLS] [SHA256/512 - Neon Optimization] 69 | * [Mbed TLS] [New 2.x LTS] 70 | * [PSA Crypto] [Support Missing PSA Crypto v1.0 APIs supported in MbedCrypto] 71 | * [PSA Crypto] M-AEAD Implementation 72 | * [PSA Crypto] EdDSA API Design 73 | * [PSA Crypto] PBKDF2 API Design 74 | * [PSA Crypto] ECJPAKE API Design 75 | * DTLS-SRTP 76 | * Lucky13 Security Improvements 77 | * [PSA Crypto] [PSA Crypto API implementation v1.0 Specification - Phase1] 78 | * [Unified PSA Driver Interface]- API Design and initial support 79 | * [PSA Crypto] PSA driver - Handle Opaque Persistent Key in Secure Element - [Design] 80 | * [Mbed TLS] [Use PSA: misc. gaps] 81 | * [Bignum] [ECP Curves field reduction - NIST] 82 | 83 | -------------------------------------------------------------------------------- /kb/how-to/add-entropy-sources-to-entropy-pool.md: -------------------------------------------------------------------------------- 1 | # Why to add an entropy source 2 | 3 | Good entropy is the fundamental basis for good cryptography and SSL or TLS. If your entropy is weak or predictable, a strong adversary can break your security. 4 | 5 | Therefore, you want to have at least one, but preferably multiple sources of good or reasonable entropy. 6 | 7 | For that purpose, Arm Mbed TLS provides the [entropy collector](/entropy-source-code). The entropy collector takes entropy from multiple sources and combines it into a single entropy source for use. 8 | 9 | ## Default entropy sources 10 | 11 | In the default Mbed TLS, the entropy collector tries to use what the platform you run can provide. For Linux and UNIX-like systems, this is **/dev/urandom**. For Windows, this is `CryptGenRandom` of the **CryptoAPI**. These are considered strong entropy sources. 12 | 13 | If you have **MBEDTLS_TIMING_C** enabled, the entropy collector also adds the `mbedtls_timing_hardclock()` value. This is only a little entropy, but every bit helps. 14 | 15 | If you have **MBEDTLS_HAVEGE_C** enabled, Mbed TLS also uses the HAVEGE RNG. 16 | 17 | **Note:** The HAVEGE random generator is considered reasonable but not good. Please do not base your full entropy on this. 18 | 19 | ## Adding own sources 20 | 21 | When you run Mbed TLS on a different platform, such as an embedded platform, you have to add platform-specific or application-specific entropy sources. 22 | 23 | To add a source to the entropy collector, you can use `mbedtls_entropy_add_source()`. It requires you to provide a callback (`f_source`) that you can call whenever the entropy pool tries to gather entropy, the data (`p_source`) that you need with your callback and a `threshold`. This threshold indicates the minimum number of bytes the entropy pool should wait on from this callback before releasing entropy. Choose this value wisely. Choosing a value that is higher than your callback can provide will block entropy collection. 24 | 25 | Starting with the 2.0 branch, you also need to indicate if this source is strong or not. For example, **/dev/urandom** and `CryptGenRandom()` are strong. Hardware RNG is a strong source if your platform has it, but the `mbedtls_timing_hardclock()` value and HAVEGE are weak. The entropy module refuses to deliver entropy unless it has at least one strong source. 26 | 27 | ## Entropy source failed 28 | 29 | When collecting entropy for a request, the entropy pool does a maximum of 256 polls to each entropy source to retrieve entropy from them. If the **threshold** value for a source is higher than the entropy it can deliver in those 256 polls, you **will** receive an error! 30 | 31 | ## Limited sources 32 | 33 | If you have an entropy source that only provides some limited entropy, but not on every poll, it can be wise to select a *threshold* value of **0**. A zero-threshold does not cause the entropy pool to return an error if it cannot provide any entropy in 256 calls. 34 | 35 | ## Seed files 36 | 37 | In addition to platform specific sources, such as timing of network packets, keyboard input and so on, you can also use a seed file to produce entropy for your system. The advantage of a seed file is that you can generate it on a high-entropy system and then update and use it on your low-entropy system. 38 | 39 | **Note:** You must make sure the seed file is unique for each device. 40 | 41 | 43 | -------------------------------------------------------------------------------- /reviews/review-priorities.md: -------------------------------------------------------------------------------- 1 | # PR Prioritisation 2 | 3 | The Mbed TLS core team prioritise PRs to help us spend our review capacity on the items that best help the project. 4 | 5 | When PRs are first triaged, a label is applied to help reviewers determine what to work on (and what not to work on). The different classifications are described below. 6 | 7 | Please note that if your PR falls into the lower priority categories, we are happy to increase its priority if needed. This might happen through: 8 | 9 | - Commenting on the PR to explain why there is an important use-case for it 10 | - Other users commenting to show wider demand for the PR 11 | - Attending the regular Tech Forum call to discuss the PR 12 | - Advocating for the PR on the project mailing list 13 | - Find others to review your PR 14 | 15 | Classifications are done through labels, e.g.: priority-high. 16 | 17 | Please note that these are the priorities used by the core team. External contributors are welcome to review PRs according to their own priorities, and such review activity will help highlight PRs which should get attention from the core team. 18 | 19 | ## priority-very-high 20 | 21 | Same criteria as priority-high, below, but needed for the Mbed TLS team's most important commitments. 22 | 23 | This classification is often used for vulnerability fixes with a public disclosure date. 24 | 25 | 26 | ## priority-high 27 | 28 | This classification is used for PRs which have a target date for merging - typically one of: 29 | 30 | - Security (or other high-priority) bug fixes needed in the next release 31 | - Items that the Mbed TLS team have planned for delivery in the current quarter 32 | 33 | These PRs should receive review promptly. 34 | 35 | 36 | ## priority-medium 37 | 38 | This is for PRs which advance the core team's aims for Mbed TLS, but are not needed to meet delivery in the current quarter. These PRs will receive review on a best-effort basis, but assistance from the community would be helpful. 39 | 40 | These would typically address one of the following areas: 41 | 42 | * Security 43 | * Non-urgent and lower-priority security improvements 44 | * Robustness 45 | * Non-urgent bug fixes 46 | * Test improvements 47 | * Documentation 48 | * PSA Crypto 49 | * Provide a reference implementation for PSA Crypto 50 | * Driver interface for secure elements & crypto processors 51 | * TLS 52 | * Support latest TLS versions and features - especially client features important for embedded devices 53 | * DTLS, QUIC 54 | * Embedded applications 55 | * Improvements to code-size, memory footprint and performance on embedded devices 56 | 57 | 58 | ## priority-low 59 | 60 | This is for PRs which are potentially useful or nice to have, but are unlikely to receive review soon. This might include PRs in the following areas: 61 | 62 | * New ciphers for which there is low demand 63 | * Minor performance enhancements 64 | * Enhancements that don't suit embedded applications 65 | * Code (especially assembly) for platforms where the team has little experience for review or maintenance, or limited ability to test 66 | * Note: we currently have the capability to maintain & test aarch32, aarch64, x86 and x86-64 on Ubuntu, FreeBSD and Windows 67 | * Minor quality/test improvements, e.g. clean-up of test infrastructure or build scripts 68 | * Items where the team might not be able to afford the maintenance cost 69 | 70 | After at least one year, some items in this category may be closed if a clear need does not emerge with time. This is more likely to happen for larger and more complex PRs. 71 | 72 | 73 | ## priority-scheduled 74 | 75 | This is an additional label used for larger PRs (typically priority-medium) which require significant team bandwidth to review. These items will not be reviewed immediately, but they will be scheduled in the project roadmap with time allocated for review. 76 | -------------------------------------------------------------------------------- /getting_started/building.md: -------------------------------------------------------------------------------- 1 | # Building 2 | 3 | Mbed TLS supports a number of different build environments out-of-the-box. However, the code and dependencies let you build with any environment. 4 | 5 | ## Prerequisites 6 | 7 | * GNU Make, CMake or Visual Studio. 8 | * A C toolchain (compiler, linker, archiver) that supports C99. 9 | * Python 3.6 or later to generate the test code. 10 | * Perl to run the tests. 11 | 12 | ## Building with Make 13 | 14 | If using Make, you can build by running: 15 | ```sh 16 | make 17 | ``` 18 | To run the test suite, run: 19 | ```sh 20 | make check 21 | ``` 22 | 23 | To select a different compiler, set the `CC` variable to the name or path of the 24 | compiler and linker (default: `cc`) and set `AR` to a compatible archiver 25 | (default: `ar`); for example: 26 | ```sh 27 | make CC=arm-linux-gnueabi-gcc AR=arm-linux-gnueabi-ar 28 | ``` 29 | The provided makefiles pass options to the compiler that assume a GCC-like 30 | command line syntax. To use a different compiler, you may need to pass different 31 | values for `CFLAGS`, `WARNINGS_CFLAGS` and `LDFLAGS`. 32 | 33 | 34 | ## Building with CMake 35 | 36 | If you have CMake, the build process is better able to handle all the dependencies and do minimal builds. To build the source using CMake, run: 37 | ```sh 38 | cmake . 39 | make 40 | ``` 41 | In order to run the tests, enter: 42 | ```sh 43 | make test 44 | ``` 45 | The test suites need Perl to be built. If you don't have Perl installed, you'll want to disable the test suites with: 46 | ```sh 47 | cmake -DENABLE_TESTING=Off . 48 | ``` 49 | If you disabled the test suites, but kept the programs enabled, you can still run a much smaller set of tests with: 50 | ```sh 51 | programs/test/selftest 52 | ``` 53 | To configure CMake for building a shared library, use: 54 | ```sh 55 | cmake -DUSE_SHARED_MBEDTLS_LIBRARY=On . 56 | ``` 57 | 58 | ### Switching build modes in CMake 59 | 60 | CMake supports different build modes, to allow the stripping of debug information, or to add coverage information to the binaries. 61 | 62 | The following modes are supported: 63 | 64 | * **Release:** This generates the default code without any unnecessary information in the binary files. 65 | * **Debug:** This generates debug information and disables optimization of the code. 66 | * **Coverage:** This generates code coverage information in addition to debug information. 67 | * **ASan:** This instruments the code with **AddressSanitizer** to check for memory errors. This includes **LeakSanitizer**, with recent versions of **gcc** and **clang**. With the most recent version of **clang**, this mode also uses **UndefinedSanitizer** to check for undefined behavior. 68 | * **ASanDbg:** Same as **ASan** but slower, with debug information and better stack traces. 69 | * **MemSan:** Uses **MemorySanitizer** to check for uninitialized memory reads. This is experimental, and needs the most recent **clang** on Linux/x86_64. 70 | * **MemSanDbg:** Same as **MSan** but slower, with debug information, better stack traces and origin tracking. 71 | * **Check:** This activates the compiler warnings that depend on optimization and treats all warnings as errors. 72 | 73 | For debug mode, enter at the command line: 74 | ```sh 75 | cmake -D CMAKE_BUILD_TYPE=Debug . 76 | ``` 77 | To list other available CMake options, use: 78 | ```sh 79 | cmake -LH 80 | ``` 81 | Note that with CMake, if you want to change the compiler or its options after you already ran CMake, you need to clear its cache first: 82 | ```sh 83 | find . -iname '*cmake*' -not -name CMakeLists.txt -exec rm -rf {} + 84 | CC=gcc CFLAGS='-fstack-protector-strong' cmake . 85 | ``` 86 | 87 | ## Windows Visual Studio 2013 and later 88 | 89 | Inside Visual C++: open `visualc/VS2013/mbedTLS.sln` and select **Rebuild all**. 90 | 91 | If you are using a later version of Visual Studio, it should prompt you to upgrade the files on first use. Accept this, and you are ready to build and compile. 92 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2025-03-1.md: -------------------------------------------------------------------------------- 1 | # TLS clients may unwittingly skip server authentication 2 | 3 | **Title** | TLS clients may unwittingly skip server authentication 4 | --------- | ---------------------------------------------------------- 5 | **CVE** | CVE-2025-27809 6 | **Date** | 24 March 2025 7 | **Affects** | All versions of PolarSSL and Mbed TLS 8 | **Severity** | HIGH 9 | **Credit** | Daniel Stenberg 10 | 11 | ## Vulnerability 12 | 13 | The security of the TLS protocol relies on clients authenticating the server. 14 | If a TLS client fails to authenticate the server, a network-based attacker can act as a man-in-the-middle and impersonate the server to the client. 15 | 16 | Server authentication relies on one of two mechanisms, depending on the key exchange mode: either a pre-shared key or a certificate chain. The vulnerability considered here affects certificate-based authentication. 17 | 18 | Certificate-based authentication has three steps, all of which are necessary: 19 | 20 | * The end certificate must be issued for the server that the client is trying to reach. Mbed TLS checks that the certificate content matches the name passed to `mbedtls_ssl_set_hostname()`. 21 | * The certificate chain must be valid. Mbed TLS always checks this. 22 | * The root of the certificate chain must be a trusted certificate authority (trusted CA). Certificate authentication will fail if no trusted CAs are defined. 23 | 24 | Due to an insecure default in Mbed TLS up to 2.8.9 and Mbed TLS 3.x up to 3.6.2, if a TLS client application does not call `mbedtls_ssl_set_hostname()`, the first step is silently skipped. This allows any server with a certificate signed by a trusted CA to impersonate any other server. 25 | 26 | ## Impact 27 | 28 | TLS client applications that do not call `mbedtls_ssl_set_hostname()` are likely to be vulnerable to impersonation by a network-based attacker. This gives the attacker access to all the data exchanged over TLS, and the ability to modify this data. 29 | 30 | ## Affected versions 31 | 32 | All versions of PolarSSL, all versions of Mbed TLS up to 2.28.9, and all versions of Mbed TLS 3.x up to 3.6.2 are affected. 33 | 34 | ## Resolution 35 | 36 | Developers of TLS client applications should ensure that their application calls `mbedtls_ssl_set_hostname()` with the expected server name, unless they only allow cipher suites (key exchange modes in TLS 1.3) based on a pre-shared key. 37 | 38 | Please note that TLS client applications typically need to mention the server name twice: once to the network stack (e.g. to `mbedtls_net_connect()`) to set up the underlying transport, and once to the TLS stack (to `mbedtls_ssl_set_hostname()`) to arrange for server authentication. 39 | 40 | We recommend that users should upgrade to Mbed TLS 2.28.10 or Mbed TLS 3.6.3. These versions disable the insecure default, and instead cause certificate authentication to fail if `mbedtls_ssl_set_hostname()` has not been called. 41 | 42 | See also [our FAQ](../kb/attacks/ssl_set_hostname/) on this vulnerability. 43 | 44 | ## Work-around 45 | 46 | TLS client applications should call `mbedtls_ssl_set_hostname()` with the expected server name, unless they only allow cipher suites (key exchange modes in TLS 1.3) based on a pre-shared key. 47 | 48 | TLS clients are not affected if they operate in a closed ecosystem where the trusted certificate authority only issues certificates to trusted hosts. We still recommend calling `mbedtls_ssl_set_hostname()` as a second line of defense in case a part of the public-key infrastructure is compromised. 49 | 50 | TLS clients are not affected if, before exchanging any data on the TLS connection, they check that the fingerprint of the server certificate matches a known good fingerprint (certificate pinning). 51 | 52 | TLS clients that only allow connections using pre-shared keys are not affected. 53 | 54 | See also [our FAQ](../kb/attacks/ssl_set_hostname/) on this vulnerability. 55 | -------------------------------------------------------------------------------- /kb/development/deprecation.md: -------------------------------------------------------------------------------- 1 | # Deprecations 2 | 3 | To ensure backwards-compatibility between versions of Mbed TLS, elements of the public interface may not be removed except during the release of a new major version. Instead, they may be 'deprecated', indicating to users that they will be removed in the future. 4 | 5 | When a build is made with `MBEDTLS_DEPRECATED_WARNING` defined, a compiler warning will be generated to warn a user that a function or constant will be removed at some point in the future, notifying users that they should change to a replacement function or constant at their own convenience. Note: this only works when using GCC-like compilers that recognize `__attribute__((deprecated))`. 6 | 7 | To find examples of past deprecations, look at the previous major version of Mbed TLS. 8 | 9 | ## Deprecating functions 10 | 11 | To deprecate a function, the following actions must be taken: 12 | * In the header file (e.g. `include/mbedtls/xyz.h`): 13 | * Surround the function declaration with `#if !defined(MBEDTLS_DEPRECATED_REMOVED)`. 14 | * Add a line to the docstring consisting of the keyword `\deprecated` followed by the reason for deprecation and (where applicable) the function it is superseded by. 15 | * Add the `MBEDTLS_DEPRECATED` annotation to the function prototype (so `int foo();` becomes `int MBEDTLS_DEPRECATED foo();`). 16 | * Make sure the header file includes `mbedtls/platform_util.h` (this contains the definition of `MBEDTLS_DEPRECATED`). 17 | * In the source file (e.g. `library/xyz.c`): 18 | * Surround the function definition with `#if !defined(MBEDTLS_DEPRECATED_REMOVED)`. 19 | * If the function is superseded, ensure there is no code duplication between the old function and the new one. Typically this means refactoring the old function to be a simple wrapper around the new function. 20 | * In a new file in ChangeLog.d (e.g. `ChangeLog.d/change-xyz-api.txt`) 21 | * Add an entry under the heading `New deprecations` that describes the deprecation. See [the ChangeLog readme](https://github.com/Mbed-TLS/mbedtls/blob/development/ChangeLog.d/00README.md) for more information on the format of ChangeLog entries. 22 | * In the function's unit tests (see [the test guidelines](test_suites.md) for more information on unit tests): 23 | * Add `MBEDTLS_TEST_DEPRECATED` to the `depends_on:` line in the `.function` file that tests the deprecated function. 24 | * If there are test functions that can test either the deprecated function or the replacement, they may use the directive `#if defined(MBEDTLS_TEST_DEPRECATED)` to select the function to use. 25 | 26 | ## Deprecating constants 27 | 28 | Numeric and string constants can also be deprecated by wrapping them in the macros `MBEDTLS_DEPRECATED_NUMERIC_CONSTANT()` and `MBEDTLS_DEPRECATED_STRING_CONSTANT()` respectively. For example, the code: 29 | ```c 30 | const int X = 42; 31 | ``` 32 | would become: 33 | ```c 34 | const int X = MBEDTLS_DEPRECATED_NUMERIC_CONSTANT(42); 35 | ``` 36 | The file where the constant is defined must include `mbedtls/platform_util.h` as it contains the definition of `MBEDTLS_DEPRECATED_NUMERIC_CONSTANT`. 37 | 38 | Any testcases (in `.data` files) that use the deprecated constant must have `MBEDTLS_TEST_DEPRECATED` added to their `depends_on:` line. 39 | 40 | ## Partial deprecation 41 | 42 | From time to time it is necessary to deprecate one specific aspect of a function. For example, calling a function in a particular mode or with a particular parameter may be deprecated. In this case, simply add a line to the function's doxygen description explaining the deprecation. For example: 43 | ```c 44 | /** 45 | * \brief This function divides x by y 46 | * 47 | * \deprecated It is deprecated to call this function with y = 0. 48 | * Future versions of this function will return an error 49 | * when called with y = 0, rather than returning INT_MAX as 50 | * is the current behaviour. 51 | * 52 | * ... 53 | */ 54 | ``` 55 | -------------------------------------------------------------------------------- /security-advisories/mbedtls-security-advisory-2025-06-6.md: -------------------------------------------------------------------------------- 1 | # NULL pointer dereference after using `mbedtls_asn1_store_named_data()` 2 | 3 | **Title** | NULL pointer dereference after using `mbedtls_asn1_store_named_data()` 4 | --------- | ---------------------------------------------------------- 5 | **CVE** | CVE-2025-48965 6 | **Date** | 30 June 2025 7 | **Affects** | all versions of Mbed TLS up to 3.6.3 8 | **Not affected** | Mbed TLS 3.6.4 and later 3.6 versions, upcoming Mbed TLS 4.x versions 9 | **Impact** | NULL pointer dereference (CWE-476) 10 | **Severity** | MEDIUM 11 | **Credits** | Found by Linh Le and Ngan Nguyen from Calif. 12 | 13 | ## Vulnerability 14 | 15 | In some circumstances (see below), `mbedtls_asn1_store_named_data()` leaves its 16 | output list with an item in an inconsistent state with `val.p == NULL` but 17 | `val.len > 0`. In that case, future uses of the list, either by the same 18 | function or by other functions, are likely to dereference `val.p`, a NULL 19 | pointer. 20 | 21 | There are two ways this can happen: 22 | 23 | 1. By calling `mbedtls_asn1_store_named_data()` directly. 24 | 2. By calling it indirectly via `mbedtls_x509_string_to_names()` or associated 25 | functions (listed below). 26 | 27 | When calling `mbedtls_x509_string_to_names()` directly, the problem happens when 28 | an item with a certain OID has already been entered into the list, then 29 | `mbedtls_asn1_store_named_data()` is called with the same OID and `val_len = 0`. 30 | It then `free()`s `val.p` as documented, but fails to update `val.len`. Calling 31 | `mbedtls_asn1_store_named_data()` again with the same OID (and a length not 32 | greater than the last non-zero length) will cause a NULL pointer dereference. 33 | Using the list in other ways is likely to also cause a NULL dereference. 34 | 35 | The fault in `mbedtls_asn1_store_named_data()` can also be triggered by 36 | malicious input when used indirectly via the following string-parsing functions: 37 | 38 | - `mbedtls_x509_string_to_names()`, 39 | - `mbedtls_x509write_crt_set_subject_name()`, 40 | - `mbedtls_x509write_crt_set_issuer_name()`, 41 | - `mbedtls_x509write_csr_set_subject_name()`. 42 | 43 | With these functions, the incorrect behaviour is triggered by input strings that 44 | contain at least two entries with the same type: one with a non-zero length, and 45 | a subsequent one of length zero. 46 | 47 | This causes the list to contain an item in an inconsistent state; the NULL 48 | dereference itself will happen either in a subsequent call to 49 | `mbedtls_x509_write_names()` using that list, or directly within the same call 50 | to `mbedtls_x509_string_to_names()` (or one of its wrappers as listed above) if 51 | there is another entry with the same type after the one of length zero. 52 | 53 | Specifically, inputs like "DC=foo,DC=#0000" will parse apparently successfully, 54 | but using the output list (or CRT/CSR structure) with other functions will cause 55 | them to dereference a NULL pointer. Inputs like "DC=foo,DC=#0000,DC=bar" will 56 | cause a NULL dereference directly in the string parsing function. 57 | 58 | ## Impact 59 | 60 | NULL pointer dereference, leading to DoS on platforms with memory protection, 61 | and possibly code execution on microcontrollers without an MMU or MPU. 62 | 63 | ## Affected versions 64 | 65 | All versions of Mbed TLS up to Mbed TLS 3.6.3 included are affected. 66 | 67 | The first fixed version is Mbed TLS 3.6.4. 68 | 69 | ## Resolution 70 | 71 | Affected users should upgrade to Mbed TLS 3.6.4 (or TF-PSA-Crypto 1.x / Mbed TLS 72 | 4.x once they are released). 73 | 74 | ## Work-around 75 | 76 | Applications that do not call `mbedtls_asn1_store_named_data()` or any of the 77 | string-parsing functions mentioned above are not affected. Applications that 78 | call these functions only with trusted inputs are not affected. 79 | 80 | Note that these functions are used to create certificates or CSRs; as a result, 81 | applications that only use but do not create certificates or CSRs should not be 82 | affected. 83 | --------------------------------------------------------------------------------