Merge branch 'development' into Remove__CHECK_PARAMS_option

This commit is contained in:
TRodziewicz 2021-06-07 15:41:49 +02:00
commit 0730cd5d9e
78 changed files with 6402 additions and 1229 deletions

View File

@ -0,0 +1,6 @@
API changes
* For multi-part AEAD operations with the cipher module, calling
mbedtls_cipher_finish() is now mandatory. Previously the documentation
was unclear on this point, and this function happened to never do
anything with the currently implemented AEADs, so in practice it was
possible to skip calling it, which is no longer supported.

View File

@ -0,0 +1,3 @@
API changes
* The function mbedtls_x509write_csr_set_extension() has an extra parameter
which allows to mark an extension as critical. Fixes #4055.

View File

@ -0,0 +1,4 @@
API changes
* The option MBEDTLS_ECP_FIXED_POINT_OPTIM use pre-computed comb tables
instead of computing tables in runtime. Thus, this option now increase
code size, and it does not increase RAM usage in runtime anymore.

View File

@ -1,11 +1,10 @@
Removals
* Remove the TLS 1.0, TLS 1.1 and DTLS 1.0 support by removing the following
deprecated library constants: MBEDTLS_SSL_PROTO_TLS1,
MBEDTLS_SSL_PROTO_TLS1_1, MBEDTLS_SSL_CBC_RECORD_SPLITTING,
MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED,
MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED, MBEDTLS_SSL_RECORD_CHECKING,
MBEDTLS_SSL_FALLBACK_SCSV, MBEDTLS_SSL_FALLBACK_SCSV_VALUE,
MBEDTLS_SSL_IS_FALLBACK, MBEDTLS_SSL_IS_NOT_FALLBACK, and functions:
* Remove support for TLS 1.0, TLS 1.1 and DTLS 1.0, as well as support for
CBC record splitting, fallback SCSV, and the ability to configure
ciphersuites per version, which are no longer relevant. This removes the
configuration options MBEDTLS_SSL_PROTO_TLS1,
MBEDTLS_SSL_PROTO_TLS1_1, MBEDTLS_SSL_CBC_RECORD_SPLITTING and
MBEDTLS_SSL_FALLBACK_SCSV as well as the functions
mbedtls_ssl_conf_cbc_record_splitting(),
mbedtls_ssl_get_key_exchange_md_ssl_tls(), mbedtls_ssl_conf_fallback().
Fixes #4286.
mbedtls_ssl_get_key_exchange_md_ssl_tls(), mbedtls_ssl_conf_fallback(),
and mbedtls_ssl_conf_ciphersuites_for_version(). Fixes #4286.

View File

@ -0,0 +1,4 @@
Changes
* Replace MBEDTLS_SSL_CID_PADDING_GRANULARITY and
MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY with a new single unified option
MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY. Fixes #4335.

13
ChangeLog.d/issue4367.txt Normal file
View File

@ -0,0 +1,13 @@
Removals
* Remove all the 3DES ciphersuites:
MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA,
MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,
MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA,
MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,
MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA,
MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA,
MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA. Remove the
MBEDTLS_REMOVE_3DES_CIPHERSUITES option which is no longer relevant.
Fixes #4367.

View File

@ -0,0 +1,3 @@
Removals
* Remove the MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3 option and let the code
behave as if it was always disabled. Fixes #4386.

View File

@ -0,0 +1,3 @@
Features
* The new function mbedtls_mpi_random() generates a random value in a
given range uniformly.

View File

@ -0,0 +1,4 @@
Security
* Fix a bias in the generation of finite-field Diffie-Hellman-Merkle (DHM)
private keys and of blinding values for DHM and elliptic curves (ECP)
computations. Reported by FlorianF89 in #4245.

View File

@ -0,0 +1,7 @@
API changes
* Modify semantics of `mbedtls_ssl_conf_[opaque_]psk()`:
In Mbed TLS 2.X, the API prescribes that later calls overwrite
the effect of earlier calls. In Mbed TLS 3.0, calling
`mbedtls_ssl_conf_[opaque_]psk()` more than once will fail,
leaving the PSK that was configured first intact.
Support for more than one PSK may be added in 3.X.

View File

@ -0,0 +1,3 @@
Removals
* Remove MBEDTLS_ECDH_LEGACY_CONTEXT config option since this was purely for
backward compatibility which is no longer supported. Addresses #4404.

View File

@ -0,0 +1,10 @@
Remove 3DES ciphersuites
--
This change does not affect users using default settings for 3DES in `config.h`
because the 3DES ciphersuites were disabled by that.
3DES has weaknesses/limitations and there are better alternatives, and more and
more standard bodies are recommending against its use in TLS.
The migration path here is to chose from the recomended in literature alternatives.

View File

@ -0,0 +1,9 @@
CCM interface changes: impact for alternative implementations
-------------------------------------------------------------
The CCM interface has changed with the addition of support for
multi-part operations. Five new API functions have been defined:
mbedtls_ccm_starts(), mbedtls_ccm_set_lengths(),
mbedtls_ccm_update_ad(), mbedtls_ccm_update() and mbedtls_ccm_finish().
Alternative implementations of CCM (`MBEDTLS_CCM_ALT`) have now to
implement those additional five API functions.

View File

@ -0,0 +1,15 @@
Calling `mbedtls_cipher_finish()` is mandatory for all multi-part operations
----------------------------------------------------------------------------
This only affects people who use the cipher module to perform AEAD operations
using the multi-part API.
Previously, the documentation didn't state explicitly if it was OK to call
`mbedtls_cipher_check_tag()` or `mbedtls_cipher_write_tag()` directly after
the last call to `mbedtls_cipher_update()` - that is, without calling
`mbedtls_cipher_finish()` in-between. If you code was missing that call,
please add it and be prepared to get as much as 15 bytes of output.
Currently the output is always 0 bytes, but it may be more when alternative
implementations of the underlying primitives are in use, or with future
versions of the library.

View File

@ -0,0 +1,14 @@
Combine the `MBEDTLS_SSL_CID_PADDING_GRANULARITY` and `MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY` options
--
This change affects users who modified the default `config.h` padding granularity
settings, i.e. enabled at least one of the options.
The `config.h` options `MBEDTLS_SSL_CID_PADDING_GRANULARITY` and
`MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY` were combined into one option because
they used exactly the same padding mechanism and hence their respective padding
granularities can be used in exactly the same way. This change simplifies the
code maintenance.
The new single option `MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY` can be used
for both DTLS-CID and TLS 1.3.

View File

@ -0,0 +1,9 @@
Change the API to allow adding critical extensions to CSRs
------------------------------------------------------------------
This affects applications that call the `mbedtls_x509write_csr_set_extension`
function.
The API is changed to include the parameter `critical` which allow to mark an
extension included in a CSR as critical. To get the previous behaviour pass
`0`.

View File

@ -0,0 +1,11 @@
Change MBEDTLS_ECP_FIXED_POINT_OPTIM behaviour
------------------------------------------------------
The option `MBEDTLS_ECP_FIXED_POINT_OPTIM` now increase code size and it does
not increase peak RAM usage anymore.
If you are limited by code size, you can define `MBEDTLS_ECP_FIXED_POINT_OPTIM`
to `0` in your config file. The impact depends on the number and size of
enabled curves. For example, for P-256 the difference is 1KB; see the documentation
of this option for details.

View File

@ -0,0 +1,18 @@
Relaxed semantics for PSK configuration
-----------------------------------------------------------------
This affects users which call the PSK configuration APIs
`mbedtlsl_ssl_conf_psk()` and `mbedtls_ssl_conf_psk_opaque()`
multiple times on the same SSL configuration.
In Mbed TLS 2.x, users would observe later calls overwriting
the effect of earlier calls, with the prevailing PSK being
the one that has been configured last. In Mbed TLS 3.0,
calling `mbedtls_ssl_conf_[opaque_]psk()` multiple times
will return an error, leaving the first PSK intact.
To achieve equivalent functionality when migrating to Mbed TLS 3.0,
users calling `mbedtls_ssl_conf_[opaque_]psk()` multiple times should
remove all but the last call, so that only one call to _either_
`mbedtls_ssl_conf_psk()` _or_ `mbedtls_ssl_conf_psk_opaque()`
remains.

View File

@ -0,0 +1,14 @@
Remove the `MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3` option
--
This change does not affect users who were using the default configuration, as
this option was already disabled by default. Also, it does not affect users who
are working with current V3 X.509 certificates.
Extensions were added in V3 of the X.509 specification, so pre-V3 certificates
containing extensions were never compliant. Mbed TLS now rejects them with a
parsing error in all configurations, as it did previously in the default
configuration.
If you are working with the pre-V3 certificates you need to switch to the
current ones.

View File

@ -3,9 +3,25 @@ Remove suport for TLS 1.0, 1.1 and DTLS 1.0
This change affects users of the TLS 1.0, 1.1 and DTLS 1.0 protocols.
The versions of (D)TLS that are being removed are not as secure as the latest
versions. Keeping them in the library creates opportunities for misconfiguration
These versions have been deprecated by RFC 8996.
Keeping them in the library creates opportunities for misconfiguration
and possibly downgrade attacks. More generally, more code means a larger attack
surface, even if the code is supposedly not used.
The migration path is to adopt the latest versions of the protocol.
As a consequence of removing TLS 1.0, support for CBC record splitting was
also removed, as it was a work-around for a weakness in this particular
version. There is no migration path since the feature is no longer relevant.
As a consequence of currently supporting only one version of (D)TLS (and in the
future 1.3 which will have a different version negociation mechanism), support
for fallback SCSV (RFC 7507) was also removed. There is no migration path as
it's no longer useful with TLS 1.2 and later.
As a consequence of currently supporting only one version of (D)TLS (and in the
future 1.3 which will have a different concept of ciphersuites), support for
configuring ciphersuites separately for each version via
`mbedtls_ssl_conf_ciphersuites_for_version()` was removed. Use
`mbedtls_ssl_conf_ciphersuites()` to configure ciphersuites to use with (D)TLS
1.2; in the future a different API will be added for (D)TLS 1.3.

View File

@ -871,6 +871,44 @@ int mbedtls_mpi_fill_random( mbedtls_mpi *X, size_t size,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
/** Generate a random number uniformly in a range.
*
* This function generates a random number between \p min inclusive and
* \p N exclusive.
*
* The procedure complies with RFC 6979 §3.3 (deterministic ECDSA)
* when the RNG is a suitably parametrized instance of HMAC_DRBG
* and \p min is \c 1.
*
* \note There are `N - min` possible outputs. The lower bound
* \p min can be reached, but the upper bound \p N cannot.
*
* \param X The destination MPI. This must point to an initialized MPI.
* \param min The minimum value to return.
* It must be nonnegative.
* \param N The upper bound of the range, exclusive.
* In other words, this is one plus the maximum value to return.
* \p N must be strictly larger than \p min.
* \param f_rng The RNG function to use. This must not be \c NULL.
* \param p_rng The RNG parameter to be passed to \p f_rng.
*
* \return \c 0 if successful.
* \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
* \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p min or \p N is invalid
* or if they are incompatible.
* \return #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if the implementation was
* unable to find a suitable value within a limited number
* of attempts. This has a negligible probability if \p N
* is significantly larger than \p min, which is the case
* for all usual cryptographic applications.
* \return Another negative error code on failure.
*/
int mbedtls_mpi_random( mbedtls_mpi *X,
mbedtls_mpi_sint min,
const mbedtls_mpi *N,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
/**
* \brief Compute the greatest common divisor: G = gcd(A, B)
*

View File

@ -55,6 +55,11 @@
#include "mbedtls/cipher.h"
#define MBEDTLS_CCM_DECRYPT 0
#define MBEDTLS_CCM_ENCRYPT 1
#define MBEDTLS_CCM_STAR_DECRYPT 2
#define MBEDTLS_CCM_STAR_ENCRYPT 3
#define MBEDTLS_ERR_CCM_BAD_INPUT -0x000D /**< Bad input parameters to the function. */
#define MBEDTLS_ERR_CCM_AUTH_FAILED -0x000F /**< Authenticated decryption failed. */
@ -133,10 +138,10 @@ void mbedtls_ccm_free( mbedtls_ccm_context *ctx );
* \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12,
* or 13. The length L of the message length field is
* 15 - \p iv_len.
* \param add The additional data field. If \p add_len is greater than
* zero, \p add must be a readable buffer of at least that
* \param ad The additional data field. If \p ad_len is greater than
* zero, \p ad must be a readable buffer of at least that
* length.
* \param add_len The length of additional data in Bytes.
* \param ad_len The length of additional data in Bytes.
* This must be less than `2^16 - 2^8`.
* \param input The buffer holding the input data. If \p length is greater
* than zero, \p input must be a readable buffer of at least
@ -154,7 +159,7 @@ void mbedtls_ccm_free( mbedtls_ccm_context *ctx );
*/
int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *ad, size_t ad_len,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len );
@ -179,9 +184,9 @@ int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
* \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12,
* or 13. The length L of the message length field is
* 15 - \p iv_len.
* \param add The additional data field. This must be a readable buffer of
* at least \p add_len Bytes.
* \param add_len The length of additional data in Bytes.
* \param ad The additional data field. This must be a readable buffer of
* at least \p ad_len Bytes.
* \param ad_len The length of additional data in Bytes.
* This must be less than 2^16 - 2^8.
* \param input The buffer holding the input data. If \p length is greater
* than zero, \p input must be a readable buffer of at least
@ -202,7 +207,7 @@ int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
*/
int mbedtls_ccm_star_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *ad, size_t ad_len,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len );
@ -218,9 +223,9 @@ int mbedtls_ccm_star_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
* \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12,
* or 13. The length L of the message length field is
* 15 - \p iv_len.
* \param add The additional data field. This must be a readable buffer
* of at least that \p add_len Bytes..
* \param add_len The length of additional data in Bytes.
* \param ad The additional data field. This must be a readable buffer
* of at least that \p ad_len Bytes..
* \param ad_len The length of additional data in Bytes.
* This must be less than 2^16 - 2^8.
* \param input The buffer holding the input data. If \p length is greater
* than zero, \p input must be a readable buffer of at least
@ -239,7 +244,7 @@ int mbedtls_ccm_star_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
*/
int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *ad, size_t ad_len,
const unsigned char *input, unsigned char *output,
const unsigned char *tag, size_t tag_len );
@ -260,9 +265,9 @@ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
* \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12,
* or 13. The length L of the message length field is
* 15 - \p iv_len.
* \param add The additional data field. This must be a readable buffer of
* at least that \p add_len Bytes.
* \param add_len The length of additional data in Bytes.
* \param ad The additional data field. This must be a readable buffer of
* at least that \p ad_len Bytes.
* \param ad_len The length of additional data in Bytes.
* This must be less than 2^16 - 2^8.
* \param input The buffer holding the input data. If \p length is greater
* than zero, \p input must be a readable buffer of at least
@ -284,10 +289,208 @@ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
*/
int mbedtls_ccm_star_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *ad, size_t ad_len,
const unsigned char *input, unsigned char *output,
const unsigned char *tag, size_t tag_len );
/**
* \brief This function starts a CCM encryption or decryption
* operation.
*
* This function and mbedtls_ccm_set_lengths() must be called
* before calling mbedtls_ccm_update_ad() or
* mbedtls_ccm_update(). This function can be called before
* or after mbedtls_ccm_set_lengths().
*
* \note This function is not implemented in Mbed TLS yet.
*
* \param ctx The CCM context. This must be initialized.
* \param mode The operation to perform: #MBEDTLS_CCM_ENCRYPT or
* #MBEDTLS_CCM_DECRYPT or #MBEDTLS_CCM_STAR_ENCRYPT or
* #MBEDTLS_CCM_STAR_DECRYPT.
* \param iv The initialization vector. This must be a readable buffer
* of at least \p iv_len Bytes.
* \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12,
* or 13. The length L of the message length field is
* 15 - \p iv_len.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CCM_BAD_INPUT on failure:
* \p ctx is in an invalid state,
* \p mode is invalid,
* \p iv_len is invalid (lower than \c 7 or greater than
* \c 13).
*/
int mbedtls_ccm_starts( mbedtls_ccm_context *ctx,
int mode,
const unsigned char *iv,
size_t iv_len );
/**
* \brief This function declares the lengths of the message
* and additional data for a CCM encryption or decryption
* operation.
*
* This function and mbedtls_ccm_starts() must be called
* before calling mbedtls_ccm_update_ad() or
* mbedtls_ccm_update(). This function can be called before
* or after mbedtls_ccm_starts().
*
* \note This function is not implemented in Mbed TLS yet.
*
* \param ctx The CCM context. This must be initialized.
* \param total_ad_len The total length of additional data in bytes.
* This must be less than `2^16 - 2^8`.
* \param plaintext_len The length in bytes of the plaintext to encrypt or
* result of the decryption (thus not encompassing the
* additional data that are not encrypted).
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CCM_BAD_INPUT on failure:
* \p ctx is in an invalid state,
* \p total_ad_len is greater than \c 0xFF00.
*/
int mbedtls_ccm_set_lengths( mbedtls_ccm_context *ctx,
size_t total_ad_len,
size_t plaintext_len );
/**
* \brief This function feeds an input buffer as associated data
* (authenticated but not encrypted data) in a CCM
* encryption or decryption operation.
*
* You may call this function zero, one or more times
* to pass successive parts of the additional data. The
* lengths \p ad_len of the data parts should eventually add
* up exactly to the total length of additional data
* \c total_ad_len passed to mbedtls_ccm_set_lengths(). You
* may not call this function after calling
* mbedtls_ccm_update().
*
* \note This function is not implemented in Mbed TLS yet.
*
* \param ctx The CCM context. This must have been started with
* mbedtls_ccm_starts(), the lengths of the message and
* additional data must have been declared with
* mbedtls_ccm_set_lengths() and this must not have yet
* received any input with mbedtls_ccm_update().
* \param ad The buffer holding the additional data, or \c NULL
* if \p ad_len is \c 0.
* \param ad_len The length of the additional data. If \c 0,
* \p ad may be \c NULL.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CCM_BAD_INPUT on failure:
* \p ctx is in an invalid state,
* total input length too long.
*/
int mbedtls_ccm_update_ad( mbedtls_ccm_context *ctx,
const unsigned char *ad,
size_t ad_len );
/**
* \brief This function feeds an input buffer into an ongoing CCM
* encryption or decryption operation.
*
* You may call this function zero, one or more times
* to pass successive parts of the input: the plaintext to
* encrypt, or the ciphertext (not including the tag) to
* decrypt. After the last part of the input, call
* mbedtls_ccm_finish(). The lengths \p input_len of the
* data parts should eventually add up exactly to the
* plaintext length \c plaintext_len passed to
* mbedtls_ccm_set_lengths().
*
* This function may produce output in one of the following
* ways:
* - Immediate output: the output length is always equal
* to the input length.
* - Buffered output: except for the last part of input data,
* the output consists of a whole number of 16-byte blocks.
* If the total input length so far (not including
* associated data) is 16 \* *B* + *A* with *A* < 16 then
* the total output length is 16 \* *B*.
* For the last part of input data, the output length is
* equal to the input length plus the number of bytes (*A*)
* buffered in the previous call to the function (if any).
* The function uses the plaintext length
* \c plaintext_len passed to mbedtls_ccm_set_lengths()
* to detect the last part of input data.
*
* In particular:
* - It is always correct to call this function with
* \p output_size >= \p input_len + 15.
* - If \p input_len is a multiple of 16 for all the calls
* to this function during an operation (not necessary for
* the last one) then it is correct to use \p output_size
* =\p input_len.
*
* \note This function is not implemented in Mbed TLS yet.
*
* \param ctx The CCM context. This must have been started with
* mbedtls_ccm_starts() and the lengths of the message and
* additional data must have been declared with
* mbedtls_ccm_set_lengths().
* \param input The buffer holding the input data. If \p input_len
* is greater than zero, this must be a readable buffer
* of at least \p input_len bytes.
* \param input_len The length of the input data in bytes.
* \param output The buffer for the output data. If \p output_size
* is greater than zero, this must be a writable buffer of
* at least \p output_size bytes.
* \param output_size The size of the output buffer in bytes.
* See the function description regarding the output size.
* \param output_len On success, \p *output_len contains the actual
* length of the output written in \p output.
* On failure, the content of \p *output_len is
* unspecified.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CCM_BAD_INPUT on failure:
* \p ctx is in an invalid state,
* total input length too long,
* or \p output_size too small.
*/
int mbedtls_ccm_update( mbedtls_ccm_context *ctx,
const unsigned char *input, size_t input_len,
unsigned char *output, size_t output_size,
size_t *output_len );
/**
* \brief This function finishes the CCM operation and generates
* the authentication tag.
*
* It wraps up the CCM stream, and generates the
* tag. The tag can have a maximum length of 16 Bytes.
*
* \note This function is not implemented in Mbed TLS yet.
*
* \param ctx The CCM context. This must have been started with
* mbedtls_ccm_starts() and the lengths of the message and
* additional data must have been declared with
* mbedtls_ccm_set_lengths().
* \param tag The buffer for holding the tag. If \p tag_len is greater
* than zero, this must be a writable buffer of at least \p
* tag_len Bytes.
* \param tag_len The length of the tag to generate in Bytes:
* 4, 6, 8, 10, 12, 14 or 16.
* For CCM*, zero is also valid.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CCM_BAD_INPUT on failure:
* \p ctx is in an invalid state,
* invalid value of \p tag_len,
* the total amount of additional data passed to
* mbedtls_ccm_update_ad() was lower than the total length of
* additional data \c total_ad_len passed to
* mbedtls_ccm_set_lengths(),
* the total amount of input data passed to
* mbedtls_ccm_update() was lower than the plaintext length
* \c plaintext_len passed to mbedtls_ccm_set_lengths().
*/
int mbedtls_ccm_finish( mbedtls_ccm_context *ctx,
unsigned char *tag, size_t tag_len );
#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
/**
* \brief The CCM checkup routine.

View File

@ -130,16 +130,6 @@
#error "MBEDTLS_ECP_RESTARTABLE defined, but it cannot coexist with an alternative or PSA-based ECP implementation"
#endif
#if defined(MBEDTLS_ECP_RESTARTABLE) && \
! defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
#error "MBEDTLS_ECP_RESTARTABLE defined, but not MBEDTLS_ECDH_LEGACY_CONTEXT"
#endif
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED) && \
defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
#error "MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED defined, but MBEDTLS_ECDH_LEGACY_CONTEXT not disabled"
#endif
#if defined(MBEDTLS_ECDSA_DETERMINISTIC) && !defined(MBEDTLS_HMAC_DRBG_C)
#error "MBEDTLS_ECDSA_DETERMINISTIC defined, but not all prerequisites"
#endif
@ -840,6 +830,14 @@
#error "MBEDTLS_CHECK_PARAMS was removed in Mbed TLS 3.0. See https://github.com/ARMmbed/mbedtls/issues/4313"
#endif
#if defined(MBEDTLS_SSL_CID_PADDING_GRANULARITY) //no-check-names
#error "MBEDTLS_SSL_CID_PADDING_GRANULARITY was removed in Mbed TLS 3.0. See https://github.com/ARMmbed/mbedtls/issues/4335"
#endif
#if defined(MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY) //no-check-names
#error "MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY was removed in Mbed TLS 3.0. See https://github.com/ARMmbed/mbedtls/issues/4335"
#endif
/*
* Avoid warning from -pedantic. This is a convenient place for this
* workaround since this is included by every single file before the

View File

@ -437,10 +437,23 @@ void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx );
/**
* \brief This function initializes a cipher context for
* \brief This function prepares a cipher context for
* use with the given cipher primitive.
*
* \param ctx The context to initialize. This must be initialized.
* \note After calling this function, you should call
* mbedtls_cipher_setkey() and, if the mode uses padding,
* mbedtls_cipher_set_padding_mode(), then for each
* message to encrypt or decrypt with this key, either:
* - mbedtls_cipher_crypt() for one-shot processing with
* non-AEAD modes;
* - mbedtls_cipher_auth_encrypt_ext() or
* mbedtls_cipher_auth_decrypt_ext() for one-shot
* processing with AEAD modes or NIST_KW;
* - for multi-part processing, see the documentation of
* mbedtls_cipher_reset().
*
* \param ctx The context to prepare. This must be initialized by
* a call to mbedtls_cipher_init() first.
* \param cipher_info The cipher to use.
*
* \return \c 0 on success.
@ -448,10 +461,6 @@ void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx );
* parameter-verification failure.
* \return #MBEDTLS_ERR_CIPHER_ALLOC_FAILED if allocation of the
* cipher-specific context fails.
*
* \internal Currently, the function also clears the structure.
* In future versions, the caller will be required to call
* mbedtls_cipher_init() on the structure first.
*/
int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx,
const mbedtls_cipher_info_t *cipher_info );
@ -687,7 +696,30 @@ int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx,
/**
* \brief This function resets the cipher state.
*
* \param ctx The generic cipher context. This must be initialized.
* \note With non-AEAD ciphers, the order of calls for each message
* is as follows:
* 1. mbedtls_cipher_set_iv() if the mode uses an IV/nonce.
* 2. mbedtls_cipher_reset()
* 3. mbedtls_cipher_update() one or more times
* 4. mbedtls_cipher_finish()
* .
* This sequence can be repeated to encrypt or decrypt multiple
* messages with the same key.
*
* \note With AEAD ciphers, the order of calls for each message
* is as follows:
* 1. mbedtls_cipher_set_iv() if the mode uses an IV/nonce.
* 2. mbedtls_cipher_reset()
* 3. mbedtls_cipher_update_ad()
* 4. mbedtls_cipher_update() one or more times
* 5. mbedtls_cipher_finish()
* 6. mbedtls_cipher_check_tag() (for decryption) or
* mbedtls_cipher_write_tag() (for encryption).
* .
* This sequence can be repeated to encrypt or decrypt multiple
* messages with the same key.
*
* \param ctx The generic cipher context. This must be bound to a key.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on

View File

@ -616,26 +616,6 @@
*/
//#define MBEDTLS_CTR_DRBG_USE_128_BIT_KEY
/**
* \def MBEDTLS_REMOVE_3DES_CIPHERSUITES
*
* Remove 3DES ciphersuites by default in SSL / TLS.
* This flag removes the ciphersuites based on 3DES from the default list as
* returned by mbedtls_ssl_list_ciphersuites(). However, it is still possible
* to enable (some of) them with mbedtls_ssl_conf_ciphersuites() by including
* them explicitly.
*
* A man-in-the-browser attacker can recover authentication tokens sent through
* a TLS connection using a 3DES based cipher suite (see "On the Practical
* (In-)Security of 64-bit Block Ciphers" by Karthikeyan Bhargavan and Gaëtan
* Leurent, see https://sweet32.info/SWEET32_CCS16.pdf). If this attack falls
* in your threat model or you are unsure, then you should keep this option
* enabled to remove 3DES based cipher suites.
*
* Comment this macro to keep 3DES in the default ciphersuite list.
*/
#define MBEDTLS_REMOVE_3DES_CIPHERSUITES
/**
* \def MBEDTLS_ECP_DP_SECP192R1_ENABLED
*
@ -713,39 +693,10 @@
*
* \note This option only works with the default software implementation of
* elliptic curve functionality. It is incompatible with
* MBEDTLS_ECP_ALT, MBEDTLS_ECDH_XXX_ALT, MBEDTLS_ECDSA_XXX_ALT
* and MBEDTLS_ECDH_LEGACY_CONTEXT.
* MBEDTLS_ECP_ALT, MBEDTLS_ECDH_XXX_ALT, MBEDTLS_ECDSA_XXX_ALT.
*/
//#define MBEDTLS_ECP_RESTARTABLE
/**
* \def MBEDTLS_ECDH_LEGACY_CONTEXT
*
* Use a backward compatible ECDH context.
*
* Mbed TLS supports two formats for ECDH contexts (#mbedtls_ecdh_context
* defined in `ecdh.h`). For most applications, the choice of format makes
* no difference, since all library functions can work with either format,
* except that the new format is incompatible with MBEDTLS_ECP_RESTARTABLE.
* The new format used when this option is disabled is smaller
* (56 bytes on a 32-bit platform). In future versions of the library, it
* will support alternative implementations of ECDH operations.
* The new format is incompatible with applications that access
* context fields directly and with restartable ECP operations.
*
* Define this macro if you enable MBEDTLS_ECP_RESTARTABLE or if you
* want to access ECDH context fields directly. Otherwise you should
* comment out this macro definition.
*
* This option has no effect if #MBEDTLS_ECDH_C is not enabled.
*
* \note This configuration option is experimental. Future versions of the
* library may modify the way the ECDH context layout is configured
* and may modify the layout of the new context type.
*/
#define MBEDTLS_ECDH_LEGACY_CONTEXT
/**
* \def MBEDTLS_ECDSA_DETERMINISTIC
*
@ -777,7 +728,6 @@
* MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA
* MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256
* MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256
* MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA
*/
#define MBEDTLS_KEY_EXCHANGE_PSK_ENABLED
@ -800,7 +750,6 @@
* MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA
* MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256
* MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256
* MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA
*
* \warning Using DHE constitutes a security risk as it
* is not possible to validate custom DH parameters.
@ -826,7 +775,6 @@
* MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
* MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
* MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256
* MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA
*/
#define MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
@ -850,7 +798,6 @@
* MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA
* MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256
* MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256
* MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA
*/
#define MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED
@ -876,7 +823,6 @@
* MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256
* MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256
* MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
* MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA
*/
#define MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
@ -902,7 +848,6 @@
* MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256
* MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
* MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
* MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
*
* \warning Using DHE constitutes a security risk as it
* is not possible to validate custom DH parameters.
@ -933,7 +878,6 @@
* MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
* MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256
* MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
* MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
*/
#define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
@ -956,7 +900,6 @@
* MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
* MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256
* MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256
* MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
*/
#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
@ -969,7 +912,6 @@
*
* This enables the following ciphersuites (if other requisites are
* enabled as well):
* MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
* MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
* MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
* MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
@ -992,7 +934,6 @@
*
* This enables the following ciphersuites (if other requisites are
* enabled as well):
* MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
* MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
* MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
* MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
@ -1872,16 +1813,6 @@
*/
#define MBEDTLS_VERSION_FEATURES
/**
* \def MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3
*
* If set, the X509 parser will not break-off when parsing an X509 certificate
* and encountering an extension in a v1 or v2 certificate.
*
* Uncomment to prevent an error.
*/
//#define MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3
/**
* \def MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION
*
@ -2356,19 +2287,6 @@
* Caller: library/pem.c
* library/cipher.c
*
* This module enables the following ciphersuites (if other requisites are
* enabled as well):
* MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
* MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
* MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
* MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
* MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
* MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA
* MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA
* MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA
* MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA
* MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA
*
* PEM_PARSE uses DES/3DES for decrypting encrypted keys.
*
* \warning DES is considered a weak cipher and its use constitutes a
@ -3384,27 +3302,10 @@
*/
//#define MBEDTLS_SSL_CID_OUT_LEN_MAX 32
/** \def MBEDTLS_SSL_CID_PADDING_GRANULARITY
/** \def MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY
*
* This option controls the use of record plaintext padding
* when using the Connection ID extension in DTLS 1.2.
*
* The padding will always be chosen so that the length of the
* padded plaintext is a multiple of the value of this option.
*
* Note: A value of \c 1 means that no padding will be used
* for outgoing records.
*
* Note: On systems lacking division instructions,
* a power of two should be preferred.
*
*/
//#define MBEDTLS_SSL_CID_PADDING_GRANULARITY 16
/** \def MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY
*
* This option controls the use of record plaintext padding
* in TLS 1.3.
* in TLS 1.3 and when using the Connection ID extension in DTLS 1.2.
*
* The padding will always be chosen so that the length of the
* padded plaintext is a multiple of the value of this option.
@ -3415,7 +3316,7 @@
* Note: On systems lacking division instructions,
* a power of two should be preferred.
*/
//#define MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY 1
//#define MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY 16
/** \def MBEDTLS_SSL_OUT_CONTENT_LEN
*

View File

@ -38,6 +38,30 @@
extern "C" {
#endif
/****************************************************************/
/* De facto synonyms */
/****************************************************************/
#if defined(PSA_WANT_ALG_ECDSA_ANY) && !defined(PSA_WANT_ALG_ECDSA)
#define PSA_WANT_ALG_ECDSA PSA_WANT_ALG_ECDSA_ANY
#elif !defined(PSA_WANT_ALG_ECDSA_ANY) && defined(PSA_WANT_ALG_ECDSA)
#define PSA_WANT_ALG_ECDSA_ANY PSA_WANT_ALG_ECDSA
#endif
#if defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN_RAW) && !defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN)
#define PSA_WANT_ALG_RSA_PKCS1V15_SIGN PSA_WANT_ALG_RSA_PKCS1V15_SIGN_RAW
#elif !defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN_RAW) && defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN)
#define PSA_WANT_ALG_RSA_PKCS1V15_SIGN_RAW PSA_WANT_ALG_RSA_PKCS1V15_SIGN
#endif
/****************************************************************/
/* Require built-in implementations based on PSA requirements */
/****************************************************************/
#if defined(MBEDTLS_PSA_CRYPTO_CONFIG)
#if defined(PSA_WANT_ALG_DETERMINISTIC_ECDSA)
@ -497,6 +521,12 @@ extern "C" {
#endif /* !MBEDTLS_PSA_ACCEL_ECC_SECP_K1_256 */
#endif /* PSA_WANT_ECC_SECP_K1_256 */
/****************************************************************/
/* Infer PSA requirements from Mbed TLS capabilities */
/****************************************************************/
#else /* MBEDTLS_PSA_CRYPTO_CONFIG */
/*
@ -522,6 +552,7 @@ extern "C" {
#if defined(MBEDTLS_ECDSA_C)
#define MBEDTLS_PSA_BUILTIN_ALG_ECDSA 1
#define PSA_WANT_ALG_ECDSA 1
#define PSA_WANT_ALG_ECDSA_ANY 1
// Only add in DETERMINISTIC support if ECDSA is also enabled
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
@ -586,6 +617,7 @@ extern "C" {
#define PSA_WANT_ALG_RSA_PKCS1V15_CRYPT 1
#define MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN 1
#define PSA_WANT_ALG_RSA_PKCS1V15_SIGN 1
#define PSA_WANT_ALG_RSA_PKCS1V15_SIGN_RAW 1
#endif /* MBEDTLSS_PKCS1_V15 */
#if defined(MBEDTLS_PKCS1_V21)
#define MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP 1

View File

@ -40,6 +40,25 @@
#include "mbedtls/ecp.h"
/*
* Mbed TLS supports two formats for ECDH contexts (#mbedtls_ecdh_context
* defined in `ecdh.h`). For most applications, the choice of format makes
* no difference, since all library functions can work with either format,
* except that the new format is incompatible with MBEDTLS_ECP_RESTARTABLE.
* The new format used when this option is disabled is smaller
* (56 bytes on a 32-bit platform). In future versions of the library, it
* will support alternative implementations of ECDH operations.
* The new format is incompatible with applications that access
* context fields directly and with restartable ECP operations.
*/
#if defined(MBEDTLS_ECP_RESTARTABLE)
#define MBEDTLS_ECDH_LEGACY_CONTEXT
#else
#undef MBEDTLS_ECDH_LEGACY_CONTEXT
#endif
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
#undef MBEDTLS_ECDH_LEGACY_CONTEXT
#include "everest/everest.h"

View File

@ -229,7 +229,7 @@ typedef struct mbedtls_ecp_group
int (*t_post)(mbedtls_ecp_point *, void *); /*!< Unused. */
void *t_data; /*!< Unused. */
mbedtls_ecp_point *T; /*!< Pre-computed points for ecp_mul_comb(). */
size_t T_size; /*!< The number of pre-computed points. */
size_t T_size; /*!< The number of dynamic allocated pre-computed points. */
}
mbedtls_ecp_group;
@ -276,15 +276,16 @@ mbedtls_ecp_group;
#if !defined(MBEDTLS_ECP_FIXED_POINT_OPTIM)
/*
* Trade memory for speed on fixed-point multiplication.
* Trade code size for speed on fixed-point multiplication.
*
* This speeds up repeated multiplication of the generator (that is, the
* multiplication in ECDSA signatures, and half of the multiplications in
* ECDSA verification and ECDHE) by a factor roughly 3 to 4.
*
* The cost is increasing EC peak memory usage by a factor roughly 2.
* For each n-bit Short Weierstrass curve that is enabled, this adds 4n bytes
* of code size if n < 384 and 8n otherwise.
*
* Change this value to 0 to reduce peak memory usage.
* Change this value to 0 to reduce code size.
*/
#define MBEDTLS_ECP_FIXED_POINT_OPTIM 1 /**< Enable fixed-point speed-up. */
#endif /* MBEDTLS_ECP_FIXED_POINT_OPTIM */

