Merge branch 'development' into iotssl-1251-2.7

Conflict resolution:

* ChangeLog: put the new entries in their rightful place.
* library/x509write_crt.c: the change in development was whitespace
  only, so use the one from the iotssl-1251 feature branch.
This commit is contained in:
Gilles Peskine 2018-01-19 11:25:10 +01:00
commit d91f2a26cb
270 changed files with 12457 additions and 2565 deletions

41
.github/issue_template.md vendored Normal file
View file

@ -0,0 +1,41 @@
Note: This is just a template, so feel free to use/remove the unnecessary things
### Description
- Type: Bug | Enhancement\Feature Request | Question
- Priority: Blocker | Major | Minor
---------------------------------------------------------------
## Bug
**OS**
Mbed OS|linux|windows|
**mbed TLS build:**
Version: x.x.x or git commit id
OS version: x.x.x
Configuration: please attach config.h file where possible
Compiler and options (if you used a pre-built binary, please indicate how you obtained it):
Additional environment information:
**Peer device TLS stack and version**
OpenSSL|GnuTls|Chrome|NSS(Firefox)|SecureChannel (IIS/Internet Explorer/Edge)|Other
Version:
**Expected behavior**
**Actual behavior**
**Steps to reproduce**
----------------------------------------------------------------
## Enhancement\Feature Request
**Justification - why does the library need this feature?**
**Suggested enhancement**
-----------------------------------------------------------------
## Question
**Please first check for answers in the [Mbed TLS knowledge Base](https://tls.mbed.org/kb), and preferably file an issue in the [Mbed TLS support forum](https://tls.mbed.org/discussions)**

39
.github/pull_request_template.md vendored Normal file
View file

@ -0,0 +1,39 @@
Notes:
* Pull requests cannot be accepted until:
- The submitter has [accepted the online agreement here with a click through](https://developer.mbed.org/contributor_agreement/)
or for companies or those that do not wish to create an mbed account, a slightly different agreement can be found [here](https://www.mbed.com/en/about-mbed/contributor-license-agreements/)
- The PR follows the [mbed TLS coding standards](https://tls.mbed.org/kb/development/mbedtls-coding-standards)
* This is just a template, so feel free to use/remove the unnecessary things
## Description
A few sentences describing the overall goals of the pull request's commits.
## Status
**READY/IN DEVELOPMENT/HOLD**
## Requires Backporting
When there is a bug fix, it should be backported to all maintained and supported branches.
Changes do not have to be backported if:
- This PR is a new feature\enhancement
- This PR contains changes in the API. If this is true, and there is a need for the fix to be backported, the fix should be handled differently in the legacy branch
Yes | NO
Which branch?
## Migrations
If there is any API change, what's the incentive and logic for it.
YES | NO
## Additional comments
Any additional information that could be of interest
## Todos
- [ ] Tests
- [ ] Documentation
- [ ] Changelog updated
- [ ] Backported
## Steps to test or reproduce
Outline the steps to test or reproduce the PR here.

219
ChangeLog
View file

@ -1,16 +1,56 @@
mbed TLS ChangeLog (Sorted per branch, date) mbed TLS ChangeLog (Sorted per branch, date)
= mbed TLS x.x.x released xxxx-xx-xx = mbed TLS x.x.x branch released xxxx-xx-xx
Bugfix Security
* Fix the entropy.c module to not call mbedtls_sha256_starts() or * Fix a potential heap buffer overflow in mbedtls_ssl_write. When the (by
mbedtls_sha512_starts() in the mbedtls_entropy_init() function. default enabled) maximum fragment length extension is disabled in the
* Fix the entropy.c module to ensure that mbedtls_sha256_init() or config and the application data buffer passed to mbedtls_ssl_write
mbedtls_sha512_init() is called before operating on the relevant context is larger than the internal message buffer (16384 bytes by default), the
structure. Also, ensure that message digest contexts are freed when latter overflows. The exploitability of this issue depends on whether the
calling mbedtls_entropy_free(). application layer can be forced into sending such large packets. The issue
was independently reported by Tim Nordell via e-mail and by Florin Petriuc
and sjorsdewit on GitHub. Fix proposed by Florin Petriuc in #1022. Fixes #707.
Features
* Allow comments in test data files.
* The selftest program can execute a subset of the tests based on command
line arguments.
* New unit tests for timing. Improve the self-test to be more robust
when run on a heavily-loaded machine.
* Add alternative implementation support for CCM and CMAC (MBEDTLS_CCM_ALT,
MBEDTLS_CMAC_ALT). Submitted by Steve Cooreman, Silicon Labs.
* Add support for alternative implementations of GCM, selected by the
configuration flag MBEDTLS_GCM_ALT.
* Add support for alternative implementations for ECDSA, controlled by new
configuration flags MBEDTLS_ECDSA_SIGN_ALT, MBEDTLS_ECDSA_VERIFY_ALT and
MBEDTLS_ECDSDA_GENKEY_AT in config.h.
The following functions from the ECDSA module can be replaced
with alternative implementation:
mbedtls_ecdsa_sign(), mbedtls_ecdsa_verify() and mbedtls_ecdsa_genkey().
* Add support for alternative implementation for ECDH, controlled by new
configuration flags MBEDTLS_ECDH_COMPUTE_SHARED_ALT and
MBEDTLS_ECDH_GEN_PUBLIC_ALT in config.h.
The following functions from the ECDH module can be replaced
with an alternative implementation:
mbedtls_ecdh_gen_public() and mbedtls_ecdh_compute_shared().
New deprecations
* Deprecate usage of RSA primitives with non-matching key-type
(e.g., signing with a public key).
* Direct manipulation of structure fields of RSA contexts is deprecated.
Users are advised to use the extended RSA API instead.
API Changes API Changes
* Extend RSA interface by multiple functions allowing structure-
independent setup and export of RSA contexts. Most notably,
mbedtls_rsa_import and mbedtls_rsa_complete are introduced for setting
up RSA contexts from partial key material and having them completed to the
needs of the implementation automatically. This allows to setup private RSA
contexts from keys consisting of N,D,E only, even if P,Q are needed for the
purpose or CRT and/or blinding.
* The configuration option MBEDTLS_RSA_ALT can be used to define alternative
implementations of the RSA interface declared in rsa.h.
* The following functions in the MD2, MD4, MD5, SHA1, SHA256 and SHA512 * The following functions in the MD2, MD4, MD5, SHA1, SHA256 and SHA512
modules have been deprecated and replaced as shown below. The new modules have been deprecated and replaced as shown below. The new
functions change the return type from void to int to allow returning error functions change the return type from void to int to allow returning error
@ -25,6 +65,150 @@ API Changes
codes are checked for error after every usage, except in the ssl_tls.c codes are checked for error after every usage, except in the ssl_tls.c
module. module.
Bugfix
* Fix ssl_parse_record_header() to silently discard invalid DTLS records
as recommended in RFC 6347 Section 4.1.2.7.
* Fix memory leak in mbedtls_ssl_set_hostname() when called multiple times.
Found by projectgus and jethrogb, #836.
* Fix usage help in ssl_server2 example. Found and fixed by Bei Lin.
* Parse signature algorithm extension when renegotiating. Previously,
renegotiated handshakes would only accept signatures using SHA-1
regardless of the peer's preferences, or fail if SHA-1 was disabled.
* Fix leap year calculation in x509_date_is_valid() to ensure that invalid
dates on leap years with 100 and 400 intervals are handled correctly. Found
by Nicholas Wilson. #694
* Fix out-of-memory problem when parsing 4096-bit PKCS8-encrypted RSA keys.
Found independently by Florian in the mbed TLS forum and by Mishamax.
#878, #1019.
* Fix variable used before assignment compilation warnings with IAR
toolchain. Found by gkerrien38.
* Fix unchecked return codes from AES, DES and 3DES functions in
pem_aes_decrypt(), pem_des_decrypt() and pem_des3_decrypt() respectively.
If a call to one of the functions of the cryptographic primitive modules
failed, the error may not be noticed by the function
mbedtls_pem_read_buffer() causing it to return invalid values. Found by
Guido Vranken. #756
* Include configuration file in md.h, to fix compilation warnings.
Reported by aaronmdjones in #1001
* Correct extraction of signature-type from PK instance in X.509 CRT and CSR
writing routines that prevented these functions to work with alternative
RSA implementations. Raised by J.B. in the Mbed TLS forum. Fixes #1011.
* Don't print X.509 version tag for v1 CRT's, and omit extensions for
non-v3 CRT's.
* Fix bugs in RSA test suite under MBEDTLS_NO_PLATFORM_ENTROPY. #1023 #1024
* Fix net_would_block to avoid modification by errno through fcntl call.
Found by nkolban. Fixes #845.
* Fix handling of handshake messages in mbedtls_ssl_read in case
MBEDTLS_SSL_RENEGOTIATION is disabled. Found by erja-gp.
* Add a check for invalid private parameters in mbedtls_ecdsa_sign.
Reported by Yolan Romailler.
* Fix word size check in in pk.c to not depend on MBEDTLS_HAVE_INT64.
* Fix incorrect unit in benchmark output. #850
* Fix crash when calling mbedtls_ssl_cache_free() twice. Found by
MilenkoMitrovic, #1104
* Fix mbedtls_timing_alarm(0) on Unix.
* Fix use of uninitialized memory in mbedtls_timing_get_timer when reset=1.
* Fix possible memory leaks in mbedtls_gcm_self_test().
* Added missing return code checks in mbedtls_aes_self_test().
* Fix issues in RSA key generation program programs/x509/rsa_genkey and the
RSA test suite where the failure of CTR DRBG initialization lead to
freeing an RSA context and several MPI's without proper initialization
beforehand.
* Fix the entropy.c module to not call mbedtls_sha256_starts() or
mbedtls_sha512_starts() in the mbedtls_entropy_init() function.
* Fix the entropy.c module to ensure that mbedtls_sha256_init() or
mbedtls_sha512_init() is called before operating on the relevant context
structure. Also, ensure that message digest contexts are freed when
calling mbedtls_entropy_free().
Changes
* Extend cert_write example program by options to set the CRT version
and the message digest. Further, allow enabling/disabling of authority
identifier, subject identifier and basic constraints extensions.
* Only check for necessary RSA structure fields in `mbedtls_rsa_private`. In
particular, don't require P,Q if neither CRT nor blinding are
used. Reported and fix proposed independently by satur9nine and sliai
on GitHub.
* Only run AES-192 self-test if AES-192 is available. Fixes #963.
* Tighten the RSA PKCS#1 v1.5 signature verification code and remove the
undeclared dependency of the RSA module on the ASN.1 module.
= mbed TLS 2.6.0 branch released 2017-08-10
Security
* Fix authentication bypass in SSL/TLS: when authmode is set to optional,
mbedtls_ssl_get_verify_result() would incorrectly return 0 when the peer's
X.509 certificate chain had more than MBEDTLS_X509_MAX_INTERMEDIATE_CA
(default: 8) intermediates, even when it was not trusted. This could be
triggered remotely from either side. (With authmode set to 'required'
(the default), the handshake was correctly aborted).
* Reliably wipe sensitive data after use in the AES example applications
programs/aes/aescrypt2 and programs/aes/crypt_and_hash.
Found by Laurent Simon.
Features
* Add the functions mbedtls_platform_setup() and mbedtls_platform_teardown()
and the context struct mbedtls_platform_context to perform
platform-specific setup and teardown operations. The macro
MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT allows the functions to be overridden
by the user in a platform_alt.h file. These new functions are required in
some embedded environments to provide a means of initialising underlying
cryptographic acceleration hardware.
API Changes
* Reverted API/ABI breaking changes introduced in mbed TLS 2.5.1, to make the
API consistent with mbed TLS 2.5.0. Specifically removed the inline
qualifier from the functions mbedtls_aes_decrypt, mbedtls_aes_encrypt,
mbedtls_ssl_ciphersuite_uses_ec and mbedtls_ssl_ciphersuite_uses_psk. Found
by James Cowgill. #978
* Certificate verification functions now set flags to -1 in case the full
chain was not verified due to an internal error (including in the verify
callback) or chain length limitations.
* With authmode set to optional, the TLS handshake is now aborted if the
verification of the peer's certificate failed due to an overlong chain or
a fatal error in the verify callback.
Bugfix
* Add a check if iv_len is zero in GCM, and return an error if it is zero.
Reported by roberto. #716
* Replace preprocessor condition from #if defined(MBEDTLS_THREADING_PTHREAD)
to #if defined(MBEDTLS_THREADING_C) as the library cannot assume they will
always be implemented by pthread support. #696
* Fix a resource leak on Windows platforms in mbedtls_x509_crt_parse_path(),
in the case of an error. Found by redplait. #590
* Add MBEDTLS_MPI_CHK to check for error value of mbedtls_mpi_fill_random.
Reported and fix suggested by guidovranken. #740
* Fix conditional preprocessor directives in bignum.h to enable 64-bit
compilation when using ARM Compiler 6.
* Fix a potential integer overflow in the version verification for DER
encoded X.509 CRLs. The overflow could enable maliciously constructed CRLs
to bypass the version verification check. Found by Peng Li/Yueh-Hsun Lin,
KNOX Security, Samsung Research America
* Fix potential integer overflow in the version verification for DER
encoded X.509 CSRs. The overflow could enable maliciously constructed CSRs
to bypass the version verification check. Found by Peng Li/Yueh-Hsun Lin,
KNOX Security, Samsung Research America
* Fix a potential integer overflow in the version verification for DER
encoded X.509 certificates. The overflow could enable maliciously
constructed certificates to bypass the certificate verification check.
* Fix a call to the libc function time() to call the platform abstraction
function mbedtls_time() instead. Found by wairua. #666
* Avoid shadowing of time and index functions through mbed TLS function
arguments. Found by inestlerode. #557.
Changes
* Added config.h option MBEDTLS_NO_UDBL_DIVISION, to prevent the use of
64-bit division. This is useful on embedded platforms where 64-bit division
created a dependency on external libraries. #708
* Removed mutexes from ECP hardware accelerator code. Now all hardware
accelerator code in the library leaves concurrency handling to the
platform. Reported by Steven Cooreman. #863
* Define the macro MBEDTLS_AES_ROM_TABLES in the configuration file
config-no-entropy.h to reduce the RAM footprint.
* Added a test script that can be hooked into git that verifies commits
before they are pushed.
* Improve documentation of PKCS1 decryption functions.
= mbed TLS 2.5.1 released 2017-06-21 = mbed TLS 2.5.1 released 2017-06-21
Security Security
@ -278,7 +462,7 @@ Security
* Fix potential integer overflow to buffer overflow in * Fix potential integer overflow to buffer overflow in
mbedtls_rsa_rsaes_pkcs1_v15_encrypt and mbedtls_rsa_rsaes_oaep_encrypt mbedtls_rsa_rsaes_pkcs1_v15_encrypt and mbedtls_rsa_rsaes_oaep_encrypt
(not triggerable remotely in (D)TLS). (not triggerable remotely in (D)TLS).
* Fix a potential integer underflow to buffer overread in * Fix a potential integer underflow to buffer overread in
mbedtls_rsa_rsaes_oaep_decrypt. It is not triggerable remotely in mbedtls_rsa_rsaes_oaep_decrypt. It is not triggerable remotely in
SSL/TLS. SSL/TLS.
@ -298,7 +482,7 @@ Bugfix
* Fix an issue that caused valid certificates to be rejected whenever an * Fix an issue that caused valid certificates to be rejected whenever an
expired or not yet valid certificate was parsed before a valid certificate expired or not yet valid certificate was parsed before a valid certificate
in the trusted certificate list. in the trusted certificate list.
* Fix bug in mbedtls_x509_crt_parse that caused trailing extra data in the * Fix bug in mbedtls_x509_crt_parse that caused trailing extra data in the
buffer after DER certificates to be included in the raw representation. buffer after DER certificates to be included in the raw representation.
* Fix issue that caused a hang when generating RSA keys of odd bitlength * Fix issue that caused a hang when generating RSA keys of odd bitlength
* Fix bug in mbedtls_rsa_rsaes_pkcs1_v15_encrypt that made null pointer * Fix bug in mbedtls_rsa_rsaes_pkcs1_v15_encrypt that made null pointer
@ -1554,7 +1738,7 @@ Security
Changes Changes
* Allow enabling of dummy error_strerror() to support some use-cases * Allow enabling of dummy error_strerror() to support some use-cases
* Debug messages about padding errors during SSL message decryption are * Debug messages about padding errors during SSL message decryption are
disabled by default and can be enabled with POLARSSL_SSL_DEBUG_ALL disabled by default and can be enabled with POLARSSL_SSL_DEBUG_ALL
* Sending of security-relevant alert messages that do not break * Sending of security-relevant alert messages that do not break
interoperability can be switched on/off with the flag interoperability can be switched on/off with the flag
POLARSSL_SSL_ALL_ALERT_MESSAGES POLARSSL_SSL_ALL_ALERT_MESSAGES
@ -1583,7 +1767,7 @@ Bugfix
Changes Changes
* Added p_hw_data to ssl_context for context specific hardware acceleration * Added p_hw_data to ssl_context for context specific hardware acceleration
data data
* During verify trust-CA is only checked for expiration and CRL presence * During verify trust-CA is only checked for expiration and CRL presence
Bugfixes Bugfixes
* Fixed client authentication compatibility * Fixed client authentication compatibility
@ -1881,9 +2065,9 @@ Features
with random data (Fixed ticket #10) with random data (Fixed ticket #10)
Changes Changes
* Debug print of MPI now removes leading zero octets and * Debug print of MPI now removes leading zero octets and
displays actual bit size of the value. displays actual bit size of the value.
* x509parse_key() (and as a consequence x509parse_keyfile()) * x509parse_key() (and as a consequence x509parse_keyfile())
does not zeroize memory in advance anymore. Use rsa_init() does not zeroize memory in advance anymore. Use rsa_init()
before parsing a key or keyfile! before parsing a key or keyfile!
@ -1905,7 +2089,7 @@ Features
printing of X509 CRLs from file printing of X509 CRLs from file
Changes Changes
* Parsing of PEM files moved to separate module (Fixes * Parsing of PEM files moved to separate module (Fixes
ticket #13). Also possible to remove PEM support for ticket #13). Also possible to remove PEM support for
systems only using DER encoding systems only using DER encoding
@ -2048,7 +2232,7 @@ Bug fixes
* Fixed HMAC-MD2 by modifying md2_starts(), so that the * Fixed HMAC-MD2 by modifying md2_starts(), so that the
required HMAC ipad and opad variables are not cleared. required HMAC ipad and opad variables are not cleared.
(found by code coverage tests) (found by code coverage tests)
* Prevented use of long long in bignum if * Prevented use of long long in bignum if
POLARSSL_HAVE_LONGLONG not defined (found by Giles POLARSSL_HAVE_LONGLONG not defined (found by Giles
Bathgate). Bathgate).
* Fixed incorrect handling of negative strings in * Fixed incorrect handling of negative strings in
@ -2089,7 +2273,7 @@ Bug fixes
* Made definition of net_htons() endian-clean for big endian * Made definition of net_htons() endian-clean for big endian
systems (Found by Gernot). systems (Found by Gernot).
* Undefining POLARSSL_HAVE_ASM now also handles prevents asm in * Undefining POLARSSL_HAVE_ASM now also handles prevents asm in
padlock and timing code. padlock and timing code.
* Fixed an off-by-one buffer allocation in ssl_set_hostname() * Fixed an off-by-one buffer allocation in ssl_set_hostname()
responsible for crashes and unwanted behaviour. responsible for crashes and unwanted behaviour.
* Added support for Certificate Revocation List (CRL) parsing. * Added support for Certificate Revocation List (CRL) parsing.
@ -2263,4 +2447,3 @@ XySSL ChangeLog
who maintains the Debian package :-) who maintains the Debian package :-)
= Version 0.1 released on 2006-11-01 = Version 0.1 released on 2006-11-01

View file

@ -1,37 +1,37 @@
README for mbed TLS README for Mbed TLS
=================== ===================
Configuration Configuration
------------- -------------
mbed TLS should build out of the box on most systems. Some platform specific options are available in the fully documented configuration file `include/mbedtls/config.h`, which is also the place where features can be selected. This file can be edited manually, or in a more programmatic way using the Perl script `scripts/config.pl` (use `--help` for usage instructions). Mbed TLS should build out of the box on most systems. Some platform specific options are available in the fully documented configuration file `include/mbedtls/config.h`, which is also the place where features can be selected. This file can be edited manually, or in a more programmatic way using the Perl script `scripts/config.pl` (use `--help` for usage instructions).
Compiler options can be set using conventional environment variables such as `CC` and `CFLAGS` when using the Make and CMake build system (see below). Compiler options can be set using conventional environment variables such as `CC` and `CFLAGS` when using the Make and CMake build system (see below).
Compiling Compiling
--------- ---------
There are currently four active build systems used within mbed TLS releases: There are currently four active build systems used within Mbed TLS releases:
- yotta - yotta
- Make - GNU Make
- CMake - CMake
- Microsoft Visual Studio (Visual Studio 6 and Visual Studio 2010) - Microsoft Visual Studio (Microsoft Visual Studio 2010 or later)
The main systems used for development are CMake and Make. Those systems are always complete and up-to-date. The others should reflect all changes present in the CMake and Make build system, although features may not be ported there automatically. The main systems used for development are CMake and GNU Make. Those systems are always complete and up-to-date. The others should reflect all changes present in the CMake and Make build system, although features may not be ported there automatically.
Yotta, as a build system, is slightly different from the other build systems: Yotta, as a build system, is slightly different from the other build systems:
- it provides a minimalistic configuration file by default - it provides a minimalistic configuration file by default
- depending on the yotta target, features of mbed OS may be used in examples and tests - depending on the yotta target, features of Mbed OS may be used in examples and tests
The Make and CMake build systems create three libraries: libmbedcrypto, libmbedx509, and libmbedtls. Note that libmbedtls depends on libmbedx509 and libmbedcrypto, and libmbedx509 depends on libmbedcrypto. As a result, some linkers will expect flags to be in a specific order, for example the GNU linker wants `-lmbedtls -lmbedx509 -lmbedcrypto`. Also, when loading shared libraries using dlopen(), you'll need to load libmbedcrypto first, then libmbedx509, before you can load libmbedtls. The Make and CMake build systems create three libraries: libmbedcrypto, libmbedx509, and libmbedtls. Note that libmbedtls depends on libmbedx509 and libmbedcrypto, and libmbedx509 depends on libmbedcrypto. As a result, some linkers will expect flags to be in a specific order, for example the GNU linker wants `-lmbedtls -lmbedx509 -lmbedcrypto`. Also, when loading shared libraries using dlopen(), you'll need to load libmbedcrypto first, then libmbedx509, before you can load libmbedtls.
### Yotta ### Yotta
[yotta](http://yottabuild.org) is a package manager and build system developed by mbed, and is the build system of mbed OS 16.03. To install it on your platform, please follow the yotta [installation instructions](http://docs.yottabuild.org/#installing). [yotta](http://yottabuild.org) is a package manager and build system developed by Mbed, and is the build system of Mbed OS 16.03. To install it on your platform, please follow the yotta [installation instructions](http://docs.yottabuild.org/#installing).
Once yotta is installed, you can use it to download the latest version of mbed TLS from the yotta registry with: Once yotta is installed, you can use it to download the latest version of Mbed TLS from the yotta registry with:
yotta install mbedtls yotta install mbedtls
@ -39,24 +39,26 @@ and build it with:
yotta build yotta build
If, on the other hand, you already have a copy of mbed TLS from a source other than the yotta registry, for example from cloning our GitHub repository, or from downloading a tarball of the standalone edition, then you'll first need to generate the yotta module by running: If, on the other hand, you already have a copy of Mbed TLS from a source other than the yotta registry, for example from cloning our GitHub repository, or from downloading a tarball of the standalone edition, then you'll first need to generate the yotta module by running:
yotta/create-module.sh yotta/create-module.sh
This should be executed from the root mbed TLS project directory. This will create the yotta module in the `yotta/module` directory within it. You can then change to that directory and build as usual: This should be executed from the root Mbed TLS project directory. This will create the yotta module in the `yotta/module` directory within it. You can then change to that directory and build as usual:
cd yotta/module cd yotta/module
yotta build yotta build
In any case, you'll probably want to set the yotta target before building unless it has already been set globally. For more information on using yotta, please consult the [yotta documentation](http://docs.yottabuild.org/). In any case, you'll probably want to set the yotta target before building unless it has already been set globally. For more information on using yotta, please consult the [yotta documentation](http://docs.yottabuild.org/).
For more details on the yotta/mbed OS edition of mbed TLS, including example programs, please consult the [Readme at the root of the yotta module](https://github.com/ARMmbed/mbedtls/blob/development/yotta/data/README.md). For more details on the yotta/Mbed OS edition of Mbed TLS, including example programs, please consult the [Readme at the root of the yotta module](https://github.com/ARMmbed/mbedtls/blob/development/yotta/data/README.md).
### Make ### Make
We intentionally only use the minimum of `Make` functionality, as a lot of `Make` features are not supported on all different implementations of Make or on different platforms. As such, the Makefiles sometimes require some manual changes or export statements in order to work for your platform. We require GNU Make. To build the library and the sample programs, GNU Make and a C compiler are sufficient. Some of the more advanced build targets require some Unix/Linux tools.
In order to build from the source code using Make, just enter at the command line: We intentionally only use a minimum of functionality in the makefiles in order to keep them as simple and independent of different toolchains as possible, to allow users to more easily move between different platforms. Users who need more features are recommended to use CMake.
In order to build from the source code using GNU Make, just enter at the command line:
make make
@ -76,9 +78,9 @@ In order to build for a Windows platform, you should use `WINDOWS_BUILD=1` if th
Setting the variable `SHARED` in your environment will build shared libraries in addition to the static libraries. Setting `DEBUG` gives you a debug build. You can override `CFLAGS` and `LDFLAGS` by setting them in your environment or on the make command line; if you do so, essential parts such as `-I` will still be preserved. Warning options may be overridden separately using `WARNING_CFLAGS`. Setting the variable `SHARED` in your environment will build shared libraries in addition to the static libraries. Setting `DEBUG` gives you a debug build. You can override `CFLAGS` and `LDFLAGS` by setting them in your environment or on the make command line; if you do so, essential parts such as `-I` will still be preserved. Warning options may be overridden separately using `WARNING_CFLAGS`.
Depending on your platform, you might run into some issues. Please check the Makefiles in `library/`, `programs/` and `tests/` for options to manually add or remove for specific platforms. You can also check [the mbed TLS Knowledge Base](https://tls.mbed.org/kb) for articles on your platform or issue. Depending on your platform, you might run into some issues. Please check the Makefiles in `library/`, `programs/` and `tests/` for options to manually add or remove for specific platforms. You can also check [the Mbed TLS Knowledge Base](https://tls.mbed.org/kb) for articles on your platform or issue.
In case you find that you need to do something else as well, please let us know what, so we can add it to the [mbed TLS knowledge base](https://tls.mbed.org/kb). In case you find that you need to do something else as well, please let us know what, so we can add it to the [Mbed TLS knowledge base](https://tls.mbed.org/kb).
### CMake ### CMake
@ -141,7 +143,7 @@ We've included example programs for a lot of different features and uses in `pro
Tests Tests
----- -----
mbed TLS includes an elaborate test suite in `tests/` that initially requires Perl to generate the tests files (e.g. `test\_suite\_mpi.c`). These files are generated from a `function file` (e.g. `suites/test\_suite\_mpi.function`) and a `data file` (e.g. `suites/test\_suite\_mpi.data`). The `function file` contains the test functions. The `data file` contains the test cases, specified as parameters that will be passed to the test function. Mbed TLS includes an elaborate test suite in `tests/` that initially requires Perl to generate the tests files (e.g. `test\_suite\_mpi.c`). These files are generated from a `function file` (e.g. `suites/test\_suite\_mpi.function`) and a `data file` (e.g. `suites/test\_suite\_mpi.data`). The `function file` contains the test functions. The `data file` contains the test cases, specified as parameters that will be passed to the test function.
For machines with a Unix shell and OpenSSL (and optionally GnuTLS) installed, additional test scripts are available: For machines with a Unix shell and OpenSSL (and optionally GnuTLS) installed, additional test scripts are available:
@ -156,14 +158,14 @@ Configurations
We provide some non-standard configurations focused on specific use cases in the `configs/` directory. You can read more about those in `configs/README.txt` We provide some non-standard configurations focused on specific use cases in the `configs/` directory. You can read more about those in `configs/README.txt`
Porting mbed TLS Porting Mbed TLS
---------------- ----------------
mbed TLS can be ported to many different architectures, OS's and platforms. Before starting a port, you may find the following knowledge base articles useful: Mbed TLS can be ported to many different architectures, OS's and platforms. Before starting a port, you may find the following knowledge base articles useful:
- [Porting mbed TLS to a new environment or OS](https://tls.mbed.org/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS) - [Porting Mbed TLS to a new environment or OS](https://tls.mbed.org/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS)
- [What external dependencies does mbed TLS rely on?](https://tls.mbed.org/kb/development/what-external-dependencies-does-mbedtls-rely-on) - [What external dependencies does Mbed TLS rely on?](https://tls.mbed.org/kb/development/what-external-dependencies-does-mbedtls-rely-on)
- [How do I configure mbed TLS](https://tls.mbed.org/kb/compiling-and-building/how-do-i-configure-mbedtls) - [How do I configure Mbed TLS](https://tls.mbed.org/kb/compiling-and-building/how-do-i-configure-mbedtls)
Contributing Contributing
------------ ------------
@ -174,12 +176,12 @@ We gratefully accept bug reports and contributions from the community. There are
- We would ask that contributions conform to [our coding standards](https://tls.mbed.org/kb/development/mbedtls-coding-standards), and that contributions should be fully tested before submission. - We would ask that contributions conform to [our coding standards](https://tls.mbed.org/kb/development/mbedtls-coding-standards), and that contributions should be fully tested before submission.
- As with any open source project, contributions will be reviewed by the project team and community and may need some modifications to be accepted. - As with any open source project, contributions will be reviewed by the project team and community and may need some modifications to be accepted.
To accept the Contributors Licence Agreement (CLA), individual contributors can do this by creating an mbed account and [accepting the online agreement here with a click through](https://developer.mbed.org/contributor_agreement/). Alternatively, for contributions from corporations, or those that do not wish to create an mbed account, a slightly different agreement can be found [here](https://www.mbed.com/en/about-mbed/contributor-license-agreements/). This agreement should be signed and returned to ARM as described in the instructions given. To accept the Contributors Licence Agreement (CLA), individual contributors can do this by creating an Mbed account and [accepting the online agreement here with a click through](https://os.mbed.com/contributor_agreement/). Alternatively, for contributions from corporations, or those that do not wish to create an Mbed account, a slightly different agreement can be found [here](https://www.mbed.com/en/about-mbed/contributor-license-agreements/). This agreement should be signed and returned to Arm as described in the instructions given.
### Making a Contribution ### Making a Contribution
1. [Check for open issues](https://github.com/ARMmbed/mbedtls/issues) or [start a discussion](https://tls.mbed.org/discussions) around a feature idea or a bug. 1. [Check for open issues](https://github.com/ARMmbed/mbedtls/issues) or [start a discussion](https://tls.mbed.org/discussions) around a feature idea or a bug.
2. Fork the [mbed TLS repository on GitHub](https://github.com/ARMmbed/mbedtls) to start making your changes. As a general rule, you should use the "development" branch as a basis. 2. Fork the [Mbed TLS repository on GitHub](https://github.com/ARMmbed/mbedtls) to start making your changes. As a general rule, you should use the "development" branch as a basis.
3. Write a test which shows that the bug was fixed or that the feature works as expected. 3. Write a test which shows that the bug was fixed or that the feature works as expected.
4. Send a pull request and bug us until it gets merged and published. Contributions may need some modifications, so work with us to get your change accepted. We will include your name in the ChangeLog :) 4. Send a pull request and bug us until it gets merged and published. Contributions may need some modifications, so work with us to get your change accepted. We will include your name in the ChangeLog :)

View file

@ -8,7 +8,7 @@ These files are complete replacements for the default config.h. To use one of
them, you can pick one of the following methods: them, you can pick one of the following methods:
1. Replace the default file include/mbedtls/config.h with the chosen one. 1. Replace the default file include/mbedtls/config.h with the chosen one.
(Depending on your compiler, you may need to ajust the line with (Depending on your compiler, you may need to adjust the line with
#include "mbedtls/check_config.h" then.) #include "mbedtls/check_config.h" then.)
2. Define MBEDTLS_CONFIG_FILE and adjust the include path accordingly. 2. Define MBEDTLS_CONFIG_FILE and adjust the include path accordingly.

View file

@ -80,6 +80,9 @@
#define MBEDTLS_X509_CRT_PARSE_C #define MBEDTLS_X509_CRT_PARSE_C
#define MBEDTLS_X509_CRL_PARSE_C #define MBEDTLS_X509_CRL_PARSE_C
/* Miscellaneous options */
#define MBEDTLS_AES_ROM_TABLES
#include "check_config.h" #include "check_config.h"
#endif /* MBEDTLS_CONFIG_H */ #endif /* MBEDTLS_CONFIG_H */

View file

@ -21,7 +21,7 @@
*/ */
/** /**
* @mainpage mbed TLS v2.5.1 source code documentation * @mainpage mbed TLS v2.6.0 source code documentation
* *
* This documentation describes the internal structure of mbed TLS. It was * This documentation describes the internal structure of mbed TLS. It was
* automatically generated from specially formatted comment blocks in * automatically generated from specially formatted comment blocks in

View file

@ -28,7 +28,7 @@ DOXYFILE_ENCODING = UTF-8
# identify the project. Note that if you do not use Doxywizard you need # identify the project. Note that if you do not use Doxywizard you need
# to put quotes around the project name if it contains spaces. # to put quotes around the project name if it contains spaces.
PROJECT_NAME = "mbed TLS v2.5.1" PROJECT_NAME = "mbed TLS v2.6.0"
# The PROJECT_NUMBER tag can be used to enter a project or revision number. # The PROJECT_NUMBER tag can be used to enter a project or revision number.
# This could be handy for archiving the generated documentation or # This could be handy for archiving the generated documentation or

View file

@ -36,9 +36,13 @@
#define MBEDTLS_AES_ENCRYPT 1 #define MBEDTLS_AES_ENCRYPT 1
#define MBEDTLS_AES_DECRYPT 0 #define MBEDTLS_AES_DECRYPT 0
/* Error codes in range 0x0020-0x0022 */
#define MBEDTLS_ERR_AES_INVALID_KEY_LENGTH -0x0020 /**< Invalid key length. */ #define MBEDTLS_ERR_AES_INVALID_KEY_LENGTH -0x0020 /**< Invalid key length. */
#define MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH -0x0022 /**< Invalid data input length. */ #define MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH -0x0022 /**< Invalid data input length. */
/* Error codes in range 0x0023-0x0023 */
#define MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE -0x0023 /**< Feature not available, e.g. unsupported AES key size. */
#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \ #if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
!defined(inline) && !defined(__cplusplus) !defined(inline) && !defined(__cplusplus)
#define inline __inline #define inline __inline
@ -287,9 +291,8 @@ int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx,
#define MBEDTLS_DEPRECATED #define MBEDTLS_DEPRECATED
#endif #endif
/** /**
* \brief Internal AES block encryption function * \brief Deprecated internal AES block encryption function
* (Only exposed to allow overriding it, * without return value.
* see MBEDTLS_AES_ENCRYPT_ALT)
* *
* \deprecated Superseded by mbedtls_aes_encrypt_ext() in 2.5.0 * \deprecated Superseded by mbedtls_aes_encrypt_ext() in 2.5.0
* *
@ -297,18 +300,13 @@ int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx,
* \param input Plaintext block * \param input Plaintext block
* \param output Output (ciphertext) block * \param output Output (ciphertext) block
*/ */
MBEDTLS_DEPRECATED static inline void mbedtls_aes_encrypt( MBEDTLS_DEPRECATED void mbedtls_aes_encrypt( mbedtls_aes_context *ctx,
mbedtls_aes_context *ctx, const unsigned char input[16],
const unsigned char input[16], unsigned char output[16] );
unsigned char output[16] )
{
mbedtls_internal_aes_encrypt( ctx, input, output );
}
/** /**
* \brief Internal AES block decryption function * \brief Deprecated internal AES block decryption function
* (Only exposed to allow overriding it, * without return value.
* see MBEDTLS_AES_DECRYPT_ALT)
* *
* \deprecated Superseded by mbedtls_aes_decrypt_ext() in 2.5.0 * \deprecated Superseded by mbedtls_aes_decrypt_ext() in 2.5.0
* *
@ -316,13 +314,9 @@ MBEDTLS_DEPRECATED static inline void mbedtls_aes_encrypt(
* \param input Ciphertext block * \param input Ciphertext block
* \param output Output (plaintext) block * \param output Output (plaintext) block
*/ */
MBEDTLS_DEPRECATED static inline void mbedtls_aes_decrypt( MBEDTLS_DEPRECATED void mbedtls_aes_decrypt( mbedtls_aes_context *ctx,
mbedtls_aes_context *ctx, const unsigned char input[16],
const unsigned char input[16], unsigned char output[16] );
unsigned char output[16] )
{
mbedtls_internal_aes_decrypt( ctx, input, output );
}
#undef MBEDTLS_DEPRECATED #undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */ #endif /* !MBEDTLS_DEPRECATED_REMOVED */

View file

@ -59,7 +59,7 @@
/** /**
* \name DER constants * \name DER constants
* These constants comply with DER encoded the ANS1 type tags. * These constants comply with the DER encoded ASN.1 type tags.
* DER encoding uses hexadecimal representation. * DER encoding uses hexadecimal representation.
* An example DER sequence is:\n * An example DER sequence is:\n
* - 0x02 -- tag indicating INTEGER * - 0x02 -- tag indicating INTEGER

View file

@ -70,7 +70,7 @@
* Maximum size of MPIs allowed in bits and bytes for user-MPIs. * Maximum size of MPIs allowed in bits and bytes for user-MPIs.
* ( Default: 512 bytes => 4096 bits, Maximum tested: 2048 bytes => 16384 bits ) * ( Default: 512 bytes => 4096 bits, Maximum tested: 2048 bytes => 16384 bits )
* *
* Note: Calculations can results temporarily in larger MPIs. So the number * Note: Calculations can temporarily result in larger MPIs. So the number
* of limbs required (MBEDTLS_MPI_MAX_LIMBS) is higher. * of limbs required (MBEDTLS_MPI_MAX_LIMBS) is higher.
*/ */
#define MBEDTLS_MPI_MAX_SIZE 1024 /**< Maximum number of bytes for usable MPIs. */ #define MBEDTLS_MPI_MAX_SIZE 1024 /**< Maximum number of bytes for usable MPIs. */
@ -103,36 +103,71 @@
/* /*
* Define the base integer type, architecture-wise. * Define the base integer type, architecture-wise.
* *
* 32-bit integers can be forced on 64-bit arches (eg. for testing purposes) * 32 or 64-bit integer types can be forced regardless of the underlying
* by defining MBEDTLS_HAVE_INT32 and undefining MBEDTLS_HAVE_ASM * architecture by defining MBEDTLS_HAVE_INT32 or MBEDTLS_HAVE_INT64
* respectively and undefining MBEDTLS_HAVE_ASM.
*
* Double-width integers (e.g. 128-bit in 64-bit architectures) can be
* disabled by defining MBEDTLS_NO_UDBL_DIVISION.
*/ */
#if ( ! defined(MBEDTLS_HAVE_INT32) && \ #if !defined(MBEDTLS_HAVE_INT32)
defined(_MSC_VER) && defined(_M_AMD64) ) #if defined(_MSC_VER) && defined(_M_AMD64)
#define MBEDTLS_HAVE_INT64 /* Always choose 64-bit when using MSC */
typedef int64_t mbedtls_mpi_sint; #if !defined(MBEDTLS_HAVE_INT64)
typedef uint64_t mbedtls_mpi_uint; #define MBEDTLS_HAVE_INT64
#else #endif /* !MBEDTLS_HAVE_INT64 */
#if ( ! defined(MBEDTLS_HAVE_INT32) && \ typedef int64_t mbedtls_mpi_sint;
defined(__GNUC__) && ( \ typedef uint64_t mbedtls_mpi_uint;
defined(__amd64__) || defined(__x86_64__) || \ #elif defined(__GNUC__) && ( \
defined(__ppc64__) || defined(__powerpc64__) || \ defined(__amd64__) || defined(__x86_64__) || \
defined(__ia64__) || defined(__alpha__) || \ defined(__ppc64__) || defined(__powerpc64__) || \
(defined(__sparc__) && defined(__arch64__)) || \ defined(__ia64__) || defined(__alpha__) || \
defined(__s390x__) || defined(__mips64) ) ) ( defined(__sparc__) && defined(__arch64__) ) || \
#define MBEDTLS_HAVE_INT64 defined(__s390x__) || defined(__mips64) )
typedef int64_t mbedtls_mpi_sint; #if !defined(MBEDTLS_HAVE_INT64)
typedef uint64_t mbedtls_mpi_uint; #define MBEDTLS_HAVE_INT64
/* mbedtls_t_udbl defined as 128-bit unsigned int */ #endif /* MBEDTLS_HAVE_INT64 */
typedef unsigned int mbedtls_t_udbl __attribute__((mode(TI))); typedef int64_t mbedtls_mpi_sint;
#define MBEDTLS_HAVE_UDBL typedef uint64_t mbedtls_mpi_uint;
#else #if !defined(MBEDTLS_NO_UDBL_DIVISION)
#define MBEDTLS_HAVE_INT32 /* mbedtls_t_udbl defined as 128-bit unsigned int */
typedef int32_t mbedtls_mpi_sint; typedef unsigned int mbedtls_t_udbl __attribute__((mode(TI)));
typedef uint32_t mbedtls_mpi_uint; #define MBEDTLS_HAVE_UDBL
typedef uint64_t mbedtls_t_udbl; #endif /* !MBEDTLS_NO_UDBL_DIVISION */
#define MBEDTLS_HAVE_UDBL #elif defined(__ARMCC_VERSION) && defined(__aarch64__)
#endif /* !MBEDTLS_HAVE_INT32 && __GNUC__ && 64-bit platform */ /*
#endif /* !MBEDTLS_HAVE_INT32 && _MSC_VER && _M_AMD64 */ * __ARMCC_VERSION is defined for both armcc and armclang and
* __aarch64__ is only defined by armclang when compiling 64-bit code
*/
#if !defined(MBEDTLS_HAVE_INT64)
#define MBEDTLS_HAVE_INT64
#endif /* !MBEDTLS_HAVE_INT64 */
typedef int64_t mbedtls_mpi_sint;
typedef uint64_t mbedtls_mpi_uint;
#if !defined(MBEDTLS_NO_UDBL_DIVISION)
/* mbedtls_t_udbl defined as 128-bit unsigned int */
typedef __uint128_t mbedtls_t_udbl;
#define MBEDTLS_HAVE_UDBL
#endif /* !MBEDTLS_NO_UDBL_DIVISION */
#elif defined(MBEDTLS_HAVE_INT64)
/* Force 64-bit integers with unknown compiler */
typedef int64_t mbedtls_mpi_sint;
typedef uint64_t mbedtls_mpi_uint;
#endif
#endif /* !MBEDTLS_HAVE_INT32 */
#if !defined(MBEDTLS_HAVE_INT64)
/* Default to 32-bit compilation */
#if !defined(MBEDTLS_HAVE_INT32)
#define MBEDTLS_HAVE_INT32
#endif /* !MBEDTLS_HAVE_INT32 */
typedef int32_t mbedtls_mpi_sint;
typedef uint32_t mbedtls_mpi_uint;
#if !defined(MBEDTLS_NO_UDBL_DIVISION)
typedef uint64_t mbedtls_t_udbl;
#define MBEDTLS_HAVE_UDBL
#endif /* !MBEDTLS_NO_UDBL_DIVISION */
#endif /* !MBEDTLS_HAVE_INT64 */
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {

View file

@ -28,6 +28,10 @@
#define MBEDTLS_ERR_CCM_BAD_INPUT -0x000D /**< Bad input parameters to function. */ #define MBEDTLS_ERR_CCM_BAD_INPUT -0x000D /**< Bad input parameters to function. */
#define MBEDTLS_ERR_CCM_AUTH_FAILED -0x000F /**< Authenticated decryption failed. */ #define MBEDTLS_ERR_CCM_AUTH_FAILED -0x000F /**< Authenticated decryption failed. */
#if !defined(MBEDTLS_CCM_ALT)
// Regular implementation
//
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
@ -125,6 +129,18 @@ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *input, unsigned char *output, const unsigned char *input, unsigned char *output,
const unsigned char *tag, size_t tag_len ); const unsigned char *tag, size_t tag_len );
#ifdef __cplusplus
}
#endif
#else /* !MBEDTLS_CCM_ALT */
#include "ccm_alt.h"
#endif /* !MBEDTLS_CCM_ALT */
#ifdef __cplusplus
extern "C" {
#endif
#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C) #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
/** /**
* \brief Checkup routine * \brief Checkup routine

View file

@ -650,6 +650,15 @@
#error "MBEDTLS_X509_CSR_WRITE_C defined, but not all prerequisites" #error "MBEDTLS_X509_CSR_WRITE_C defined, but not all prerequisites"
#endif #endif
#if defined(MBEDTLS_HAVE_INT32) && defined(MBEDTLS_HAVE_INT64)
#error "MBEDTLS_HAVE_INT32 and MBEDTLS_HAVE_INT64 cannot be defined simultaneously"
#endif /* MBEDTLS_HAVE_INT32 && MBEDTLS_HAVE_INT64 */
#if ( defined(MBEDTLS_HAVE_INT32) || defined(MBEDTLS_HAVE_INT64) ) && \
defined(MBEDTLS_HAVE_ASM)
#error "MBEDTLS_HAVE_INT32/MBEDTLS_HAVE_INT64 and MBEDTLS_HAVE_ASM cannot be defined simultaneously"
#endif /* (MBEDTLS_HAVE_INT32 || MBEDTLS_HAVE_INT64) && MBEDTLS_HAVE_ASM */
/* /*
* Avoid warning from -pedantic. This is a convenient place for this * Avoid warning from -pedantic. This is a convenient place for this
* workaround since this is included by every single file before the * workaround since this is included by every single file before the

View file

@ -39,6 +39,8 @@ extern "C" {
#define MBEDTLS_CIPHER_BLKSIZE_MAX 8 /* longest used by CMAC is 3DES */ #define MBEDTLS_CIPHER_BLKSIZE_MAX 8 /* longest used by CMAC is 3DES */
#endif #endif
#if !defined(MBEDTLS_CMAC_ALT)
/** /**
* CMAC context structure - Contains internal state information only * CMAC context structure - Contains internal state information only
*/ */
@ -154,6 +156,18 @@ int mbedtls_aes_cmac_prf_128( const unsigned char *key, size_t key_len,
unsigned char output[16] ); unsigned char output[16] );
#endif /* MBEDTLS_AES_C */ #endif /* MBEDTLS_AES_C */
#ifdef __cplusplus
}
#endif
#else /* !MBEDTLS_CMAC_ALT */
#include "cmac_alt.h"
#endif /* !MBEDTLS_CMAC_ALT */
#ifdef __cplusplus
extern "C" {
#endif
#if defined(MBEDTLS_SELF_TEST) && ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_DES_C) ) #if defined(MBEDTLS_SELF_TEST) && ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_DES_C) )
/** /**
* \brief Checkup routine * \brief Checkup routine

View file

@ -55,6 +55,34 @@
*/ */
#define MBEDTLS_HAVE_ASM #define MBEDTLS_HAVE_ASM
/**
* \def MBEDTLS_NO_UDBL_DIVISION
*
* The platform lacks support for double-width integer division (64-bit
* division on a 32-bit platform, 128-bit division on a 64-bit platform).
*
* Used in:
* include/mbedtls/bignum.h
* library/bignum.c
*
* The bignum code uses double-width division to speed up some operations.
* Double-width division is often implemented in software that needs to
* be linked with the program. The presence of a double-width integer
* type is usually detected automatically through preprocessor macros,
* but the automatic detection cannot know whether the code needs to
* and can be linked with an implementation of division for that type.
* By default division is assumed to be usable if the type is present.
* Uncomment this option to prevent the use of double-width division.
*
* Note that division for the native integer type is always required.
* Furthermore, a 64-bit type is always required even on a 32-bit
* platform, but it need not support multiplication or division. In some
* cases it is also desirable to disable some double-width operations. For
* example, if double-width division is implemented in software, disabling
* it can reduce code size in some embedded targets.
*/
//#define MBEDTLS_NO_UDBL_DIVISION
/** /**
* \def MBEDTLS_HAVE_SSE2 * \def MBEDTLS_HAVE_SSE2
* *
@ -163,6 +191,7 @@
//#define MBEDTLS_PLATFORM_PRINTF_ALT //#define MBEDTLS_PLATFORM_PRINTF_ALT
//#define MBEDTLS_PLATFORM_SNPRINTF_ALT //#define MBEDTLS_PLATFORM_SNPRINTF_ALT
//#define MBEDTLS_PLATFORM_NV_SEED_ALT //#define MBEDTLS_PLATFORM_NV_SEED_ALT
//#define MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT
/** /**
* \def MBEDTLS_DEPRECATED_WARNING * \def MBEDTLS_DEPRECATED_WARNING
@ -237,15 +266,19 @@
//#define MBEDTLS_ARC4_ALT //#define MBEDTLS_ARC4_ALT
//#define MBEDTLS_BLOWFISH_ALT //#define MBEDTLS_BLOWFISH_ALT
//#define MBEDTLS_CAMELLIA_ALT //#define MBEDTLS_CAMELLIA_ALT
//#define MBEDTLS_CCM_ALT
//#define MBEDTLS_CMAC_ALT
//#define MBEDTLS_DES_ALT //#define MBEDTLS_DES_ALT
//#define MBEDTLS_XTEA_ALT //#define MBEDTLS_GCM_ALT
//#define MBEDTLS_MD2_ALT //#define MBEDTLS_MD2_ALT
//#define MBEDTLS_MD4_ALT //#define MBEDTLS_MD4_ALT
//#define MBEDTLS_MD5_ALT //#define MBEDTLS_MD5_ALT
//#define MBEDTLS_RIPEMD160_ALT //#define MBEDTLS_RIPEMD160_ALT
//#define MBEDTLS_RSA_ALT
//#define MBEDTLS_SHA1_ALT //#define MBEDTLS_SHA1_ALT
//#define MBEDTLS_SHA256_ALT //#define MBEDTLS_SHA256_ALT
//#define MBEDTLS_SHA512_ALT //#define MBEDTLS_SHA512_ALT
//#define MBEDTLS_XTEA_ALT
/* /*
* When replacing the elliptic curve module, pleace consider, that it is * When replacing the elliptic curve module, pleace consider, that it is
* implemented with two .c files: * implemented with two .c files:
@ -273,9 +306,15 @@
* of mbedtls_sha1_context, so your implementation of mbedtls_sha1_process must be compatible * of mbedtls_sha1_context, so your implementation of mbedtls_sha1_process must be compatible
* with this definition. * with this definition.
* *
* Note: if you use the AES_xxx_ALT macros, then is is recommended to also set * \note Because of a signature change, the core AES encryption and decryption routines are
* MBEDTLS_AES_ROM_TABLES in order to help the linker garbage-collect the AES * currently named mbedtls_aes_internal_encrypt and mbedtls_aes_internal_decrypt,
* tables. * respectively. When setting up alternative implementations, these functions should
* be overriden, but the wrapper functions mbedtls_aes_decrypt and mbedtls_aes_encrypt
* must stay untouched.
*
* \note If you use the AES_xxx_ALT macros, then is is recommended to also set
* MBEDTLS_AES_ROM_TABLES in order to help the linker garbage-collect the AES
* tables.
* *
* Uncomment a macro to enable alternate implementation of the corresponding * Uncomment a macro to enable alternate implementation of the corresponding
* function. * function.
@ -294,6 +333,11 @@
//#define MBEDTLS_AES_SETKEY_DEC_ALT //#define MBEDTLS_AES_SETKEY_DEC_ALT
//#define MBEDTLS_AES_ENCRYPT_ALT //#define MBEDTLS_AES_ENCRYPT_ALT
//#define MBEDTLS_AES_DECRYPT_ALT //#define MBEDTLS_AES_DECRYPT_ALT
//#define MBEDTLS_ECDH_GEN_PUBLIC_ALT
//#define MBEDTLS_ECDH_COMPUTE_SHARED_ALT
//#define MBEDTLS_ECDSA_VERIFY_ALT
//#define MBEDTLS_ECDSA_SIGN_ALT
//#define MBEDTLS_ECDSA_GENKEY_ALT
/** /**
* \def MBEDTLS_ECP_INTERNAL_ALT * \def MBEDTLS_ECP_INTERNAL_ALT
@ -1120,6 +1164,13 @@
* misuse/misunderstand. * misuse/misunderstand.
* *
* Comment this to disable support for renegotiation. * Comment this to disable support for renegotiation.
*
* \note Even if this option is disabled, both client and server are aware
* of the Renegotiation Indication Extension (RFC 5746) used to
* prevent the SSL renegotiation attack (see RFC 5746 Sect. 1).
* (See \c mbedtls_ssl_conf_legacy_renegotiation for the
* configuration of this extension).
*
*/ */
#define MBEDTLS_SSL_RENEGOTIATION #define MBEDTLS_SSL_RENEGOTIATION
@ -1614,6 +1665,7 @@
* library/ecp.c * library/ecp.c
* library/ecdsa.c * library/ecdsa.c
* library/rsa.c * library/rsa.c
* library/rsa_internal.c
* library/ssl_tls.c * library/ssl_tls.c
* *
* This module is required for RSA, DHM and ECC (ECDH, ECDSA) support. * This module is required for RSA, DHM and ECC (ECDH, ECDSA) support.
@ -2227,6 +2279,7 @@
* Enable the RSA public-key cryptosystem. * Enable the RSA public-key cryptosystem.
* *
* Module: library/rsa.c * Module: library/rsa.c
* library/rsa_internal.c
* Caller: library/ssl_cli.c * Caller: library/ssl_cli.c
* library/ssl_srv.c * library/ssl_srv.c
* library/ssl_tls.c * library/ssl_tls.c

View file

@ -461,7 +461,7 @@ int mbedtls_ecp_tls_write_point( const mbedtls_ecp_group *grp, const mbedtls_ecp
* \brief Set a group using well-known domain parameters * \brief Set a group using well-known domain parameters
* *
* \param grp Destination group * \param grp Destination group
* \param index Index in the list of well-known domain parameters * \param id Index in the list of well-known domain parameters
* *
* \return 0 if successful, * \return 0 if successful,
* MBEDTLS_ERR_MPI_XXX if initialization failed * MBEDTLS_ERR_MPI_XXX if initialization failed
@ -470,7 +470,7 @@ int mbedtls_ecp_tls_write_point( const mbedtls_ecp_group *grp, const mbedtls_ecp
* \note Index should be a value of RFC 4492's enum NamedCurve, * \note Index should be a value of RFC 4492's enum NamedCurve,
* usually in the form of a MBEDTLS_ECP_DP_XXX macro. * usually in the form of a MBEDTLS_ECP_DP_XXX macro.
*/ */
int mbedtls_ecp_group_load( mbedtls_ecp_group *grp, mbedtls_ecp_group_id index ); int mbedtls_ecp_group_load( mbedtls_ecp_group *grp, mbedtls_ecp_group_id id );
/** /**
* \brief Set a group from a TLS ECParameters record * \brief Set a group from a TLS ECParameters record

View file

@ -52,7 +52,7 @@
* GCM 2 0x0012-0x0014 * GCM 2 0x0012-0x0014
* BLOWFISH 2 0x0016-0x0018 * BLOWFISH 2 0x0016-0x0018
* THREADING 3 0x001A-0x001E * THREADING 3 0x001A-0x001E
* AES 2 0x0020-0x0022 * AES 2 0x0020-0x0022 0x0023-0x0023
* CAMELLIA 2 0x0024-0x0026 * CAMELLIA 2 0x0024-0x0026
* XTEA 1 0x0028-0x0028 * XTEA 1 0x0028-0x0028
* BASE64 2 0x002A-0x002C * BASE64 2 0x002A-0x002C
@ -71,11 +71,11 @@
* Name ID Nr of Errors * Name ID Nr of Errors
* PEM 1 9 * PEM 1 9
* PKCS#12 1 4 (Started from top) * PKCS#12 1 4 (Started from top)
* X509 2 19 * X509 2 20
* PKCS5 2 4 (Started from top) * PKCS5 2 4 (Started from top)
* DHM 3 9 * DHM 3 9
* PK 3 14 (Started from top) * PK 3 14 (Started from top)
* RSA 4 9 * RSA 4 10
* ECP 4 8 (Started from top) * ECP 4 8 (Started from top)
* MD 5 4 * MD 5 4
* CIPHER 6 6 * CIPHER 6 6

View file

@ -33,6 +33,8 @@
#define MBEDTLS_ERR_GCM_AUTH_FAILED -0x0012 /**< Authenticated decryption failed. */ #define MBEDTLS_ERR_GCM_AUTH_FAILED -0x0012 /**< Authenticated decryption failed. */
#define MBEDTLS_ERR_GCM_BAD_INPUT -0x0014 /**< Bad input parameters to function. */ #define MBEDTLS_ERR_GCM_BAD_INPUT -0x0014 /**< Bad input parameters to function. */
#if !defined(MBEDTLS_GCM_ALT)
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
@ -206,6 +208,18 @@ int mbedtls_gcm_finish( mbedtls_gcm_context *ctx,
*/ */
void mbedtls_gcm_free( mbedtls_gcm_context *ctx ); void mbedtls_gcm_free( mbedtls_gcm_context *ctx );
#ifdef __cplusplus
}
#endif
#else /* !MBEDTLS_GCM_ALT */
#include "gcm_alt.h"
#endif /* !MBEDTLS_GCM_ALT */
#ifdef __cplusplus
extern "C" {
#endif
/** /**
* \brief Checkup routine * \brief Checkup routine
* *
@ -217,4 +231,5 @@ int mbedtls_gcm_self_test( int verbose );
} }
#endif #endif
#endif /* gcm.h */ #endif /* gcm.h */

View file

@ -27,6 +27,12 @@
#include <stddef.h> #include <stddef.h>
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#define MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE -0x5080 /**< The selected feature is not available. */ #define MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE -0x5080 /**< The selected feature is not available. */
#define MBEDTLS_ERR_MD_BAD_INPUT_DATA -0x5100 /**< Bad input parameters to function. */ #define MBEDTLS_ERR_MD_BAD_INPUT_DATA -0x5100 /**< Bad input parameters to function. */
#define MBEDTLS_ERR_MD_ALLOC_FAILED -0x5180 /**< Failed to allocate memory. */ #define MBEDTLS_ERR_MD_ALLOC_FAILED -0x5180 /**< Failed to allocate memory. */

View file

@ -288,6 +288,54 @@ int mbedtls_platform_set_nv_seed(
#endif /* MBEDTLS_PLATFORM_NV_SEED_ALT */ #endif /* MBEDTLS_PLATFORM_NV_SEED_ALT */
#endif /* MBEDTLS_ENTROPY_NV_SEED */ #endif /* MBEDTLS_ENTROPY_NV_SEED */
#if !defined(MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT)
/**
* \brief Platform context structure
*
* \note This structure may be used to assist platform-specific
* setup/teardown operations.
*/
typedef struct {
char dummy; /**< Placeholder member as empty structs are not portable */
}
mbedtls_platform_context;
#else
#include "platform_alt.h"
#endif /* !MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */
/**
* \brief Perform any platform initialisation operations
*
* \param ctx mbed TLS context
*
* \return 0 if successful
*
* \note This function is intended to allow platform specific initialisation,
* and should be called before any other library functions. Its
* implementation is platform specific, and by default, unless platform
* specific code is provided, it does nothing.
*
* Its use and whether its necessary to be called is dependent on the
* platform.
*/
int mbedtls_platform_setup( mbedtls_platform_context *ctx );
/**
* \brief Perform any platform teardown operations
*
* \param ctx mbed TLS context
*
* \note This function should be called after every other mbed TLS module has
* been correctly freed using the appropriate free function.
* Its implementation is platform specific, and by default, unless
* platform specific code is provided, it does nothing.
*
* Its use and whether its necessary to be called is dependent on the
* platform.
*/
void mbedtls_platform_teardown( mbedtls_platform_context *ctx );
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif

View file

@ -48,6 +48,7 @@
#define MBEDTLS_ERR_RSA_VERIFY_FAILED -0x4380 /**< The PKCS#1 verification failed. */ #define MBEDTLS_ERR_RSA_VERIFY_FAILED -0x4380 /**< The PKCS#1 verification failed. */
#define MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE -0x4400 /**< The output buffer for decryption is not large enough. */ #define MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE -0x4400 /**< The output buffer for decryption is not large enough. */
#define MBEDTLS_ERR_RSA_RNG_FAILED -0x4480 /**< The random generator failed to generate non-zeros. */ #define MBEDTLS_ERR_RSA_RNG_FAILED -0x4480 /**< The random generator failed to generate non-zeros. */
#define MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION -0x4500 /**< The implementation doesn't offer the requested operation, e.g. because of security violations or lack of functionality */
/* /*
* RSA constants * RSA constants
@ -67,14 +68,23 @@
* The above constants may be used even if the RSA module is compile out, * The above constants may be used even if the RSA module is compile out,
* eg for alternative (PKCS#11) RSA implemenations in the PK layers. * eg for alternative (PKCS#11) RSA implemenations in the PK layers.
*/ */
#if defined(MBEDTLS_RSA_C)
#if !defined(MBEDTLS_RSA_ALT)
// Regular implementation
//
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
/** /**
* \brief RSA context structure * \brief RSA context structure
*
* \note Direct manipulation of the members of this structure
* is deprecated and will no longer be supported starting
* from the next major release. All manipulation should instead
* be done through the public interface functions.
*
*/ */
typedef struct typedef struct
{ {
@ -87,19 +97,21 @@ typedef struct
mbedtls_mpi D; /*!< private exponent */ mbedtls_mpi D; /*!< private exponent */
mbedtls_mpi P; /*!< 1st prime factor */ mbedtls_mpi P; /*!< 1st prime factor */
mbedtls_mpi Q; /*!< 2nd prime factor */ mbedtls_mpi Q; /*!< 2nd prime factor */
mbedtls_mpi DP; /*!< D % (P - 1) */ mbedtls_mpi DP; /*!< D % (P - 1) */
mbedtls_mpi DQ; /*!< D % (Q - 1) */ mbedtls_mpi DQ; /*!< D % (Q - 1) */
mbedtls_mpi QP; /*!< 1 / (Q % P) */ mbedtls_mpi QP; /*!< 1 / (Q % P) */
mbedtls_mpi RN; /*!< cached R^2 mod N */ mbedtls_mpi RN; /*!< cached R^2 mod N */
mbedtls_mpi RP; /*!< cached R^2 mod P */ mbedtls_mpi RP; /*!< cached R^2 mod P */
mbedtls_mpi RQ; /*!< cached R^2 mod Q */ mbedtls_mpi RQ; /*!< cached R^2 mod Q */
mbedtls_mpi Vi; /*!< cached blinding value */ mbedtls_mpi Vi; /*!< cached blinding value */
mbedtls_mpi Vf; /*!< cached un-blinding value */ mbedtls_mpi Vf; /*!< cached un-blinding value */
int padding; /*!< MBEDTLS_RSA_PKCS_V15 for 1.5 padding and int padding; /*!< \c MBEDTLS_RSA_PKCS_V15 for 1.5 padding and
MBEDTLS_RSA_PKCS_v21 for OAEP/PSS */ \c MBEDTLS_RSA_PKCS_v21 for OAEP/PSS */
int hash_id; /*!< Hash identifier of mbedtls_md_type_t as int hash_id; /*!< Hash identifier of mbedtls_md_type_t as
specified in the mbedtls_md.h header file specified in the mbedtls_md.h header file
for the EME-OAEP and EMSA-PSS for the EME-OAEP and EMSA-PSS
@ -113,15 +125,15 @@ mbedtls_rsa_context;
/** /**
* \brief Initialize an RSA context * \brief Initialize an RSA context
* *
* Note: Set padding to MBEDTLS_RSA_PKCS_V21 for the RSAES-OAEP * Note: Set padding to \c MBEDTLS_RSA_PKCS_V21 for the RSAES-OAEP
* encryption scheme and the RSASSA-PSS signature scheme. * encryption scheme and the RSASSA-PSS signature scheme.
* *
* \param ctx RSA context to be initialized * \param ctx RSA context to be initialized
* \param padding MBEDTLS_RSA_PKCS_V15 or MBEDTLS_RSA_PKCS_V21 * \param padding \c MBEDTLS_RSA_PKCS_V15 or \c MBEDTLS_RSA_PKCS_V21
* \param hash_id MBEDTLS_RSA_PKCS_V21 hash identifier * \param hash_id \c MBEDTLS_RSA_PKCS_V21 hash identifier
* *
* \note The hash_id parameter is actually ignored * \note The hash_id parameter is actually ignored
* when using MBEDTLS_RSA_PKCS_V15 padding. * when using \c MBEDTLS_RSA_PKCS_V15 padding.
* *
* \note Choice of padding mode is strictly enforced for private key * \note Choice of padding mode is strictly enforced for private key
* operations, since there might be security concerns in * operations, since there might be security concerns in
@ -132,21 +144,241 @@ mbedtls_rsa_context;
* \note The chosen hash is always used for OEAP encryption. * \note The chosen hash is always used for OEAP encryption.
* For PSS signatures, it's always used for making signatures, * For PSS signatures, it's always used for making signatures,
* but can be overriden (and always is, if set to * but can be overriden (and always is, if set to
* MBEDTLS_MD_NONE) for verifying them. * \c MBEDTLS_MD_NONE) for verifying them.
*/ */
void mbedtls_rsa_init( mbedtls_rsa_context *ctx, void mbedtls_rsa_init( mbedtls_rsa_context *ctx,
int padding, int padding,
int hash_id); int hash_id);
/**
* \brief Import a set of core parameters into an RSA context
*
* \param ctx Initialized RSA context to store parameters
* \param N RSA modulus, or NULL
* \param P First prime factor of N, or NULL
* \param Q Second prime factor of N, or NULL
* \param D Private exponent, or NULL
* \param E Public exponent, or NULL
*
* \note This function can be called multiple times for successive
* imports if the parameters are not simultaneously present.
* Any sequence of calls to this function should be followed
* by a call to \c mbedtls_rsa_complete which will check
* and complete the provided information to a ready-for-use
* public or private RSA key.
*
* \note See the documentation of \c mbedtls_rsa_complete for more
* information on which parameters are necessary to setup
* a private or public RSA key.
*
* \note The imported parameters are copied and need not be preserved
* for the lifetime of the RSA context being set up.
*
* \return 0 if successful, non-zero error code on failure.
*/
int mbedtls_rsa_import( mbedtls_rsa_context *ctx,
const mbedtls_mpi *N,
const mbedtls_mpi *P, const mbedtls_mpi *Q,
const mbedtls_mpi *D, const mbedtls_mpi *E );
/**
* \brief Import core RSA parameters in raw big-endian
* binary format into an RSA context
*
* \param ctx Initialized RSA context to store parameters
* \param N RSA modulus, or NULL
* \param N_len Byte length of N, ignored if N == NULL
* \param P First prime factor of N, or NULL
* \param P_len Byte length of P, ignored if P == NULL
* \param Q Second prime factor of N, or NULL
* \param Q_len Byte length of Q, ignored if Q == NULL
* \param D Private exponent, or NULL
* \param D_len Byte length of D, ignored if D == NULL
* \param E Public exponent, or NULL
* \param E_len Byte length of E, ignored if E == NULL
*
* \note This function can be called multiple times for successive
* imports if the parameters are not simultaneously present.
* Any sequence of calls to this function should be followed
* by a call to \c mbedtls_rsa_complete which will check
* and complete the provided information to a ready-for-use
* public or private RSA key.
*
* \note See the documentation of \c mbedtls_rsa_complete for more
* information on which parameters are necessary to setup
* a private or public RSA key.
*
* \note The imported parameters are copied and need not be preserved
* for the lifetime of the RSA context being set up.
*
* \return 0 if successful, non-zero error code on failure.
*/
int mbedtls_rsa_import_raw( mbedtls_rsa_context *ctx,
unsigned char const *N, size_t N_len,
unsigned char const *P, size_t P_len,
unsigned char const *Q, size_t Q_len,
unsigned char const *D, size_t D_len,
unsigned char const *E, size_t E_len );
/**
* \brief Attempt to complete an RSA context from
* a set of imported core parameters.
*
* \param ctx Initialized RSA context to store parameters
*
* \note
* - To setup an RSA public key, precisely N and E
* must have been imported.
*
* - To setup an RSA private key, enough information must be
* present for the other parameters to be derivable.
*
* The default implementation supports the following:
* - Derive P, Q from N, D, E
* - Derive N, D from P, Q, E.
*
* - Alternative implementations need not support these
* and may return \c MBEDTLS_ERR_RSA_BAD_INPUT_DATA instead.
*
* \return
* - 0 if successful. In this case, it is guaranteed
* that the RSA context can be used for RSA operations
* without the risk of failure or crash.
* - \c MBEDTLS_ERR_RSA_BAD_INPUT_DATA if the attempted
* derivations failed.
*
* \warning This function need not perform consistency checks
* for the imported parameters! In particular, parameters that
* are not needed by the implementation may be silently discarded
* and left unchecked. For the purpose of checking the consistency
* of the key material, see \c mbedtls_rsa_check_privkey.
*
*/
int mbedtls_rsa_complete( mbedtls_rsa_context *ctx );
/**
* \brief Export core parameters of an RSA key
*
* \param ctx Initialized RSA context
* \param N MPI to hold the RSA modulus, or NULL
* \param P MPI to hold the first prime factor of N, or NULL
* \param Q MPI to hold the second prime factor of N, or NULL
* \param D MPI to hold the private exponent, or NULL
* \param E MPI to hold the public exponent, or NULL
*
* \return
* - 0 if successful. In this case, the non-NULL buffers
* pointed to by N, P, Q, D, E are fully written, with
* additional unused space filled leading by 0-bytes.
* - Non-zero return code otherwise. In particular, if
* exporting the requested parameters
* cannot be done because of a lack of functionality
* or because of security policies, the error code
* \c MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION is returned.
* In this case, the RSA context stays intact and can
* be continued to be used.
*
* \note Reasons for returning \c MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION
* would be the following: Firstly, it might be that an
* alternative RSA implementation is in use which stores
* the key externally, and which either cannot or should not
* export it into RAM. Alternatively, an implementation
* (regardless of SW or HW) might not support deducing e.g.
* P, Q from N, D, E if the former are not part of the
* implementation.
*
*/
int mbedtls_rsa_export( const mbedtls_rsa_context *ctx,
mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q,
mbedtls_mpi *D, mbedtls_mpi *E );
/**
* \brief Export core parameters of an RSA key
* in raw big-endian binary format
*
* \param ctx Initialized RSA context
* \param N Byte array to store the RSA modulus, or NULL
* \param N_len Size of buffer for modulus
* \param P Byte array to hold the first prime factor of N, or NULL
* \param P_len Size of buffer for first prime factor
* \param Q Byte array to hold the second prime factor of N, or NULL
* \param Q_len Size of buffer for second prime factor
* \param D Byte array to hold the private exponent, or NULL
* \param D_len Size of buffer for private exponent
* \param E Byte array to hold the public exponent, or NULL
* \param E_len Size of buffer for public exponent
*
* \note The length fields are ignored if the corresponding
* buffer pointers are NULL.
*
* \return
* - 0 if successful. In this case, the non-NULL buffers
* pointed to by N, P, Q, D, E are fully written, with
* additional unused space filled leading by 0-bytes.
* - Non-zero return code otherwise. In particular, if
* exporting the requested parameters
* cannot be done because of a lack of functionality
* or because of security policies, the error code
* \c MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION is returned.
* In this case, the RSA context stays intact and can
* be continued to be used.
*
* \note Reasons for returning \c MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION
* would be the following: Firstly, it might be that an
* alternative RSA implementation is in use which stores
* the key externally, and which either cannot or should not
* export it into RAM. Alternatively, an implementation
* (regardless of SW or HW) might not support deducing e.g.
* P, Q from N, D, E if the former are not part of the
* implementation.
*
*
*/
int mbedtls_rsa_export_raw( const mbedtls_rsa_context *ctx,
unsigned char *N, size_t N_len,
unsigned char *P, size_t P_len,
unsigned char *Q, size_t Q_len,
unsigned char *D, size_t D_len,
unsigned char *E, size_t E_len );
/**
* \brief Export CRT parameters of a private RSA key
*
* \param ctx Initialized RSA context
* \param DP MPI to hold D modulo P-1, or NULL
* \param DQ MPI to hold D modulo Q-1, or NULL
* \param QP MPI to hold modular inverse of Q modulo P, or NULL
*
* \return 0 if successful, non-zero error code otherwise.
*
* \note Alternative RSA implementations not using CRT-parameters
* internally can implement this function using based on
* \c mbedtls_rsa_deduce_opt.
*
*/
int mbedtls_rsa_export_crt( const mbedtls_rsa_context *ctx,
mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP );
/** /**
* \brief Set padding for an already initialized RSA context * \brief Set padding for an already initialized RSA context
* See \c mbedtls_rsa_init() for details. * See \c mbedtls_rsa_init() for details.
* *
* \param ctx RSA context to be set * \param ctx RSA context to be set
* \param padding MBEDTLS_RSA_PKCS_V15 or MBEDTLS_RSA_PKCS_V21 * \param padding \c MBEDTLS_RSA_PKCS_V15 or \c MBEDTLS_RSA_PKCS_V21
* \param hash_id MBEDTLS_RSA_PKCS_V21 hash identifier * \param hash_id \c MBEDTLS_RSA_PKCS_V21 hash identifier
*/ */
void mbedtls_rsa_set_padding( mbedtls_rsa_context *ctx, int padding, int hash_id); void mbedtls_rsa_set_padding( mbedtls_rsa_context *ctx, int padding,
int hash_id);
/**
* \brief Get length of RSA modulus in bytes
*
* \param ctx Initialized RSA context
*
* \return Length of RSA modulus, in bytes.
*
*/
size_t mbedtls_rsa_get_len( const mbedtls_rsa_context *ctx );
/** /**
* \brief Generate an RSA keypair * \brief Generate an RSA keypair
@ -160,28 +392,61 @@ void mbedtls_rsa_set_padding( mbedtls_rsa_context *ctx, int padding, int hash_id
* \note mbedtls_rsa_init() must be called beforehand to setup * \note mbedtls_rsa_init() must be called beforehand to setup
* the RSA context. * the RSA context.
* *
* \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code * \return 0 if successful, or an \c MBEDTLS_ERR_RSA_XXX error code
*/ */
int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx, int mbedtls_rsa_gen_key( mbedtls_rsa_context *ctx,
int (*f_rng)(void *, unsigned char *, size_t), int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng, void *p_rng,
unsigned int nbits, int exponent ); unsigned int nbits, int exponent );
/** /**
* \brief Check a public RSA key * \brief Check if a context contains (at least) an RSA public key
* *
* \param ctx RSA context to be checked * \param ctx RSA context to be checked
* *
* \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code * \return 0 if successful, or an \c MBEDTLS_ERR_RSA_XXX error code.
* On success, it is guaranteed that enough information is
* present to perform an RSA public key operation
* \c mbedtls_rsa_public.
*
*/ */
int mbedtls_rsa_check_pubkey( const mbedtls_rsa_context *ctx ); int mbedtls_rsa_check_pubkey( const mbedtls_rsa_context *ctx );
/** /**
* \brief Check a private RSA key * \brief Check if a context contains an RSA private key
* and perform basic consistency checks.
* *
* \param ctx RSA context to be checked * \param ctx RSA context to be checked
*
* \return 0 if successful, or an \c MBEDTLS_ERR_RSA_XXX error code.
*
* \note The consistency checks performed by this function not only
* ensure that \c mbedtls_rsa_private can be called successfully
* on the given context, but that the various parameters are
* mutually consistent with high probability, in the sense that
* \c mbedtls_rsa_public and \c mbedtls_rsa_private are inverses.
*
* \warning This function should catch accidental misconfigurations
* like swapping of parameters, but it cannot establish full
* trust in neither the quality nor the consistency of the key
* material that was used to setup the given RSA context:
* - Regarding consistency, note (see \c mbedtls_rsa_complete)
* that imported parameters irrelevant for the implementation
* might be silently dropped, in which case the present
* function doesn't have access to and hence cannot check them.
* If you want to check the consistency of the entire
* content of, say, an PKCS1-encoded RSA private key, you
* should use \c mbedtls_rsa_validate_params before setting
* up the RSA context.
* Further, if the implementation performs empirical checks,
* these checks will substantiate but not guarantee consistency.
* - Regarding quality, this function is not expected to perform
* extended quality assessments like checking that the prime
* factors are safe. Further, it is the user's responsibility to
* ensure trustworthiness of the source of his RSA parameters,
* a question going beyond what's effectively checkable
* by the library.
* *
* \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code
*/ */
int mbedtls_rsa_check_privkey( const mbedtls_rsa_context *ctx ); int mbedtls_rsa_check_privkey( const mbedtls_rsa_context *ctx );
@ -192,9 +457,10 @@ int mbedtls_rsa_check_privkey( const mbedtls_rsa_context *ctx );
* \param pub RSA context holding the public key * \param pub RSA context holding the public key
* \param prv RSA context holding the private key * \param prv RSA context holding the private key
* *
* \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code * \return 0 if successful, or an \c MBEDTLS_ERR_RSA_XXX error code
*/ */
int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub, const mbedtls_rsa_context *prv ); int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub,
const mbedtls_rsa_context *prv );
/** /**
* \brief Do an RSA public key operation * \brief Do an RSA public key operation
@ -203,7 +469,7 @@ int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub, const mbedtls_rs
* \param input input buffer * \param input input buffer
* \param output output buffer * \param output output buffer
* *
* \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code * \return 0 if successful, or an \c MBEDTLS_ERR_RSA_XXX error code
* *
* \note This function does NOT take care of message * \note This function does NOT take care of message
* padding. Also, be sure to set input[0] = 0 or ensure that * padding. Also, be sure to set input[0] = 0 or ensure that
@ -225,7 +491,7 @@ int mbedtls_rsa_public( mbedtls_rsa_context *ctx,
* \param input input buffer * \param input input buffer
* \param output output buffer * \param output output buffer
* *
* \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code * \return 0 if successful, or an \c MBEDTLS_ERR_RSA_XXX error code
* *
* \note The input and output buffers must be large * \note The input and output buffers must be large
* enough (eg. 128 bytes if RSA-1024 is used). * enough (eg. 128 bytes if RSA-1024 is used).
@ -243,14 +509,23 @@ int mbedtls_rsa_private( mbedtls_rsa_context *ctx,
* *
* \param ctx RSA context * \param ctx RSA context
* \param f_rng RNG function (Needed for padding and PKCS#1 v2.1 encoding * \param f_rng RNG function (Needed for padding and PKCS#1 v2.1 encoding
* and MBEDTLS_RSA_PRIVATE) * and \c MBEDTLS_RSA_PRIVATE)
* \param p_rng RNG parameter * \param p_rng RNG parameter
* \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE * \param mode \c MBEDTLS_RSA_PUBLIC or \c MBEDTLS_RSA_PRIVATE
* \param ilen contains the plaintext length * \param ilen contains the plaintext length
* \param input buffer holding the data to be encrypted * \param input buffer holding the data to be encrypted
* \param output buffer that will hold the ciphertext * \param output buffer that will hold the ciphertext
* *
* \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code * \deprecated It is deprecated and discouraged to call this function
* in mode MBEDTLS_RSA_PRIVATE. Future versions of the libary
* are likely to remove the mode argument and have it implicitly
* set to MBEDTLS_RSA_PUBLIC.
*
* \note Alternative implementations of RSA need not support
* mode being set to MBEDTLS_RSA_PRIVATE and may instead
* return MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.
*
* \return 0 if successful, or an \c MBEDTLS_ERR_RSA_XXX error code
* *
* \note The output buffer must be as large as the size * \note The output buffer must be as large as the size
* of ctx->N (eg. 128 bytes if RSA-1024 is used). * of ctx->N (eg. 128 bytes if RSA-1024 is used).
@ -266,14 +541,23 @@ int mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context *ctx,
* \brief Perform a PKCS#1 v1.5 encryption (RSAES-PKCS1-v1_5-ENCRYPT) * \brief Perform a PKCS#1 v1.5 encryption (RSAES-PKCS1-v1_5-ENCRYPT)
* *
* \param ctx RSA context * \param ctx RSA context
* \param f_rng RNG function (Needed for padding and MBEDTLS_RSA_PRIVATE) * \param f_rng RNG function (Needed for padding and \c MBEDTLS_RSA_PRIVATE)
* \param p_rng RNG parameter * \param p_rng RNG parameter
* \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE * \param mode \c MBEDTLS_RSA_PUBLIC or \c MBEDTLS_RSA_PRIVATE
* \param ilen contains the plaintext length * \param ilen contains the plaintext length
* \param input buffer holding the data to be encrypted * \param input buffer holding the data to be encrypted
* \param output buffer that will hold the ciphertext * \param output buffer that will hold the ciphertext
* *
* \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code * \deprecated It is deprecated and discouraged to call this function
* in mode MBEDTLS_RSA_PRIVATE. Future versions of the libary
* are likely to remove the mode argument and have it implicitly
* set to MBEDTLS_RSA_PUBLIC.
*
* \note Alternative implementations of RSA need not support
* mode being set to MBEDTLS_RSA_PRIVATE and may instead
* return MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.
*
* \return 0 if successful, or an \c MBEDTLS_ERR_RSA_XXX error code
* *
* \note The output buffer must be as large as the size * \note The output buffer must be as large as the size
* of ctx->N (eg. 128 bytes if RSA-1024 is used). * of ctx->N (eg. 128 bytes if RSA-1024 is used).
@ -290,16 +574,25 @@ int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx,
* *
* \param ctx RSA context * \param ctx RSA context
* \param f_rng RNG function (Needed for padding and PKCS#1 v2.1 encoding * \param f_rng RNG function (Needed for padding and PKCS#1 v2.1 encoding
* and MBEDTLS_RSA_PRIVATE) * and \c MBEDTLS_RSA_PRIVATE)
* \param p_rng RNG parameter * \param p_rng RNG parameter
* \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE * \param mode \c MBEDTLS_RSA_PUBLIC or \c MBEDTLS_RSA_PRIVATE
* \param label buffer holding the custom label to use * \param label buffer holding the custom label to use
* \param label_len contains the label length * \param label_len contains the label length
* \param ilen contains the plaintext length * \param ilen contains the plaintext length
* \param input buffer holding the data to be encrypted * \param input buffer holding the data to be encrypted
* \param output buffer that will hold the ciphertext * \param output buffer that will hold the ciphertext
* *
* \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code * \deprecated It is deprecated and discouraged to call this function
* in mode MBEDTLS_RSA_PRIVATE. Future versions of the libary
* are likely to remove the mode argument and have it implicitly
* set to MBEDTLS_RSA_PUBLIC.
*
* \note Alternative implementations of RSA need not support
* mode being set to MBEDTLS_RSA_PRIVATE and may instead
* return MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.
*
* \return 0 if successful, or an \c MBEDTLS_ERR_RSA_XXX error code
* *
* \note The output buffer must be as large as the size * \note The output buffer must be as large as the size
* of ctx->N (eg. 128 bytes if RSA-1024 is used). * of ctx->N (eg. 128 bytes if RSA-1024 is used).
@ -319,19 +612,34 @@ int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx,
* the message padding * the message padding
* *
* \param ctx RSA context * \param ctx RSA context
* \param f_rng RNG function (Only needed for MBEDTLS_RSA_PRIVATE) * \param f_rng RNG function (Only needed for \c MBEDTLS_RSA_PRIVATE)
* \param p_rng RNG parameter * \param p_rng RNG parameter
* \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE * \param mode \c MBEDTLS_RSA_PUBLIC or \c MBEDTLS_RSA_PRIVATE
* \param olen will contain the plaintext length * \param olen will contain the plaintext length
* \param input buffer holding the encrypted data * \param input buffer holding the encrypted data
* \param output buffer that will hold the plaintext * \param output buffer that will hold the plaintext
* \param output_max_len maximum length of the output buffer * \param output_max_len maximum length of the output buffer
* *
* \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code * \deprecated It is deprecated and discouraged to call this function
* in mode MBEDTLS_RSA_PUBLIC. Future versions of the libary
* are likely to remove the mode argument and have it implicitly
* set to MBEDTLS_RSA_PRIVATE.
* *
* \note The output buffer must be as large as the size * \note Alternative implementations of RSA need not support
* of ctx->N (eg. 128 bytes if RSA-1024 is used) otherwise * mode being set to MBEDTLS_RSA_PUBLIC and may instead
* an error is thrown. * return MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.
*
* \return 0 if successful, or an \c MBEDTLS_ERR_RSA_XXX error code
*
* \note The output buffer length \c output_max_len should be
* as large as the size \c ctx->len of \c ctx->N (eg. 128 bytes
* if RSA-1024 is used) to be able to hold an arbitrary
* decrypted message. If it is not large enough to hold
* the decryption of the particular ciphertext provided,
* the function will return \c MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE.
*
* \note The input buffer must be as large as the size
* of \c ctx->N (eg. 128 bytes if RSA-1024 is used).
*/ */
int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx, int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx,
int (*f_rng)(void *, unsigned char *, size_t), int (*f_rng)(void *, unsigned char *, size_t),
@ -345,19 +653,34 @@ int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx,
* \brief Perform a PKCS#1 v1.5 decryption (RSAES-PKCS1-v1_5-DECRYPT) * \brief Perform a PKCS#1 v1.5 decryption (RSAES-PKCS1-v1_5-DECRYPT)
* *
* \param ctx RSA context * \param ctx RSA context
* \param f_rng RNG function (Only needed for MBEDTLS_RSA_PRIVATE) * \param f_rng RNG function (Only needed for \c MBEDTLS_RSA_PRIVATE)
* \param p_rng RNG parameter * \param p_rng RNG parameter
* \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE * \param mode \c MBEDTLS_RSA_PUBLIC or \c MBEDTLS_RSA_PRIVATE
* \param olen will contain the plaintext length * \param olen will contain the plaintext length
* \param input buffer holding the encrypted data * \param input buffer holding the encrypted data
* \param output buffer that will hold the plaintext * \param output buffer that will hold the plaintext
* \param output_max_len maximum length of the output buffer * \param output_max_len maximum length of the output buffer
* *
* \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code * \deprecated It is deprecated and discouraged to call this function
* in mode MBEDTLS_RSA_PUBLIC. Future versions of the libary
* are likely to remove the mode argument and have it implicitly
* set to MBEDTLS_RSA_PRIVATE.
* *
* \note The output buffer must be as large as the size * \note Alternative implementations of RSA need not support
* of ctx->N (eg. 128 bytes if RSA-1024 is used) otherwise * mode being set to MBEDTLS_RSA_PUBLIC and may instead
* an error is thrown. * return MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.
*
* \return 0 if successful, or an \c MBEDTLS_ERR_RSA_XXX error code
*
* \note The output buffer length \c output_max_len should be
* as large as the size \c ctx->len of \c ctx->N (eg. 128 bytes
* if RSA-1024 is used) to be able to hold an arbitrary
* decrypted message. If it is not large enough to hold
* the decryption of the particular ciphertext provided,
* the function will return \c MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE.
*
* \note The input buffer must be as large as the size
* of \c ctx->N (eg. 128 bytes if RSA-1024 is used).
*/ */
int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx, int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx,
int (*f_rng)(void *, unsigned char *, size_t), int (*f_rng)(void *, unsigned char *, size_t),
@ -371,9 +694,9 @@ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx,
* \brief Perform a PKCS#1 v2.1 OAEP decryption (RSAES-OAEP-DECRYPT) * \brief Perform a PKCS#1 v2.1 OAEP decryption (RSAES-OAEP-DECRYPT)
* *
* \param ctx RSA context * \param ctx RSA context
* \param f_rng RNG function (Only needed for MBEDTLS_RSA_PRIVATE) * \param f_rng RNG function (Only needed for \c MBEDTLS_RSA_PRIVATE)
* \param p_rng RNG parameter * \param p_rng RNG parameter
* \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE * \param mode \c MBEDTLS_RSA_PUBLIC or \c MBEDTLS_RSA_PRIVATE
* \param label buffer holding the custom label to use * \param label buffer holding the custom label to use
* \param label_len contains the label length * \param label_len contains the label length
* \param olen will contain the plaintext length * \param olen will contain the plaintext length
@ -381,11 +704,27 @@ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx,
* \param output buffer that will hold the plaintext * \param output buffer that will hold the plaintext
* \param output_max_len maximum length of the output buffer * \param output_max_len maximum length of the output buffer
* *
* \return 0 if successful, or an MBEDTLS_ERR_RSA_XXX error code * \deprecated It is deprecated and discouraged to call this function
* in mode MBEDTLS_RSA_PUBLIC. Future versions of the libary
* are likely to remove the mode argument and have it implicitly
* set to MBEDTLS_RSA_PRIVATE.
*
* \note Alternative implementations of RSA need not support
* mode being set to MBEDTLS_RSA_PUBLIC and may instead
* return MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.
*
* \return 0 if successful, or an \c MBEDTLS_ERR_RSA_XXX error code
*
* \note The output buffer length \c output_max_len should be
* as large as the size \c ctx->len of \c ctx->N (eg. 128 bytes
* if RSA-1024 is used) to be able to hold an arbitrary
* decrypted message. If it is not large enough to hold
* the decryption of the particular ciphertext provided,
* the function will return \c MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE.
*
* \note The input buffer must be as large as the size
* of \c ctx->N (eg. 128 bytes if RSA-1024 is used).
* *
* \note The output buffer must be as large as the size
* of ctx->N (eg. 128 bytes if RSA-1024 is used) otherwise
* an error is thrown.
*/ */
int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx, int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx,
int (*f_rng)(void *, unsigned char *, size_t), int (*f_rng)(void *, unsigned char *, size_t),
@ -404,22 +743,33 @@ int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx,
* *
* \param ctx RSA context * \param ctx RSA context
* \param f_rng RNG function (Needed for PKCS#1 v2.1 encoding and for * \param f_rng RNG function (Needed for PKCS#1 v2.1 encoding and for
* MBEDTLS_RSA_PRIVATE) * \c MBEDTLS_RSA_PRIVATE)
* \param p_rng RNG parameter * \param p_rng RNG parameter
* \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE * \param mode \c MBEDTLS_RSA_PUBLIC or \c MBEDTLS_RSA_PRIVATE
* \param md_alg a MBEDTLS_MD_XXX (use MBEDTLS_MD_NONE for signing raw data) * \param md_alg a \c MBEDTLS_MD_XXX (use \c MBEDTLS_MD_NONE for
* \param hashlen message digest length (for MBEDTLS_MD_NONE only) * signing raw data)
* \param hashlen message digest length (for \c MBEDTLS_MD_NONE only)
* \param hash buffer holding the message digest * \param hash buffer holding the message digest
* \param sig buffer that will hold the ciphertext * \param sig buffer that will hold the ciphertext
* *
* \return 0 if the signing operation was successful, * \deprecated It is deprecated and discouraged to call this function
* or an MBEDTLS_ERR_RSA_XXX error code * in mode MBEDTLS_RSA_PUBLIC. Future versions of the libary
* are likely to remove the mode argument and have it implicitly
* set to MBEDTLS_RSA_PRIVATE.
* *
* \note The "sig" buffer must be as large as the size * \note Alternative implementations of RSA need not support
* of ctx->N (eg. 128 bytes if RSA-1024 is used). * mode being set to MBEDTLS_RSA_PUBLIC and may instead
* return MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.
*
* \return 0 if the signing operation was successful,
* or an \c MBEDTLS_ERR_RSA_XXX error code
*
* \note The \c sig buffer must be as large as the size
* of \c ctx->N (eg. 128 bytes if RSA-1024 is used).
* *
* \note In case of PKCS#1 v2.1 encoding, see comments on * \note In case of PKCS#1 v2.1 encoding, see comments on
* \note \c mbedtls_rsa_rsassa_pss_sign() for details on md_alg and hash_id. * \c mbedtls_rsa_rsassa_pss_sign() for details on
* \c md_alg and \c hash_id.
*/ */
int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx, int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx,
int (*f_rng)(void *, unsigned char *, size_t), int (*f_rng)(void *, unsigned char *, size_t),
@ -434,19 +784,29 @@ int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx,
* \brief Perform a PKCS#1 v1.5 signature (RSASSA-PKCS1-v1_5-SIGN) * \brief Perform a PKCS#1 v1.5 signature (RSASSA-PKCS1-v1_5-SIGN)
* *
* \param ctx RSA context * \param ctx RSA context
* \param f_rng RNG function (Only needed for MBEDTLS_RSA_PRIVATE) * \param f_rng RNG function (Only needed for \c MBEDTLS_RSA_PRIVATE)
* \param p_rng RNG parameter * \param p_rng RNG parameter
* \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE * \param mode \c MBEDTLS_RSA_PUBLIC or \c MBEDTLS_RSA_PRIVATE
* \param md_alg a MBEDTLS_MD_XXX (use MBEDTLS_MD_NONE for signing raw data) * \param md_alg a \c MBEDTLS_MD_XXX (use \c MBEDTLS_MD_NONE
* \param hashlen message digest length (for MBEDTLS_MD_NONE only) * for signing raw data)
* \param hashlen message digest length (for \c MBEDTLS_MD_NONE only)
* \param hash buffer holding the message digest * \param hash buffer holding the message digest
* \param sig buffer that will hold the ciphertext * \param sig buffer that will hold the ciphertext
* *
* \return 0 if the signing operation was successful, * \deprecated It is deprecated and discouraged to call this function
* or an MBEDTLS_ERR_RSA_XXX error code * in mode MBEDTLS_RSA_PUBLIC. Future versions of the libary
* are likely to remove the mode argument and have it implicitly
* set to MBEDTLS_RSA_PRIVATE.
* *
* \note The "sig" buffer must be as large as the size * \note Alternative implementations of RSA need not support
* of ctx->N (eg. 128 bytes if RSA-1024 is used). * mode being set to MBEDTLS_RSA_PUBLIC and may instead
* return MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.
*
* \return 0 if the signing operation was successful,
* or an \c MBEDTLS_ERR_RSA_XXX error code
*
* \note The \c sig buffer must be as large as the size
* of \c ctx->N (eg. 128 bytes if RSA-1024 is used).
*/ */
int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx, int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx,
int (*f_rng)(void *, unsigned char *, size_t), int (*f_rng)(void *, unsigned char *, size_t),
@ -462,22 +822,32 @@ int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx,
* *
* \param ctx RSA context * \param ctx RSA context
* \param f_rng RNG function (Needed for PKCS#1 v2.1 encoding and for * \param f_rng RNG function (Needed for PKCS#1 v2.1 encoding and for
* MBEDTLS_RSA_PRIVATE) * \c MBEDTLS_RSA_PRIVATE)
* \param p_rng RNG parameter * \param p_rng RNG parameter
* \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE * \param mode \c MBEDTLS_RSA_PUBLIC or \c MBEDTLS_RSA_PRIVATE
* \param md_alg a MBEDTLS_MD_XXX (use MBEDTLS_MD_NONE for signing raw data) * \param md_alg a \c MBEDTLS_MD_XXX (use \c MBEDTLS_MD_NONE
* \param hashlen message digest length (for MBEDTLS_MD_NONE only) * for signing raw data)
* \param hashlen message digest length (for \c MBEDTLS_MD_NONE only)
* \param hash buffer holding the message digest * \param hash buffer holding the message digest
* \param sig buffer that will hold the ciphertext * \param sig buffer that will hold the ciphertext
* *
* \deprecated It is deprecated and discouraged to call this function
* in mode MBEDTLS_RSA_PUBLIC. Future versions of the libary
* are likely to remove the mode argument and have it implicitly
* set to MBEDTLS_RSA_PRIVATE.
*
* \note Alternative implementations of RSA need not support
* mode being set to MBEDTLS_RSA_PUBLIC and may instead
* return MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.
*
* \return 0 if the signing operation was successful, * \return 0 if the signing operation was successful,
* or an MBEDTLS_ERR_RSA_XXX error code * or an \c MBEDTLS_ERR_RSA_XXX error code
* *
* \note The "sig" buffer must be as large as the size * \note The \c sig buffer must be as large as the size
* of ctx->N (eg. 128 bytes if RSA-1024 is used). * of \c ctx->N (eg. 128 bytes if RSA-1024 is used).
* *
* \note The hash_id in the RSA context is the one used for the * \note The \c hash_id in the RSA context is the one used for the
* encoding. md_alg in the function call is the type of hash * encoding. \c md_alg in the function call is the type of hash
* that is encoded. According to RFC 3447 it is advised to * that is encoded. According to RFC 3447 it is advised to
* keep both hashes the same. * keep both hashes the same.
*/ */
@ -496,19 +866,28 @@ int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx,
* the message digest * the message digest
* *
* \param ctx points to an RSA public key * \param ctx points to an RSA public key
* \param f_rng RNG function (Only needed for MBEDTLS_RSA_PRIVATE) * \param f_rng RNG function (Only needed for \c MBEDTLS_RSA_PRIVATE)
* \param p_rng RNG parameter * \param p_rng RNG parameter
* \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE * \param mode \c MBEDTLS_RSA_PUBLIC or \c MBEDTLS_RSA_PRIVATE
* \param md_alg a MBEDTLS_MD_XXX (use MBEDTLS_MD_NONE for signing raw data) * \param md_alg a \c MBEDTLS_MD_XXX (use \c MBEDTLS_MD_NONE for signing raw data)
* \param hashlen message digest length (for MBEDTLS_MD_NONE only) * \param hashlen message digest length (for \c MBEDTLS_MD_NONE only)
* \param hash buffer holding the message digest * \param hash buffer holding the message digest
* \param sig buffer holding the ciphertext * \param sig buffer holding the ciphertext
* *
* \return 0 if the verify operation was successful, * \deprecated It is deprecated and discouraged to call this function
* or an MBEDTLS_ERR_RSA_XXX error code * in mode MBEDTLS_RSA_PRIVATE. Future versions of the libary
* are likely to remove the mode argument and have it implicitly
* set to MBEDTLS_RSA_PUBLIC.
* *
* \note The "sig" buffer must be as large as the size * \note Alternative implementations of RSA need not support
* of ctx->N (eg. 128 bytes if RSA-1024 is used). * mode being set to MBEDTLS_RSA_PRIVATE and may instead
* return MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.
*
* \return 0 if the verify operation was successful,
* or an \c MBEDTLS_ERR_RSA_XXX error code
*
* \note The \c sig buffer must be as large as the size
* of \c ctx->N (eg. 128 bytes if RSA-1024 is used).
* *
* \note In case of PKCS#1 v2.1 encoding, see comments on * \note In case of PKCS#1 v2.1 encoding, see comments on
* \c mbedtls_rsa_rsassa_pss_verify() about md_alg and hash_id. * \c mbedtls_rsa_rsassa_pss_verify() about md_alg and hash_id.
@ -526,19 +905,29 @@ int mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx,
* \brief Perform a PKCS#1 v1.5 verification (RSASSA-PKCS1-v1_5-VERIFY) * \brief Perform a PKCS#1 v1.5 verification (RSASSA-PKCS1-v1_5-VERIFY)
* *
* \param ctx points to an RSA public key * \param ctx points to an RSA public key
* \param f_rng RNG function (Only needed for MBEDTLS_RSA_PRIVATE) * \param f_rng RNG function (Only needed for \c MBEDTLS_RSA_PRIVATE)
* \param p_rng RNG parameter * \param p_rng RNG parameter
* \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE * \param mode \c MBEDTLS_RSA_PUBLIC or \c MBEDTLS_RSA_PRIVATE
* \param md_alg a MBEDTLS_MD_XXX (use MBEDTLS_MD_NONE for signing raw data) * \param md_alg a \c MBEDTLS_MD_XXX (use \c MBEDTLS_MD_NONE
* \param hashlen message digest length (for MBEDTLS_MD_NONE only) * for signing raw data)
* \param hashlen message digest length (for \c MBEDTLS_MD_NONE only)
* \param hash buffer holding the message digest * \param hash buffer holding the message digest
* \param sig buffer holding the ciphertext * \param sig buffer holding the ciphertext
* *
* \return 0 if the verify operation was successful, * \deprecated It is deprecated and discouraged to call this function
* or an MBEDTLS_ERR_RSA_XXX error code * in mode MBEDTLS_RSA_PRIVATE. Future versions of the libary
* are likely to remove the mode argument and have it implicitly
* set to MBEDTLS_RSA_PUBLIC.
* *
* \note The "sig" buffer must be as large as the size * \note Alternative implementations of RSA need not support
* of ctx->N (eg. 128 bytes if RSA-1024 is used). * mode being set to MBEDTLS_RSA_PRIVATE and may instead
* return MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.
*
* \return 0 if the verify operation was successful,
* or an \c MBEDTLS_ERR_RSA_XXX error code
*
* \note The \c sig buffer must be as large as the size
* of \c ctx->N (eg. 128 bytes if RSA-1024 is used).
*/ */
int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx, int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx,
int (*f_rng)(void *, unsigned char *, size_t), int (*f_rng)(void *, unsigned char *, size_t),
@ -554,25 +943,34 @@ int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx,
* (This is the "simple" version.) * (This is the "simple" version.)
* *
* \param ctx points to an RSA public key * \param ctx points to an RSA public key
* \param f_rng RNG function (Only needed for MBEDTLS_RSA_PRIVATE) * \param f_rng RNG function (Only needed for \c MBEDTLS_RSA_PRIVATE)
* \param p_rng RNG parameter * \param p_rng RNG parameter
* \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE * \param mode \c MBEDTLS_RSA_PUBLIC or \c MBEDTLS_RSA_PRIVATE
* \param md_alg a MBEDTLS_MD_XXX (use MBEDTLS_MD_NONE for signing raw data) * \param md_alg a \c MBEDTLS_MD_XXX (use \c MBEDTLS_MD_NONE for signing raw data)
* \param hashlen message digest length (for MBEDTLS_MD_NONE only) * \param hashlen message digest length (for \c MBEDTLS_MD_NONE only)
* \param hash buffer holding the message digest * \param hash buffer holding the message digest
* \param sig buffer holding the ciphertext * \param sig buffer holding the ciphertext
* *
* \deprecated It is deprecated and discouraged to call this function
* in mode MBEDTLS_RSA_PRIVATE. Future versions of the libary
* are likely to remove the mode argument and have it implicitly
* set to MBEDTLS_RSA_PUBLIC.
*
* \note Alternative implementations of RSA need not support
* mode being set to MBEDTLS_RSA_PRIVATE and may instead
* return MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION.
*
* \return 0 if the verify operation was successful, * \return 0 if the verify operation was successful,
* or an MBEDTLS_ERR_RSA_XXX error code * or an \c MBEDTLS_ERR_RSA_XXX error code
* *
* \note The "sig" buffer must be as large as the size * \note The \c sig buffer must be as large as the size
* of ctx->N (eg. 128 bytes if RSA-1024 is used). * of \c ctx->N (eg. 128 bytes if RSA-1024 is used).
* *
* \note The hash_id in the RSA context is the one used for the * \note The \c hash_id in the RSA context is the one used for the
* verification. md_alg in the function call is the type of * verification. \c md_alg in the function call is the type of
* hash that is verified. According to RFC 3447 it is advised to * hash that is verified. According to RFC 3447 it is advised to
* keep both hashes the same. If hash_id in the RSA context is * keep both hashes the same. If \c hash_id in the RSA context is
* unset, the md_alg from the function call is used. * unset, the \c md_alg from the function call is used.
*/ */
int mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context *ctx, int mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context *ctx,
int (*f_rng)(void *, unsigned char *, size_t), int (*f_rng)(void *, unsigned char *, size_t),
@ -588,24 +986,24 @@ int mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context *ctx,
* (This is the version with "full" options.) * (This is the version with "full" options.)
* *
* \param ctx points to an RSA public key * \param ctx points to an RSA public key
* \param f_rng RNG function (Only needed for MBEDTLS_RSA_PRIVATE) * \param f_rng RNG function (Only needed for \c MBEDTLS_RSA_PRIVATE)
* \param p_rng RNG parameter * \param p_rng RNG parameter
* \param mode MBEDTLS_RSA_PUBLIC or MBEDTLS_RSA_PRIVATE * \param mode \c MBEDTLS_RSA_PUBLIC or \c MBEDTLS_RSA_PRIVATE
* \param md_alg a MBEDTLS_MD_XXX (use MBEDTLS_MD_NONE for signing raw data) * \param md_alg a \c MBEDTLS_MD_XXX (use \c MBEDTLS_MD_NONE for signing raw data)
* \param hashlen message digest length (for MBEDTLS_MD_NONE only) * \param hashlen message digest length (for \c MBEDTLS_MD_NONE only)
* \param hash buffer holding the message digest * \param hash buffer holding the message digest
* \param mgf1_hash_id message digest used for mask generation * \param mgf1_hash_id message digest used for mask generation
* \param expected_salt_len Length of the salt used in padding, use * \param expected_salt_len Length of the salt used in padding, use
* MBEDTLS_RSA_SALT_LEN_ANY to accept any salt length * \c MBEDTLS_RSA_SALT_LEN_ANY to accept any salt length
* \param sig buffer holding the ciphertext * \param sig buffer holding the ciphertext
* *
* \return 0 if the verify operation was successful, * \return 0 if the verify operation was successful,
* or an MBEDTLS_ERR_RSA_XXX error code * or an \c MBEDTLS_ERR_RSA_XXX error code
* *
* \note The "sig" buffer must be as large as the size * \note The \c sig buffer must be as large as the size
* of ctx->N (eg. 128 bytes if RSA-1024 is used). * of \c ctx->N (eg. 128 bytes if RSA-1024 is used).
* *
* \note The hash_id in the RSA context is ignored. * \note The \c hash_id in the RSA context is ignored.
*/ */
int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx, int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx,
int (*f_rng)(void *, unsigned char *, size_t), int (*f_rng)(void *, unsigned char *, size_t),
@ -625,7 +1023,7 @@ int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx,
* \param src Source context * \param src Source context
* *
* \return 0 on success, * \return 0 on success,
* MBEDTLS_ERR_MPI_ALLOC_FAILED on memory allocation failure * \c MBEDTLS_ERR_MPI_ALLOC_FAILED on memory allocation failure
*/ */
int mbedtls_rsa_copy( mbedtls_rsa_context *dst, const mbedtls_rsa_context *src ); int mbedtls_rsa_copy( mbedtls_rsa_context *dst, const mbedtls_rsa_context *src );
@ -636,6 +1034,18 @@ int mbedtls_rsa_copy( mbedtls_rsa_context *dst, const mbedtls_rsa_context *src )
*/ */
void mbedtls_rsa_free( mbedtls_rsa_context *ctx ); void mbedtls_rsa_free( mbedtls_rsa_context *ctx );
#ifdef __cplusplus
}
#endif
#else /* MBEDTLS_RSA_ALT */
#include "rsa_alt.h"
#endif /* MBEDTLS_RSA_ALT */
#ifdef __cplusplus
extern "C" {
#endif
/** /**
* \brief Checkup routine * \brief Checkup routine
* *
@ -647,6 +1057,4 @@ int mbedtls_rsa_self_test( int verbose );
} }
#endif #endif
#endif /* MBEDTLS_RSA_C */
#endif /* rsa.h */ #endif /* rsa.h */

View file

@ -0,0 +1,215 @@
/**
* \file rsa_internal.h
*
* \brief Context-independent RSA helper functions
*
* Copyright (C) 2006-2017, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*
*
* This file declares some RSA-related helper functions useful when
* implementing the RSA interface. They are public and provided in a
* separate compilation unit in order to make it easy for designers of
* alternative RSA implementations to use them in their code, as it is
* conceived that the functionality they provide will be necessary
* for most complete implementations.
*
* End-users of Mbed TLS not intending to re-implement the RSA functionality
* are not expected to get into the need of making use of these functions directly,
* but instead should be able to use the functions declared in rsa.h.
*
* There are two classes of helper functions:
* (1) Parameter-generating helpers. These are:
* - mbedtls_rsa_deduce_primes
* - mbedtls_rsa_deduce_private_exponent
* - mbedtls_rsa_deduce_crt
* Each of these functions takes a set of core RSA parameters
* and generates some other, or CRT related parameters.
* (2) Parameter-checking helpers. These are:
* - mbedtls_rsa_validate_params
* - mbedtls_rsa_validate_crt
* They take a set of core or CRT related RSA parameters
* and check their validity.
*
*/
#ifndef MBEDTLS_RSA_INTERNAL_H
#define MBEDTLS_RSA_INTERNAL_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include "bignum.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Compute RSA prime moduli P, Q from public modulus N=PQ
* and a pair of private and public key.
*
* \note This is a 'static' helper function not operating on
* an RSA context. Alternative implementations need not
* overwrite it.
*
* \param N RSA modulus N = PQ, with P, Q to be found
* \param E RSA public exponent
* \param D RSA private exponent
* \param P Pointer to MPI holding first prime factor of N on success
* \param Q Pointer to MPI holding second prime factor of N on success
*
* \return
* - 0 if successful. In this case, P and Q constitute a
* factorization of N.
* - A non-zero error code otherwise.
*
* \note It is neither checked that P, Q are prime nor that
* D, E are modular inverses wrt. P-1 and Q-1. For that,
* use the helper function \c mbedtls_rsa_validate_params.
*
*/
int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N, mbedtls_mpi const *E,
mbedtls_mpi const *D,
mbedtls_mpi *P, mbedtls_mpi *Q );
/**
* \brief Compute RSA private exponent from
* prime moduli and public key.
*
* \note This is a 'static' helper function not operating on
* an RSA context. Alternative implementations need not
* overwrite it.
*
* \param P First prime factor of RSA modulus
* \param Q Second prime factor of RSA modulus
* \param E RSA public exponent
* \param D Pointer to MPI holding the private exponent on success.
*
* \return
* - 0 if successful. In this case, D is set to a simultaneous
* modular inverse of E modulo both P-1 and Q-1.
* - A non-zero error code otherwise.
*
* \note This function does not check whether P and Q are primes.
*
*/
int mbedtls_rsa_deduce_private_exponent( mbedtls_mpi const *P,
mbedtls_mpi const *Q,
mbedtls_mpi const *E,
mbedtls_mpi *D );
/**
* \brief Generate RSA-CRT parameters
*
* \note This is a 'static' helper function not operating on
* an RSA context. Alternative implementations need not
* overwrite it.
*
* \param P First prime factor of N
* \param Q Second prime factor of N
* \param D RSA private exponent
* \param DP Output variable for D modulo P-1
* \param DQ Output variable for D modulo Q-1
* \param QP Output variable for the modular inverse of Q modulo P.
*
* \return 0 on success, non-zero error code otherwise.
*
* \note This function does not check whether P, Q are
* prime and whether D is a valid private exponent.
*
*/
int mbedtls_rsa_deduce_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q,
const mbedtls_mpi *D, mbedtls_mpi *DP,
mbedtls_mpi *DQ, mbedtls_mpi *QP );
/**
* \brief Check validity of core RSA parameters
*
* \note This is a 'static' helper function not operating on
* an RSA context. Alternative implementations need not
* overwrite it.
*
* \param N RSA modulus N = PQ
* \param P First prime factor of N
* \param Q Second prime factor of N
* \param D RSA private exponent
* \param E RSA public exponent
* \param f_rng PRNG to be used for primality check, or NULL
* \param p_rng PRNG context for f_rng, or NULL
*
* \return
* - 0 if the following conditions are satisfied
* if all relevant parameters are provided:
* - P prime if f_rng != NULL (%)
* - Q prime if f_rng != NULL (%)
* - 1 < N = P * Q
* - 1 < D, E < N
* - D and E are modular inverses modulo P-1 and Q-1
* (%) This is only done if MBEDTLS_GENPRIME is defined.
* - A non-zero error code otherwise.
*
* \note The function can be used with a restricted set of arguments
* to perform specific checks only. E.g., calling it with
* (-,P,-,-,-) and a PRNG amounts to a primality check for P.
*/
int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P,
const mbedtls_mpi *Q, const mbedtls_mpi *D,
const mbedtls_mpi *E,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
/**
* \brief Check validity of RSA CRT parameters
*
* \note This is a 'static' helper function not operating on
* an RSA context. Alternative implementations need not
* overwrite it.
*
* \param P First prime factor of RSA modulus
* \param Q Second prime factor of RSA modulus
* \param D RSA private exponent
* \param DP MPI to check for D modulo P-1
* \param DQ MPI to check for D modulo P-1
* \param QP MPI to check for the modular inverse of Q modulo P.
*
* \return
* - 0 if the following conditions are satisfied:
* - D = DP mod P-1 if P, D, DP != NULL
* - Q = DQ mod P-1 if P, D, DQ != NULL
* - QP = Q^-1 mod P if P, Q, QP != NULL
* - \c MBEDTLS_ERR_RSA_KEY_CHECK_FAILED if check failed,
* potentially including \c MBEDTLS_ERR_MPI_XXX if some
* MPI calculations failed.
* - \c MBEDTLS_ERR_RSA_BAD_INPUT_DATA if insufficient
* data was provided to check DP, DQ or QP.
*
* \note The function can be used with a restricted set of arguments
* to perform specific checks only. E.g., calling it with the
* parameters (P, -, D, DP, -, -) will check DP = D mod P-1.
*/
int mbedtls_rsa_validate_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q,
const mbedtls_mpi *D, const mbedtls_mpi *DP,
const mbedtls_mpi *DQ, const mbedtls_mpi *QP );
#endif /* rsa_internal.h */

View file

@ -1052,7 +1052,7 @@ void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode );
* *
* If set, the verify callback is called for each * If set, the verify callback is called for each
* certificate in the chain. For implementation * certificate in the chain. For implementation
* information, please see \c x509parse_verify() * information, please see \c mbedtls_x509_crt_verify()
* *
* \param conf SSL configuration * \param conf SSL configuration
* \param f_vrfy verification function * \param f_vrfy verification function
@ -1794,15 +1794,22 @@ void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf,
#if defined(MBEDTLS_X509_CRT_PARSE_C) #if defined(MBEDTLS_X509_CRT_PARSE_C)
/** /**
* \brief Set the hostname to check against the received server * \brief Set or reset the hostname to check against the received
* certificate. It sets the ServerName TLS extension too, * server certificate. It sets the ServerName TLS extension,
* if the extension is enabled. * too, if that extension is enabled. (client-side only)
* (client-side only)
* *
* \param ssl SSL context * \param ssl SSL context
* \param hostname the server hostname * \param hostname the server hostname, may be NULL to clear hostname
* \note Maximum hostname length MBEDTLS_SSL_MAX_HOST_NAME_LEN.
* *
* \return 0 if successful or MBEDTLS_ERR_SSL_ALLOC_FAILED * \return 0 if successful, MBEDTLS_ERR_SSL_ALLOC_FAILED on
* allocation failure, MBEDTLS_ERR_SSL_BAD_INPUT_DATA on
* too long input hostname.
*
* Hostname set to the one provided on success (cleared
* when NULL). On allocation failure hostname is cleared.
* On too long input failure, old hostname is unchanged.
*/ */
int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname ); int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname );
#endif /* MBEDTLS_X509_CRT_PARSE_C */ #endif /* MBEDTLS_X509_CRT_PARSE_C */

View file

@ -359,23 +359,8 @@ mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_pk_alg( const mbedtls_ssl_ciph
mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_alg( const mbedtls_ssl_ciphersuite_t *info ); mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_alg( const mbedtls_ssl_ciphersuite_t *info );
#endif #endif
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) int mbedtls_ssl_ciphersuite_uses_ec( const mbedtls_ssl_ciphersuite_t *info );
static inline int mbedtls_ssl_ciphersuite_uses_ec( const mbedtls_ssl_ciphersuite_t *info ) int mbedtls_ssl_ciphersuite_uses_psk( const mbedtls_ssl_ciphersuite_t *info );
{
switch( info->key_exchange )
{
case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
return( 1 );
default:
return( 0 );
}
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED) #if defined(MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED)
static inline int mbedtls_ssl_ciphersuite_has_pfs( const mbedtls_ssl_ciphersuite_t *info ) static inline int mbedtls_ssl_ciphersuite_has_pfs( const mbedtls_ssl_ciphersuite_t *info )
@ -429,23 +414,6 @@ static inline int mbedtls_ssl_ciphersuite_uses_ecdh( const mbedtls_ssl_ciphersui
} }
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED */ #endif /* MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
static inline int mbedtls_ssl_ciphersuite_uses_psk( const mbedtls_ssl_ciphersuite_t *info )
{
switch( info->key_exchange )
{
case MBEDTLS_KEY_EXCHANGE_PSK:
case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
return( 1 );
default:
return( 0 );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
static inline int mbedtls_ssl_ciphersuite_cert_req_allowed( const mbedtls_ssl_ciphersuite_t *info ) static inline int mbedtls_ssl_ciphersuite_cert_req_allowed( const mbedtls_ssl_ciphersuite_t *info )
{ {
switch( info->key_exchange ) switch( info->key_exchange )

View file

@ -97,9 +97,6 @@ extern int (*mbedtls_mutex_unlock)( mbedtls_threading_mutex_t *mutex );
*/ */
extern mbedtls_threading_mutex_t mbedtls_threading_readdir_mutex; extern mbedtls_threading_mutex_t mbedtls_threading_readdir_mutex;
extern mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex; extern mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex;
#if defined(MBEDTLS_ECP_INTERNAL_ALT)
extern mbedtls_threading_mutex_t mbedtls_threading_ecp_mutex;
#endif
#endif /* MBEDTLS_THREADING_C */ #endif /* MBEDTLS_THREADING_C */
#ifdef __cplusplus #ifdef __cplusplus

View file

@ -1,7 +1,7 @@
/** /**
* \file timing.h * \file timing.h
* *
* \brief Portable interface to the CPU cycle counter * \brief Portable interface to timeouts and to the CPU cycle counter
* *
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0 * SPDX-License-Identifier: Apache-2.0
@ -65,6 +65,9 @@ extern volatile int mbedtls_timing_alarmed;
* \warning This is only a best effort! Do not rely on this! * \warning This is only a best effort! Do not rely on this!
* In particular, it is known to be unreliable on virtual * In particular, it is known to be unreliable on virtual
* machines. * machines.
*
* \note This value starts at an unspecified origin and
* may wrap around.
*/ */
unsigned long mbedtls_timing_hardclock( void ); unsigned long mbedtls_timing_hardclock( void );
@ -72,7 +75,18 @@ unsigned long mbedtls_timing_hardclock( void );
* \brief Return the elapsed time in milliseconds * \brief Return the elapsed time in milliseconds
* *
* \param val points to a timer structure * \param val points to a timer structure
* \param reset if set to 1, the timer is restarted * \param reset If 0, query the elapsed time. Otherwise (re)start the timer.
*
* \return Elapsed time since the previous reset in ms. When
* restarting, this is always 0.
*
* \note To initialize a timer, call this function with reset=1.
*
* Determining the elapsed time and resetting the timer is not
* atomic on all platforms, so after the sequence
* `{ get_timer(1); ...; time1 = get_timer(1); ...; time2 =
* get_timer(0) }` the value time1+time2 is only approximately
* the delay since the first reset.
*/ */
unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset ); unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset );
@ -80,6 +94,7 @@ unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int
* \brief Setup an alarm clock * \brief Setup an alarm clock
* *
* \param seconds delay before the "mbedtls_timing_alarmed" flag is set * \param seconds delay before the "mbedtls_timing_alarmed" flag is set
* (must be >=0)
* *
* \warning Only one alarm at a time is supported. In a threaded * \warning Only one alarm at a time is supported. In a threaded
* context, this means one for the whole process, not one per * context, this means one for the whole process, not one per
@ -91,11 +106,15 @@ void mbedtls_set_alarm( int seconds );
* \brief Set a pair of delays to watch * \brief Set a pair of delays to watch
* (See \c mbedtls_timing_get_delay().) * (See \c mbedtls_timing_get_delay().)
* *
* \param data Pointer to timing data * \param data Pointer to timing data.
* Must point to a valid \c mbedtls_timing_delay_context struct. * Must point to a valid \c mbedtls_timing_delay_context struct.
* \param int_ms First (intermediate) delay in milliseconds. * \param int_ms First (intermediate) delay in milliseconds.
* The effect if int_ms > fin_ms is unspecified.
* \param fin_ms Second (final) delay in milliseconds. * \param fin_ms Second (final) delay in milliseconds.
* Pass 0 to cancel the current delay. * Pass 0 to cancel the current delay.
*
* \note To set a single delay, either use \c mbedtls_timing_set_timer
* directly or use this function with int_ms == fin_ms.
*/ */
void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms ); void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms );
@ -106,7 +125,7 @@ void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms );
* \param data Pointer to timing data * \param data Pointer to timing data
* Must point to a valid \c mbedtls_timing_delay_context struct. * Must point to a valid \c mbedtls_timing_delay_context struct.
* *
* \return -1 if cancelled (fin_ms = 0) * \return -1 if cancelled (fin_ms = 0),
* 0 if none of the delays are passed, * 0 if none of the delays are passed,
* 1 if only the intermediate delay is passed, * 1 if only the intermediate delay is passed,
* 2 if the final delay is passed. * 2 if the final delay is passed.

View file

@ -38,17 +38,17 @@
* Major, Minor, Patchlevel * Major, Minor, Patchlevel
*/ */
#define MBEDTLS_VERSION_MAJOR 2 #define MBEDTLS_VERSION_MAJOR 2
#define MBEDTLS_VERSION_MINOR 5 #define MBEDTLS_VERSION_MINOR 6
#define MBEDTLS_VERSION_PATCH 1 #define MBEDTLS_VERSION_PATCH 0
/** /**
* The single version number has the following structure: * The single version number has the following structure:
* MMNNPP00 * MMNNPP00
* Major version | Minor version | Patch version * Major version | Minor version | Patch version
*/ */
#define MBEDTLS_VERSION_NUMBER 0x02050100 #define MBEDTLS_VERSION_NUMBER 0x02060000
#define MBEDTLS_VERSION_STRING "2.5.1" #define MBEDTLS_VERSION_STRING "2.6.0"
#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.5.1" #define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.6.0"
#if defined(MBEDTLS_VERSION_C) #if defined(MBEDTLS_VERSION_C)

View file

@ -76,6 +76,7 @@
#define MBEDTLS_ERR_X509_ALLOC_FAILED -0x2880 /**< Allocation of memory failed. */ #define MBEDTLS_ERR_X509_ALLOC_FAILED -0x2880 /**< Allocation of memory failed. */
#define MBEDTLS_ERR_X509_FILE_IO_ERROR -0x2900 /**< Read/write of file failed. */ #define MBEDTLS_ERR_X509_FILE_IO_ERROR -0x2900 /**< Read/write of file failed. */
#define MBEDTLS_ERR_X509_BUFFER_TOO_SMALL -0x2980 /**< Destination buffer is too small. */ #define MBEDTLS_ERR_X509_BUFFER_TOO_SMALL -0x2980 /**< Destination buffer is too small. */
#define MBEDTLS_ERR_X509_FATAL_ERROR -0x3000 /**< A fatal error occured, eg the chain is too long or the vrfy callback failed. */
/* \} name */ /* \} name */
/** /**
@ -246,12 +247,12 @@ int mbedtls_x509_serial_gets( char *buf, size_t size, const mbedtls_x509_buf *se
* \note Intended usage is "if( is_past( valid_to ) ) ERROR". * \note Intended usage is "if( is_past( valid_to ) ) ERROR".
* Hence the return value of 1 if on internal errors. * Hence the return value of 1 if on internal errors.
* *
* \param time mbedtls_x509_time to check * \param to mbedtls_x509_time to check
* *
* \return 1 if the given time is in the past or an error occured, * \return 1 if the given time is in the past or an error occured,
* 0 otherwise. * 0 otherwise.
*/ */
int mbedtls_x509_time_is_past( const mbedtls_x509_time *time ); int mbedtls_x509_time_is_past( const mbedtls_x509_time *to );
/** /**
* \brief Check a given mbedtls_x509_time against the system time * \brief Check a given mbedtls_x509_time against the system time
@ -260,12 +261,12 @@ int mbedtls_x509_time_is_past( const mbedtls_x509_time *time );
* \note Intended usage is "if( is_future( valid_from ) ) ERROR". * \note Intended usage is "if( is_future( valid_from ) ) ERROR".
* Hence the return value of 1 if on internal errors. * Hence the return value of 1 if on internal errors.
* *
* \param time mbedtls_x509_time to check * \param from mbedtls_x509_time to check
* *
* \return 1 if the given time is in the future or an error occured, * \return 1 if the given time is in the future or an error occured,
* 0 otherwise. * 0 otherwise.
*/ */
int mbedtls_x509_time_is_future( const mbedtls_x509_time *time ); int mbedtls_x509_time_is_future( const mbedtls_x509_time *from );
/** /**
* \brief Checkup routine * \brief Checkup routine
@ -294,7 +295,7 @@ int mbedtls_x509_get_sig_alg( const mbedtls_x509_buf *sig_oid, const mbedtls_x50
mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg, mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg,
void **sig_opts ); void **sig_opts );
int mbedtls_x509_get_time( unsigned char **p, const unsigned char *end, int mbedtls_x509_get_time( unsigned char **p, const unsigned char *end,
mbedtls_x509_time *time ); mbedtls_x509_time *t );
int mbedtls_x509_get_serial( unsigned char **p, const unsigned char *end, int mbedtls_x509_get_serial( unsigned char **p, const unsigned char *end,
mbedtls_x509_buf *serial ); mbedtls_x509_buf *serial );
int mbedtls_x509_get_ext( unsigned char **p, const unsigned char *end, int mbedtls_x509_get_ext( unsigned char **p, const unsigned char *end,

View file

@ -267,7 +267,13 @@ int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
* *
* All flags left after returning from the callback * All flags left after returning from the callback
* are also returned to the application. The function should * are also returned to the application. The function should
* return 0 for anything but a fatal error. * return 0 for anything (including invalid certificates)
* other than fatal error, as a non-zero return code
* immediately aborts the verification process. For fatal
* errors, a specific error code should be used (different
* from MBEDTLS_ERR_X509_CERT_VERIFY_FAILED which should not
* be returned at this point), or MBEDTLS_ERR_X509_FATAL_ERROR
* can be used if no better code is available.
* *
* \note In case verification failed, the results can be displayed * \note In case verification failed, the results can be displayed
* using \c mbedtls_x509_crt_verify_info() * using \c mbedtls_x509_crt_verify_info()
@ -289,12 +295,13 @@ int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
* \param f_vrfy verification function * \param f_vrfy verification function
* \param p_vrfy verification parameter * \param p_vrfy verification parameter
* *
* \return 0 if successful or MBEDTLS_ERR_X509_CERT_VERIFY_FAILED * \return 0 (and flags set to 0) if the chain was verified and valid,
* in which case *flags will have one or more * MBEDTLS_ERR_X509_CERT_VERIFY_FAILED if the chain was verified
* MBEDTLS_X509_BADCERT_XXX or MBEDTLS_X509_BADCRL_XXX flags * but found to be invalid, in which case *flags will have one
* set, * or more MBEDTLS_X509_BADCERT_XXX or MBEDTLS_X509_BADCRL_XXX
* or another error in case of a fatal error encountered * flags set, or another error (and flags set to 0xffffffff)
* during the verification process. * in case of a fatal error encountered during the
* verification process.
*/ */
int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt, int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca, mbedtls_x509_crt *trust_ca,

View file

@ -48,6 +48,7 @@ set(src_crypto
platform.c platform.c
ripemd160.c ripemd160.c
rsa.c rsa.c
rsa_internal.c
sha1.c sha1.c
sha256.c sha256.c
sha512.c sha512.c
@ -140,15 +141,15 @@ endif(USE_STATIC_MBEDTLS_LIBRARY)
if(USE_SHARED_MBEDTLS_LIBRARY) if(USE_SHARED_MBEDTLS_LIBRARY)
add_library(mbedcrypto SHARED ${src_crypto}) add_library(mbedcrypto SHARED ${src_crypto})
set_target_properties(mbedcrypto PROPERTIES VERSION 2.5.1 SOVERSION 0) set_target_properties(mbedcrypto PROPERTIES VERSION 2.6.0 SOVERSION 0)
target_link_libraries(mbedcrypto ${libs}) target_link_libraries(mbedcrypto ${libs})
add_library(mbedx509 SHARED ${src_x509}) add_library(mbedx509 SHARED ${src_x509})
set_target_properties(mbedx509 PROPERTIES VERSION 2.5.1 SOVERSION 0) set_target_properties(mbedx509 PROPERTIES VERSION 2.6.0 SOVERSION 0)
target_link_libraries(mbedx509 ${libs} mbedcrypto) target_link_libraries(mbedx509 ${libs} mbedcrypto)
add_library(mbedtls SHARED ${src_tls}) add_library(mbedtls SHARED ${src_tls})
set_target_properties(mbedtls PROPERTIES VERSION 2.5.1 SOVERSION 10) set_target_properties(mbedtls PROPERTIES VERSION 2.6.0 SOVERSION 10)
target_link_libraries(mbedtls ${libs} mbedx509) target_link_libraries(mbedtls ${libs} mbedx509)
install(TARGETS mbedtls mbedx509 mbedcrypto install(TARGETS mbedtls mbedx509 mbedcrypto

View file

@ -59,9 +59,9 @@ OBJS_CRYPTO= aes.o aesni.o arc4.o \
padlock.o pem.o pk.o \ padlock.o pem.o pk.o \
pk_wrap.o pkcs12.o pkcs5.o \ pk_wrap.o pkcs12.o pkcs5.o \
pkparse.o pkwrite.o platform.o \ pkparse.o pkwrite.o platform.o \
ripemd160.o rsa.o sha1.o \ ripemd160.o rsa_internal.o rsa.o \
sha256.o sha512.o threading.o \ sha1.o sha256.o sha512.o \
timing.o version.o \ threading.o timing.o version.o \
version_features.o xtea.o version_features.o xtea.o
OBJS_X509= certs.o pkcs11.o x509.o \ OBJS_X509= certs.o pkcs11.o x509.o \

View file

@ -765,6 +765,13 @@ int mbedtls_internal_aes_encrypt( mbedtls_aes_context *ctx,
} }
#endif /* !MBEDTLS_AES_ENCRYPT_ALT */ #endif /* !MBEDTLS_AES_ENCRYPT_ALT */
void mbedtls_aes_encrypt( mbedtls_aes_context *ctx,
const unsigned char input[16],
unsigned char output[16] )
{
mbedtls_internal_aes_encrypt( ctx, input, output );
}
/* /*
* AES-ECB block decryption * AES-ECB block decryption
*/ */
@ -824,6 +831,13 @@ int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx,
} }
#endif /* !MBEDTLS_AES_DECRYPT_ALT */ #endif /* !MBEDTLS_AES_DECRYPT_ALT */
void mbedtls_aes_decrypt( mbedtls_aes_context *ctx,
const unsigned char input[16],
unsigned char output[16] )
{
mbedtls_internal_aes_decrypt( ctx, input, output );
}
/* /*
* AES-ECB block encryption/decryption * AES-ECB block encryption/decryption
*/ */
@ -1221,9 +1235,11 @@ static const int aes_test_ctr_len[3] =
*/ */
int mbedtls_aes_self_test( int verbose ) int mbedtls_aes_self_test( int verbose )
{ {
int ret = 0, i, j, u, v; int ret = 0, i, j, u, mode;
unsigned int keybits;
unsigned char key[32]; unsigned char key[32];
unsigned char buf[64]; unsigned char buf[64];
const unsigned char *aes_tests;
#if defined(MBEDTLS_CIPHER_MODE_CBC) || defined(MBEDTLS_CIPHER_MODE_CFB) #if defined(MBEDTLS_CIPHER_MODE_CBC) || defined(MBEDTLS_CIPHER_MODE_CFB)
unsigned char iv[16]; unsigned char iv[16];
#endif #endif
@ -1249,45 +1265,52 @@ int mbedtls_aes_self_test( int verbose )
for( i = 0; i < 6; i++ ) for( i = 0; i < 6; i++ )
{ {
u = i >> 1; u = i >> 1;
v = i & 1; keybits = 128 + u * 64;
mode = i & 1;
if( verbose != 0 ) if( verbose != 0 )
mbedtls_printf( " AES-ECB-%3d (%s): ", 128 + u * 64, mbedtls_printf( " AES-ECB-%3d (%s): ", keybits,
( v == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" ); ( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" );
memset( buf, 0, 16 ); memset( buf, 0, 16 );
if( v == MBEDTLS_AES_DECRYPT ) if( mode == MBEDTLS_AES_DECRYPT )
{ {
mbedtls_aes_setkey_dec( &ctx, key, 128 + u * 64 ); ret = mbedtls_aes_setkey_dec( &ctx, key, keybits );
aes_tests = aes_test_ecb_dec[u];
for( j = 0; j < 10000; j++ )
mbedtls_aes_crypt_ecb( &ctx, v, buf, buf );
if( memcmp( buf, aes_test_ecb_dec[u], 16 ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
ret = 1;
goto exit;
}
} }
else else
{ {
mbedtls_aes_setkey_enc( &ctx, key, 128 + u * 64 ); ret = mbedtls_aes_setkey_enc( &ctx, key, keybits );
aes_tests = aes_test_ecb_enc[u];
}
for( j = 0; j < 10000; j++ ) /*
mbedtls_aes_crypt_ecb( &ctx, v, buf, buf ); * AES-192 is an optional feature that may be unavailable when
* there is an alternative underlying implementation i.e. when
* MBEDTLS_AES_ALT is defined.
*/
if( ret == MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE && keybits == 192 )
{
mbedtls_printf( "skipped\n" );
continue;
}
else if( ret != 0 )
{
goto exit;
}
if( memcmp( buf, aes_test_ecb_enc[u], 16 ) != 0 ) for( j = 0; j < 10000; j++ )
{ {
if( verbose != 0 ) ret = mbedtls_aes_crypt_ecb( &ctx, mode, buf, buf );
mbedtls_printf( "failed\n" ); if( ret != 0 )
ret = 1;
goto exit; goto exit;
} }
if( memcmp( buf, aes_tests, 16 ) != 0 )
{
ret = 1;
goto exit;
} }
if( verbose != 0 ) if( verbose != 0 )
@ -1304,55 +1327,64 @@ int mbedtls_aes_self_test( int verbose )
for( i = 0; i < 6; i++ ) for( i = 0; i < 6; i++ )
{ {
u = i >> 1; u = i >> 1;
v = i & 1; keybits = 128 + u * 64;
mode = i & 1;
if( verbose != 0 ) if( verbose != 0 )
mbedtls_printf( " AES-CBC-%3d (%s): ", 128 + u * 64, mbedtls_printf( " AES-CBC-%3d (%s): ", keybits,
( v == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" ); ( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" );
memset( iv , 0, 16 ); memset( iv , 0, 16 );
memset( prv, 0, 16 ); memset( prv, 0, 16 );
memset( buf, 0, 16 ); memset( buf, 0, 16 );
if( v == MBEDTLS_AES_DECRYPT ) if( mode == MBEDTLS_AES_DECRYPT )
{ {
mbedtls_aes_setkey_dec( &ctx, key, 128 + u * 64 ); ret = mbedtls_aes_setkey_dec( &ctx, key, keybits );
aes_tests = aes_test_cbc_dec[u];
for( j = 0; j < 10000; j++ )
mbedtls_aes_crypt_cbc( &ctx, v, 16, iv, buf, buf );
if( memcmp( buf, aes_test_cbc_dec[u], 16 ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
ret = 1;
goto exit;
}
} }
else else
{ {
mbedtls_aes_setkey_enc( &ctx, key, 128 + u * 64 ); ret = mbedtls_aes_setkey_enc( &ctx, key, keybits );
aes_tests = aes_test_cbc_enc[u];
}
for( j = 0; j < 10000; j++ ) /*
* AES-192 is an optional feature that may be unavailable when
* there is an alternative underlying implementation i.e. when
* MBEDTLS_AES_ALT is defined.
*/
if( ret == MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE && keybits == 192 )
{
mbedtls_printf( "skipped\n" );
continue;
}
else if( ret != 0 )
{
goto exit;
}
for( j = 0; j < 10000; j++ )
{
if( mode == MBEDTLS_AES_ENCRYPT )
{ {
unsigned char tmp[16]; unsigned char tmp[16];
mbedtls_aes_crypt_cbc( &ctx, v, 16, iv, buf, buf );
memcpy( tmp, prv, 16 ); memcpy( tmp, prv, 16 );
memcpy( prv, buf, 16 ); memcpy( prv, buf, 16 );
memcpy( buf, tmp, 16 ); memcpy( buf, tmp, 16 );
} }
if( memcmp( prv, aes_test_cbc_enc[u], 16 ) != 0 ) ret = mbedtls_aes_crypt_cbc( &ctx, mode, 16, iv, buf, buf );
{ if( ret != 0 )
if( verbose != 0 )
mbedtls_printf( "failed\n" );
ret = 1;
goto exit; goto exit;
}
}
if( memcmp( buf, aes_tests, 16 ) != 0 )
{
ret = 1;
goto exit;
} }
if( verbose != 0 ) if( verbose != 0 )
@ -1370,45 +1402,52 @@ int mbedtls_aes_self_test( int verbose )
for( i = 0; i < 6; i++ ) for( i = 0; i < 6; i++ )
{ {
u = i >> 1; u = i >> 1;
v = i & 1; keybits = 128 + u * 64;
mode = i & 1;
if( verbose != 0 ) if( verbose != 0 )
mbedtls_printf( " AES-CFB128-%3d (%s): ", 128 + u * 64, mbedtls_printf( " AES-CFB128-%3d (%s): ", keybits,
( v == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" ); ( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" );
memcpy( iv, aes_test_cfb128_iv, 16 ); memcpy( iv, aes_test_cfb128_iv, 16 );
memcpy( key, aes_test_cfb128_key[u], 16 + u * 8 ); memcpy( key, aes_test_cfb128_key[u], keybits / 8 );
offset = 0; offset = 0;
mbedtls_aes_setkey_enc( &ctx, key, 128 + u * 64 ); ret = mbedtls_aes_setkey_enc( &ctx, key, keybits );
/*
* AES-192 is an optional feature that may be unavailable when
* there is an alternative underlying implementation i.e. when
* MBEDTLS_AES_ALT is defined.
*/
if( ret == MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE && keybits == 192 )
{
mbedtls_printf( "skipped\n" );
continue;
}
else if( ret != 0 )
{
goto exit;
}
if( v == MBEDTLS_AES_DECRYPT ) if( mode == MBEDTLS_AES_DECRYPT )
{ {
memcpy( buf, aes_test_cfb128_ct[u], 64 ); memcpy( buf, aes_test_cfb128_ct[u], 64 );
mbedtls_aes_crypt_cfb128( &ctx, v, 64, &offset, iv, buf, buf ); aes_tests = aes_test_cfb128_pt;
if( memcmp( buf, aes_test_cfb128_pt, 64 ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
ret = 1;
goto exit;
}
} }
else else
{ {
memcpy( buf, aes_test_cfb128_pt, 64 ); memcpy( buf, aes_test_cfb128_pt, 64 );
mbedtls_aes_crypt_cfb128( &ctx, v, 64, &offset, iv, buf, buf ); aes_tests = aes_test_cfb128_ct[u];
}
if( memcmp( buf, aes_test_cfb128_ct[u], 64 ) != 0 ) ret = mbedtls_aes_crypt_cfb128( &ctx, mode, 64, &offset, iv, buf, buf );
{ if( ret != 0 )
if( verbose != 0 ) goto exit;
mbedtls_printf( "failed\n" );
ret = 1; if( memcmp( buf, aes_tests, 64 ) != 0 )
goto exit; {
} ret = 1;
goto exit;
} }
if( verbose != 0 ) if( verbose != 0 )
@ -1426,51 +1465,41 @@ int mbedtls_aes_self_test( int verbose )
for( i = 0; i < 6; i++ ) for( i = 0; i < 6; i++ )
{ {
u = i >> 1; u = i >> 1;
v = i & 1; mode = i & 1;
if( verbose != 0 ) if( verbose != 0 )
mbedtls_printf( " AES-CTR-128 (%s): ", mbedtls_printf( " AES-CTR-128 (%s): ",
( v == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" ); ( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" );
memcpy( nonce_counter, aes_test_ctr_nonce_counter[u], 16 ); memcpy( nonce_counter, aes_test_ctr_nonce_counter[u], 16 );
memcpy( key, aes_test_ctr_key[u], 16 ); memcpy( key, aes_test_ctr_key[u], 16 );
offset = 0; offset = 0;
mbedtls_aes_setkey_enc( &ctx, key, 128 ); if( ( ret = mbedtls_aes_setkey_enc( &ctx, key, 128 ) ) != 0 )
goto exit;
if( v == MBEDTLS_AES_DECRYPT ) len = aes_test_ctr_len[u];
if( mode == MBEDTLS_AES_DECRYPT )
{ {
len = aes_test_ctr_len[u];
memcpy( buf, aes_test_ctr_ct[u], len ); memcpy( buf, aes_test_ctr_ct[u], len );
aes_tests = aes_test_ctr_pt[u];
mbedtls_aes_crypt_ctr( &ctx, len, &offset, nonce_counter, stream_block,
buf, buf );
if( memcmp( buf, aes_test_ctr_pt[u], len ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
ret = 1;
goto exit;
}
} }
else else
{ {
len = aes_test_ctr_len[u];
memcpy( buf, aes_test_ctr_pt[u], len ); memcpy( buf, aes_test_ctr_pt[u], len );
aes_tests = aes_test_ctr_ct[u];
}
mbedtls_aes_crypt_ctr( &ctx, len, &offset, nonce_counter, stream_block, ret = mbedtls_aes_crypt_ctr( &ctx, len, &offset, nonce_counter,
buf, buf ); stream_block, buf, buf );
if( ret != 0 )
goto exit;
if( memcmp( buf, aes_test_ctr_ct[u], len ) != 0 ) if( memcmp( buf, aes_tests, len ) != 0 )
{ {
if( verbose != 0 ) ret = 1;
mbedtls_printf( "failed\n" ); goto exit;
ret = 1;
goto exit;
}
} }
if( verbose != 0 ) if( verbose != 0 )
@ -1484,6 +1513,9 @@ int mbedtls_aes_self_test( int verbose )
ret = 0; ret = 0;
exit: exit:
if( ret != 0 && verbose != 0 )
mbedtls_printf( "failed\n" );
mbedtls_aes_free( &ctx ); mbedtls_aes_free( &ctx );
return( ret ); return( ret );

View file

@ -49,6 +49,8 @@
#endif /* MBEDTLS_PLATFORM_C */ #endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */ #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
#if !defined(MBEDTLS_CCM_ALT)
/* Implementation that should never be optimized out by the compiler */ /* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize( void *v, size_t n ) { static void mbedtls_zeroize( void *v, size_t n ) {
volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0; volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0;
@ -348,6 +350,7 @@ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
return( 0 ); return( 0 );
} }
#endif /* !MBEDTLS_CCM_ALT */
#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C) #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
/* /*

View file

@ -116,31 +116,6 @@ const size_t mbedtls_test_cli_key_ec_len = sizeof( mbedtls_test_cli_key_ec );
#endif /* MBEDTLS_ECDSA_C */ #endif /* MBEDTLS_ECDSA_C */
#if defined(MBEDTLS_RSA_C) #if defined(MBEDTLS_RSA_C)
#if defined(MBEDTLS_SHA1_C)
#define TEST_CA_CRT_RSA_SHA1 \
"-----BEGIN CERTIFICATE-----\r\n" \
"MIIDhzCCAm+gAwIBAgIBADANBgkqhkiG9w0BAQUFADA7MQswCQYDVQQGEwJOTDER\r\n" \
"MA8GA1UEChMIUG9sYXJTU0wxGTAXBgNVBAMTEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n" \
"MTEwMjEyMTQ0NDAwWhcNMjEwMjEyMTQ0NDAwWjA7MQswCQYDVQQGEwJOTDERMA8G\r\n" \
"A1UEChMIUG9sYXJTU0wxGTAXBgNVBAMTEFBvbGFyU1NMIFRlc3QgQ0EwggEiMA0G\r\n" \
"CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDA3zf8F7vglp0/ht6WMn1EpRagzSHx\r\n" \
"mdTs6st8GFgIlKXsm8WL3xoemTiZhx57wI053zhdcHgH057Zk+i5clHFzqMwUqny\r\n" \
"50BwFMtEonILwuVA+T7lpg6z+exKY8C4KQB0nFc7qKUEkHHxvYPZP9al4jwqj+8n\r\n" \
"YMPGn8u67GB9t+aEMr5P+1gmIgNb1LTV+/Xjli5wwOQuvfwu7uJBVcA0Ln0kcmnL\r\n" \
"R7EUQIN9Z/SG9jGr8XmksrUuEvmEF/Bibyc+E1ixVA0hmnM3oTDPb5Lc9un8rNsu\r\n" \
"KNF+AksjoBXyOGVkCeoMbo4bF6BxyLObyavpw/LPh5aPgAIynplYb6LVAgMBAAGj\r\n" \
"gZUwgZIwDAYDVR0TBAUwAwEB/zAdBgNVHQ4EFgQUtFrkpbPe0lL2udWmlQ/rPrzH\r\n" \
"/f8wYwYDVR0jBFwwWoAUtFrkpbPe0lL2udWmlQ/rPrzH/f+hP6Q9MDsxCzAJBgNV\r\n" \
"BAYTAk5MMREwDwYDVQQKEwhQb2xhclNTTDEZMBcGA1UEAxMQUG9sYXJTU0wgVGVz\r\n" \
"dCBDQYIBADANBgkqhkiG9w0BAQUFAAOCAQEAuP1U2ABUkIslsCfdlc2i94QHHYeJ\r\n" \
"SsR4EdgHtdciUI5I62J6Mom+Y0dT/7a+8S6MVMCZP6C5NyNyXw1GWY/YR82XTJ8H\r\n" \
"DBJiCTok5DbZ6SzaONBzdWHXwWwmi5vg1dxn7YxrM9d0IjxM27WNKs4sDQhZBQkF\r\n" \
"pjmfs2cb4oPl4Y9T9meTx/lvdkRYEug61Jfn6cA+qHpyPYdTH+UshITnmp5/Ztkf\r\n" \
"m/UTSLBNFNHesiTZeH31NcxYGdHSme9Nc/gfidRa0FLOCfWxRlFqAI47zG9jAQCZ\r\n" \
"7Z2mCGDNMhjQc+BYcdnl0lPXjdDK6V0qCg1dVewhUBcW5gZKzV7e9+DpVA==\r\n" \
"-----END CERTIFICATE-----\r\n"
static const char mbedtls_test_ca_crt_rsa_sha1[] = TEST_CA_CRT_RSA_SHA1;
#endif
#if defined(MBEDTLS_SHA256_C) #if defined(MBEDTLS_SHA256_C)
#define TEST_CA_CRT_RSA_SHA256 \ #define TEST_CA_CRT_RSA_SHA256 \
@ -165,7 +140,46 @@ static const char mbedtls_test_ca_crt_rsa_sha1[] = TEST_CA_CRT_RSA_SHA1;
"ApH0CnB80bYJshYHPHHymOtleAB8KSYtqm75g/YNobjnjB6cm4HkW3OZRVIl6fYY\r\n" \ "ApH0CnB80bYJshYHPHHymOtleAB8KSYtqm75g/YNobjnjB6cm4HkW3OZRVIl6fYY\r\n" \
"n20NRVA1Vjs6GAROr4NqW4k/+LofY9y0LLDE+p0oIEKXIsIvhPr39swxSA==\r\n" \ "n20NRVA1Vjs6GAROr4NqW4k/+LofY9y0LLDE+p0oIEKXIsIvhPr39swxSA==\r\n" \
"-----END CERTIFICATE-----\r\n" "-----END CERTIFICATE-----\r\n"
const char mbedtls_test_ca_crt_rsa[] = TEST_CA_CRT_RSA_SHA256;
const size_t mbedtls_test_ca_crt_rsa_len = sizeof( mbedtls_test_ca_crt_rsa );
#define TEST_CA_CRT_RSA_SOME
static const char mbedtls_test_ca_crt_rsa_sha256[] = TEST_CA_CRT_RSA_SHA256; static const char mbedtls_test_ca_crt_rsa_sha256[] = TEST_CA_CRT_RSA_SHA256;
#endif
#if !defined(TEST_CA_CRT_RSA_SOME) || defined(MBEDTLS_SHA1_C)
#define TEST_CA_CRT_RSA_SHA1 \
"-----BEGIN CERTIFICATE-----\r\n" \
"MIIDhzCCAm+gAwIBAgIBADANBgkqhkiG9w0BAQUFADA7MQswCQYDVQQGEwJOTDER\r\n" \
"MA8GA1UEChMIUG9sYXJTU0wxGTAXBgNVBAMTEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n" \
"MTEwMjEyMTQ0NDAwWhcNMjEwMjEyMTQ0NDAwWjA7MQswCQYDVQQGEwJOTDERMA8G\r\n" \
"A1UEChMIUG9sYXJTU0wxGTAXBgNVBAMTEFBvbGFyU1NMIFRlc3QgQ0EwggEiMA0G\r\n" \
"CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDA3zf8F7vglp0/ht6WMn1EpRagzSHx\r\n" \
"mdTs6st8GFgIlKXsm8WL3xoemTiZhx57wI053zhdcHgH057Zk+i5clHFzqMwUqny\r\n" \
"50BwFMtEonILwuVA+T7lpg6z+exKY8C4KQB0nFc7qKUEkHHxvYPZP9al4jwqj+8n\r\n" \
"YMPGn8u67GB9t+aEMr5P+1gmIgNb1LTV+/Xjli5wwOQuvfwu7uJBVcA0Ln0kcmnL\r\n" \
"R7EUQIN9Z/SG9jGr8XmksrUuEvmEF/Bibyc+E1ixVA0hmnM3oTDPb5Lc9un8rNsu\r\n" \
"KNF+AksjoBXyOGVkCeoMbo4bF6BxyLObyavpw/LPh5aPgAIynplYb6LVAgMBAAGj\r\n" \
"gZUwgZIwDAYDVR0TBAUwAwEB/zAdBgNVHQ4EFgQUtFrkpbPe0lL2udWmlQ/rPrzH\r\n" \
"/f8wYwYDVR0jBFwwWoAUtFrkpbPe0lL2udWmlQ/rPrzH/f+hP6Q9MDsxCzAJBgNV\r\n" \
"BAYTAk5MMREwDwYDVQQKEwhQb2xhclNTTDEZMBcGA1UEAxMQUG9sYXJTU0wgVGVz\r\n" \
"dCBDQYIBADANBgkqhkiG9w0BAQUFAAOCAQEAuP1U2ABUkIslsCfdlc2i94QHHYeJ\r\n" \
"SsR4EdgHtdciUI5I62J6Mom+Y0dT/7a+8S6MVMCZP6C5NyNyXw1GWY/YR82XTJ8H\r\n" \
"DBJiCTok5DbZ6SzaONBzdWHXwWwmi5vg1dxn7YxrM9d0IjxM27WNKs4sDQhZBQkF\r\n" \
"pjmfs2cb4oPl4Y9T9meTx/lvdkRYEug61Jfn6cA+qHpyPYdTH+UshITnmp5/Ztkf\r\n" \
"m/UTSLBNFNHesiTZeH31NcxYGdHSme9Nc/gfidRa0FLOCfWxRlFqAI47zG9jAQCZ\r\n" \
"7Z2mCGDNMhjQc+BYcdnl0lPXjdDK6V0qCg1dVewhUBcW5gZKzV7e9+DpVA==\r\n" \
"-----END CERTIFICATE-----\r\n"
#if !defined (TEST_CA_CRT_RSA_SOME)
const char mbedtls_test_ca_crt_rsa[] = TEST_CA_CRT_RSA_SHA1;
const size_t mbedtls_test_ca_crt_rsa_len = sizeof( mbedtls_test_ca_crt_rsa );
#endif
static const char mbedtls_test_ca_crt_rsa_sha1[] = TEST_CA_CRT_RSA_SHA1;
#endif #endif
const char mbedtls_test_ca_key_rsa[] = const char mbedtls_test_ca_key_rsa[] =
@ -257,7 +271,7 @@ const char mbedtls_test_srv_key_rsa[] =
"-----END RSA PRIVATE KEY-----\r\n"; "-----END RSA PRIVATE KEY-----\r\n";
const size_t mbedtls_test_srv_key_rsa_len = sizeof( mbedtls_test_srv_key_rsa ); const size_t mbedtls_test_srv_key_rsa_len = sizeof( mbedtls_test_srv_key_rsa );
static const char mbedtls_test_cli_crt_rsa_sha256[] = const char mbedtls_test_cli_crt_rsa[] =
"-----BEGIN CERTIFICATE-----\r\n" "-----BEGIN CERTIFICATE-----\r\n"
"MIIDhTCCAm2gAwIBAgIBBDANBgkqhkiG9w0BAQsFADA7MQswCQYDVQQGEwJOTDER\r\n" "MIIDhTCCAm2gAwIBAgIBBDANBgkqhkiG9w0BAQsFADA7MQswCQYDVQQGEwJOTDER\r\n"
"MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n" "MA8GA1UECgwIUG9sYXJTU0wxGTAXBgNVBAMMEFBvbGFyU1NMIFRlc3QgQ0EwHhcN\r\n"
@ -279,6 +293,7 @@ static const char mbedtls_test_cli_crt_rsa_sha256[] =
"ofGZpiM2NqRPePgYy+Vc75Zk28xkRQq1ncprgQb3S4vTsZdScpM9hLf+eMlrgqlj\r\n" "ofGZpiM2NqRPePgYy+Vc75Zk28xkRQq1ncprgQb3S4vTsZdScpM9hLf+eMlrgqlj\r\n"
"c5PLSkXBeLE5+fedkyfTaLxxQlgCpuoOhKBm04/R1pWNzUHyqagjO9Q=\r\n" "c5PLSkXBeLE5+fedkyfTaLxxQlgCpuoOhKBm04/R1pWNzUHyqagjO9Q=\r\n"
"-----END CERTIFICATE-----\r\n"; "-----END CERTIFICATE-----\r\n";
const size_t mbedtls_test_cli_crt_rsa_len = sizeof( mbedtls_test_cli_crt_rsa );
const char mbedtls_test_cli_key_rsa[] = const char mbedtls_test_cli_key_rsa[] =
"-----BEGIN RSA PRIVATE KEY-----\r\n" "-----BEGIN RSA PRIVATE KEY-----\r\n"
@ -354,19 +369,19 @@ const size_t mbedtls_test_cas_len[] = {
}; };
#if defined(MBEDTLS_RSA_C) #if defined(MBEDTLS_RSA_C)
const char *mbedtls_test_ca_crt = mbedtls_test_ca_crt_rsa_sha256; const char *mbedtls_test_ca_crt = mbedtls_test_ca_crt_rsa; /* SHA1 or SHA256 */
const char *mbedtls_test_ca_key = mbedtls_test_ca_key_rsa; const char *mbedtls_test_ca_key = mbedtls_test_ca_key_rsa;
const char *mbedtls_test_ca_pwd = mbedtls_test_ca_pwd_rsa; const char *mbedtls_test_ca_pwd = mbedtls_test_ca_pwd_rsa;
const char *mbedtls_test_srv_crt = mbedtls_test_srv_crt_rsa; const char *mbedtls_test_srv_crt = mbedtls_test_srv_crt_rsa;
const char *mbedtls_test_srv_key = mbedtls_test_srv_key_rsa; const char *mbedtls_test_srv_key = mbedtls_test_srv_key_rsa;
const char *mbedtls_test_cli_crt = mbedtls_test_cli_crt_rsa_sha256; const char *mbedtls_test_cli_crt = mbedtls_test_cli_crt_rsa;
const char *mbedtls_test_cli_key = mbedtls_test_cli_key_rsa; const char *mbedtls_test_cli_key = mbedtls_test_cli_key_rsa;
const size_t mbedtls_test_ca_crt_len = sizeof( mbedtls_test_ca_crt_rsa_sha256 ); const size_t mbedtls_test_ca_crt_len = sizeof( mbedtls_test_ca_crt_rsa );
const size_t mbedtls_test_ca_key_len = sizeof( mbedtls_test_ca_key_rsa ); const size_t mbedtls_test_ca_key_len = sizeof( mbedtls_test_ca_key_rsa );
const size_t mbedtls_test_ca_pwd_len = sizeof( mbedtls_test_ca_pwd_rsa ) - 1; const size_t mbedtls_test_ca_pwd_len = sizeof( mbedtls_test_ca_pwd_rsa ) - 1;
const size_t mbedtls_test_srv_crt_len = sizeof( mbedtls_test_srv_crt_rsa ); const size_t mbedtls_test_srv_crt_len = sizeof( mbedtls_test_srv_crt_rsa );
const size_t mbedtls_test_srv_key_len = sizeof( mbedtls_test_srv_key_rsa ); const size_t mbedtls_test_srv_key_len = sizeof( mbedtls_test_srv_key_rsa );
const size_t mbedtls_test_cli_crt_len = sizeof( mbedtls_test_cli_crt_rsa_sha256 ); const size_t mbedtls_test_cli_crt_len = sizeof( mbedtls_test_cli_crt_rsa );
const size_t mbedtls_test_cli_key_len = sizeof( mbedtls_test_cli_key_rsa ); const size_t mbedtls_test_cli_key_len = sizeof( mbedtls_test_cli_key_rsa );
#else /* ! MBEDTLS_RSA_C, so MBEDTLS_ECDSA_C */ #else /* ! MBEDTLS_RSA_C, so MBEDTLS_ECDSA_C */
const char *mbedtls_test_ca_crt = mbedtls_test_ca_crt_ec; const char *mbedtls_test_ca_crt = mbedtls_test_ca_crt_ec;

View file

@ -65,6 +65,8 @@
#endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_SELF_TEST */
#endif /* MBEDTLS_PLATFORM_C */ #endif /* MBEDTLS_PLATFORM_C */
#if !defined(MBEDTLS_CMAC_ALT) || defined(MBEDTLS_SELF_TEST)
/* Implementation that should never be optimized out by the compiler */ /* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize( void *v, size_t n ) { static void mbedtls_zeroize( void *v, size_t n ) {
volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0; volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0;
@ -164,15 +166,17 @@ exit:
return( ret ); return( ret );
} }
#endif /* !defined(MBEDTLS_CMAC_ALT) || defined(MBEDTLS_SELF_TEST) */
#if !defined(MBEDTLS_CMAC_ALT)
static void cmac_xor_block( unsigned char *output, const unsigned char *input1, static void cmac_xor_block( unsigned char *output, const unsigned char *input1,
const unsigned char *input2, const unsigned char *input2,
const size_t block_size ) const size_t block_size )
{ {
size_t index; size_t idx;
for( index = 0; index < block_size; index++ ) for( idx = 0; idx < block_size; idx++ )
output[ index ] = input1[ index ] ^ input2[ index ]; output[ idx ] = input1[ idx ] ^ input2[ idx ];
} }
/* /*
@ -468,6 +472,8 @@ exit:
} }
#endif /* MBEDTLS_AES_C */ #endif /* MBEDTLS_AES_C */
#endif /* !MBEDTLS_CMAC_ALT */
#if defined(MBEDTLS_SELF_TEST) #if defined(MBEDTLS_SELF_TEST)
/* /*
* CMAC test data for SP800-38B * CMAC test data for SP800-38B

View file

@ -165,7 +165,7 @@ int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size,
*/ */
do do
{ {
mbedtls_mpi_fill_random( &ctx->X, x_size, f_rng, p_rng ); MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->X, x_size, f_rng, p_rng ) );
while( mbedtls_mpi_cmp_mpi( &ctx->X, &ctx->P ) >= 0 ) while( mbedtls_mpi_cmp_mpi( &ctx->X, &ctx->P ) >= 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &ctx->X, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &ctx->X, 1 ) );
@ -251,7 +251,7 @@ int mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size,
*/ */
do do
{ {
mbedtls_mpi_fill_random( &ctx->X, x_size, f_rng, p_rng ); MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->X, x_size, f_rng, p_rng ) );
while( mbedtls_mpi_cmp_mpi( &ctx->X, &ctx->P ) >= 0 ) while( mbedtls_mpi_cmp_mpi( &ctx->X, &ctx->P ) >= 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &ctx->X, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &ctx->X, 1 ) );
@ -324,7 +324,7 @@ static int dhm_update_blinding( mbedtls_dhm_context *ctx,
count = 0; count = 0;
do do
{ {
mbedtls_mpi_fill_random( &ctx->Vi, mbedtls_mpi_size( &ctx->P ), f_rng, p_rng ); MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &ctx->Vi, mbedtls_mpi_size( &ctx->P ), f_rng, p_rng ) );
while( mbedtls_mpi_cmp_mpi( &ctx->Vi, &ctx->P ) >= 0 ) while( mbedtls_mpi_cmp_mpi( &ctx->Vi, &ctx->P ) >= 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &ctx->Vi, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &ctx->Vi, 1 ) );

View file

@ -38,6 +38,7 @@
#include <string.h> #include <string.h>
#if !defined(MBEDTLS_ECDH_GEN_PUBLIC_ALT)
/* /*
* Generate public key: simple wrapper around mbedtls_ecp_gen_keypair * Generate public key: simple wrapper around mbedtls_ecp_gen_keypair
*/ */
@ -47,7 +48,9 @@ int mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp
{ {
return mbedtls_ecp_gen_keypair( grp, d, Q, f_rng, p_rng ); return mbedtls_ecp_gen_keypair( grp, d, Q, f_rng, p_rng );
} }
#endif /* MBEDTLS_ECDH_GEN_PUBLIC_ALT */
#if !defined(MBEDTLS_ECDH_COMPUTE_SHARED_ALT)
/* /*
* Compute shared secret (SEC1 3.3.1) * Compute shared secret (SEC1 3.3.1)
*/ */
@ -81,6 +84,7 @@ cleanup:
return( ret ); return( ret );
} }
#endif /* MBEDTLS_ECDH_COMPUTE_SHARED_ALT */
/* /*
* Initialize context * Initialize context

View file

@ -65,6 +65,7 @@ cleanup:
return( ret ); return( ret );
} }
#if !defined(MBEDTLS_ECDSA_SIGN_ALT)
/* /*
* Compute ECDSA signature of a hashed message (SEC1 4.1.3) * Compute ECDSA signature of a hashed message (SEC1 4.1.3)
* Obviously, compared to SEC1 4.1.3, we skip step 4 (hash message) * Obviously, compared to SEC1 4.1.3, we skip step 4 (hash message)
@ -81,6 +82,10 @@ int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
if( grp->N.p == NULL ) if( grp->N.p == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
/* Make sure d is in range 1..n-1 */
if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 )
return( MBEDTLS_ERR_ECP_INVALID_KEY );
mbedtls_ecp_point_init( &R ); mbedtls_ecp_point_init( &R );
mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t ); mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t );
@ -153,6 +158,7 @@ cleanup:
return( ret ); return( ret );
} }
#endif /* MBEDTLS_ECDSA_SIGN_ALT */
#if defined(MBEDTLS_ECDSA_DETERMINISTIC) #if defined(MBEDTLS_ECDSA_DETERMINISTIC)
/* /*
@ -192,6 +198,7 @@ cleanup:
} }
#endif /* MBEDTLS_ECDSA_DETERMINISTIC */ #endif /* MBEDTLS_ECDSA_DETERMINISTIC */
#if !defined(MBEDTLS_ECDSA_VERIFY_ALT)
/* /*
* Verify ECDSA signature of hashed message (SEC1 4.1.4) * Verify ECDSA signature of hashed message (SEC1 4.1.4)
* Obviously, compared to SEC1 4.1.3, we skip step 2 (hash message) * Obviously, compared to SEC1 4.1.3, we skip step 2 (hash message)
@ -277,6 +284,7 @@ cleanup:
return( ret ); return( ret );
} }
#endif /* MBEDTLS_ECDSA_VERIFY_ALT */
/* /*
* Convert a signature (given by context) to ASN.1 * Convert a signature (given by context) to ASN.1
@ -402,6 +410,7 @@ cleanup:
return( ret ); return( ret );
} }
#if !defined(MBEDTLS_ECDSA_GENKEY_ALT)
/* /*
* Generate key pair * Generate key pair
*/ */
@ -411,6 +420,7 @@ int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid,
return( mbedtls_ecp_group_load( &ctx->grp, gid ) || return( mbedtls_ecp_group_load( &ctx->grp, gid ) ||
mbedtls_ecp_gen_keypair( &ctx->grp, &ctx->d, &ctx->Q, f_rng, p_rng ) ); mbedtls_ecp_gen_keypair( &ctx->grp, &ctx->d, &ctx->Q, f_rng, p_rng ) );
} }
#endif /* MBEDTLS_ECDSA_GENKEY_ALT */
/* /*
* Set context from an mbedtls_ecp_keypair * Set context from an mbedtls_ecp_keypair

View file

@ -1128,7 +1128,7 @@ static int ecp_randomize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *p
/* Generate l such that 1 < l < p */ /* Generate l such that 1 < l < p */
do do
{ {
mbedtls_mpi_fill_random( &l, p_size, f_rng, p_rng ); MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &l, p_size, f_rng, p_rng ) );
while( mbedtls_mpi_cmp_mpi( &l, &grp->P ) >= 0 ) while( mbedtls_mpi_cmp_mpi( &l, &grp->P ) >= 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &l, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &l, 1 ) );
@ -1527,7 +1527,7 @@ static int ecp_randomize_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P
/* Generate l such that 1 < l < p */ /* Generate l such that 1 < l < p */
do do
{ {
mbedtls_mpi_fill_random( &l, p_size, f_rng, p_rng ); MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &l, p_size, f_rng, p_rng ) );
while( mbedtls_mpi_cmp_mpi( &l, &grp->P ) >= 0 ) while( mbedtls_mpi_cmp_mpi( &l, &grp->P ) >= 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &l, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &l, 1 ) );
@ -1690,11 +1690,6 @@ int mbedtls_ecp_mul( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
return( ret ); return( ret );
#if defined(MBEDTLS_ECP_INTERNAL_ALT) #if defined(MBEDTLS_ECP_INTERNAL_ALT)
#if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_lock( &mbedtls_threading_ecp_mutex ) != 0 )
return ( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
#endif
if ( is_grp_capable = mbedtls_internal_ecp_grp_capable( grp ) ) if ( is_grp_capable = mbedtls_internal_ecp_grp_capable( grp ) )
{ {
MBEDTLS_MPI_CHK( mbedtls_internal_ecp_init( grp ) ); MBEDTLS_MPI_CHK( mbedtls_internal_ecp_init( grp ) );
@ -1719,11 +1714,6 @@ cleanup:
mbedtls_internal_ecp_free( grp ); mbedtls_internal_ecp_free( grp );
} }
#if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_unlock( &mbedtls_threading_ecp_mutex ) != 0 )
return ( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
#endif
#endif /* MBEDTLS_ECP_INTERNAL_ALT */ #endif /* MBEDTLS_ECP_INTERNAL_ALT */
return( ret ); return( ret );
} }
@ -1831,11 +1821,6 @@ int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
MBEDTLS_MPI_CHK( mbedtls_ecp_mul_shortcuts( grp, R, n, Q ) ); MBEDTLS_MPI_CHK( mbedtls_ecp_mul_shortcuts( grp, R, n, Q ) );
#if defined(MBEDTLS_ECP_INTERNAL_ALT) #if defined(MBEDTLS_ECP_INTERNAL_ALT)
#if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_lock( &mbedtls_threading_ecp_mutex ) != 0 )
return ( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
#endif
if ( is_grp_capable = mbedtls_internal_ecp_grp_capable( grp ) ) if ( is_grp_capable = mbedtls_internal_ecp_grp_capable( grp ) )
{ {
MBEDTLS_MPI_CHK( mbedtls_internal_ecp_init( grp ) ); MBEDTLS_MPI_CHK( mbedtls_internal_ecp_init( grp ) );
@ -1853,11 +1838,6 @@ cleanup:
mbedtls_internal_ecp_free( grp ); mbedtls_internal_ecp_free( grp );
} }
#if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_unlock( &mbedtls_threading_ecp_mutex ) != 0 )
return ( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
#endif
#endif /* MBEDTLS_ECP_INTERNAL_ALT */ #endif /* MBEDTLS_ECP_INTERNAL_ALT */
mbedtls_ecp_point_free( &mP ); mbedtls_ecp_point_free( &mP );

View file

@ -85,6 +85,9 @@ void mbedtls_entropy_init( mbedtls_entropy_context *ctx )
mbedtls_havege_init( &ctx->havege_data ); mbedtls_havege_init( &ctx->havege_data );
#endif #endif
/* Reminder: Update ENTROPY_HAVE_STRONG in the test files
* when adding more strong entropy sources here. */
#if defined(MBEDTLS_TEST_NULL_ENTROPY) #if defined(MBEDTLS_TEST_NULL_ENTROPY)
mbedtls_entropy_add_source( ctx, mbedtls_null_entropy_poll, NULL, mbedtls_entropy_add_source( ctx, mbedtls_null_entropy_poll, NULL,
1, MBEDTLS_ENTROPY_SOURCE_STRONG ); 1, MBEDTLS_ENTROPY_SOURCE_STRONG );
@ -145,24 +148,24 @@ int mbedtls_entropy_add_source( mbedtls_entropy_context *ctx,
mbedtls_entropy_f_source_ptr f_source, void *p_source, mbedtls_entropy_f_source_ptr f_source, void *p_source,
size_t threshold, int strong ) size_t threshold, int strong )
{ {
int index, ret = 0; int idx, ret = 0;
#if defined(MBEDTLS_THREADING_C) #if defined(MBEDTLS_THREADING_C)
if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 ) if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
return( ret ); return( ret );
#endif #endif
index = ctx->source_count; idx = ctx->source_count;
if( index >= MBEDTLS_ENTROPY_MAX_SOURCES ) if( idx >= MBEDTLS_ENTROPY_MAX_SOURCES )
{ {
ret = MBEDTLS_ERR_ENTROPY_MAX_SOURCES; ret = MBEDTLS_ERR_ENTROPY_MAX_SOURCES;
goto exit; goto exit;
} }
ctx->source[index].f_source = f_source; ctx->source[idx].f_source = f_source;
ctx->source[index].p_source = p_source; ctx->source[idx].p_source = p_source;
ctx->source[index].threshold = threshold; ctx->source[idx].threshold = threshold;
ctx->source[index].strong = strong; ctx->source[idx].strong = strong;
ctx->source_count++; ctx->source_count++;

View file

@ -331,6 +331,8 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
mbedtls_snprintf( buf, buflen, "RSA - The output buffer for decryption is not large enough" ); mbedtls_snprintf( buf, buflen, "RSA - The output buffer for decryption is not large enough" );
if( use_ret == -(MBEDTLS_ERR_RSA_RNG_FAILED) ) if( use_ret == -(MBEDTLS_ERR_RSA_RNG_FAILED) )
mbedtls_snprintf( buf, buflen, "RSA - The random generator failed to generate non-zeros" ); mbedtls_snprintf( buf, buflen, "RSA - The random generator failed to generate non-zeros" );
if( use_ret == -(MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION) )
mbedtls_snprintf( buf, buflen, "RSA - The implementation doesn't offer the requested operation, e.g. because of security violations or lack of functionality" );
#endif /* MBEDTLS_RSA_C */ #endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_SSL_TLS_C) #if defined(MBEDTLS_SSL_TLS_C)
@ -480,6 +482,8 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
mbedtls_snprintf( buf, buflen, "X509 - Read/write of file failed" ); mbedtls_snprintf( buf, buflen, "X509 - Read/write of file failed" );
if( use_ret == -(MBEDTLS_ERR_X509_BUFFER_TOO_SMALL) ) if( use_ret == -(MBEDTLS_ERR_X509_BUFFER_TOO_SMALL) )
mbedtls_snprintf( buf, buflen, "X509 - Destination buffer is too small" ); mbedtls_snprintf( buf, buflen, "X509 - Destination buffer is too small" );
if( use_ret == -(MBEDTLS_ERR_X509_FATAL_ERROR) )
mbedtls_snprintf( buf, buflen, "X509 - A fatal error occured, eg the chain is too long or the vrfy callback failed" );
#endif /* MBEDTLS_X509_USE_C || MBEDTLS_X509_CREATE_C */ #endif /* MBEDTLS_X509_USE_C || MBEDTLS_X509_CREATE_C */
// END generated code // END generated code
@ -516,6 +520,8 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
mbedtls_snprintf( buf, buflen, "AES - Invalid key length" ); mbedtls_snprintf( buf, buflen, "AES - Invalid key length" );
if( use_ret == -(MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH) ) if( use_ret == -(MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH) )
mbedtls_snprintf( buf, buflen, "AES - Invalid data input length" ); mbedtls_snprintf( buf, buflen, "AES - Invalid data input length" );
if( use_ret == -(MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "AES - Feature not available, e.g. unsupported AES key size" );
#endif /* MBEDTLS_AES_C */ #endif /* MBEDTLS_AES_C */
#if defined(MBEDTLS_ASN1_PARSE_C) #if defined(MBEDTLS_ASN1_PARSE_C)

View file

@ -46,6 +46,7 @@
#endif #endif
#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C) #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
#include "mbedtls/aes.h"
#if defined(MBEDTLS_PLATFORM_C) #if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h" #include "mbedtls/platform.h"
#else #else
@ -54,6 +55,8 @@
#endif /* MBEDTLS_PLATFORM_C */ #endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */ #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
#if !defined(MBEDTLS_GCM_ALT)
/* /*
* 32-bit integer manipulation macros (big endian) * 32-bit integer manipulation macros (big endian)
*/ */
@ -277,8 +280,10 @@ int mbedtls_gcm_starts( mbedtls_gcm_context *ctx,
size_t use_len, olen = 0; size_t use_len, olen = 0;
/* IV and AD are limited to 2^64 bits, so 2^61 bytes */ /* IV and AD are limited to 2^64 bits, so 2^61 bytes */
if( ( (uint64_t) iv_len ) >> 61 != 0 || /* IV is not allowed to be zero length */
( (uint64_t) add_len ) >> 61 != 0 ) if( iv_len == 0 ||
( (uint64_t) iv_len ) >> 61 != 0 ||
( (uint64_t) add_len ) >> 61 != 0 )
{ {
return( MBEDTLS_ERR_GCM_BAD_INPUT ); return( MBEDTLS_ERR_GCM_BAD_INPUT );
} }
@ -506,6 +511,8 @@ void mbedtls_gcm_free( mbedtls_gcm_context *ctx )
mbedtls_zeroize( ctx, sizeof( mbedtls_gcm_context ) ); mbedtls_zeroize( ctx, sizeof( mbedtls_gcm_context ) );
} }
#endif /* !MBEDTLS_GCM_ALT */
#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C) #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
/* /*
* AES-GCM test vectors from: * AES-GCM test vectors from:
@ -742,34 +749,48 @@ int mbedtls_gcm_self_test( int verbose )
int i, j, ret; int i, j, ret;
mbedtls_cipher_id_t cipher = MBEDTLS_CIPHER_ID_AES; mbedtls_cipher_id_t cipher = MBEDTLS_CIPHER_ID_AES;
mbedtls_gcm_init( &ctx );
for( j = 0; j < 3; j++ ) for( j = 0; j < 3; j++ )
{ {
int key_len = 128 + 64 * j; int key_len = 128 + 64 * j;
for( i = 0; i < MAX_TESTS; i++ ) for( i = 0; i < MAX_TESTS; i++ )
{ {
mbedtls_gcm_init( &ctx );
if( verbose != 0 ) if( verbose != 0 )
mbedtls_printf( " AES-GCM-%3d #%d (%s): ", mbedtls_printf( " AES-GCM-%3d #%d (%s): ",
key_len, i, "enc" ); key_len, i, "enc" );
mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]], key_len ); ret = mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]],
key_len );
/*
* AES-192 is an optional feature that may be unavailable when
* there is an alternative underlying implementation i.e. when
* MBEDTLS_AES_ALT is defined.
*/
if( ret == MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE && key_len == 192 )
{
mbedtls_printf( "skipped\n" );
break;
}
else if( ret != 0 )
{
goto exit;
}
ret = mbedtls_gcm_crypt_and_tag( &ctx, MBEDTLS_GCM_ENCRYPT, ret = mbedtls_gcm_crypt_and_tag( &ctx, MBEDTLS_GCM_ENCRYPT,
pt_len[i], pt_len[i],
iv[iv_index[i]], iv_len[i], iv[iv_index[i]], iv_len[i],
additional[add_index[i]], add_len[i], additional[add_index[i]], add_len[i],
pt[pt_index[i]], buf, 16, tag_buf ); pt[pt_index[i]], buf, 16, tag_buf );
if( ret != 0 )
goto exit;
if( ret != 0 || if ( memcmp( buf, ct[j * 6 + i], pt_len[i] ) != 0 ||
memcmp( buf, ct[j * 6 + i], pt_len[i] ) != 0 || memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )
memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )
{ {
if( verbose != 0 ) ret = 1;
mbedtls_printf( "failed\n" ); goto exit;
return( 1 );
} }
mbedtls_gcm_free( &ctx ); mbedtls_gcm_free( &ctx );
@ -777,26 +798,31 @@ int mbedtls_gcm_self_test( int verbose )
if( verbose != 0 ) if( verbose != 0 )
mbedtls_printf( "passed\n" ); mbedtls_printf( "passed\n" );
mbedtls_gcm_init( &ctx );
if( verbose != 0 ) if( verbose != 0 )
mbedtls_printf( " AES-GCM-%3d #%d (%s): ", mbedtls_printf( " AES-GCM-%3d #%d (%s): ",
key_len, i, "dec" ); key_len, i, "dec" );
mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]], key_len ); ret = mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]],
key_len );
if( ret != 0 )
goto exit;
ret = mbedtls_gcm_crypt_and_tag( &ctx, MBEDTLS_GCM_DECRYPT, ret = mbedtls_gcm_crypt_and_tag( &ctx, MBEDTLS_GCM_DECRYPT,
pt_len[i], pt_len[i],
iv[iv_index[i]], iv_len[i], iv[iv_index[i]], iv_len[i],
additional[add_index[i]], add_len[i], additional[add_index[i]], add_len[i],
ct[j * 6 + i], buf, 16, tag_buf ); ct[j * 6 + i], buf, 16, tag_buf );
if( ret != 0 || if( ret != 0 )
memcmp( buf, pt[pt_index[i]], pt_len[i] ) != 0 || goto exit;
if( memcmp( buf, pt[pt_index[i]], pt_len[i] ) != 0 ||
memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 ) memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )
{ {
if( verbose != 0 ) ret = 1;
mbedtls_printf( "failed\n" ); goto exit;
return( 1 );
} }
mbedtls_gcm_free( &ctx ); mbedtls_gcm_free( &ctx );
@ -804,66 +830,51 @@ int mbedtls_gcm_self_test( int verbose )
if( verbose != 0 ) if( verbose != 0 )
mbedtls_printf( "passed\n" ); mbedtls_printf( "passed\n" );
mbedtls_gcm_init( &ctx );
if( verbose != 0 ) if( verbose != 0 )
mbedtls_printf( " AES-GCM-%3d #%d split (%s): ", mbedtls_printf( " AES-GCM-%3d #%d split (%s): ",
key_len, i, "enc" ); key_len, i, "enc" );
mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]], key_len ); ret = mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]],
key_len );
if( ret != 0 )
goto exit;
ret = mbedtls_gcm_starts( &ctx, MBEDTLS_GCM_ENCRYPT, ret = mbedtls_gcm_starts( &ctx, MBEDTLS_GCM_ENCRYPT,
iv[iv_index[i]], iv_len[i], iv[iv_index[i]], iv_len[i],
additional[add_index[i]], add_len[i] ); additional[add_index[i]], add_len[i] );
if( ret != 0 ) if( ret != 0 )
{ goto exit;
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
}
if( pt_len[i] > 32 ) if( pt_len[i] > 32 )
{ {
size_t rest_len = pt_len[i] - 32; size_t rest_len = pt_len[i] - 32;
ret = mbedtls_gcm_update( &ctx, 32, pt[pt_index[i]], buf ); ret = mbedtls_gcm_update( &ctx, 32, pt[pt_index[i]], buf );
if( ret != 0 ) if( ret != 0 )
{ goto exit;
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
}
ret = mbedtls_gcm_update( &ctx, rest_len, pt[pt_index[i]] + 32, ret = mbedtls_gcm_update( &ctx, rest_len, pt[pt_index[i]] + 32,
buf + 32 ); buf + 32 );
if( ret != 0 ) if( ret != 0 )
{ goto exit;
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
}
} }
else else
{ {
ret = mbedtls_gcm_update( &ctx, pt_len[i], pt[pt_index[i]], buf ); ret = mbedtls_gcm_update( &ctx, pt_len[i], pt[pt_index[i]], buf );
if( ret != 0 ) if( ret != 0 )
{ goto exit;
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
}
} }
ret = mbedtls_gcm_finish( &ctx, tag_buf, 16 ); ret = mbedtls_gcm_finish( &ctx, tag_buf, 16 );
if( ret != 0 || if( ret != 0 )
memcmp( buf, ct[j * 6 + i], pt_len[i] ) != 0 || goto exit;
if( memcmp( buf, ct[j * 6 + i], pt_len[i] ) != 0 ||
memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 ) memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )
{ {
if( verbose != 0 ) ret = 1;
mbedtls_printf( "failed\n" ); goto exit;
return( 1 );
} }
mbedtls_gcm_free( &ctx ); mbedtls_gcm_free( &ctx );
@ -871,80 +882,75 @@ int mbedtls_gcm_self_test( int verbose )
if( verbose != 0 ) if( verbose != 0 )
mbedtls_printf( "passed\n" ); mbedtls_printf( "passed\n" );
mbedtls_gcm_init( &ctx );
if( verbose != 0 ) if( verbose != 0 )
mbedtls_printf( " AES-GCM-%3d #%d split (%s): ", mbedtls_printf( " AES-GCM-%3d #%d split (%s): ",
key_len, i, "dec" ); key_len, i, "dec" );
mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]], key_len ); ret = mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]],
key_len );
if( ret != 0 )
goto exit;
ret = mbedtls_gcm_starts( &ctx, MBEDTLS_GCM_DECRYPT, ret = mbedtls_gcm_starts( &ctx, MBEDTLS_GCM_DECRYPT,
iv[iv_index[i]], iv_len[i], iv[iv_index[i]], iv_len[i],
additional[add_index[i]], add_len[i] ); additional[add_index[i]], add_len[i] );
if( ret != 0 ) if( ret != 0 )
{ goto exit;
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
}
if( pt_len[i] > 32 ) if( pt_len[i] > 32 )
{ {
size_t rest_len = pt_len[i] - 32; size_t rest_len = pt_len[i] - 32;
ret = mbedtls_gcm_update( &ctx, 32, ct[j * 6 + i], buf ); ret = mbedtls_gcm_update( &ctx, 32, ct[j * 6 + i], buf );
if( ret != 0 ) if( ret != 0 )
{ goto exit;
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
}
ret = mbedtls_gcm_update( &ctx, rest_len, ct[j * 6 + i] + 32, ret = mbedtls_gcm_update( &ctx, rest_len, ct[j * 6 + i] + 32,
buf + 32 ); buf + 32 );
if( ret != 0 ) if( ret != 0 )
{ goto exit;
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
}
} }
else else
{ {
ret = mbedtls_gcm_update( &ctx, pt_len[i], ct[j * 6 + i], buf ); ret = mbedtls_gcm_update( &ctx, pt_len[i], ct[j * 6 + i],
buf );
if( ret != 0 ) if( ret != 0 )
{ goto exit;
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
}
} }
ret = mbedtls_gcm_finish( &ctx, tag_buf, 16 ); ret = mbedtls_gcm_finish( &ctx, tag_buf, 16 );
if( ret != 0 || if( ret != 0 )
memcmp( buf, pt[pt_index[i]], pt_len[i] ) != 0 || goto exit;
if( memcmp( buf, pt[pt_index[i]], pt_len[i] ) != 0 ||
memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 ) memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )
{ {
if( verbose != 0 ) ret = 1;
mbedtls_printf( "failed\n" ); goto exit;
return( 1 );
} }
mbedtls_gcm_free( &ctx ); mbedtls_gcm_free( &ctx );
if( verbose != 0 ) if( verbose != 0 )
mbedtls_printf( "passed\n" ); mbedtls_printf( "passed\n" );
} }
} }
if( verbose != 0 ) if( verbose != 0 )
mbedtls_printf( "\n" ); mbedtls_printf( "\n" );
return( 0 ); ret = 0;
exit:
if( ret != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
mbedtls_gcm_free( &ctx );
}
return( ret );
} }
#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */ #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */

View file

@ -63,8 +63,8 @@
#endif #endif
#endif /* _MSC_VER */ #endif /* _MSC_VER */
#define read(fd,buf,len) recv(fd,(char*)buf,(int) len,0) #define read(fd,buf,len) recv( fd, (char*)( buf ), (int)( len ), 0 )
#define write(fd,buf,len) send(fd,(char*)buf,(int) len,0) #define write(fd,buf,len) send( fd, (char*)( buf ), (int)( len ), 0 )
#define close(fd) closesocket(fd) #define close(fd) closesocket(fd)
static int wsa_init_done = 0; static int wsa_init_done = 0;
@ -85,7 +85,7 @@ static int wsa_init_done = 0;
#endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */ #endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
/* Some MS functions want int and MSVC warns if we pass size_t, /* Some MS functions want int and MSVC warns if we pass size_t,
* but the standard fucntions use socklen_t, so cast only for MSVC */ * but the standard functions use socklen_t, so cast only for MSVC */
#if defined(_MSC_VER) #if defined(_MSC_VER)
#define MSVC_INT_CAST (int) #define MSVC_INT_CAST (int)
#else #else
@ -270,13 +270,18 @@ static int net_would_block( const mbedtls_net_context *ctx )
*/ */
static int net_would_block( const mbedtls_net_context *ctx ) static int net_would_block( const mbedtls_net_context *ctx )
{ {
int err = errno;
/* /*
* Never return 'WOULD BLOCK' on a non-blocking socket * Never return 'WOULD BLOCK' on a non-blocking socket
*/ */
if( ( fcntl( ctx->fd, F_GETFL ) & O_NONBLOCK ) != O_NONBLOCK ) if( ( fcntl( ctx->fd, F_GETFL ) & O_NONBLOCK ) != O_NONBLOCK )
{
errno = err;
return( 0 ); return( 0 );
}
switch( errno ) switch( errno = err )
{ {
#if defined EAGAIN #if defined EAGAIN
case EAGAIN: case EAGAIN:

View file

@ -157,8 +157,9 @@ static int pem_des_decrypt( unsigned char des_iv[8],
if( ( ret = pem_pbkdf1( des_key, 8, des_iv, pwd, pwdlen ) ) != 0 ) if( ( ret = pem_pbkdf1( des_key, 8, des_iv, pwd, pwdlen ) ) != 0 )
goto exit; goto exit;
mbedtls_des_setkey_dec( &des_ctx, des_key ); if( ( ret = mbedtls_des_setkey_dec( &des_ctx, des_key ) ) != 0 )
mbedtls_des_crypt_cbc( &des_ctx, MBEDTLS_DES_DECRYPT, buflen, goto exit;
ret = mbedtls_des_crypt_cbc( &des_ctx, MBEDTLS_DES_DECRYPT, buflen,
des_iv, buf, buf ); des_iv, buf, buf );
exit: exit:
@ -184,8 +185,9 @@ static int pem_des3_decrypt( unsigned char des3_iv[8],
if( ( ret = pem_pbkdf1( des3_key, 24, des3_iv, pwd, pwdlen ) ) != 0 ) if( ( ret = pem_pbkdf1( des3_key, 24, des3_iv, pwd, pwdlen ) ) != 0 )
goto exit; goto exit;
mbedtls_des3_set3key_dec( &des3_ctx, des3_key ); if( ( ret = mbedtls_des3_set3key_dec( &des3_ctx, des3_key ) ) != 0 )
mbedtls_des3_crypt_cbc( &des3_ctx, MBEDTLS_DES_DECRYPT, buflen, goto exit;
ret = mbedtls_des3_crypt_cbc( &des3_ctx, MBEDTLS_DES_DECRYPT, buflen,
des3_iv, buf, buf ); des3_iv, buf, buf );
exit: exit:
@ -213,8 +215,9 @@ static int pem_aes_decrypt( unsigned char aes_iv[16], unsigned int keylen,
if( ( ret = pem_pbkdf1( aes_key, keylen, aes_iv, pwd, pwdlen ) ) != 0 ) if( ( ret = pem_pbkdf1( aes_key, keylen, aes_iv, pwd, pwdlen ) ) != 0 )
goto exit; goto exit;
mbedtls_aes_setkey_dec( &aes_ctx, aes_key, keylen * 8 ); if( ( ret = mbedtls_aes_setkey_dec( &aes_ctx, aes_key, keylen * 8 ) ) != 0 )
mbedtls_aes_crypt_cbc( &aes_ctx, MBEDTLS_AES_DECRYPT, buflen, goto exit;
ret = mbedtls_aes_crypt_cbc( &aes_ctx, MBEDTLS_AES_DECRYPT, buflen,
aes_iv, buf, buf ); aes_iv, buf, buf );
exit: exit:

View file

@ -29,8 +29,6 @@
#include "mbedtls/pk.h" #include "mbedtls/pk.h"
#include "mbedtls/pk_internal.h" #include "mbedtls/pk_internal.h"
#include "mbedtls/bignum.h"
#if defined(MBEDTLS_RSA_C) #if defined(MBEDTLS_RSA_C)
#include "mbedtls/rsa.h" #include "mbedtls/rsa.h"
#endif #endif
@ -42,6 +40,7 @@
#endif #endif
#include <limits.h> #include <limits.h>
#include <stdint.h>
/* Implementation that should never be optimized out by the compiler */ /* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize( void *v, size_t n ) { static void mbedtls_zeroize( void *v, size_t n ) {
@ -213,10 +212,10 @@ int mbedtls_pk_verify_ext( mbedtls_pk_type_t type, const void *options,
int ret; int ret;
const mbedtls_pk_rsassa_pss_options *pss_opts; const mbedtls_pk_rsassa_pss_options *pss_opts;
#if defined(MBEDTLS_HAVE_INT64) #if SIZE_MAX > UINT_MAX
if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len ) if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
#endif /* MBEDTLS_HAVE_INT64 */ #endif /* SIZE_MAX > UINT_MAX */
if( options == NULL ) if( options == NULL )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );

View file

@ -30,7 +30,6 @@
/* Even if RSA not activated, for the sake of RSA-alt */ /* Even if RSA not activated, for the sake of RSA-alt */
#include "mbedtls/rsa.h" #include "mbedtls/rsa.h"
#include "mbedtls/bignum.h"
#include <string.h> #include <string.h>
@ -51,6 +50,7 @@
#endif #endif
#include <limits.h> #include <limits.h>
#include <stdint.h>
#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT) #if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
/* Implementation that should never be optimized out by the compiler */ /* Implementation that should never be optimized out by the compiler */
@ -68,7 +68,8 @@ static int rsa_can_do( mbedtls_pk_type_t type )
static size_t rsa_get_bitlen( const void *ctx ) static size_t rsa_get_bitlen( const void *ctx )
{ {
return( 8 * ((const mbedtls_rsa_context *) ctx)->len ); const mbedtls_rsa_context * rsa = (const mbedtls_rsa_context *) ctx;
return( 8 * mbedtls_rsa_get_len( rsa ) );
} }
static int rsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg, static int rsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg,
@ -76,21 +77,23 @@ static int rsa_verify_wrap( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *sig, size_t sig_len ) const unsigned char *sig, size_t sig_len )
{ {
int ret; int ret;
mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx;
size_t rsa_len = mbedtls_rsa_get_len( rsa );
#if defined(MBEDTLS_HAVE_INT64) #if SIZE_MAX > UINT_MAX
if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len ) if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
#endif /* MBEDTLS_HAVE_INT64 */ #endif /* SIZE_MAX > UINT_MAX */
if( sig_len < ((mbedtls_rsa_context *) ctx)->len ) if( sig_len < rsa_len )
return( MBEDTLS_ERR_RSA_VERIFY_FAILED ); return( MBEDTLS_ERR_RSA_VERIFY_FAILED );
if( ( ret = mbedtls_rsa_pkcs1_verify( (mbedtls_rsa_context *) ctx, NULL, NULL, if( ( ret = mbedtls_rsa_pkcs1_verify( rsa, NULL, NULL,
MBEDTLS_RSA_PUBLIC, md_alg, MBEDTLS_RSA_PUBLIC, md_alg,
(unsigned int) hash_len, hash, sig ) ) != 0 ) (unsigned int) hash_len, hash, sig ) ) != 0 )
return( ret ); return( ret );
if( sig_len > ((mbedtls_rsa_context *) ctx)->len ) if( sig_len > rsa_len )
return( MBEDTLS_ERR_PK_SIG_LEN_MISMATCH ); return( MBEDTLS_ERR_PK_SIG_LEN_MISMATCH );
return( 0 ); return( 0 );
@ -101,14 +104,16 @@ static int rsa_sign_wrap( void *ctx, mbedtls_md_type_t md_alg,
unsigned char *sig, size_t *sig_len, unsigned char *sig, size_t *sig_len,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{ {
#if defined(MBEDTLS_HAVE_INT64) mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx;
#if SIZE_MAX > UINT_MAX
if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len ) if( md_alg == MBEDTLS_MD_NONE && UINT_MAX < hash_len )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
#endif /* MBEDTLS_HAVE_INT64 */ #endif /* SIZE_MAX > UINT_MAX */
*sig_len = ((mbedtls_rsa_context *) ctx)->len; *sig_len = mbedtls_rsa_get_len( rsa );
return( mbedtls_rsa_pkcs1_sign( (mbedtls_rsa_context *) ctx, f_rng, p_rng, MBEDTLS_RSA_PRIVATE, return( mbedtls_rsa_pkcs1_sign( rsa, f_rng, p_rng, MBEDTLS_RSA_PRIVATE,
md_alg, (unsigned int) hash_len, hash, sig ) ); md_alg, (unsigned int) hash_len, hash, sig ) );
} }
@ -117,10 +122,12 @@ static int rsa_decrypt_wrap( void *ctx,
unsigned char *output, size_t *olen, size_t osize, unsigned char *output, size_t *olen, size_t osize,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{ {
if( ilen != ((mbedtls_rsa_context *) ctx)->len ) mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx;
if( ilen != mbedtls_rsa_get_len( rsa ) )
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA ); return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
return( mbedtls_rsa_pkcs1_decrypt( (mbedtls_rsa_context *) ctx, f_rng, p_rng, return( mbedtls_rsa_pkcs1_decrypt( rsa, f_rng, p_rng,
MBEDTLS_RSA_PRIVATE, olen, input, output, osize ) ); MBEDTLS_RSA_PRIVATE, olen, input, output, osize ) );
} }
@ -129,13 +136,14 @@ static int rsa_encrypt_wrap( void *ctx,
unsigned char *output, size_t *olen, size_t osize, unsigned char *output, size_t *olen, size_t osize,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{ {
*olen = ((mbedtls_rsa_context *) ctx)->len; mbedtls_rsa_context * rsa = (mbedtls_rsa_context *) ctx;
*olen = mbedtls_rsa_get_len( rsa );
if( *olen > osize ) if( *olen > osize )
return( MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE ); return( MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE );
return( mbedtls_rsa_pkcs1_encrypt( (mbedtls_rsa_context *) ctx, return( mbedtls_rsa_pkcs1_encrypt( rsa, f_rng, p_rng, MBEDTLS_RSA_PUBLIC,
f_rng, p_rng, MBEDTLS_RSA_PUBLIC, ilen, input, output ) ); ilen, input, output ) );
} }
static int rsa_check_pair_wrap( const void *pub, const void *prv ) static int rsa_check_pair_wrap( const void *pub, const void *prv )
@ -415,10 +423,10 @@ static int rsa_alt_sign_wrap( void *ctx, mbedtls_md_type_t md_alg,
{ {
mbedtls_rsa_alt_context *rsa_alt = (mbedtls_rsa_alt_context *) ctx; mbedtls_rsa_alt_context *rsa_alt = (mbedtls_rsa_alt_context *) ctx;
#if defined(MBEDTLS_HAVE_INT64) #if SIZE_MAX > UINT_MAX
if( UINT_MAX < hash_len ) if( UINT_MAX < hash_len )
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
#endif /* MBEDTLS_HAVE_INT64 */ #endif /* SIZE_MAX > UINT_MAX */
*sig_len = rsa_alt->key_len_func( rsa_alt->key ); *sig_len = rsa_alt->key_len_func( rsa_alt->key );

View file

@ -60,12 +60,15 @@
#define mbedtls_free free #define mbedtls_free free
#endif #endif
#if defined(MBEDTLS_FS_IO) #if defined(MBEDTLS_FS_IO) || \
defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
/* Implementation that should never be optimized out by the compiler */ /* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize( void *v, size_t n ) { static void mbedtls_zeroize( void *v, size_t n ) {
volatile unsigned char *p = v; while( n-- ) *p++ = 0; volatile unsigned char *p = v; while( n-- ) *p++ = 0;
} }
#endif
#if defined(MBEDTLS_FS_IO)
/* /*
* Load all data from a file into a given buffer. * Load all data from a file into a given buffer.
* *
@ -520,19 +523,36 @@ static int pk_get_rsapubkey( unsigned char **p,
return( MBEDTLS_ERR_PK_INVALID_PUBKEY + return( MBEDTLS_ERR_PK_INVALID_PUBKEY +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
if( ( ret = mbedtls_asn1_get_mpi( p, end, &rsa->N ) ) != 0 || /* Import N */
( ret = mbedtls_asn1_get_mpi( p, end, &rsa->E ) ) != 0 ) if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_INTEGER ) ) != 0 )
return( MBEDTLS_ERR_PK_INVALID_PUBKEY + ret ); return( MBEDTLS_ERR_PK_INVALID_PUBKEY + ret );
if( ( ret = mbedtls_rsa_import_raw( rsa, *p, len, NULL, 0, NULL, 0,
NULL, 0, NULL, 0 ) ) != 0 )
return( MBEDTLS_ERR_PK_INVALID_PUBKEY );
*p += len;
/* Import E */
if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_INTEGER ) ) != 0 )
return( MBEDTLS_ERR_PK_INVALID_PUBKEY + ret );
if( ( ret = mbedtls_rsa_import_raw( rsa, NULL, 0, NULL, 0, NULL, 0,
NULL, 0, *p, len ) ) != 0 )
return( MBEDTLS_ERR_PK_INVALID_PUBKEY );
*p += len;
if( mbedtls_rsa_complete( rsa ) != 0 ||
mbedtls_rsa_check_pubkey( rsa ) != 0 )
{
return( MBEDTLS_ERR_PK_INVALID_PUBKEY );
}
if( *p != end ) if( *p != end )
return( MBEDTLS_ERR_PK_INVALID_PUBKEY + return( MBEDTLS_ERR_PK_INVALID_PUBKEY +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ); MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
if( ( ret = mbedtls_rsa_check_pubkey( rsa ) ) != 0 )
return( MBEDTLS_ERR_PK_INVALID_PUBKEY );
rsa->len = mbedtls_mpi_size( &rsa->N );
return( 0 ); return( 0 );
} }
#endif /* MBEDTLS_RSA_C */ #endif /* MBEDTLS_RSA_C */
@ -643,10 +663,13 @@ static int pk_parse_key_pkcs1_der( mbedtls_rsa_context *rsa,
const unsigned char *key, const unsigned char *key,
size_t keylen ) size_t keylen )
{ {
int ret; int ret, version;
size_t len; size_t len;
unsigned char *p, *end; unsigned char *p, *end;
mbedtls_mpi T;
mbedtls_mpi_init( &T );
p = (unsigned char *) key; p = (unsigned char *) key;
end = p + keylen; end = p + keylen;
@ -674,45 +697,88 @@ static int pk_parse_key_pkcs1_der( mbedtls_rsa_context *rsa,
end = p + len; end = p + len;
if( ( ret = mbedtls_asn1_get_int( &p, end, &rsa->ver ) ) != 0 ) if( ( ret = mbedtls_asn1_get_int( &p, end, &version ) ) != 0 )
{ {
return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
} }
if( rsa->ver != 0 ) if( version != 0 )
{ {
return( MBEDTLS_ERR_PK_KEY_INVALID_VERSION ); return( MBEDTLS_ERR_PK_KEY_INVALID_VERSION );
} }
if( ( ret = mbedtls_asn1_get_mpi( &p, end, &rsa->N ) ) != 0 || /* Import N */
( ret = mbedtls_asn1_get_mpi( &p, end, &rsa->E ) ) != 0 || if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
( ret = mbedtls_asn1_get_mpi( &p, end, &rsa->D ) ) != 0 || MBEDTLS_ASN1_INTEGER ) ) != 0 ||
( ret = mbedtls_asn1_get_mpi( &p, end, &rsa->P ) ) != 0 || ( ret = mbedtls_rsa_import_raw( rsa, p, len, NULL, 0, NULL, 0,
( ret = mbedtls_asn1_get_mpi( &p, end, &rsa->Q ) ) != 0 || NULL, 0, NULL, 0 ) ) != 0 )
( ret = mbedtls_asn1_get_mpi( &p, end, &rsa->DP ) ) != 0 || goto cleanup;
( ret = mbedtls_asn1_get_mpi( &p, end, &rsa->DQ ) ) != 0 || p += len;
( ret = mbedtls_asn1_get_mpi( &p, end, &rsa->QP ) ) != 0 )
{
mbedtls_rsa_free( rsa );
return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
}
rsa->len = mbedtls_mpi_size( &rsa->N ); /* Import E */
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_INTEGER ) ) != 0 ||
( ret = mbedtls_rsa_import_raw( rsa, NULL, 0, NULL, 0, NULL, 0,
NULL, 0, p, len ) ) != 0 )
goto cleanup;
p += len;
/* Import D */
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_INTEGER ) ) != 0 ||
( ret = mbedtls_rsa_import_raw( rsa, NULL, 0, NULL, 0, NULL, 0,
p, len, NULL, 0 ) ) != 0 )
goto cleanup;
p += len;
/* Import P */
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_INTEGER ) ) != 0 ||
( ret = mbedtls_rsa_import_raw( rsa, NULL, 0, p, len, NULL, 0,
NULL, 0, NULL, 0 ) ) != 0 )
goto cleanup;
p += len;
/* Import Q */
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_INTEGER ) ) != 0 ||
( ret = mbedtls_rsa_import_raw( rsa, NULL, 0, NULL, 0, p, len,
NULL, 0, NULL, 0 ) ) != 0 )
goto cleanup;
p += len;
/* Complete the RSA private key */
if( ( ret = mbedtls_rsa_complete( rsa ) ) != 0 )
goto cleanup;
/* Check optional parameters */
if( ( ret = mbedtls_asn1_get_mpi( &p, end, &T ) ) != 0 ||
( ret = mbedtls_asn1_get_mpi( &p, end, &T ) ) != 0 ||
( ret = mbedtls_asn1_get_mpi( &p, end, &T ) ) != 0 )
goto cleanup;
if( p != end ) if( p != end )
{ {
mbedtls_rsa_free( rsa ); ret = MBEDTLS_ERR_PK_KEY_INVALID_FORMAT +
return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ;
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
} }
if( ( ret = mbedtls_rsa_check_privkey( rsa ) ) != 0 ) cleanup:
mbedtls_mpi_free( &T );
if( ret != 0 )
{ {
/* Wrap error code if it's coming from a lower level */
if( ( ret & 0xff80 ) == 0 )
ret = MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret;
else
ret = MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
mbedtls_rsa_free( rsa ); mbedtls_rsa_free( rsa );
return( ret );
} }
return( 0 ); return( ret );
} }
#endif /* MBEDTLS_RSA_C */ #endif /* MBEDTLS_RSA_C */
@ -844,6 +910,16 @@ static int pk_parse_key_sec1_der( mbedtls_ecp_keypair *eck,
/* /*
* Parse an unencrypted PKCS#8 encoded private key * Parse an unencrypted PKCS#8 encoded private key
*
* Notes:
*
* - This function does not own the key buffer. It is the
* responsibility of the caller to take care of zeroizing
* and freeing it after use.
*
* - The function is responsible for freeing the provided
* PK context on failure.
*
*/ */
static int pk_parse_key_pkcs8_unencrypted_der( static int pk_parse_key_pkcs8_unencrypted_der(
mbedtls_pk_context *pk, mbedtls_pk_context *pk,
@ -859,7 +935,7 @@ static int pk_parse_key_pkcs8_unencrypted_der(
const mbedtls_pk_info_t *pk_info; const mbedtls_pk_info_t *pk_info;
/* /*
* This function parses the PrivatKeyInfo object (PKCS#8 v1.2 = RFC 5208) * This function parses the PrivateKeyInfo object (PKCS#8 v1.2 = RFC 5208)
* *
* PrivateKeyInfo ::= SEQUENCE { * PrivateKeyInfo ::= SEQUENCE {
* version Version, * version Version,
@ -932,16 +1008,22 @@ static int pk_parse_key_pkcs8_unencrypted_der(
/* /*
* Parse an encrypted PKCS#8 encoded private key * Parse an encrypted PKCS#8 encoded private key
*
* To save space, the decryption happens in-place on the given key buffer.
* Also, while this function may modify the keybuffer, it doesn't own it,
* and instead it is the responsibility of the caller to zeroize and properly
* free it after use.
*
*/ */
#if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C) #if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
static int pk_parse_key_pkcs8_encrypted_der( static int pk_parse_key_pkcs8_encrypted_der(
mbedtls_pk_context *pk, mbedtls_pk_context *pk,
const unsigned char *key, size_t keylen, unsigned char *key, size_t keylen,
const unsigned char *pwd, size_t pwdlen ) const unsigned char *pwd, size_t pwdlen )
{ {
int ret, decrypted = 0; int ret, decrypted = 0;
size_t len; size_t len;
unsigned char buf[2048]; unsigned char *buf;
unsigned char *p, *end; unsigned char *p, *end;
mbedtls_asn1_buf pbe_alg_oid, pbe_params; mbedtls_asn1_buf pbe_alg_oid, pbe_params;
#if defined(MBEDTLS_PKCS12_C) #if defined(MBEDTLS_PKCS12_C)
@ -949,16 +1031,14 @@ static int pk_parse_key_pkcs8_encrypted_der(
mbedtls_md_type_t md_alg; mbedtls_md_type_t md_alg;
#endif #endif
memset( buf, 0, sizeof( buf ) ); p = key;
p = (unsigned char *) key;
end = p + keylen; end = p + keylen;
if( pwdlen == 0 ) if( pwdlen == 0 )
return( MBEDTLS_ERR_PK_PASSWORD_REQUIRED ); return( MBEDTLS_ERR_PK_PASSWORD_REQUIRED );
/* /*
* This function parses the EncryptedPrivatKeyInfo object (PKCS#8) * This function parses the EncryptedPrivateKeyInfo object (PKCS#8)
* *
* EncryptedPrivateKeyInfo ::= SEQUENCE { * EncryptedPrivateKeyInfo ::= SEQUENCE {
* encryptionAlgorithm EncryptionAlgorithmIdentifier, * encryptionAlgorithm EncryptionAlgorithmIdentifier,
@ -970,6 +1050,7 @@ static int pk_parse_key_pkcs8_encrypted_der(
* EncryptedData ::= OCTET STRING * EncryptedData ::= OCTET STRING
* *
* The EncryptedData OCTET STRING is a PKCS#8 PrivateKeyInfo * The EncryptedData OCTET STRING is a PKCS#8 PrivateKeyInfo
*
*/ */
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
@ -985,11 +1066,10 @@ static int pk_parse_key_pkcs8_encrypted_der(
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 ) if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret ); return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT + ret );
if( len > sizeof( buf ) ) buf = p;
return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
/* /*
* Decrypt EncryptedData with appropriate PDE * Decrypt EncryptedData with appropriate PBE
*/ */
#if defined(MBEDTLS_PKCS12_C) #if defined(MBEDTLS_PKCS12_C)
if( mbedtls_oid_get_pkcs12_pbe_alg( &pbe_alg_oid, &md_alg, &cipher_alg ) == 0 ) if( mbedtls_oid_get_pkcs12_pbe_alg( &pbe_alg_oid, &md_alg, &cipher_alg ) == 0 )
@ -1081,10 +1161,8 @@ int mbedtls_pk_parse_key( mbedtls_pk_context *pk,
if( ret == 0 ) if( ret == 0 )
{ {
if( ( pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA ) ) == NULL ) pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA );
return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG ); if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 ||
if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 ||
( ret = pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ), ( ret = pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ),
pem.buf, pem.buflen ) ) != 0 ) pem.buf, pem.buflen ) ) != 0 )
{ {
@ -1113,10 +1191,9 @@ int mbedtls_pk_parse_key( mbedtls_pk_context *pk,
key, pwd, pwdlen, &len ); key, pwd, pwdlen, &len );
if( ret == 0 ) if( ret == 0 )
{ {
if( ( pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY ) ) == NULL ) pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY );
return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );
if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 || if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 ||
( ret = pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ), ( ret = pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ),
pem.buf, pem.buflen ) ) != 0 ) pem.buf, pem.buflen ) ) != 0 )
{ {
@ -1194,12 +1271,24 @@ int mbedtls_pk_parse_key( mbedtls_pk_context *pk,
* error * error
*/ */
#if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C) #if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
if( ( ret = pk_parse_key_pkcs8_encrypted_der( pk, key, keylen,
pwd, pwdlen ) ) == 0 )
{ {
return( 0 ); unsigned char *key_copy;
if( ( key_copy = mbedtls_calloc( 1, keylen ) ) == NULL )
return( MBEDTLS_ERR_PK_ALLOC_FAILED );
memcpy( key_copy, key, keylen );
ret = pk_parse_key_pkcs8_encrypted_der( pk, key_copy, keylen,
pwd, pwdlen );
mbedtls_zeroize( key_copy, keylen );
mbedtls_free( key_copy );
} }
if( ret == 0 )
return( 0 );
mbedtls_pk_free( pk ); mbedtls_pk_free( pk );
if( ret == MBEDTLS_ERR_PK_PASSWORD_MISMATCH ) if( ret == MBEDTLS_ERR_PK_PASSWORD_MISMATCH )
@ -1214,29 +1303,35 @@ int mbedtls_pk_parse_key( mbedtls_pk_context *pk,
mbedtls_pk_free( pk ); mbedtls_pk_free( pk );
#if defined(MBEDTLS_RSA_C) #if defined(MBEDTLS_RSA_C)
if( ( pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA ) ) == NULL )
return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );
if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 || pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA );
( ret = pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ), key, keylen ) ) == 0 ) if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 ||
( ret = pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ),
key, keylen ) ) != 0 )
{
mbedtls_pk_free( pk );
}
else
{ {
return( 0 ); return( 0 );
} }
mbedtls_pk_free( pk );
#endif /* MBEDTLS_RSA_C */ #endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_ECP_C) #if defined(MBEDTLS_ECP_C)
if( ( pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY ) ) == NULL )
return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );
if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 || pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY );
( ret = pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ), key, keylen ) ) == 0 ) if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 ||
( ret = pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ),
key, keylen ) ) != 0 )
{
mbedtls_pk_free( pk );
}
else
{ {
return( 0 ); return( 0 );
} }
mbedtls_pk_free( pk );
#endif /* MBEDTLS_ECP_C */ #endif /* MBEDTLS_ECP_C */
return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT ); return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );

View file

@ -62,13 +62,31 @@
* } * }
*/ */
static int pk_write_rsa_pubkey( unsigned char **p, unsigned char *start, static int pk_write_rsa_pubkey( unsigned char **p, unsigned char *start,
mbedtls_rsa_context *rsa ) mbedtls_rsa_context *rsa )
{ {
int ret; int ret;
size_t len = 0; size_t len = 0;
mbedtls_mpi T;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( p, start, &rsa->E ) ); mbedtls_mpi_init( &T );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( p, start, &rsa->N ) );
/* Export E */
if ( ( ret = mbedtls_rsa_export( rsa, NULL, NULL, NULL, NULL, &T ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( p, start, &T ) ) < 0 )
goto end_of_export;
len += ret;
/* Export N */
if ( ( ret = mbedtls_rsa_export( rsa, &T, NULL, NULL, NULL, NULL ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( p, start, &T ) ) < 0 )
goto end_of_export;
len += ret;
end_of_export:
mbedtls_mpi_free( &T );
if( ret < 0 )
return( ret );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_CONSTRUCTED |
@ -83,7 +101,7 @@ static int pk_write_rsa_pubkey( unsigned char **p, unsigned char *start,
* EC public key is an EC point * EC public key is an EC point
*/ */
static int pk_write_ec_pubkey( unsigned char **p, unsigned char *start, static int pk_write_ec_pubkey( unsigned char **p, unsigned char *start,
mbedtls_ecp_keypair *ec ) mbedtls_ecp_keypair *ec )
{ {
int ret; int ret;
size_t len = 0; size_t len = 0;
@ -111,7 +129,7 @@ static int pk_write_ec_pubkey( unsigned char **p, unsigned char *start,
* } * }
*/ */
static int pk_write_ec_param( unsigned char **p, unsigned char *start, static int pk_write_ec_param( unsigned char **p, unsigned char *start,
mbedtls_ecp_keypair *ec ) mbedtls_ecp_keypair *ec )
{ {
int ret; int ret;
size_t len = 0; size_t len = 0;
@ -128,7 +146,7 @@ static int pk_write_ec_param( unsigned char **p, unsigned char *start,
#endif /* MBEDTLS_ECP_C */ #endif /* MBEDTLS_ECP_C */
int mbedtls_pk_write_pubkey( unsigned char **p, unsigned char *start, int mbedtls_pk_write_pubkey( unsigned char **p, unsigned char *start,
const mbedtls_pk_context *key ) const mbedtls_pk_context *key )
{ {
int ret; int ret;
size_t len = 0; size_t len = 0;
@ -205,21 +223,79 @@ int mbedtls_pk_write_key_der( mbedtls_pk_context *key, unsigned char *buf, size_
#if defined(MBEDTLS_RSA_C) #if defined(MBEDTLS_RSA_C)
if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_RSA ) if( mbedtls_pk_get_type( key ) == MBEDTLS_PK_RSA )
{ {
mbedtls_mpi T; /* Temporary holding the exported parameters */
mbedtls_rsa_context *rsa = mbedtls_pk_rsa( *key ); mbedtls_rsa_context *rsa = mbedtls_pk_rsa( *key );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &c, buf, &rsa->QP ) ); /*
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &c, buf, &rsa->DQ ) ); * Export the parameters one after another to avoid simultaneous copies.
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &c, buf, &rsa->DP ) ); */
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &c, buf, &rsa->Q ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &c, buf, &rsa->P ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &c, buf, &rsa->D ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &c, buf, &rsa->E ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &c, buf, &rsa->N ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_int( &c, buf, 0 ) );
mbedtls_mpi_init( &T );
/* Export QP */
if( ( ret = mbedtls_rsa_export_crt( rsa, NULL, NULL, &T ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
goto end_of_export;
len += ret;
/* Export DQ */
if( ( ret = mbedtls_rsa_export_crt( rsa, NULL, &T, NULL ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
goto end_of_export;
len += ret;
/* Export DP */
if( ( ret = mbedtls_rsa_export_crt( rsa, &T, NULL, NULL ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
goto end_of_export;
len += ret;
/* Export Q */
if ( ( ret = mbedtls_rsa_export( rsa, NULL, NULL,
&T, NULL, NULL ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
goto end_of_export;
len += ret;
/* Export P */
if ( ( ret = mbedtls_rsa_export( rsa, NULL, &T,
NULL, NULL, NULL ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
goto end_of_export;
len += ret;
/* Export D */
if ( ( ret = mbedtls_rsa_export( rsa, NULL, NULL,
NULL, &T, NULL ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
goto end_of_export;
len += ret;
/* Export E */
if ( ( ret = mbedtls_rsa_export( rsa, NULL, NULL,
NULL, NULL, &T ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
goto end_of_export;
len += ret;
/* Export N */
if ( ( ret = mbedtls_rsa_export( rsa, &T, NULL,
NULL, NULL, NULL ) ) != 0 ||
( ret = mbedtls_asn1_write_mpi( &c, buf, &T ) ) < 0 )
goto end_of_export;
len += ret;
end_of_export:
mbedtls_mpi_free( &T );
if( ret < 0 )
return( ret );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_int( &c, buf, 0 ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c,
MBEDTLS_ASN1_SEQUENCE ) ); buf, MBEDTLS_ASN1_CONSTRUCTED |
MBEDTLS_ASN1_SEQUENCE ) );
} }
else else
#endif /* MBEDTLS_RSA_C */ #endif /* MBEDTLS_RSA_C */

View file

@ -304,4 +304,24 @@ int mbedtls_platform_set_nv_seed(
#endif /* MBEDTLS_PLATFORM_NV_SEED_ALT */ #endif /* MBEDTLS_PLATFORM_NV_SEED_ALT */
#endif /* MBEDTLS_ENTROPY_NV_SEED */ #endif /* MBEDTLS_ENTROPY_NV_SEED */
#if !defined(MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT)
/*
* Placeholder platform setup that does nothing by default
*/
int mbedtls_platform_setup( mbedtls_platform_context *ctx )
{
(void)ctx;
return( 0 );
}
/*
* Placeholder platform teardown that does nothing by default
*/
void mbedtls_platform_teardown( mbedtls_platform_context *ctx )
{
(void)ctx;
}
#endif /* MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */
#endif /* MBEDTLS_PLATFORM_C */ #endif /* MBEDTLS_PLATFORM_C */

File diff suppressed because it is too large Load diff

487
library/rsa_internal.c Normal file
View file

@ -0,0 +1,487 @@
/*
* Helper functions for the RSA module
*
* Copyright (C) 2006-2017, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_RSA_C)
#include "mbedtls/rsa.h"
#include "mbedtls/bignum.h"
#include "mbedtls/rsa_internal.h"
/*
* Compute RSA prime factors from public and private exponents
*
* Summary of algorithm:
* Setting F := lcm(P-1,Q-1), the idea is as follows:
*
* (a) For any 1 <= X < N with gcd(X,N)=1, we have X^F = 1 modulo N, so X^(F/2)
* is a square root of 1 in Z/NZ. Since Z/NZ ~= Z/PZ x Z/QZ by CRT and the
* square roots of 1 in Z/PZ and Z/QZ are +1 and -1, this leaves the four
* possibilities X^(F/2) = (+-1, +-1). If it happens that X^(F/2) = (-1,+1)
* or (+1,-1), then gcd(X^(F/2) + 1, N) will be equal to one of the prime
* factors of N.
*
* (b) If we don't know F/2 but (F/2) * K for some odd (!) K, then the same
* construction still applies since (-)^K is the identity on the set of
* roots of 1 in Z/NZ.
*
* The public and private key primitives (-)^E and (-)^D are mutually inverse
* bijections on Z/NZ if and only if (-)^(DE) is the identity on Z/NZ, i.e.
* if and only if DE - 1 is a multiple of F, say DE - 1 = F * L.
* Splitting L = 2^t * K with K odd, we have
*
* DE - 1 = FL = (F/2) * (2^(t+1)) * K,
*
* so (F / 2) * K is among the numbers
*
* (DE - 1) >> 1, (DE - 1) >> 2, ..., (DE - 1) >> ord
*
* where ord is the order of 2 in (DE - 1).
* We can therefore iterate through these numbers apply the construction
* of (a) and (b) above to attempt to factor N.
*
*/
int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N,
mbedtls_mpi const *E, mbedtls_mpi const *D,
mbedtls_mpi *P, mbedtls_mpi *Q )
{
int ret = 0;
uint16_t attempt; /* Number of current attempt */
uint16_t iter; /* Number of squares computed in the current attempt */
uint16_t order; /* Order of 2 in DE - 1 */
mbedtls_mpi T; /* Holds largest odd divisor of DE - 1 */
mbedtls_mpi K; /* Temporary holding the current candidate */
const unsigned char primes[] = { 2,
3, 5, 7, 11, 13, 17, 19, 23,
29, 31, 37, 41, 43, 47, 53, 59,
61, 67, 71, 73, 79, 83, 89, 97,
101, 103, 107, 109, 113, 127, 131, 137,
139, 149, 151, 157, 163, 167, 173, 179,
181, 191, 193, 197, 199, 211, 223, 227,
229, 233, 239, 241, 251
};
const size_t num_primes = sizeof( primes ) / sizeof( *primes );
if( P == NULL || Q == NULL || P->p != NULL || Q->p != NULL )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
if( mbedtls_mpi_cmp_int( N, 0 ) <= 0 ||
mbedtls_mpi_cmp_int( D, 1 ) <= 0 ||
mbedtls_mpi_cmp_mpi( D, N ) >= 0 ||
mbedtls_mpi_cmp_int( E, 1 ) <= 0 ||
mbedtls_mpi_cmp_mpi( E, N ) >= 0 )
{
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
}
/*
* Initializations and temporary changes
*/
mbedtls_mpi_init( &K );
mbedtls_mpi_init( &T );
/* T := DE - 1 */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, D, E ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &T, &T, 1 ) );
if( ( order = (uint16_t) mbedtls_mpi_lsb( &T ) ) == 0 )
{
ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
goto cleanup;
}
/* After this operation, T holds the largest odd divisor of DE - 1. */
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &T, order ) );
/*
* Actual work
*/
/* Skip trying 2 if N == 1 mod 8 */
attempt = 0;
if( N->p[0] % 8 == 1 )
attempt = 1;
for( ; attempt < num_primes; ++attempt )
{
mbedtls_mpi_lset( &K, primes[attempt] );
/* Check if gcd(K,N) = 1 */
MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( P, &K, N ) );
if( mbedtls_mpi_cmp_int( P, 1 ) != 0 )
continue;
/* Go through K^T + 1, K^(2T) + 1, K^(4T) + 1, ...
* and check whether they have nontrivial GCD with N. */
MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &K, &K, &T, N,
Q /* temporarily use Q for storing Montgomery
* multiplication helper values */ ) );
for( iter = 1; iter <= order; ++iter )
{
/* If we reach 1 prematurely, there's no point
* in continuing to square K */
if( mbedtls_mpi_cmp_int( &K, 1 ) == 0 )
break;
MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &K, &K, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( P, &K, N ) );
if( mbedtls_mpi_cmp_int( P, 1 ) == 1 &&
mbedtls_mpi_cmp_mpi( P, N ) == -1 )
{
/*
* Have found a nontrivial divisor P of N.
* Set Q := N / P.
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( Q, NULL, N, P ) );
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, &K, &K ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, N ) );
}
/*
* If we get here, then either we prematurely aborted the loop because
* we reached 1, or K holds primes[attempt]^(DE - 1) mod N, which must
* be 1 if D,E,N were consistent.
* Check if that's the case and abort if not, to avoid very long,
* yet eventually failing, computations if N,D,E were not sane.
*/
if( mbedtls_mpi_cmp_int( &K, 1 ) != 0 )
{
break;
}
}
ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
cleanup:
mbedtls_mpi_free( &K );
mbedtls_mpi_free( &T );
return( ret );
}
/*
* Given P, Q and the public exponent E, deduce D.
* This is essentially a modular inversion.
*/
int mbedtls_rsa_deduce_private_exponent( mbedtls_mpi const *P,
mbedtls_mpi const *Q,
mbedtls_mpi const *E,
mbedtls_mpi *D )
{
int ret = 0;
mbedtls_mpi K, L;
if( D == NULL || mbedtls_mpi_cmp_int( D, 0 ) != 0 )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
if( mbedtls_mpi_cmp_int( P, 1 ) <= 0 ||
mbedtls_mpi_cmp_int( Q, 1 ) <= 0 ||
mbedtls_mpi_cmp_int( E, 0 ) == 0 )
{
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
}
mbedtls_mpi_init( &K );
mbedtls_mpi_init( &L );
/* Temporarily put K := P-1 and L := Q-1 */
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, Q, 1 ) );
/* Temporarily put D := gcd(P-1, Q-1) */
MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( D, &K, &L ) );
/* K := LCM(P-1, Q-1) */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, &K, &L ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &K, NULL, &K, D ) );
/* Compute modular inverse of E in LCM(P-1, Q-1) */
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( D, E, &K ) );
cleanup:
mbedtls_mpi_free( &K );
mbedtls_mpi_free( &L );
return( ret );
}
/*
* Check that RSA CRT parameters are in accordance with core parameters.
*/
int mbedtls_rsa_validate_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q,
const mbedtls_mpi *D, const mbedtls_mpi *DP,
const mbedtls_mpi *DQ, const mbedtls_mpi *QP )
{
int ret = 0;
mbedtls_mpi K, L;
mbedtls_mpi_init( &K );
mbedtls_mpi_init( &L );
/* Check that DP - D == 0 mod P - 1 */
if( DP != NULL )
{
if( P == NULL )
{
ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &L, DP, D ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &L, &L, &K ) );
if( mbedtls_mpi_cmp_int( &L, 0 ) != 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
}
/* Check that DQ - D == 0 mod Q - 1 */
if( DQ != NULL )
{
if( Q == NULL )
{
ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, Q, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &L, DQ, D ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &L, &L, &K ) );
if( mbedtls_mpi_cmp_int( &L, 0 ) != 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
}
/* Check that QP * Q - 1 == 0 mod P */
if( QP != NULL )
{
if( P == NULL || Q == NULL )
{
ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, QP, Q ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, P ) );
if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
}
cleanup:
/* Wrap MPI error codes by RSA check failure error code */
if( ret != 0 &&
ret != MBEDTLS_ERR_RSA_KEY_CHECK_FAILED &&
ret != MBEDTLS_ERR_RSA_BAD_INPUT_DATA )
{
ret += MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
}
mbedtls_mpi_free( &K );
mbedtls_mpi_free( &L );
return( ret );
}
/*
* Check that core RSA parameters are sane.
*/
int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P,
const mbedtls_mpi *Q, const mbedtls_mpi *D,
const mbedtls_mpi *E,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = 0;
mbedtls_mpi K, L;
mbedtls_mpi_init( &K );
mbedtls_mpi_init( &L );
/*
* Step 1: If PRNG provided, check that P and Q are prime
*/
#if defined(MBEDTLS_GENPRIME)
if( f_rng != NULL && P != NULL &&
( ret = mbedtls_mpi_is_prime( P, f_rng, p_rng ) ) != 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
if( f_rng != NULL && Q != NULL &&
( ret = mbedtls_mpi_is_prime( Q, f_rng, p_rng ) ) != 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
#else
((void) f_rng);
((void) p_rng);
#endif /* MBEDTLS_GENPRIME */
/*
* Step 2: Check that 1 < N = P * Q
*/
if( P != NULL && Q != NULL && N != NULL )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, P, Q ) );
if( mbedtls_mpi_cmp_int( N, 1 ) <= 0 ||
mbedtls_mpi_cmp_mpi( &K, N ) != 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
}
/*
* Step 3: Check and 1 < D, E < N if present.
*/
if( N != NULL && D != NULL && E != NULL )
{
if ( mbedtls_mpi_cmp_int( D, 1 ) <= 0 ||
mbedtls_mpi_cmp_int( E, 1 ) <= 0 ||
mbedtls_mpi_cmp_mpi( D, N ) >= 0 ||
mbedtls_mpi_cmp_mpi( E, N ) >= 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
}
/*
* Step 4: Check that D, E are inverse modulo P-1 and Q-1
*/
if( P != NULL && Q != NULL && D != NULL && E != NULL )
{
if( mbedtls_mpi_cmp_int( P, 1 ) <= 0 ||
mbedtls_mpi_cmp_int( Q, 1 ) <= 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
/* Compute DE-1 mod P-1 */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, D, E ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, P, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, &L ) );
if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
/* Compute DE-1 mod Q-1 */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, D, E ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, Q, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, &L ) );
if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
}
cleanup:
mbedtls_mpi_free( &K );
mbedtls_mpi_free( &L );
/* Wrap MPI error codes by RSA check failure error code */
if( ret != 0 && ret != MBEDTLS_ERR_RSA_KEY_CHECK_FAILED )
{
ret += MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
}
return( ret );
}
int mbedtls_rsa_deduce_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q,
const mbedtls_mpi *D, mbedtls_mpi *DP,
mbedtls_mpi *DQ, mbedtls_mpi *QP )
{
int ret = 0;
mbedtls_mpi K;
mbedtls_mpi_init( &K );
/* DP = D mod P-1 */
if( DP != NULL )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( DP, D, &K ) );
}
/* DQ = D mod Q-1 */
if( DQ != NULL )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, Q, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( DQ, D, &K ) );
}
/* QP = Q^{-1} mod P */
if( QP != NULL )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( QP, Q, P ) );
}
cleanup:
mbedtls_mpi_free( &K );
return( ret );
}
#endif /* MBEDTLS_RSA_C */

View file

@ -138,7 +138,7 @@ int mbedtls_ssl_cache_set( void *data, const mbedtls_ssl_session *session )
{ {
int ret = 1; int ret = 1;
#if defined(MBEDTLS_HAVE_TIME) #if defined(MBEDTLS_HAVE_TIME)
mbedtls_time_t t = time( NULL ), oldest = 0; mbedtls_time_t t = mbedtls_time( NULL ), oldest = 0;
mbedtls_ssl_cache_entry *old = NULL; mbedtls_ssl_cache_entry *old = NULL;
#endif #endif
mbedtls_ssl_cache_context *cache = (mbedtls_ssl_cache_context *) data; mbedtls_ssl_cache_context *cache = (mbedtls_ssl_cache_context *) data;
@ -321,6 +321,7 @@ void mbedtls_ssl_cache_free( mbedtls_ssl_cache_context *cache )
#if defined(MBEDTLS_THREADING_C) #if defined(MBEDTLS_THREADING_C)
mbedtls_mutex_free( &cache->mutex ); mbedtls_mutex_free( &cache->mutex );
#endif #endif
cache->chain = NULL;
} }
#endif /* MBEDTLS_SSL_CACHE_C */ #endif /* MBEDTLS_SSL_CACHE_C */

View file

@ -1834,6 +1834,42 @@ mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_alg( const mbedtls_ssl_ciphers
return( MBEDTLS_PK_NONE ); return( MBEDTLS_PK_NONE );
} }
} }
#endif /* MBEDTLS_PK_C */ #endif /* MBEDTLS_PK_C */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
int mbedtls_ssl_ciphersuite_uses_ec( const mbedtls_ssl_ciphersuite_t *info )
{
switch( info->key_exchange )
{
case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
return( 1 );
default:
return( 0 );
}
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
int mbedtls_ssl_ciphersuite_uses_psk( const mbedtls_ssl_ciphersuite_t *info )
{
switch( info->key_exchange )
{
case MBEDTLS_KEY_EXCHANGE_PSK:
case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
return( 1 );
default:
return( 0 );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#endif /* MBEDTLS_SSL_TLS_C */ #endif /* MBEDTLS_SSL_TLS_C */

View file

@ -80,6 +80,13 @@ static void ssl_write_hostname_ext( mbedtls_ssl_context *ssl,
} }
/* /*
* Sect. 3, RFC 6066 (TLS Extensions Definitions)
*
* In order to provide any of the server names, clients MAY include an
* extension of type "server_name" in the (extended) client hello. The
* "extension_data" field of this extension SHALL contain
* "ServerNameList" where:
*
* struct { * struct {
* NameType name_type; * NameType name_type;
* select (name_type) { * select (name_type) {
@ -96,6 +103,7 @@ static void ssl_write_hostname_ext( mbedtls_ssl_context *ssl,
* struct { * struct {
* ServerName server_name_list<1..2^16-1> * ServerName server_name_list<1..2^16-1>
* } ServerNameList; * } ServerNameList;
*
*/ */
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME ) & 0xFF );
@ -126,6 +134,9 @@ static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl,
*olen = 0; *olen = 0;
/* We're always including an TLS_EMPTY_RENEGOTIATION_INFO_SCSV in the
* initial ClientHello, in which case also adding the renegotiation
* info extension is NOT RECOMMENDED as per RFC 5746 Section 3.4. */
if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
return; return;
@ -963,6 +974,8 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl )
ext_len += olen; ext_len += olen;
#endif #endif
/* Note that TLS_EMPTY_RENEGOTIATION_INFO_SCSV is always added
* even if MBEDTLS_SSL_RENEGOTIATION is not defined. */
#if defined(MBEDTLS_SSL_RENEGOTIATION) #if defined(MBEDTLS_SSL_RENEGOTIATION)
ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen ); ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen; ext_len += olen;
@ -1440,9 +1453,6 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl )
#endif #endif
int handshake_failure = 0; int handshake_failure = 0;
const mbedtls_ssl_ciphersuite_t *suite_info; const mbedtls_ssl_ciphersuite_t *suite_info;
#if defined(MBEDTLS_DEBUG_C)
uint32_t t;
#endif
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello" ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello" ) );
@ -1545,13 +1555,11 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl )
return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION ); return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
} }
#if defined(MBEDTLS_DEBUG_C) MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %lu",
t = ( (uint32_t) buf[2] << 24 ) ( (uint32_t) buf[2] << 24 ) |
| ( (uint32_t) buf[3] << 16 ) ( (uint32_t) buf[3] << 16 ) |
| ( (uint32_t) buf[4] << 8 ) ( (uint32_t) buf[4] << 8 ) |
| ( (uint32_t) buf[5] ); ( (uint32_t) buf[5] ) ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %lu", t ) );
#endif
memcpy( ssl->handshake->randbytes + 32, buf + 2, 32 ); memcpy( ssl->handshake->randbytes + 32, buf + 2, 32 );
@ -2258,7 +2266,7 @@ static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )
int ret; int ret;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info = const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info; ssl->transform_negotiate->ciphersuite_info;
unsigned char *p, *end; unsigned char *p = NULL, *end = NULL;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) );

View file

@ -1694,11 +1694,8 @@ read_record_header:
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
case MBEDTLS_TLS_EXT_SIG_ALG: case MBEDTLS_TLS_EXT_SIG_ALG:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found signature_algorithms extension" ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "found signature_algorithms extension" ) );
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
break;
#endif
ret = ssl_parse_signature_algorithms_ext( ssl, ext + 4, ext_size ); ret = ssl_parse_signature_algorithms_ext( ssl, ext + 4, ext_size );
if( ret != 0 ) if( ret != 0 )
return( ret ); return( ret );

View file

@ -3504,8 +3504,15 @@ static int ssl_parse_record_header( mbedtls_ssl_context *ssl )
ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA ) ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
{ {
MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type" ) ); MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ); #if defined(MBEDTLS_SSL_PROTO_DTLS)
/* Silently ignore invalid DTLS records as recommended by RFC 6347
* Section 4.1.2.7 */
if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
#endif /* MBEDTLS_SSL_PROTO_DTLS */
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_INVALID_RECORD ); return( MBEDTLS_ERR_SSL_INVALID_RECORD );
} }
@ -6170,7 +6177,7 @@ void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf,
{ {
conf->sig_hashes = hashes; conf->sig_hashes = hashes;
} }
#endif #endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
#if defined(MBEDTLS_ECP_C) #if defined(MBEDTLS_ECP_C)
/* /*
@ -6181,36 +6188,53 @@ void mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf,
{ {
conf->curve_list = curve_list; conf->curve_list = curve_list;
} }
#endif #endif /* MBEDTLS_ECP_C */
#if defined(MBEDTLS_X509_CRT_PARSE_C) #if defined(MBEDTLS_X509_CRT_PARSE_C)
int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname ) int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname )
{ {
size_t hostname_len; /* Initialize to suppress unnecessary compiler warning */
size_t hostname_len = 0;
/* Check if new hostname is valid before
* making any change to current one */
if( hostname != NULL )
{
hostname_len = strlen( hostname );
if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN )
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
/* Now it's clear that we will overwrite the old hostname,
* so we can free it safely */
if( ssl->hostname != NULL )
{
mbedtls_zeroize( ssl->hostname, strlen( ssl->hostname ) );
mbedtls_free( ssl->hostname );
}
/* Passing NULL as hostname shall clear the old one */
if( hostname == NULL ) if( hostname == NULL )
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); {
ssl->hostname = NULL;
}
else
{
ssl->hostname = mbedtls_calloc( 1, hostname_len + 1 );
if( ssl->hostname == NULL )
return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
hostname_len = strlen( hostname ); memcpy( ssl->hostname, hostname, hostname_len );
if( hostname_len + 1 == 0 ) ssl->hostname[hostname_len] = '\0';
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); }
if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN )
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
ssl->hostname = mbedtls_calloc( 1, hostname_len + 1 );
if( ssl->hostname == NULL )
return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
memcpy( ssl->hostname, hostname, hostname_len );
ssl->hostname[hostname_len] = '\0';
return( 0 ); return( 0 );
} }
#endif #endif /* MBEDTLS_X509_CRT_PARSE_C */
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf, void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf,
@ -6870,7 +6894,6 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )
} }
} }
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
{ {
MBEDTLS_SSL_DEBUG_MSG( 1, ( "received handshake message" ) ); MBEDTLS_SSL_DEBUG_MSG( 1, ( "received handshake message" ) );
@ -6912,12 +6935,35 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )
} }
#endif /* MBEDTLS_SSL_SRV_C */ #endif /* MBEDTLS_SSL_SRV_C */
#if defined(MBEDTLS_SSL_RENEGOTIATION)
/* Determine whether renegotiation attempt should be accepted */ /* Determine whether renegotiation attempt should be accepted */
if( ! ( ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ||
( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
ssl->conf->allow_legacy_renegotiation ==
MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) ) )
{
/*
* Accept renegotiation request
*/
if( ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED || /* DTLS clients need to know renego is server-initiated */
( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && #if defined(MBEDTLS_SSL_PROTO_DTLS)
ssl->conf->allow_legacy_renegotiation == if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) ) ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
{
ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
}
#endif
ret = ssl_start_renegotiation( ssl );
if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_SSL_RENEGOTIATION */
{ {
/* /*
* Refuse renegotiation * Refuse renegotiation
@ -6955,31 +7001,10 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
} }
} }
else
{
/*
* Accept renegotiation request
*/
/* DTLS clients need to know renego is server-initiated */
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
{
ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
}
#endif
ret = ssl_start_renegotiation( ssl );
if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
return( ret );
}
}
return( MBEDTLS_ERR_SSL_WANT_READ ); return( MBEDTLS_ERR_SSL_WANT_READ );
} }
#if defined(MBEDTLS_SSL_RENEGOTIATION)
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
{ {
if( ssl->conf->renego_max_records >= 0 ) if( ssl->conf->renego_max_records >= 0 )
@ -7065,7 +7090,9 @@ static int ssl_write_real( mbedtls_ssl_context *ssl,
int ret; int ret;
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
size_t max_len = mbedtls_ssl_get_max_frag_len( ssl ); size_t max_len = mbedtls_ssl_get_max_frag_len( ssl );
#else
size_t max_len = MBEDTLS_SSL_MAX_CONTENT_LEN;
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
if( len > max_len ) if( len > max_len )
{ {
#if defined(MBEDTLS_SSL_PROTO_DTLS) #if defined(MBEDTLS_SSL_PROTO_DTLS)
@ -7080,7 +7107,6 @@ static int ssl_write_real( mbedtls_ssl_context *ssl,
#endif #endif
len = max_len; len = max_len;
} }
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
if( ssl->out_left != 0 ) if( ssl->out_left != 0 )
{ {
@ -7111,7 +7137,7 @@ static int ssl_write_real( mbedtls_ssl_context *ssl,
* *
* With non-blocking I/O, ssl_write_real() may return WANT_WRITE, * With non-blocking I/O, ssl_write_real() may return WANT_WRITE,
* then the caller will call us again with the same arguments, so * then the caller will call us again with the same arguments, so
* remember wether we already did the split or not. * remember whether we already did the split or not.
*/ */
#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
static int ssl_write_split( mbedtls_ssl_context *ssl, static int ssl_write_split( mbedtls_ssl_context *ssl,

View file

@ -113,9 +113,6 @@ void mbedtls_threading_set_alt( void (*mutex_init)( mbedtls_threading_mutex_t *
mbedtls_mutex_init( &mbedtls_threading_readdir_mutex ); mbedtls_mutex_init( &mbedtls_threading_readdir_mutex );
mbedtls_mutex_init( &mbedtls_threading_gmtime_mutex ); mbedtls_mutex_init( &mbedtls_threading_gmtime_mutex );
#if defined(MBEDTLS_ECP_INTERNAL_ALT)
mbedtls_mutex_init( &mbedtls_threading_ecp_mutex );
#endif
} }
/* /*
@ -125,9 +122,6 @@ void mbedtls_threading_free_alt( void )
{ {
mbedtls_mutex_free( &mbedtls_threading_readdir_mutex ); mbedtls_mutex_free( &mbedtls_threading_readdir_mutex );
mbedtls_mutex_free( &mbedtls_threading_gmtime_mutex ); mbedtls_mutex_free( &mbedtls_threading_gmtime_mutex );
#if defined(MBEDTLS_ECP_INTERNAL_ALT)
mbedtls_mutex_free( &mbedtls_threading_ecp_mutex );
#endif
} }
#endif /* MBEDTLS_THREADING_ALT */ #endif /* MBEDTLS_THREADING_ALT */
@ -139,8 +133,5 @@ void mbedtls_threading_free_alt( void )
#endif #endif
mbedtls_threading_mutex_t mbedtls_threading_readdir_mutex MUTEX_INIT; mbedtls_threading_mutex_t mbedtls_threading_readdir_mutex MUTEX_INIT;
mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex MUTEX_INIT; mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex MUTEX_INIT;
#if defined(MBEDTLS_ECP_INTERNAL_ALT)
mbedtls_threading_mutex_t mbedtls_threading_ecp_mutex MUTEX_INIT;
#endif
#endif /* MBEDTLS_THREADING_C */ #endif /* MBEDTLS_THREADING_C */

View file

@ -244,21 +244,23 @@ volatile int mbedtls_timing_alarmed = 0;
unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset ) unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset )
{ {
unsigned long delta;
LARGE_INTEGER offset, hfreq;
struct _hr_time *t = (struct _hr_time *) val; struct _hr_time *t = (struct _hr_time *) val;
QueryPerformanceCounter( &offset );
QueryPerformanceFrequency( &hfreq );
delta = (unsigned long)( ( 1000 *
( offset.QuadPart - t->start.QuadPart ) ) /
hfreq.QuadPart );
if( reset ) if( reset )
{
QueryPerformanceCounter( &t->start ); QueryPerformanceCounter( &t->start );
return( 0 );
return( delta ); }
else
{
unsigned long delta;
LARGE_INTEGER now, hfreq;
QueryPerformanceCounter( &now );
QueryPerformanceFrequency( &hfreq );
delta = (unsigned long)( ( now.QuadPart - t->start.QuadPart ) * 1000ul
/ hfreq.QuadPart );
return( delta );
}
} }
/* It's OK to use a global because alarm() is supposed to be global anyway */ /* It's OK to use a global because alarm() is supposed to be global anyway */
@ -285,23 +287,22 @@ void mbedtls_set_alarm( int seconds )
unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset ) unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset )
{ {
unsigned long delta;
struct timeval offset;
struct _hr_time *t = (struct _hr_time *) val; struct _hr_time *t = (struct _hr_time *) val;
gettimeofday( &offset, NULL );
if( reset ) if( reset )
{ {
t->start.tv_sec = offset.tv_sec; gettimeofday( &t->start, NULL );
t->start.tv_usec = offset.tv_usec;
return( 0 ); return( 0 );
} }
else
delta = ( offset.tv_sec - t->start.tv_sec ) * 1000 {
+ ( offset.tv_usec - t->start.tv_usec ) / 1000; unsigned long delta;
struct timeval now;
return( delta ); gettimeofday( &now, NULL );
delta = ( now.tv_sec - t->start.tv_sec ) * 1000ul
+ ( now.tv_usec - t->start.tv_usec ) / 1000;
return( delta );
}
} }
static void sighandler( int signum ) static void sighandler( int signum )
@ -315,6 +316,12 @@ void mbedtls_set_alarm( int seconds )
mbedtls_timing_alarmed = 0; mbedtls_timing_alarmed = 0;
signal( SIGALRM, sighandler ); signal( SIGALRM, sighandler );
alarm( seconds ); alarm( seconds );
if( seconds == 0 )
{
/* alarm(0) cancelled any previous pending alarm, but the
handler won't fire, so raise the flag straight away. */
mbedtls_timing_alarmed = 1;
}
} }
#endif /* _WIN32 && !EFIX64 && !EFI32 */ #endif /* _WIN32 && !EFIX64 && !EFI32 */
@ -378,13 +385,21 @@ static void busy_msleep( unsigned long msec )
(void) j; (void) j;
} }
#define FAIL do \ #define FAIL do \
{ \ { \
if( verbose != 0 ) \ if( verbose != 0 ) \
mbedtls_printf( "failed\n" ); \ { \
\ mbedtls_printf( "failed at line %d\n", __LINE__ ); \
return( 1 ); \ mbedtls_printf( " cycles=%lu ratio=%lu millisecs=%lu secs=%lu hardfail=%d a=%lu b=%lu\n", \
} while( 0 ) cycles, ratio, millisecs, secs, hardfail, \
(unsigned long) a, (unsigned long) b ); \
mbedtls_printf( " elapsed(hires)=%lu elapsed(ctx)=%lu status(ctx)=%d\n", \
mbedtls_timing_get_timer( &hires, 0 ), \
mbedtls_timing_get_timer( &ctx.timer, 0 ), \
mbedtls_timing_get_delay( &ctx ) ); \
} \
return( 1 ); \
} while( 0 )
/* /*
* Checkup routine * Checkup routine
@ -394,22 +409,22 @@ static void busy_msleep( unsigned long msec )
*/ */
int mbedtls_timing_self_test( int verbose ) int mbedtls_timing_self_test( int verbose )
{ {
unsigned long cycles, ratio; unsigned long cycles = 0, ratio = 0;
unsigned long millisecs, secs; unsigned long millisecs = 0, secs = 0;
int hardfail; int hardfail = 0;
struct mbedtls_timing_hr_time hires; struct mbedtls_timing_hr_time hires;
uint32_t a, b; uint32_t a = 0, b = 0;
mbedtls_timing_delay_context ctx; mbedtls_timing_delay_context ctx;
if( verbose != 0 ) if( verbose != 0 )
mbedtls_printf( " TIMING tests note: will take some time!\n" ); mbedtls_printf( " TIMING tests note: will take some time!\n" );
if( verbose != 0 ) if( verbose != 0 )
mbedtls_printf( " TIMING test #1 (set_alarm / get_timer): " ); mbedtls_printf( " TIMING test #1 (set_alarm / get_timer): " );
for( secs = 1; secs <= 3; secs++ )
{ {
secs = 1;
(void) mbedtls_timing_get_timer( &hires, 1 ); (void) mbedtls_timing_get_timer( &hires, 1 );
mbedtls_set_alarm( (int) secs ); mbedtls_set_alarm( (int) secs );
@ -421,12 +436,7 @@ int mbedtls_timing_self_test( int verbose )
/* For some reason on Windows it looks like alarm has an extra delay /* For some reason on Windows it looks like alarm has an extra delay
* (maybe related to creating a new thread). Allow some room here. */ * (maybe related to creating a new thread). Allow some room here. */
if( millisecs < 800 * secs || millisecs > 1200 * secs + 300 ) if( millisecs < 800 * secs || millisecs > 1200 * secs + 300 )
{ FAIL;
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
}
} }
if( verbose != 0 ) if( verbose != 0 )
@ -435,28 +445,22 @@ int mbedtls_timing_self_test( int verbose )
if( verbose != 0 ) if( verbose != 0 )
mbedtls_printf( " TIMING test #2 (set/get_delay ): " ); mbedtls_printf( " TIMING test #2 (set/get_delay ): " );
for( a = 200; a <= 400; a += 200 )
{ {
for( b = 200; b <= 400; b += 200 ) a = 800;
{ b = 400;
mbedtls_timing_set_delay( &ctx, a, a + b ); mbedtls_timing_set_delay( &ctx, a, a + b ); /* T = 0 */
busy_msleep( a - a / 8 ); busy_msleep( a - a / 4 ); /* T = a - a/4 */
if( mbedtls_timing_get_delay( &ctx ) != 0 ) if( mbedtls_timing_get_delay( &ctx ) != 0 )
FAIL; FAIL;
busy_msleep( a / 4 ); busy_msleep( a / 4 + b / 4 ); /* T = a + b/4 */
if( mbedtls_timing_get_delay( &ctx ) != 1 ) if( mbedtls_timing_get_delay( &ctx ) != 1 )
FAIL; FAIL;
busy_msleep( b - a / 8 - b / 8 ); busy_msleep( b ); /* T = a + b + b/4 */
if( mbedtls_timing_get_delay( &ctx ) != 1 ) if( mbedtls_timing_get_delay( &ctx ) != 2 )
FAIL; FAIL;
busy_msleep( b / 4 );
if( mbedtls_timing_get_delay( &ctx ) != 2 )
FAIL;
}
} }
mbedtls_timing_set_delay( &ctx, 0, 0 ); mbedtls_timing_set_delay( &ctx, 0, 0 );
@ -475,7 +479,6 @@ int mbedtls_timing_self_test( int verbose )
* On a 4Ghz 32-bit machine the cycle counter wraps about once per second; * On a 4Ghz 32-bit machine the cycle counter wraps about once per second;
* since the whole test is about 10ms, it shouldn't happen twice in a row. * since the whole test is about 10ms, it shouldn't happen twice in a row.
*/ */
hardfail = 0;
hard_test: hard_test:
if( hardfail > 1 ) if( hardfail > 1 )

View file

@ -36,6 +36,9 @@ static const char *features[] = {
#if defined(MBEDTLS_HAVE_ASM) #if defined(MBEDTLS_HAVE_ASM)
"MBEDTLS_HAVE_ASM", "MBEDTLS_HAVE_ASM",
#endif /* MBEDTLS_HAVE_ASM */ #endif /* MBEDTLS_HAVE_ASM */
#if defined(MBEDTLS_NO_UDBL_DIVISION)
"MBEDTLS_NO_UDBL_DIVISION",
#endif /* MBEDTLS_NO_UDBL_DIVISION */
#if defined(MBEDTLS_HAVE_SSE2) #if defined(MBEDTLS_HAVE_SSE2)
"MBEDTLS_HAVE_SSE2", "MBEDTLS_HAVE_SSE2",
#endif /* MBEDTLS_HAVE_SSE2 */ #endif /* MBEDTLS_HAVE_SSE2 */
@ -69,6 +72,9 @@ static const char *features[] = {
#if defined(MBEDTLS_PLATFORM_NV_SEED_ALT) #if defined(MBEDTLS_PLATFORM_NV_SEED_ALT)
"MBEDTLS_PLATFORM_NV_SEED_ALT", "MBEDTLS_PLATFORM_NV_SEED_ALT",
#endif /* MBEDTLS_PLATFORM_NV_SEED_ALT */ #endif /* MBEDTLS_PLATFORM_NV_SEED_ALT */
#if defined(MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT)
"MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT",
#endif /* MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */
#if defined(MBEDTLS_DEPRECATED_WARNING) #if defined(MBEDTLS_DEPRECATED_WARNING)
"MBEDTLS_DEPRECATED_WARNING", "MBEDTLS_DEPRECATED_WARNING",
#endif /* MBEDTLS_DEPRECATED_WARNING */ #endif /* MBEDTLS_DEPRECATED_WARNING */
@ -90,12 +96,18 @@ static const char *features[] = {
#if defined(MBEDTLS_CAMELLIA_ALT) #if defined(MBEDTLS_CAMELLIA_ALT)
"MBEDTLS_CAMELLIA_ALT", "MBEDTLS_CAMELLIA_ALT",
#endif /* MBEDTLS_CAMELLIA_ALT */ #endif /* MBEDTLS_CAMELLIA_ALT */
#if defined(MBEDTLS_CCM_ALT)
"MBEDTLS_CCM_ALT",
#endif /* MBEDTLS_CCM_ALT */
#if defined(MBEDTLS_CMAC_ALT)
"MBEDTLS_CMAC_ALT",
#endif /* MBEDTLS_CMAC_ALT */
#if defined(MBEDTLS_DES_ALT) #if defined(MBEDTLS_DES_ALT)
"MBEDTLS_DES_ALT", "MBEDTLS_DES_ALT",
#endif /* MBEDTLS_DES_ALT */ #endif /* MBEDTLS_DES_ALT */
#if defined(MBEDTLS_XTEA_ALT) #if defined(MBEDTLS_GCM_ALT)
"MBEDTLS_XTEA_ALT", "MBEDTLS_GCM_ALT",
#endif /* MBEDTLS_XTEA_ALT */ #endif /* MBEDTLS_GCM_ALT */
#if defined(MBEDTLS_MD2_ALT) #if defined(MBEDTLS_MD2_ALT)
"MBEDTLS_MD2_ALT", "MBEDTLS_MD2_ALT",
#endif /* MBEDTLS_MD2_ALT */ #endif /* MBEDTLS_MD2_ALT */
@ -108,6 +120,9 @@ static const char *features[] = {
#if defined(MBEDTLS_RIPEMD160_ALT) #if defined(MBEDTLS_RIPEMD160_ALT)
"MBEDTLS_RIPEMD160_ALT", "MBEDTLS_RIPEMD160_ALT",
#endif /* MBEDTLS_RIPEMD160_ALT */ #endif /* MBEDTLS_RIPEMD160_ALT */
#if defined(MBEDTLS_RSA_ALT)
"MBEDTLS_RSA_ALT",
#endif /* MBEDTLS_RSA_ALT */
#if defined(MBEDTLS_SHA1_ALT) #if defined(MBEDTLS_SHA1_ALT)
"MBEDTLS_SHA1_ALT", "MBEDTLS_SHA1_ALT",
#endif /* MBEDTLS_SHA1_ALT */ #endif /* MBEDTLS_SHA1_ALT */
@ -117,6 +132,9 @@ static const char *features[] = {
#if defined(MBEDTLS_SHA512_ALT) #if defined(MBEDTLS_SHA512_ALT)
"MBEDTLS_SHA512_ALT", "MBEDTLS_SHA512_ALT",
#endif /* MBEDTLS_SHA512_ALT */ #endif /* MBEDTLS_SHA512_ALT */
#if defined(MBEDTLS_XTEA_ALT)
"MBEDTLS_XTEA_ALT",
#endif /* MBEDTLS_XTEA_ALT */
#if defined(MBEDTLS_ECP_ALT) #if defined(MBEDTLS_ECP_ALT)
"MBEDTLS_ECP_ALT", "MBEDTLS_ECP_ALT",
#endif /* MBEDTLS_ECP_ALT */ #endif /* MBEDTLS_ECP_ALT */
@ -162,6 +180,21 @@ static const char *features[] = {
#if defined(MBEDTLS_AES_DECRYPT_ALT) #if defined(MBEDTLS_AES_DECRYPT_ALT)
"MBEDTLS_AES_DECRYPT_ALT", "MBEDTLS_AES_DECRYPT_ALT",
#endif /* MBEDTLS_AES_DECRYPT_ALT */ #endif /* MBEDTLS_AES_DECRYPT_ALT */
#if defined(MBEDTLS_ECDH_GEN_PUBLIC_ALT)
"MBEDTLS_ECDH_GEN_PUBLIC_ALT",
#endif /* MBEDTLS_ECDH_GEN_PUBLIC_ALT */
#if defined(MBEDTLS_ECDH_COMPUTE_SHARED_ALT)
"MBEDTLS_ECDH_COMPUTE_SHARED_ALT",
#endif /* MBEDTLS_ECDH_COMPUTE_SHARED_ALT */
#if defined(MBEDTLS_ECDSA_VERIFY_ALT)
"MBEDTLS_ECDSA_VERIFY_ALT",
#endif /* MBEDTLS_ECDSA_VERIFY_ALT */
#if defined(MBEDTLS_ECDSA_SIGN_ALT)
"MBEDTLS_ECDSA_SIGN_ALT",
#endif /* MBEDTLS_ECDSA_SIGN_ALT */
#if defined(MBEDTLS_ECDSA_GENKEY_ALT)
"MBEDTLS_ECDSA_GENKEY_ALT",
#endif /* MBEDTLS_ECDSA_GENKEY_ALT */
#if defined(MBEDTLS_ECP_INTERNAL_ALT) #if defined(MBEDTLS_ECP_INTERNAL_ALT)
"MBEDTLS_ECP_INTERNAL_ALT", "MBEDTLS_ECP_INTERNAL_ALT",
#endif /* MBEDTLS_ECP_INTERNAL_ALT */ #endif /* MBEDTLS_ECP_INTERNAL_ALT */

View file

@ -496,29 +496,35 @@ static int x509_parse_int( unsigned char **p, size_t n, int *res )
return( 0 ); return( 0 );
} }
static int x509_date_is_valid(const mbedtls_x509_time *time) static int x509_date_is_valid(const mbedtls_x509_time *t )
{ {
int ret = MBEDTLS_ERR_X509_INVALID_DATE; int ret = MBEDTLS_ERR_X509_INVALID_DATE;
int month_len;
CHECK_RANGE( 0, 9999, time->year ); CHECK_RANGE( 0, 9999, t->year );
CHECK_RANGE( 0, 23, time->hour ); CHECK_RANGE( 0, 23, t->hour );
CHECK_RANGE( 0, 59, time->min ); CHECK_RANGE( 0, 59, t->min );
CHECK_RANGE( 0, 59, time->sec ); CHECK_RANGE( 0, 59, t->sec );
switch( time->mon ) switch( t->mon )
{ {
case 1: case 3: case 5: case 7: case 8: case 10: case 12: case 1: case 3: case 5: case 7: case 8: case 10: case 12:
CHECK_RANGE( 1, 31, time->day ); month_len = 31;
break; break;
case 4: case 6: case 9: case 11: case 4: case 6: case 9: case 11:
CHECK_RANGE( 1, 30, time->day ); month_len = 30;
break; break;
case 2: case 2:
CHECK_RANGE( 1, 28 + (time->year % 4 == 0), time->day ); if( ( !( t->year % 4 ) && t->year % 100 ) ||
!( t->year % 400 ) )
month_len = 29;
else
month_len = 28;
break; break;
default: default:
return( ret ); return( ret );
} }
CHECK_RANGE( 1, month_len, t->day );
return( 0 ); return( 0 );
} }
@ -528,7 +534,7 @@ static int x509_date_is_valid(const mbedtls_x509_time *time)
* field. * field.
*/ */
static int x509_parse_time( unsigned char **p, size_t len, size_t yearlen, static int x509_parse_time( unsigned char **p, size_t len, size_t yearlen,
mbedtls_x509_time *time ) mbedtls_x509_time *tm )
{ {
int ret; int ret;
@ -542,26 +548,26 @@ static int x509_parse_time( unsigned char **p, size_t len, size_t yearlen,
/* /*
* Parse year, month, day, hour, minute * Parse year, month, day, hour, minute
*/ */
CHECK( x509_parse_int( p, yearlen, &time->year ) ); CHECK( x509_parse_int( p, yearlen, &tm->year ) );
if ( 2 == yearlen ) if ( 2 == yearlen )
{ {
if ( time->year < 50 ) if ( tm->year < 50 )
time->year += 100; tm->year += 100;
time->year += 1900; tm->year += 1900;
} }
CHECK( x509_parse_int( p, 2, &time->mon ) ); CHECK( x509_parse_int( p, 2, &tm->mon ) );
CHECK( x509_parse_int( p, 2, &time->day ) ); CHECK( x509_parse_int( p, 2, &tm->day ) );
CHECK( x509_parse_int( p, 2, &time->hour ) ); CHECK( x509_parse_int( p, 2, &tm->hour ) );
CHECK( x509_parse_int( p, 2, &time->min ) ); CHECK( x509_parse_int( p, 2, &tm->min ) );
/* /*
* Parse seconds if present * Parse seconds if present
*/ */
if ( len >= 2 ) if ( len >= 2 )
{ {
CHECK( x509_parse_int( p, 2, &time->sec ) ); CHECK( x509_parse_int( p, 2, &tm->sec ) );
len -= 2; len -= 2;
} }
else else
@ -582,7 +588,7 @@ static int x509_parse_time( unsigned char **p, size_t len, size_t yearlen,
if ( 0 != len ) if ( 0 != len )
return ( MBEDTLS_ERR_X509_INVALID_DATE ); return ( MBEDTLS_ERR_X509_INVALID_DATE );
CHECK( x509_date_is_valid( time ) ); CHECK( x509_date_is_valid( tm ) );
return ( 0 ); return ( 0 );
} }
@ -593,7 +599,7 @@ static int x509_parse_time( unsigned char **p, size_t len, size_t yearlen,
* generalTime GeneralizedTime } * generalTime GeneralizedTime }
*/ */
int mbedtls_x509_get_time( unsigned char **p, const unsigned char *end, int mbedtls_x509_get_time( unsigned char **p, const unsigned char *end,
mbedtls_x509_time *time ) mbedtls_x509_time *tm )
{ {
int ret; int ret;
size_t len, year_len; size_t len, year_len;
@ -619,7 +625,7 @@ int mbedtls_x509_get_time( unsigned char **p, const unsigned char *end,
if( ret != 0 ) if( ret != 0 )
return( MBEDTLS_ERR_X509_INVALID_DATE + ret ); return( MBEDTLS_ERR_X509_INVALID_DATE + ret );
return x509_parse_time( p, len, year_len, time ); return x509_parse_time( p, len, year_len, tm );
} }
int mbedtls_x509_get_sig( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *sig ) int mbedtls_x509_get_sig( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *sig )

View file

@ -352,14 +352,14 @@ int mbedtls_x509_crl_parse_der( mbedtls_x509_crl *chain,
return( ret ); return( ret );
} }
crl->version++; if( crl->version < 0 || crl->version > 1 )
if( crl->version > 2 )
{ {
mbedtls_x509_crl_free( crl ); mbedtls_x509_crl_free( crl );
return( MBEDTLS_ERR_X509_UNKNOWN_VERSION ); return( MBEDTLS_ERR_X509_UNKNOWN_VERSION );
} }
crl->version++;
if( ( ret = mbedtls_x509_get_sig_alg( &crl->sig_oid, &sig_params1, if( ( ret = mbedtls_x509_get_sig_alg( &crl->sig_oid, &sig_params1,
&crl->sig_md, &crl->sig_pk, &crl->sig_md, &crl->sig_pk,
&crl->sig_opts ) ) != 0 ) &crl->sig_opts ) ) != 0 )

View file

@ -748,14 +748,14 @@ static int x509_crt_parse_der_core( mbedtls_x509_crt *crt, const unsigned char *
return( ret ); return( ret );
} }
crt->version++; if( crt->version < 0 || crt->version > 2 )
if( crt->version > 3 )
{ {
mbedtls_x509_crt_free( crt ); mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_UNKNOWN_VERSION ); return( MBEDTLS_ERR_X509_UNKNOWN_VERSION );
} }
crt->version++;
if( ( ret = mbedtls_x509_get_sig_alg( &crt->sig_oid, &sig_params1, if( ( ret = mbedtls_x509_get_sig_alg( &crt->sig_oid, &sig_params1,
&crt->sig_md, &crt->sig_pk, &crt->sig_md, &crt->sig_pk,
&crt->sig_opts ) ) != 0 ) &crt->sig_opts ) ) != 0 )
@ -1146,7 +1146,10 @@ int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path )
p, (int) len - 1, p, (int) len - 1,
NULL, NULL ); NULL, NULL );
if( w_ret == 0 ) if( w_ret == 0 )
return( MBEDTLS_ERR_X509_FILE_IO_ERROR ); {
ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
goto cleanup;
}
w_ret = mbedtls_x509_crt_parse_file( chain, filename ); w_ret = mbedtls_x509_crt_parse_file( chain, filename );
if( w_ret < 0 ) if( w_ret < 0 )
@ -1159,6 +1162,7 @@ int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path )
if( GetLastError() != ERROR_NO_MORE_FILES ) if( GetLastError() != ERROR_NO_MORE_FILES )
ret = MBEDTLS_ERR_X509_FILE_IO_ERROR; ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
cleanup:
FindClose( hFind ); FindClose( hFind );
#else /* _WIN32 */ #else /* _WIN32 */
int t_ret; int t_ret;
@ -1171,13 +1175,13 @@ int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path )
if( dir == NULL ) if( dir == NULL )
return( MBEDTLS_ERR_X509_FILE_IO_ERROR ); return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
#if defined(MBEDTLS_THREADING_PTHREAD) #if defined(MBEDTLS_THREADING_C)
if( ( ret = mbedtls_mutex_lock( &mbedtls_threading_readdir_mutex ) ) != 0 ) if( ( ret = mbedtls_mutex_lock( &mbedtls_threading_readdir_mutex ) ) != 0 )
{ {
closedir( dir ); closedir( dir );
return( ret ); return( ret );
} }
#endif #endif /* MBEDTLS_THREADING_C */
while( ( entry = readdir( dir ) ) != NULL ) while( ( entry = readdir( dir ) ) != NULL )
{ {
@ -1210,10 +1214,10 @@ int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path )
cleanup: cleanup:
closedir( dir ); closedir( dir );
#if defined(MBEDTLS_THREADING_PTHREAD) #if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_unlock( &mbedtls_threading_readdir_mutex ) != 0 ) if( mbedtls_mutex_unlock( &mbedtls_threading_readdir_mutex ) != 0 )
ret = MBEDTLS_ERR_THREADING_MUTEX_ERROR; ret = MBEDTLS_ERR_THREADING_MUTEX_ERROR;
#endif #endif /* MBEDTLS_THREADING_C */
#endif /* _WIN32 */ #endif /* _WIN32 */
@ -2057,8 +2061,8 @@ static int x509_crt_verify_child(
/* path_cnt is 0 for the first intermediate CA */ /* path_cnt is 0 for the first intermediate CA */
if( 1 + path_cnt > MBEDTLS_X509_MAX_INTERMEDIATE_CA ) if( 1 + path_cnt > MBEDTLS_X509_MAX_INTERMEDIATE_CA )
{ {
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; /* return immediately as the goal is to avoid unbounded recursion */
return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ); return( MBEDTLS_ERR_X509_FATAL_ERROR );
} }
if( mbedtls_x509_time_is_past( &child->valid_to ) ) if( mbedtls_x509_time_is_past( &child->valid_to ) )
@ -2202,11 +2206,14 @@ int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
mbedtls_x509_sequence *cur = NULL; mbedtls_x509_sequence *cur = NULL;
mbedtls_pk_type_t pk_type; mbedtls_pk_type_t pk_type;
if( profile == NULL )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
*flags = 0; *flags = 0;
if( profile == NULL )
{
ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA;
goto exit;
}
if( cn != NULL ) if( cn != NULL )
{ {
name = &crt->subject; name = &crt->subject;
@ -2280,7 +2287,7 @@ int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
ret = x509_crt_verify_top( crt, parent, ca_crl, profile, ret = x509_crt_verify_top( crt, parent, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy ); pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 ) if( ret != 0 )
return( ret ); goto exit;
} }
else else
{ {
@ -2295,17 +2302,30 @@ int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
ret = x509_crt_verify_child( crt, parent, trust_ca, ca_crl, profile, ret = x509_crt_verify_child( crt, parent, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy ); pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 ) if( ret != 0 )
return( ret ); goto exit;
} }
else else
{ {
ret = x509_crt_verify_top( crt, trust_ca, ca_crl, profile, ret = x509_crt_verify_top( crt, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy ); pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 ) if( ret != 0 )
return( ret ); goto exit;
} }
} }
exit:
/* prevent misuse of the vrfy callback - VERIFY_FAILED would be ignored by
* the SSL module for authmode optional, but non-zero return from the
* callback means a fatal error so it shouldn't be ignored */
if( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED )
ret = MBEDTLS_ERR_X509_FATAL_ERROR;
if( ret != 0 )
{
*flags = (uint32_t) -1;
return( ret );
}
if( *flags != 0 ) if( *flags != 0 )
return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ); return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );

View file

@ -168,14 +168,14 @@ int mbedtls_x509_csr_parse_der( mbedtls_x509_csr *csr,
return( ret ); return( ret );
} }
csr->version++; if( csr->version != 0 )
if( csr->version != 1 )
{ {
mbedtls_x509_csr_free( csr ); mbedtls_x509_csr_free( csr );
return( MBEDTLS_ERR_X509_UNKNOWN_VERSION ); return( MBEDTLS_ERR_X509_UNKNOWN_VERSION );
} }
csr->version++;
/* /*
* subject Name * subject Name
*/ */

View file

@ -51,7 +51,7 @@ static void mbedtls_zeroize( void *v, size_t n ) {
void mbedtls_x509write_crt_init( mbedtls_x509write_cert *ctx ) void mbedtls_x509write_crt_init( mbedtls_x509write_cert *ctx )
{ {
memset( ctx, 0, sizeof(mbedtls_x509write_cert) ); memset( ctx, 0, sizeof( mbedtls_x509write_cert ) );
mbedtls_mpi_init( &ctx->serial ); mbedtls_mpi_init( &ctx->serial );
ctx->version = MBEDTLS_X509_CRT_VERSION_3; ctx->version = MBEDTLS_X509_CRT_VERSION_3;
@ -65,7 +65,7 @@ void mbedtls_x509write_crt_free( mbedtls_x509write_cert *ctx )
mbedtls_asn1_free_named_data_list( &ctx->issuer ); mbedtls_asn1_free_named_data_list( &ctx->issuer );
mbedtls_asn1_free_named_data_list( &ctx->extensions ); mbedtls_asn1_free_named_data_list( &ctx->extensions );
mbedtls_zeroize( ctx, sizeof(mbedtls_x509write_cert) ); mbedtls_zeroize( ctx, sizeof( mbedtls_x509write_cert ) );
} }
void mbedtls_x509write_crt_set_version( mbedtls_x509write_cert *ctx, int version ) void mbedtls_x509write_crt_set_version( mbedtls_x509write_cert *ctx, int version )
@ -196,7 +196,7 @@ int mbedtls_x509write_crt_set_authority_key_identifier( mbedtls_x509write_cert *
{ {
int ret; int ret;
unsigned char buf[MBEDTLS_MPI_MAX_SIZE * 2 + 20]; /* tag, length + 2xMPI */ unsigned char buf[MBEDTLS_MPI_MAX_SIZE * 2 + 20]; /* tag, length + 2xMPI */
unsigned char *c = buf + sizeof(buf); unsigned char *c = buf + sizeof( buf );
size_t len = 0; size_t len = 0;
memset( buf, 0, sizeof(buf) ); memset( buf, 0, sizeof(buf) );
@ -218,7 +218,7 @@ int mbedtls_x509write_crt_set_authority_key_identifier( mbedtls_x509write_cert *
return mbedtls_x509write_crt_set_extension( ctx, MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER, return mbedtls_x509write_crt_set_extension( ctx, MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER,
MBEDTLS_OID_SIZE( MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER ), MBEDTLS_OID_SIZE( MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER ),
0, buf + sizeof(buf) - len, len ); 0, buf + sizeof( buf ) - len, len );
} }
#endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_SHA1_C */
@ -270,7 +270,7 @@ int mbedtls_x509write_crt_set_ns_cert_type( mbedtls_x509write_cert *ctx,
} }
static int x509_write_time( unsigned char **p, unsigned char *start, static int x509_write_time( unsigned char **p, unsigned char *start,
const char *time, size_t size ) const char *t, size_t size )
{ {
int ret; int ret;
size_t len = 0; size_t len = 0;
@ -278,10 +278,10 @@ static int x509_write_time( unsigned char **p, unsigned char *start,
/* /*
* write MBEDTLS_ASN1_UTC_TIME if year < 2050 (2 bytes shorter) * write MBEDTLS_ASN1_UTC_TIME if year < 2050 (2 bytes shorter)
*/ */
if( time[0] == '2' && time[1] == '0' && time [2] < '5' ) if( t[0] == '2' && t[1] == '0' && t[2] < '5' )
{ {
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start, MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start,
(const unsigned char *) time + 2, (const unsigned char *) t + 2,
size - 2 ) ); size - 2 ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_UTC_TIME ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_UTC_TIME ) );
@ -289,7 +289,7 @@ static int x509_write_time( unsigned char **p, unsigned char *start,
else else
{ {
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start, MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start,
(const unsigned char *) time, (const unsigned char *) t,
size ) ); size ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_GENERALIZED_TIME ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_GENERALIZED_TIME ) );
@ -319,12 +319,18 @@ int mbedtls_x509write_crt_der( mbedtls_x509write_cert *ctx, unsigned char *buf,
c = tmp_buf + sizeof( tmp_buf ); c = tmp_buf + sizeof( tmp_buf );
/* Signature algorithm needed in TBS, and later for actual signature */ /* Signature algorithm needed in TBS, and later for actual signature */
pk_alg = mbedtls_pk_get_type( ctx->issuer_key );
if( pk_alg == MBEDTLS_PK_ECKEY ) /* There's no direct way of extracting a signature algorithm
* (represented as an element of mbedtls_pk_type_t) from a PK instance. */
if( mbedtls_pk_can_do( ctx->issuer_key, MBEDTLS_PK_RSA ) )
pk_alg = MBEDTLS_PK_RSA;
else if( mbedtls_pk_can_do( ctx->issuer_key, MBEDTLS_PK_ECDSA ) )
pk_alg = MBEDTLS_PK_ECDSA; pk_alg = MBEDTLS_PK_ECDSA;
else
return( MBEDTLS_ERR_X509_INVALID_ALG );
if( ( ret = mbedtls_oid_get_oid_by_sig_alg( pk_alg, ctx->md_alg, if( ( ret = mbedtls_oid_get_oid_by_sig_alg( pk_alg, ctx->md_alg,
&sig_oid, &sig_oid_len ) ) != 0 ) &sig_oid, &sig_oid_len ) ) != 0 )
{ {
return( ret ); return( ret );
} }
@ -332,13 +338,18 @@ int mbedtls_x509write_crt_der( mbedtls_x509write_cert *ctx, unsigned char *buf,
/* /*
* Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
*/ */
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_extensions( &c, tmp_buf, ctx->extensions ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) ); /* Only for v3 */
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONSTRUCTED | if( ctx->version == MBEDTLS_X509_CRT_VERSION_3 )
MBEDTLS_ASN1_SEQUENCE ) ); {
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_extensions( &c, tmp_buf, ctx->extensions ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) );
MBEDTLS_ASN1_CONSTRUCTED | 3 ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONSTRUCTED |
MBEDTLS_ASN1_SEQUENCE ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC |
MBEDTLS_ASN1_CONSTRUCTED | 3 ) );
}
/* /*
* SubjectPublicKeyInfo * SubjectPublicKeyInfo
@ -390,16 +401,21 @@ int mbedtls_x509write_crt_der( mbedtls_x509write_cert *ctx, unsigned char *buf,
/* /*
* Version ::= INTEGER { v1(0), v2(1), v3(2) } * Version ::= INTEGER { v1(0), v2(1), v3(2) }
*/ */
sub_len = 0;
MBEDTLS_ASN1_CHK_ADD( sub_len, mbedtls_asn1_write_int( &c, tmp_buf, ctx->version ) ); /* Can be omitted for v1 */
len += sub_len; if( ctx->version != MBEDTLS_X509_CRT_VERSION_1 )
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, sub_len ) ); {
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | sub_len = 0;
MBEDTLS_ASN1_CONSTRUCTED | 0 ) ); MBEDTLS_ASN1_CHK_ADD( sub_len, mbedtls_asn1_write_int( &c, tmp_buf, ctx->version ) );
len += sub_len;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, sub_len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC |
MBEDTLS_ASN1_CONSTRUCTED | 0 ) );
}
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, tmp_buf, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, tmp_buf, MBEDTLS_ASN1_CONSTRUCTED |
MBEDTLS_ASN1_SEQUENCE ) ); MBEDTLS_ASN1_SEQUENCE ) );
/* /*
* Make signature * Make signature

View file

@ -50,7 +50,7 @@ static void mbedtls_zeroize( void *v, size_t n ) {
void mbedtls_x509write_csr_init( mbedtls_x509write_csr *ctx ) void mbedtls_x509write_csr_init( mbedtls_x509write_csr *ctx )
{ {
memset( ctx, 0, sizeof(mbedtls_x509write_csr) ); memset( ctx, 0, sizeof( mbedtls_x509write_csr ) );
} }
void mbedtls_x509write_csr_free( mbedtls_x509write_csr *ctx ) void mbedtls_x509write_csr_free( mbedtls_x509write_csr *ctx )
@ -58,7 +58,7 @@ void mbedtls_x509write_csr_free( mbedtls_x509write_csr *ctx )
mbedtls_asn1_free_named_data_list( &ctx->subject ); mbedtls_asn1_free_named_data_list( &ctx->subject );
mbedtls_asn1_free_named_data_list( &ctx->extensions ); mbedtls_asn1_free_named_data_list( &ctx->extensions );
mbedtls_zeroize( ctx, sizeof(mbedtls_x509write_csr) ); mbedtls_zeroize( ctx, sizeof( mbedtls_x509write_csr ) );
} }
void mbedtls_x509write_csr_set_md_alg( mbedtls_x509write_csr *ctx, mbedtls_md_type_t md_alg ) void mbedtls_x509write_csr_set_md_alg( mbedtls_x509write_csr *ctx, mbedtls_md_type_t md_alg )
@ -194,14 +194,21 @@ int mbedtls_x509write_csr_der( mbedtls_x509write_csr *ctx, unsigned char *buf, s
*/ */
mbedtls_md( mbedtls_md_info_from_type( ctx->md_alg ), c, len, hash ); mbedtls_md( mbedtls_md_info_from_type( ctx->md_alg ), c, len, hash );
pk_alg = mbedtls_pk_get_type( ctx->key );
if( pk_alg == MBEDTLS_PK_ECKEY )
pk_alg = MBEDTLS_PK_ECDSA;
if( ( ret = mbedtls_pk_sign( ctx->key, ctx->md_alg, hash, 0, sig, &sig_len, if( ( ret = mbedtls_pk_sign( ctx->key, ctx->md_alg, hash, 0, sig, &sig_len,
f_rng, p_rng ) ) != 0 || f_rng, p_rng ) ) != 0 )
( ret = mbedtls_oid_get_oid_by_sig_alg( pk_alg, ctx->md_alg, {
&sig_oid, &sig_oid_len ) ) != 0 ) return( ret );
}
if( mbedtls_pk_can_do( ctx->key, MBEDTLS_PK_RSA ) )
pk_alg = MBEDTLS_PK_RSA;
else if( mbedtls_pk_can_do( ctx->key, MBEDTLS_PK_ECDSA ) )
pk_alg = MBEDTLS_PK_ECDSA;
else
return( MBEDTLS_ERR_X509_INVALID_ALG );
if( ( ret = mbedtls_oid_get_oid_by_sig_alg( pk_alg, ctx->md_alg,
&sig_oid, &sig_oid_len ) ) != 0 )
{ {
return( ret ); return( ret );
} }

View file

@ -79,7 +79,9 @@ int main( int argc, char *argv[] )
FILE *fkey, *fin = NULL, *fout = NULL; FILE *fkey, *fin = NULL, *fout = NULL;
char *p; char *p;
unsigned char IV[16]; unsigned char IV[16];
unsigned char tmp[16];
unsigned char key[512]; unsigned char key[512];
unsigned char digest[32]; unsigned char digest[32];
unsigned char buffer[1024]; unsigned char buffer[1024];
@ -123,10 +125,10 @@ int main( int argc, char *argv[] )
} }
mode = atoi( argv[1] ); mode = atoi( argv[1] );
memset(IV, 0, sizeof(IV)); memset( IV, 0, sizeof( IV ) );
memset(key, 0, sizeof(key)); memset( key, 0, sizeof( key ) );
memset(digest, 0, sizeof(digest)); memset( digest, 0, sizeof( digest ) );
memset(buffer, 0, sizeof(buffer)); memset( buffer, 0, sizeof( buffer ) );
if( mode != MODE_ENCRYPT && mode != MODE_DECRYPT ) if( mode != MODE_ENCRYPT && mode != MODE_DECRYPT )
{ {
@ -153,7 +155,7 @@ int main( int argc, char *argv[] )
} }
/* /*
* Read the secret key and clean the command line. * Read the secret key from file or command line
*/ */
if( ( fkey = fopen( argv[4], "rb" ) ) != NULL ) if( ( fkey = fopen( argv[4], "rb" ) ) != NULL )
{ {
@ -185,8 +187,6 @@ int main( int argc, char *argv[] )
} }
} }
memset( argv[4], 0, strlen( argv[4] ) );
#if defined(_WIN32_WCE) #if defined(_WIN32_WCE)
filesize = fseek( fin, 0L, SEEK_END ); filesize = fseek( fin, 0L, SEEK_END );
#else #else
@ -272,7 +272,6 @@ int main( int argc, char *argv[] )
mbedtls_md_finish( &sha_ctx, digest ); mbedtls_md_finish( &sha_ctx, digest );
} }
memset( key, 0, sizeof( key ) );
mbedtls_aes_setkey_enc( &aes_ctx, digest, 256 ); mbedtls_aes_setkey_enc( &aes_ctx, digest, 256 );
mbedtls_md_hmac_starts( &sha_ctx, digest, 32 ); mbedtls_md_hmac_starts( &sha_ctx, digest, 32 );
@ -319,8 +318,6 @@ int main( int argc, char *argv[] )
if( mode == MODE_DECRYPT ) if( mode == MODE_DECRYPT )
{ {
unsigned char tmp[16];
/* /*
* The encrypted file must be structured as follows: * The encrypted file must be structured as follows:
* *
@ -374,7 +371,6 @@ int main( int argc, char *argv[] )
mbedtls_md_finish( &sha_ctx, digest ); mbedtls_md_finish( &sha_ctx, digest );
} }
memset( key, 0, sizeof( key ) );
mbedtls_aes_setkey_dec( &aes_ctx, digest, 256 ); mbedtls_aes_setkey_dec( &aes_ctx, digest, 256 );
mbedtls_md_hmac_starts( &sha_ctx, digest, 32 ); mbedtls_md_hmac_starts( &sha_ctx, digest, 32 );
@ -441,6 +437,15 @@ exit:
if( fout ) if( fout )
fclose( fout ); fclose( fout );
/* Zeroize all command line arguments to also cover
the case when the user has missed or reordered some,
in which case the key might not be in argv[4]. */
for( i = 0; i < (unsigned int) argc; i++ )
memset( argv[i], 0, strlen( argv[i] ) );
memset( IV, 0, sizeof( IV ) );
memset( key, 0, sizeof( key ) );
memset( tmp, 0, sizeof( tmp ) );
memset( buffer, 0, sizeof( buffer ) ); memset( buffer, 0, sizeof( buffer ) );
memset( digest, 0, sizeof( digest ) ); memset( digest, 0, sizeof( digest ) );

View file

@ -192,7 +192,7 @@ int main( int argc, char *argv[] )
} }
/* /*
* Read the secret key and clean the command line. * Read the secret key from file or command line
*/ */
if( ( fkey = fopen( argv[6], "rb" ) ) != NULL ) if( ( fkey = fopen( argv[6], "rb" ) ) != NULL )
{ {
@ -224,8 +224,6 @@ int main( int argc, char *argv[] )
} }
} }
memset( argv[6], 0, strlen( argv[6] ) );
#if defined(_WIN32_WCE) #if defined(_WIN32_WCE)
filesize = fseek( fin, 0L, SEEK_END ); filesize = fseek( fin, 0L, SEEK_END );
#else #else
@ -303,8 +301,6 @@ int main( int argc, char *argv[] )
} }
memset( key, 0, sizeof( key ) );
if( mbedtls_cipher_setkey( &cipher_ctx, digest, cipher_info->key_bitlen, if( mbedtls_cipher_setkey( &cipher_ctx, digest, cipher_info->key_bitlen,
MBEDTLS_ENCRYPT ) != 0 ) MBEDTLS_ENCRYPT ) != 0 )
{ {
@ -444,8 +440,6 @@ int main( int argc, char *argv[] )
mbedtls_md_finish( &md_ctx, digest ); mbedtls_md_finish( &md_ctx, digest );
} }
memset( key, 0, sizeof( key ) );
if( mbedtls_cipher_setkey( &cipher_ctx, digest, cipher_info->key_bitlen, if( mbedtls_cipher_setkey( &cipher_ctx, digest, cipher_info->key_bitlen,
MBEDTLS_DECRYPT ) != 0 ) MBEDTLS_DECRYPT ) != 0 )
{ {
@ -540,7 +534,16 @@ exit:
if( fout ) if( fout )
fclose( fout ); fclose( fout );
/* Zeroize all command line arguments to also cover
the case when the user has missed or reordered some,
in which case the key might not be in argv[6]. */
for( i = 0; i < argc; i++ )
memset( argv[i], 0, strlen( argv[i] ) );
memset( IV, 0, sizeof( IV ) );
memset( key, 0, sizeof( key ) );
memset( buffer, 0, sizeof( buffer ) ); memset( buffer, 0, sizeof( buffer ) );
memset( output, 0, sizeof( output ) );
memset( digest, 0, sizeof( digest ) ); memset( digest, 0, sizeof( digest ) );
mbedtls_cipher_free( &cipher_ctx ); mbedtls_cipher_free( &cipher_ctx );

View file

@ -86,6 +86,8 @@ int main( void )
mbedtls_dhm_context dhm; mbedtls_dhm_context dhm;
mbedtls_aes_context aes; mbedtls_aes_context aes;
mbedtls_mpi N, P, Q, D, E;
mbedtls_net_init( &listen_fd ); mbedtls_net_init( &listen_fd );
mbedtls_net_init( &client_fd ); mbedtls_net_init( &client_fd );
mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_SHA256 ); mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_SHA256 );
@ -93,6 +95,9 @@ int main( void )
mbedtls_aes_init( &aes ); mbedtls_aes_init( &aes );
mbedtls_ctr_drbg_init( &ctr_drbg ); mbedtls_ctr_drbg_init( &ctr_drbg );
mbedtls_mpi_init( &N ); mbedtls_mpi_init( &P ); mbedtls_mpi_init( &Q );
mbedtls_mpi_init( &D ); mbedtls_mpi_init( &E );
/* /*
* 1. Setup the RNG * 1. Setup the RNG
*/ */
@ -124,24 +129,33 @@ int main( void )
mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 ); mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 );
if( ( ret = mbedtls_mpi_read_file( &rsa.N , 16, f ) ) != 0 || if( ( ret = mbedtls_mpi_read_file( &N , 16, f ) ) != 0 ||
( ret = mbedtls_mpi_read_file( &rsa.E , 16, f ) ) != 0 || ( ret = mbedtls_mpi_read_file( &E , 16, f ) ) != 0 ||
( ret = mbedtls_mpi_read_file( &rsa.D , 16, f ) ) != 0 || ( ret = mbedtls_mpi_read_file( &D , 16, f ) ) != 0 ||
( ret = mbedtls_mpi_read_file( &rsa.P , 16, f ) ) != 0 || ( ret = mbedtls_mpi_read_file( &P , 16, f ) ) != 0 ||
( ret = mbedtls_mpi_read_file( &rsa.Q , 16, f ) ) != 0 || ( ret = mbedtls_mpi_read_file( &Q , 16, f ) ) != 0 )
( ret = mbedtls_mpi_read_file( &rsa.DP, 16, f ) ) != 0 ||
( ret = mbedtls_mpi_read_file( &rsa.DQ, 16, f ) ) != 0 ||
( ret = mbedtls_mpi_read_file( &rsa.QP, 16, f ) ) != 0 )
{ {
mbedtls_printf( " failed\n ! mbedtls_mpi_read_file returned %d\n\n", ret ); mbedtls_printf( " failed\n ! mbedtls_mpi_read_file returned %d\n\n",
ret );
fclose( f ); fclose( f );
goto exit; goto exit;
} }
rsa.len = ( mbedtls_mpi_bitlen( &rsa.N ) + 7 ) >> 3;
fclose( f ); fclose( f );
if( ( ret = mbedtls_rsa_import( &rsa, &N, &P, &Q, &D, &E ) ) != 0 )
{
mbedtls_printf( " failed\n ! mbedtls_rsa_import returned %d\n\n",
ret );
goto exit;
}
if( ( ret = mbedtls_rsa_complete( &rsa ) ) != 0 )
{
mbedtls_printf( " failed\n ! mbedtls_rsa_complete returned %d\n\n",
ret );
goto exit;
}
/* /*
* 2b. Get the DHM modulus and generator * 2b. Get the DHM modulus and generator
*/ */
@ -291,6 +305,9 @@ int main( void )
exit: exit:
mbedtls_mpi_free( &N ); mbedtls_mpi_free( &P ); mbedtls_mpi_free( &Q );
mbedtls_mpi_free( &D ); mbedtls_mpi_free( &E );
mbedtls_net_free( &client_fd ); mbedtls_net_free( &client_fd );
mbedtls_net_free( &listen_fd ); mbedtls_net_free( &listen_fd );

View file

@ -204,7 +204,7 @@ int main( int argc, char *argv[] )
mbedtls_printf( " ok\n" ); mbedtls_printf( " ok\n" );
/* /*
* Verification: are the computed secret equal? * Verification: are the computed secrets equal?
*/ */
mbedtls_printf( " . Checking if both computed secrets are equal..." ); mbedtls_printf( " . Checking if both computed secrets are equal..." );
fflush( stdout ); fflush( stdout );

View file

@ -191,6 +191,7 @@ int main( int argc, char *argv[] )
char buf[1024]; char buf[1024];
int i; int i;
char *p, *q; char *p, *q;
mbedtls_mpi N, P, Q, D, E, DP, DQ, QP;
mbedtls_entropy_context entropy; mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg; mbedtls_ctr_drbg_context ctr_drbg;
const char *pers = "gen_key"; const char *pers = "gen_key";
@ -201,6 +202,11 @@ int main( int argc, char *argv[] )
/* /*
* Set to sane values * Set to sane values
*/ */
mbedtls_mpi_init( &N ); mbedtls_mpi_init( &P ); mbedtls_mpi_init( &Q );
mbedtls_mpi_init( &D ); mbedtls_mpi_init( &E ); mbedtls_mpi_init( &DP );
mbedtls_mpi_init( &DQ ); mbedtls_mpi_init( &QP );
mbedtls_pk_init( &key ); mbedtls_pk_init( &key );
mbedtls_ctr_drbg_init( &ctr_drbg ); mbedtls_ctr_drbg_init( &ctr_drbg );
memset( buf, 0, sizeof( buf ) ); memset( buf, 0, sizeof( buf ) );
@ -323,7 +329,7 @@ int main( int argc, char *argv[] )
if( opt.type == MBEDTLS_PK_RSA ) if( opt.type == MBEDTLS_PK_RSA )
{ {
ret = mbedtls_rsa_gen_key( mbedtls_pk_rsa( key ), mbedtls_ctr_drbg_random, &ctr_drbg, ret = mbedtls_rsa_gen_key( mbedtls_pk_rsa( key ), mbedtls_ctr_drbg_random, &ctr_drbg,
opt.rsa_keysize, 65537 ); opt.rsa_keysize, 65537 );
if( ret != 0 ) if( ret != 0 )
{ {
mbedtls_printf( " failed\n ! mbedtls_rsa_gen_key returned -0x%04x", -ret ); mbedtls_printf( " failed\n ! mbedtls_rsa_gen_key returned -0x%04x", -ret );
@ -336,7 +342,7 @@ int main( int argc, char *argv[] )
if( opt.type == MBEDTLS_PK_ECKEY ) if( opt.type == MBEDTLS_PK_ECKEY )
{ {
ret = mbedtls_ecp_gen_key( opt.ec_curve, mbedtls_pk_ec( key ), ret = mbedtls_ecp_gen_key( opt.ec_curve, mbedtls_pk_ec( key ),
mbedtls_ctr_drbg_random, &ctr_drbg ); mbedtls_ctr_drbg_random, &ctr_drbg );
if( ret != 0 ) if( ret != 0 )
{ {
mbedtls_printf( " failed\n ! mbedtls_rsa_gen_key returned -0x%04x", -ret ); mbedtls_printf( " failed\n ! mbedtls_rsa_gen_key returned -0x%04x", -ret );
@ -359,14 +365,22 @@ int main( int argc, char *argv[] )
if( mbedtls_pk_get_type( &key ) == MBEDTLS_PK_RSA ) if( mbedtls_pk_get_type( &key ) == MBEDTLS_PK_RSA )
{ {
mbedtls_rsa_context *rsa = mbedtls_pk_rsa( key ); mbedtls_rsa_context *rsa = mbedtls_pk_rsa( key );
mbedtls_mpi_write_file( "N: ", &rsa->N, 16, NULL );
mbedtls_mpi_write_file( "E: ", &rsa->E, 16, NULL ); if( ( ret = mbedtls_rsa_export ( rsa, &N, &P, &Q, &D, &E ) ) != 0 ||
mbedtls_mpi_write_file( "D: ", &rsa->D, 16, NULL ); ( ret = mbedtls_rsa_export_crt( rsa, &DP, &DQ, &QP ) ) != 0 )
mbedtls_mpi_write_file( "P: ", &rsa->P, 16, NULL ); {
mbedtls_mpi_write_file( "Q: ", &rsa->Q, 16, NULL ); mbedtls_printf( " failed\n ! could not export RSA parameters\n\n" );
mbedtls_mpi_write_file( "DP: ", &rsa->DP, 16, NULL ); goto exit;
mbedtls_mpi_write_file( "DQ: ", &rsa->DQ, 16, NULL ); }
mbedtls_mpi_write_file( "QP: ", &rsa->QP, 16, NULL );
mbedtls_mpi_write_file( "N: ", &N, 16, NULL );
mbedtls_mpi_write_file( "E: ", &E, 16, NULL );
mbedtls_mpi_write_file( "D: ", &D, 16, NULL );
mbedtls_mpi_write_file( "P: ", &P, 16, NULL );
mbedtls_mpi_write_file( "Q: ", &Q, 16, NULL );
mbedtls_mpi_write_file( "DP: ", &DP, 16, NULL );
mbedtls_mpi_write_file( "DQ: ", &DQ, 16, NULL );
mbedtls_mpi_write_file( "QP: ", &QP, 16, NULL );
} }
else else
#endif #endif
@ -409,6 +423,10 @@ exit:
#endif #endif
} }
mbedtls_mpi_free( &N ); mbedtls_mpi_free( &P ); mbedtls_mpi_free( &Q );
mbedtls_mpi_free( &D ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &DP );
mbedtls_mpi_free( &DQ ); mbedtls_mpi_free( &QP );
mbedtls_pk_free( &key ); mbedtls_pk_free( &key );
mbedtls_ctr_drbg_free( &ctr_drbg ); mbedtls_ctr_drbg_free( &ctr_drbg );
mbedtls_entropy_free( &entropy ); mbedtls_entropy_free( &entropy );
@ -422,4 +440,3 @@ exit:
} }
#endif /* MBEDTLS_PK_WRITE_C && MBEDTLS_PEM_WRITE_C && MBEDTLS_FS_IO && #endif /* MBEDTLS_PK_WRITE_C && MBEDTLS_PEM_WRITE_C && MBEDTLS_FS_IO &&
* MBEDTLS_ENTROPY_C && MBEDTLS_CTR_DRBG_C */ * MBEDTLS_ENTROPY_C && MBEDTLS_CTR_DRBG_C */

View file

@ -84,17 +84,23 @@ struct options
int main( int argc, char *argv[] ) int main( int argc, char *argv[] )
{ {
int ret = 0; int ret = 0;
mbedtls_pk_context pk;
char buf[1024]; char buf[1024];
int i; int i;
char *p, *q; char *p, *q;
mbedtls_pk_context pk;
mbedtls_mpi N, P, Q, D, E, DP, DQ, QP;
/* /*
* Set to sane values * Set to sane values
*/ */
mbedtls_pk_init( &pk ); mbedtls_pk_init( &pk );
memset( buf, 0, sizeof(buf) ); memset( buf, 0, sizeof(buf) );
mbedtls_mpi_init( &N ); mbedtls_mpi_init( &P ); mbedtls_mpi_init( &Q );
mbedtls_mpi_init( &D ); mbedtls_mpi_init( &E ); mbedtls_mpi_init( &DP );
mbedtls_mpi_init( &DQ ); mbedtls_mpi_init( &QP );
if( argc == 0 ) if( argc == 0 )
{ {
usage: usage:
@ -189,14 +195,22 @@ int main( int argc, char *argv[] )
if( mbedtls_pk_get_type( &pk ) == MBEDTLS_PK_RSA ) if( mbedtls_pk_get_type( &pk ) == MBEDTLS_PK_RSA )
{ {
mbedtls_rsa_context *rsa = mbedtls_pk_rsa( pk ); mbedtls_rsa_context *rsa = mbedtls_pk_rsa( pk );
mbedtls_mpi_write_file( "N: ", &rsa->N, 16, NULL );
mbedtls_mpi_write_file( "E: ", &rsa->E, 16, NULL ); if( ( ret = mbedtls_rsa_export ( rsa, &N, &P, &Q, &D, &E ) ) != 0 ||
mbedtls_mpi_write_file( "D: ", &rsa->D, 16, NULL ); ( ret = mbedtls_rsa_export_crt( rsa, &DP, &DQ, &QP ) ) != 0 )
mbedtls_mpi_write_file( "P: ", &rsa->P, 16, NULL ); {
mbedtls_mpi_write_file( "Q: ", &rsa->Q, 16, NULL ); mbedtls_printf( " failed\n ! could not export RSA parameters\n\n" );
mbedtls_mpi_write_file( "DP: ", &rsa->DP, 16, NULL ); goto exit;
mbedtls_mpi_write_file( "DQ: ", &rsa->DQ, 16, NULL ); }
mbedtls_mpi_write_file( "QP: ", &rsa->QP, 16, NULL );
mbedtls_mpi_write_file( "N: ", &N, 16, NULL );
mbedtls_mpi_write_file( "E: ", &E, 16, NULL );
mbedtls_mpi_write_file( "D: ", &D, 16, NULL );
mbedtls_mpi_write_file( "P: ", &P, 16, NULL );
mbedtls_mpi_write_file( "Q: ", &Q, 16, NULL );
mbedtls_mpi_write_file( "DP: ", &DP, 16, NULL );
mbedtls_mpi_write_file( "DQ: ", &DQ, 16, NULL );
mbedtls_mpi_write_file( "QP: ", &QP, 16, NULL );
} }
else else
#endif #endif
@ -239,8 +253,15 @@ int main( int argc, char *argv[] )
if( mbedtls_pk_get_type( &pk ) == MBEDTLS_PK_RSA ) if( mbedtls_pk_get_type( &pk ) == MBEDTLS_PK_RSA )
{ {
mbedtls_rsa_context *rsa = mbedtls_pk_rsa( pk ); mbedtls_rsa_context *rsa = mbedtls_pk_rsa( pk );
mbedtls_mpi_write_file( "N: ", &rsa->N, 16, NULL );
mbedtls_mpi_write_file( "E: ", &rsa->E, 16, NULL ); if( ( ret = mbedtls_rsa_export( rsa, &N, NULL, NULL,
NULL, &E ) ) != 0 )
{
mbedtls_printf( " failed\n ! could not export RSA parameters\n\n" );
goto exit;
}
mbedtls_mpi_write_file( "N: ", &N, 16, NULL );
mbedtls_mpi_write_file( "E: ", &E, 16, NULL );
} }
else else
#endif #endif
@ -265,11 +286,17 @@ int main( int argc, char *argv[] )
exit: exit:
#if defined(MBEDTLS_ERROR_C) #if defined(MBEDTLS_ERROR_C)
mbedtls_strerror( ret, buf, sizeof(buf) ); if( ret != 0 )
mbedtls_printf( " ! Last error was: %s\n", buf ); {
mbedtls_strerror( ret, buf, sizeof(buf) );
mbedtls_printf( " ! Last error was: %s\n", buf );
}
#endif #endif
mbedtls_pk_free( &pk ); mbedtls_pk_free( &pk );
mbedtls_mpi_free( &N ); mbedtls_mpi_free( &P ); mbedtls_mpi_free( &Q );
mbedtls_mpi_free( &D ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &DP );
mbedtls_mpi_free( &DQ ); mbedtls_mpi_free( &QP );
#if defined(_WIN32) #if defined(_WIN32)
mbedtls_printf( " + Press Enter to exit this program.\n" ); mbedtls_printf( " + Press Enter to exit this program.\n" );

View file

@ -76,7 +76,7 @@
#define OUTPUT_FORMAT_DER 1 #define OUTPUT_FORMAT_DER 1
#define USAGE \ #define USAGE \
"\n usage: key_app param=<>...\n" \ "\n usage: key_app_writer param=<>...\n" \
"\n acceptable parameters:\n" \ "\n acceptable parameters:\n" \
" mode=private|public default: none\n" \ " mode=private|public default: none\n" \
" filename=%%s default: keyfile.key\n" \ " filename=%%s default: keyfile.key\n" \
@ -190,17 +190,23 @@ static int write_private_key( mbedtls_pk_context *key, const char *output_file )
int main( int argc, char *argv[] ) int main( int argc, char *argv[] )
{ {
int ret = 0; int ret = 0;
mbedtls_pk_context key;
char buf[1024]; char buf[1024];
int i; int i;
char *p, *q; char *p, *q;
mbedtls_pk_context key;
mbedtls_mpi N, P, Q, D, E, DP, DQ, QP;
/* /*
* Set to sane values * Set to sane values
*/ */
mbedtls_pk_init( &key ); mbedtls_pk_init( &key );
memset( buf, 0, sizeof( buf ) ); memset( buf, 0, sizeof( buf ) );
mbedtls_mpi_init( &N ); mbedtls_mpi_init( &P ); mbedtls_mpi_init( &Q );
mbedtls_mpi_init( &D ); mbedtls_mpi_init( &E ); mbedtls_mpi_init( &DP );
mbedtls_mpi_init( &DQ ); mbedtls_mpi_init( &QP );
if( argc == 0 ) if( argc == 0 )
{ {
usage: usage:
@ -300,14 +306,22 @@ int main( int argc, char *argv[] )
if( mbedtls_pk_get_type( &key ) == MBEDTLS_PK_RSA ) if( mbedtls_pk_get_type( &key ) == MBEDTLS_PK_RSA )
{ {
mbedtls_rsa_context *rsa = mbedtls_pk_rsa( key ); mbedtls_rsa_context *rsa = mbedtls_pk_rsa( key );
mbedtls_mpi_write_file( "N: ", &rsa->N, 16, NULL );
mbedtls_mpi_write_file( "E: ", &rsa->E, 16, NULL ); if( ( ret = mbedtls_rsa_export ( rsa, &N, &P, &Q, &D, &E ) ) != 0 ||
mbedtls_mpi_write_file( "D: ", &rsa->D, 16, NULL ); ( ret = mbedtls_rsa_export_crt( rsa, &DP, &DQ, &QP ) ) != 0 )
mbedtls_mpi_write_file( "P: ", &rsa->P, 16, NULL ); {
mbedtls_mpi_write_file( "Q: ", &rsa->Q, 16, NULL ); mbedtls_printf( " failed\n ! could not export RSA parameters\n\n" );
mbedtls_mpi_write_file( "DP: ", &rsa->DP, 16, NULL ); goto exit;
mbedtls_mpi_write_file( "DQ: ", &rsa->DQ, 16, NULL ); }
mbedtls_mpi_write_file( "QP: ", &rsa->QP, 16, NULL );
mbedtls_mpi_write_file( "N: ", &N, 16, NULL );
mbedtls_mpi_write_file( "E: ", &E, 16, NULL );
mbedtls_mpi_write_file( "D: ", &D, 16, NULL );
mbedtls_mpi_write_file( "P: ", &P, 16, NULL );
mbedtls_mpi_write_file( "Q: ", &Q, 16, NULL );
mbedtls_mpi_write_file( "DP: ", &DP, 16, NULL );
mbedtls_mpi_write_file( "DQ: ", &DQ, 16, NULL );
mbedtls_mpi_write_file( "QP: ", &QP, 16, NULL );
} }
else else
#endif #endif
@ -353,8 +367,15 @@ int main( int argc, char *argv[] )
if( mbedtls_pk_get_type( &key ) == MBEDTLS_PK_RSA ) if( mbedtls_pk_get_type( &key ) == MBEDTLS_PK_RSA )
{ {
mbedtls_rsa_context *rsa = mbedtls_pk_rsa( key ); mbedtls_rsa_context *rsa = mbedtls_pk_rsa( key );
mbedtls_mpi_write_file( "N: ", &rsa->N, 16, NULL );
mbedtls_mpi_write_file( "E: ", &rsa->E, 16, NULL ); if( ( ret = mbedtls_rsa_export( rsa, &N, NULL, NULL,
NULL, &E ) ) != 0 )
{
mbedtls_printf( " failed\n ! could not export RSA parameters\n\n" );
goto exit;
}
mbedtls_mpi_write_file( "N: ", &N, 16, NULL );
mbedtls_mpi_write_file( "E: ", &E, 16, NULL );
} }
else else
#endif #endif
@ -394,6 +415,10 @@ exit:
#endif #endif
} }
mbedtls_mpi_free( &N ); mbedtls_mpi_free( &P ); mbedtls_mpi_free( &Q );
mbedtls_mpi_free( &D ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &DP );
mbedtls_mpi_free( &DQ ); mbedtls_mpi_free( &QP );
mbedtls_pk_free( &key ); mbedtls_pk_free( &key );
#if defined(_WIN32) #if defined(_WIN32)

View file

@ -64,6 +64,7 @@ int main( int argc, char *argv[] )
int return_val, exit_val, c; int return_val, exit_val, c;
size_t i; size_t i;
mbedtls_rsa_context rsa; mbedtls_rsa_context rsa;
mbedtls_mpi N, P, Q, D, E, DP, DQ, QP;
mbedtls_entropy_context entropy; mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg; mbedtls_ctr_drbg_context ctr_drbg;
unsigned char result[1024]; unsigned char result[1024];
@ -91,6 +92,9 @@ int main( int argc, char *argv[] )
mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 ); mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 );
mbedtls_ctr_drbg_init( &ctr_drbg ); mbedtls_ctr_drbg_init( &ctr_drbg );
mbedtls_entropy_init( &entropy ); mbedtls_entropy_init( &entropy );
mbedtls_mpi_init( &N ); mbedtls_mpi_init( &P ); mbedtls_mpi_init( &Q );
mbedtls_mpi_init( &D ); mbedtls_mpi_init( &E ); mbedtls_mpi_init( &DP );
mbedtls_mpi_init( &DQ ); mbedtls_mpi_init( &QP );
return_val = mbedtls_ctr_drbg_seed( &ctr_drbg, mbedtls_entropy_func, return_val = mbedtls_ctr_drbg_seed( &ctr_drbg, mbedtls_entropy_func,
&entropy, (const unsigned char *) pers, &entropy, (const unsigned char *) pers,
@ -114,14 +118,14 @@ int main( int argc, char *argv[] )
goto exit; goto exit;
} }
if( ( return_val = mbedtls_mpi_read_file( &rsa.N , 16, f ) ) != 0 || if( ( return_val = mbedtls_mpi_read_file( &N , 16, f ) ) != 0 ||
( return_val = mbedtls_mpi_read_file( &rsa.E , 16, f ) ) != 0 || ( return_val = mbedtls_mpi_read_file( &E , 16, f ) ) != 0 ||
( return_val = mbedtls_mpi_read_file( &rsa.D , 16, f ) ) != 0 || ( return_val = mbedtls_mpi_read_file( &D , 16, f ) ) != 0 ||
( return_val = mbedtls_mpi_read_file( &rsa.P , 16, f ) ) != 0 || ( return_val = mbedtls_mpi_read_file( &P , 16, f ) ) != 0 ||
( return_val = mbedtls_mpi_read_file( &rsa.Q , 16, f ) ) != 0 || ( return_val = mbedtls_mpi_read_file( &Q , 16, f ) ) != 0 ||
( return_val = mbedtls_mpi_read_file( &rsa.DP, 16, f ) ) != 0 || ( return_val = mbedtls_mpi_read_file( &DP , 16, f ) ) != 0 ||
( return_val = mbedtls_mpi_read_file( &rsa.DQ, 16, f ) ) != 0 || ( return_val = mbedtls_mpi_read_file( &DQ , 16, f ) ) != 0 ||
( return_val = mbedtls_mpi_read_file( &rsa.QP, 16, f ) ) != 0 ) ( return_val = mbedtls_mpi_read_file( &QP , 16, f ) ) != 0 )
{ {
exit_val = MBEDTLS_EXIT_FAILURE; exit_val = MBEDTLS_EXIT_FAILURE;
mbedtls_printf( " failed\n ! mbedtls_mpi_read_file returned %d\n\n", mbedtls_printf( " failed\n ! mbedtls_mpi_read_file returned %d\n\n",
@ -129,11 +133,22 @@ int main( int argc, char *argv[] )
fclose( f ); fclose( f );
goto exit; goto exit;
} }
rsa.len = ( mbedtls_mpi_bitlen( &rsa.N ) + 7 ) >> 3;
fclose( f ); fclose( f );
if( ( return_val = mbedtls_rsa_import( &rsa, &N, &P, &Q, &D, &E ) ) != 0 )
{
mbedtls_printf( " failed\n ! mbedtls_rsa_import returned %d\n\n",
return_val );
goto exit;
}
if( ( return_val = mbedtls_rsa_complete( &rsa ) ) != 0 )
{
mbedtls_printf( " failed\n ! mbedtls_rsa_complete returned %d\n\n",
return_val );
goto exit;
}
/* /*
* Extract the RSA encrypted value from the text file * Extract the RSA encrypted value from the text file
*/ */
@ -184,6 +199,9 @@ exit:
mbedtls_ctr_drbg_free( &ctr_drbg ); mbedtls_ctr_drbg_free( &ctr_drbg );
mbedtls_entropy_free( &entropy ); mbedtls_entropy_free( &entropy );
mbedtls_rsa_free( &rsa ); mbedtls_rsa_free( &rsa );
mbedtls_mpi_free( &N ); mbedtls_mpi_free( &P ); mbedtls_mpi_free( &Q );
mbedtls_mpi_free( &D ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &DP );
mbedtls_mpi_free( &DQ ); mbedtls_mpi_free( &QP );
#if defined(_WIN32) #if defined(_WIN32)
mbedtls_printf( " + Press Enter to exit this program.\n" ); mbedtls_printf( " + Press Enter to exit this program.\n" );
@ -193,4 +211,3 @@ exit:
return( exit_val ); return( exit_val );
} }
#endif /* MBEDTLS_BIGNUM_C && MBEDTLS_RSA_C && MBEDTLS_FS_IO */ #endif /* MBEDTLS_BIGNUM_C && MBEDTLS_RSA_C && MBEDTLS_FS_IO */

View file

@ -69,6 +69,7 @@ int main( int argc, char *argv[] )
unsigned char input[1024]; unsigned char input[1024];
unsigned char buf[512]; unsigned char buf[512];
const char *pers = "rsa_encrypt"; const char *pers = "rsa_encrypt";
mbedtls_mpi N, E;
exit_val = MBEDTLS_EXIT_SUCCESS; exit_val = MBEDTLS_EXIT_SUCCESS;
@ -86,6 +87,7 @@ int main( int argc, char *argv[] )
mbedtls_printf( "\n . Seeding the random number generator..." ); mbedtls_printf( "\n . Seeding the random number generator..." );
fflush( stdout ); fflush( stdout );
mbedtls_mpi_init( &N ); mbedtls_mpi_init( &E );
mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 ); mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 );
mbedtls_ctr_drbg_init( &ctr_drbg ); mbedtls_ctr_drbg_init( &ctr_drbg );
mbedtls_entropy_init( &entropy ); mbedtls_entropy_init( &entropy );
@ -112,8 +114,8 @@ int main( int argc, char *argv[] )
goto exit; goto exit;
} }
if( ( return_val = mbedtls_mpi_read_file( &rsa.N, 16, f ) ) != 0 || if( ( return_val = mbedtls_mpi_read_file( &N, 16, f ) ) != 0 ||
( return_val = mbedtls_mpi_read_file( &rsa.E, 16, f ) ) != 0 ) ( return_val = mbedtls_mpi_read_file( &E, 16, f ) ) != 0 )
{ {
exit_val = MBEDTLS_EXIT_FAILURE; exit_val = MBEDTLS_EXIT_FAILURE;
mbedtls_printf( " failed\n ! mbedtls_mpi_read_file returned %d\n\n", mbedtls_printf( " failed\n ! mbedtls_mpi_read_file returned %d\n\n",
@ -121,11 +123,17 @@ int main( int argc, char *argv[] )
fclose( f ); fclose( f );
goto exit; goto exit;
} }
rsa.len = ( mbedtls_mpi_bitlen( &rsa.N ) + 7 ) >> 3;
fclose( f ); fclose( f );
if( ( return_val = mbedtls_rsa_import( &rsa, &N, NULL,
NULL, NULL, &E ) ) != 0 )
{
exit_val = MBEDTLS_EXIT_FAILURE;
mbedtls_printf( " failed\n ! mbedtls_rsa_import returned %d\n\n",
return_val );
goto exit;
}
if( strlen( argv[1] ) > 100 ) if( strlen( argv[1] ) > 100 )
{ {
exit_val = MBEDTLS_EXIT_FAILURE; exit_val = MBEDTLS_EXIT_FAILURE;
@ -171,6 +179,7 @@ int main( int argc, char *argv[] )
mbedtls_printf( "\n . Done (created \"%s\")\n\n", "result-enc.txt" ); mbedtls_printf( "\n . Done (created \"%s\")\n\n", "result-enc.txt" );
exit: exit:
mbedtls_mpi_free( &N ); mbedtls_mpi_free( &E );
mbedtls_ctr_drbg_free( &ctr_drbg ); mbedtls_ctr_drbg_free( &ctr_drbg );
mbedtls_entropy_free( &entropy ); mbedtls_entropy_free( &entropy );
mbedtls_rsa_free( &rsa ); mbedtls_rsa_free( &rsa );

View file

@ -65,11 +65,16 @@ int main( void )
mbedtls_rsa_context rsa; mbedtls_rsa_context rsa;
mbedtls_entropy_context entropy; mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg; mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_mpi N, P, Q, D, E, DP, DQ, QP;
FILE *fpub = NULL; FILE *fpub = NULL;
FILE *fpriv = NULL; FILE *fpriv = NULL;
const char *pers = "rsa_genkey"; const char *pers = "rsa_genkey";
mbedtls_ctr_drbg_init( &ctr_drbg ); mbedtls_ctr_drbg_init( &ctr_drbg );
mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 );
mbedtls_mpi_init( &N ); mbedtls_mpi_init( &P ); mbedtls_mpi_init( &Q );
mbedtls_mpi_init( &D ); mbedtls_mpi_init( &E ); mbedtls_mpi_init( &DP );
mbedtls_mpi_init( &DQ ); mbedtls_mpi_init( &QP );
mbedtls_printf( "\n . Seeding the random number generator..." ); mbedtls_printf( "\n . Seeding the random number generator..." );
fflush( stdout ); fflush( stdout );
@ -86,10 +91,8 @@ int main( void )
mbedtls_printf( " ok\n . Generating the RSA key [ %d-bit ]...", KEY_SIZE ); mbedtls_printf( " ok\n . Generating the RSA key [ %d-bit ]...", KEY_SIZE );
fflush( stdout ); fflush( stdout );
mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 );
if( ( ret = mbedtls_rsa_gen_key( &rsa, mbedtls_ctr_drbg_random, &ctr_drbg, KEY_SIZE, if( ( ret = mbedtls_rsa_gen_key( &rsa, mbedtls_ctr_drbg_random, &ctr_drbg, KEY_SIZE,
EXPONENT ) ) != 0 ) EXPONENT ) ) != 0 )
{ {
mbedtls_printf( " failed\n ! mbedtls_rsa_gen_key returned %d\n\n", ret ); mbedtls_printf( " failed\n ! mbedtls_rsa_gen_key returned %d\n\n", ret );
goto exit; goto exit;
@ -98,6 +101,14 @@ int main( void )
mbedtls_printf( " ok\n . Exporting the public key in rsa_pub.txt...." ); mbedtls_printf( " ok\n . Exporting the public key in rsa_pub.txt...." );
fflush( stdout ); fflush( stdout );
if( ( ret = mbedtls_rsa_export ( &rsa, &N, &P, &Q, &D, &E ) ) != 0 ||
( ret = mbedtls_rsa_export_crt( &rsa, &DP, &DQ, &QP ) ) != 0 )
{
mbedtls_printf( " failed\n ! could not export RSA parameters\n\n" );
ret = 1;
goto exit;
}
if( ( fpub = fopen( "rsa_pub.txt", "wb+" ) ) == NULL ) if( ( fpub = fopen( "rsa_pub.txt", "wb+" ) ) == NULL )
{ {
mbedtls_printf( " failed\n ! could not open rsa_pub.txt for writing\n\n" ); mbedtls_printf( " failed\n ! could not open rsa_pub.txt for writing\n\n" );
@ -105,8 +116,8 @@ int main( void )
goto exit; goto exit;
} }
if( ( ret = mbedtls_mpi_write_file( "N = ", &rsa.N, 16, fpub ) ) != 0 || if( ( ret = mbedtls_mpi_write_file( "N = ", &N, 16, fpub ) ) != 0 ||
( ret = mbedtls_mpi_write_file( "E = ", &rsa.E, 16, fpub ) ) != 0 ) ( ret = mbedtls_mpi_write_file( "E = ", &E, 16, fpub ) ) != 0 )
{ {
mbedtls_printf( " failed\n ! mbedtls_mpi_write_file returned %d\n\n", ret ); mbedtls_printf( " failed\n ! mbedtls_mpi_write_file returned %d\n\n", ret );
goto exit; goto exit;
@ -122,14 +133,14 @@ int main( void )
goto exit; goto exit;
} }
if( ( ret = mbedtls_mpi_write_file( "N = " , &rsa.N , 16, fpriv ) ) != 0 || if( ( ret = mbedtls_mpi_write_file( "N = " , &N , 16, fpriv ) ) != 0 ||
( ret = mbedtls_mpi_write_file( "E = " , &rsa.E , 16, fpriv ) ) != 0 || ( ret = mbedtls_mpi_write_file( "E = " , &E , 16, fpriv ) ) != 0 ||
( ret = mbedtls_mpi_write_file( "D = " , &rsa.D , 16, fpriv ) ) != 0 || ( ret = mbedtls_mpi_write_file( "D = " , &D , 16, fpriv ) ) != 0 ||
( ret = mbedtls_mpi_write_file( "P = " , &rsa.P , 16, fpriv ) ) != 0 || ( ret = mbedtls_mpi_write_file( "P = " , &P , 16, fpriv ) ) != 0 ||
( ret = mbedtls_mpi_write_file( "Q = " , &rsa.Q , 16, fpriv ) ) != 0 || ( ret = mbedtls_mpi_write_file( "Q = " , &Q , 16, fpriv ) ) != 0 ||
( ret = mbedtls_mpi_write_file( "DP = ", &rsa.DP, 16, fpriv ) ) != 0 || ( ret = mbedtls_mpi_write_file( "DP = ", &DP, 16, fpriv ) ) != 0 ||
( ret = mbedtls_mpi_write_file( "DQ = ", &rsa.DQ, 16, fpriv ) ) != 0 || ( ret = mbedtls_mpi_write_file( "DQ = ", &DQ, 16, fpriv ) ) != 0 ||
( ret = mbedtls_mpi_write_file( "QP = ", &rsa.QP, 16, fpriv ) ) != 0 ) ( ret = mbedtls_mpi_write_file( "QP = ", &QP, 16, fpriv ) ) != 0 )
{ {
mbedtls_printf( " failed\n ! mbedtls_mpi_write_file returned %d\n\n", ret ); mbedtls_printf( " failed\n ! mbedtls_mpi_write_file returned %d\n\n", ret );
goto exit; goto exit;
@ -157,6 +168,9 @@ exit:
if( fpriv != NULL ) if( fpriv != NULL )
fclose( fpriv ); fclose( fpriv );
mbedtls_mpi_free( &N ); mbedtls_mpi_free( &P ); mbedtls_mpi_free( &Q );
mbedtls_mpi_free( &D ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &DP );
mbedtls_mpi_free( &DQ ); mbedtls_mpi_free( &QP );
mbedtls_rsa_free( &rsa ); mbedtls_rsa_free( &rsa );
mbedtls_ctr_drbg_free( &ctr_drbg ); mbedtls_ctr_drbg_free( &ctr_drbg );
mbedtls_entropy_free( &entropy ); mbedtls_entropy_free( &entropy );

View file

@ -61,8 +61,14 @@ int main( int argc, char *argv[] )
unsigned char hash[32]; unsigned char hash[32];
unsigned char buf[MBEDTLS_MPI_MAX_SIZE]; unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
char filename[512]; char filename[512];
mbedtls_mpi N, P, Q, D, E, DP, DQ, QP;
mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 ); mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 );
mbedtls_mpi_init( &N ); mbedtls_mpi_init( &P ); mbedtls_mpi_init( &Q );
mbedtls_mpi_init( &D ); mbedtls_mpi_init( &E ); mbedtls_mpi_init( &DP );
mbedtls_mpi_init( &DQ ); mbedtls_mpi_init( &QP );
ret = 1; ret = 1;
if( argc != 2 ) if( argc != 2 )
@ -87,24 +93,35 @@ int main( int argc, char *argv[] )
goto exit; goto exit;
} }
if( ( ret = mbedtls_mpi_read_file( &rsa.N , 16, f ) ) != 0 || if( ( ret = mbedtls_mpi_read_file( &N , 16, f ) ) != 0 ||
( ret = mbedtls_mpi_read_file( &rsa.E , 16, f ) ) != 0 || ( ret = mbedtls_mpi_read_file( &E , 16, f ) ) != 0 ||
( ret = mbedtls_mpi_read_file( &rsa.D , 16, f ) ) != 0 || ( ret = mbedtls_mpi_read_file( &D , 16, f ) ) != 0 ||
( ret = mbedtls_mpi_read_file( &rsa.P , 16, f ) ) != 0 || ( ret = mbedtls_mpi_read_file( &P , 16, f ) ) != 0 ||
( ret = mbedtls_mpi_read_file( &rsa.Q , 16, f ) ) != 0 || ( ret = mbedtls_mpi_read_file( &Q , 16, f ) ) != 0 ||
( ret = mbedtls_mpi_read_file( &rsa.DP, 16, f ) ) != 0 || ( ret = mbedtls_mpi_read_file( &DP , 16, f ) ) != 0 ||
( ret = mbedtls_mpi_read_file( &rsa.DQ, 16, f ) ) != 0 || ( ret = mbedtls_mpi_read_file( &DQ , 16, f ) ) != 0 ||
( ret = mbedtls_mpi_read_file( &rsa.QP, 16, f ) ) != 0 ) ( ret = mbedtls_mpi_read_file( &QP , 16, f ) ) != 0 )
{ {
mbedtls_printf( " failed\n ! mbedtls_mpi_read_file returned %d\n\n", ret ); mbedtls_printf( " failed\n ! mbedtls_mpi_read_file returned %d\n\n", ret );
fclose( f ); fclose( f );
goto exit; goto exit;
} }
rsa.len = ( mbedtls_mpi_bitlen( &rsa.N ) + 7 ) >> 3;
fclose( f ); fclose( f );
if( ( ret = mbedtls_rsa_import( &rsa, &N, &P, &Q, &D, &E ) ) != 0 )
{
mbedtls_printf( " failed\n ! mbedtls_rsa_import returned %d\n\n",
ret );
goto exit;
}
if( ( ret = mbedtls_rsa_complete( &rsa ) ) != 0 )
{
mbedtls_printf( " failed\n ! mbedtls_rsa_complete returned %d\n\n",
ret );
goto exit;
}
mbedtls_printf( "\n . Checking the private key" ); mbedtls_printf( "\n . Checking the private key" );
fflush( stdout ); fflush( stdout );
if( ( ret = mbedtls_rsa_check_privkey( &rsa ) ) != 0 ) if( ( ret = mbedtls_rsa_check_privkey( &rsa ) ) != 0 )
@ -158,6 +175,9 @@ int main( int argc, char *argv[] )
exit: exit:
mbedtls_rsa_free( &rsa ); mbedtls_rsa_free( &rsa );
mbedtls_mpi_free( &N ); mbedtls_mpi_free( &P ); mbedtls_mpi_free( &Q );
mbedtls_mpi_free( &D ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &DP );
mbedtls_mpi_free( &DQ ); mbedtls_mpi_free( &QP );
#if defined(_WIN32) #if defined(_WIN32)
mbedtls_printf( " + Press Enter to exit this program.\n" ); mbedtls_printf( " + Press Enter to exit this program.\n" );

View file

@ -203,7 +203,7 @@ int main( int argc, char *argv[] )
/* /*
* 4. Handshake * 4. Handshake
*/ */
mbedtls_printf( " . Performing the SSL/TLS handshake..." ); mbedtls_printf( " . Performing the DTLS handshake..." );
fflush( stdout ); fflush( stdout );
do ret = mbedtls_ssl_handshake( &ssl ); do ret = mbedtls_ssl_handshake( &ssl );

View file

@ -63,6 +63,9 @@ int main( void )
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#define MAX_REQUEST_SIZE 20000
#define MAX_REQUEST_SIZE_STR "20000"
#define DFL_SERVER_NAME "localhost" #define DFL_SERVER_NAME "localhost"
#define DFL_SERVER_ADDR NULL #define DFL_SERVER_ADDR NULL
#define DFL_SERVER_PORT "4433" #define DFL_SERVER_PORT "4433"
@ -242,8 +245,8 @@ int main( void )
" server_addr=%%s default: given by name\n" \ " server_addr=%%s default: given by name\n" \
" server_port=%%d default: 4433\n" \ " server_port=%%d default: 4433\n" \
" request_page=%%s default: \".\"\n" \ " request_page=%%s default: \".\"\n" \
" request_size=%%d default: about 34 (basic request)\n" \ " request_size=%%d default: about 34 (basic request)\n" \
" (minimum: 0, max: 16384)\n" \ " (minimum: 0, max: " MAX_REQUEST_SIZE_STR " )\n" \
" debug_level=%%d default: 0 (disabled)\n" \ " debug_level=%%d default: 0 (disabled)\n" \
" nbio=%%d default: 0 (blocking I/O)\n" \ " nbio=%%d default: 0 (blocking I/O)\n" \
" options: 1 (non-blocking), 2 (added delays)\n" \ " options: 1 (non-blocking), 2 (added delays)\n" \
@ -437,7 +440,9 @@ int main( int argc, char *argv[] )
{ {
int ret = 0, len, tail_len, i, written, frags, retry_left; int ret = 0, len, tail_len, i, written, frags, retry_left;
mbedtls_net_context server_fd; mbedtls_net_context server_fd;
unsigned char buf[MBEDTLS_SSL_MAX_CONTENT_LEN + 1];
unsigned char buf[MAX_REQUEST_SIZE + 1];
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
unsigned char psk[MBEDTLS_PSK_MAX_LEN]; unsigned char psk[MBEDTLS_PSK_MAX_LEN];
size_t psk_len = 0; size_t psk_len = 0;
@ -602,7 +607,8 @@ int main( int argc, char *argv[] )
else if( strcmp( p, "request_size" ) == 0 ) else if( strcmp( p, "request_size" ) == 0 )
{ {
opt.request_size = atoi( q ); opt.request_size = atoi( q );
if( opt.request_size < 0 || opt.request_size > MBEDTLS_SSL_MAX_CONTENT_LEN ) if( opt.request_size < 0 ||
opt.request_size > MAX_REQUEST_SIZE )
goto usage; goto usage;
} }
else if( strcmp( p, "ca_file" ) == 0 ) else if( strcmp( p, "ca_file" ) == 0 )
@ -1494,8 +1500,8 @@ send_request:
mbedtls_printf( " > Write to server:" ); mbedtls_printf( " > Write to server:" );
fflush( stdout ); fflush( stdout );
len = mbedtls_snprintf( (char *) buf, sizeof(buf) - 1, GET_REQUEST, len = mbedtls_snprintf( (char *) buf, sizeof( buf ) - 1, GET_REQUEST,
opt.request_page ); opt.request_page );
tail_len = (int) strlen( GET_REQUEST_END ); tail_len = (int) strlen( GET_REQUEST_END );
/* Add padding to GET request to reach opt.request_size in length */ /* Add padding to GET request to reach opt.request_size in length */
@ -1506,7 +1512,7 @@ send_request:
len += opt.request_size - len - tail_len; len += opt.request_size - len - tail_len;
} }
strncpy( (char *) buf + len, GET_REQUEST_END, sizeof(buf) - len - 1 ); strncpy( (char *) buf + len, GET_REQUEST_END, sizeof( buf ) - len - 1 );
len += tail_len; len += tail_len;
/* Truncate if request size is smaller than the "natural" size */ /* Truncate if request size is smaller than the "natural" size */
@ -1550,6 +1556,12 @@ send_request:
frags = 1; frags = 1;
written = ret; written = ret;
if( written < len )
{
mbedtls_printf( " warning\n ! request didn't fit into single datagram and "
"was truncated to size %u", (unsigned) written );
}
} }
buf[written] = '\0'; buf[written] = '\0';

View file

@ -326,7 +326,7 @@ int main( void )
#define USAGE \ #define USAGE \
"\n usage: ssl_server2 param=<>...\n" \ "\n usage: ssl_server2 param=<>...\n" \
"\n acceptable parameters:\n" \ "\n acceptable parameters:\n" \
" server_addr=%%d default: (all interfaces)\n" \ " server_addr=%%s default: (all interfaces)\n" \
" server_port=%%d default: 4433\n" \ " server_port=%%d default: 4433\n" \
" debug_level=%%d default: 0 (disabled)\n" \ " debug_level=%%d default: 0 (disabled)\n" \
" nbio=%%d default: 0 (blocking I/O)\n" \ " nbio=%%d default: 0 (blocking I/O)\n" \
@ -2168,7 +2168,7 @@ handshake:
#if defined(MBEDTLS_X509_CRT_PARSE_C) #if defined(MBEDTLS_X509_CRT_PARSE_C)
/* /*
* 5. Verify the server certificate * 5. Verify the client certificate
*/ */
mbedtls_printf( " . Verifying peer X.509 certificate..." ); mbedtls_printf( " . Verifying peer X.509 certificate..." );

View file

@ -126,7 +126,7 @@ do { \
CODE; \ CODE; \
} \ } \
\ \
mbedtls_printf( "%9lu Kb/s, %9lu cycles/byte\n", \ mbedtls_printf( "%9lu KiB/s, %9lu cycles/byte\n", \
ii * BUFSIZE / 1024, \ ii * BUFSIZE / 1024, \
( mbedtls_timing_hardclock() - tsc ) / ( jj * BUFSIZE ) ); \ ( mbedtls_timing_hardclock() - tsc ) / ( jj * BUFSIZE ) ); \
} while( 0 ) } while( 0 )

View file

@ -107,8 +107,8 @@ static int run_test_snprintf( void )
* self-test. If this fails, we attempt the test anyway, so no error is passed * self-test. If this fails, we attempt the test anyway, so no error is passed
* back. * back.
*/ */
#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_ENTROPY_C) && \ #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_ENTROPY_C)
defined(MBEDTLS_ENTROPY_NV_SEED) && !defined(MBEDTLS_NO_PLATFORM_ENTROPY) #if defined(MBEDTLS_ENTROPY_NV_SEED) && !defined(MBEDTLS_NO_PLATFORM_ENTROPY)
static void create_entropy_seed_file( void ) static void create_entropy_seed_file( void )
{ {
int result; int result;
@ -136,9 +136,137 @@ static void create_entropy_seed_file( void )
} }
#endif #endif
int mbedtls_entropy_self_test_wrapper( int verbose )
{
#if defined(MBEDTLS_ENTROPY_NV_SEED) && !defined(MBEDTLS_NO_PLATFORM_ENTROPY)
create_entropy_seed_file( );
#endif
return( mbedtls_entropy_self_test( verbose ) );
}
#endif
#if defined(MBEDTLS_SELF_TEST)
#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
int mbedtls_memory_buffer_alloc_free_and_self_test( int verbose )
{
if( verbose != 0 )
{
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_memory_buffer_alloc_status( );
#endif
}
mbedtls_memory_buffer_alloc_free( );
return( mbedtls_memory_buffer_alloc_self_test( verbose ) );
}
#endif
typedef struct
{
const char *name;
int ( *function )( int );
} selftest_t;
const selftest_t selftests[] =
{
#if defined(MBEDTLS_MD2_C)
{"md2", mbedtls_md2_self_test},
#endif
#if defined(MBEDTLS_MD4_C)
{"md4", mbedtls_md4_self_test},
#endif
#if defined(MBEDTLS_MD5_C)
{"md5", mbedtls_md5_self_test},
#endif
#if defined(MBEDTLS_RIPEMD160_C)
{"ripemd160", mbedtls_ripemd160_self_test},
#endif
#if defined(MBEDTLS_SHA1_C)
{"sha1", mbedtls_sha1_self_test},
#endif
#if defined(MBEDTLS_SHA256_C)
{"sha256", mbedtls_sha256_self_test},
#endif
#if defined(MBEDTLS_SHA512_C)
{"sha512", mbedtls_sha512_self_test},
#endif
#if defined(MBEDTLS_ARC4_C)
{"arc4", mbedtls_arc4_self_test},
#endif
#if defined(MBEDTLS_DES_C)
{"des", mbedtls_des_self_test},
#endif
#if defined(MBEDTLS_AES_C)
{"aes", mbedtls_aes_self_test},
#endif
#if defined(MBEDTLS_GCM_C) && defined(MBEDTLS_AES_C)
{"gcm", mbedtls_gcm_self_test},
#endif
#if defined(MBEDTLS_CCM_C) && defined(MBEDTLS_AES_C)
{"ccm", mbedtls_ccm_self_test},
#endif
#if defined(MBEDTLS_CMAC_C)
{"cmac", mbedtls_cmac_self_test},
#endif
#if defined(MBEDTLS_BASE64_C)
{"base64", mbedtls_base64_self_test},
#endif
#if defined(MBEDTLS_BIGNUM_C)
{"mpi", mbedtls_mpi_self_test},
#endif
#if defined(MBEDTLS_RSA_C)
{"rsa", mbedtls_rsa_self_test},
#endif
#if defined(MBEDTLS_X509_USE_C)
{"x509", mbedtls_x509_self_test},
#endif
#if defined(MBEDTLS_XTEA_C)
{"xtea", mbedtls_xtea_self_test},
#endif
#if defined(MBEDTLS_CAMELLIA_C)
{"camellia", mbedtls_camellia_self_test},
#endif
#if defined(MBEDTLS_CTR_DRBG_C)
{"ctr_drbg", mbedtls_ctr_drbg_self_test},
#endif
#if defined(MBEDTLS_HMAC_DRBG_C)
{"hmac_drbg", mbedtls_hmac_drbg_self_test},
#endif
#if defined(MBEDTLS_ECP_C)
{"ecp", mbedtls_ecp_self_test},
#endif
#if defined(MBEDTLS_ECJPAKE_C)
{"ecjpake", mbedtls_ecjpake_self_test},
#endif
#if defined(MBEDTLS_DHM_C)
{"dhm", mbedtls_dhm_self_test},
#endif
#if defined(MBEDTLS_ENTROPY_C)
{"entropy", mbedtls_entropy_self_test_wrapper},
#endif
#if defined(MBEDTLS_PKCS5_C)
{"pkcs5", mbedtls_pkcs5_self_test},
#endif
/* Slower test after the faster ones */
#if defined(MBEDTLS_TIMING_C)
{"timing", mbedtls_timing_self_test},
#endif
/* Heap test comes last */
#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
{"memory_buffer_alloc", mbedtls_memory_buffer_alloc_free_and_self_test},
#endif
{NULL, NULL}
};
#endif /* MBEDTLS_SELF_TEST */
int main( int argc, char *argv[] ) int main( int argc, char *argv[] )
{ {
int v, suites_tested = 0, suites_failed = 0; #if defined(MBEDTLS_SELF_TEST)
const selftest_t *test;
#endif /* MBEDTLS_SELF_TEST */
char **argp;
int v = 1; /* v=1 for verbose mode */
int exclude_mode = 0;
int suites_tested = 0, suites_failed = 0;
#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) && defined(MBEDTLS_SELF_TEST) #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) && defined(MBEDTLS_SELF_TEST)
unsigned char buf[1000000]; unsigned char buf[1000000];
#endif #endif
@ -165,16 +293,24 @@ int main( int argc, char *argv[] )
mbedtls_exit( MBEDTLS_EXIT_FAILURE ); mbedtls_exit( MBEDTLS_EXIT_FAILURE );
} }
if( argc == 2 && ( strcmp( argv[1], "--quiet" ) == 0 || for( argp = argv + ( argc >= 1 ? 1 : argc ); *argp != NULL; ++argp )
strcmp( argv[1], "-q" ) == 0 ) )
{ {
v = 0; if( strcmp( *argp, "--quiet" ) == 0 ||
strcmp( *argp, "-q" ) == 0 )
{
v = 0;
}
else if( strcmp( *argp, "--exclude" ) == 0 ||
strcmp( *argp, "-x" ) == 0 )
{
exclude_mode = 1;
}
else
break;
} }
else
{ if( v != 0 )
v = 1;
mbedtls_printf( "\n" ); mbedtls_printf( "\n" );
}
#if defined(MBEDTLS_SELF_TEST) #if defined(MBEDTLS_SELF_TEST)
@ -182,246 +318,60 @@ int main( int argc, char *argv[] )
mbedtls_memory_buffer_alloc_init( buf, sizeof(buf) ); mbedtls_memory_buffer_alloc_init( buf, sizeof(buf) );
#endif #endif
#if defined(MBEDTLS_MD2_C) if( *argp != NULL && exclude_mode == 0 )
if( mbedtls_md2_self_test( v ) != 0 )
{ {
suites_failed++; /* Run the specified tests */
for( ; *argp != NULL; argp++ )
{
for( test = selftests; test->name != NULL; test++ )
{
if( !strcmp( *argp, test->name ) )
{
if( test->function( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
break;
}
}
if( test->name == NULL )
{
mbedtls_printf( " Test suite %s not available -> failed\n\n", *argp );
suites_failed++;
}
}
} }
suites_tested++; else
#endif
#if defined(MBEDTLS_MD4_C)
if( mbedtls_md4_self_test( v ) != 0 )
{ {
suites_failed++; /* Run all the tests except excluded ones */
for( test = selftests; test->name != NULL; test++ )
{
if( exclude_mode )
{
char **excluded;
for( excluded = argp; *excluded != NULL; ++excluded )
{
if( !strcmp( *excluded, test->name ) )
break;
}
if( *excluded )
{
if( v )
mbedtls_printf( " Skip: %s\n", test->name );
continue;
}
}
if( test->function( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
}
} }
suites_tested++;
#endif
#if defined(MBEDTLS_MD5_C)
if( mbedtls_md5_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_RIPEMD160_C)
if( mbedtls_ripemd160_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_SHA1_C)
if( mbedtls_sha1_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_SHA256_C)
if( mbedtls_sha256_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_SHA512_C)
if( mbedtls_sha512_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_ARC4_C)
if( mbedtls_arc4_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_DES_C)
if( mbedtls_des_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_AES_C)
if( mbedtls_aes_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_GCM_C) && defined(MBEDTLS_AES_C)
if( mbedtls_gcm_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_CCM_C) && defined(MBEDTLS_AES_C)
if( mbedtls_ccm_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_CMAC_C)
if( ( mbedtls_cmac_self_test( v ) ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_BASE64_C)
if( mbedtls_base64_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_BIGNUM_C)
if( mbedtls_mpi_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_RSA_C)
if( mbedtls_rsa_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_X509_USE_C)
if( mbedtls_x509_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_XTEA_C)
if( mbedtls_xtea_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_CAMELLIA_C)
if( mbedtls_camellia_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_CTR_DRBG_C)
if( mbedtls_ctr_drbg_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_HMAC_DRBG_C)
if( mbedtls_hmac_drbg_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_ECP_C)
if( mbedtls_ecp_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_ECJPAKE_C)
if( mbedtls_ecjpake_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_DHM_C)
if( mbedtls_dhm_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_ENTROPY_C)
#if defined(MBEDTLS_ENTROPY_NV_SEED) && !defined(MBEDTLS_NO_PLATFORM_ENTROPY)
create_entropy_seed_file();
#endif
if( mbedtls_entropy_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#if defined(MBEDTLS_PKCS5_C)
if( mbedtls_pkcs5_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
/* Slow tests last */
#if defined(MBEDTLS_TIMING_C)
if( mbedtls_timing_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
if( v != 0 )
{
#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) && defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_memory_buffer_alloc_status();
#endif
}
#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
mbedtls_memory_buffer_alloc_free();
if( mbedtls_memory_buffer_alloc_self_test( v ) != 0 )
{
suites_failed++;
}
suites_tested++;
#endif
#else #else
(void) exclude_mode;
mbedtls_printf( " MBEDTLS_SELF_TEST not defined.\n" ); mbedtls_printf( " MBEDTLS_SELF_TEST not defined.\n" );
#endif #endif

View file

@ -51,6 +51,7 @@ int main( void )
#include "mbedtls/x509_csr.h" #include "mbedtls/x509_csr.h"
#include "mbedtls/entropy.h" #include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h" #include "mbedtls/ctr_drbg.h"
#include "mbedtls/md.h"
#include "mbedtls/error.h" #include "mbedtls/error.h"
#include <stdio.h> #include <stdio.h>
@ -59,9 +60,9 @@ int main( void )
#if defined(MBEDTLS_X509_CSR_PARSE_C) #if defined(MBEDTLS_X509_CSR_PARSE_C)
#define USAGE_CSR \ #define USAGE_CSR \
" request_file=%%s default: (empty)\n" \ " request_file=%%s default: (empty)\n" \
" If request_file is specified, subject_key,\n" \ " If request_file is specified, subject_key,\n" \
" subject_pwd and subject_name are ignored!\n" " subject_pwd and subject_name are ignored!\n"
#else #else
#define USAGE_CSR "" #define USAGE_CSR ""
#endif /* MBEDTLS_X509_CSR_PARSE_C */ #endif /* MBEDTLS_X509_CSR_PARSE_C */
@ -83,50 +84,70 @@ int main( void )
#define DFL_MAX_PATHLEN -1 #define DFL_MAX_PATHLEN -1
#define DFL_KEY_USAGE 0 #define DFL_KEY_USAGE 0
#define DFL_NS_CERT_TYPE 0 #define DFL_NS_CERT_TYPE 0
#define DFL_VERSION 3
#define DFL_AUTH_IDENT 1
#define DFL_SUBJ_IDENT 1
#define DFL_CONSTRAINTS 1
#define DFL_DIGEST MBEDTLS_MD_SHA256
#define USAGE \ #define USAGE \
"\n usage: cert_write param=<>...\n" \ "\n usage: cert_write param=<>...\n" \
"\n acceptable parameters:\n" \ "\n acceptable parameters:\n" \
USAGE_CSR \ USAGE_CSR \
" subject_key=%%s default: subject.key\n" \ " subject_key=%%s default: subject.key\n" \
" subject_pwd=%%s default: (empty)\n" \ " subject_pwd=%%s default: (empty)\n" \
" subject_name=%%s default: CN=Cert,O=mbed TLS,C=UK\n" \ " subject_name=%%s default: CN=Cert,O=mbed TLS,C=UK\n" \
"\n" \ "\n" \
" issuer_crt=%%s default: (empty)\n" \ " issuer_crt=%%s default: (empty)\n" \
" If issuer_crt is specified, issuer_name is\n" \ " If issuer_crt is specified, issuer_name is\n" \
" ignored!\n" \ " ignored!\n" \
" issuer_name=%%s default: CN=CA,O=mbed TLS,C=UK\n" \ " issuer_name=%%s default: CN=CA,O=mbed TLS,C=UK\n" \
"\n" \ "\n" \
" selfsign=%%d default: 0 (false)\n" \ " selfsign=%%d default: 0 (false)\n" \
" If selfsign is enabled, issuer_name and\n" \ " If selfsign is enabled, issuer_name and\n" \
" issuer_key are required (issuer_crt and\n" \ " issuer_key are required (issuer_crt and\n" \
" subject_* are ignored\n" \ " subject_* are ignored\n" \
" issuer_key=%%s default: ca.key\n" \ " issuer_key=%%s default: ca.key\n" \
" issuer_pwd=%%s default: (empty)\n" \ " issuer_pwd=%%s default: (empty)\n" \
" output_file=%%s default: cert.crt\n" \ " output_file=%%s default: cert.crt\n" \
" serial=%%s default: 1\n" \ " serial=%%s default: 1\n" \
" not_before=%%s default: 20010101000000\n"\ " not_before=%%s default: 20010101000000\n"\
" not_after=%%s default: 20301231235959\n"\ " not_after=%%s default: 20301231235959\n"\
" is_ca=%%d default: 0 (disabled)\n" \ " is_ca=%%d default: 0 (disabled)\n" \
" max_pathlen=%%d default: -1 (none)\n" \ " max_pathlen=%%d default: -1 (none)\n" \
" key_usage=%%s default: (empty)\n" \ " md=%%s default: SHA256\n" \
" Comma-separated-list of values:\n" \ " Supported values:\n" \
" digital_signature\n" \ " MD5, SHA1, SHA256, SHA512\n"\
" non_repudiation\n" \ " version=%%d default: 3\n" \
" key_encipherment\n" \ " Possible values: 1, 2, 3\n"\
" data_encipherment\n" \ " subject_identifier=%%s default: 1\n" \
" key_agreement\n" \ " Possible values: 0, 1\n" \
" key_cert_sign\n" \ " (Considered for v3 only)\n"\
" crl_sign\n" \ " authority_identifier=%%s default: 1\n" \
" ns_cert_type=%%s default: (empty)\n" \ " Possible values: 0, 1\n" \
" Comma-separated-list of values:\n" \ " (Considered for v3 only)\n"\
" ssl_client\n" \ " basic_constraints=%%d default: 1\n" \
" ssl_server\n" \ " Possible values: 0, 1\n" \
" email\n" \ " (Considered for v3 only)\n"\
" object_signing\n" \ " key_usage=%%s default: (empty)\n" \
" ssl_ca\n" \ " Comma-separated-list of values:\n" \
" email_ca\n" \ " digital_signature\n" \
" object_signing_ca\n" \ " non_repudiation\n" \
" key_encipherment\n" \
" data_encipherment\n" \
" key_agreement\n" \
" key_cert_sign\n" \
" crl_sign\n" \
" (Considered for v3 only)\n"\
" ns_cert_type=%%s default: (empty)\n" \
" Comma-separated-list of values:\n" \
" ssl_client\n" \
" ssl_server\n" \
" email\n" \
" object_signing\n" \
" ssl_ca\n" \
" email_ca\n" \
" object_signing_ca\n" \
"\n" "\n"
/* /*
@ -149,6 +170,11 @@ struct options
int selfsign; /* selfsign the certificate */ int selfsign; /* selfsign the certificate */
int is_ca; /* is a CA certificate */ int is_ca; /* is a CA certificate */
int max_pathlen; /* maximum CA path length */ int max_pathlen; /* maximum CA path length */
int authority_identifier; /* add authority identifier to CRT */
int subject_identifier; /* add subject identifier to CRT */
int basic_constraints; /* add basic constraints ext to CRT */
int version; /* CRT version */
mbedtls_md_type_t md; /* Hash used for signing */
unsigned char key_usage; /* key usage flags */ unsigned char key_usage; /* key usage flags */
unsigned char ns_cert_type; /* NS cert type */ unsigned char ns_cert_type; /* NS cert type */
} opt; } opt;
@ -163,7 +189,8 @@ int write_certificate( mbedtls_x509write_cert *crt, const char *output_file,
size_t len = 0; size_t len = 0;
memset( output_buf, 0, 4096 ); memset( output_buf, 0, 4096 );
if( ( ret = mbedtls_x509write_crt_pem( crt, output_buf, 4096, f_rng, p_rng ) ) < 0 ) if( ( ret = mbedtls_x509write_crt_pem( crt, output_buf, 4096,
f_rng, p_rng ) ) < 0 )
return( ret ); return( ret );
len = strlen( (char *) output_buf ); len = strlen( (char *) output_buf );
@ -207,7 +234,6 @@ int main( int argc, char *argv[] )
* Set to sane values * Set to sane values
*/ */
mbedtls_x509write_crt_init( &crt ); mbedtls_x509write_crt_init( &crt );
mbedtls_x509write_crt_set_md_alg( &crt, MBEDTLS_MD_SHA256 );
mbedtls_pk_init( &loaded_issuer_key ); mbedtls_pk_init( &loaded_issuer_key );
mbedtls_pk_init( &loaded_subject_key ); mbedtls_pk_init( &loaded_subject_key );
mbedtls_mpi_init( &serial ); mbedtls_mpi_init( &serial );
@ -243,6 +269,11 @@ int main( int argc, char *argv[] )
opt.max_pathlen = DFL_MAX_PATHLEN; opt.max_pathlen = DFL_MAX_PATHLEN;
opt.key_usage = DFL_KEY_USAGE; opt.key_usage = DFL_KEY_USAGE;
opt.ns_cert_type = DFL_NS_CERT_TYPE; opt.ns_cert_type = DFL_NS_CERT_TYPE;
opt.version = DFL_VERSION - 1;
opt.md = DFL_DIGEST;
opt.subject_identifier = DFL_SUBJ_IDENT;
opt.authority_identifier = DFL_AUTH_IDENT;
opt.basic_constraints = DFL_CONSTRAINTS;
for( i = 1; i < argc; i++ ) for( i = 1; i < argc; i++ )
{ {
@ -286,23 +317,88 @@ int main( int argc, char *argv[] )
{ {
opt.serial = q; opt.serial = q;
} }
else if( strcmp( p, "authority_identifier" ) == 0 )
{
opt.authority_identifier = atoi( q );
if( opt.authority_identifier != 0 &&
opt.authority_identifier != 1 )
{
mbedtls_printf( "Invalid argument for option %s\n", p );
goto usage;
}
}
else if( strcmp( p, "subject_identifier" ) == 0 )
{
opt.subject_identifier = atoi( q );
if( opt.subject_identifier != 0 &&
opt.subject_identifier != 1 )
{
mbedtls_printf( "Invalid argument for option %s\n", p );
goto usage;
}
}
else if( strcmp( p, "basic_constraints" ) == 0 )
{
opt.basic_constraints = atoi( q );
if( opt.basic_constraints != 0 &&
opt.basic_constraints != 1 )
{
mbedtls_printf( "Invalid argument for option %s\n", p );
goto usage;
}
}
else if( strcmp( p, "md" ) == 0 )
{
if( strcmp( q, "SHA1" ) == 0 )
opt.md = MBEDTLS_MD_SHA1;
else if( strcmp( q, "SHA256" ) == 0 )
opt.md = MBEDTLS_MD_SHA256;
else if( strcmp( q, "SHA512" ) == 0 )
opt.md = MBEDTLS_MD_SHA512;
else if( strcmp( q, "MD5" ) == 0 )
opt.md = MBEDTLS_MD_MD5;
else
{
mbedtls_printf( "Invalid argument for option %s\n", p );
goto usage;
}
}
else if( strcmp( p, "version" ) == 0 )
{
opt.version = atoi( q );
if( opt.version < 1 || opt.version > 3 )
{
mbedtls_printf( "Invalid argument for option %s\n", p );
goto usage;
}
opt.version--;
}
else if( strcmp( p, "selfsign" ) == 0 ) else if( strcmp( p, "selfsign" ) == 0 )
{ {
opt.selfsign = atoi( q ); opt.selfsign = atoi( q );
if( opt.selfsign < 0 || opt.selfsign > 1 ) if( opt.selfsign < 0 || opt.selfsign > 1 )
{
mbedtls_printf( "Invalid argument for option %s\n", p );
goto usage; goto usage;
}
} }
else if( strcmp( p, "is_ca" ) == 0 ) else if( strcmp( p, "is_ca" ) == 0 )
{ {
opt.is_ca = atoi( q ); opt.is_ca = atoi( q );
if( opt.is_ca < 0 || opt.is_ca > 1 ) if( opt.is_ca < 0 || opt.is_ca > 1 )
{
mbedtls_printf( "Invalid argument for option %s\n", p );
goto usage; goto usage;
}
} }
else if( strcmp( p, "max_pathlen" ) == 0 ) else if( strcmp( p, "max_pathlen" ) == 0 )
{ {
opt.max_pathlen = atoi( q ); opt.max_pathlen = atoi( q );
if( opt.max_pathlen < -1 || opt.max_pathlen > 127 ) if( opt.max_pathlen < -1 || opt.max_pathlen > 127 )
{
mbedtls_printf( "Invalid argument for option %s\n", p );
goto usage; goto usage;
}
} }
else if( strcmp( p, "key_usage" ) == 0 ) else if( strcmp( p, "key_usage" ) == 0 )
{ {
@ -326,7 +422,10 @@ int main( int argc, char *argv[] )
else if( strcmp( q, "crl_sign" ) == 0 ) else if( strcmp( q, "crl_sign" ) == 0 )
opt.key_usage |= MBEDTLS_X509_KU_CRL_SIGN; opt.key_usage |= MBEDTLS_X509_KU_CRL_SIGN;
else else
{
mbedtls_printf( "Invalid argument for option %s\n", p );
goto usage; goto usage;
}
q = r; q = r;
} }
@ -353,7 +452,10 @@ int main( int argc, char *argv[] )
else if( strcmp( q, "object_signing_ca" ) == 0 ) else if( strcmp( q, "object_signing_ca" ) == 0 )
opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA; opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA;
else else
{
mbedtls_printf( "Invalid argument for option %s\n", p );
goto usage; goto usage;
}
q = r; q = r;
} }
@ -376,7 +478,8 @@ int main( int argc, char *argv[] )
strlen( pers ) ) ) != 0 ) strlen( pers ) ) ) != 0 )
{ {
mbedtls_strerror( ret, buf, 1024 ); mbedtls_strerror( ret, buf, 1024 );
mbedtls_printf( " failed\n ! mbedtls_ctr_drbg_seed returned %d - %s\n", ret, buf ); mbedtls_printf( " failed\n ! mbedtls_ctr_drbg_seed returned %d - %s\n",
ret, buf );
goto exit; goto exit;
} }
@ -390,7 +493,8 @@ int main( int argc, char *argv[] )
if( ( ret = mbedtls_mpi_read_string( &serial, 10, opt.serial ) ) != 0 ) if( ( ret = mbedtls_mpi_read_string( &serial, 10, opt.serial ) ) != 0 )
{ {
mbedtls_strerror( ret, buf, 1024 ); mbedtls_strerror( ret, buf, 1024 );
mbedtls_printf( " failed\n ! mbedtls_mpi_read_string returned -0x%02x - %s\n\n", -ret, buf ); mbedtls_printf( " failed\n ! mbedtls_mpi_read_string "
"returned -0x%04x - %s\n\n", -ret, buf );
goto exit; goto exit;
} }
@ -409,7 +513,8 @@ int main( int argc, char *argv[] )
if( ( ret = mbedtls_x509_crt_parse_file( &issuer_crt, opt.issuer_crt ) ) != 0 ) if( ( ret = mbedtls_x509_crt_parse_file( &issuer_crt, opt.issuer_crt ) ) != 0 )
{ {
mbedtls_strerror( ret, buf, 1024 ); mbedtls_strerror( ret, buf, 1024 );
mbedtls_printf( " failed\n ! mbedtls_x509_crt_parse_file returned -0x%02x - %s\n\n", -ret, buf ); mbedtls_printf( " failed\n ! mbedtls_x509_crt_parse_file "
"returned -0x%04x - %s\n\n", -ret, buf );
goto exit; goto exit;
} }
@ -418,7 +523,8 @@ int main( int argc, char *argv[] )
if( ret < 0 ) if( ret < 0 )
{ {
mbedtls_strerror( ret, buf, 1024 ); mbedtls_strerror( ret, buf, 1024 );
mbedtls_printf( " failed\n ! mbedtls_x509_dn_gets returned -0x%02x - %s\n\n", -ret, buf ); mbedtls_printf( " failed\n ! mbedtls_x509_dn_gets "
"returned -0x%04x - %s\n\n", -ret, buf );
goto exit; goto exit;
} }
@ -441,7 +547,8 @@ int main( int argc, char *argv[] )
if( ( ret = mbedtls_x509_csr_parse_file( &csr, opt.request_file ) ) != 0 ) if( ( ret = mbedtls_x509_csr_parse_file( &csr, opt.request_file ) ) != 0 )
{ {
mbedtls_strerror( ret, buf, 1024 ); mbedtls_strerror( ret, buf, 1024 );
mbedtls_printf( " failed\n ! mbedtls_x509_csr_parse_file returned -0x%02x - %s\n\n", -ret, buf ); mbedtls_printf( " failed\n ! mbedtls_x509_csr_parse_file "
"returned -0x%04x - %s\n\n", -ret, buf );
goto exit; goto exit;
} }
@ -450,7 +557,8 @@ int main( int argc, char *argv[] )
if( ret < 0 ) if( ret < 0 )
{ {
mbedtls_strerror( ret, buf, 1024 ); mbedtls_strerror( ret, buf, 1024 );
mbedtls_printf( " failed\n ! mbedtls_x509_dn_gets returned -0x%02x - %s\n\n", -ret, buf ); mbedtls_printf( " failed\n ! mbedtls_x509_dn_gets "
"returned -0x%04x - %s\n\n", -ret, buf );
goto exit; goto exit;
} }
@ -474,7 +582,8 @@ int main( int argc, char *argv[] )
if( ret != 0 ) if( ret != 0 )
{ {
mbedtls_strerror( ret, buf, 1024 ); mbedtls_strerror( ret, buf, 1024 );
mbedtls_printf( " failed\n ! mbedtls_pk_parse_keyfile returned -0x%02x - %s\n\n", -ret, buf ); mbedtls_printf( " failed\n ! mbedtls_pk_parse_keyfile "
"returned -0x%04x - %s\n\n", -ret, buf );
goto exit; goto exit;
} }
@ -489,7 +598,8 @@ int main( int argc, char *argv[] )
if( ret != 0 ) if( ret != 0 )
{ {
mbedtls_strerror( ret, buf, 1024 ); mbedtls_strerror( ret, buf, 1024 );
mbedtls_printf( " failed\n ! mbedtls_pk_parse_keyfile returned -x%02x - %s\n\n", -ret, buf ); mbedtls_printf( " failed\n ! mbedtls_pk_parse_keyfile "
"returned -x%02x - %s\n\n", -ret, buf );
goto exit; goto exit;
} }
@ -503,7 +613,8 @@ int main( int argc, char *argv[] )
mbedtls_mpi_cmp_mpi( &mbedtls_pk_rsa( issuer_crt.pk )->E, mbedtls_mpi_cmp_mpi( &mbedtls_pk_rsa( issuer_crt.pk )->E,
&mbedtls_pk_rsa( *issuer_key )->E ) != 0 ) &mbedtls_pk_rsa( *issuer_key )->E ) != 0 )
{ {
mbedtls_printf( " failed\n ! issuer_key does not match issuer certificate\n\n" ); mbedtls_printf( " failed\n ! issuer_key does not match "
"issuer certificate\n\n" );
ret = -1; ret = -1;
goto exit; goto exit;
} }
@ -526,25 +637,31 @@ int main( int argc, char *argv[] )
if( ( ret = mbedtls_x509write_crt_set_subject_name( &crt, opt.subject_name ) ) != 0 ) if( ( ret = mbedtls_x509write_crt_set_subject_name( &crt, opt.subject_name ) ) != 0 )
{ {
mbedtls_strerror( ret, buf, 1024 ); mbedtls_strerror( ret, buf, 1024 );
mbedtls_printf( " failed\n ! mbedtls_x509write_crt_set_subject_name returned -0x%02x - %s\n\n", -ret, buf ); mbedtls_printf( " failed\n ! mbedtls_x509write_crt_set_subject_name "
"returned -0x%04x - %s\n\n", -ret, buf );
goto exit; goto exit;
} }
if( ( ret = mbedtls_x509write_crt_set_issuer_name( &crt, opt.issuer_name ) ) != 0 ) if( ( ret = mbedtls_x509write_crt_set_issuer_name( &crt, opt.issuer_name ) ) != 0 )
{ {
mbedtls_strerror( ret, buf, 1024 ); mbedtls_strerror( ret, buf, 1024 );
mbedtls_printf( " failed\n ! mbedtls_x509write_crt_set_issuer_name returned -0x%02x - %s\n\n", -ret, buf ); mbedtls_printf( " failed\n ! mbedtls_x509write_crt_set_issuer_name "
"returned -0x%04x - %s\n\n", -ret, buf );
goto exit; goto exit;
} }
mbedtls_printf( " . Setting certificate values ..." ); mbedtls_printf( " . Setting certificate values ..." );
fflush( stdout ); fflush( stdout );
mbedtls_x509write_crt_set_version( &crt, opt.version );
mbedtls_x509write_crt_set_md_alg( &crt, opt.md );
ret = mbedtls_x509write_crt_set_serial( &crt, &serial ); ret = mbedtls_x509write_crt_set_serial( &crt, &serial );
if( ret != 0 ) if( ret != 0 )
{ {
mbedtls_strerror( ret, buf, 1024 ); mbedtls_strerror( ret, buf, 1024 );
mbedtls_printf( " failed\n ! mbedtls_x509write_crt_set_serial returned -0x%02x - %s\n\n", -ret, buf ); mbedtls_printf( " failed\n ! mbedtls_x509write_crt_set_serial "
"returned -0x%04x - %s\n\n", -ret, buf );
goto exit; goto exit;
} }
@ -552,55 +669,74 @@ int main( int argc, char *argv[] )
if( ret != 0 ) if( ret != 0 )
{ {
mbedtls_strerror( ret, buf, 1024 ); mbedtls_strerror( ret, buf, 1024 );
mbedtls_printf( " failed\n ! mbedtls_x509write_crt_set_validity returned -0x%02x - %s\n\n", -ret, buf ); mbedtls_printf( " failed\n ! mbedtls_x509write_crt_set_validity "
"returned -0x%04x - %s\n\n", -ret, buf );
goto exit; goto exit;
} }
mbedtls_printf( " ok\n" ); mbedtls_printf( " ok\n" );
mbedtls_printf( " . Adding the Basic Constraints extension ..." ); if( opt.version == MBEDTLS_X509_CRT_VERSION_3 &&
fflush( stdout ); opt.basic_constraints != 0 )
ret = mbedtls_x509write_crt_set_basic_constraints( &crt, opt.is_ca,
opt.max_pathlen );
if( ret != 0 )
{ {
mbedtls_strerror( ret, buf, 1024 ); mbedtls_printf( " . Adding the Basic Constraints extension ..." );
mbedtls_printf( " failed\n ! x509write_crt_set_basic_contraints returned -0x%02x - %s\n\n", -ret, buf ); fflush( stdout );
goto exit;
}
mbedtls_printf( " ok\n" ); ret = mbedtls_x509write_crt_set_basic_constraints( &crt, opt.is_ca,
opt.max_pathlen );
if( ret != 0 )
{
mbedtls_strerror( ret, buf, 1024 );
mbedtls_printf( " failed\n ! x509write_crt_set_basic_contraints "
"returned -0x%04x - %s\n\n", -ret, buf );
goto exit;
}
mbedtls_printf( " ok\n" );
}
#if defined(MBEDTLS_SHA1_C) #if defined(MBEDTLS_SHA1_C)
mbedtls_printf( " . Adding the Subject Key Identifier ..." ); if( opt.version == MBEDTLS_X509_CRT_VERSION_3 &&
fflush( stdout ); opt.subject_identifier != 0 )
ret = mbedtls_x509write_crt_set_subject_key_identifier( &crt );
if( ret != 0 )
{ {
mbedtls_strerror( ret, buf, 1024 ); mbedtls_printf( " . Adding the Subject Key Identifier ..." );
mbedtls_printf( " failed\n ! mbedtls_x509write_crt_set_subject_key_identifier returned -0x%02x - %s\n\n", -ret, buf ); fflush( stdout );
goto exit;
ret = mbedtls_x509write_crt_set_subject_key_identifier( &crt );
if( ret != 0 )
{
mbedtls_strerror( ret, buf, 1024 );
mbedtls_printf( " failed\n ! mbedtls_x509write_crt_set_subject"
"_key_identifier returned -0x%04x - %s\n\n",
-ret, buf );
goto exit;
}
mbedtls_printf( " ok\n" );
} }
mbedtls_printf( " ok\n" ); if( opt.version == MBEDTLS_X509_CRT_VERSION_3 &&
opt.authority_identifier != 0 )
mbedtls_printf( " . Adding the Authority Key Identifier ..." );
fflush( stdout );
ret = mbedtls_x509write_crt_set_authority_key_identifier( &crt );
if( ret != 0 )
{ {
mbedtls_strerror( ret, buf, 1024 ); mbedtls_printf( " . Adding the Authority Key Identifier ..." );
mbedtls_printf( " failed\n ! mbedtls_x509write_crt_set_authority_key_identifier returned -0x%02x - %s\n\n", -ret, buf ); fflush( stdout );
goto exit;
}
mbedtls_printf( " ok\n" ); ret = mbedtls_x509write_crt_set_authority_key_identifier( &crt );
if( ret != 0 )
{
mbedtls_strerror( ret, buf, 1024 );
mbedtls_printf( " failed\n ! mbedtls_x509write_crt_set_authority_"
"key_identifier returned -0x%04x - %s\n\n",
-ret, buf );
goto exit;
}
mbedtls_printf( " ok\n" );
}
#endif /* MBEDTLS_SHA1_C */ #endif /* MBEDTLS_SHA1_C */
if( opt.key_usage ) if( opt.version == MBEDTLS_X509_CRT_VERSION_3 &&
opt.key_usage != 0 )
{ {
mbedtls_printf( " . Adding the Key Usage extension ..." ); mbedtls_printf( " . Adding the Key Usage extension ..." );
fflush( stdout ); fflush( stdout );
@ -609,14 +745,16 @@ int main( int argc, char *argv[] )
if( ret != 0 ) if( ret != 0 )
{ {
mbedtls_strerror( ret, buf, 1024 ); mbedtls_strerror( ret, buf, 1024 );
mbedtls_printf( " failed\n ! mbedtls_x509write_crt_set_key_usage returned -0x%02x - %s\n\n", -ret, buf ); mbedtls_printf( " failed\n ! mbedtls_x509write_crt_set_key_usage "
"returned -0x%04x - %s\n\n", -ret, buf );
goto exit; goto exit;
} }
mbedtls_printf( " ok\n" ); mbedtls_printf( " ok\n" );
} }
if( opt.ns_cert_type ) if( opt.version == MBEDTLS_X509_CRT_VERSION_3 &&
opt.ns_cert_type != 0 )
{ {
mbedtls_printf( " . Adding the NS Cert Type extension ..." ); mbedtls_printf( " . Adding the NS Cert Type extension ..." );
fflush( stdout ); fflush( stdout );
@ -625,7 +763,8 @@ int main( int argc, char *argv[] )
if( ret != 0 ) if( ret != 0 )
{ {
mbedtls_strerror( ret, buf, 1024 ); mbedtls_strerror( ret, buf, 1024 );
mbedtls_printf( " failed\n ! mbedtls_x509write_crt_set_ns_cert_type returned -0x%02x - %s\n\n", -ret, buf ); mbedtls_printf( " failed\n ! mbedtls_x509write_crt_set_ns_cert_type "
"returned -0x%04x - %s\n\n", -ret, buf );
goto exit; goto exit;
} }
@ -642,7 +781,8 @@ int main( int argc, char *argv[] )
mbedtls_ctr_drbg_random, &ctr_drbg ) ) != 0 ) mbedtls_ctr_drbg_random, &ctr_drbg ) ) != 0 )
{ {
mbedtls_strerror( ret, buf, 1024 ); mbedtls_strerror( ret, buf, 1024 );
mbedtls_printf( " failed\n ! write_certifcate -0x%02x - %s\n\n", -ret, buf ); mbedtls_printf( " failed\n ! write_certificate -0x%04x - %s\n\n",
-ret, buf );
goto exit; goto exit;
} }

View file

@ -45,7 +45,7 @@ my $config_file = "include/mbedtls/config.h";
my $usage = <<EOU; my $usage = <<EOU;
$0 [-f <file> | --file <file>] [-o | --force] $0 [-f <file> | --file <file>] [-o | --force]
[set <symbol> <value> | unset <symbol> | get <symbol> | [set <symbol> <value> | unset <symbol> | get <symbol> |
full | realfull] full | realfull | baremetal]
Commands Commands
set <symbol> [<value>] - Uncomments or adds a #define for the <symbol> to set <symbol> [<value>] - Uncomments or adds a #define for the <symbol> to
@ -56,13 +56,14 @@ Commands
unset <symbol> - Comments out the #define for the given symbol if unset <symbol> - Comments out the #define for the given symbol if
present in the configuration file. present in the configuration file.
get <symbol> - Finds the #define for the given symbol, returning get <symbol> - Finds the #define for the given symbol, returning
an exitcode of 0 if the symbol is found, and -1 if an exitcode of 0 if the symbol is found, and 1 if
not. The value of the symbol is output if one is not. The value of the symbol is output if one is
specified in the configuration file. specified in the configuration file.
full - Uncomments all #define's in the configuration file full - Uncomments all #define's in the configuration file
excluding some reserved symbols, until the excluding some reserved symbols, until the
'Module configuration options' section 'Module configuration options' section
realfull - Uncomments all #define's with no exclusions realfull - Uncomments all #define's with no exclusions
baremetal - Sets full configuration suitable for baremetal build.
Options Options
-f | --file <filename> - The file or file path for the configuration file -f | --file <filename> - The file or file path for the configuration file
@ -91,14 +92,38 @@ MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3
MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION
MBEDTLS_ZLIB_SUPPORT MBEDTLS_ZLIB_SUPPORT
MBEDTLS_PKCS11_C MBEDTLS_PKCS11_C
MBEDTLS_NO_UDBL_DIVISION
_ALT\s*$ _ALT\s*$
); );
# Things that should be disabled in "baremetal"
my @excluded_baremetal = qw(
MBEDTLS_NET_C
MBEDTLS_TIMING_C
MBEDTLS_FS_IO
MBEDTLS_ENTROPY_NV_SEED
MBEDTLS_HAVE_TIME
MBEDTLS_HAVE_TIME_DATE
MBEDTLS_DEPRECATED_WARNING
MBEDTLS_HAVEGE_C
MBEDTLS_THREADING_C
MBEDTLS_THREADING_PTHREAD
MBEDTLS_MEMORY_BACKTRACE
MBEDTLS_MEMORY_BUFFER_ALLOC_C
MBEDTLS_PLATFORM_TIME_ALT
MBEDTLS_PLATFORM_FPRINTF_ALT
);
# Things that should be enabled in "full" even if they match @excluded # Things that should be enabled in "full" even if they match @excluded
my @non_excluded = qw( my @non_excluded = qw(
PLATFORM_[A-Z0-9]+_ALT PLATFORM_[A-Z0-9]+_ALT
); );
# Things that should be enabled in "baremetal"
my @non_excluded_baremetal = qw(
MBEDTLS_NO_PLATFORM_ENTROPY
);
# Process the command line arguments # Process the command line arguments
my $force_option = 0; my $force_option = 0;
@ -123,7 +148,7 @@ while ($arg = shift) {
# ...else assume it's a command # ...else assume it's a command
$action = $arg; $action = $arg;
if ($action eq "full" || $action eq "realfull") { if ($action eq "full" || $action eq "realfull" || $action eq "baremetal" ) {
# No additional parameters # No additional parameters
die $usage if @ARGV; die $usage if @ARGV;
@ -166,7 +191,12 @@ open my $config_read, '<', $config_file or die "read $config_file: $!\n";
my @config_lines = <$config_read>; my @config_lines = <$config_read>;
close $config_read; close $config_read;
my ($exclude_re, $no_exclude_re); # Add required baremetal symbols to the list that is included.
if ( $action eq "baremetal" ) {
@non_excluded = ( @non_excluded, @non_excluded_baremetal );
}
my ($exclude_re, $no_exclude_re, $exclude_baremetal_re);
if ($action eq "realfull") { if ($action eq "realfull") {
$exclude_re = qr/^$/; $exclude_re = qr/^$/;
$no_exclude_re = qr/./; $no_exclude_re = qr/./;
@ -174,22 +204,30 @@ if ($action eq "realfull") {
$exclude_re = join '|', @excluded; $exclude_re = join '|', @excluded;
$no_exclude_re = join '|', @non_excluded; $no_exclude_re = join '|', @non_excluded;
} }
if ( $action eq "baremetal" ) {
$exclude_baremetal_re = join '|', @excluded_baremetal;
}
open my $config_write, '>', $config_file or die "write $config_file: $!\n"; my $config_write = undef;
if ($action ne "get") {
open $config_write, '>', $config_file or die "write $config_file: $!\n";
}
my $done; my $done;
for my $line (@config_lines) { for my $line (@config_lines) {
if ($action eq "full" || $action eq "realfull") { if ($action eq "full" || $action eq "realfull" || $action eq "baremetal" ) {
if ($line =~ /name SECTION: Module configuration options/) { if ($line =~ /name SECTION: Module configuration options/) {
$done = 1; $done = 1;
} }
if (!$done && $line =~ m!^//\s?#define! && if (!$done && $line =~ m!^//\s?#define! &&
( $line !~ /$exclude_re/ || $line =~ /$no_exclude_re/ ) ) { ( $line !~ /$exclude_re/ || $line =~ /$no_exclude_re/ ) &&
( $action ne "baremetal" || ( $line !~ /$exclude_baremetal_re/ ) ) ) {
$line =~ s!^//\s?!!; $line =~ s!^//\s?!!;
} }
if (!$done && $line =~ m!^\s?#define! && if (!$done && $line =~ m!^\s?#define! &&
! ( $line !~ /$exclude_re/ || $line =~ /$no_exclude_re/ ) ) { ! ( ( $line !~ /$exclude_re/ || $line =~ /$no_exclude_re/ ) &&
( $action ne "baremetal" || ( $line !~ /$exclude_baremetal_re/ ) ) ) ) {
$line =~ s!^!//!; $line =~ s!^!//!;
} }
} elsif ($action eq "unset") { } elsif ($action eq "unset") {
@ -205,17 +243,19 @@ for my $line (@config_lines) {
$done = 1; $done = 1;
} }
} elsif (!$done && $action eq "get") { } elsif (!$done && $action eq "get") {
if ($line =~ /^\s*#define\s*$name\s*(.*)\s*\b/) { if ($line =~ /^\s*#define\s*$name(?:\s+(.*?))\s*(?:$|\/\*|\/\/)/) {
$value = $1; $value = $1;
$done = 1; $done = 1;
} }
} }
print $config_write $line; if (defined $config_write) {
print $config_write $line or die "write $config_file: $!\n";
}
} }
# Did the set command work? # Did the set command work?
if ($action eq "set"&& $force_option && !$done) { if ($action eq "set" && $force_option && !$done) {
# If the force option was set, append the symbol to the end of the file # If the force option was set, append the symbol to the end of the file
my $line = "#define $name"; my $line = "#define $name";
@ -223,20 +263,22 @@ if ($action eq "set"&& $force_option && !$done) {
$line .= "\n"; $line .= "\n";
$done = 1; $done = 1;
print $config_write $line; print $config_write $line or die "write $config_file: $!\n";
} }
close $config_write; if (defined $config_write) {
close $config_write or die "close $config_file: $!\n";
}
if ($action eq "get") { if ($action eq "get") {
if($done) { if ($done) {
if ($value ne '') { if ($value ne '') {
print $value; print "$value\n";
} }
exit 0; exit 0;
} else { } else {
# If the symbol was not found, return an error # If the symbol was not found, return an error
exit -1; exit 1;
} }
} }

View file

@ -2,8 +2,8 @@
expression x, y; expression x, y;
statement S; statement S;
@@ @@
x = mbedtls_malloc(...); x = mbedtls_calloc(...);
y = mbedtls_malloc(...); y = mbedtls_calloc(...);
... ...
* if (x == NULL || y == NULL) * if (x == NULL || y == NULL)
S S
@ -13,8 +13,8 @@ expression x, y;
statement S; statement S;
@@ @@
if ( if (
* (x = mbedtls_malloc(...)) == NULL * (x = mbedtls_calloc(...)) == NULL
|| ||
* (y = mbedtls_malloc(...)) == NULL * (y = mbedtls_calloc(...)) == NULL
) )
S S

View file

@ -1,70 +0,0 @@
#!/usr/bin/perl
# Check for malloc calls not shortly followed by initialisation.
#
# Known limitations:
# - false negative: can't see allocations spanning more than one line
# - possible false negatives, see patterns
# - false positive: malloc-malloc-init-init is not accepted
# - false positives: "non-standard" init functions (eg, the things being
# initialised is not the first arg, or initialise struct members)
#
# Since false positives are expected, the results must be manually reviewed.
#
# Typical usage: scripts/malloc-init.pl library/*.c
use warnings;
use strict;
use utf8;
use open qw(:std utf8);
my $limit = 7;
my $inits = qr/memset|memcpy|_init|fread|base64_..code/;
# cases to bear in mind:
#
# 0. foo = malloc(...); memset( foo, ... );
# 1. *foo = malloc(...); memset( *foo, ... );
# 2. type *foo = malloc(...); memset( foo, ...);
# 3. foo = malloc(...); foo_init( (type *) foo );
# 4. foo = malloc(...); for(i=0..n) { init( &foo[i] ); }
#
# The chosen patterns are a bit relaxed, but unlikely to cause false positives
# in real code (initialising *foo or &foo instead of foo will likely be caught
# by functional tests).
#
my $id = qr/([a-zA-Z-0-9_\->\.]*)/;
my $prefix = qr/\s(?:\*?|\&?|\([a-z_]* \*\))\s*/;
my $name;
my $line;
my @bad;
die "Usage: $0 file.c [...]\n" unless @ARGV;
while (my $file = shift @ARGV)
{
open my $fh, "<", $file or die "read $file failed: $!\n";
while (<$fh>)
{
if( /mbedtls_malloc\(/ ) {
if( /$id\s*=.*mbedtls_malloc\(/ ) {
push @bad, "$file:$line:$name" if $name;
$name = $1;
$line = $.;
} else {
push @bad, "$file:$.:???" unless /return mbedtls_malloc/;
}
} elsif( $name && /(?:$inits)\($prefix\Q$name\E\b/ ) {
undef $name;
} elsif( $name && $. - $line > $limit ) {
push @bad, "$file:$line:$name";
undef $name;
undef $line;
}
}
close $fh or die;
}
print "$_\n" for @bad;

View file

@ -0,0 +1,7 @@
@rm_calloc_cast@
expression x, n, m;
type T;
@@
x =
- (T *)
mbedtls_calloc(n, m)

View file

@ -1,7 +0,0 @@
@rm_malloc_cast@
expression x, n;
type T;
@@
x =
- (T *)
mbedtls_malloc(n)

View file

@ -866,6 +866,33 @@ has_mem_err() {
fi fi
} }
# Wait for process $2 to be listening on port $1
if type lsof >/dev/null 2>/dev/null; then
wait_server_start() {
START_TIME=$(date +%s)
if is_dtls "$MODE"; then
proto=UDP
else
proto=TCP
fi
while ! lsof -a -n -b -i "$proto:$1" -p "$2" >/dev/null 2>/dev/null; do
if [ $(( $(date +%s) - $START_TIME )) -gt $DOG_DELAY ]; then
echo "SERVERSTART TIMEOUT"
echo "SERVERSTART TIMEOUT" >> $SRV_OUT
break
fi
# Linux and *BSD support decimal arguments to sleep. On other
# OSes this may be a tight loop.
sleep 0.1 2>/dev/null || true
done
}
else
wait_server_start() {
sleep 1
}
fi
# start_server <name> # start_server <name>
# also saves name and command # also saves name and command
start_server() { start_server() {
@ -895,7 +922,7 @@ start_server() {
while :; do echo bla; sleep 1; done | $SERVER_CMD >> $SRV_OUT 2>&1 & while :; do echo bla; sleep 1; done | $SERVER_CMD >> $SRV_OUT 2>&1 &
PROCESS_ID=$! PROCESS_ID=$!
sleep 1 wait_server_start "$PORT" "$PROCESS_ID"
} }
# terminate the running server # terminate the running server

View file

@ -12,6 +12,7 @@
## Tools ## Tools
OPENSSL ?= openssl OPENSSL ?= openssl
MBEDTLS_CERT_WRITE ?= $(PWD)/../../programs/x509/cert_write
## Build the generated test data. Note that since the final outputs ## Build the generated test data. Note that since the final outputs
## are committed to the repository, this target should do nothing on a ## are committed to the repository, this target should do nothing on a
@ -30,6 +31,7 @@ all_final := # files used by tests
#### Generate certificates from existing keys #### Generate certificates from existing keys
################################################################ ################################################################
test_ca_crt = test-ca.crt
test_ca_key_file_rsa = test-ca.key test_ca_key_file_rsa = test-ca.key
test_ca_pwd_rsa = PolarSSLTest test_ca_pwd_rsa = PolarSSLTest
test_ca_config_file = test-ca.opensslconf test_ca_config_file = test-ca.opensslconf
@ -66,6 +68,330 @@ all_final += server2-sha256.crt
################################################################
#### Generate various RSA keys
################################################################
### Password used for PKCS1-encoded encrypted RSA keys
keys_rsa_basic_pwd = testkey
### Password used for PKCS8-encoded encrypted RSA keys
keys_rsa_pkcs8_pwd = PolarSSLTest
### Basic 1024-, 2048- and 4096-bit unencrypted RSA keys from which
### all other encrypted RSA keys are derived.
rsa_pkcs1_1024_clear.pem:
$(OPENSSL) genrsa -out $@ 1024
all_final += rsa_pkcs1_1024_clear.pem
rsa_pkcs1_2048_clear.pem:
$(OPENSSL) genrsa -out $@ 2048
all_final += rsa_pkcs1_2048_clear.pem
rsa_pkcs1_4096_clear.pem:
$(OPENSSL) genrsa -out $@ 4096
all_final += rsa_pkcs1_4096_clear.pem
###
### PKCS1-encoded, encrypted RSA keys
###
### 1024-bit
rsa_pkcs1_1024_des.pem: rsa_pkcs1_1024_clear.pem
$(OPENSSL) rsa -des -in $< -out $@ -passout "pass:$(keys_rsa_basic_pwd)"
all_final += rsa_pkcs1_1024_des.pem
rsa_pkcs1_1024_3des.pem: rsa_pkcs1_1024_clear.pem
$(OPENSSL) rsa -des3 -in $< -out $@ -passout "pass:$(keys_rsa_basic_pwd)"
all_final += rsa_pkcs1_1024_3des.pem
rsa_pkcs1_1024_aes128.pem: rsa_pkcs1_1024_clear.pem
$(OPENSSL) rsa -aes128 -in $< -out $@ -passout "pass:$(keys_rsa_basic_pwd)"
all_final += rsa_pkcs1_1024_aes128.pem
rsa_pkcs1_1024_aes192.pem: rsa_pkcs1_1024_clear.pem
$(OPENSSL) rsa -aes192 -in $< -out $@ -passout "pass:$(keys_rsa_basic_pwd)"
all_final += rsa_pkcs1_1024_aes192.pem
rsa_pkcs1_1024_aes256.pem: rsa_pkcs1_1024_clear.pem
$(OPENSSL) rsa -aes256 -in $< -out $@ -passout "pass:$(keys_rsa_basic_pwd)"
all_final += rsa_pkcs1_1024_aes256.pem
keys_rsa_enc_basic_1024: rsa_pkcs1_1024_des.pem rsa_pkcs1_1024_3des.pem rsa_pkcs1_1024_aes128.pem rsa_pkcs1_1024_aes192.pem rsa_pkcs1_1024_aes256.pem
# 2048-bit
rsa_pkcs1_2048_des.pem: rsa_pkcs1_2048_clear.pem
$(OPENSSL) rsa -des -in $< -out $@ -passout "pass:$(keys_rsa_basic_pwd)"
all_final += rsa_pkcs1_2048_des.pem
rsa_pkcs1_2048_3des.pem: rsa_pkcs1_2048_clear.pem
$(OPENSSL) rsa -des3 -in $< -out $@ -passout "pass:$(keys_rsa_basic_pwd)"
all_final += rsa_pkcs1_2048_3des.pem
rsa_pkcs1_2048_aes128.pem: rsa_pkcs1_2048_clear.pem
$(OPENSSL) rsa -aes128 -in $< -out $@ -passout "pass:$(keys_rsa_basic_pwd)"
all_final += rsa_pkcs1_2048_aes128.pem
rsa_pkcs1_2048_aes192.pem: rsa_pkcs1_2048_clear.pem
$(OPENSSL) rsa -aes192 -in $< -out $@ -passout "pass:$(keys_rsa_basic_pwd)"
all_final += rsa_pkcs1_2048_aes192.pem
rsa_pkcs1_2048_aes256.pem: rsa_pkcs1_2048_clear.pem
$(OPENSSL) rsa -aes256 -in $< -out $@ -passout "pass:$(keys_rsa_basic_pwd)"
all_final += rsa_pkcs1_2048_aes256.pem
keys_rsa_enc_basic_2048: rsa_pkcs1_2048_des.pem rsa_pkcs1_2048_3des.pem rsa_pkcs1_2048_aes128.pem rsa_pkcs1_2048_aes192.pem rsa_pkcs1_2048_aes256.pem
# 4096-bit
rsa_pkcs1_4096_des.pem: rsa_pkcs1_4096_clear.pem
$(OPENSSL) rsa -des -in $< -out $@ -passout "pass:$(keys_rsa_basic_pwd)"
all_final += rsa_pkcs1_4096_des.pem
rsa_pkcs1_4096_3des.pem: rsa_pkcs1_4096_clear.pem
$(OPENSSL) rsa -des3 -in $< -out $@ -passout "pass:$(keys_rsa_basic_pwd)"
all_final += rsa_pkcs1_4096_3des.pem
rsa_pkcs1_4096_aes128.pem: rsa_pkcs1_4096_clear.pem
$(OPENSSL) rsa -aes128 -in $< -out $@ -passout "pass:$(keys_rsa_basic_pwd)"
all_final += rsa_pkcs1_4096_aes128.pem
rsa_pkcs1_4096_aes192.pem: rsa_pkcs1_4096_clear.pem
$(OPENSSL) rsa -aes192 -in $< -out $@ -passout "pass:$(keys_rsa_basic_pwd)"
all_final += rsa_pkcs1_4096_aes192.pem
rsa_pkcs1_4096_aes256.pem: rsa_pkcs1_4096_clear.pem
$(OPENSSL) rsa -aes256 -in $< -out $@ -passout "pass:$(keys_rsa_basic_pwd)"
all_final += rsa_pkcs1_4096_aes256.pem
keys_rsa_enc_basic_4096: rsa_pkcs1_4096_des.pem rsa_pkcs1_4096_3des.pem rsa_pkcs1_4096_aes128.pem rsa_pkcs1_4096_aes192.pem rsa_pkcs1_4096_aes256.pem
###
### PKCS8-v1 encoded, encrypted RSA keys
###
### 1024-bit
rsa_pkcs8_pbe_sha1_1024_3des.der: rsa_pkcs1_1024_clear.pem
$(OPENSSL) pkcs8 -inform PEM -in $< -outform DER -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)" -topk8 -v1 PBE-SHA1-3DES
all_final += rsa_pkcs8_pbe_sha1_1024_3des.der
rsa_pkcs8_pbe_sha1_1024_3des.pem: rsa_pkcs1_1024_clear.pem
$(OPENSSL) pkcs8 -inform PEM -in $< -outform PEM -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)" -topk8 -v1 PBE-SHA1-3DES
all_final += rsa_pkcs8_pbe_sha1_1024_3des.pem
keys_rsa_enc_pkcs8_v1_1024_3des: rsa_pkcs8_pbe_sha1_1024_3des.pem rsa_pkcs8_pbe_sha1_1024_3des.der
rsa_pkcs8_pbe_sha1_1024_2des.der: rsa_pkcs1_1024_clear.pem
$(OPENSSL) pkcs8 -inform PEM -in $< -outform DER -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)" -topk8 -v1 PBE-SHA1-2DES
all_final += rsa_pkcs8_pbe_sha1_1024_2des.der
rsa_pkcs8_pbe_sha1_1024_2des.pem: rsa_pkcs1_1024_clear.pem
$(OPENSSL) pkcs8 -inform PEM -in $< -outform PEM -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)" -topk8 -v1 PBE-SHA1-2DES
all_final += rsa_pkcs8_pbe_sha1_1024_2des.pem
keys_rsa_enc_pkcs8_v1_1024_2des: rsa_pkcs8_pbe_sha1_1024_2des.pem rsa_pkcs8_pbe_sha1_1024_2des.der
rsa_pkcs8_pbe_sha1_1024_rc4_128.der: rsa_pkcs1_1024_clear.pem
$(OPENSSL) pkcs8 -inform PEM -in $< -outform DER -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)" -topk8 -v1 PBE-SHA1-RC4-128
all_final += rsa_pkcs8_pbe_sha1_1024_rc4_128.der
rsa_pkcs8_pbe_sha1_1024_rc4_128.pem: rsa_pkcs1_1024_clear.pem
$(OPENSSL) pkcs8 -inform PEM -in $< -outform PEM -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)" -topk8 -v1 PBE-SHA1-RC4-128
all_final += rsa_pkcs8_pbe_sha1_1024_rc4_128.pem
keys_rsa_enc_pkcs8_v1_1024_rc4_128: rsa_pkcs8_pbe_sha1_1024_rc4_128.pem rsa_pkcs8_pbe_sha1_1024_rc4_128.der
keys_rsa_enc_pkcs8_v1_1024: keys_rsa_enc_pkcs8_v1_1024_3des keys_rsa_enc_pkcs8_v1_1024_2des keys_rsa_enc_pkcs8_v1_1024_rc4_128
### 2048-bit
rsa_pkcs8_pbe_sha1_2048_3des.der: rsa_pkcs1_2048_clear.pem
$(OPENSSL) pkcs8 -inform PEM -in $< -outform DER -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)" -topk8 -v1 PBE-SHA1-3DES
all_final += rsa_pkcs8_pbe_sha1_2048_3des.der
rsa_pkcs8_pbe_sha1_2048_3des.pem: rsa_pkcs1_2048_clear.pem
$(OPENSSL) pkcs8 -inform PEM -in $< -outform PEM -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)" -topk8 -v1 PBE-SHA1-3DES
all_final += rsa_pkcs8_pbe_sha1_2048_3des.pem
keys_rsa_enc_pkcs8_v1_2048_3des: rsa_pkcs8_pbe_sha1_2048_3des.pem rsa_pkcs8_pbe_sha1_2048_3des.der
rsa_pkcs8_pbe_sha1_2048_2des.der: rsa_pkcs1_2048_clear.pem
$(OPENSSL) pkcs8 -inform PEM -in $< -outform DER -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)" -topk8 -v1 PBE-SHA1-2DES
all_final += rsa_pkcs8_pbe_sha1_2048_2des.der
rsa_pkcs8_pbe_sha1_2048_2des.pem: rsa_pkcs1_2048_clear.pem
$(OPENSSL) pkcs8 -inform PEM -in $< -outform PEM -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)" -topk8 -v1 PBE-SHA1-2DES
all_final += rsa_pkcs8_pbe_sha1_2048_2des.pem
keys_rsa_enc_pkcs8_v1_2048_2des: rsa_pkcs8_pbe_sha1_2048_2des.pem rsa_pkcs8_pbe_sha1_2048_2des.der
rsa_pkcs8_pbe_sha1_2048_rc4_128.der: rsa_pkcs1_2048_clear.pem
$(OPENSSL) pkcs8 -inform PEM -in $< -outform DER -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)" -topk8 -v1 PBE-SHA1-RC4-128
all_final += rsa_pkcs8_pbe_sha1_2048_rc4_128.der
rsa_pkcs8_pbe_sha1_2048_rc4_128.pem: rsa_pkcs1_2048_clear.pem
$(OPENSSL) pkcs8 -inform PEM -in $< -outform PEM -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)" -topk8 -v1 PBE-SHA1-RC4-128
all_final += rsa_pkcs8_pbe_sha1_2048_rc4_128.pem
keys_rsa_enc_pkcs8_v1_2048_rc4_128: rsa_pkcs8_pbe_sha1_2048_rc4_128.pem rsa_pkcs8_pbe_sha1_2048_rc4_128.der
keys_rsa_enc_pkcs8_v1_2048: keys_rsa_enc_pkcs8_v1_2048_3des keys_rsa_enc_pkcs8_v1_2048_2des keys_rsa_enc_pkcs8_v1_2048_rc4_128
### 4096-bit
rsa_pkcs8_pbe_sha1_4096_3des.der: rsa_pkcs1_4096_clear.pem
$(OPENSSL) pkcs8 -inform PEM -in $< -outform DER -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)" -topk8 -v1 PBE-SHA1-3DES
all_final += rsa_pkcs8_pbe_sha1_4096_3des.der
rsa_pkcs8_pbe_sha1_4096_3des.pem: rsa_pkcs1_4096_clear.pem
$(OPENSSL) pkcs8 -inform PEM -in $< -outform PEM -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)" -topk8 -v1 PBE-SHA1-3DES
all_final += rsa_pkcs8_pbe_sha1_4096_3des.pem
keys_rsa_enc_pkcs8_v1_4096_3des: rsa_pkcs8_pbe_sha1_4096_3des.pem rsa_pkcs8_pbe_sha1_4096_3des.der
rsa_pkcs8_pbe_sha1_4096_2des.der: rsa_pkcs1_4096_clear.pem
$(OPENSSL) pkcs8 -inform PEM -in $< -outform DER -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)" -topk8 -v1 PBE-SHA1-2DES
all_final += rsa_pkcs8_pbe_sha1_4096_2des.der
rsa_pkcs8_pbe_sha1_4096_2des.pem: rsa_pkcs1_4096_clear.pem
$(OPENSSL) pkcs8 -inform PEM -in $< -outform PEM -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)" -topk8 -v1 PBE-SHA1-2DES
all_final += rsa_pkcs8_pbe_sha1_4096_2des.pem
keys_rsa_enc_pkcs8_v1_4096_2des: rsa_pkcs8_pbe_sha1_4096_2des.pem rsa_pkcs8_pbe_sha1_4096_2des.der
rsa_pkcs8_pbe_sha1_4096_rc4_128.der: rsa_pkcs1_4096_clear.pem
$(OPENSSL) pkcs8 -inform PEM -in $< -outform DER -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)" -topk8 -v1 PBE-SHA1-RC4-128
all_final += rsa_pkcs8_pbe_sha1_4096_rc4_128.der
rsa_pkcs8_pbe_sha1_4096_rc4_128.pem: rsa_pkcs1_4096_clear.pem
$(OPENSSL) pkcs8 -inform PEM -in $< -outform PEM -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)" -topk8 -v1 PBE-SHA1-RC4-128
all_final += rsa_pkcs8_pbe_sha1_4096_rc4_128.pem
keys_rsa_enc_pkcs8_v1_4096_rc4_128: rsa_pkcs8_pbe_sha1_4096_rc4_128.pem rsa_pkcs8_pbe_sha1_4096_rc4_128.der
keys_rsa_enc_pkcs8_v1_4096: keys_rsa_enc_pkcs8_v1_4096_3des keys_rsa_enc_pkcs8_v1_4096_2des keys_rsa_enc_pkcs8_v1_4096_rc4_128
###
### PKCS8-v2 encoded, encrypted RSA keys
###
### 1024-bit
rsa_pkcs8_pbes2_pbkdf2_1024_3des.der: rsa_pkcs1_1024_clear.pem
$(OPENSSL) pkcs8 -topk8 -v2 des3 -inform PEM -in $< -outform DER -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)"
all_final += rsa_pkcs8_pbes2_pbkdf2_1024_3des.der
rsa_pkcs8_pbes2_pbkdf2_1024_3des.pem: rsa_pkcs1_1024_clear.pem
$(OPENSSL) pkcs8 -topk8 -v2 des3 -inform PEM -in $< -outform PEM -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)"
all_final += rsa_pkcs8_pbes2_pbkdf2_1024_3des.pem
keys_rsa_enc_pkcs8_v2_1024_3des: rsa_pkcs8_pbes2_pbkdf2_1024_3des.der rsa_pkcs8_pbes2_pbkdf2_1024_3des.pem
rsa_pkcs8_pbes2_pbkdf2_1024_des.der: rsa_pkcs1_1024_clear.pem
$(OPENSSL) pkcs8 -topk8 -v2 des -inform PEM -in $< -outform DER -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)"
all_final += rsa_pkcs8_pbes2_pbkdf2_1024_des.der
rsa_pkcs8_pbes2_pbkdf2_1024_des.pem: rsa_pkcs1_1024_clear.pem
$(OPENSSL) pkcs8 -topk8 -v2 des -inform PEM -in $< -outform PEM -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)"
all_final += rsa_pkcs8_pbes2_pbkdf2_1024_des.pem
keys_rsa_enc_pkcs8_v2_1024_des: rsa_pkcs8_pbes2_pbkdf2_1024_des.der rsa_pkcs8_pbes2_pbkdf2_1024_des.pem
keys_rsa_enc_pkcs8_v2_1024: keys_rsa_enc_pkcs8_v2_1024_3des keys_rsa_enc_pkcs8_v2_1024_des
### 2048-bit
rsa_pkcs8_pbes2_pbkdf2_2048_3des.der: rsa_pkcs1_2048_clear.pem
$(OPENSSL) pkcs8 -topk8 -v2 des3 -inform PEM -in $< -outform DER -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)"
all_final += rsa_pkcs8_pbes2_pbkdf2_2048_3des.der
rsa_pkcs8_pbes2_pbkdf2_2048_3des.pem: rsa_pkcs1_2048_clear.pem
$(OPENSSL) pkcs8 -topk8 -v2 des3 -inform PEM -in $< -outform PEM -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)"
all_final += rsa_pkcs8_pbes2_pbkdf2_2048_3des.pem
keys_rsa_enc_pkcs8_v2_2048_3des: rsa_pkcs8_pbes2_pbkdf2_2048_3des.der rsa_pkcs8_pbes2_pbkdf2_2048_3des.pem
rsa_pkcs8_pbes2_pbkdf2_2048_des.der: rsa_pkcs1_2048_clear.pem
$(OPENSSL) pkcs8 -topk8 -v2 des -inform PEM -in $< -outform DER -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)"
all_final += rsa_pkcs8_pbes2_pbkdf2_2048_des.der
rsa_pkcs8_pbes2_pbkdf2_2048_des.pem: rsa_pkcs1_2048_clear.pem
$(OPENSSL) pkcs8 -topk8 -v2 des -inform PEM -in $< -outform PEM -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)"
all_final += rsa_pkcs8_pbes2_pbkdf2_2048_des.pem
keys_rsa_enc_pkcs8_v2_2048_des: rsa_pkcs8_pbes2_pbkdf2_2048_des.der rsa_pkcs8_pbes2_pbkdf2_2048_des.pem
keys_rsa_enc_pkcs8_v2_2048: keys_rsa_enc_pkcs8_v2_2048_3des keys_rsa_enc_pkcs8_v2_2048_des
### 4096-bit
rsa_pkcs8_pbes2_pbkdf2_4096_3des.der: rsa_pkcs1_4096_clear.pem
$(OPENSSL) pkcs8 -topk8 -v2 des3 -inform PEM -in $< -outform DER -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)"
all_final += rsa_pkcs8_pbes2_pbkdf2_4096_3des.der
rsa_pkcs8_pbes2_pbkdf2_4096_3des.pem: rsa_pkcs1_4096_clear.pem
$(OPENSSL) pkcs8 -topk8 -v2 des3 -inform PEM -in $< -outform PEM -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)"
all_final += rsa_pkcs8_pbes2_pbkdf2_4096_3des.pem
keys_rsa_enc_pkcs8_v2_4096_3des: rsa_pkcs8_pbes2_pbkdf2_4096_3des.der rsa_pkcs8_pbes2_pbkdf2_4096_3des.pem
rsa_pkcs8_pbes2_pbkdf2_4096_des.der: rsa_pkcs1_4096_clear.pem
$(OPENSSL) pkcs8 -topk8 -v2 des -inform PEM -in $< -outform DER -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)"
all_final += rsa_pkcs8_pbes2_pbkdf2_4096_des.der
rsa_pkcs8_pbes2_pbkdf2_4096_des.pem: rsa_pkcs1_4096_clear.pem
$(OPENSSL) pkcs8 -topk8 -v2 des -inform PEM -in $< -outform PEM -out $@ -passout "pass:$(keys_rsa_pkcs8_pwd)"
all_final += rsa_pkcs8_pbes2_pbkdf2_4096_des.pem
keys_rsa_enc_pkcs8_v2_4096_des: rsa_pkcs8_pbes2_pbkdf2_4096_des.der rsa_pkcs8_pbes2_pbkdf2_4096_des.pem
keys_rsa_enc_pkcs8_v2_4096: keys_rsa_enc_pkcs8_v2_4096_3des keys_rsa_enc_pkcs8_v2_4096_des
###
### Rules to generate all RSA keys from a particular class
###
### Generate basic unencrypted RSA keys
keys_rsa_unenc: rsa_pkcs1_1024_clear.pem rsa_pkcs1_2048_clear.pem rsa_pkcs1_4096_clear.pem
### Generate PKCS1-encoded encrypted RSA keys
keys_rsa_enc_basic: keys_rsa_enc_basic_1024 keys_rsa_enc_basic_2048 keys_rsa_enc_basic_4096
### Generate PKCS8-v1 encrypted RSA keys
keys_rsa_enc_pkcs8_v1: keys_rsa_enc_pkcs8_v1_1024 keys_rsa_enc_pkcs8_v1_2048 keys_rsa_enc_pkcs8_v1_4096
### Generate PKCS8-v2 encrypted RSA keys
keys_rsa_enc_pkcs8_v2: keys_rsa_enc_pkcs8_v2_1024 keys_rsa_enc_pkcs8_v2_2048 keys_rsa_enc_pkcs8_v2_4096
### Generate all RSA keys
keys_rsa_all: keys_rsa_unenc keys_rsa_enc_basic keys_rsa_enc_pkcs8_v1 keys_rsa_enc_pkcs8_v2
################################################################
### Generate certificates for CRT write check tests
################################################################
### The test files use the Mbed TLS generated certificates server1*.crt,
### but for comparison with OpenSSL also rules for OpenSSL-generated
### certificates server1*.crt.openssl are offered.
###
### Known differences:
### * OpenSSL encodes trailing zero-bits in bit-strings occurring in X.509 extension
### as unused bits, while Mbed TLS doesn't.
test_ca_server1_db = test-ca.server1.db
test_ca_server1_serial = test-ca.server1.serial
test_ca_server1_config_file = test-ca.server1.opensslconf
server1.csr: server1.key server1_csr.opensslconf
$(OPENSSL) req -keyform PEM -key server1.key -config server1_csr.opensslconf -out $@ -new
all_final += server1.csr
server1.crt: server1.key server1.csr $(test_ca_crt) $(test_ca_key_file_rsa)
$(MBEDTLS_CERT_WRITE) request_file=server1.csr issuer_crt=$(test_ca_crt) issuer_key=$(test_ca_key_file_rsa) issuer_pwd=$(test_ca_pwd_rsa) version=1 not_before=20110212144406 not_after=20210212144406 md=SHA1 version=3 output_file=$@
server1.noauthid.crt: server1.key server1.csr $(test_ca_crt) $(test_ca_key_file_rsa)
$(MBEDTLS_CERT_WRITE) request_file=server1.csr issuer_crt=$(test_ca_crt) issuer_key=$(test_ca_key_file_rsa) issuer_pwd=$(test_ca_pwd_rsa) not_before=20110212144406 not_after=20210212144406 md=SHA1 authority_identifier=0 version=3 output_file=$@
server1.der: server1.crt
$(OPENSSL) x509 -inform PEM -in $< -outform DER -out $@
all_final += server1.crt server1.noauthid.crt server1.der
server1.key_usage.crt: server1.key server1.csr $(test_ca_crt) $(test_ca_key_file_rsa)
$(MBEDTLS_CERT_WRITE) request_file=server1.csr issuer_crt=$(test_ca_crt) issuer_key=$(test_ca_key_file_rsa) issuer_pwd=$(test_ca_pwd_rsa) version=1 not_before=20110212144406 not_after=20210212144406 md=SHA1 key_usage=digital_signature,non_repudiation,key_encipherment version=3 output_file=$@
server1.key_usage_noauthid.crt: server1.key server1.csr $(test_ca_crt) $(test_ca_key_file_rsa)
$(MBEDTLS_CERT_WRITE) request_file=server1.csr issuer_crt=$(test_ca_crt) issuer_key=$(test_ca_key_file_rsa) issuer_pwd=$(test_ca_pwd_rsa) version=1 not_before=20110212144406 not_after=20210212144406 md=SHA1 key_usage=digital_signature,non_repudiation,key_encipherment authority_identifier=0 version=3 output_file=$@
server1.key_usage.der: server1.key_usage.crt
$(OPENSSL) x509 -inform PEM -in $< -outform DER -out $@
all_final += server1.key_usage.crt server1.key_usage_noauthid.crt server1.key_usage.der
server1.cert_type.crt: server1.key server1.csr $(test_ca_crt) $(test_ca_key_file_rsa)
$(MBEDTLS_CERT_WRITE) request_file=server1.csr issuer_crt=$(test_ca_crt) issuer_key=$(test_ca_key_file_rsa) issuer_pwd=$(test_ca_pwd_rsa) version=1 not_before=20110212144406 not_after=20210212144406 md=SHA1 ns_cert_type=ssl_server version=3 output_file=$@
server1.cert_type_noauthid.crt: server1.key server1.csr $(test_ca_crt) $(test_ca_key_file_rsa)
$(MBEDTLS_CERT_WRITE) request_file=server1.csr issuer_crt=$(test_ca_crt) issuer_key=$(test_ca_key_file_rsa) issuer_pwd=$(test_ca_pwd_rsa) version=1 not_before=20110212144406 not_after=20210212144406 md=SHA1 ns_cert_type=ssl_server authority_identifier=0 version=3 output_file=$@
server1.cert_type.der: server1.cert_type.crt
$(OPENSSL) x509 -inform PEM -in $< -outform DER -out $@
all_final += server1.cert_type.crt server1.cert_type_noauthid.crt server1.cert_type.der
server1.v1.crt: server1.key server1.csr $(test_ca_crt) $(test_ca_key_file_rsa)
$(MBEDTLS_CERT_WRITE) request_file=server1.csr issuer_crt=$(test_ca_crt) issuer_key=$(test_ca_key_file_rsa) issuer_pwd=$(test_ca_pwd_rsa) version=1 not_before=20110212144406 not_after=20210212144406 md=SHA1 version=1 output_file=$@
server1.v1.der: server1.v1.crt
$(OPENSSL) x509 -inform PEM -in $< -outform DER -out $@
all_final += server1.v1.crt server1.v1.der
# OpenSSL-generated certificates for comparison
# Also provide certificates in DER format to allow
# direct binary comparison using e.g. dumpasn1
server1.crt.openssl server1.key_usage.crt.openssl server1.cert_type.crt.openssl: server1.key server1.csr $(test_ca_crt) $(test_ca_key_file_rsa) $(test_ca_server1_config_file)
echo "01" > $(test_ca_server1_serial)
rm -f $(test_ca_server1_db)
touch $(test_ca_server1_db)
$(OPENSSL) ca -batch -passin "pass:$(test_ca_pwd_rsa)" -config $(test_ca_server1_config_file) -in server1.csr -extensions v3_ext -extfile $@.v3_ext -out $@
server1.der.openssl: server1.crt.openssl
$(OPENSSL) x509 -inform PEM -in $< -outform DER -out $@
server1.key_usage.der.openssl: server1.key_usage.crt.openssl
$(OPENSSL) x509 -inform PEM -in $< -outform DER -out $@
server1.cert_type.der.openssl: server1.cert_type.crt.openssl
$(OPENSSL) x509 -inform PEM -in $< -outform DER -out $@
server1.v1.crt.openssl: server1.key server1.csr $(test_ca_crt) $(test_ca_key_file_rsa) $(test_ca_server1_config_file)
echo "01" > $(test_ca_server1_serial)
rm -f $(test_ca_server1_db)
touch $(test_ca_server1_db)
$(OPENSSL) ca -batch -passin "pass:$(test_ca_pwd_rsa)" -config $(test_ca_server1_config_file) -in server1.csr -out $@
server1.v1.der.openssl: server1.v1.crt.openssl
$(OPENSSL) x509 -inform PEM -in $< -outform DER -out $@
server1_all: server1.csr server1.crt server1.noauthid.crt server1.crt.openssl server1.v1.crt server1.v1.crt.openssl server1.key_usage.crt server1.key_usage_noauthid.crt server1.key_usage.crt.openssl server1.cert_type.crt server1.cert_type_noauthid.crt server1.cert_type.crt.openssl server1.der server1.der.openssl server1.v1.der server1.v1.der.openssl server1.key_usage.der server1.key_usage.der.openssl server1.cert_type.der server1.cert_type.der.openssl
################################################################ ################################################################
#### Meta targets #### Meta targets
################################################################ ################################################################
@ -74,6 +400,14 @@ all_final: $(all_final)
all: $(all_intermediate) $(all_final) all: $(all_intermediate) $(all_final)
.PHONY: default all_final all .PHONY: default all_final all
.PHONY: keys_rsa_all
.PHONY: keys_rsa_unenc keys_rsa_enc_basic
.PHONY: keys_rsa_enc_pkcs8_v1 keys_rsa_enc_pkcs8_v2
.PHONY: keys_rsa_enc_basic_1024 keys_rsa_enc_basic_2048 keys_rsa_enc_basic_4096
.PHONY: keys_rsa_enc_pkcs8_v1_1024 keys_rsa_enc_pkcs8_v2_1024
.PHONY: keys_rsa_enc_pkcs8_v1_2048 keys_rsa_enc_pkcs8_v2_2048
.PHONY: keys_rsa_enc_pkcs8_v1_4096 keys_rsa_enc_pkcs8_v2_4096
.PHONY: server1_all
# These files should not be committed to the repository. # These files should not be committed to the repository.
list_intermediate: list_intermediate:

View file

@ -0,0 +1,11 @@
-----BEGIN CERTIFICATE-----
MIIBpTCCAUugAwIBAgIJAPygloXKk6BwMAoGCCqGSM49BAMCMC8xCzAJBgNVBAYT
AlVLMREwDwYDVQQKDAhtYmVkIFRMUzENMAsGA1UEAwwEQ0EwMDAeFw0xNzA2MjIx
MTUwMzJaFw0yNzA2MjMxMTUwMzJaMC8xCzAJBgNVBAYTAlVLMREwDwYDVQQKDAht
YmVkIFRMUzENMAsGA1UEAwwEQ0EwMDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA
BFW41/qAwAPpy+Txdc7PKmzZsq9CPiujKU4vpF1ekXnGx2HP420QobwBVVWhkzRm
LwdboH2j65dcCKjQ7mv/dxKjUDBOMB0GA1UdDgQWBBQlFYvU5WboI4fcdPoiQs8/
fPHZrTAfBgNVHSMEGDAWgBQlFYvU5WboI4fcdPoiQs8/fPHZrTAMBgNVHRMEBTAD
AQH/MAoGCCqGSM49BAMCA0gAMEUCIQC7iRcVzwMyfVK5imirJ7MqJQ04euH4CLOt
IZ+SNfaERAIgSU0MWFDosVEIpg8YMqIHeF7Mg4ZyH6+fGazJgVLttUY=
-----END CERTIFICATE-----

View file

@ -0,0 +1,8 @@
-----BEGIN EC PARAMETERS-----
BggqhkjOPQMBBw==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIARPaEIfROHkE9Y0ZgHh7Mc3ZU6LR9lCOIw1ksYTHp5EoAoGCCqGSM49
AwEHoUQDQgAEVbjX+oDAA+nL5PF1zs8qbNmyr0I+K6MpTi+kXV6RecbHYc/jbRCh
vAFVVaGTNGYvB1ugfaPrl1wIqNDua/93Eg==
-----END EC PRIVATE KEY-----

View file

@ -0,0 +1,13 @@
-----BEGIN CERTIFICATE-----
MIIB3jCCAYWgAwIBAgIBATAKBggqhkjOPQQDAjAvMQswCQYDVQQGEwJVSzERMA8G
A1UECgwIbWJlZCBUTFMxDTALBgNVBAMMBENBMDAwHhcNMTcwNjIyMTE1MDMyWhcN
MjcwNjIzMTE1MDMyWjAvMQswCQYDVQQGEwJVSzERMA8GA1UECgwIbWJlZCBUTFMx
DTALBgNVBAMMBENBMDEwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQznn9zHHwL
GO8VR4W9V7vMlxCdoojzEOiX5Y6JtPtFOz866ueHY6zoN0/mJ6DnqnSXilJIUUeW
6eGfqmka7nxko4GRMIGOMB0GA1UdDgQWBBSh3uHkX5nj86yFEFwjscSWM40P+jBf
BgNVHSMEWDBWgBQlFYvU5WboI4fcdPoiQs8/fPHZraEzpDEwLzELMAkGA1UEBhMC
VUsxETAPBgNVBAoMCG1iZWQgVExTMQ0wCwYDVQQDDARDQTAwggkA/KCWhcqToHAw
DAYDVR0TBAUwAwEB/zAKBggqhkjOPQQDAgNHADBEAiBasbuinP+pJTU4oDCVD8zQ
1rJBDSOKIEyWu84/D6Hj6wIgVMPUoO01bPhzllAa/gW8Xk/daey09SBgN3AT9pWU
TDA=
-----END CERTIFICATE-----

View file

@ -0,0 +1,8 @@
-----BEGIN EC PARAMETERS-----
BggqhkjOPQMBBw==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEINSnxPqUNMba8F2KWNxU88heSs7vgas5BOzjRwQsQe6IoAoGCCqGSM49
AwEHoUQDQgAEM55/cxx8CxjvFUeFvVe7zJcQnaKI8xDol+WOibT7RTs/Ournh2Os
6DdP5ieg56p0l4pSSFFHlunhn6ppGu58ZA==
-----END EC PRIVATE KEY-----

View file

@ -0,0 +1,12 @@
-----BEGIN CERTIFICATE-----
MIIB1zCCAX2gAwIBAgIBATAKBggqhkjOPQQDAjAvMQswCQYDVQQGEwJVSzERMA8G
A1UECgwIbWJlZCBUTFMxDTALBgNVBAMMBENBMDEwHhcNMTcwNjIyMTE1MDMyWhcN
MjcwNjIzMTE1MDMyWjAvMQswCQYDVQQGEwJVSzERMA8GA1UECgwIbWJlZCBUTFMx
DTALBgNVBAMMBENBMDIwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQWHpv1i6lf
wvNPOP5ka6S0n55EvzoaYK6pbTXP6yMOW/4XZSPKx5Zoq4FMe0cKzGIIFL1rzj1V
2czYB+qvLhyio4GJMIGGMB0GA1UdDgQWBBT5RCgQ0AlZTQbfFB2+6+w0XRvydTBX
BgNVHSMEUDBOgBSh3uHkX5nj86yFEFwjscSWM40P+qEzpDEwLzELMAkGA1UEBhMC
VUsxETAPBgNVBAoMCG1iZWQgVExTMQ0wCwYDVQQDDARDQTAwggEBMAwGA1UdEwQF
MAMBAf8wCgYIKoZIzj0EAwIDSAAwRQIhAI7unGW/gr9tOc3i+dF5N815srgh+FrX
oj9Et74EcSpTAiBubv+vOH0DE0gmYI11HeAIgutWqqMIC72dZlwTF/Vi3g==
-----END CERTIFICATE-----

View file

@ -0,0 +1,8 @@
-----BEGIN EC PARAMETERS-----
BggqhkjOPQMBBw==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIPW9zE8cjiZ8w17jTAebb4xAmEg6heEEnEaG4lGCd38joAoGCCqGSM49
AwEHoUQDQgAEFh6b9YupX8LzTzj+ZGuktJ+eRL86GmCuqW01z+sjDlv+F2UjyseW
aKuBTHtHCsxiCBS9a849VdnM2Afqry4cog==
-----END EC PRIVATE KEY-----

View file

@ -0,0 +1,12 @@
-----BEGIN CERTIFICATE-----
MIIB2DCCAX2gAwIBAgIBATAKBggqhkjOPQQDAjAvMQswCQYDVQQGEwJVSzERMA8G
A1UECgwIbWJlZCBUTFMxDTALBgNVBAMMBENBMDIwHhcNMTcwNjIyMTE1MDMyWhcN
MjcwNjIzMTE1MDMyWjAvMQswCQYDVQQGEwJVSzERMA8GA1UECgwIbWJlZCBUTFMx
DTALBgNVBAMMBENBMDMwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQRDXDNIi1p
ereudhqwa2LslXgsxnB63Hu5y5lg+1WPruIYPzD/Ho0APveVdzFLVji19+bE4+tF
PYL1SpsN1WfWo4GJMIGGMB0GA1UdDgQWBBQApzZdtBdD3dLxouQpr/aDiVttdzBX
BgNVHSMEUDBOgBT5RCgQ0AlZTQbfFB2+6+w0XRvydaEzpDEwLzELMAkGA1UEBhMC
VUsxETAPBgNVBAoMCG1iZWQgVExTMQ0wCwYDVQQDDARDQTAxggEBMAwGA1UdEwQF
MAMBAf8wCgYIKoZIzj0EAwIDSQAwRgIhAOnd+7bAofkHVa4KFNjv3TCegw1lrhuM
8Of8wgvrTEGoAiEAsS8iKMpSfXH4D0egg4gLamE6akde965rDtySU+ve9lg=
-----END CERTIFICATE-----

View file

@ -0,0 +1,8 @@
-----BEGIN EC PARAMETERS-----
BggqhkjOPQMBBw==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIBx2xwapGbHTy79IbpJkc/w9LJXPKNG7gGRLPOGPQFI6oAoGCCqGSM49
AwEHoUQDQgAEEQ1wzSItaXq3rnYasGti7JV4LMZwetx7ucuZYPtVj67iGD8w/x6N
AD73lXcxS1Y4tffmxOPrRT2C9UqbDdVn1g==
-----END EC PRIVATE KEY-----

View file

@ -0,0 +1,12 @@
-----BEGIN CERTIFICATE-----
MIIB1jCCAX2gAwIBAgIBATAKBggqhkjOPQQDAjAvMQswCQYDVQQGEwJVSzERMA8G
A1UECgwIbWJlZCBUTFMxDTALBgNVBAMMBENBMDMwHhcNMTcwNjIyMTE1MDMyWhcN
MjcwNjIzMTE1MDMyWjAvMQswCQYDVQQGEwJVSzERMA8GA1UECgwIbWJlZCBUTFMx
DTALBgNVBAMMBENBMDQwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQUXDgcUVNT
9hovbZE5HL6rjOb7C55wEuWKThV/CcZ4rWrXx7VXHYdD/R3aDA7JSvYpm2sTok4i
sblDzhZM/GDNo4GJMIGGMB0GA1UdDgQWBBQox4F1NsZunlsduoGvzIgRSYfB3zBX
BgNVHSMEUDBOgBQApzZdtBdD3dLxouQpr/aDiVttd6EzpDEwLzELMAkGA1UEBhMC
VUsxETAPBgNVBAoMCG1iZWQgVExTMQ0wCwYDVQQDDARDQTAyggEBMAwGA1UdEwQF
MAMBAf8wCgYIKoZIzj0EAwIDRwAwRAIgAkiNhqFAZXSUWEDK91OZvQGdeZOtd6mC
+Wv3fGk3t28CIEKOwidkUTUaiPdZ4efmAr+CEeGzdq27ob2S+nqqHqgV
-----END CERTIFICATE-----

View file

@ -0,0 +1,8 @@
-----BEGIN EC PARAMETERS-----
BggqhkjOPQMBBw==
-----END EC PARAMETERS-----
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIDQvTm0wfEAKoymv8ePBv7cRxrnM4g6LREnSll5ghQsXoAoGCCqGSM49
AwEHoUQDQgAEFFw4HFFTU/YaL22RORy+q4zm+wuecBLlik4VfwnGeK1q18e1Vx2H
Q/0d2gwOyUr2KZtrE6JOIrG5Q84WTPxgzQ==
-----END EC PRIVATE KEY-----

View file

@ -0,0 +1,12 @@
-----BEGIN CERTIFICATE-----
MIIB1zCCAX2gAwIBAgIBATAKBggqhkjOPQQDAjAvMQswCQYDVQQGEwJVSzERMA8G
A1UECgwIbWJlZCBUTFMxDTALBgNVBAMMBENBMDQwHhcNMTcwNjIyMTE1MDMyWhcN
MjcwNjIzMTE1MDMyWjAvMQswCQYDVQQGEwJVSzERMA8GA1UECgwIbWJlZCBUTFMx
DTALBgNVBAMMBENBMDUwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQEdT0OFf5G
UcrgX2XllCyJzP94NZ464GsgB6psNLsDeL+j7AU+oJy7VLvW/lHh3ODgl08Z9bhq
LFBmNjnHbm8Qo4GJMIGGMB0GA1UdDgQWBBTXh06MAV9S4l4lG1TKOrKRBh4qnzBX
BgNVHSMEUDBOgBQox4F1NsZunlsduoGvzIgRSYfB36EzpDEwLzELMAkGA1UEBhMC
VUsxETAPBgNVBAoMCG1iZWQgVExTMQ0wCwYDVQQDDARDQTAzggEBMAwGA1UdEwQF
MAMBAf8wCgYIKoZIzj0EAwIDSAAwRQIhAIW++zqDZlLLUk/emePohdNOp5JO3wS9
XvkBJ6Wua7GBAiAdx+EKmdjVrwnzrQltTgnmSfGMXhKNYifK3uD83W3pcQ==
-----END CERTIFICATE-----

Some files were not shown because too many files have changed in this diff Show more