So far, we've used the `peer_cert` pointer to detect whether
we're parsing the first CRT, but that will soon be removed
if `MBEDTLS_SSL_KEEP_PEER_CERTIFICATE` is unset.
This commit introduces a helper function `ssl_clear_peer_cert()`
which frees all data related to the peer's certificate from an
`mbedtls_ssl_session` structure. Currently, this is the peer's
certificate itself, while eventually, it'll be its digest only.
After mitigating the 'triple handshake attack' by checking that
the peer's end-CRT didn't change during renegotation, the current
code avoids re-parsing the CRT by moving the CRT-pointer from the
old session to the new one. While efficient, this will no longer
work once only the hash of the peer's CRT is stored beyond the
handshake.
This commit removes the code-path moving the old CRT, and instead
frees the entire peer CRT chain from the initial handshake as soon
as the 'triple handshake attack' protection has completed.
Renamed the tests because they are explicitly testing Curve25519 and
nothing else. Improved test coverage, test documentation and extended
in-code documentation with a specific reference to the standard as well.
The library is able to perform computations and cryptographic schemes on
curves with x coordinate ladder representation. Here we add the
capability to export such points.
The function `mbedtls_mpi_write_binary()` writes big endian byte order,
but we need to be able to write little endian in some caseses. (For
example when handling keys corresponding to Montgomery curves.)
Used `echo xx | tac -rs ..` to transform the test data to little endian.
The private keys used in ECDH differ in the case of Weierstrass and
Montgomery curves. They have different constraints, the former is based
on big endian, the latter little endian byte order. The fundamental
approach is different too:
- Weierstrass keys have to be in the right interval, otherwise they are
rejected.
- Any byte array of the right size is a valid Montgomery key and it
needs to be masked before interpreting it as a number.
Historically it was sufficient to use mbedtls_mpi_read_binary() to read
private keys, but as a preparation to improve support for Montgomery
curves we add mbedtls_ecp_read_key() to enable uniform treatment of EC
keys.
For the masking the `mbedtls_mpi_set_bit()` function is used. This is
suboptimal but seems to provide the best trade-off at this time.
Alternatives considered:
- Making a copy of the input buffer (less efficient)
- removing the `const` constraint from the input buffer (breaks the api
and makes it less user friendly)
- applying the mask directly to the limbs (violates the api between the
modules and creates and unwanted dependency)
The library is able to perform computations and cryptographic schemes on
curves with x coordinate ladder representation. Here we add the
capability to import such points.
The function `mbedtls_mpi_read_binary()` expects big endian byte order,
but we need to be able to read from little endian in some caseses. (For
example when handling keys corresponding to Montgomery curves.)
Used `echo xx | tac -rs .. | tr [a-z] [A-Z]` to transform the test data
to little endian and `echo "ibase=16;xx" | bc` to convert to decimal.
Define MBEDTLS_ECDH_LEGACY_CONTEXT in config.h instead of hard-coding
this in ecdh.h so that its absence can be tested. Document it as
experimental so that we reserve the right to change it in the future.
If mbedtls_ecdh_get_params is called with keys belonging to
different groups, make it return an error the second time, rather than
silently interpret the first key as being on the second curve.
This makes the non-regression test added by the previous commit pass.
This commit improves hygiene and formatting of macro definitions
throughout the library. Specifically:
- It adds brackets around parameters to avoid unintended
interpretation of arguments, e.g. due to operator precedence.
- It adds uses of the `do { ... } while( 0 )` idiom for macros that
can be used as commands.
- Populate the ECDH private key slot with a fresh private EC key
designated for the correct algorithm.
- Export the public part of the ECDH private key from PSA and
reformat it to suite the format of the ClientKeyExchange message.
- Perform the PSA-based ECDH key agreement and store the result
as the premaster secret for the connection.
- Reformat the server's ECDH public key to make it suitable
for the PSA key agreement API. Currently, the key agreement
API needs a full SubjectPublicKeyInfo structure, while the
TLS ServerKeyExchange message only contains a ECPoint structure.
Enable handling of zero-length null output in PKCS1 v1.5 decryption.
Prevent undefined behavior by avoiding a memcpy() to zero-length null
output buffers.
In mbedtls_rsa_rsaes_oaep_encrypt and
mbedtls_rsa_rsaes_pkcs1_v15_encrypt, if the input length is 0 (which
is unusual and mostly useless, but permitted) then it is fine for the
input pointer to be NULL. Don't return an error in this case.
When `input` is NULL, `memcpy( p, input, ilen )` has undefined behavior
even if `ilen` is zero. So skip the `memcpy` call in this case.
Likewise, in `mbedtls_rsa_rsaes_oaep_decrypt`, skip the `memcpy` call if
`*olen` is zero.
Context: During a handshake, the SSL/TLS handshake logic constructs
an instance of ::mbedtls_ssl_session representing the SSL session
being established. This structure contains information such as the
session's master secret, the peer certificate, or the session ticket
issues by the server (if applicable).
During a renegotiation, the new session is constructed aside the existing
one and destroys and replaces the latter only when the renegotiation is
complete. While conceptually clear, this means that during the renegotiation,
large pieces of information such as the peer's CRT or the session ticket
exist twice in memory, even though the original versions are removed
eventually.
This commit removes the simultaneous presence of two peer CRT chains
in memory during renegotiation, in the following way:
- Unlike in the case of SessionTickets handled in the previous commit,
we cannot simply free the peer's CRT chain from the previous handshake
before parsing the new one, as we need to verify that the peer's end-CRT
hasn't changed to mitigate the 'Triple Handshake Attack'.
- Instead, we perform a binary comparison of the original peer end-CRT
with the one presented during renegotiation, and if it succeeds, we
avoid re-parsing CRT by moving the corresponding CRT pointer from the
old to the new session structure.
- The remaining CRTs in the peer's chain are not affected by the triple
handshake attack protection, and for them we may employ the canonical
approach of freeing them before parsing the remainder of the new chain.
Note that this commit intends to not change any observable behavior
of the stack. In particular:
- The peer's CRT chain is still verified during renegotiation.
- The tail of the peer's CRT chain may change during renegotiation.
Context: During a handshake, the SSL/TLS handshake logic constructs
an instance of ::mbedtls_ssl_session representing the SSL session
being established. This structure contains information such as the
session's master secret, the peer certificate, or the session ticket
issues by the server (if applicable).
During a renegotiation, the new session is constructed aside the existing
one and destroys and replaces the latter only when the renegotiation is
complete. While conceptually clear, this means that during the renegotiation,
large pieces of information such as the peer's CRT or the session ticket
exist twice in memory, even though the original versions are removed
eventually.
This commit starts removing this memory inefficiency by freeing the old
session's SessionTicket before the one for the new session is allocated.
Context:
The existing API `mbedtls_x509_parse_crt_der()` for parsing DER
encoded X.509 CRTs unconditionally makes creates a copy of the
input buffer in RAM. While this comes at the benefit of easy use,
-- specifically: allowing the user to free or re-use the input
buffer right after the call -- it creates a significant memory
overhead, as the CRT is duplicated in memory (at least temporarily).
This might not be tolerable a resource constrained device.
As a remedy, this commit adds a new X.509 API call
`mbedtls_x509_parse_crt_der_nocopy()`
which has the same signature as `mbedtls_x509_parse_crt_der()`
and almost the same semantics, with one difference: The input
buffer must persist and be unmodified for the lifetime of the
established instance of `mbedtls_x509_crt`, that is, until
`mbedtls_x509_crt_free()` is called.
Resolve incompatibilties in the RSA module where changes made for
parameter validation prevent Mbed Crypto from working. Mbed Crypto
depends on being able to pass zero-length buffers that are NULL to RSA
encryption functions.
This reverts commit 2f660d047d.
Context: There are two public key writing functions in Mbed TLS. First,
mbedtls_pk_write_pubkey(), which exports a public key in the form of a
SubjectPublicKey structure containing the raw keying material
(for example, EC point coordinates for an EC public key, without
reference to the underlying curve). Secondly, mbedtls_pk_write_pubkey_der(),
which exports a public key in the form of a SubjectPublicKeyInfo structure,
wrapping the SubjectPublicKey structure by additional information
identifying the type of public key (and for ECC, e.g., it'd also contain
the ECC group identifier). The implementation of mbedtls_pk_write_pubkey_der()
calls mbedtls_pk_write_pubkey() first and then adds the corresponding
algorithm identifier wrapper.
Both of these functions need to be provided for PSA-based opaque PK contexts,
based on PSA's public key export function.
Previously, PSA used the SubjectPublicKeyInfo structure as its export format,
so mbedtls_pk_write_pubkey_der() could be easily implemented, while
mbedtls_pk_write_pubkey() would need to trim the output of the PSA export.
The previous implementation of mbedtls_pk_write_pubkey() is not quite right
because it calls PSA export doesn't do any trimming, hence exporting the large
SubjectPublicKeyInfo structure instead of the small SubjectPublicKey.
mbedtls_pk_write_pubkey_der(), in turn, immediately returns after calling
mbedtls_pk_write_pubkey(), hence also returning the SubjectPublicKeyInfo
structure, which is correct.
By now, the PSA public key export format has changed to the smaller
SubjectPublicKey structure. This means that, now, mbedtls_pk_write_pubkey()
can be implemented by just calling the PSA export, and that
mbedtls_pk_write_pubkey_der() needs to add the algorithm information around
it, just as in the other types of PK contexts. While not correct for the
old format, the existing code for mbedtls_pk_write_pubkey() is therefore
correct for the new PSA public key format, and needs no change apart from
the missing pointer shift in the last commit.
The implementation of mbedtls_pk_write_pubkey_der() needs a special code
path for PSA-based opaque PK contexts, as the PK context only contains
the PSA key handle, and the PSA API needs to be used to extract the
underlying EC curve to be able to write the AlgorithmParameter structure
that's part of the SubjectPublicKeyInfo structure.
That's what this commit does, (hopefully) making both
mbedtls_pk_write_pubkey() and mbedtls_pk_write_pubkey_der() export
the correctly formatted public key based on the new PSA public key format.
In mbedtls_mpi_exp_mod(), the limit check on wsize is never true when
MBEDTLS_MPI_WINDOW_SIZE is at least 6. Wrap in a preprocessor guard
to remove the dead code and resolve a Coverity finding from the
DEADCODE checker.
Change-Id: Ice7739031a9e8249283a04de11150565b613ae89
Additional changes to temporarily enable running tests:
ssl_srv.c and test_suite_ecdh use mbedtls_ecp_group_load instead of
mbedtls_ecdh_setup
test_suite_ctr_drbg uses mbedtls_ctr_drbg_update instead of
mbedtls_ctr_drbg_update_ret
Previously, PSA used SubjectPublicKeyInfo structures to serialize EC public keys.
This has recently been changed to using ECPoint structures instead, but the wrapper
making PSA ECDSA verification available through Mbed TLS' PK API hasn't yet been
adapted accordingly - which is what this commit does.
Luckily, Mbed TLS' PK API offers two functions mbedtls_pk_write_pubkey()
and mbedtls_pk_write_pubkey_der(), the latter exporting a SubjectPublicKeyInfo
structure and the former exporting an ECPoint structure in case of EC public
keys. For the adaptation of the ECDSA wrapper ecdsa_verify_wrap() it is therefore
sufficient to use mbedtls_pk_write_pubkey() instead of mbedtls_pk_write_pubkey_der().
The file oid.c had conditional inclusion of functions based on a config.h
define that belongs to X.509, which is backwards. For now, just include those
functions unconditionally and rely on the linker to garbage-collect them if
not used.
In the longer term X.509-specific functions are likely to be removed from
libmbedcrypto, but at this step the goal is to preserve the API (and even ABI)
of libmbedcrypto for as long as possible while separating the source trees of
Mbed Crypto and Mbed TLS.
As agreed during the workshop, temporarily move definitions to oid.h even if
they might not semantically belong here, as a short-term measure allowing to
build libmbecrypto on its own (without X.509 files present in the source tree)
but still provide all the things Mbed TLS currently expects, and more
specifically preserve the API and ABI exposed by libmbedtls.
Return the error code if failed, instead of returning value `1`.
If not failed, return the call of the underlying function,
in `mbedtls_ecdsa_genkey()`.
Use `cmake -D CMAKE_BUILD_TYPE=Asan` rather than manually setting
`-fsanitize=address`. This lets cmake determine the necessary compiler
and linker flags.
With UNSAFE_BUILD on, force -Wno-error. This is necessary to build
with MBEDTLS_TEST_NULL_ENTROPY.
mbedtls_mpi_read_binary() calls memcpy() with the source pointer being
the source pointer passed to mbedtls_mpi_read_binary(), the latter may
be NULL if the buffer length is 0 (and this happens e.g. in the ECJPAKE
test suite). The behavior of memcpy(), in contrast, is undefined when
called with NULL source buffer, even if the length of the copy operation
is 0.
This commit fixes this by explicitly checking that the source pointer is
not NULL before calling memcpy(), and skipping the call otherwise.
Context: The function `mbedtls_mpi_fill_random()` uses a temporary stack
buffer to hold the random data before reading it into the target MPI.
Problem: This is inefficient both computationally and memory-wise.
Memory-wise, it may lead to a stack overflow on constrained devices with
limited stack.
Fix: This commit introduces the following changes to get rid of the
temporary stack buffer entirely:
1. It modifies the call to the PRNG to output the random data directly
into the target MPI's data buffer.
This alone, however, constitutes a change of observable behaviour:
The previous implementation guaranteed to interpret the bytes emitted by
the PRNG in a big-endian fashion, while rerouting the PRNG output into the
target MPI's limb array leads to an interpretation that depends on the
endianness of the host machine.
As a remedy, the following change is applied, too:
2. Reorder the bytes emitted from the PRNG within the target MPI's
data buffer to ensure big-endian semantics.
Luckily, the byte reordering was already implemented as part of
`mbedtls_mpi_read_binary()`, so:
3. Extract bigendian-to-host byte reordering from
`mbedtls_mpi_read_binary()` to a separate internal function
`mpi_bigendian_to_host()` to be used by `mbedtls_mpi_read_binary()`
and `mbedtls_mpi_fill_random()`.
The calls to cipher_finish didn't actually do anything:
- the cipher mode is always ECB
- in that case cipher_finish() only sets *olen to zero, and returns either 0
or an error depending on whether there was pending data
- olen is a local variable in the caller, so setting it to zero right before
returning is not essential
- the return value of cipher_finis() was not checked by the caller so that's
not useful either
- the cipher layer does not have ALT implementations so the behaviour
described above is unconditional on ALT implementations (in particular,
cipher_finish() can't be useful to hardware as (with ECB) it doesn't call any
functions from lower-level modules that could release resources for example)
Since the calls are causing issues with parameter validation, and were no
serving any functional purpose, it's simpler to just remove them.
Somehow, mbedtls_sha256_ret() is defined even if MBEDTLS_SHA256_ALT
is set, and it is using SHA256_VALIDATE_RET. The documentation should
be enhanced to indicate that MBEDTLS_SHA256_ALT does _not_ replace
the entire module, but only the core SHA-256 functions.
Somehow, mbedtls_sha512_ret() is defined even if MBEDTLS_SHA512_ALT
is set, and it is using SHA512_VALIDATE_RET. The documentation should
be enhanced to indicate that MBEDTLS_SHA512_ALT does _not_ replace
the entire module, but only the core SHA-512 functions.
Somehow, mbedtls_sha1_ret() is defined even if MBEDTLS_SHA1_ALT
is set, and it is using SHA1_VALIDATE_RET. The documentation should
be enhanced to indicate that MBEDTLS_SHA1_ALT does _not_ replace
the entire module, but only the core SHA-1 functions.
Document when a context must be initialized or not, when it must be
set up or not, and whether it needs a private key or a public key will
do.
The implementation is sometimes more liberal than the documentation,
accepting a non-set-up context as a context that can't perform the
requested information. This preserves backward compatibility.
The MPI_VALIDATE_RET() macro cannot be used for parameter
validation of mbedtls_mpi_lsb() because this function returns
a size_t.
Use the underlying MBEDTLS_INTERNAL_VALIDATE_RET() insteaed,
returning 0 on failure.
Also, add a test for this behaviour.
A 0-length buffer for the key is a legitimate edge case. Ensure that
it works, even with buf=NULL. Document the key and keylen parameters.
There are already test cases for parsing an empty buffer. A subsequent
commit will add tests for writing to an empty buffer.
Add checks for null pointers under MBEDTLS_CHECK_PARAMS.
In functions that perform operations with a context, only check if the
context pointer is non-null under MBEDTLS_CHECK_PARAMS. In the default
configuration, unconditionally dereference the context pointer.
In functions that query a context, support NULL as a
pointer-to-context argument, and return the same value as for a
context which has been initialized but not set up.
- The validity of the input and output parameters is checked by
parameter validation.
- A PRNG is required in public mode only (even though it's also
recommended in private mode), so move the check to the
corresponding branch.
The check was already done later when calling ECB, (as evidenced by the tests
passing, which have a call with data_unit set to NULL), but it's more readable
to have it here too, and more helpful when debugging.
The function called through the macro MBEDTLS_PARAM_FAILED() must be supplied by
users and makes no sense as a library function, apart from debug and test.
Function calls to alternative implementations have to follow certain
rules in order to preserve correct functionality. To avoid accidentally
breaking these rules we state them explicitly in the ECP module for
ourselves and every contributor to see.
We initialized the ECC hardware before calling
mbedtls_ecp_mul_shortcuts(). This in turn calls
mbedtls_ecp_mul_restartable(), which initializes and frees the hardware
too. This issue has been introduced by recent changes and caused some
accelerators to hang.
We move the initialization after the mbedtle_ecp_mul_shortcuts() calls
to avoid double initialization.
The SSL module accesses ECDH context members directly. This can't work
with the new context, where we can't make any assumption about the
implementation of the context.
This commit makes use of the new functions to avoid accessing ECDH
members directly. The only members that are still accessed directly are
the group ID and the point format and they are independent from the
implementation.
The SSL module accesses ECDH context members directly to print debug
information. This can't work with the new context, where we can't make
assumptions about the implementation of the context. This commit adds
new debug functions to complete the encapsulation of the ECDH context
and work around the problem.
The functionality from public API functions are moved to
`xxx_internal()` functions. The public API functions are modified to do
basic parameter validation and dispatch the call to the right
implementation.
There is no intended change in behaviour when
`MBEDTLS_ECDH_LEGACY_CONTEXT` is enabled.
In the future we want to support alternative ECDH implementations. We
can't make assumptions about the structure of the context they might
use, and therefore shouldn't access the members of
`mbedtls_ecdh_context`.
Currently the lifecycle of the context can't be done without direct
manipulation. This commit adds `mbedtls_ecdh_setup()` to complete
covering the context lifecycle with functions.
`mbedtls_ecp_tls_read_group()` both parses the group ID and loads the
group into the structure provided. We want to support alternative
implementations of ECDH in the future and for that we need to parse the
group ID without populating an `mbedtls_ecp_group` structure (because
alternative implementations might not use that).
This commit moves the part that parses the group ID to a new function.
There is no need to test the new function directly, because the tests
for `mbedtls_ecp_tls_read_group()` are already implicitly testing it.
There is no intended change in behaviour in this commit.
Refactor `mpi_write_hlp()` to not be recursive, to fix stack overflows.
Iterate over the `mbedtls_mpi` division of the radix requested,
until it is zero. Each iteration, put the residue in the next LSB
of the output buffer. Fixes#2190
Refactor mbedtls_ctr_drbg_update_seed_file and
mbedtls_hmac_drbg_update_seed_file to make the error logic clearer.
The new code does not use fseek, so it works with non-seekable files.
Return early from mbedtls_pk_write_pubkey_der - public opaque key
exporting is expected to contain all of the needed data, therefore it shouldn't
be written again.
There is a probability that r will be encoded as 31 or less bytes in DER,
so additional padding is added in such case.
Added a signature-part extraction function to tidy up the code further.
Reasons:
- For the first release, we attempt to support TLS-1.2 only,
- At least TLS-1.0 is known to not work at the moment, as
for CBC ciphersuites the code in mbedtls_ssl_decrypt_buf()
and mbedtls_ssl_encrypt_buf() assumes that mbedtls_cipher_crypt()
updates the structure field for the IV in the cipher context,
which the PSA-based implementation currently doesn't.
This commit modifies the default SSL ticket implementation
from `library/ssl_ticket.c` to use PSA-based cipher context
for ticket creation and parsing.
As in mbedtls_ssl_derive_keys() adapted in an earlier commit,
we allow fallback to the ordinary mbedtls_cipher_setup()
if the provided cipher is not known. We do this even though
we always call mbedtls_ssl_ticket_setup() with AES-GCM
in our own code since this function is public and might
be used with other ciphers by users.
This commit changes the code path in mbedtls_ssl_derive_keys()
responsible for setting up record protection cipher contexts
to attempt to use the new API mbedtls_cipher_setup_psa() in
case MBEDTLS_USE_PSA_CRYPTO is set.
For that, the AEAD tag length must be provided, which is already
computed earlier in mbedtls_ssl_derive_keys() and only needs to be
stored a function scope to be available for mbedtls_cipher_setup_psa().
If mbedtls_cipher_setup_psa() fails cleanly indicating that the
requested cipher is not supported in PSA, we fall through to
the default setup using mbedtls_cipher_setup(). However, we print
a debug message in this case, to allow catching the fallthrough in
tests where we know we're using a cipher which should be supported
by PSA.
mbedtls_cipher_setup_psa() should return
MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE when the requested
cipher is not supported by PSA, so that the caller can
try the original mbedtls_cipher_setup() instead.
The previous version of mbedtls_cipher_setup_psa(), however,
only attempted to translate the cipher mode (GCM, CCM, CBC,
ChaChaPoly, Stream), but didn't consider the underlying
cipher primitive. Hence, it wouldn't fail when attempting
to setup a cipher context for, say, 3DES-CBC, where CBC
is currently supported by PSA but 3DES isn't.
This commit adds a check to mbedtls_cipher_setup_psa()
for whether the requested cipher primitive is available
in the underlying PSA Crypto implementation, and fails
cleanly with MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE if
it is isn't.
For AEAD ciphers, the information contained in mbedtls_cipher_info
is not enough to deduce a PSA algorithm value of type psa_algorithm_t.
This is because mbedtls_cipher_info doesn't contain the AEAD tag
length, while values of type psa_algorithm_t do.
This commit adds the AEAD tag length as a separate parameter
to mbedtls_cipher_setup_psa(). For Non-AEAD ciphers, the value
must be 0.
This approach is preferred over passing psa_algorithm_t directly
in order to keep the changes in existing code using the cipher layer
small.
Mbed TLS cipher layer allows usage of keys for other purposes
than indicated in the `operation` parameter of `mbedtls_cipher_setkey()`.
The semantics of the PSA Crypto API, in contrast, checks key
usage against the key policy.
As a remedy, this commit modifies the PSA key slot setup to
always allow both encryption and decryption.
This commit implements the internal key slot management performed
by PSA-based cipher contexts. Specifically, `mbedtls_cipher_setkey()`
wraps the provided raw key material into a key slot, and
`mbedtls_cipher_free()` destroys that key slot.
This field determines whether a cipher context should
use an external implementation of the PSA Crypto API for
cryptographic operations, or Mbed TLS' own crypto library.
The commit also adds dummy implementations for the cipher API.
It's better for names in the API to describe the "what" (opaque keys) rather
than the "how" (using PSA), at least since we don't intend to have multiple
function doing the same "what" in different ways in the foreseeable future.
Unfortunately the can_do wrapper does not receive the key context as an
argument, so it cannot check psa_get_key_information(). Later we might want to
change our internal structures to fix this, but for now we'll just restrict
opaque PSA keys to be ECDSA keypairs, as this is the only thing we need for
now. It also simplifies testing a bit (no need to test each key type).