View File

@ -145,6 +145,7 @@
#define MBEDTLS_OID_AT_DN_QUALIFIER MBEDTLS_OID_AT "\x2E" /**< id-at-dnQualifier AttributeType:= {id-at 46} */
#define MBEDTLS_OID_AT_PSEUDONYM MBEDTLS_OID_AT "\x41" /**< id-at-pseudonym AttributeType:= {id-at 65} */
#define MBEDTLS_OID_UID "\x09\x92\x26\x89\x93\xF2\x2C\x64\x01\x01" /** id-domainComponent AttributeType:= {itu-t(0) data(9) pss(2342) ucl(19200300) pilot(100) pilotAttributeType(1) uid(1)} */
#define MBEDTLS_OID_DOMAIN_COMPONENT "\x09\x92\x26\x89\x93\xF2\x2C\x64\x01\x19" /** id-domainComponent AttributeType:= {itu-t(0) data(9) pss(2342) ucl(19200300) pilot(100) pilotAttributeType(1) domainComponent(25)} */
/*

View File

@ -125,14 +125,10 @@
*/
/* These are the high an low bytes of ProtocolVersion as defined by:
* - RFC 2246: ProtocolVersion version = { 3, 1 }; // TLS v1.0
* - RFC 4346: ProtocolVersion version = { 3, 2 }; // TLS v1.1
* - RFC 5246: ProtocolVersion version = { 3, 3 }; // TLS v1.2
* - RFC 8446: see section 4.2.1
*/
#define MBEDTLS_SSL_MAJOR_VERSION_3 3
#define MBEDTLS_SSL_MINOR_VERSION_1 1 /*!< TLS v1.0 deprecated */
#define MBEDTLS_SSL_MINOR_VERSION_2 2 /*!< TLS v1.1 deprecated */
#define MBEDTLS_SSL_MINOR_VERSION_3 3 /*!< TLS v1.2 */
#define MBEDTLS_SSL_MINOR_VERSION_4 4 /*!< TLS v1.3 (experimental) */
@ -257,12 +253,8 @@
#define MBEDTLS_SSL_CID_OUT_LEN_MAX 32
#endif
#if !defined(MBEDTLS_SSL_CID_PADDING_GRANULARITY)
#define MBEDTLS_SSL_CID_PADDING_GRANULARITY 16
#endif
#if !defined(MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY)
#define MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY 1
#if !defined(MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY)
#define MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY 16
#endif
/* \} name SECTION: Module settings */
@ -980,10 +972,8 @@ struct mbedtls_ssl_config
* Pointers
*/
/** Allowed ciphersuites per version. To access list's elements, please use
* \c mbedtls_ssl_get_protocol_version_ciphersuites
*/
const int *ciphersuite_list[3];
/** Allowed ciphersuites for (D)TLS 1.2 (0-terminated) */
const int *ciphersuite_list;
/** Callback for printing debug output */
void (*f_dbg)(void *, int, const char *, int, const char *);
@ -2512,17 +2502,6 @@ const mbedtls_ssl_session *mbedtls_ssl_get_session_pointer( const mbedtls_ssl_co
void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf,
const int *ciphersuites );
/**
* \brief Get ciphersuite for given protocol's minor version.
*
* \param conf The SSL configuration.
* \param prot_version Protocol version. One of MBEDTLS_SSL_MINOR_VERSION_x macros.
* \return Ciphersuites pointer if successful.
* \return \c NULL if no ciphersuites where found.
*/
const int *mbedtls_ssl_get_protocol_version_ciphersuites(
const mbedtls_ssl_config *conf, int prot_version );
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
#define MBEDTLS_SSL_UNEXPECTED_CID_IGNORE 0
#define MBEDTLS_SSL_UNEXPECTED_CID_FAIL 1
@ -2562,27 +2541,6 @@ int mbedtls_ssl_conf_cid( mbedtls_ssl_config *conf, size_t len,
int ignore_other_cids );
#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
/**
* \brief Set the list of allowed ciphersuites and the
* preference order for a specific version of the protocol.
* (Only useful on the server side)
*
* The ciphersuites array is not copied, and must remain
* valid for the lifetime of the ssl_config.
*
* \param conf SSL configuration
* \param ciphersuites 0-terminated list of allowed ciphersuites
* \param major Major version number (only MBEDTLS_SSL_MAJOR_VERSION_3
* supported)
* \param minor Minor version number (only MBEDTLS_SSL_MINOR_VERSION_3
* supported)
*
* \note With DTLS, use MBEDTLS_SSL_MINOR_VERSION_3 for DTLS 1.2
*/
void mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf,
const int *ciphersuites,
int major, int minor );
#if defined(MBEDTLS_X509_CRT_PARSE_C)
/**
* \brief Set the X.509 security profile used for verification
@ -2712,8 +2670,14 @@ int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf,
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
/**
* \brief Configure a pre-shared key (PSK) and identity
* to be used in PSK-based ciphersuites.
* \brief Configure pre-shared keys (PSKs) and their
* identities to be used in PSK-based ciphersuites.
*
* Only one PSK can be registered, through either
* mbedtls_ssl_conf_psk() or mbedtls_ssl_conf_psk_opaque().
* If you attempt to register more than one PSK, this function
* fails, though this may change in future versions, which
* may add support for multiple PSKs.
*
* \note This is mainly useful for clients. Servers will usually
* want to use \c mbedtls_ssl_conf_psk_cb() instead.
@ -2721,13 +2685,6 @@ int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf,
* \note A PSK set by \c mbedtls_ssl_set_hs_psk() in the PSK callback
* takes precedence over a PSK configured by this function.
*
* \warning Currently, clients can only register a single pre-shared key.
* Calling this function or mbedtls_ssl_conf_psk_opaque() more
* than once will overwrite values configured in previous calls.
* Support for setting multiple PSKs on clients and selecting
* one based on the identity hint is not a planned feature,
* but feedback is welcomed.
*
* \param conf The SSL configuration to register the PSK with.
* \param psk The pointer to the pre-shared key to use.
* \param psk_len The length of the pre-shared key in bytes.
@ -2740,7 +2697,9 @@ int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf,
* of the SSL configuration.
*
* \return \c 0 if successful.
* \return An \c MBEDTLS_ERR_SSL_XXX error code on failure.
* \return #MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE if no more PSKs
* can be configured. In this case, the old PSK(s) remain intact.
* \return Another negative error code on other kinds of failure.
*/
int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,
const unsigned char *psk, size_t psk_len,
@ -2748,8 +2707,14 @@ int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,
#if defined(MBEDTLS_USE_PSA_CRYPTO)
/**
* \brief Configure an opaque pre-shared key (PSK) and identity
* to be used in PSK-based ciphersuites.
* \brief Configure one or more opaque pre-shared keys (PSKs) and
* their identities to be used in PSK-based ciphersuites.
*
* Only one PSK can be registered, through either
* mbedtls_ssl_conf_psk() or mbedtls_ssl_conf_psk_opaque().
* If you attempt to register more than one PSK, this function
* fails, though this may change in future versions, which
* may add support for multiple PSKs.
*
* \note This is mainly useful for clients. Servers will usually
* want to use \c mbedtls_ssl_conf_psk_cb() instead.
@ -2758,13 +2723,6 @@ int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,
* the PSK callback takes precedence over an opaque PSK
* configured by this function.
*
* \warning Currently, clients can only register a single pre-shared key.
* Calling this function or mbedtls_ssl_conf_psk() more than
* once will overwrite values configured in previous calls.
* Support for setting multiple PSKs on clients and selecting
* one based on the identity hint is not a planned feature,
* but feedback is welcomed.
*
* \param conf The SSL configuration to register the PSK with.
* \param psk The identifier of the key slot holding the PSK.
* Until \p conf is destroyed or this function is successfully
@ -2781,7 +2739,9 @@ int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,
* SSL configuration.
*
* \return \c 0 if successful.
* \return An \c MBEDTLS_ERR_SSL_XXX error code on failure.
* \return #MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE if no more PSKs
* can be configured. In this case, the old PSK(s) remain intact.
* \return Another negative error code on other kinds of failure.
*/
int mbedtls_ssl_conf_psk_opaque( mbedtls_ssl_config *conf,
psa_key_id_t psk,
@ -3231,8 +3191,7 @@ void mbedtls_ssl_get_dtls_srtp_negotiation_result( const mbedtls_ssl_context *ss
*
* \param conf SSL configuration
* \param major Major version number (only MBEDTLS_SSL_MAJOR_VERSION_3 supported)
* \param minor Minor version number (MBEDTLS_SSL_MINOR_VERSION_1 and MBEDTLS_SSL_MINOR_VERSION_2,
* MBEDTLS_SSL_MINOR_VERSION_3 supported)
* \param minor Minor version number (only MBEDTLS_SSL_MINOR_VERSION_3 supported)
*/
void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor );
@ -3247,9 +3206,7 @@ void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int mino
*
* \param conf SSL configuration
* \param major Major version number (only MBEDTLS_SSL_MAJOR_VERSION_3 supported)
* \param minor Minor version number (MBEDTLS_SSL_MINOR_VERSION_1,
* MBEDTLS_SSL_MINOR_VERSION_2,
* MBEDTLS_SSL_MINOR_VERSION_3 supported)
* \param minor Minor version number (only MBEDTLS_SSL_MINOR_VERSION_3 supported)
*/
void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor );

View File

@ -42,10 +42,6 @@ extern "C" {
#define MBEDTLS_TLS_RSA_WITH_NULL_MD5 0x01 /**< Weak! */
#define MBEDTLS_TLS_RSA_WITH_NULL_SHA 0x02 /**< Weak! */
#define MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA 0x0A
#define MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA 0x16
#define MBEDTLS_TLS_PSK_WITH_NULL_SHA 0x2C /**< Weak! */
#define MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA 0x2D /**< Weak! */
#define MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA 0x2E /**< Weak! */
@ -68,15 +64,12 @@ extern "C" {
#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA 0x84
#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA 0x88
#define MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA 0x8B
#define MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA 0x8C
#define MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA 0x8D
#define MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA 0x8F
#define MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA 0x90
#define MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA 0x91
#define MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA 0x93
#define MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA 0x94
#define MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA 0x95
@ -114,22 +107,18 @@ extern "C" {
#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 0xC4 /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA 0xC001 /**< Weak! */
#define MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA 0xC003
#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0xC004
#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0xC005
#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA 0xC006 /**< Weak! */
#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA 0xC008
#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0xC009
#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0xC00A
#define MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA 0xC00B /**< Weak! */
#define MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA 0xC00D
#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA 0xC00E
#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA 0xC00F
#define MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA 0xC010 /**< Weak! */
#define MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA 0xC012
#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA 0xC013
#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA 0xC014
@ -151,7 +140,6 @@ extern "C" {
#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 0xC031 /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 0xC032 /**< TLS 1.2 */
#define MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA 0xC034
#define MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA 0xC035
#define MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA 0xC036
#define MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 0xC037

View File

@ -235,6 +235,7 @@ int mbedtls_x509write_csr_set_ns_cert_type( mbedtls_x509write_csr *ctx,
* \param ctx CSR context to use
* \param oid OID of the extension
* \param oid_len length of the OID
* \param critical Set to 1 to mark the extension as critical, 0 otherwise.
* \param val value of the extension OCTET STRING
* \param val_len length of the value data
*
@ -242,6 +243,7 @@ int mbedtls_x509write_csr_set_ns_cert_type( mbedtls_x509write_csr *ctx,
*/
int mbedtls_x509write_csr_set_extension( mbedtls_x509write_csr *ctx,
const char *oid, size_t oid_len,
int critical,
const unsigned char *val, size_t val_len );
/**

View File

@ -1005,7 +1005,7 @@ int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx,
#endif
#if defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_HAVE_X86)
if( aes_padlock_ace )
if( aes_padlock_ace > 0)
{
if( mbedtls_padlock_xcryptecb( ctx, mode, input, output ) == 0 )
return( 0 );
@ -1047,7 +1047,7 @@ int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx,
return( MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH );
#if defined(MBEDTLS_PADLOCK_C) && defined(MBEDTLS_HAVE_X86)
if( aes_padlock_ace )
if( aes_padlock_ace > 0 )
{
if( mbedtls_padlock_xcryptcbc( ctx, mode, length, iv, input, output ) == 0 )
return( 0 );

View File

@ -181,6 +181,27 @@ int mbedtls_mpi_shrink( mbedtls_mpi *X, size_t nblimbs )
return( 0 );
}
/* Resize X to have exactly n limbs and set it to 0. */
static int mbedtls_mpi_resize_clear( mbedtls_mpi *X, size_t limbs )
{
if( limbs == 0 )
{
mbedtls_mpi_free( X );
return( 0 );
}
else if( X->n == limbs )
{
memset( X->p, 0, limbs * ciL );
X->s = 1;
return( 0 );
}
else
{
mbedtls_mpi_free( X );
return( mbedtls_mpi_grow( X, limbs ) );
}
}
/*
* Copy the contents of Y into X
*/
@ -838,14 +859,7 @@ int mbedtls_mpi_read_binary_le( mbedtls_mpi *X,
size_t const limbs = CHARS_TO_LIMBS( buflen );
/* Ensure that target MPI has exactly the necessary number of limbs */
if( X->n != limbs )
{
mbedtls_mpi_free( X );
mbedtls_mpi_init( X );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, limbs ) );
}
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, limbs ) );
for( i = 0; i < buflen; i++ )
X->p[i / ciL] |= ((mbedtls_mpi_uint) buf[i]) << ((i % ciL) << 3);
@ -874,17 +888,11 @@ int mbedtls_mpi_read_binary( mbedtls_mpi *X, const unsigned char *buf, size_t bu
MPI_VALIDATE_RET( buflen == 0 || buf != NULL );
/* Ensure that target MPI has exactly the necessary number of limbs */
if( X->n != limbs )
{
mbedtls_mpi_free( X );
mbedtls_mpi_init( X );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, limbs ) );
}
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, limbs ) );
/* Avoid calling `memcpy` with NULL source argument,
/* Avoid calling `memcpy` with NULL source or destination argument,
* even if buflen is 0. */
if( buf != NULL )
if( buflen != 0 )
{
Xp = (unsigned char*) X->p;
memcpy( Xp + overhead, buf, buflen );
@ -2395,6 +2403,33 @@ cleanup:
return( ret );
}
/* Fill X with n_bytes random bytes.
* X must already have room for those bytes.
* The ordering of the bytes returned from the RNG is suitable for
* deterministic ECDSA (see RFC 6979 §3.3 and mbedtls_mpi_random()).
* The size and sign of X are unchanged.
* n_bytes must not be 0.
*/
static int mpi_fill_random_internal(
mbedtls_mpi *X, size_t n_bytes,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
const size_t limbs = CHARS_TO_LIMBS( n_bytes );
const size_t overhead = ( limbs * ciL ) - n_bytes;
if( X->n < limbs )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
memset( X->p, 0, overhead );
memset( (unsigned char *) X->p + limbs * ciL, 0, ( X->n - limbs ) * ciL );
MBEDTLS_MPI_CHK( f_rng( p_rng, (unsigned char *) X->p + overhead, n_bytes ) );
mpi_bigendian_to_host( X->p, limbs );
cleanup:
return( ret );
}
/*
* Fill X with size bytes of random.
*
@ -2408,25 +2443,84 @@ int mbedtls_mpi_fill_random( mbedtls_mpi *X, size_t size,
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t const limbs = CHARS_TO_LIMBS( size );
size_t const overhead = ( limbs * ciL ) - size;
unsigned char *Xp;
MPI_VALIDATE_RET( X != NULL );
MPI_VALIDATE_RET( f_rng != NULL );
/* Ensure that target MPI has exactly the necessary number of limbs */
if( X->n != limbs )
MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, limbs ) );
if( size == 0 )
return( 0 );
ret = mpi_fill_random_internal( X, size, f_rng, p_rng );
cleanup:
return( ret );
}
int mbedtls_mpi_random( mbedtls_mpi *X,
mbedtls_mpi_sint min,
const mbedtls_mpi *N,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
int count;
unsigned cmp = 0;
size_t n_bits = mbedtls_mpi_bitlen( N );
size_t n_bytes = ( n_bits + 7 ) / 8;
if( min < 0 )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
if( mbedtls_mpi_cmp_int( N, min ) <= 0 )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
/*
* When min == 0, each try has at worst a probability 1/2 of failing
* (the msb has a probability 1/2 of being 0, and then the result will
* be < N), so after 30 tries failure probability is a most 2**(-30).
*
* When N is just below a power of 2, as is the case when generating
* a random scalar on most elliptic curves, 1 try is enough with
* overwhelming probability. When N is just above a power of 2,
* as when generating a random scalar on secp224k1, each try has
* a probability of failing that is almost 1/2.
*
* The probabilities are almost the same if min is nonzero but negligible
* compared to N. This is always the case when N is crypto-sized, but
* it's convenient to support small N for testing purposes. When N
* is small, use a higher repeat count, otherwise the probability of
* failure is macroscopic.
*/
count = ( n_bytes > 4 ? 30 : 250 );
/* Ensure that target MPI has exactly the same number of limbs
* as the upper bound, even if the upper bound has leading zeros.
* This is necessary for the mbedtls_mpi_lt_mpi_ct() check. */
MBEDTLS_MPI_CHK( mbedtls_mpi_resize_clear( X, N->n ) );
/*
* Match the procedure given in RFC 6979 §3.3 (deterministic ECDSA)
* when f_rng is a suitably parametrized instance of HMAC_DRBG:
* - use the same byte ordering;
* - keep the leftmost n_bits bits of the generated octet string;
* - try until result is in the desired range.
* This also avoids any bias, which is especially important for ECDSA.
*/
do
{
mbedtls_mpi_free( X );
mbedtls_mpi_init( X );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, limbs ) );
MBEDTLS_MPI_CHK( mpi_fill_random_internal( X, n_bytes, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( X, 8 * n_bytes - n_bits ) );
if( --count == 0 )
{
ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_lt_mpi_ct( X, N, &cmp ) );
}
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );
Xp = (unsigned char*) X->p;
MBEDTLS_MPI_CHK( f_rng( p_rng, Xp + overhead, size ) );
mpi_bigendian_to_host( X->p, limbs );
while( mbedtls_mpi_cmp_int( X, min ) < 0 || cmp != 1 );
cleanup:
return( ret );

View File

@ -100,22 +100,21 @@ static int dhm_read_bignum( mbedtls_mpi *X,
*/
static int dhm_check_range( const mbedtls_mpi *param, const mbedtls_mpi *P )
{
mbedtls_mpi L, U;
mbedtls_mpi U;
int ret = 0;
mbedtls_mpi_init( &L ); mbedtls_mpi_init( &U );
mbedtls_mpi_init( &U );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &L, 2 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &U, P, 2 ) );
if( mbedtls_mpi_cmp_mpi( param, &L ) < 0 ||
if( mbedtls_mpi_cmp_int( param, 2 ) < 0 ||
mbedtls_mpi_cmp_mpi( param, &U ) > 0 )
{
ret = MBEDTLS_ERR_DHM_BAD_INPUT_DATA;
}
cleanup:
mbedtls_mpi_free( &L ); mbedtls_mpi_free( &U );
mbedtls_mpi_free( &U );
return( ret );
}
@ -151,38 +150,44 @@ int mbedtls_dhm_read_params( mbedtls_dhm_context *ctx,
}
/*
* Setup and write the ServerKeyExchange parameters
* Pick a random R in the range [2, M-2] for blinding or key generation.
*/
int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size,
unsigned char *output, size_t *olen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
static int dhm_random_below( mbedtls_mpi *R, const mbedtls_mpi *M,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
int ret, count = 0;
size_t n1, n2, n3;
unsigned char *p;
DHM_VALIDATE_RET( ctx != NULL );
DHM_VALIDATE_RET( output != NULL );
DHM_VALIDATE_RET( olen != NULL );
DHM_VALIDATE_RET( f_rng != NULL );
int ret;
MBEDTLS_MPI_CHK( mbedtls_mpi_random( R, 3, M, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( R, R, 1 ) );
cleanup:
return( ret );
}
static int dhm_make_common( mbedtls_dhm_context *ctx, int x_size,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = 0;
if( mbedtls_mpi_cmp_int( &ctx->P, 0 ) == 0 )
return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );
if( x_size < 0 )
return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );
/*
* Generate X as large as possible ( < P )
*/
do
if( (unsigned) x_size < mbedtls_mpi_size( &ctx->P ) )
{
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 )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &ctx->X, 1 ) );
if( count++ > 10 )
return( MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED );
}
while( dhm_check_range( &ctx->X, &ctx->P ) != 0 );
else
{
/* Generate X as large as possible ( <= P - 2 ) */
ret = dhm_random_below( &ctx->X, &ctx->P, f_rng, p_rng );
if( ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )
return( MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED );
if( ret != 0 )
return( ret );
}
/*
* Calculate GX = G^X mod P
@ -193,8 +198,33 @@ int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size,
if( ( ret = dhm_check_range( &ctx->GX, &ctx->P ) ) != 0 )
return( ret );
cleanup:
return( ret );
}
/*
* Setup and write the ServerKeyExchange parameters
*/
int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size,
unsigned char *output, size_t *olen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
size_t n1, n2, n3;
unsigned char *p;
DHM_VALIDATE_RET( ctx != NULL );
DHM_VALIDATE_RET( output != NULL );
DHM_VALIDATE_RET( olen != NULL );
DHM_VALIDATE_RET( f_rng != NULL );
ret = dhm_make_common( ctx, x_size, f_rng, p_rng );
if( ret != 0 )
goto cleanup;
/*
* export P, G, GX
* Export P, G, GX. RFC 5246 §4.4 states that "leading zero octets are
* not required". We omit leading zeros for compactness.
*/
#define DHM_MPI_EXPORT( X, n ) \
do { \
@ -220,11 +250,9 @@ int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size,
ctx->len = n1;
cleanup:
if( ret != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED, ret ) );
return( 0 );
if( ret != 0 && ret > -128 )
ret = MBEDTLS_ERROR_ADD( MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED, ret );
return( ret );
}
/*
@ -276,7 +304,7 @@ int mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret, count = 0;
int ret;
DHM_VALIDATE_RET( ctx != NULL );
DHM_VALIDATE_RET( output != NULL );
DHM_VALIDATE_RET( f_rng != NULL );
@ -284,62 +312,17 @@ int mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size,
if( olen < 1 || olen > ctx->len )
return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );
if( mbedtls_mpi_cmp_int( &ctx->P, 0 ) == 0 )
return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );
/*
* generate X and calculate GX = G^X mod P
*/
do
{
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 )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &ctx->X, 1 ) );
if( count++ > 10 )
return( MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED );
}
while( dhm_check_range( &ctx->X, &ctx->P ) != 0 );
MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &ctx->GX, &ctx->G, &ctx->X,
&ctx->P , &ctx->RP ) );
if( ( ret = dhm_check_range( &ctx->GX, &ctx->P ) ) != 0 )
return( ret );
ret = dhm_make_common( ctx, x_size, f_rng, p_rng );
if( ret == MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED )
return( MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED );
if( ret != 0 )
goto cleanup;
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->GX, output, olen ) );
cleanup:
if( ret != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED, ret ) );
return( 0 );
}
/*
* Pick a random R in the range [2, M) for blinding purposes
*/
static int dhm_random_below( mbedtls_mpi *R, const mbedtls_mpi *M,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
int ret, count;
count = 0;
do
{
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( R, mbedtls_mpi_size( M ), f_rng, p_rng ) );
while( mbedtls_mpi_cmp_mpi( R, M ) >= 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( R, 1 ) );
if( count++ > 10 )
return( MBEDTLS_ERR_MPI_NOT_ACCEPTABLE );
}
while( mbedtls_mpi_cmp_int( R, 1 ) <= 0 );
cleanup:
if( ret != 0 && ret > -128 )
ret = MBEDTLS_ERROR_ADD( MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED, ret );
return( ret );
}
@ -390,7 +373,7 @@ static int dhm_update_blinding( mbedtls_dhm_context *ctx,
* We need to generate blinding values from scratch
*/
/* Vi = random( 2, P-1 ) */
/* Vi = random( 2, P-2 ) */
MBEDTLS_MPI_CHK( dhm_random_below( &ctx->Vi, &ctx->P, f_rng, p_rng ) );
/* Vf = Vi^-X mod P
@ -454,8 +437,9 @@ int mbedtls_dhm_calc_secret( mbedtls_dhm_context *ctx,
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &ctx->K, &ctx->K, &ctx->P ) );
}
/* Output the secret without any leading zero byte. This is mandatory
* for TLS per RFC 5246 §8.1.2. */
*olen = mbedtls_mpi_size( &ctx->K );
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->K, output, *olen ) );
cleanup:

View File

@ -728,6 +728,18 @@ void mbedtls_ecp_point_free( mbedtls_ecp_point *pt )
mbedtls_mpi_free( &( pt->Z ) );
}
/*
* Check that the comb table (grp->T) is static initialized.
*/
static int ecp_group_is_static_comb_table( const mbedtls_ecp_group *grp ) {
#if MBEDTLS_ECP_FIXED_POINT_OPTIM == 1
return grp->T != NULL && grp->T_size == 0;
#else
(void) grp;
return 0;
#endif
}
/*
* Unallocate (the components of) a group
*/
@ -747,7 +759,7 @@ void mbedtls_ecp_group_free( mbedtls_ecp_group *grp )
mbedtls_mpi_free( &grp->N );
}
if( grp->T != NULL )
if( !ecp_group_is_static_comb_table(grp) && grp->T != NULL )
{
for( i = 0; i < grp->T_size; i++ )
mbedtls_ecp_point_free( &grp->T[i] );
@ -1701,26 +1713,11 @@ static int ecp_randomize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *p
#else
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi l, ll;
int count = 0;
size_t p_size = ( grp->pbits + 7 ) / 8;
mbedtls_mpi_init( &l ); mbedtls_mpi_init( &ll );
/* Generate l such that 1 < l < p */
do
{
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &l, p_size, f_rng, p_rng ) );
while( mbedtls_mpi_cmp_mpi( &l, &grp->P ) >= 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &l, 1 ) );
if( count++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
}
while( mbedtls_mpi_cmp_int( &l, 1 ) <= 0 );
MBEDTLS_MPI_CHK( mbedtls_mpi_random( &l, 2, &grp->P, f_rng, p_rng ) );
/* Z = l * Z */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &pt->Z, &pt->Z, &l ) );
@ -1736,6 +1733,8 @@ static int ecp_randomize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *p
cleanup:
mbedtls_mpi_free( &l ); mbedtls_mpi_free( &ll );
if( ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
return( ret );
#endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) */
}
@ -2245,11 +2244,16 @@ static unsigned char ecp_pick_window_size( const mbedtls_ecp_group *grp,
w++;
/*
* Make sure w is within bounds.
* If static comb table may not be used (!p_eq_g) or static comb table does
* not exists, make sure w is within bounds.
* (The last test is useful only for very small curves in the test suite.)
*
* The user reduces MBEDTLS_ECP_WINDOW_SIZE does not changes the size of
* static comb table, because the size of static comb table is fixed when
* it is generated.
*/
#if( MBEDTLS_ECP_WINDOW_SIZE < 6 )
if( w > MBEDTLS_ECP_WINDOW_SIZE )
if( (!p_eq_g || !ecp_group_is_static_comb_table(grp)) && w > MBEDTLS_ECP_WINDOW_SIZE )
w = MBEDTLS_ECP_WINDOW_SIZE;
#endif
if( w >= grp->nbits )
@ -2485,25 +2489,10 @@ static int ecp_randomize_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P
#else
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi l;
int count = 0;
size_t p_size = ( grp->pbits + 7 ) / 8;
mbedtls_mpi_init( &l );
/* Generate l such that 1 < l < p */
do
{
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &l, p_size, f_rng, p_rng ) );
while( mbedtls_mpi_cmp_mpi( &l, &grp->P ) >= 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &l, 1 ) );
if( count++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
}
while( mbedtls_mpi_cmp_int( &l, 1 ) <= 0 );
MBEDTLS_MPI_CHK( mbedtls_mpi_random( &l, 2, &grp->P, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &P->X, &P->X, &l ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &P->Z, &P->Z, &l ) );
@ -2511,6 +2500,8 @@ static int ecp_randomize_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P
cleanup:
mbedtls_mpi_free( &l );
if( ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
return( ret );
#endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT) */
}
@ -3040,6 +3031,56 @@ int mbedtls_ecp_check_privkey( const mbedtls_ecp_group *grp,
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
}
#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
MBEDTLS_STATIC_TESTABLE
int mbedtls_ecp_gen_privkey_mx( size_t high_bit,
mbedtls_mpi *d,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
size_t n_random_bytes = high_bit / 8 + 1;
/* [Curve25519] page 5 */
/* Generate a (high_bit+1)-bit random number by generating just enough
* random bytes, then shifting out extra bits from the top (necessary
* when (high_bit+1) is not a multiple of 8). */
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_random_bytes,
f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_random_bytes - high_bit - 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, high_bit, 1 ) );
/* Make sure the last two bits are unset for Curve448, three bits for
Curve25519 */
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 0, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 1, 0 ) );
if( high_bit == 254 )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 2, 0 ) );
}
cleanup:
return( ret );
}
#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
static int mbedtls_ecp_gen_privkey_sw(
const mbedtls_mpi *N, mbedtls_mpi *d,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
int ret = mbedtls_mpi_random( d, 1, N, f_rng, p_rng );
switch( ret )
{
case MBEDTLS_ERR_MPI_NOT_ACCEPTABLE:
return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
default:
return( ret );
}
}
#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
/*
* Generate a private key
*/
@ -3048,89 +3089,21 @@ int mbedtls_ecp_gen_privkey( const mbedtls_ecp_group *grp,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
size_t n_size;
ECP_VALIDATE_RET( grp != NULL );
ECP_VALIDATE_RET( d != NULL );
ECP_VALIDATE_RET( f_rng != NULL );
n_size = ( grp->nbits + 7 ) / 8;
#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
{
/* [M225] page 5 */
size_t b;
do {
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );
} while( mbedtls_mpi_bitlen( d ) == 0);
/* Make sure the most significant bit is nbits */
b = mbedtls_mpi_bitlen( d ) - 1; /* mbedtls_mpi_bitlen is one-based */
if( b > grp->nbits )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, b - grp->nbits ) );
else
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, grp->nbits, 1 ) );
/* Make sure the last two bits are unset for Curve448, three bits for
Curve25519 */
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 0, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 1, 0 ) );
if( grp->nbits == 254 )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 2, 0 ) );
}
}
return( mbedtls_ecp_gen_privkey_mx( grp->nbits, d, f_rng, p_rng ) );
#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
{
/* SEC1 3.2.1: Generate d such that 1 <= n < N */
int count = 0;
unsigned cmp = 0;
/*
* Match the procedure given in RFC 6979 (deterministic ECDSA):
* - use the same byte ordering;
* - keep the leftmost nbits bits of the generated octet string;
* - try until result is in the desired range.
* This also avoids any biais, which is especially important for ECDSA.
*/
do
{
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_size - grp->nbits ) );
/*
* Each try has at worst a probability 1/2 of failing (the msb has
* a probability 1/2 of being 0, and then the result will be < N),
* so after 30 tries failure probability is a most 2**(-30).
*
* For most curves, 1 try is enough with overwhelming probability,
* since N starts with a lot of 1s in binary, but some curves
* such as secp224k1 are actually very close to the worst case.
*/
if( ++count > 30 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
ret = mbedtls_mpi_lt_mpi_ct( d, &grp->N, &cmp );
if( ret != 0 )
{
goto cleanup;
}
}
while( mbedtls_mpi_cmp_int( d, 1 ) < 0 || cmp != 1 );
}
return( mbedtls_ecp_gen_privkey_sw( &grp->N, d, f_rng, p_rng ) );
#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
cleanup:
return( ret );
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
}
/*

File diff suppressed because it is too large Load Diff

View File

@ -27,6 +27,7 @@
#define MBEDTLS_ECP_INVASIVE_H
#include "common.h"
#include "mbedtls/bignum.h"
#include "mbedtls/ecp.h"
#if defined(MBEDTLS_TEST_HOOKS) && defined(MBEDTLS_ECP_C)
@ -46,6 +47,35 @@
void mbedtls_ecp_fix_negative( mbedtls_mpi *N, signed char c, size_t bits );
#endif
#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
/** Generate a private key on a Montgomery curve (Curve25519 or Curve448).
*
* This function implements key generation for the set of secret keys
* specified in [Curve25519] p. 5 and in [Curve448]. The resulting value
* has the lower bits masked but is not necessarily canonical.
*
* \note - [Curve25519] http://cr.yp.to/ecdh/curve25519-20060209.pdf
* - [RFC7748] https://tools.ietf.org/html/rfc7748
*
* \p high_bit The position of the high-order bit of the key to generate.
* This is the bit-size of the key minus 1:
* 254 for Curve25519 or 447 for Curve448.
* \param d The randomly generated key. This is a number of size
* exactly \p n_bits + 1 bits, with the least significant bits
* masked as specified in [Curve25519] and in [RFC7748] §5.
* \param f_rng The RNG function.
* \param p_rng The RNG context to be passed to \p f_rng.
*
* \return \c 0 on success.
* \return \c MBEDTLS_ERR_ECP_xxx or MBEDTLS_ERR_MPI_xxx on failure.
*/
int mbedtls_ecp_gen_privkey_mx( size_t n_bits,
mbedtls_mpi *d,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
#endif /* MBEDTLS_TEST_HOOKS && MBEDTLS_ECP_C */
#endif /* MBEDTLS_ECP_INVASIVE_H */

View File

@ -189,8 +189,6 @@ int mbedtls_nist_kw_wrap( mbedtls_nist_kw_context *ctx,
uint64_t t = 0;
unsigned char outbuff[KW_SEMIBLOCK_LENGTH * 2];
unsigned char inbuff[KW_SEMIBLOCK_LENGTH * 2];
unsigned char *R2 = output + KW_SEMIBLOCK_LENGTH;
unsigned char *A = output;
*out_len = 0;
/*
@ -266,6 +264,9 @@ int mbedtls_nist_kw_wrap( mbedtls_nist_kw_context *ctx,
}
else
{
unsigned char *R2 = output + KW_SEMIBLOCK_LENGTH;
unsigned char *A = output;
/*
* Do the wrapping function W, as defined in RFC 3394 section 2.2.1
*/
@ -329,7 +330,7 @@ static int unwrap( mbedtls_nist_kw_context *ctx,
uint64_t t = 0;
unsigned char outbuff[KW_SEMIBLOCK_LENGTH * 2];
unsigned char inbuff[KW_SEMIBLOCK_LENGTH * 2];
unsigned char *R = output + ( semiblocks - 2 ) * KW_SEMIBLOCK_LENGTH;
unsigned char *R = NULL;
*out_len = 0;
if( semiblocks < MIN_SEMIBLOCKS_COUNT )
@ -339,6 +340,7 @@ static int unwrap( mbedtls_nist_kw_context *ctx,
memcpy( A, input, KW_SEMIBLOCK_LENGTH );
memmove( output, input + KW_SEMIBLOCK_LENGTH, ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH );
R = output + ( semiblocks - 2 ) * KW_SEMIBLOCK_LENGTH;
/* Calculate intermediate values */
for( t = s; t >= 1; t-- )

View File

@ -237,6 +237,10 @@ static const oid_x520_attr_t oid_x520_attr_type[] =
OID_DESCRIPTOR( MBEDTLS_OID_AT_PSEUDONYM, "id-at-pseudonym", "Pseudonym" ),
"pseudonym",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_UID, "id-uid", "User Id" ),
"uid",
},
{
OID_DESCRIPTOR( MBEDTLS_OID_DOMAIN_COMPONENT, "id-domainComponent", "Domain component" ),
"DC",

View File

@ -31,6 +31,7 @@
#include "mbedtls/ssl_ciphersuites.h"
#include "mbedtls/ssl.h"
#include "ssl_misc.h"
#include <string.h>
@ -254,18 +255,6 @@ static const int ciphersuite_preference[] =
MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256,
MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256,
/* 3DES suites */
MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA,
MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA,
MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA,
MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,
MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,
MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA,
MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA,
/* NULL suites */
MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA,
MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA,
@ -471,18 +460,6 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif /* MBEDTLS_GCM_C */
#endif /* MBEDTLS_CAMELLIA_C */
#if defined(MBEDTLS_DES_C)
#if defined(MBEDTLS_CIPHER_MODE_CBC)
#if defined(MBEDTLS_SHA1_C)
{ MBEDTLS_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, "TLS-ECDHE-ECDSA-WITH-3DES-EDE-CBC-SHA",
MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif /* MBEDTLS_SHA1_C */
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#endif /* MBEDTLS_DES_C */
#if defined(MBEDTLS_CIPHER_NULL_CIPHER)
#if defined(MBEDTLS_SHA1_C)
{ MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA, "TLS-ECDHE-ECDSA-WITH-NULL-SHA",
@ -580,18 +557,6 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif /* MBEDTLS_GCM_C */
#endif /* MBEDTLS_CAMELLIA_C */
#if defined(MBEDTLS_DES_C)
#if defined(MBEDTLS_CIPHER_MODE_CBC)
#if defined(MBEDTLS_SHA1_C)
{ MBEDTLS_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, "TLS-ECDHE-RSA-WITH-3DES-EDE-CBC-SHA",
MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif /* MBEDTLS_SHA1_C */
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#endif /* MBEDTLS_DES_C */
#if defined(MBEDTLS_CIPHER_NULL_CIPHER)
#if defined(MBEDTLS_SHA1_C)
{ MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA, "TLS-ECDHE-RSA-WITH-NULL-SHA",
@ -726,17 +691,6 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif /* MBEDTLS_GCM_C */
#endif /* MBEDTLS_CAMELLIA_C */
#if defined(MBEDTLS_DES_C)
#if defined(MBEDTLS_CIPHER_MODE_CBC)
#if defined(MBEDTLS_SHA1_C)
{ MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, "TLS-DHE-RSA-WITH-3DES-EDE-CBC-SHA",
MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif /* MBEDTLS_SHA1_C */
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#endif /* MBEDTLS_DES_C */
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
@ -863,18 +817,6 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif /* MBEDTLS_GCM_C */
#endif /* MBEDTLS_CAMELLIA_C */
#if defined(MBEDTLS_DES_C)
#if defined(MBEDTLS_CIPHER_MODE_CBC)
#if defined(MBEDTLS_SHA1_C)
{ MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA, "TLS-RSA-WITH-3DES-EDE-CBC-SHA",
MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif /* MBEDTLS_SHA1_C */
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#endif /* MBEDTLS_DES_C */
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)
@ -963,18 +905,6 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif /* MBEDTLS_GCM_C */
#endif /* MBEDTLS_CAMELLIA_C */
#if defined(MBEDTLS_DES_C)
#if defined(MBEDTLS_CIPHER_MODE_CBC)
#if defined(MBEDTLS_SHA1_C)
{ MBEDTLS_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, "TLS-ECDH-RSA-WITH-3DES-EDE-CBC-SHA",
MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_RSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif /* MBEDTLS_SHA1_C */
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#endif /* MBEDTLS_DES_C */
#if defined(MBEDTLS_CIPHER_NULL_CIPHER)
#if defined(MBEDTLS_SHA1_C)
{ MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA, "TLS-ECDH-RSA-WITH-NULL-SHA",
@ -1072,18 +1002,6 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif /* MBEDTLS_GCM_C */
#endif /* MBEDTLS_CAMELLIA_C */
#if defined(MBEDTLS_DES_C)
#if defined(MBEDTLS_CIPHER_MODE_CBC)
#if defined(MBEDTLS_SHA1_C)
{ MBEDTLS_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, "TLS-ECDH-ECDSA-WITH-3DES-EDE-CBC-SHA",
MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif /* MBEDTLS_SHA1_C */
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#endif /* MBEDTLS_DES_C */
#if defined(MBEDTLS_CIPHER_NULL_CIPHER)
#if defined(MBEDTLS_SHA1_C)
{ MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA, "TLS-ECDH-ECDSA-WITH-NULL-SHA",
@ -1208,18 +1126,6 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif /* MBEDTLS_GCM_C */
#endif /* MBEDTLS_CAMELLIA_C */
#if defined(MBEDTLS_DES_C)
#if defined(MBEDTLS_CIPHER_MODE_CBC)
#if defined(MBEDTLS_SHA1_C)
{ MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA, "TLS-PSK-WITH-3DES-EDE-CBC-SHA",
MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif /* MBEDTLS_SHA1_C */
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#endif /* MBEDTLS_DES_C */
#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
@ -1335,18 +1241,6 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif /* MBEDTLS_GCM_C */
#endif /* MBEDTLS_CAMELLIA_C */
#if defined(MBEDTLS_DES_C)
#if defined(MBEDTLS_CIPHER_MODE_CBC)
#if defined(MBEDTLS_SHA1_C)
{ MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA, "TLS-DHE-PSK-WITH-3DES-EDE-CBC-SHA",
MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_DHE_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif /* MBEDTLS_SHA1_C */
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#endif /* MBEDTLS_DES_C */
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
@ -1405,18 +1299,6 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#endif /* MBEDTLS_CAMELLIA_C */
#if defined(MBEDTLS_DES_C)
#if defined(MBEDTLS_CIPHER_MODE_CBC)
#if defined(MBEDTLS_SHA1_C)
{ MBEDTLS_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA, "TLS-ECDHE-PSK-WITH-3DES-EDE-CBC-SHA",
MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif /* MBEDTLS_SHA1_C */
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#endif /* MBEDTLS_DES_C */
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
@ -1510,18 +1392,6 @@ static const mbedtls_ssl_ciphersuite_t ciphersuite_definitions[] =
#endif /* MBEDTLS_GCM_C */
#endif /* MBEDTLS_CAMELLIA_C */
#if defined(MBEDTLS_DES_C)
#if defined(MBEDTLS_CIPHER_MODE_CBC)
#if defined(MBEDTLS_SHA1_C)
{ MBEDTLS_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA, "TLS-RSA-PSK-WITH-3DES-EDE-CBC-SHA",
MBEDTLS_CIPHER_DES_EDE3_CBC, MBEDTLS_MD_SHA1, MBEDTLS_KEY_EXCHANGE_RSA_PSK,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1,
MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3,
0 },
#endif /* MBEDTLS_SHA1_C */
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#endif /* MBEDTLS_DES_C */
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
@ -2047,14 +1917,6 @@ static int ciphersuite_is_removed( const mbedtls_ssl_ciphersuite_t *cs_info )
{
(void)cs_info;
#if defined(MBEDTLS_REMOVE_3DES_CIPHERSUITES)
if( cs_info->cipher == MBEDTLS_CIPHER_DES_EDE3_ECB ||
cs_info->cipher == MBEDTLS_CIPHER_DES_EDE3_CBC )
{
return( 1 );
}
#endif /* MBEDTLS_REMOVE_3DES_CIPHERSUITES */
return( 0 );
}

View File

@ -1155,8 +1155,7 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl )
/*
* Ciphersuite list
*/
ciphersuites = mbedtls_ssl_get_protocol_version_ciphersuites( ssl->conf,
ssl->minor_ver );
ciphersuites = ssl->conf->ciphersuite_list;
/* Skip writing ciphersuite length for now */
n = 0;
@ -2244,7 +2243,7 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl )
i = 0;
while( 1 )
{
if( mbedtls_ssl_get_protocol_version_ciphersuites( ssl->conf, ssl->minor_ver )[i] == 0 )
if( ssl->conf->ciphersuite_list[i] == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message(
@ -2254,7 +2253,7 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl )
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
if( mbedtls_ssl_get_protocol_version_ciphersuites( ssl->conf, ssl->minor_ver )[i++] ==
if( ssl->conf->ciphersuite_list[i++] ==
ssl->session_negotiate->ciphersuite )
{
break;

View File

@ -65,6 +65,16 @@
#define inline __inline
#endif
/* Legacy minor version numbers as defined by:
* - RFC 2246: ProtocolVersion version = { 3, 1 }; // TLS v1.0
* - RFC 4346: ProtocolVersion version = { 3, 2 }; // TLS v1.1
*
* We no longer support these versions, but some code still references those
* constants, for keep them for now until we clean up that code.
*/
#define MBEDTLS_SSL_MINOR_VERSION_1 1
#define MBEDTLS_SSL_MINOR_VERSION_2 2
/* Determine minimum supported version */
#define MBEDTLS_SSL_MIN_MAJOR_VERSION MBEDTLS_SSL_MAJOR_VERSION_3
@ -164,7 +174,7 @@
#endif
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
#define MBEDTLS_SSL_MAX_CID_EXPANSION MBEDTLS_SSL_CID_PADDING_GRANULARITY
#define MBEDTLS_SSL_MAX_CID_EXPANSION MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY
#else
#define MBEDTLS_SSL_MAX_CID_EXPANSION 0
#endif

View File

@ -579,7 +579,7 @@ int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl,
{
size_t padding =
ssl_compute_padding_length( rec->data_len,
MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY );
MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY );
if( ssl_build_inner_plaintext( data,
&rec->data_len,
post_avail,
@ -605,7 +605,7 @@ int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl,
{
size_t padding =
ssl_compute_padding_length( rec->data_len,
MBEDTLS_SSL_CID_PADDING_GRANULARITY );
MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY );
/*
* Wrap plaintext into DTLSInnerPlaintext structure.
* See ssl_build_inner_plaintext() for more information.

View File

@ -1870,7 +1870,7 @@ read_record_header:
* and certificate from the SNI callback triggered by the SNI extension.)
*/
got_common_suite = 0;
ciphersuites = mbedtls_ssl_get_protocol_version_ciphersuites( ssl->conf, ssl->minor_ver );
ciphersuites = ssl->conf->ciphersuite_list;
ciphersuite_info = NULL;
#if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE)
for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 )

View File

@ -3514,73 +3514,10 @@ int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session
}
#endif /* MBEDTLS_SSL_CLI_C */
static int protocol_version_to_ciphersuites_list_index(int prot_version)
{
switch(prot_version) {
case MBEDTLS_SSL_MINOR_VERSION_1:
return 0;
case MBEDTLS_SSL_MINOR_VERSION_2:
return 1;
case MBEDTLS_SSL_MINOR_VERSION_3:
return 2;
default:
return -1;
};
}
static void set_protocol_version_ciphersuites( mbedtls_ssl_config *conf,
int prot_version,
const int* ciphersuites )
{
int ciphersuite_list_index =
protocol_version_to_ciphersuites_list_index(prot_version);
if ( ciphersuite_list_index >= 0 &&
(unsigned int)ciphersuite_list_index <
sizeof(conf->ciphersuite_list)/sizeof(conf->ciphersuite_list[0]) )
{
conf->ciphersuite_list[ciphersuite_list_index] = ciphersuites;
}
}
void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf,
const int *ciphersuites )
{
set_protocol_version_ciphersuites(conf, MBEDTLS_SSL_MINOR_VERSION_1,
ciphersuites);
set_protocol_version_ciphersuites(conf, MBEDTLS_SSL_MINOR_VERSION_2,
ciphersuites);
set_protocol_version_ciphersuites(conf, MBEDTLS_SSL_MINOR_VERSION_3,
ciphersuites);
}
const int *mbedtls_ssl_get_protocol_version_ciphersuites(
const mbedtls_ssl_config *conf, int prot_version )
{
int ciphersuite_list_index =
protocol_version_to_ciphersuites_list_index(prot_version);
if ( ciphersuite_list_index >= 0 &&
(unsigned int)ciphersuite_list_index <
sizeof(conf->ciphersuite_list)/sizeof(conf->ciphersuite_list[0]) )
{
return conf->ciphersuite_list[ciphersuite_list_index];
}
else
{
return NULL;
}
}
void mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf,
const int *ciphersuites,
int major, int minor )
{
if( major != MBEDTLS_SSL_MAJOR_VERSION_3 )
return;
if( minor != MBEDTLS_SSL_MINOR_VERSION_3 )
return;
set_protocol_version_ciphersuites(conf, minor, ciphersuites);
conf->ciphersuite_list = ciphersuites;
}
#if defined(MBEDTLS_X509_CRT_PARSE_C)
@ -3721,6 +3658,19 @@ int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl,
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
static int ssl_conf_psk_is_configured( mbedtls_ssl_config const *conf )
{
#if defined(MBEDTLS_USE_PSA_CRYPTO)
if( !mbedtls_svc_key_id_is_null( conf->psk_opaque ) )
return( 1 );
#endif /* MBEDTLS_USE_PSA_CRYPTO */
if( conf->psk != NULL )
return( 1 );
return( 0 );
}
static void ssl_conf_remove_psk( mbedtls_ssl_config *conf )
{
/* Remove reference to existing PSK, if any. */
@ -3786,8 +3736,10 @@ int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,
const unsigned char *psk_identity, size_t psk_identity_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
/* Remove opaque/raw PSK + PSK Identity */
ssl_conf_remove_psk( conf );
/* We currently only support one PSK, raw or opaque. */
if( ssl_conf_psk_is_configured( conf ) )
return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
/* Check and set raw PSK */
if( psk == NULL )
@ -3855,8 +3807,10 @@ int mbedtls_ssl_conf_psk_opaque( mbedtls_ssl_config *conf,
size_t psk_identity_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
/* Clear opaque/raw PSK + PSK Identity, if present. */
ssl_conf_remove_psk( conf );
/* We currently only support one PSK, raw or opaque. */
if( ssl_conf_psk_is_configured( conf ) )
return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
/* Check and set opaque PSK */
if( mbedtls_svc_key_id_is_null( psk ) )
@ -6261,12 +6215,7 @@ int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf,
conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
set_protocol_version_ciphersuites(conf, MBEDTLS_SSL_MINOR_VERSION_1,
ssl_preset_suiteb_ciphersuites);
set_protocol_version_ciphersuites(conf, MBEDTLS_SSL_MINOR_VERSION_2,
ssl_preset_suiteb_ciphersuites);
set_protocol_version_ciphersuites(conf, MBEDTLS_SSL_MINOR_VERSION_3,
ssl_preset_suiteb_ciphersuites);
conf->ciphersuite_list = ssl_preset_suiteb_ciphersuites;
#if defined(MBEDTLS_X509_CRT_PARSE_C)
conf->cert_profile = &mbedtls_x509_crt_profile_suiteb;
@ -6300,13 +6249,7 @@ int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf,
if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_3;
#endif
const int* default_ciphersuites = mbedtls_ssl_list_ciphersuites();
set_protocol_version_ciphersuites(conf, MBEDTLS_SSL_MINOR_VERSION_1,
default_ciphersuites);
set_protocol_version_ciphersuites(conf, MBEDTLS_SSL_MINOR_VERSION_2,
default_ciphersuites);
set_protocol_version_ciphersuites(conf, MBEDTLS_SSL_MINOR_VERSION_3,
default_ciphersuites);
conf->ciphersuite_list = mbedtls_ssl_list_ciphersuites();
#if defined(MBEDTLS_X509_CRT_PARSE_C)
conf->cert_profile = &mbedtls_x509_crt_profile_default;

View File

@ -1268,9 +1268,7 @@ static int x509_crt_parse_der_core( mbedtls_x509_crt *crt,
}
}
#if !defined(MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3)
if( crt->version == 3 )
#endif
{
ret = x509_get_crt_ext( &p, end, crt, cb, p_ctx );
if( ret != 0 )

View File

@ -83,10 +83,11 @@ int mbedtls_x509write_csr_set_subject_name( mbedtls_x509write_csr *ctx,
int mbedtls_x509write_csr_set_extension( mbedtls_x509write_csr *ctx,
const char *oid, size_t oid_len,
int critical,
const unsigned char *val, size_t val_len )
{
return mbedtls_x509_set_extension( &ctx->extensions, oid, oid_len,
0, val, val_len );
critical, val, val_len );
}
int mbedtls_x509write_csr_set_key_usage( mbedtls_x509write_csr *ctx, unsigned char key_usage )
@ -103,7 +104,7 @@ int mbedtls_x509write_csr_set_key_usage( mbedtls_x509write_csr *ctx, unsigned ch
ret = mbedtls_x509write_csr_set_extension( ctx, MBEDTLS_OID_KEY_USAGE,
MBEDTLS_OID_SIZE( MBEDTLS_OID_KEY_USAGE ),
c, (size_t)ret );
0, c, (size_t)ret );
if( ret != 0 )
return( ret );
@ -125,7 +126,7 @@ int mbedtls_x509write_csr_set_ns_cert_type( mbedtls_x509write_csr *ctx,
ret = mbedtls_x509write_csr_set_extension( ctx, MBEDTLS_OID_NS_CERT_TYPE,
MBEDTLS_OID_SIZE( MBEDTLS_OID_NS_CERT_TYPE ),
c, (size_t)ret );
0, c, (size_t)ret );
if( ret != 0 )
return( ret );

View File

@ -93,7 +93,6 @@ int main( void )
#define DFL_ECJPAKE_PW NULL
#define DFL_PSK_LIST NULL
#define DFL_FORCE_CIPHER 0
#define DFL_VERSION_SUITES NULL
#define DFL_RENEGOTIATION MBEDTLS_SSL_RENEGOTIATION_DISABLED
#define DFL_ALLOW_LEGACY -2
#define DFL_RENEGOTIATE 0
@ -501,9 +500,6 @@ int main( void )
" force_version=%%s default: \"\" (none)\n" \
" options: tls1_2, dtls1_2\n" \
"\n" \
" version_suites=a,b,c per-version ciphersuites\n" \
" in order from tls1 to tls1_2\n" \
" default: all enabled\n" \
" force_ciphersuite=<name> default: all enabled\n" \
" query_config=<name> return 0 if the specified\n" \
" configuration macro is defined and 1\n" \
@ -565,7 +561,6 @@ struct options
char *psk_list; /* list of PSK id/key pairs for callback */
const char *ecjpake_pw; /* the EC J-PAKE password */
int force_ciphersuite[2]; /* protocol/ciphersuite to use, or all */
const char *version_suites; /* per-version ciphersuites */
int renegotiation; /* enable / disable renegotiation */
int allow_legacy; /* allow legacy renegotiation */
int renegotiate; /* attempt renegotiation? */
@ -1253,7 +1248,6 @@ int main( int argc, char *argv[] )
{
int ret = 0, len, written, frags, exchanges_left;
int query_config_ret = 0;
int version_suites[3][2];
io_ctx_t io_ctx;
unsigned char* buf = 0;
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
@ -1481,7 +1475,6 @@ int main( int argc, char *argv[] )
opt.psk_list = DFL_PSK_LIST;
opt.ecjpake_pw = DFL_ECJPAKE_PW;
opt.force_ciphersuite[0]= DFL_FORCE_CIPHER;
opt.version_suites = DFL_VERSION_SUITES;
opt.renegotiation = DFL_RENEGOTIATION;
opt.allow_legacy = DFL_ALLOW_LEGACY;
opt.renegotiate = DFL_RENEGOTIATE;
@ -1669,8 +1662,6 @@ int main( int argc, char *argv[] )
}
else if( strcmp( p, "curves" ) == 0 )
opt.curves = q;
else if( strcmp( p, "version_suites" ) == 0 )
opt.version_suites = q;
else if( strcmp( p, "renegotiation" ) == 0 )
{
opt.renegotiation = (atoi( q )) ?
@ -2036,10 +2027,6 @@ int main( int argc, char *argv[] )
if( opt.min_version < ciphersuite_info->min_minor_ver )
{
opt.min_version = ciphersuite_info->min_minor_ver;
/* DTLS starts with TLS 1.1 */
if( opt.transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
opt.min_version < MBEDTLS_SSL_MINOR_VERSION_2 )
opt.min_version = MBEDTLS_SSL_MINOR_VERSION_2;
}
#if defined(MBEDTLS_USE_PSA_CRYPTO)
@ -2067,47 +2054,6 @@ int main( int argc, char *argv[] )
#endif /* MBEDTLS_USE_PSA_CRYPTO */
}
if( opt.version_suites != NULL )
{
const char *name[3] = { 0 };
/* Parse 4-element coma-separated list */
for( i = 0, p = (char *) opt.version_suites;
i < 3 && *p != '\0';
i++ )
{
name[i] = p;
/* Terminate the current string and move on to next one */
while( *p != ',' && *p != '\0' )
p++;
if( *p == ',' )
*p++ = '\0';
}
if( i != 3 )
{
mbedtls_printf( "too few values for version_suites\n" );
ret = 1;
goto exit;
}
memset( version_suites, 0, sizeof( version_suites ) );
/* Get the suites identifiers from their name */
for( i = 0; i < 3; i++ )
{
version_suites[i][0] = mbedtls_ssl_get_ciphersuite_id( name[i] );
if( version_suites[i][0] == 0 )
{
mbedtls_printf( "unknown ciphersuite: '%s'\n", name[i] );
ret = 2;
goto usage;
}
}
}
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
if( mbedtls_test_unhexify( cid, sizeof( cid ),
opt.cid_val, &cid_len ) != 0 )
@ -2689,19 +2635,6 @@ int main( int argc, char *argv[] )
if( opt.force_ciphersuite[0] != DFL_FORCE_CIPHER )
mbedtls_ssl_conf_ciphersuites( &conf, opt.force_ciphersuite );
if( opt.version_suites != NULL )
{
mbedtls_ssl_conf_ciphersuites_for_version( &conf, version_suites[0],
MBEDTLS_SSL_MAJOR_VERSION_3,
MBEDTLS_SSL_MINOR_VERSION_1 );
mbedtls_ssl_conf_ciphersuites_for_version( &conf, version_suites[1],
MBEDTLS_SSL_MAJOR_VERSION_3,
MBEDTLS_SSL_MINOR_VERSION_2 );
mbedtls_ssl_conf_ciphersuites_for_version( &conf, version_suites[2],
MBEDTLS_SSL_MAJOR_VERSION_3,
MBEDTLS_SSL_MINOR_VERSION_3 );
}
if( opt.allow_legacy != DFL_ALLOW_LEGACY )
mbedtls_ssl_conf_legacy_renegotiation( &conf, opt.allow_legacy );
#if defined(MBEDTLS_SSL_RENEGOTIATION)

View File

@ -251,7 +251,11 @@ static int myrand( void *rng_state, unsigned char *output, size_t len )
#if defined(MBEDTLS_ECP_C)
void ecp_clear_precomputed( mbedtls_ecp_group *grp )
{
if( grp->T != NULL )
if( grp->T != NULL
#if MBEDTLS_ECP_FIXED_POINT_OPTIM == 1
&& grp->T_size != 0
#endif
)
{
size_t i;
for( i = 0; i < grp->T_size; i++ )

View File

@ -189,7 +189,6 @@ EXCLUDE_FROM_FULL = frozenset([
'MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER', # incompatible with USE_PSA_CRYPTO
'MBEDTLS_PSA_CRYPTO_SPM', # platform dependency (PSA SPM)
'MBEDTLS_PSA_INJECT_ENTROPY', # build dependency (hook functions)
'MBEDTLS_REMOVE_3DES_CIPHERSUITES', # removes a feature
'MBEDTLS_RSA_NO_CRT', # influences the use of RSA in X.509 and TLS
'MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN', # build dependency (clang+memsan)
'MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND', # build dependency (valgrind headers)

249
scripts/ecp_comb_table.py Executable file
View File

@ -0,0 +1,249 @@
#!/usr/bin/env python3
"""
Purpose
This script dumps comb table of ec curve. When you add a new ec curve, you
can use this script to generate codes to define `<curve>_T` in ecp_curves.c
"""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import subprocess
import sys
import tempfile
HOW_TO_ADD_NEW_CURVE = """
If you are trying to add new curve, you can follow these steps:
1. Define curve parameters (<curve>_p, <curve>_gx, etc...) in ecp_curves.c.
2. Add a macro to define <curve>_T to NULL following these parameters.
3. Build mbedcrypto
4. Run this script with an argument of new curve
5. Copy the output of this script into ecp_curves.c and replace the macro added
in Step 2
6. Rebuild and test if everything is ok
Replace the <curve> in the above with the name of the curve you want to add."""
CC = os.getenv('CC', 'cc')
MBEDTLS_LIBRARY_PATH = os.getenv('MBEDTLS_LIBRARY_PATH', "library")
SRC_DUMP_COMB_TABLE = r'''
#include <stdio.h>
#include <stdlib.h>
#include "mbedtls/ecp.h"
#include "mbedtls/error.h"
static void dump_mpi_initialize( const char *name, const mbedtls_mpi *d )
{
uint8_t buf[128] = {0};
size_t olen;
uint8_t *p;
olen = mbedtls_mpi_size( d );
mbedtls_mpi_write_binary_le( d, buf, olen );
printf("static const mbedtls_mpi_uint %s[] = {\n", name);
for (p = buf; p < buf + olen; p += 8) {
printf( " BYTES_TO_T_UINT_8( 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X ),\n",
p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7] );
}
printf("};\n");
}
static void dump_T( const mbedtls_ecp_group *grp )
{
char name[128];
printf( "#if MBEDTLS_ECP_FIXED_POINT_OPTIM == 1\n" );
for (size_t i = 0; i < grp->T_size; ++i) {
snprintf( name, sizeof(name), "%s_T_%zu_X", CURVE_NAME, i );
dump_mpi_initialize( name, &grp->T[i].X );
snprintf( name, sizeof(name), "%s_T_%zu_Y", CURVE_NAME, i );
dump_mpi_initialize( name, &grp->T[i].Y );
}
printf( "static const mbedtls_ecp_point %s_T[%zu] = {\n", CURVE_NAME, grp->T_size );
size_t olen;
for (size_t i = 0; i < grp->T_size; ++i) {
int z;
if ( mbedtls_mpi_cmp_int(&grp->T[i].Z, 0) == 0 ) {
z = 0;
} else if ( mbedtls_mpi_cmp_int(&grp->T[i].Z, 1) == 0 ) {
z = 1;
} else {
fprintf( stderr, "Unexpected value of Z (i = %d)\n", (int)i );
exit( 1 );
}
printf( " ECP_POINT_INIT_XY_Z%d(%s_T_%zu_X, %s_T_%zu_Y),\n",
z,
CURVE_NAME, i,
CURVE_NAME, i
);
}
printf("};\n#endif\n\n");
}
int main()
{
int rc;
mbedtls_mpi m;
mbedtls_ecp_point R;
mbedtls_ecp_group grp;
mbedtls_ecp_group_init( &grp );
rc = mbedtls_ecp_group_load( &grp, CURVE_ID );
if (rc != 0) {
char buf[100];
mbedtls_strerror( rc, buf, sizeof(buf) );
fprintf( stderr, "mbedtls_ecp_group_load: %s (-0x%x)\n", buf, -rc );
return 1;
}
grp.T = NULL;
mbedtls_ecp_point_init( &R );
mbedtls_mpi_init( &m);
mbedtls_mpi_lset( &m, 1 );
rc = mbedtls_ecp_mul( &grp, &R, &m, &grp.G, NULL, NULL );
if ( rc != 0 ) {
char buf[100];
mbedtls_strerror( rc, buf, sizeof(buf) );
fprintf( stderr, "mbedtls_ecp_mul: %s (-0x%x)\n", buf, -rc );
return 1;
}
if ( grp.T == NULL ) {
fprintf( stderr, "grp.T is not generated. Please make sure"
"MBEDTLS_ECP_FIXED_POINT_OPTIM is enabled in config.h\n" );
return 1;
}
dump_T( &grp );
return 0;
}
'''
SRC_DUMP_KNOWN_CURVE = r'''
#include <stdio.h>
#include <stdlib.h>
#include "mbedtls/ecp.h"
int main() {
const mbedtls_ecp_curve_info *info = mbedtls_ecp_curve_list();
mbedtls_ecp_group grp;
mbedtls_ecp_group_init( &grp );
while ( info->name != NULL ) {
mbedtls_ecp_group_load( &grp, info->grp_id );
if ( mbedtls_ecp_get_type(&grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS ) {
printf( " %s", info->name );
}
info++;
}
printf( "\n" );
return 0;
}
'''
def join_src_path(*args):
return os.path.normpath(os.path.join(os.path.dirname(__file__), "..", *args))
def run_c_source(src, cflags):
"""
Compile and run C source code
:param src: the c language code to run
:param cflags: additional cflags passing to compiler
:return:
"""
binname = tempfile.mktemp(prefix="mbedtls")
fd, srcname = tempfile.mkstemp(prefix="mbedtls", suffix=".c")
srcfile = os.fdopen(fd, mode="w")
srcfile.write(src)
srcfile.close()
args = [CC,
*cflags,
'-I' + join_src_path("include"),
"-o", binname,
'-L' + MBEDTLS_LIBRARY_PATH,
srcname,
'-lmbedcrypto']
p = subprocess.run(args=args, check=False)
if p.returncode != 0:
return False
p = subprocess.run(args=[binname], check=False, env={
'LD_LIBRARY_PATH': MBEDTLS_LIBRARY_PATH
})
if p.returncode != 0:
return False
os.unlink(srcname)
os.unlink(binname)
return True
def compute_curve(curve):
"""compute comb table for curve"""
r = run_c_source(
SRC_DUMP_COMB_TABLE,
[
'-g',
'-DCURVE_ID=MBEDTLS_ECP_DP_%s' % curve.upper(),
'-DCURVE_NAME="%s"' % curve.lower(),
])
if not r:
print("""\
Unable to compile and run utility.""", file=sys.stderr)
sys.exit(1)
def usage():
print("""
Usage: python %s <curve>...
Arguments:
curve Specify one or more curve names (e.g secp256r1)
All possible curves: """ % sys.argv[0])
run_c_source(SRC_DUMP_KNOWN_CURVE, [])
print("""
Environment Variable:
CC Specify which c compile to use to compile utility.
MBEDTLS_LIBRARY_PATH
Specify the path to mbedcrypto library. (e.g. build/library/)
How to add a new curve: %s""" % HOW_TO_ADD_NEW_CURVE)
def run_main():
shared_lib_path = os.path.normpath(os.path.join(MBEDTLS_LIBRARY_PATH, "libmbedcrypto.so"))
static_lib_path = os.path.normpath(os.path.join(MBEDTLS_LIBRARY_PATH, "libmbedcrypto.a"))
if not os.path.exists(shared_lib_path) and not os.path.exists(static_lib_path):
print("Warning: both '%s' and '%s' are not exists. This script will use "
"the library from your system instead of the library compiled by "
"this source directory.\n"
"You can specify library path using environment variable "
"'MBEDTLS_LIBRARY_PATH'." % (shared_lib_path, static_lib_path),
file=sys.stderr)
if len(sys.argv) <= 1:
usage()
else:
for curve in sys.argv[1:]:
compute_curve(curve)
if __name__ == '__main__':
run_main()

View File

@ -33,7 +33,7 @@ class KeyType:
`name` is a string 'PSA_KEY_TYPE_xxx' which is the name of a PSA key
type macro. For key types that take arguments, the arguments can
be passed either through the optional argument `params` or by
passing an expression of the form 'PSA_KEY_TYPE_xxx(param1, param2)'
passing an expression of the form 'PSA_KEY_TYPE_xxx(param1, ...)'
in `name` as a string.
"""
@ -48,7 +48,7 @@ class KeyType:
m = re.match(r'(\w+)\s*\((.*)\)\Z', self.name)
assert m is not None
self.name = m.group(1)
params = ','.split(m.group(2))
params = m.group(2).split(',')
self.params = (None if params is None else
[param.strip() for param in params])
"""The parameters of the key type, if there are any.

View File

@ -18,7 +18,55 @@
import itertools
import re
from typing import Dict, Iterable, Iterator, List, Set
from typing import Dict, Iterable, Iterator, List, Optional, Pattern, Set, Tuple, Union
class ReadFileLineException(Exception):
def __init__(self, filename: str, line_number: Union[int, str]) -> None:
message = 'in {} at {}'.format(filename, line_number)
super(ReadFileLineException, self).__init__(message)
self.filename = filename
self.line_number = line_number
class read_file_lines:
# Dear Pylint, conventionally, a context manager class name is lowercase.
# pylint: disable=invalid-name,too-few-public-methods
"""Context manager to read a text file line by line.
```
with read_file_lines(filename) as lines:
for line in lines:
process(line)
```
is equivalent to
```
with open(filename, 'r') as input_file:
for line in input_file:
process(line)
```
except that if process(line) raises an exception, then the read_file_lines
snippet annotates the exception with the file name and line number.
"""
def __init__(self, filename: str, binary: bool = False) -> None:
self.filename = filename
self.line_number = 'entry' #type: Union[int, str]
self.generator = None #type: Optional[Iterable[Tuple[int, str]]]
self.binary = binary
def __enter__(self) -> 'read_file_lines':
self.generator = enumerate(open(self.filename,
'rb' if self.binary else 'r'))
return self
def __iter__(self) -> Iterator[str]:
assert self.generator is not None
for line_number, content in self.generator:
self.line_number = line_number
yield content
self.line_number = 'exit'
def __exit__(self, exc_type, exc_value, exc_traceback) -> None:
if exc_type is not None:
raise ReadFileLineException(self.filename, self.line_number) \
from exc_value
class PSAMacroEnumerator:
@ -57,6 +105,20 @@ class PSAMacroEnumerator:
'tag_length': [],
'min_tag_length': [],
} #type: Dict[str, List[str]]
# Whether to include intermediate macros in enumerations. Intermediate
# macros serve as category headers and are not valid values of their
# type. See `is_internal_name`.
# Always false in this class, may be set to true in derived classes.
self.include_intermediate = False
def is_internal_name(self, name: str) -> bool:
"""Whether this is an internal macro. Internal macros will be skipped."""
if not self.include_intermediate:
if name.endswith('_BASE') or name.endswith('_NONE'):
return True
if '_CATEGORY_' in name:
return True
return name.endswith('_FLAG') or name.endswith('_MASK')
def gather_arguments(self) -> None:
"""Populate the list of values for macro arguments.
@ -73,7 +135,11 @@ class PSAMacroEnumerator:
@staticmethod
def _format_arguments(name: str, arguments: Iterable[str]) -> str:
"""Format a macro call with arguments.."""
"""Format a macro call with arguments.
The resulting format is consistent with
`InputsForTest.normalize_argument`.
"""
return name + '(' + ', '.join(arguments) + ')'
_argument_split_re = re.compile(r' *, *')
@ -111,6 +177,15 @@ class PSAMacroEnumerator:
except BaseException as e:
raise Exception('distribute_arguments({})'.format(name)) from e
def distribute_arguments_without_duplicates(
self, seen: Set[str], name: str
) -> Iterator[str]:
"""Same as `distribute_arguments`, but don't repeat seen results."""
for result in self.distribute_arguments(name):
if result not in seen:
seen.add(result)
yield result
def generate_expressions(self, names: Iterable[str]) -> Iterator[str]:
"""Generate expressions covering values constructed from the given names.
@ -123,7 +198,11 @@ class PSAMacroEnumerator:
* ``macros.generate_expressions(macros.key_types)`` generates all
key types.
"""
return itertools.chain(*map(self.distribute_arguments, names))
seen = set() #type: Set[str]
return itertools.chain(*(
self.distribute_arguments_without_duplicates(seen, name)
for name in names
))
class PSAMacroCollector(PSAMacroEnumerator):
@ -144,15 +223,6 @@ class PSAMacroCollector(PSAMacroEnumerator):
self.key_types_from_group = {} #type: Dict[str, str]
self.algorithms_from_hash = {} #type: Dict[str, str]
def is_internal_name(self, name: str) -> bool:
"""Whether this is an internal macro. Internal macros will be skipped."""
if not self.include_intermediate:
if name.endswith('_BASE') or name.endswith('_NONE'):
return True
if '_CATEGORY_' in name:
return True
return name.endswith('_FLAG') or name.endswith('_MASK')
def record_algorithm_subtype(self, name: str, expansion: str) -> None:
"""Record the subtype of an algorithm constructor.
@ -251,3 +321,179 @@ class PSAMacroCollector(PSAMacroEnumerator):
m = re.search(self._continued_line_re, line)
line = re.sub(self._nonascii_re, rb'', line).decode('ascii')
self.read_line(line)
class InputsForTest(PSAMacroEnumerator):
# pylint: disable=too-many-instance-attributes
"""Accumulate information about macros to test.
enumerate
This includes macro names as well as information about their arguments
when applicable.
"""
def __init__(self) -> None:
super().__init__()
self.all_declared = set() #type: Set[str]
# Identifier prefixes
self.table_by_prefix = {
'ERROR': self.statuses,
'ALG': self.algorithms,
'ECC_CURVE': self.ecc_curves,
'DH_GROUP': self.dh_groups,
'KEY_TYPE': self.key_types,
'KEY_USAGE': self.key_usage_flags,
} #type: Dict[str, Set[str]]
# Test functions
self.table_by_test_function = {
# Any function ending in _algorithm also gets added to
# self.algorithms.
'key_type': [self.key_types],
'block_cipher_key_type': [self.key_types],
'stream_cipher_key_type': [self.key_types],
'ecc_key_family': [self.ecc_curves],
'ecc_key_types': [self.ecc_curves],
'dh_key_family': [self.dh_groups],
'dh_key_types': [self.dh_groups],
'hash_algorithm': [self.hash_algorithms],
'mac_algorithm': [self.mac_algorithms],
'cipher_algorithm': [],
'hmac_algorithm': [self.mac_algorithms],
'aead_algorithm': [self.aead_algorithms],
'key_derivation_algorithm': [self.kdf_algorithms],
'key_agreement_algorithm': [self.ka_algorithms],
'asymmetric_signature_algorithm': [],
'asymmetric_signature_wildcard': [self.algorithms],
'asymmetric_encryption_algorithm': [],
'other_algorithm': [],
} #type: Dict[str, List[Set[str]]]
self.arguments_for['mac_length'] += ['1', '63']
self.arguments_for['min_mac_length'] += ['1', '63']
self.arguments_for['tag_length'] += ['1', '63']
self.arguments_for['min_tag_length'] += ['1', '63']
def add_numerical_values(self) -> None:
"""Add numerical values that are not supported to the known identifiers."""
# Sets of names per type
self.algorithms.add('0xffffffff')
self.ecc_curves.add('0xff')
self.dh_groups.add('0xff')
self.key_types.add('0xffff')
self.key_usage_flags.add('0x80000000')
# Hard-coded values for unknown algorithms
#
# These have to have values that are correct for their respective
# PSA_ALG_IS_xxx macros, but are also not currently assigned and are
# not likely to be assigned in the near future.
self.hash_algorithms.add('0x020000fe') # 0x020000ff is PSA_ALG_ANY_HASH
self.mac_algorithms.add('0x03007fff')
self.ka_algorithms.add('0x09fc0000')
self.kdf_algorithms.add('0x080000ff')
# For AEAD algorithms, the only variability is over the tag length,
# and this only applies to known algorithms, so don't test an
# unknown algorithm.
def get_names(self, type_word: str) -> Set[str]:
"""Return the set of known names of values of the given type."""
return {
'status': self.statuses,
'algorithm': self.algorithms,
'ecc_curve': self.ecc_curves,
'dh_group': self.dh_groups,
'key_type': self.key_types,
'key_usage': self.key_usage_flags,
}[type_word]
# Regex for interesting header lines.
# Groups: 1=macro name, 2=type, 3=argument list (optional).
_header_line_re = \
re.compile(r'#define +' +
r'(PSA_((?:(?:DH|ECC|KEY)_)?[A-Z]+)_\w+)' +
r'(?:\(([^\n()]*)\))?')
# Regex of macro names to exclude.
_excluded_name_re = re.compile(r'_(?:GET|IS|OF)_|_(?:BASE|FLAG|MASK)\Z')
# Additional excluded macros.
_excluded_names = set([
# Macros that provide an alternative way to build the same
# algorithm as another macro.
'PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG',
'PSA_ALG_FULL_LENGTH_MAC',
# Auxiliary macro whose name doesn't fit the usual patterns for
# auxiliary macros.
'PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG_CASE',
])
def parse_header_line(self, line: str) -> None:
"""Parse a C header line, looking for "#define PSA_xxx"."""
m = re.match(self._header_line_re, line)
if not m:
return
name = m.group(1)
self.all_declared.add(name)
if re.search(self._excluded_name_re, name) or \
name in self._excluded_names or \
self.is_internal_name(name):
return
dest = self.table_by_prefix.get(m.group(2))
if dest is None:
return
dest.add(name)
if m.group(3):
self.argspecs[name] = self._argument_split(m.group(3))
_nonascii_re = re.compile(rb'[^\x00-\x7f]+') #type: Pattern
def parse_header(self, filename: str) -> None:
"""Parse a C header file, looking for "#define PSA_xxx"."""
with read_file_lines(filename, binary=True) as lines:
for line in lines:
line = re.sub(self._nonascii_re, rb'', line).decode('ascii')
self.parse_header_line(line)
_macro_identifier_re = re.compile(r'[A-Z]\w+')
def generate_undeclared_names(self, expr: str) -> Iterable[str]:
for name in re.findall(self._macro_identifier_re, expr):
if name not in self.all_declared:
yield name
def accept_test_case_line(self, function: str, argument: str) -> bool:
#pylint: disable=unused-argument
undeclared = list(self.generate_undeclared_names(argument))
if undeclared:
raise Exception('Undeclared names in test case', undeclared)
return True
@staticmethod
def normalize_argument(argument: str) -> str:
"""Normalize whitespace in the given C expression.
The result uses the same whitespace as
` PSAMacroEnumerator.distribute_arguments`.
"""
return re.sub(r',', r', ', re.sub(r' +', r'', argument))
def add_test_case_line(self, function: str, argument: str) -> None:
"""Parse a test case data line, looking for algorithm metadata tests."""
sets = []
if function.endswith('_algorithm'):
sets.append(self.algorithms)
if function == 'key_agreement_algorithm' and \
argument.startswith('PSA_ALG_KEY_AGREEMENT('):
# We only want *raw* key agreement algorithms as such, so
# exclude ones that are already chained with a KDF.
# Keep the expression as one to test as an algorithm.
function = 'other_algorithm'
sets += self.table_by_test_function[function]
if self.accept_test_case_line(function, argument):
for s in sets:
s.add(self.normalize_argument(argument))
# Regex matching a *.data line containing a test function call and
# its arguments. The actual definition is partly positional, but this
# regex is good enough in practice.
_test_case_line_re = re.compile(r'(?!depends_on:)(\w+):([^\n :][^:\n]*)')
def parse_test_cases(self, filename: str) -> None:
"""Parse a test case file (*.data), looking for algorithm metadata tests."""
with read_file_lines(filename) as lines:
for line in lines:
m = re.match(self._test_case_line_re, line)
if m:
self.add_test_case_line(m.group(1), m.group(2))

View File

@ -151,6 +151,8 @@ add_test_suite(psa_crypto_se_driver_hal)
add_test_suite(psa_crypto_se_driver_hal_mocks)
add_test_suite(psa_crypto_slot_management)
add_test_suite(psa_crypto_storage_format psa_crypto_storage_format.misc)
add_test_suite(psa_crypto_storage_format psa_crypto_storage_format.current)
add_test_suite(psa_crypto_storage_format psa_crypto_storage_format.v0)
add_test_suite(psa_its)
add_test_suite(random)
add_test_suite(rsa)

View File

@ -36,8 +36,11 @@
typedef struct
{
unsigned char *buf;
unsigned char *buf; /* Pointer to a buffer of length bytes. */
size_t length;
/* If fallback_f_rng is NULL, fail after delivering length bytes. */
int ( *fallback_f_rng )( void*, unsigned char *, size_t );
void *fallback_p_rng;
} mbedtls_test_rnd_buf_info;
/**
@ -67,24 +70,25 @@ int mbedtls_test_rnd_std_rand( void *rng_state,
size_t len );
/**
* This function only returns zeros
* This function only returns zeros.
*
* rng_state shall be NULL.
* \p rng_state shall be \c NULL.
*/
int mbedtls_test_rnd_zero_rand( void *rng_state,
unsigned char *output,
size_t len );
/**
* This function returns random based on a buffer it receives.
* This function returns random data based on a buffer it receives.
*
* rng_state shall be a pointer to a rnd_buf_info structure.
* \p rng_state shall be a pointer to a #mbedtls_test_rnd_buf_info structure.
*
* The number of bytes released from the buffer on each call to
* the random function is specified by per_call. (Can be between
* 1 and 4)
* the random function is specified by \p len.
*
* After the buffer is empty it will return rand();
* After the buffer is empty, this function will call the fallback RNG in the
* #mbedtls_test_rnd_buf_info structure if there is one, and
* will return #MBEDTLS_ERR_ENTROPY_SOURCE_FAILED otherwise.
*/
int mbedtls_test_rnd_buffer_rand( void *rng_state,
unsigned char *output,
@ -96,7 +100,7 @@ int mbedtls_test_rnd_buffer_rand( void *rng_state,
* Pseudo random is based on the XTEA encryption algorithm to
* generate pseudorandom.
*
* rng_state shall be a pointer to a rnd_pseudo_info structure.
* \p rng_state shall be a pointer to a #mbedtls_test_rnd_pseudo_info structure.
*/
int mbedtls_test_rnd_pseudo_rand( void *rng_state,
unsigned char *output,

View File

@ -1085,26 +1085,8 @@ component_test_ecp_restartable_no_internal_rng () {
# no SSL tests as they all depend on having a DRBG
}
component_test_new_ecdh_context () {
msg "build: new ECDH context (ASan build)" # ~ 6 min
scripts/config.py unset MBEDTLS_ECDH_LEGACY_CONTEXT
CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: new ECDH context - main suites (inc. selftests) (ASan build)" # ~ 50s
make test
msg "test: new ECDH context - ECDH-related part of ssl-opt.sh (ASan build)" # ~ 5s
if_build_succeeded tests/ssl-opt.sh -f ECDH
msg "test: new ECDH context - compat.sh with some ECDH ciphersuites (ASan build)" # ~ 3 min
# Exclude some symmetric ciphers that are redundant here to gain time.
if_build_succeeded tests/compat.sh -f ECDH -V NO -e 'ARCFOUR\|ARIA\|CAMELLIA\|CHACHA\|DES\|RC4'
}
component_test_everest () {
msg "build: Everest ECDH context (ASan build)" # ~ 6 min
scripts/config.py unset MBEDTLS_ECDH_LEGACY_CONTEXT
scripts/config.py set MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED
CC=clang cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
@ -1122,7 +1104,6 @@ component_test_everest () {
component_test_everest_curve25519_only () {
msg "build: Everest ECDH context, only Curve25519" # ~ 6 min
scripts/config.py unset MBEDTLS_ECDH_LEGACY_CONTEXT
scripts/config.py set MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED
scripts/config.py unset MBEDTLS_ECDSA_C
scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED
@ -2294,7 +2275,6 @@ support_test_m32_o1 () {
component_test_m32_everest () {
msg "build: i386, Everest ECDH context (ASan build)" # ~ 6 min
scripts/config.py unset MBEDTLS_ECDH_LEGACY_CONTEXT
scripts/config.py set MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED
make CC=gcc CFLAGS="$ASAN_CFLAGS -m32 -O2" LDFLAGS="-m32 $ASAN_CFLAGS"

View File

@ -44,23 +44,28 @@ if [ $# -ne 0 ] && [ "$1" = "-u" ]; then
UPDATE='y'
fi
# check SCRIPT FILENAME[...]
# check SCRIPT DIRECTORY
# Run SCRIPT and check that it does not modify any of the specified files.
# In the first form, there can be any number of FILENAMEs, which must be
# regular files.
# In the second form, there must be a single DIRECTORY, standing for the
# list of files in the directory. Running SCRIPT must not modify any file
# in the directory and must not add or remove files either.
# If $UPDATE is empty, abort with an error status if a file is modified.
check()
{
SCRIPT=$1
TO_CHECK=$2
PATTERN=""
FILES=""
shift
if [ -d $TO_CHECK ]; then
rm -f "$TO_CHECK"/*.bak
for FILE in $TO_CHECK/*; do
FILES="$FILE $FILES"
done
else
FILES=$TO_CHECK
directory=
if [ -d "$1" ]; then
directory="$1"
rm -f "$directory"/*.bak
set -- "$1"/*
fi
for FILE in $FILES; do
for FILE in "$@"; do
if [ -e "$FILE" ]; then
cp "$FILE" "$FILE.bak"
else
@ -68,37 +73,32 @@ check()
fi
done
$SCRIPT
"$SCRIPT"
# Compare the script output to the old files and remove backups
for FILE in $FILES; do
if ! diff $FILE $FILE.bak >/dev/null 2>&1; then
for FILE in "$@"; do
if ! diff "$FILE" "$FILE.bak" >/dev/null 2>&1; then
echo "'$FILE' was either modified or deleted by '$SCRIPT'"
if [ -z "$UPDATE" ]; then
exit 1
fi
fi
if [ -z "$UPDATE" ]; then
mv $FILE.bak $FILE
mv "$FILE.bak" "$FILE"
else
rm -f "$FILE.bak"
fi
if [ -d $TO_CHECK ]; then
# Create a grep regular expression that we can check against the
# directory contents to test whether new files have been created
if [ -z $PATTERN ]; then
PATTERN="$(basename $FILE)"
else
PATTERN="$PATTERN\|$(basename $FILE)"
fi
fi
done
if [ -d $TO_CHECK ]; then
if [ -n "$directory" ]; then
old_list="$*"
set -- "$directory"/*
new_list="$*"
# Check if there are any new files
if ls -1 $TO_CHECK | grep -v "$PATTERN" >/dev/null 2>&1; then
echo "Files were created by '$SCRIPT'"
if [ "$old_list" != "$new_list" ]; then
echo "Files were deleted or created by '$SCRIPT'"
echo "Before: $old_list"
echo "After: $new_list"
if [ -z "$UPDATE" ]; then
exit 1
fi

View File

@ -60,6 +60,14 @@ def finish_family_dependencies(dependencies: List[str], bits: int) -> List[str]:
"""
return [finish_family_dependency(dep, bits) for dep in dependencies]
SYMBOLS_WITHOUT_DEPENDENCY = frozenset([
'PSA_ALG_AEAD_WITH_AT_LEAST_THIS_LENGTH_TAG', # modifier, only in policies
'PSA_ALG_AEAD_WITH_SHORTENED_TAG', # modifier
'PSA_ALG_ANY_HASH', # only in policies
'PSA_ALG_AT_LEAST_THIS_LENGTH_MAC', # modifier, only in policies
'PSA_ALG_KEY_AGREEMENT', # chaining
'PSA_ALG_TRUNCATED_MAC', # modifier
])
def automatic_dependencies(*expressions: str) -> List[str]:
"""Infer dependencies of a test case by looking for PSA_xxx symbols.
@ -70,6 +78,7 @@ def automatic_dependencies(*expressions: str) -> List[str]:
used = set()
for expr in expressions:
used.update(re.findall(r'PSA_(?:ALG|ECC_FAMILY|KEY_TYPE)_\w+', expr))
used.difference_update(SYMBOLS_WITHOUT_DEPENDENCY)
return sorted(psa_want_symbol(name) for name in used)
# A temporary hack: at the time of writing, not all dependency symbols
@ -100,24 +109,27 @@ class Information:
@staticmethod
def remove_unwanted_macros(
constructors: macro_collector.PSAMacroCollector
constructors: macro_collector.PSAMacroEnumerator
) -> None:
# Mbed TLS doesn't support DSA. Don't attempt to generate any related
# test case.
# Mbed TLS doesn't support finite-field DH yet and will not support
# finite-field DSA. Don't attempt to generate any related test case.
constructors.key_types.discard('PSA_KEY_TYPE_DH_KEY_PAIR')
constructors.key_types.discard('PSA_KEY_TYPE_DH_PUBLIC_KEY')
constructors.key_types.discard('PSA_KEY_TYPE_DSA_KEY_PAIR')
constructors.key_types.discard('PSA_KEY_TYPE_DSA_PUBLIC_KEY')
constructors.algorithms_from_hash.pop('PSA_ALG_DSA', None)
constructors.algorithms_from_hash.pop('PSA_ALG_DETERMINISTIC_DSA', None)
def read_psa_interface(self) -> macro_collector.PSAMacroCollector:
def read_psa_interface(self) -> macro_collector.PSAMacroEnumerator:
"""Return the list of known key types, algorithms, etc."""
constructors = macro_collector.PSAMacroCollector()
constructors = macro_collector.InputsForTest()
header_file_names = ['include/psa/crypto_values.h',
'include/psa/crypto_extra.h']
test_suites = ['tests/suites/test_suite_psa_crypto_metadata.data']
for header_file_name in header_file_names:
with open(header_file_name, 'rb') as header_file:
constructors.read_file(header_file)
constructors.parse_header(header_file_name)
for test_cases in test_suites:
constructors.parse_test_cases(test_cases)
self.remove_unwanted_macros(constructors)
constructors.gather_arguments()
return constructors
@ -199,14 +211,18 @@ class NotSupported:
)
# To be added: derive
ECC_KEY_TYPES = ('PSA_KEY_TYPE_ECC_KEY_PAIR',
'PSA_KEY_TYPE_ECC_PUBLIC_KEY')
def test_cases_for_not_supported(self) -> Iterator[test_case.TestCase]:
"""Generate test cases that exercise the creation of keys of unsupported types."""
for key_type in sorted(self.constructors.key_types):
if key_type in self.ECC_KEY_TYPES:
continue
kt = crypto_knowledge.KeyType(key_type)
yield from self.test_cases_for_key_type_not_supported(kt)
for curve_family in sorted(self.constructors.ecc_curves):
for constr in ('PSA_KEY_TYPE_ECC_KEY_PAIR',
'PSA_KEY_TYPE_ECC_PUBLIC_KEY'):
for constr in self.ECC_KEY_TYPES:
kt = crypto_knowledge.KeyType(constr, [curve_family])
yield from self.test_cases_for_key_type_not_supported(
kt, param_descr='type')
@ -260,13 +276,17 @@ class StorageFormat:
if self.forward:
extra_arguments = []
else:
flags = []
# Some test keys have the RAW_DATA type and attributes that don't
# necessarily make sense. We do this to validate numerical
# encodings of the attributes.
# Raw data keys have no useful exercise anyway so there is no
# loss of test coverage.
exercise = key.type.string != 'PSA_KEY_TYPE_RAW_DATA'
extra_arguments = ['1' if exercise else '0']
if key.type.string != 'PSA_KEY_TYPE_RAW_DATA':
flags.append('TEST_FLAG_EXERCISE')
if 'READ_ONLY' in key.lifetime.string:
flags.append('TEST_FLAG_READ_ONLY')
extra_arguments = [' | '.join(flags) if flags else '0']
tc.set_arguments([key.lifetime.string,
key.type.string, str(key.bits),
key.usage.string, key.alg.string, key.alg2.string,
@ -335,23 +355,17 @@ class StorageFormat:
def all_keys_for_types(self) -> Iterator[StorageKey]:
"""Generate test keys covering key types and their representations."""
for key_type in sorted(self.constructors.key_types):
key_types = sorted(self.constructors.key_types)
for key_type in self.constructors.generate_expressions(key_types):
yield from self.keys_for_type(key_type)
for key_type in sorted(self.constructors.key_types_from_curve):
for curve in sorted(self.constructors.ecc_curves):
yield from self.keys_for_type(key_type, [curve])
## Diffie-Hellman (FFDH) is not supported yet, either in
## crypto_knowledge.py or in Mbed TLS.
# for key_type in sorted(self.constructors.key_types_from_group):
# for group in sorted(self.constructors.dh_groups):
# yield from self.keys_for_type(key_type, [group])
def keys_for_algorithm(self, alg: str) -> Iterator[StorageKey]:
"""Generate test keys for the specified algorithm."""
# For now, we don't have information on the compatibility of key
# types and algorithms. So we just test the encoding of algorithms,
# and not that operations can be performed with them.
descr = alg
descr = re.sub(r'PSA_ALG_', r'', alg)
descr = re.sub(r',', r', ', re.sub(r' +', r'', descr))
usage = 'PSA_KEY_USAGE_EXPORT'
key1 = StorageKey(version=self.version,
id=1, lifetime=0x00000001,
@ -370,17 +384,21 @@ class StorageFormat:
def all_keys_for_algorithms(self) -> Iterator[StorageKey]:
"""Generate test keys covering algorithm encodings."""
for alg in sorted(self.constructors.algorithms):
algorithms = sorted(self.constructors.algorithms)
for alg in self.constructors.generate_expressions(algorithms):
yield from self.keys_for_algorithm(alg)
# To do: algorithm constructors with parameters
def all_test_cases(self) -> Iterator[test_case.TestCase]:
"""Generate all storage format test cases."""
for key in self.all_keys_for_usage_flags():
yield self.make_test_case(key)
for key in self.all_keys_for_types():
yield self.make_test_case(key)
for key in self.all_keys_for_algorithms():
# First build a list of all keys, then construct all the corresponding
# test cases. This allows all required information to be obtained in
# one go, which is a significant performance gain as the information
# includes numerical values obtained by compiling a C program.
keys = [] #type: List[StorageKey]
keys += self.all_keys_for_usage_flags()
keys += self.all_keys_for_types()
keys += self.all_keys_for_algorithms()
for key in keys:
yield self.make_test_case(key)
# To do: vary id, lifetime

View File

@ -28,231 +28,30 @@ import os
import re
import subprocess
import sys
from typing import Iterable, List, Optional, Tuple
import scripts_path # pylint: disable=unused-import
from mbedtls_dev import c_build_helper
from mbedtls_dev import macro_collector
from mbedtls_dev.macro_collector import InputsForTest, PSAMacroEnumerator
from mbedtls_dev import typing_util
class ReadFileLineException(Exception):
def __init__(self, filename, line_number):
message = 'in {} at {}'.format(filename, line_number)
super(ReadFileLineException, self).__init__(message)
self.filename = filename
self.line_number = line_number
class read_file_lines:
# Dear Pylint, conventionally, a context manager class name is lowercase.
# pylint: disable=invalid-name,too-few-public-methods
"""Context manager to read a text file line by line.
```
with read_file_lines(filename) as lines:
for line in lines:
process(line)
```
is equivalent to
```
with open(filename, 'r') as input_file:
for line in input_file:
process(line)
```
except that if process(line) raises an exception, then the read_file_lines
snippet annotates the exception with the file name and line number.
"""
def __init__(self, filename, binary=False):
self.filename = filename
self.line_number = 'entry'
self.generator = None
self.binary = binary
def __enter__(self):
self.generator = enumerate(open(self.filename,
'rb' if self.binary else 'r'))
return self
def __iter__(self):
for line_number, content in self.generator:
self.line_number = line_number
yield content
self.line_number = 'exit'
def __exit__(self, exc_type, exc_value, exc_traceback):
if exc_type is not None:
raise ReadFileLineException(self.filename, self.line_number) \
from exc_value
class InputsForTest(macro_collector.PSAMacroEnumerator):
# pylint: disable=too-many-instance-attributes
"""Accumulate information about macros to test.
This includes macro names as well as information about their arguments
when applicable.
"""
def __init__(self):
super().__init__()
self.all_declared = set()
# Sets of names per type
self.statuses.add('PSA_SUCCESS')
self.algorithms.add('0xffffffff')
self.ecc_curves.add('0xff')
self.dh_groups.add('0xff')
self.key_types.add('0xffff')
self.key_usage_flags.add('0x80000000')
# Hard-coded values for unknown algorithms
#
# These have to have values that are correct for their respective
# PSA_ALG_IS_xxx macros, but are also not currently assigned and are
# not likely to be assigned in the near future.
self.hash_algorithms.add('0x020000fe') # 0x020000ff is PSA_ALG_ANY_HASH
self.mac_algorithms.add('0x03007fff')
self.ka_algorithms.add('0x09fc0000')
self.kdf_algorithms.add('0x080000ff')
# For AEAD algorithms, the only variability is over the tag length,
# and this only applies to known algorithms, so don't test an
# unknown algorithm.
# Identifier prefixes
self.table_by_prefix = {
'ERROR': self.statuses,
'ALG': self.algorithms,
'ECC_CURVE': self.ecc_curves,
'DH_GROUP': self.dh_groups,
'KEY_TYPE': self.key_types,
'KEY_USAGE': self.key_usage_flags,
}
# Test functions
self.table_by_test_function = {
# Any function ending in _algorithm also gets added to
# self.algorithms.
'key_type': [self.key_types],
'block_cipher_key_type': [self.key_types],
'stream_cipher_key_type': [self.key_types],
'ecc_key_family': [self.ecc_curves],
'ecc_key_types': [self.ecc_curves],
'dh_key_family': [self.dh_groups],
'dh_key_types': [self.dh_groups],
'hash_algorithm': [self.hash_algorithms],
'mac_algorithm': [self.mac_algorithms],
'cipher_algorithm': [],
'hmac_algorithm': [self.mac_algorithms],
'aead_algorithm': [self.aead_algorithms],
'key_derivation_algorithm': [self.kdf_algorithms],
'key_agreement_algorithm': [self.ka_algorithms],
'asymmetric_signature_algorithm': [],
'asymmetric_signature_wildcard': [self.algorithms],
'asymmetric_encryption_algorithm': [],
'other_algorithm': [],
}
self.arguments_for['mac_length'] += ['1', '63']
self.arguments_for['min_mac_length'] += ['1', '63']
self.arguments_for['tag_length'] += ['1', '63']
self.arguments_for['min_tag_length'] += ['1', '63']
def get_names(self, type_word):
"""Return the set of known names of values of the given type."""
return {
'status': self.statuses,
'algorithm': self.algorithms,
'ecc_curve': self.ecc_curves,
'dh_group': self.dh_groups,
'key_type': self.key_types,
'key_usage': self.key_usage_flags,
}[type_word]
# Regex for interesting header lines.
# Groups: 1=macro name, 2=type, 3=argument list (optional).
_header_line_re = \
re.compile(r'#define +' +
r'(PSA_((?:(?:DH|ECC|KEY)_)?[A-Z]+)_\w+)' +
r'(?:\(([^\n()]*)\))?')
# Regex of macro names to exclude.
_excluded_name_re = re.compile(r'_(?:GET|IS|OF)_|_(?:BASE|FLAG|MASK)\Z')
# Additional excluded macros.
_excluded_names = set([
# Macros that provide an alternative way to build the same
# algorithm as another macro.
'PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG',
'PSA_ALG_FULL_LENGTH_MAC',
# Auxiliary macro whose name doesn't fit the usual patterns for
# auxiliary macros.
'PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG_CASE',
])
def parse_header_line(self, line):
"""Parse a C header line, looking for "#define PSA_xxx"."""
m = re.match(self._header_line_re, line)
if not m:
return
name = m.group(1)
self.all_declared.add(name)
if re.search(self._excluded_name_re, name) or \
name in self._excluded_names:
return
dest = self.table_by_prefix.get(m.group(2))
if dest is None:
return
dest.add(name)
if m.group(3):
self.argspecs[name] = self._argument_split(m.group(3))
_nonascii_re = re.compile(rb'[^\x00-\x7f]+')
def parse_header(self, filename):
"""Parse a C header file, looking for "#define PSA_xxx"."""
with read_file_lines(filename, binary=True) as lines:
for line in lines:
line = re.sub(self._nonascii_re, rb'', line).decode('ascii')
self.parse_header_line(line)
_macro_identifier_re = re.compile(r'[A-Z]\w+')
def generate_undeclared_names(self, expr):
for name in re.findall(self._macro_identifier_re, expr):
if name not in self.all_declared:
yield name
def accept_test_case_line(self, function, argument):
#pylint: disable=unused-argument
undeclared = list(self.generate_undeclared_names(argument))
if undeclared:
raise Exception('Undeclared names in test case', undeclared)
return True
def add_test_case_line(self, function, argument):
"""Parse a test case data line, looking for algorithm metadata tests."""
sets = []
if function.endswith('_algorithm'):
sets.append(self.algorithms)
if function == 'key_agreement_algorithm' and \
argument.startswith('PSA_ALG_KEY_AGREEMENT('):
# We only want *raw* key agreement algorithms as such, so
# exclude ones that are already chained with a KDF.
# Keep the expression as one to test as an algorithm.
function = 'other_algorithm'
sets += self.table_by_test_function[function]
if self.accept_test_case_line(function, argument):
for s in sets:
s.add(argument)
# Regex matching a *.data line containing a test function call and
# its arguments. The actual definition is partly positional, but this
# regex is good enough in practice.
_test_case_line_re = re.compile(r'(?!depends_on:)(\w+):([^\n :][^:\n]*)')
def parse_test_cases(self, filename):
"""Parse a test case file (*.data), looking for algorithm metadata tests."""
with read_file_lines(filename) as lines:
for line in lines:
m = re.match(self._test_case_line_re, line)
if m:
self.add_test_case_line(m.group(1), m.group(2))
def gather_inputs(headers, test_suites, inputs_class=InputsForTest):
def gather_inputs(headers: Iterable[str],
test_suites: Iterable[str],
inputs_class=InputsForTest) -> PSAMacroEnumerator:
"""Read the list of inputs to test psa_constant_names with."""
inputs = inputs_class()
for header in headers:
inputs.parse_header(header)
for test_cases in test_suites:
inputs.parse_test_cases(test_cases)
inputs.add_numerical_values()
inputs.gather_arguments()
return inputs
def run_c(type_word, expressions, include_path=None, keep_c=False):
def run_c(type_word: str,
expressions: Iterable[str],
include_path: Optional[str] = None,
keep_c: bool = False) -> List[str]:
"""Generate and run a program to print out numerical values of C expressions."""
if type_word == 'status':
cast_to = 'long'
@ -271,14 +70,17 @@ def run_c(type_word, expressions, include_path=None, keep_c=False):
)
NORMALIZE_STRIP_RE = re.compile(r'\s+')
def normalize(expr):
def normalize(expr: str) -> str:
"""Normalize the C expression so as not to care about trivial differences.
Currently "trivial differences" means whitespace.
"""
return re.sub(NORMALIZE_STRIP_RE, '', expr)
def collect_values(inputs, type_word, include_path=None, keep_c=False):
def collect_values(inputs: InputsForTest,
type_word: str,
include_path: Optional[str] = None,
keep_c: bool = False) -> Tuple[List[str], List[str]]:
"""Generate expressions using known macro names and calculate their values.
Return a list of pairs of (expr, value) where expr is an expression and
@ -296,12 +98,12 @@ class Tests:
Error = namedtuple('Error',
['type', 'expression', 'value', 'output'])
def __init__(self, options):
def __init__(self, options) -> None:
self.options = options
self.count = 0
self.errors = []
self.errors = [] #type: List[Tests.Error]
def run_one(self, inputs, type_word):
def run_one(self, inputs: InputsForTest, type_word: str) -> None:
"""Test psa_constant_names for the specified type.
Run the program on the names for this type.
@ -311,9 +113,10 @@ class Tests:
expressions, values = collect_values(inputs, type_word,
include_path=self.options.include,
keep_c=self.options.keep_c)
output = subprocess.check_output([self.options.program, type_word] +
values)
outputs = output.decode('ascii').strip().split('\n')
output_bytes = subprocess.check_output([self.options.program,
type_word] + values)
output = output_bytes.decode('ascii')
outputs = output.strip().split('\n')
self.count += len(expressions)
for expr, value, output in zip(expressions, values, outputs):
if self.options.show:
@ -324,13 +127,13 @@ class Tests:
value=value,
output=output))
def run_all(self, inputs):
def run_all(self, inputs: InputsForTest) -> None:
"""Run psa_constant_names on all the gathered inputs."""
for type_word in ['status', 'algorithm', 'ecc_curve', 'dh_group',
'key_type', 'key_usage']:
self.run_one(inputs, type_word)
def report(self, out):
def report(self, out: typing_util.Writable) -> None:
"""Describe each case where the output is not as expected.
Write the errors to ``out``.
@ -365,7 +168,7 @@ def main():
help='Program to test')
parser.add_argument('--show',
action='store_true',
help='Keep the intermediate C file')
help='Show tested values on stdout')
parser.add_argument('--no-show',
action='store_false', dest='show',
help='Don\'t show tested values (default)')

View File

@ -35,6 +35,8 @@
#include <test/random.h>
#include <string.h>
#include <mbedtls/entropy.h>
int mbedtls_test_rnd_std_rand( void *rng_state,
unsigned char *output,
size_t len )
@ -91,8 +93,16 @@ int mbedtls_test_rnd_buffer_rand( void *rng_state,
}
if( len - use_len > 0 )
return( mbedtls_test_rnd_std_rand( NULL, output + use_len,
len - use_len ) );
{
if( info->fallback_f_rng != NULL )
{
return( info->fallback_f_rng( info->fallback_p_rng,
output + use_len,
len - use_len ) );
}
else
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
}
return( 0 );
}

View File

@ -5614,17 +5614,6 @@ run_test "ECJPAKE: working, DTLS, nolog" \
force_ciphersuite=TLS-ECJPAKE-WITH-AES-128-CCM-8" \
0
# Tests for ciphersuites per version
requires_config_enabled MBEDTLS_SSL_PROTO_TLS1_2
requires_config_enabled MBEDTLS_CAMELLIA_C
requires_config_enabled MBEDTLS_AES_C
run_test "Per-version suites: TLS 1.2" \
"$P_SRV version_suites=TLS-RSA-WITH-AES-256-CBC-SHA,TLS-RSA-WITH-AES-128-CBC-SHA,TLS-RSA-WITH-AES-128-GCM-SHA256" \
"$P_CLI force_version=tls1_2" \
0 \
-c "Ciphersuite is TLS-RSA-WITH-AES-128-GCM-SHA256"
# Test for ClientHello without extensions
requires_gnutls

View File

@ -1,23 +1,89 @@
Diffie-Hellman full exchange #1
dhm_do_dhm:10:"23":10:"5":0
Diffie-Hellman full exchange: tiny x_size
dhm_do_dhm:10:"93450983094850938450983409623":1:10:"9345098304850938450983409622":0
Diffie-Hellman full exchange #2
dhm_do_dhm:10:"93450983094850938450983409623":10:"9345098304850938450983409622":0
Diffie-Hellman full exchange: 5-bit, x_size=3
dhm_do_dhm:10:"23":3:10:"5":0
Diffie-Hellman full exchange #3
dhm_do_dhm:10:"93450983094850938450983409623982317398171298719873918739182739712938719287391879381271":10:"9345098309485093845098340962223981329819812792137312973297123912791271":0
Diffie-Hellman full exchange: 5-bit, x_size=2
dhm_do_dhm:10:"23":2:10:"5":0
## Repeat this test case and a few similar ones several times. The RNG state
## changes, so we get to exercise the code with a few different values.
Diffie-Hellman full exchange: 5-bit #1
dhm_do_dhm:10:"23":1:10:"5":0
Diffie-Hellman full exchange: 5-bit #2
dhm_do_dhm:10:"23":1:10:"5":0
Diffie-Hellman full exchange: 5-bit #3
dhm_do_dhm:10:"23":1:10:"5":0
Diffie-Hellman full exchange: 5-bit #4
dhm_do_dhm:10:"23":1:10:"5":0
Diffie-Hellman full exchange: 5-bit #5
dhm_do_dhm:10:"23":1:10:"5":0
## This is x_size = P_size + 1. Arguably x_size > P_size makes no sense,
## but it's the current undocumented behavior to treat it the same as when
## x_size = P_size. If this behavior changes in the future, change the expected
## return status from 0 to MBEDTLS_ERR_DHM_BAD_INPUT_DATA.
Diffie-Hellman full exchange: 97-bit, x_size=14
dhm_do_dhm:10:"93450983094850938450983409623":14:10:"9345098304850938450983409622":0
Diffie-Hellman full exchange: 97-bit #1
dhm_do_dhm:10:"93450983094850938450983409623":13:10:"9345098304850938450983409622":0
Diffie-Hellman full exchange: 97-bit #2
dhm_do_dhm:10:"93450983094850938450983409623":13:10:"9345098304850938450983409622":0
Diffie-Hellman full exchange: 97-bit #3
dhm_do_dhm:10:"93450983094850938450983409623":13:10:"9345098304850938450983409622":0
Diffie-Hellman full exchange: 97-bit #4
dhm_do_dhm:10:"93450983094850938450983409623":13:10:"9345098304850938450983409622":0
Diffie-Hellman full exchange: 97-bit #5
dhm_do_dhm:10:"93450983094850938450983409623":13:10:"9345098304850938450983409622":0
Diffie-Hellman full exchange: 97-bit, x_size=12
dhm_do_dhm:10:"93450983094850938450983409623":12:10:"9345098304850938450983409622":0
Diffie-Hellman full exchange: 97-bit, x_size=11
dhm_do_dhm:10:"93450983094850938450983409623":11:10:"9345098304850938450983409622":0
Diffie-Hellman full exchange: 97-bit, x_size=1 #1
dhm_do_dhm:10:"93450983094850938450983409623":1:10:"9345098304850938450983409622":0
Diffie-Hellman full exchange: 97-bit, x_size=1 #2
dhm_do_dhm:10:"93450983094850938450983409623":1:10:"9345098304850938450983409622":0
Diffie-Hellman full exchange: 97-bit, x_size=1 #3
dhm_do_dhm:10:"93450983094850938450983409623":1:10:"9345098304850938450983409622":0
Diffie-Hellman full exchange: 97-bit, x_size=1 #4
dhm_do_dhm:10:"93450983094850938450983409623":1:10:"9345098304850938450983409622":0
Diffie-Hellman full exchange: 97-bit, x_size=1 #5
dhm_do_dhm:10:"93450983094850938450983409623":1:10:"9345098304850938450983409622":0
Diffie-Hellman full exchange: 286-bit
dhm_do_dhm:10:"93450983094850938450983409623982317398171298719873918739182739712938719287391879381271":36:10:"9345098309485093845098340962223981329819812792137312973297123912791271":0
Diffie-Hellman trivial subgroup #1
dhm_do_dhm:10:"23":10:"1":MBEDTLS_ERR_DHM_BAD_INPUT_DATA
dhm_do_dhm:10:"23":1:10:"1":MBEDTLS_ERR_DHM_BAD_INPUT_DATA
Diffie-Hellman trivial subgroup #2
dhm_do_dhm:10:"23":10:"-1":MBEDTLS_ERR_DHM_BAD_INPUT_DATA
dhm_do_dhm:10:"23":1:10:"-1":MBEDTLS_ERR_DHM_BAD_INPUT_DATA
Diffie-Hellman small modulus
dhm_do_dhm:10:"3":10:"5":MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED
dhm_do_dhm:10:"3":1:10:"5":MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED+MBEDTLS_ERR_MPI_BAD_INPUT_DATA
Diffie-Hellman zero modulus
dhm_do_dhm:10:"0":10:"5":MBEDTLS_ERR_DHM_BAD_INPUT_DATA
dhm_do_dhm:10:"0":1:10:"5":MBEDTLS_ERR_DHM_BAD_INPUT_DATA
Diffie-Hellman: x_size < 0
dhm_do_dhm:10:"93450983094850938450983409623":-1:10:"9345098304850938450983409622":MBEDTLS_ERR_DHM_BAD_INPUT_DATA
Diffie-Hellman MPI_MAX_SIZE modulus
dhm_make_public:MBEDTLS_MPI_MAX_SIZE:10:"5":0

View File

@ -1,5 +1,68 @@
/* BEGIN_HEADER */
#include "mbedtls/dhm.h"
/* Sanity checks on a Diffie-Hellman parameter: check the length-value
* syntax and check that the value is the expected one (taken from the
* DHM context by the caller). */
static int check_dhm_param_output( const mbedtls_mpi *expected,
const unsigned char *buffer,
size_t size,
size_t *offset )
{
size_t n;
mbedtls_mpi actual;
int ok = 0;
mbedtls_mpi_init( &actual );
++mbedtls_test_info.step;
TEST_ASSERT( size >= *offset + 2 );
n = ( buffer[*offset] << 8 ) | buffer[*offset + 1];
*offset += 2;
/* The DHM param output from Mbed TLS has leading zeros stripped, as
* permitted but not required by RFC 5246 \S4.4. */
TEST_EQUAL( n, mbedtls_mpi_size( expected ) );
TEST_ASSERT( size >= *offset + n );
TEST_EQUAL( 0, mbedtls_mpi_read_binary( &actual, buffer + *offset, n ) );
TEST_EQUAL( 0, mbedtls_mpi_cmp_mpi( expected, &actual ) );
*offset += n;
ok = 1;
exit:
mbedtls_mpi_free( &actual );
return( ok );
}
/* Sanity checks on Diffie-Hellman parameters: syntax, range, and comparison
* against the context. */
static int check_dhm_params( const mbedtls_dhm_context *ctx,
size_t x_size,
const unsigned char *ske, size_t ske_len )
{
size_t offset = 0;
/* Check that ctx->X and ctx->GX are within range. */
TEST_ASSERT( mbedtls_mpi_cmp_int( &ctx->X, 1 ) > 0 );
TEST_ASSERT( mbedtls_mpi_cmp_mpi( &ctx->X, &ctx->P ) < 0 );
TEST_ASSERT( mbedtls_mpi_size( &ctx->X ) <= x_size );
TEST_ASSERT( mbedtls_mpi_cmp_int( &ctx->GX, 1 ) > 0 );
TEST_ASSERT( mbedtls_mpi_cmp_mpi( &ctx->GX, &ctx->P ) < 0 );
/* Check ske: it must contain P, G and G^X, each prefixed with a
* 2-byte size. */
if( !check_dhm_param_output( &ctx->P, ske, ske_len, &offset ) )
goto exit;
if( !check_dhm_param_output( &ctx->G, ske, ske_len, &offset ) )
goto exit;
if( !check_dhm_param_output( &ctx->GX, ske, ske_len, &offset ) )
goto exit;
TEST_EQUAL( offset, ske_len );
return( 1 );
exit:
return( 0 );
}
/* END_HEADER */
/* BEGIN_DEPENDENCIES
@ -8,7 +71,7 @@
*/
/* BEGIN_CASE */
void dhm_do_dhm( int radix_P, char *input_P,
void dhm_do_dhm( int radix_P, char *input_P, int x_size,
int radix_G, char *input_G, int result )
{
mbedtls_dhm_context ctx_srv;
@ -22,7 +85,7 @@ void dhm_do_dhm( int radix_P, char *input_P,
size_t pub_cli_len = 0;
size_t sec_srv_len;
size_t sec_cli_len;
int x_size, i;
int i;
mbedtls_test_rnd_pseudo_info rnd_info;
mbedtls_dhm_init( &ctx_srv );
@ -38,17 +101,19 @@ void dhm_do_dhm( int radix_P, char *input_P,
*/
TEST_ASSERT( mbedtls_mpi_read_string( &ctx_srv.P, radix_P, input_P ) == 0 );
TEST_ASSERT( mbedtls_mpi_read_string( &ctx_srv.G, radix_G, input_G ) == 0 );
x_size = mbedtls_mpi_size( &ctx_srv.P );
pub_cli_len = x_size;
pub_cli_len = mbedtls_mpi_size( &ctx_srv.P );
/*
* First key exchange
*/
mbedtls_test_set_step( 10 );
TEST_ASSERT( mbedtls_dhm_make_params( &ctx_srv, x_size, ske, &ske_len,
&mbedtls_test_rnd_pseudo_rand,
&rnd_info ) == result );
if ( result != 0 )
goto exit;
if( !check_dhm_params( &ctx_srv, x_size, ske, ske_len ) )
goto exit;
ske[ske_len++] = 0;
ske[ske_len++] = 0;
@ -72,6 +137,7 @@ void dhm_do_dhm( int radix_P, char *input_P,
/* Re-do calc_secret on server a few times to test update of blinding values */
for( i = 0; i < 3; i++ )
{
mbedtls_test_set_step( 20 + i );
sec_srv_len = 1000;
TEST_ASSERT( mbedtls_dhm_calc_secret( &ctx_srv, sec_srv,
sizeof( sec_srv ), &sec_srv_len,
@ -88,9 +154,12 @@ void dhm_do_dhm( int radix_P, char *input_P,
*/
p = ske;
mbedtls_test_set_step( 30 );
TEST_ASSERT( mbedtls_dhm_make_params( &ctx_srv, x_size, ske, &ske_len,
&mbedtls_test_rnd_pseudo_rand,
&rnd_info ) == 0 );
if( !check_dhm_params( &ctx_srv, x_size, ske, ske_len ) )
goto exit;
ske[ske_len++] = 0;
ske[ske_len++] = 0;
TEST_ASSERT( mbedtls_dhm_read_params( &ctx_cli, &p, ske + ske_len ) == 0 );

View File

@ -73,10 +73,6 @@ ECDH restartable rfc 5903 p256 restart disabled max_ops=250
depends_on:MBEDTLS_ECP_DP_SECP256R1_ENABLED
ecdh_restart:MBEDTLS_ECP_DP_SECP256R1:"C88F01F510D9AC3F70A292DAA2316DE544E9AAB8AFE84049C62A9C57862D1433":"C6EF9C5D78AE012A011164ACB397CE2088685D8F06BF9BE0B283AB46476BEE53":"D6840F6B42F6EDAFD13116E0E12565202FEF8E9ECE7DCE03812464D04B9442DE":0:250:0:0
ECDH exchange legacy context
depends_on:MBEDTLS_ECP_DP_SECP192R1_ENABLED
ecdh_exchange_legacy:MBEDTLS_ECP_DP_SECP192R1
ECDH calc_secret: ours first, SECP256R1 (RFC 5903)
depends_on:MBEDTLS_ECP_DP_SECP256R1_ENABLED
ecdh_exchange_calc_secret:MBEDTLS_ECP_DP_SECP256R1:"c6ef9c5d78ae012a011164acb397ce2088685d8f06bf9be0b283ab46476bee53":"04dad0b65394221cf9b051e1feca5787d098dfe637fc90b9ef945d0c37725811805271a0461cdb8252d61f1c456fa3e59ab1f45b33accf5f58389e0577b8990bb3":0:"d6840f6b42f6edafd13116e0e12565202fef8e9ece7dce03812464d04b9442de"

View File

@ -116,6 +116,8 @@ void ecdh_primitive_testvec( int id, data_t * rnd_buf_A, char * xA_str,
rnd_info_A.buf = rnd_buf_A->x;
rnd_info_A.length = rnd_buf_A->len;
rnd_info_A.fallback_f_rng = mbedtls_test_rnd_std_rand;
rnd_info_A.fallback_p_rng = NULL;
/* Fix rnd_buf_A->x by shifting it left if necessary */
if( grp.nbits % 8 != 0 )
@ -132,6 +134,8 @@ void ecdh_primitive_testvec( int id, data_t * rnd_buf_A, char * xA_str,
rnd_info_B.buf = rnd_buf_B->x;
rnd_info_B.length = rnd_buf_B->len;
rnd_info_B.fallback_f_rng = mbedtls_test_rnd_std_rand;
rnd_info_B.fallback_p_rng = NULL;
/* Fix rnd_buf_B->x by shifting it left if necessary */
if( grp.nbits % 8 != 0 )
@ -238,9 +242,13 @@ void ecdh_restart( int id, data_t *dA, data_t *dB, data_t *z,
mbedtls_ecdh_init( &srv );
mbedtls_ecdh_init( &cli );
rnd_info_A.fallback_f_rng = mbedtls_test_rnd_std_rand;
rnd_info_A.fallback_p_rng = NULL;
rnd_info_A.buf = dA->x;
rnd_info_A.length = dA->len;
rnd_info_B.fallback_f_rng = mbedtls_test_rnd_std_rand;
rnd_info_B.fallback_p_rng = NULL;
rnd_info_B.buf = dB->x;
rnd_info_B.length = dB->len;
@ -341,47 +349,6 @@ exit:
}
/* END_CASE */
/* BEGIN_CASE depends_on:MBEDTLS_ECDH_LEGACY_CONTEXT */
void ecdh_exchange_legacy( int id )
{
mbedtls_ecdh_context srv, cli;
unsigned char buf[1000];
const unsigned char *vbuf;
size_t len;
mbedtls_test_rnd_pseudo_info rnd_info;
mbedtls_ecdh_init( &srv );
mbedtls_ecdh_init( &cli );
memset( &rnd_info, 0x00, sizeof( mbedtls_test_rnd_pseudo_info ) );
TEST_ASSERT( mbedtls_ecp_group_load( &srv.grp, id ) == 0 );
memset( buf, 0x00, sizeof( buf ) ); vbuf = buf;
TEST_ASSERT( mbedtls_ecdh_make_params( &srv, &len, buf, 1000,
&mbedtls_test_rnd_pseudo_rand,
&rnd_info ) == 0 );
TEST_ASSERT( mbedtls_ecdh_read_params( &cli, &vbuf, buf + len ) == 0 );
memset( buf, 0x00, sizeof( buf ) );
TEST_ASSERT( mbedtls_ecdh_make_public( &cli, &len, buf, 1000,
&mbedtls_test_rnd_pseudo_rand,
&rnd_info ) == 0 );
TEST_ASSERT( mbedtls_ecdh_read_public( &srv, buf, len ) == 0 );
TEST_ASSERT( mbedtls_ecdh_calc_secret( &srv, &len, buf, 1000,
&mbedtls_test_rnd_pseudo_rand,
&rnd_info ) == 0 );
TEST_ASSERT( mbedtls_ecdh_calc_secret( &cli, &len, buf, 1000, NULL,
NULL ) == 0 );
TEST_ASSERT( mbedtls_mpi_cmp_mpi( &srv.z, &cli.z ) == 0 );
exit:
mbedtls_ecdh_free( &srv );
mbedtls_ecdh_free( &cli );
}
/* END_CASE */
/* BEGIN_CASE */
void ecdh_exchange_calc_secret( int grp_id,
data_t *our_private_key,

View File

@ -95,6 +95,8 @@ void ecdsa_prim_test_vectors( int id, char * d_str, char * xQ_str,
TEST_ASSERT( mbedtls_mpi_read_string( &d, 16, d_str ) == 0 );
TEST_ASSERT( mbedtls_mpi_read_string( &r_check, 16, r_str ) == 0 );
TEST_ASSERT( mbedtls_mpi_read_string( &s_check, 16, s_str ) == 0 );
rnd_info.fallback_f_rng = mbedtls_test_rnd_std_rand;
rnd_info.fallback_p_rng = NULL;
rnd_info.buf = rnd_buf->x;
rnd_info.length = rnd_buf->len;

View File

@ -273,6 +273,42 @@ ECP gen keypair wrapper
depends_on:MBEDTLS_ECP_DP_SECP192R1_ENABLED
mbedtls_ecp_gen_key:MBEDTLS_ECP_DP_SECP192R1
ECP generate Montgomery key: Curve25519, random in range
genkey_mx_known_answer:254:"9e020406080a0c0e10121416181a1c1e20222426282a2c2e30323436383a3df0":"4f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8"
ECP generate Montgomery key: Curve25519, clear higher bit
genkey_mx_known_answer:254:"ff0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8":"7f808101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f78"
ECP generate Montgomery key: Curve25519, clear low bits
genkey_mx_known_answer:254:"9e020406080a0c0e10121416181a1c1e20222426282a2c2e30323436383a3dff":"4f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1ef8"
ECP generate Montgomery key: Curve25519, random = all-bits-zero
genkey_mx_known_answer:254:"0000000000000000000000000000000000000000000000000000000000000000":"4000000000000000000000000000000000000000000000000000000000000000"
ECP generate Montgomery key: Curve25519, random = all-bits-one
genkey_mx_known_answer:254:"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff":"7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8"
ECP generate Montgomery key: Curve25519, not enough entropy
genkey_mx_known_answer:254:"4f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e":""
ECP generate Montgomery key: Curve448, random in range
genkey_mx_known_answer:447:"cf0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233343536fc":"cf0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233343536fc"
ECP generate Montgomery key: Curve448, set high bit
genkey_mx_known_answer:447:"0f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233343536fc":"8f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233343536fc"
ECP generate Montgomery key: Curve448, clear low bits
genkey_mx_known_answer:447:"cf0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233343536ff":"cf0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233343536fc"
ECP generate Montgomery key: Curve448, random = all-bits-zero
genkey_mx_known_answer:447:"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000":"8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
ECP generate Montgomery key: Curve448, random = all-bits-one
genkey_mx_known_answer:447:"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff":"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"
ECP generate Montgomery key: Curve448, not enough entropy
genkey_mx_known_answer:447:"4f0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233343536":""
ECP read key #1 (short weierstrass, too small)
depends_on:MBEDTLS_ECP_DP_SECP192R1_ENABLED
mbedtls_ecp_read_key:MBEDTLS_ECP_DP_SECP192R1:"00":MBEDTLS_ERR_ECP_INVALID_KEY:0

View File

@ -15,6 +15,7 @@
#define ECP_PT_RESET( x ) \
mbedtls_ecp_point_free( x ); \
mbedtls_ecp_point_init( x );
/* END_HEADER */
/* BEGIN_DEPENDENCIES
@ -916,6 +917,55 @@ exit:
}
/* END_CASE */
/* BEGIN_CASE depends_on:MBEDTLS_TEST_HOOKS:MBEDTLS_ECP_MONTGOMERY_ENABLED */
void genkey_mx_known_answer( int bits, data_t *seed, data_t *expected )
{
mbedtls_test_rnd_buf_info rnd_info;
mbedtls_mpi d;
int ret;
uint8_t *actual = NULL;
mbedtls_mpi_init( &d );
rnd_info.buf = seed->x;
rnd_info.length = seed->len;
rnd_info.fallback_f_rng = NULL;
rnd_info.fallback_p_rng = NULL;
ASSERT_ALLOC( actual, expected->len );
ret = mbedtls_ecp_gen_privkey_mx( bits, &d,
mbedtls_test_rnd_buffer_rand, &rnd_info );
if( expected->len == 0 )
{
/* Expecting an error (happens if there isn't enough randomness) */
TEST_ASSERT( ret != 0 );
}
else
{
TEST_EQUAL( ret, 0 );
TEST_EQUAL( (size_t) bits + 1, mbedtls_mpi_bitlen( &d ) );
TEST_EQUAL( 0, mbedtls_mpi_write_binary( &d, actual, expected->len ) );
/* Test the exact result. This assumes that the output of the
* RNG is used in a specific way, which is overly constraining.
* The advantage is that it's easier to test the expected properties
* of the generated key:
* - The most significant bit must be at a specific positions
* (can be enforced by checking the bit-length).
* - The least significant bits must have specific values
* (can be enforced by checking these bits).
* - Other bits must be random (by testing with different RNG outputs,
* we validate that those bits are indeed influenced by the RNG). */
ASSERT_COMPARE( expected->x, expected->len,
actual, expected->len );
}
exit:
mbedtls_free( actual );
mbedtls_mpi_free( &d );
}
/* END_CASE */
/* BEGIN_CASE depends_on:MBEDTLS_SELF_TEST */
void ecp_selftest( )
{

View File

@ -986,46 +986,246 @@ Test bit set (Invalid bit value)
mbedtls_mpi_set_bit:16:"00":5:2:16:"00":MBEDTLS_ERR_MPI_BAD_INPUT_DATA
Fill random: 0 bytes
mpi_fill_random:0:0:0
mpi_fill_random:0:0:0:0
Fill random: 1 byte, good
mpi_fill_random:1:1:0
mpi_fill_random:1:1:0:0
Fill random: 2 bytes, good, no leading zero
mpi_fill_random:2:2:0
mpi_fill_random:2:2:0:0
Fill random: 2 bytes, good, 1 leading zero
mpi_fill_random:2:256:0
mpi_fill_random:2:256:0:0
Fill random: MAX_SIZE - 7, good
mpi_fill_random:MBEDTLS_MPI_MAX_SIZE - 7:MBEDTLS_MPI_MAX_SIZE - 7:0
mpi_fill_random:MBEDTLS_MPI_MAX_SIZE - 7:MBEDTLS_MPI_MAX_SIZE - 7:0:0
Fill random: MAX_SIZE, good
mpi_fill_random:MBEDTLS_MPI_MAX_SIZE:MBEDTLS_MPI_MAX_SIZE:0
mpi_fill_random:MBEDTLS_MPI_MAX_SIZE:MBEDTLS_MPI_MAX_SIZE:0:0
Fill random: 0 bytes, previously small >0
mpi_fill_random:0:0:1:0
Fill random: 0 bytes, previously small <0
mpi_fill_random:0:0:-1:0
Fill random: 0 bytes, previously large >0
mpi_fill_random:0:0:65:0
Fill random: 0 bytes, previously large <0
mpi_fill_random:0:0:-65:0
Fill random: 1 byte, previously small >0
mpi_fill_random:1:1:1:0
Fill random: 1 byte, previously small <0
mpi_fill_random:1:1:-1:0
Fill random: 1 byte, previously large >0
mpi_fill_random:1:1:65:0
Fill random: 1 byte, previously large <0
mpi_fill_random:1:1:-65:0
Fill random: 9 bytes, previously small >0
mpi_fill_random:1:1:1:0
Fill random: 9 bytes, previously small <0
mpi_fill_random:1:1:-1:0
Fill random: 1 byte, RNG failure
mpi_fill_random:1:0:MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
mpi_fill_random:1:0:0:MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
Fill random: 2 bytes, RNG failure after 1 byte
mpi_fill_random:2:1:MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
mpi_fill_random:2:1:0:MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
Fill random: 4 bytes, RNG failure after 3 bytes
mpi_fill_random:4:3:MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
mpi_fill_random:4:3:0:MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
Fill random: 8 bytes, RNG failure after 7 bytes
mpi_fill_random:8:7:MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
mpi_fill_random:8:7:0:MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
Fill random: 16 bytes, RNG failure after 1 bytes
mpi_fill_random:16:1:MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
mpi_fill_random:16:1:0:MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
Fill random: 16 bytes, RNG failure after 8 bytes
mpi_fill_random:16:8:MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
mpi_fill_random:16:8:0:MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
Fill random: 16 bytes, RNG failure after 15 bytes
mpi_fill_random:16:15:MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
mpi_fill_random:16:15:0:MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
Fill random: MAX_SIZE bytes, RNG failure after MAX_SIZE-1 bytes
mpi_fill_random:MBEDTLS_MPI_MAX_SIZE:MBEDTLS_MPI_MAX_SIZE-1:MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
mpi_fill_random:MBEDTLS_MPI_MAX_SIZE:MBEDTLS_MPI_MAX_SIZE-1:0:MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
MPI random in range: 1..2
mpi_random_many:1:"02":1000
MPI random in range: 1..3
mpi_random_many:1:"03":1000
MPI random in range: 1..4
mpi_random_many:1:"04":1000
MPI random in range: 1..5
mpi_random_many:1:"05":1000
MPI random in range: 1..6
mpi_random_many:1:"06":1000
MPI random in range: 1..7
mpi_random_many:1:"07":1000
MPI random in range: 1..8
mpi_random_many:1:"08":1000
MPI random in range: 1..9
mpi_random_many:1:"09":1000
MPI random in range: 1..10
mpi_random_many:1:"0a":1000
MPI random in range: 1..11
mpi_random_many:1:"0b":1000
MPI random in range: 1..12
mpi_random_many:1:"0c":1000
MPI random in range: 1..255
mpi_random_many:1:"ff":100
MPI random in range: 1..256
mpi_random_many:1:"0100":100
MPI random in range: 1..257
mpi_random_many:1:"0101":100
MPI random in range: 1..272
mpi_random_many:1:"0110":100
MPI random in range: 1..2^64-1
mpi_random_many:1:"ffffffffffffffff":100
MPI random in range: 1..2^64
mpi_random_many:1:"010000000000000000":100
MPI random in range: 1..2^64+1
mpi_random_many:1:"010000000000000001":100
MPI random in range: 1..2^64+2^63
mpi_random_many:1:"018000000000000000":100
MPI random in range: 1..2^65-1
mpi_random_many:1:"01ffffffffffffffff":100
MPI random in range: 1..2^65
mpi_random_many:1:"020000000000000000":100
MPI random in range: 1..2^65+1
mpi_random_many:1:"020000000000000001":100
MPI random in range: 1..2^65+2^64
mpi_random_many:1:"030000000000000000":100
MPI random in range: 1..2^66+2^65
mpi_random_many:1:"060000000000000000":100
MPI random in range: 1..2^71-1
mpi_random_many:1:"7fffffffffffffffff":100
MPI random in range: 1..2^71
mpi_random_many:1:"800000000000000000":100
MPI random in range: 1..2^71+1
mpi_random_many:1:"800000000000000001":100
MPI random in range: 1..2^71+2^70
mpi_random_many:1:"c00000000000000000":100
MPI random in range: 1..2^72-1
mpi_random_many:1:"ffffffffffffffffff":100
MPI random in range: 1..2^72
mpi_random_many:1:"01000000000000000000":100
MPI random in range: 1..2^72+1
mpi_random_many:1:"01000000000000000001":100
MPI random in range: 1..2^72+2^71
mpi_random_many:1:"01800000000000000000":100
MPI random in range: 0..1
mpi_random_many:0:"04":10000
MPI random in range: 0..4
mpi_random_many:0:"04":10000
MPI random in range: 2..4
mpi_random_many:2:"04":10000
MPI random in range: 3..4
mpi_random_many:3:"04":10000
MPI random in range: smaller result
mpi_random_sizes:1:"aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbb":1:0
MPI random in range: same size result (32-bit limbs)
mpi_random_sizes:1:"aaaaaaaaaaaaaaaa":2:0
MPI random in range: same size result (64-bit limbs)
mpi_random_sizes:1:"aaaaaaaaaaaaaaaa":1:0
MPI random in range: larger result
mpi_random_sizes:1:"aaaaaaaaaaaaaaaa":3:0
## The "0 limb in upper bound" tests rely on the fact that
## mbedtls_mpi_read_binary() bases the size of the MPI on the size of
## the input, without first checking for leading zeros. If this was
## not the case, the tests would still pass, but would not exercise
## the advertised behavior.
MPI random in range: leading 0 limb in upper bound #0
mpi_random_sizes:1:"00aaaaaaaaaaaaaaaa":0:0
MPI random in range: leading 0 limb in upper bound #1
mpi_random_sizes:1:"00aaaaaaaaaaaaaaaa":1:0
MPI random in range: leading 0 limb in upper bound #2
mpi_random_sizes:1:"00aaaaaaaaaaaaaaaa":2:0
MPI random in range: leading 0 limb in upper bound #3
mpi_random_sizes:1:"00aaaaaaaaaaaaaaaa":3:0
MPI random in range: leading 0 limb in upper bound #4
mpi_random_sizes:1:"00aaaaaaaaaaaaaaaa":4:0
MPI random in range: previously small >0
mpi_random_sizes:1:"1234567890":4:1
MPI random in range: previously small <0
mpi_random_sizes:1:"1234567890":4:-1
MPI random in range: previously large >0
mpi_random_sizes:1:"1234":4:65
MPI random in range: previously large <0
mpi_random_sizes:1:"1234":4:-65
MPI random bad arguments: min < 0
mpi_random_fail:-1:"04":MBEDTLS_ERR_MPI_BAD_INPUT_DATA
MPI random bad arguments: min = N = 0
mpi_random_fail:0:"00":MBEDTLS_ERR_MPI_BAD_INPUT_DATA
MPI random bad arguments: min = N = 1
mpi_random_fail:1:"01":MBEDTLS_ERR_MPI_BAD_INPUT_DATA
MPI random bad arguments: min > N = 0
mpi_random_fail:1:"00":MBEDTLS_ERR_MPI_BAD_INPUT_DATA
MPI random bad arguments: min > N = 1
mpi_random_fail:2:"01":MBEDTLS_ERR_MPI_BAD_INPUT_DATA
MPI random bad arguments: min > N = 1, 0 limb in upper bound
mpi_random_fail:2:"000000000000000001":MBEDTLS_ERR_MPI_BAD_INPUT_DATA
MPI Selftest
depends_on:MBEDTLS_SELF_TEST

View File

@ -64,6 +64,50 @@ static int f_rng_bytes_left( void *state, unsigned char *buf, size_t len )
return( 0 );
}
/* Test whether bytes represents (in big-endian base 256) a number b that
* is significantly above a power of 2. That is, b must not have a long run
* of unset bits after the most significant bit.
*
* Let n be the bit-size of b, i.e. the integer such that 2^n <= b < 2^{n+1}.
* This function returns 1 if, when drawing a number between 0 and b,
* the probability that this number is at least 2^n is not negligible.
* This probability is (b - 2^n) / b and this function checks that this
* number is above some threshold A. The threshold value is heuristic and
* based on the needs of mpi_random_many().
*/
static int is_significantly_above_a_power_of_2( data_t *bytes )
{
const uint8_t *p = bytes->x;
size_t len = bytes->len;
unsigned x;
/* Skip leading null bytes */
while( len > 0 && p[0] == 0 )
{
++p;
--len;
}
/* 0 is not significantly above a power of 2 */
if( len == 0 )
return( 0 );
/* Extract the (up to) 2 most significant bytes */
if( len == 1 )
x = p[0];
else
x = ( p[0] << 8 ) | p[1];
/* Shift the most significant bit of x to position 8 and mask it out */
while( ( x & 0xfe00 ) != 0 )
x >>= 1;
x &= 0x00ff;
/* At this point, x = floor((b - 2^n) / 2^(n-8)). b is significantly above
* a power of 2 iff x is significantly above 0 compared to 2^8.
* Testing x >= 2^4 amounts to picking A = 1/16 in the function
* description above. */
return( x >= 0x10 );
}
/* END_HEADER */
/* BEGIN_DEPENDENCIES
@ -1151,13 +1195,23 @@ exit:
/* END_CASE */
/* BEGIN_CASE */
void mpi_fill_random( int wanted_bytes, int rng_bytes, int expected_ret )
void mpi_fill_random( int wanted_bytes, int rng_bytes,
int before, int expected_ret )
{
mbedtls_mpi X;
int ret;
size_t bytes_left = rng_bytes;
mbedtls_mpi_init( &X );
if( before != 0 )
{
/* Set X to sign(before) * 2^(|before|-1) */
TEST_ASSERT( mbedtls_mpi_lset( &X, before > 0 ? 1 : -1 ) == 0 );
if( before < 0 )
before = - before;
TEST_ASSERT( mbedtls_mpi_shift_l( &X, before - 1 ) == 0 );
}
ret = mbedtls_mpi_fill_random( &X, wanted_bytes,
f_rng_bytes_left, &bytes_left );
TEST_ASSERT( ret == expected_ret );
@ -1181,6 +1235,168 @@ exit:
}
/* END_CASE */
/* BEGIN_CASE */
void mpi_random_many( int min, data_t *bound_bytes, int iterations )
{
/* Generate numbers in the range 1..bound-1. Do it iterations times.
* This function assumes that the value of bound is at least 2 and
* that iterations is large enough that a one-in-2^iterations chance
* effectively never occurs.
*/
mbedtls_mpi upper_bound;
size_t n_bits;
mbedtls_mpi result;
size_t b;
/* If upper_bound is small, stats[b] is the number of times the value b
* has been generated. Otherwise stats[b] is the number of times a
* value with bit b set has been generated. */
size_t *stats = NULL;
size_t stats_len;
int full_stats;
size_t i;
mbedtls_mpi_init( &upper_bound );
mbedtls_mpi_init( &result );
TEST_EQUAL( 0, mbedtls_mpi_read_binary( &upper_bound,
bound_bytes->x, bound_bytes->len ) );
n_bits = mbedtls_mpi_bitlen( &upper_bound );
/* Consider a bound "small" if it's less than 2^5. This value is chosen
* to be small enough that the probability of missing one value is
* negligible given the number of iterations. It must be less than
* 256 because some of the code below assumes that "small" values
* fit in a byte. */
if( n_bits <= 5 )
{
full_stats = 1;
stats_len = bound_bytes->x[bound_bytes->len - 1];
}
else
{
full_stats = 0;
stats_len = n_bits;
}
ASSERT_ALLOC( stats, stats_len );
for( i = 0; i < (size_t) iterations; i++ )
{
mbedtls_test_set_step( i );
TEST_EQUAL( 0, mbedtls_mpi_random( &result, min, &upper_bound,
mbedtls_test_rnd_std_rand, NULL ) );
TEST_ASSERT( mbedtls_mpi_cmp_mpi( &result, &upper_bound ) < 0 );
TEST_ASSERT( mbedtls_mpi_cmp_int( &result, min ) >= 0 );
if( full_stats )
{
uint8_t value;
TEST_EQUAL( 0, mbedtls_mpi_write_binary( &result, &value, 1 ) );
TEST_ASSERT( value < stats_len );
++stats[value];
}
else
{
for( b = 0; b < n_bits; b++ )
stats[b] += mbedtls_mpi_get_bit( &result, b );
}
}
if( full_stats )
{
for( b = min; b < stats_len; b++ )
{
mbedtls_test_set_step( 1000000 + b );
/* Assert that each value has been reached at least once.
* This is almost guaranteed if the iteration count is large
* enough. This is a very crude way of checking the distribution.
*/
TEST_ASSERT( stats[b] > 0 );
}
}
else
{
int statistically_safe_all_the_way =
is_significantly_above_a_power_of_2( bound_bytes );
for( b = 0; b < n_bits; b++ )
{
mbedtls_test_set_step( 1000000 + b );
/* Assert that each bit has been set in at least one result and
* clear in at least one result. Provided that iterations is not
* too small, it would be extremely unlikely for this not to be
* the case if the results are uniformly distributed.
*
* As an exception, the top bit may legitimately never be set
* if bound is a power of 2 or only slightly above.
*/
if( statistically_safe_all_the_way || b != n_bits - 1 )
{
TEST_ASSERT( stats[b] > 0 );
}
TEST_ASSERT( stats[b] < (size_t) iterations );
}
}
exit:
mbedtls_mpi_free( &upper_bound );
mbedtls_mpi_free( &result );
mbedtls_free( stats );
}
/* END_CASE */
/* BEGIN_CASE */
void mpi_random_sizes( int min, data_t *bound_bytes, int nlimbs, int before )
{
mbedtls_mpi upper_bound;
mbedtls_mpi result;
mbedtls_mpi_init( &upper_bound );
mbedtls_mpi_init( &result );
if( before != 0 )
{
/* Set result to sign(before) * 2^(|before|-1) */
TEST_ASSERT( mbedtls_mpi_lset( &result, before > 0 ? 1 : -1 ) == 0 );
if( before < 0 )
before = - before;
TEST_ASSERT( mbedtls_mpi_shift_l( &result, before - 1 ) == 0 );
}
TEST_EQUAL( 0, mbedtls_mpi_grow( &result, nlimbs ) );
TEST_EQUAL( 0, mbedtls_mpi_read_binary( &upper_bound,
bound_bytes->x, bound_bytes->len ) );
TEST_EQUAL( 0, mbedtls_mpi_random( &result, min, &upper_bound,
mbedtls_test_rnd_std_rand, NULL ) );
TEST_ASSERT( mbedtls_mpi_cmp_mpi( &result, &upper_bound ) < 0 );
TEST_ASSERT( mbedtls_mpi_cmp_int( &result, min ) >= 0 );
exit:
mbedtls_mpi_free( &upper_bound );
mbedtls_mpi_free( &result );
}
/* END_CASE */
/* BEGIN_CASE */
void mpi_random_fail( int min, data_t *bound_bytes, int expected_ret )
{
mbedtls_mpi upper_bound;
mbedtls_mpi result;
int actual_ret;
mbedtls_mpi_init( &upper_bound );
mbedtls_mpi_init( &result );
TEST_EQUAL( 0, mbedtls_mpi_read_binary( &upper_bound,
bound_bytes->x, bound_bytes->len ) );
actual_ret = mbedtls_mpi_random( &result, min, &upper_bound,
mbedtls_test_rnd_std_rand, NULL );
TEST_EQUAL( expected_ret, actual_ret );
exit:
mbedtls_mpi_free( &upper_bound );
mbedtls_mpi_free( &result );
}
/* END_CASE */
/* BEGIN_CASE depends_on:MBEDTLS_SELF_TEST */
void mpi_selftest( )
{

View File

@ -19,6 +19,8 @@ void pkcs1_rsaes_v15_encrypt( int mod, int radix_N, char * input_N,
mbedtls_test_rnd_buf_info info;
mbedtls_mpi N, E;
info.fallback_f_rng = mbedtls_test_rnd_std_rand;
info.fallback_p_rng = NULL;
info.buf = rnd_buf->x;
info.length = rnd_buf->len;
@ -268,6 +270,8 @@ void pkcs1_rsassa_v15_sign( int mod, int radix_P, char * input_P, int radix_Q,
mbedtls_mpi N, P, Q, E;
mbedtls_test_rnd_buf_info info;
info.fallback_f_rng = mbedtls_test_rnd_std_rand;
info.fallback_p_rng = NULL;
info.buf = rnd_buf->x;
info.length = rnd_buf->len;

View File

@ -18,6 +18,8 @@ void pkcs1_rsaes_oaep_encrypt( int mod, data_t * input_N, data_t * input_E,
mbedtls_test_rnd_buf_info info;
mbedtls_mpi N, E;
info.fallback_f_rng = mbedtls_test_rnd_std_rand;
info.fallback_p_rng = NULL;
info.buf = rnd_buf->x;
info.length = rnd_buf->len;
@ -122,6 +124,8 @@ void pkcs1_rsassa_pss_sign( int mod, data_t * input_P, data_t * input_Q,
mbedtls_test_rnd_buf_info info;
mbedtls_mpi N, P, Q, E;
info.fallback_f_rng = mbedtls_test_rnd_std_rand;
info.fallback_p_rng = NULL;
info.buf = rnd_buf->x;
info.length = rnd_buf->len;

View File

@ -989,7 +989,7 @@ depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_ECP_C:MBEDTLS_ECP_DP_BP512R1_ENABLED
pk_parse_public_keyfile_ec:"data_files/ec_bp512_pub.pem":0
Parse EC Key #1 (SEC1 DER)
depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_ECP_C:MBEDTLS_ECP_DP_SECP192R1_ENABLED
depends_on:MBEDTLS_ECP_C:MBEDTLS_ECP_DP_SECP192R1_ENABLED
pk_parse_keyfile_ec:"data_files/ec_prv.sec1.der":"NULL":0
Parse EC Key #2 (SEC1 PEM)
@ -1005,15 +1005,15 @@ depends_on:MBEDTLS_ECP_C:MBEDTLS_ECP_DP_SECP192R1_ENABLED
pk_parse_keyfile_ec:"data_files/ec_prv.pk8.der":"NULL":0
Parse EC Key #4a (PKCS8 DER, no public key)
depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_ECP_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED
depends_on:MBEDTLS_ECP_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED
pk_parse_keyfile_ec:"data_files/ec_prv.pk8nopub.der":"NULL":0
Parse EC Key #4b (PKCS8 DER, no public key, with parameters)
depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_ECP_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED
depends_on:MBEDTLS_ECP_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED
pk_parse_keyfile_ec:"data_files/ec_prv.pk8nopubparam.der":"NULL":0
Parse EC Key #4c (PKCS8 DER, with parameters)
depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_ECP_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED
depends_on:MBEDTLS_ECP_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED
pk_parse_keyfile_ec:"data_files/ec_prv.pk8param.der":"NULL":0
Parse EC Key #5 (PKCS8 PEM)
@ -1069,7 +1069,7 @@ depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_ECP_C:MBEDTLS_ECP_DP_BP512R1_ENABLED
pk_parse_keyfile_ec:"data_files/ec_bp512_prv.pem":"NULL":0
Parse EC Key #15 (SEC1 DER, secp256k1, SpecifiedECDomain)
depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_ECP_C:MBEDTLS_ECP_DP_SECP256K1_ENABLED:MBEDTLS_PK_PARSE_EC_EXTENDED
depends_on:MBEDTLS_ECP_C:MBEDTLS_ECP_DP_SECP256K1_ENABLED:MBEDTLS_PK_PARSE_EC_EXTENDED
pk_parse_keyfile_ec:"data_files/ec_prv.specdom.der":"NULL":0
Key ASN1 (No data)

View File

@ -7,6 +7,8 @@
#include <psa_crypto_its.h>
#define TEST_FLAG_EXERCISE 0x00000001
/** Write a key with the given attributes and key material to storage.
* Test that it has the expected representation.
*
@ -67,7 +69,7 @@ static int test_read_key( const psa_key_attributes_t *expected_attributes,
const data_t *expected_material,
psa_storage_uid_t uid,
const data_t *representation,
int exercise )
int flags )
{
psa_key_attributes_t actual_attributes = PSA_KEY_ATTRIBUTES_INIT;
mbedtls_svc_key_id_t key_id = psa_get_key_id( expected_attributes );
@ -105,7 +107,7 @@ static int test_read_key( const psa_key_attributes_t *expected_attributes,
exported_material, length );
}
if( exercise )
if( flags & TEST_FLAG_EXERCISE )
{
TEST_ASSERT( mbedtls_test_psa_exercise_key(
key_id,
@ -183,7 +185,7 @@ exit:
void key_storage_read( int lifetime_arg, int type_arg, int bits_arg,
int usage_arg, int alg_arg, int alg2_arg,
data_t *material,
data_t *representation, int exercise )
data_t *representation, int flags )
{
/* Backward compatibility: read a key in the format of a past version
* and check that this version can use it. */
@ -213,7 +215,7 @@ void key_storage_read( int lifetime_arg, int type_arg, int bits_arg,
* guarantees backward compatibility with keys that were stored by
* past versions of Mbed TLS. */
TEST_ASSERT( test_read_key( &attributes, material,
uid, representation, exercise ) );
uid, representation, flags ) );
exit:
psa_reset_key_attributes( &attributes );

View File

@ -1,3 +1,15 @@
Attempt to register multiple PSKs
test_multiple_psks:
Attempt to register multiple PSKS, incl. opaque PSK, #0
test_multiple_psks_opaque:0
Attempt to register multiple PSKs, incl. opaque PSK, #1
test_multiple_psks_opaque:1
Attempt to register multiple PSKs, incl. opaque PSK, #2
test_multiple_psks_opaque:2
Test calback buffer sanity
test_callback_buffer_sanity:

View File

@ -8,6 +8,8 @@
#include <ssl_tls13_keys.h>
#include "test/certs.h"
#include <psa/crypto.h>
#include <ssl_invasive.h>
#include <test/constant_flow.h>
@ -4535,3 +4537,109 @@ exit:
mbedtls_free( src );
}
/* END_CASE */
/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
void test_multiple_psks()
{
unsigned char psk0[10] = { 0 };
unsigned char psk0_identity[] = { 'f', 'o', 'o' };
unsigned char psk1[10] = { 0 };
unsigned char psk1_identity[] = { 'b', 'a', 'r' };
mbedtls_ssl_config conf;
mbedtls_ssl_config_init( &conf );
TEST_ASSERT( mbedtls_ssl_conf_psk( &conf,
psk0, sizeof( psk0 ),
psk0_identity, sizeof( psk0_identity ) ) == 0 );
TEST_ASSERT( mbedtls_ssl_conf_psk( &conf,
psk1, sizeof( psk1 ),
psk1_identity, sizeof( psk1_identity ) ) ==
MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
exit:
mbedtls_ssl_config_free( &conf );
}
/* END_CASE */
/* BEGIN_CASE depends_on:MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED:MBEDTLS_USE_PSA_CRYPTO */
void test_multiple_psks_opaque( int mode )
{
/*
* Mode 0: Raw PSK, then opaque PSK
* Mode 1: Opaque PSK, then raw PSK
* Mode 2: 2x opaque PSK
*/
unsigned char psk0_raw[10] = { 0 };
unsigned char psk0_raw_identity[] = { 'f', 'o', 'o' };
psa_key_id_t psk0_opaque = (psa_key_id_t) 1;
unsigned char psk0_opaque_identity[] = { 'f', 'o', 'o' };
unsigned char psk1_raw[10] = { 0 };
unsigned char psk1_raw_identity[] = { 'b', 'a', 'r' };
psa_key_id_t psk1_opaque = (psa_key_id_t) 2;
unsigned char psk1_opaque_identity[] = { 'b', 'a', 'r' };
mbedtls_ssl_config conf;
USE_PSA_INIT( );
mbedtls_ssl_config_init( &conf );
switch( mode )
{
case 0:
TEST_ASSERT( mbedtls_ssl_conf_psk( &conf,
psk0_raw, sizeof( psk0_raw ),
psk0_raw_identity, sizeof( psk0_raw_identity ) )
== 0 );
TEST_ASSERT( mbedtls_ssl_conf_psk_opaque( &conf,
psk1_opaque,
psk1_opaque_identity, sizeof( psk1_opaque_identity ) )
== MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
break;
case 1:
TEST_ASSERT( mbedtls_ssl_conf_psk_opaque( &conf,
psk0_opaque,
psk0_opaque_identity, sizeof( psk0_opaque_identity ) )
== 0 );
TEST_ASSERT( mbedtls_ssl_conf_psk( &conf,
psk1_raw, sizeof( psk1_raw ),
psk1_raw_identity, sizeof( psk1_raw_identity ) )
== MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
break;
case 2:
TEST_ASSERT( mbedtls_ssl_conf_psk_opaque( &conf,
psk0_opaque,
psk0_opaque_identity, sizeof( psk0_opaque_identity ) )
== 0 );
TEST_ASSERT( mbedtls_ssl_conf_psk_opaque( &conf,
psk1_opaque,
psk1_opaque_identity, sizeof( psk1_opaque_identity ) )
== MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
break;
default:
TEST_ASSERT( 0 );
break;
}
exit:
mbedtls_ssl_config_free( &conf );
USE_PSA_DONE( );
}
/* END_CASE */

View File

@ -178,10 +178,6 @@ X509 CRT information Non-ASCII string in issuer name and subject name
depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
x509_cert_info:"data_files/non-ascii-string-in-issuer.crt":"cert. version \: 3\nserial number \: 05\:E6\:53\:E7\:1B\:74\:F0\:B5\:D3\:84\:6D\:0C\:6D\:DC\:FA\:3F\:A4\:5A\:2B\:E0\nissuer name \: C=JP, ST=Tokyo, O=?????????????????? Ltd, CN=?????????????????? CA\nsubject name \: C=JP, ST=Tokyo, O=?????????????????? Ltd, CN=?????????????????? CA\nissued on \: 2020-05-20 16\:17\:23\nexpires on \: 2020-06-19 16\:17\:23\nsigned using \: RSA with SHA-256\nRSA key size \: 2048 bits\nbasic constraints \: CA=true\n"
X509 certificate v1 with extension
depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_RSA_C:MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3:MBEDTLS_SHA1_C
x509_cert_info:"data_files/cert_v1_with_ext.crt":"cert. version \: 1\nserial number \: BD\:ED\:44\:C7\:D2\:3E\:C2\:A4\nissuer name \: C=XX, ST=XX, L=XX, O=XX, OU=XX, emailAddress=admin@identity-check.org, CN=identity-check.org\nsubject name \: C=XX, ST=XX, L=XX, O=XX, OU=XX, emailAddress=admin@identity-check.org, CN=identity-check.org\nissued on \: 2013-07-04 16\:17\:02\nexpires on \: 2014-07-04 16\:17\:02\nsigned using \: RSA with SHA1\nRSA key size \: 2048 bits\nsubject alt name \:\n dNSName \: identity-check.org\n dNSName \: www.identity-check.org\n <unsupported>\n"
X509 SAN parsing otherName
depends_on:MBEDTLS_PEM_PARSE_C:MBEDTLS_ECDSA_C:MBEDTLS_ECP_DP_SECP256R1_ENABLED:MBEDTLS_SHA256_C
x509_parse_san:"data_files/server5-othername.crt":"type \: 0\notherName \: hardware module name \: hardware type \: 1.3.6.1.4.1.17.3, hardware serial number \: 123456\n"
@ -1575,7 +1571,7 @@ depends_on:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
x509parse_crt:"308198308182a0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D010101050003190030160210ffffffffffffffffffffffffffffffff0202ffffa201300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_OUT_OF_DATA
X509 CRT ASN1 (TBS, valid IssuerID, inv SubjectID, inv tag)
depends_on:!MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
depends_on:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
x509parse_crt:"30819a308184a0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D010101050003190030160210ffffffffffffffffffffffffffffffff0202ffffa1000500300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH
X509 CRT ASN1 (TBSCertificate v3, ext SubjectAlternativeName malformed)
@ -1595,21 +1591,13 @@ depends_on:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
x509parse_crt:"30819a308184a0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D010101050003190030160210ffffffffffffffffffffffffffffffff0202ffffa100a201300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_OUT_OF_DATA
X509 CRT ASN1 (TBS, IssuerID unsupported in v1 CRT)
depends_on:!MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
depends_on:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
x509parse_crt:"30819a308184a0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D010101050003190030160210ffffffffffffffffffffffffffffffff0202ffffa100a201300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH
X509 CRT ASN1 (TBS, IssuerID unsupported in v1 CRT, ALLOW_EXTENSIONS_NON_V3)
depends_on:MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
x509parse_crt:"30819a308184a0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D010101050003190030160210ffffffffffffffffffffffffffffffff0202ffffa100a201300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG
X509 CRT ASN1 (TBS, SubjectID unsupported in v1 CRT)
depends_on:!MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
depends_on:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
x509parse_crt:"30819a308184a0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D010101050003190030160210ffffffffffffffffffffffffffffffff0202ffffa200a201300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH
X509 CRT ASN1 (TBS, SubjectID unsupported in v1 CRT, ALLOW_EXTENSIONS_NON_V3)
depends_on:MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
x509parse_crt:"30819a308184a0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D010101050003190030160210ffffffffffffffffffffffffffffffff0202ffffa200a201300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG
X509 CRT ASN1 (TBS, inv v3Ext, inv tag)
depends_on:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
x509parse_crt:"30819c308186a0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D010101050003190030160210ffffffffffffffffffffffffffffffff0202ffffa100a2000500300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_X509_INVALID_EXTENSIONS + MBEDTLS_ERR_ASN1_UNEXPECTED_TAG
@ -1858,24 +1846,16 @@ X509 CRT ASN1 (TBS, inv v3Ext, SubjectAltName repeated outside Extensions)
depends_on:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
x509parse_crt:"3081dc3081c6a0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D010101050003190030160210ffffffffffffffffffffffffffffffff0202ffffa100a200a321301f301d0603551d11041630148208666f6f2e7465737482086261722e74657374301d0603551d11041630148208666f6f2e7465737482086261722e74657374300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH
X509 CRT (TBS, valid v3Ext in v1 CRT, ALLOW_EXTENSIONS_NON_V3)
depends_on:MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
x509parse_crt:"3081b93081a3a0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D010101050003190030160210ffffffffffffffffffffffffffffffff0202ffffa321301f301d0603551d11041630148208666f6f2e7465737482086261722e74657374300d06092a864886f70d01010b0500030200ff":"cert. version \: 1\nserial number \: DE\:AD\:BE\:EF\nissuer name \: ??=Test\nsubject name \: ??=Test\nissued on \: 2009-01-01 00\:00\:00\nexpires on \: 2009-12-31 23\:59\:59\nsigned using \: RSA with SHA-256\nRSA key size \: 128 bits\nsubject alt name \:\n dNSName \: foo.test\n dNSName \: bar.test\n":0
X509 CRT (TBS, valid v3Ext in v2 CRT, ALLOW_EXTENSIONS_NON_V3)
depends_on:MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
x509parse_crt:"3081b93081a3a0030201018204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D010101050003190030160210ffffffffffffffffffffffffffffffff0202ffffa321301f301d0603551d11041630148208666f6f2e7465737482086261722e74657374300d06092a864886f70d01010b0500030200ff":"cert. version \: 2\nserial number \: DE\:AD\:BE\:EF\nissuer name \: ??=Test\nsubject name \: ??=Test\nissued on \: 2009-01-01 00\:00\:00\nexpires on \: 2009-12-31 23\:59\:59\nsigned using \: RSA with SHA-256\nRSA key size \: 128 bits\nsubject alt name \:\n dNSName \: foo.test\n dNSName \: bar.test\n":0
X509 CRT (TBS, valid v3Ext in v3 CRT)
depends_on:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
x509parse_crt:"3081b93081a3a0030201028204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D010101050003190030160210ffffffffffffffffffffffffffffffff0202ffffa321301f301d0603551d11041630148208666f6f2e7465737482086261722e74657374300d06092a864886f70d01010b0500030200ff":"cert. version \: 3\nserial number \: DE\:AD\:BE\:EF\nissuer name \: ??=Test\nsubject name \: ??=Test\nissued on \: 2009-01-01 00\:00\:00\nexpires on \: 2009-12-31 23\:59\:59\nsigned using \: RSA with SHA-256\nRSA key size \: 128 bits\nsubject alt name \:\n dNSName \: foo.test\n dNSName \: bar.test\n":0
X509 CRT ASN1 (TBS, valid v3Ext in v1 CRT)
depends_on:!MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
depends_on:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
x509parse_crt:"3081b93081a3a0030201008204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D010101050003190030160210ffffffffffffffffffffffffffffffff0202ffffa321301f301d0603551d11041630148208666f6f2e7465737482086261722e74657374300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH
X509 CRT ASN1 (TBS, valid v3Ext in v2 CRT)
depends_on:!MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
depends_on:MBEDTLS_RSA_C:MBEDTLS_SHA256_C
x509parse_crt:"3081b93081a3a0030201018204deadbeef300d06092a864886f70d01010b0500300c310a30080600130454657374301c170c303930313031303030303030170c303931323331323335393539300c310a30080600130454657374302a300d06092A864886F70D010101050003190030160210ffffffffffffffffffffffffffffffff0202ffffa321301f301d0603551d11041630148208666f6f2e7465737482086261722e74657374300d06092a864886f70d01010b0500030200ff":"":MBEDTLS_ERR_X509_INVALID_FORMAT + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH
X509 CRT ASN1 (TBS, valid SubjectID, valid IssuerID, inv v3Ext, SubjectAltName repeated outside Extensions, inv SubjectAltNames tag)