Commit graph

5295 commits

Author SHA1 Message Date
Gilles Peskine c8000c005a Add slot_number attribute
Add a slot_number field to psa_key_attributes_t and getter/setter
functions. Since slot numbers can have the value 0, indicate the
presence of the field via a separate flag.

In psa_get_key_attributes(), report the slot number if the key is in a
secure element.

When creating a key, for now, applications cannot choose a slot
number. A subsequent commit will add this capability in the secure
element HAL.
2019-08-08 10:58:09 +02:00
Gilles Peskine 74f3352b05 Add missing guard around a union field 2019-08-08 10:58:09 +02:00
Gilles Peskine 91e8c33f48 Add infrastructure for key attribute flags
Add infrastructure for internal, external and dual-use flags, with a
compile-time check (if static_assert is available) to ensure that the
same numerical value doesn't get declared for two different purposes
in crypto_struct.h (external or dual-use) and
psa_crypto_core.h (internal).
2019-08-08 10:58:09 +02:00
Gilles Peskine 0c77b0e2f9
Merge pull request #198 from gilles-peskine-arm/psa-api-1.0-beta-merge_development_20190801
Merge mbed-crypto/development into psa-api-1.0-beta
2019-08-08 10:24:53 +02:00
Alexander K 1f5e6abfb9 Remove extra mbedtls_ecp_group_free() call since the grp is free
at the top of the function.
2019-08-07 20:40:46 +03:00
Gilles Peskine f181eca350 Fix psa_generate_random for >1024 bytes
mbedtls_ctr_drbg_random can only return up to
MBEDTLS_CTR_DRBG_MAX_REQUEST (normally 1024) bytes at a time. So if
more than that is requested, call mbedtls_ctr_drbg_random in a loop.
2019-08-07 13:49:00 +02:00
Gilles Peskine a6b2f60b4c Fix double free in psa_generate_key when psa_generate_random fails
When psa_generate_random fails, psa_generate_key_internal frees the
key buffer but a the pointer to the now-freed buffer in the slot. Then
psa_generate_key calls psa_fail_key_creation which sees the pointer
and calls free() again.

This bug was introduced by ff5f0e7221
"Implement atomic-creation psa_{generate,generator_import}_key" which
changed how psa_generate_key() cleans up on errors. I went through the
code and could not find a similar bug in cleanup on an error during
key creation.

Fix #207
2019-08-07 13:43:09 +02:00
Gilles Peskine 1b9505c451 Correct some comments 2019-08-07 10:59:45 +02:00
Gilles Peskine 01655daeee
Merge pull request #2417 from RonEld/2734
Update soon to be expired crl
2019-08-03 13:38:14 +02:00
Vikas Katariya 21599b6622 Return right error code.
Issue : 126
https://github.com/ARMmbed/mbed-crypto/issues/126

PSA_ERROR_BUFFER_TOO_SMALL error returned when we check for output_size.
2019-08-02 13:01:58 +01:00
Gilles Peskine 8908c5e81c Make psa_calculate_key_bits return psa_key_bits_t
This is cleaner and solves a complaint from MSVC about truncation from
size_t to psa_key_bits_t.
2019-07-31 18:55:00 +02:00
Gilles Peskine 8b66389d0d Adjust secure element code to the new ITS interface 2019-07-31 17:57:57 +02:00
Gilles Peskine 72c8c5b352 Merge remote-tracking branch 'upstream-crypto/development' into psa-api-1.0-beta-merge_development_20190801
Conflict resolution:
* `scripts/config.pl`:
  Take the exclusion of `MBEDTLS_PSA_CRYPTO_SE_C` from the API branch.
  Take the removal of `MBEDTLS_PSA_CRYPTO_STORAGE_ITS_C` (obsolete) from
  the development branch.
* `tests/scripts/all.sh`:
  Multiple instances of factoring a sequence of `config.pl` calls into
  a mere `config.pl baremetal` in the development branch, and a change in
  the composition of `baremetal` in the API branch. In each case, take the
  version from development.
* `tests/suites/test_suite_psa_crypto_slot_management.function`:
  A function became non-static in development and disappeared in the API
  branch. Keep the version from the API branch. Functions need to be
  non-static if they're defined but unused in some configurations,
  which is not the case for any function in this file at the moment.
* `tests/suites/test_suite_psa_crypto.function`:
  Consecutive changes in the two branches, reconciled.
2019-07-31 17:47:49 +02:00
Gilles Peskine 1b8594a218 More refactoring: consolidate attribute validation
Consolidate attribute validation at the beginning of key creation into
a single function. Improve comments.
2019-07-31 17:21:46 +02:00
Gilles Peskine 3825e14e65 Fix policy validity check on key creation.
Add a non-regression test.
2019-07-31 16:54:38 +02:00
Gilles Peskine 41e50d26ea Remove "allocated" flag from key slots
The flag to mark key slots as allocated was introduced to mark slots
that are claimed and in use, but do not have key material yet, at a
time when creating a key used several API functions: allocate a slot,
then progressively set its metadata, and finally create the key
material. Now that all of these steps are combined into a single
API function call, the notion of allocated-but-not-filled slot is no
longer relevant. So remove the corresponding flag.

A slot is occupied iff there is a key in it. (For a key in a secure
element, the key material is not present, but the slot contains the
key metadata.) This key must have a type which is nonzero, so use this
as an indicator that a slot is in use.
2019-07-31 16:54:38 +02:00
Gilles Peskine 76aa09c9a9 Take advantage of psa_core_key_attributes_t internally #2
Key creation and psa_get_key_attributes
2019-07-31 16:54:37 +02:00
Gilles Peskine b46bef2f76 Store the key size in the slot in memory
There is now a field for the key size in the key slot in memory. Use
it.

This makes psa_get_key_attributes() marginally faster at the expense
of memory that is available anyway in the current memory layout (16
bits for the size, 16 bits for flags). That's not the goal, though:
the goal is to simplify the code, in particular to make it more
uniform between transparent keys (whose size can be recomputed) and
keys in secure elements (whose size cannot be recomputed).

For keys in a secure element, the bit size is now saved by serializing
the type psa_key_bits_t (which is an alias for uint16_t) rather than
size_t.
2019-07-31 14:16:50 +02:00
Gilles Peskine 2431859dc7 Take advantage of psa_core_key_attributes_t internally: key loading 2019-07-31 14:16:19 +02:00
Gilles Peskine 4ed0e6f11a Switch storage functions over to psa_core_key_attributes_t 2019-07-31 14:15:27 +02:00
Gilles Peskine 8e3387029d Use psa_core_key_attributes_t in key slots in memory
Change the type of key slots in memory to use
psa_core_key_attributes_t rather than separate fields. The goal is to
simplify some parts of the code. This commit only does the mechanical
replacement, not the substitution.

The bit-field `allocate` is now a flag `PSA_KEY_SLOT_FLAG_ALLOCATED`
in the `flags` field.

Write accessor functions for flags.

Key slots now contain a bit size field which is currently unused.
Subsequent commits will make use of it.
2019-07-31 14:15:27 +02:00
Jaeden Amero fe93bc4ed4
Merge pull request #187 from Patater/tls-development-20190722
Bring in changes from Mbed TLS as of 2019-07-22
2019-07-31 11:50:15 +01:00
Jaeden Amero 8dd1690993 Merge remote-tracking branch 'tls/development' into development
Resolve conflicts by performing the following operations:
- Reject changes related to building a crypto submodule, since Mbed
  Crypto is the crypto submodule.
- Reject X.509, NET, and SSL changes.
- Reject changes to README, as Mbed Crypto is a different project from
  Mbed TLS, with a different README.
- Avoid adding mention of ssl-opt.sh in a comment near some modified
  code in include/CMakeLists.txt (around where ENABLE_TESTING as added).
- Align config.pl in Mbed TLS with config.pl in Mbed Crypto where PSA
  options are concerned, to make future merging easier. There is no
  reason for the two to be different in this regard, now that Mbed TLS
  always depends on Mbed Crypto. Remaining differences are only the
  PSA_CRYPTO_KEY_FILE_ID_ENCODES_OWNER option and the absence of X.509,
  NET, and SSL related options in Mbed Crypto's config.pl.
- Align config.h in Mbed Crypto with Mbed TLS's copy, with a few notable
  exceptions:
  - Leave CMAC on by default.
  - Leave storage on by default (including ITS emulation).
  - Avoid documenting the PSA Crypto API as is in beta stage in
    documentation for MBEDTLS_PSA_CRYPTO_C.
  The only remaining differences are a lack of X.509, NET, and SSL
  options in Mbed Crypto's config.h, as well as an additional
  Mbed-Crypto-specific PSA_CRYPTO_KEY_FILE_ID_ENCODES_OWNER option.
  Documentation for the check params feature and related macros is also
  updated to match Mbed TLS's description.
- Reject tests/data_files/Makefile changes to generate DER versions of
  CRTs and keys, as none of those are used by Mbed Crypto tests.
- Add the "no PEM and no filesystem" test to all.sh, without ssl-opt.sh
  run, as Mbed Crypto doesn't have ssl-opt.sh. Also remove use of PSA
  Crypto storage and ITS emulation, since those depend on filesystem
  support.
- Reject addition of test when no ciphersuites have MAC to all.sh, as
  the option being tested, MBEDTLS_SSL_SOME_MODES_USE_MAC, is not
  present in Mbed Crypto.
- Use baremetal config in all.sh, as Mbed Crypto's baremetal
  configuration does exclude the net module (as it doesn't exist in Mbed
  Crypto)
- Reject cmake_subproject_build changes, continuing to link only
  libmbedcrypto.
- Reject changes to visualc and associated templates. Mbed Crypto
  doesn't need additional logic to handle submodule-sourced headers.
- Avoid adding fuzzers from Mbed TLS. The only relevant fuzzers are the
  privkey and pubkey fuzzers, but non-trivial work would be required to
  integrate those into Mbed Crypto (more than is comfortable in a merge
  commit).
- Reject addition of Docker wrappers for compat.sh and ssl-opt.sh, as
  those are not present in Mbed Crypto.
- Remove calls to SSL-related scripts from basic-in-docker.sh

Fix test errors by performing the following:
- Avoid using a link that Doxygen can't seem to resolve in Mbed Crypto,
  but can resolve in Mbed TLS. In documentation for
  MBEDTLS_CHECK_PARAMS, don't attempt to link to MBEDTLS_PARAM_FAILED.

* origin/development: (339 commits)
  Do not build fuzz on windows
  No booleans and import config
  Removing space before opening parenthesis
  Style corrections
  Syntax fix
  Fixes warnings from MSVC
  Add a linker flag to enable gcov in basic-build-test.sh
  Update crypto submodule to a revision with the HAVEGE header changes
  Test with MBEDTLS_ECP_RESTARTABLE
  Allow TODO in code
  Use the docstring in the command line help
  Split _abi_compliance_command into smaller functions
  Record the commits that were compared
  Document how to build the typical argument for -s
  Allow running /somewhere/else/path/to/abi_check.py
  tests: Limit each log to 10 GiB
  Warn if VLAs are used
  Remove redundant compiler flag
  Consistently spell -Wextra
  Fix parsing issue when int parameter is in base 16
  ...
2019-07-31 10:37:53 +01:00
Gilles Peskine 68cc433b5b Store key sizes in 16 bits in attributes
This is larger than the maximum key size introduced in the previous
commit, by design.

Make some room for flags (not used yet).
2019-07-30 21:08:38 +02:00
Gilles Peskine c744d99386 Limit keys to 65528 bits
65528 bits is more than any reasonable key until we start supporting
post-quantum cryptography.

This limit is chosen to allow bit-sizes to be stored in 16 bits, with
65535 left to indicate an invalid value. It's a whole number of bytes,
which facilitates some calculations, in particular allowing a key of
exactly PSA_CRYPTO_MAX_STORAGE_SIZE to be created but not one bit
more.

As a resource usage limit, this is arguably too large, but that's out
of scope of the current commit.

Test that key import, generation and derivation reject overly large
sizes.
2019-07-30 20:58:33 +02:00
Gilles Peskine 7e0cff90b9 Move attribute fields to a substructure
Move the "core attributes" to a substructure of psa_key_attribute_t.
The motivation is to be able to use the new structure
psa_core_key_attributes_t internally.
2019-07-30 20:58:27 +02:00
Gilles Peskine e60d1d08a4 SE keys: save the bit size in storage
For a key in a secure element, save the bit size alongside the slot
number.

This is a quick-and-dirty implementation where the storage format
depends on sizeof(size_t), which is fragile. This should be replaced
by a more robust implementation before going into production.
2019-07-29 18:11:09 +02:00
Gilles Peskine 1801740a7c SE driver: report the bit size on key import
Add a parameter to the key import method of a secure element driver to
make it report the key size in bits. This is necessary (otherwise the
core has no idea what the bit-size is), and making import report it is
easier than adding a separate method (for other key creation methods,
this information is an input, not an output).
2019-07-29 18:07:09 +02:00
Gilles Peskine dc5bfe9784 SE keys: implement and test psa_get_key_attributes 2019-07-29 18:07:03 +02:00
Gilles Peskine 424f89453b SE keys: store the bit size internally (partial implementation)
This commit blindingly copies the size from the attributes. This is
not correct for copy and import.
2019-07-29 17:06:06 +02:00
Jaeden Amero e0b4c433fe
Merge pull request #273 from k-stachowiak/IOTCRYPT-726-unchecked-return-ecjpake
Fix unchecked return value in the ECJPake module
2019-07-29 11:48:23 +01:00
Gilles Peskine adb1c52149
Merge pull request #157 from gilles-peskine-arm/psa-se_driver-create_key
Secure element key creation foundation
2019-07-26 14:39:55 +02:00
Gilles Peskine 66be51c35d If starting a transaction fails, wipe the transaction data
Nothing has been saved to disk yet, but there is stale data in
psa_crypto_transaction. This stale data should not be reused, but do
wipe it to reduce the risk of it mattering somehow in the future.
2019-07-26 13:23:51 +02:00
Gilles Peskine 2ea06fd48d Improve documentation of transaction storage 2019-07-26 13:23:51 +02:00
Gilles Peskine f9bb29ec26 Add boilerplate to recover a transaction during init 2019-07-25 17:52:59 +02:00
Gilles Peskine 4aea1036c6 Bug fix: don't start a transaction for non-SE keys 2019-07-25 17:38:34 +02:00
Gilles Peskine 340b127ed1 psa_destroy_se_key: explain why the error is NOT_PERMITTED 2019-07-25 14:13:24 +02:00
Gilles Peskine 2e0f388d2a Don't explicitly dereference function pointers
Be stylistically consistent.
2019-07-25 11:42:19 +02:00
Gilles Peskine 60450a4812 Improve comments 2019-07-25 11:32:45 +02:00
Gilles Peskine 725f22a545 Bug fix: save the driver's persistent data in destroy_key 2019-07-25 11:32:27 +02:00
Gilles Peskine adad813d7b psa_key_slot_is_external exists. Use it. 2019-07-25 11:32:27 +02:00
Gilles Peskine f77a6acf83 Fix indentation 2019-07-25 10:51:03 +02:00
Gilles Peskine 4b73422318 Transaction support: be more future-proof
If there's ever a non-SE-related transaction, make sure it gets
handled during init.
2019-07-24 15:56:31 +02:00
Gilles Peskine 75c126b958 Explain some non-obvious parts of the code
Comment changes only.
2019-07-24 15:56:01 +02:00
Gilles Peskine f4ee662868 SE keys: error out in key creation function that lack support 2019-07-24 13:44:30 +02:00
Gilles Peskine 28f8f3068f SE keys: ensure that functions that lack support properly error out
Introduce a new function psa_get_transparent_key which returns
NOT_SUPPORTED if the key is in a secure element. Use this function in
functions that don't support keys in a secure element.

After this commit, all functions that access a key slot directly via
psa_get_key_slot or psa_get_key_from_slot rather than via
psa_get_transparent_key have at least enough support for secure
elements not to crash or otherwise cause undefined behavior. Lesser
bad behavior such as wrong results or resource leakage is still
possible in error cases.
2019-07-24 13:30:31 +02:00
Moshe Shahar 6763fe4a12 Change LINK_WITH_TRUSTED_STORAGE option to OFF 2019-07-24 14:19:35 +03:00
Moshe Shahar 7e36765945 Add CMake option for explicitly link library to trusted_storage (#2)
option name: LINK_WITH_TRUSTED_STORAGE
default value: ON
2019-07-24 13:32:13 +03:00
Gilles Peskine 573bbc1b4e Error out if a driver tries to store more than ITS can handle
Cast explicitly for the sake of MSVC which otherwise (usefully!) warns
about the truncation.
2019-07-23 20:23:16 +02:00
Simon D Hughes bda5a21112 Add psa_trusted_storage_linux persistent storage support for v1.0.0 APIs
The following provides more information on this PR:
- PSA stands for Platform Security Architecture.
- Add support for use of psa_trusted_storage_api internal_trusted_storage.h v1.0.0
  as the interface to the psa_trusted_storage_linux backend (i.e. for persistent
  storage when MBEDTLS_PSA_ITS_FILE_C is not defined). This requires changes
  to psa_crypto_its.h and psa_crypto_storage.c to migrate to the new API.
2019-07-23 17:30:37 +01:00
Gilles Peskine 8b96cad204 SE drivers: implement persistent storage
Store the persistent data of secure element drivers.

This is fully implemented, but not at all tested.
2019-07-23 17:38:08 +02:00
Gilles Peskine 1df83d4f5b SE keys: implement persistent storage
For a key in a secure element, persist the key slot.

This is implemented in the nominal case. Failures may not be handled
properly.
2019-07-23 16:13:14 +02:00
Gilles Peskine 0e8d495bd9 Add the lifetime to the key storage format
Stored keys must contain lifetime information. The lifetime used to be
implied by the location of the key, back when applications supplied
the lifetime value when opening the key. Now that all keys' metadata
are stored in a central location, this location needs to store the
lifetime explicitly.
2019-07-23 14:46:52 +02:00
Gilles Peskine bfd322ff34 Use a key attribute structure in the internal storage interface
Pass information via a key attribute structure rather than as separate
parameters to psa_crypto_storage functions. This makes it easier to
maintain the code when the metadata of a key evolves.

This has negligible impact on code size (+4B with "gcc -Os" on x86_64).
2019-07-23 13:31:54 +02:00
Gilles Peskine 274a2637f2 Make whitespace consistent 2019-07-23 11:29:06 +02:00
Gilles Peskine fc76265385 Do secure element key creation and destruction in a transaction
Key creation and key destruction for a key in a secure element both
require updating three pieces of data: the key data in the secure
element, the key metadata in internal storage, and the SE driver's
persistent data. Perform these actions in a transaction so that
recovery is possible if the action is interrupted midway.
2019-07-22 19:46:22 +02:00
Gilles Peskine c8336cb8f9 Implement a transaction record storage for resilience
Implement a transaction record that can be used for actions that
modify more than one piece of persistent data (whether in the
persistent storage or elsewhere such as in a secure element).

While performing a transaction, the transaction file is present in
storage. If the system starts with an ongoing transaction, it must
complete the transaction (not implemented yet).
2019-07-22 19:46:22 +02:00
Gilles Peskine 2838b7bfba Use smaller types in mbedtls_md_info_t
Saves a few bytes of code size.
2019-07-22 11:35:19 +02:00
Gilles Peskine 84867cffdd Don't use dynamic pointer dispatch in md
In the generic message digest abstraction, instead of storing method
pointers in the per-algorithm data structure and using wrapper
functions as those methods, call the per-algorithm function directly.

This saves some code size (2336B -> 2043B for md with all algorithms
enabled on M0+ with gcc -Os). This should also make it easier to
optimize the case when a single algorithm is supported. In addition,
this is a very slight security improvement since it removes one
opportunity for a buffer overflow to directly turn into letting the
attacker overwrite a pointer to a function pointer.

This commit does not modify the documented API. However, it removes
the possibility for users to define their own hash implementations and
use them by building their own md_info.

Changing mbedtls_md_context to contain a md type identifier rather
than a pointer to an info structure would save a few more bytes and a
few more runtime memory accesses, but would be a major API break since
a lot of code uses `const mbedtls_md_info *` to keep track of which
hash is in use.
2019-07-22 11:35:15 +02:00
Hanno Becker 80bb77e16d ECP restart: Don't calculate address of sub ctx if ctx is NULL
All modules using restartable ECC operations support passing `NULL`
as the restart context as a means to not use the feature.

The restart contexts for ECDSA and ECP are nested, and when calling
restartable ECP operations from restartable ECDSA operations, the
address of the ECP restart context to use is calculated by adding
the to the address of the ECDSA restart context the offset the of
the ECP restart context.

If the ECP restart context happens to not reside at offset `0`, this
leads to a non-`NULL` pointer being passed to restartable ECP
operations from restartable ECDSA-operations; those ECP operations
will hence assume that the pointer points to a valid ECP restart
address and likely run into a segmentation fault when trying to
dereference the non-NULL but close-to-NULL address.

The problem doesn't arise currently because luckily the ECP restart
context has offset 0 within the ECDSA restart context, but we should
not rely on it.

This commit fixes the passage from restartable ECDSA to restartable ECP
operations by propagating NULL as the restart context pointer.

Apart from being fragile, the previous version could also lead to
NULL pointer dereference failures in ASanDbg builds which dereferenced
the ECDSA restart context even though it's not needed to calculate the
address of the offset'ed ECP restart context.
2019-07-19 14:44:36 +01:00
Hanno Becker 59c92ed89b ECP restart: Don't calculate address of sub ctx if ctx is NULL
All modules using restartable ECC operations support passing `NULL`
as the restart context as a means to not use the feature.

The restart contexts for ECDSA and ECP are nested, and when calling
restartable ECP operations from restartable ECDSA operations, the
address of the ECP restart context to use is calculated by adding
the to the address of the ECDSA restart context the offset the of
the ECP restart context.

If the ECP restart context happens to not reside at offset `0`, this
leads to a non-`NULL` pointer being passed to restartable ECP
operations from restartable ECDSA-operations; those ECP operations
will hence assume that the pointer points to a valid ECP restart
address and likely run into a segmentation fault when trying to
dereference the non-NULL but close-to-NULL address.

The problem doesn't arise currently because luckily the ECP restart
context has offset 0 within the ECDSA restart context, but we should
not rely on it.

This commit fixes the passage from restartable ECDSA to restartable ECP
operations by propagating NULL as the restart context pointer.

Apart from being fragile, the previous version could also lead to
NULL pointer dereference failures in ASanDbg builds which dereferenced
the ECDSA restart context even though it's not needed to calculate the
address of the offset'ed ECP restart context.

dummy
2019-07-19 13:03:10 +01:00
Gilles Peskine 3b3b34f608 Replace some macros by functions
Replace some frequently-used macros by inline functions: instead of
calling MOD_{ADD,SUB,MUL} after the mbedtls_mpi_{add,sub,mul}_mpi,
call a function mbedtls_mpi_xxx_mod that does the same.

In the baremetal config, with "gcc -Os -mthumb -mcpu=cortex-m0plus",
ecp.o goes down from 13878 bytes to 12234.

No noticeable performance change for benchmarks on x86_64 with either
"gcc -O2" or "gcc -Os".
2019-07-18 21:08:27 +02:00
Manuel Pégourié-Gonnard 49d65ba929 Re-roll main loop with SHA512_SMALLER
Saves 1924 bytes (same measurement as before).
2019-07-17 13:16:54 +02:00
Manuel Pégourié-Gonnard 0270ed99bb Use tables and roll up some loops
Saves 108 bytes (measured as in previous commit).
2019-07-17 13:08:02 +02:00
Manuel Pégourié-Gonnard 7f0719598f Make SHA512_SMALLER turn a macro into a function
Saves 356 bytes on sha512.o compiling for Cortex-M0+ with ARM-GCC

Size measured with:
arm-none-eabi-gcc -Wall -Wextra -Iinclude -Os -mcpu=cortex-m0plus -mthumb -c library/sha512.c
arm-none-eabi-size sha512.o

GCC version:
arm-none-eabi-gcc (GNU Tools for Arm Embedded Processors 7-2018-q2-update) 7.3.1 20180622 (release) [ARM/embedded-7-branch revision 261907]
2019-07-17 13:06:55 +02:00
Manuel Pégourié-Gonnard 2306d15344 Declare new config.h option MBEDTLS_SHA512_SMALLER 2019-07-17 13:05:41 +02:00
Gilles Peskine c11c4dcf95 Favor stdint.h types in internal types
Use uint8_t for PSA buffers. Keep unsigned char for generic libc
buffers and for mbedtls buffers.
2019-07-15 11:17:53 +02:00
Gilles Peskine 7228da25f9 Favor stdint.h types in implementation-specific API 2019-07-15 11:16:18 +02:00
Andrew Thoelke 163639b830 Apply same changes to implementation source code 2019-07-15 11:14:56 +02:00
Ron Eldor 991a05b411 Add support for all SHA modes in cert_write
Add support for `MBEDTLS_SHA_224` and `MBEDTLS_SHA_384` in
`cert_write`, to support generating such certificates in
`tests/data_files/Makefile`.
2019-07-14 09:17:57 +03:00
Gilles Peskine 5d309672af SE keys: support import and export 2019-07-12 23:47:28 +02:00
Gilles Peskine 354f7671f4 SE keys: support destroy
When destroying a key in a secure element, call the driver's destroy
method and update the driver's persistent data in storage.
2019-07-12 23:46:38 +02:00
Gilles Peskine cbaff467ef SE keys: allocate a slot before creating the key 2019-07-12 23:46:04 +02:00
Gilles Peskine 73167e128f SE keys: store the slot number in the memory slot 2019-07-12 23:44:37 +02:00
Gilles Peskine 8abe6a2d5c Driver table entries are now mutable
Since driver table entries contain the driver context, which is
mutable, they can't be const anymore.
2019-07-12 23:42:20 +02:00
Gilles Peskine 5243a202c3 Driver context manipulation functions
Create the driver context when registering the driver.

Implement some helper functions to access driver information.
2019-07-12 23:42:20 +02:00
Gilles Peskine 011e4284a1 Look up the SE driver when creating a key
When creating a key with a lifetime that places it in a secure
element, retrieve the appropriate driver table entry.

This commit doesn't yet achieve behavior: so far the code only
retrieves the driver, it doesn't call the driver.
2019-07-12 11:47:50 +02:00
Gilles Peskine f989dbe6d8 SE driver lookup functions
Expose the type of an entry in the SE driver table as an opaque type
to other library modules. Soon, driver table entries will have state,
and callers will need to be able to access this state through
functions using this opaque type.

Provide functions to look up a driver by its lifetime and to retrieve
the method table from an entry.
2019-07-12 11:47:50 +02:00
Adrian L. Shaw 2282cfa660 Remove GMAC algorithm (for now)
It can't be implemented with the current version of the API
2019-07-11 15:51:45 +01:00
Ron Eldor 9eeb8611b1 Update certificates to expire in 2029
Update certificates that expire on 2021, to prolong their validity,
to make tests pass three years ahead.
2019-07-10 16:46:34 +03:00
Jaeden Amero 01604a334a Merge remote-tracking branch 'origin/pr/2726' into development
* origin/pr/2726:
  Warn if VLAs are used
  Remove redundant compiler flag
  Consistently spell -Wextra
  Allow declarations after statements
2019-07-10 07:55:25 +01:00
Jaeden Amero 150d7749ea Merge remote-tracking branch 'origin/pr/2719' into development
* origin/pr/2719:
  Deref pointer when using sizeof in x509_get_other_name
2019-07-10 07:55:09 +01:00
Jaeden Amero 0b8b5e3393 Merge remote-tracking branch 'origin/pr/2706' into development
* origin/pr/2706:
  Update Mbed Crypto to contain mbed-crypto#152
  CMake: Add a subdirectory build regression test
  README: Enable builds as a CMake subproject
  ChangeLog: Enable builds as a CMake subproject
  Remove use of CMAKE_SOURCE_DIR
2019-07-10 07:54:49 +01:00
Jaeden Amero 6d77d20f3a Merge remote-tracking branch 'origin/pr/2632' into development
* origin/pr/2632:
  Adapt ChangeLog
  Avoid use of large stack buffers in mbedtls_x509_write_crt_pem()
  Improve documentation of mbedtls_pem_write_buffer()
  Perform CRT writing in-place on the output buffer
  Adapt x509write_crt.c to coding style
2019-07-10 07:54:37 +01:00
k-stachowiak 4150335a27 Fix handling of md failure
The failure of mbedtls_md was not checked in one place. This could have led
to an incorrect computation if a hardware accelerator failed. In most cases
this would have led to the key exchange failing, so the impact would have been
a hard-to-diagnose error reported in the wrong place. If the two sides of the
key exchange failed in the same way with an output from mbedtls_md that was
independent of the input, this could have led to an apparently successful key
exchange with a predictable key, thus a glitching md accelerator could have
caused a security vulnerability.
2019-07-08 14:32:38 +02:00
Jaeden Amero b6229e304e
Merge pull request #149 from gilles-peskine-arm/havege-asan-crypto
Fix misuse of signed ints in the HAVEGE module
2019-07-05 15:30:30 +01:00
Jaeden Amero c19dcebbdd
Merge pull request #154 from yanesca/iotcrypt-789-update-tls-prf-to-multipart
Update TLS 1.2 PRF to multipart API
2019-07-04 11:53:04 +01:00
k-stachowiak 653a4a2fba Prevent dead code warning
The window size variable in ecp_pick_window_size() can take values
4, 5 or 6, but we clamp it not to exceed the value of
MBEDTLS_ECP_WINDOW_SIZE. If that is 6 (default) or higher, the
static analyzer will point out that the test:
w > MBEDTLS_ECP_WINDOW_SIZE always evaluates to false.

This commit removes the test for the cases of the window size
large enough to fit all the potential values of the variable.
2019-07-04 12:19:47 +02:00
Janos Follath d6dce9f4f3 Fix zero-length seed or label in TLS 1.2 PRF
The psa_tls12_prf_set_seed() and psa_tls12_prf_set_label() functions did
not work on platforms where malloc(0) returns NULL.

It does not affect the TLS use case but these PRFs are used in other
protocols as well and might not be used the same way. For example EAP
uses the TLS PRF with an empty secret. (This would not trigger the bug,
but is a strong indication that it is not safe to assume that certain
inputs to this function are not zero length.)

The conditional block includes the memcpy() call as well to avoid
passing a NULL pointer as a parameter resulting in undefined behaviour.

The current tests are already using zero length label and seed, there is
no need to add new test for this bug.
2019-07-04 09:11:38 +01:00
Gilles Peskine 85aba47715 Consistently spell -Wextra
-W is a deprecated alias of -Wextra. Consistently use the new name.
2019-07-02 20:05:16 +02:00
Janos Follath 0c1ed84258 Improve style 2019-06-28 15:10:06 +01:00
Gilles Peskine 9717d107ca Explain that lifetime=0 from static initialization means VOLATILE 2019-06-26 20:01:35 +02:00
Gilles Peskine a8ade16ffd Gate secure element support by a separate config option
Secure element support has its own source file, and in addition
requires many hooks in other files. This is a nontrivial amount of
code, so make it optional (but default on).
2019-06-26 20:01:35 +02:00
Janos Follath 40e1393816 Optimize TLS PRF PSK key calculation 2019-06-26 13:23:10 +01:00
Janos Follath 76c3984477 Clarify TLS PRF algorithm description 2019-06-26 12:50:36 +01:00
Ashley Duncan d85a7e9b09 Remove use of CMAKE_SOURCE_DIR
Remove use of CMAKE_SOURCE_DIR in case mbedtls is built from within
another CMake project. Define MBEDTLS_DIR to ${CMAKE_CURRENT_SOURCE_DIR}
in the main CMakeLists.txt file and refer to that when defining target
include paths to enable mbedtls to be built as a sub project.

Fixes https://github.com/ARMmbed/mbedtls/issues/2609

Signed-off-by: Ashley Duncan <ashes.man@gmail.com>
Signed-off-by: Jaeden Amero <jaeden.amero@arm.com>
2019-06-26 12:46:53 +01:00
Janos Follath 30090bc2cf Fix error code
PSA_ERROR_BAD_STATE means that the function was called on a context in a
bad state.

This error is something that can't happen while only using the PSA API and
therefore a PSA_ERROR_CORRUPTION_DETECTED is a more appropriate error
code.
2019-06-26 09:15:08 +01:00
Janos Follath 5fe19734d5 Make key derivation initialisation consistent
The macro initialiser might leave bytes in the union unspecified.
Zeroising it in setup makes sure that the behaviour is the same
independently of the initialisation method used.
2019-06-26 09:15:08 +01:00
Janos Follath ea29bfb148 Add tls12_prf key derivation to the new API
The TLS 1.2 pseudorandom function does a lot of distinct HMAC operations
with the same key. To save the battery and CPU cycles spent on
calculating the paddings and hashing the inner padding, we keep the
hash context in the status right after the inner padding having been
hashed and clone it as needed.
2019-06-26 09:15:08 +01:00
Janos Follath 844eb0e5fa Add tls12_prf_read for the new API
Technically we could have reused the old one for the new API, but then
we had to set an extra field during setup. The new version works when
all the fields that haven't been set explicitely are zero-initialised.
2019-06-26 09:15:08 +01:00
Janos Follath 7742feea53 Add stub for new tls12_prf_generate_next_block 2019-06-26 09:15:08 +01:00
Janos Follath 6c6c8fceaa Improve style 2019-06-26 09:15:08 +01:00
Janos Follath 6660f0eb98 Add TLS 1.2 PSK master secret generation 2019-06-26 09:15:08 +01:00
Janos Follath 51f4a0f9ac Style: enforce 80 column limit 2019-06-26 09:15:08 +01:00
Janos Follath c56215163f Simplify psa_key_derivation_input_bytes
The specific key derivation input functions support a subset of the
input options and need to check it anyway. Checking it at the top level
is redundant, it brings a very little value and comes with a cost in
code size and maintainability.
2019-06-26 09:15:08 +01:00
Janos Follath adbec81cc4 Remove the deprecated PSA_ALG_SELECT_RAW option
This change affects the psa_key_derivation_s structure. With the buffer
removed from the union, it is empty if MBEDTLS_MD_C is not defined.

We can avoid undefined behaviour by adding a new dummy field that is
always present or make the whole union conditional on MBEDTLS_MD_C.

In this latter case the initialiser macro has to depend on MBEDTLS_MD_C
as well. Furthermore the first structure would be either
psa_hkdf_key_derivation_t or psa_tls12_prf_key_derivation_t both of
which are very deep and would make the initialisation macro difficult
to maintain, therefore we go with the first option.
2019-06-26 09:15:08 +01:00
Janos Follath 63028dd906 Add label input for psa_tls12_prf_input 2019-06-26 09:15:08 +01:00
Janos Follath 8155054e28 Add key import for psa_tls12_prf_input 2019-06-26 09:15:08 +01:00
Janos Follath f08e2654ed Add seed input for psa_tls12_prf_input 2019-06-26 09:15:08 +01:00
Janos Follath ef83f5e98e Move raw key derivation input to a new function 2019-06-26 09:15:08 +01:00
Janos Follath b80a94e2ea Rename psa_key_derivation_input_raw
The function dispatches between all the available methods and
does not just handle the raw key derivation case like the name suggests.
2019-06-26 09:15:08 +01:00
Janos Follath b03233e196 Add stubs for psa_tls12_prf_input 2019-06-26 09:15:08 +01:00
Janos Follath 6a1d262803 Adapt psa_key_derivation_abort to the new context 2019-06-26 09:15:08 +01:00
Janos Follath 999f648437 Add new psa_tls12_prf_key_derivation_t
As part of adapting TLS 1.2 key derivation to the PSA 1.0 API we need to
change the context structure.
2019-06-26 09:15:08 +01:00
Janos Follath 083036af64 Safely erase key material upon abort
Some key derivation operation contexts (like
psa_tls12_prf_key_derivation_t) directly contain buffers with parts of
the derived key. Erase them safely as part of the abort.
2019-06-26 09:15:58 +01:00
Janos Follath 71a4c9125b Add flag for removing deprecated API
Add the compile time option PSA_PRE_1_0_KEY_DERIVATION. If this is not
turned on, then the function `psa_key_derivation()` is removed.

Most of the tests regarding key derivation haven't been adapted to the
new API yet and some of them have only been adapted partially. When this
new option is turned off, the tests using the old API and test cases
using the old API of partially adapted tests are skipped.

The sole purpose of this option is to make the transition to the new API
smoother. Once the transition is complete it can and should be removed
along with the old API and its implementation.
2019-06-26 09:15:08 +01:00
Gilles Peskine c2d56a4446 Allow declarations after statements
We officially allow C99, so don't forbid this C99 feature.
2019-06-25 18:52:06 +02:00
Ashley Duncan 3278081428 Remove use of CMAKE_SOURCE_DIR
Remove use of CMAKE_SOURCE_DIR in case mbedtls is built from within
another CMake project. Define MBEDTLS_DIR to ${CMAKE_CURRENT_SOURCE_DIR}
in the main CMakeLists.txt file and refer to that when defining target
include paths to enable mbedtls to be built as a sub project.

Fixes #2609

Signed-off-by: Ashley Duncan <ashes.man@gmail.com>
Signed-off-by: Jaeden Amero <jaeden.amero@arm.com>
2019-06-25 13:33:51 +01:00
Gilles Peskine 8f2a6dcc25 Support PSA_KEY_DERIVATION_INPUT_SEED 2019-06-25 12:02:31 +01:00
Gilles Peskine d089021128 Unregister drivers on library deinitialization 2019-06-24 19:55:48 +02:00
Gilles Peskine a899a72fd0 Implement the secure element driver registration function 2019-06-24 19:55:44 +02:00
Gilles Peskine bc2adf94a8 Fix minor type choice inconsistency 2019-06-24 15:45:09 +02:00
Sébastien Duquette 661d725044 Deref pointer when using sizeof in x509_get_other_name
Fix for #2716.
2019-06-24 09:17:18 -04:00
Jaeden Amero 66b7edb108 Merge remote-tracking branch 'origin/pr/2711' into development
* origin/pr/2711:
  programs: Make `make clean` clean all programs always
  ssl_tls: Enable Suite B with subset of ECP curves
  windows: Fix Release x64 configuration
  platform: Include stdarg.h where needed
  timing: Remove redundant include file
  net_sockets: Fix typo in net_would_block()
2019-06-21 14:09:10 +01:00
Jaeden Amero fd0f65459c Merge remote-tracking branch 'origin/pr/2697' into development
* origin/pr/2697:
  Update crypto submodule
  Add all.sh component that exercises invalid_param checks
  Remove mbedtls_param_failed from programs
  Make it easier to define MBEDTLS_PARAM_FAILED as assert
  Make test suites compatible with #include <assert.h>
  Pass -m32 to the linker as well
  Don't systematically rebuild programs
2019-06-21 13:21:05 +01:00
Jaeden Amero e2d5b9e5cc Merge remote-tracking branch 'origin/pr/2690' into development
* origin/pr/2690:
  Making version features easily ROM-able when using Arm C compiler.
2019-06-21 13:20:22 +01:00
Jaeden Amero d431104926 ssl_tls: Enable Suite B with subset of ECP curves
Make sure the code compiles even if some curves are not defined.

Fixes #1591
2019-06-20 10:59:05 +01:00
Jaeden Amero a180926556 timing: Remove redundant include file
There is no need to include winbase.h, as it will be pulled in by
windows.h as needed.

Fixes #2640
2019-06-20 10:51:21 +01:00
Jaeden Amero a152e42e9b net_sockets: Fix typo in net_would_block()
Fixes #528
2019-06-20 10:48:11 +01:00
Gilles Peskine 7846299adb Fix misuse of signed ints in the HAVEGE module
The elements of the HAVEGE state are manipulated with bitwise
operations, with the expectations that the elements are 32-bit
unsigned integers (or larger). But they are declared as int, and so
the code has undefined behavior. Clang with Asan correctly points out
some shifts that reach the sign bit.

Since these are supposed to be 32-bit unsigned integers, declare them
as uint32_t.

This is technically an API break, since the type mbedtls_havege_state
is exposed in a public header. However normal applications should not
be affected.
2019-06-14 19:23:10 +02:00
Jaeden Amero 7af080a9f9 Merge remote-tracking branch 'origin/pr/2442' into development
* origin/pr/2442:
  Correct placement of ChangeLog entry
  Improve documentation of mbedtls_x509_get_ext()
  Adapt ChangeLog
  Always return a high-level error code from X.509 module
  Obey bounds of ASN.1 substructures
2019-06-14 15:27:42 +01:00
Jaeden Amero e1b02df515 Merge remote-tracking branch 'origin/pr/2260' into development
* origin/pr/2260:
  Update crypto submodule
  Remove heading spaces in tests/data_files/Makefile
  Re-generate library/certs.c from script
  Add new line at the end of test-ca2.key.enc
  Use strict syntax to annotate origin of test data in certs.c
  Add run to all.sh exercising !MBEDTLS_PEM_PARSE_C + !MBEDTLS_FS_IO
  Allow DHM self test to run without MBEDTLS_PEM_PARSE_C
  ssl-opt.sh: Auto-skip tests that use files if MBEDTLS_FS_IO unset
  Document origin of hardcoded certificates in library/certs.c
  Adapt ChangeLog
  Rename server1.der to server1.crt.der
  Add DER encoded files to git tree
  Add build instructions to generate DER versions of CRTs and keys
  Document "none" value for ca_path/ca_file in ssl_client2/ssl_server2
  ssl_server2: Skip CA setup if `ca_path` or `ca_file` argument "none"
  ssl_client2: Skip CA setup if `ca_path` or `ca_file` argument "none"
  Correct white spaces in ssl_server2 and ssl_client2
  Adapt ssl_client2 to parse DER encoded test CRTs if PEM is disabled
  Adapt ssl_server2 to parse DER encoded test CRTs if PEM is disabled
2019-06-14 08:46:48 +01:00
Gilles Peskine c7ad122f51 Make it easier to define MBEDTLS_PARAM_FAILED as assert
Introduce a new configuration option MBEDTLS_CHECK_PARAMS_ASSERT,
which is disabled by default. When this option is enabled,
MBEDTLS_PARAM_FAILED defaults to assert rather than to a call to
mbedtls_param_failed, and <assert.h> is included.

This fixes #2671 (no easy way to make MBEDTLS_PARAM_FAILED assert)
without breaking backward compatibility. With this change,
`config.pl full` runs tests with MBEDTLS_PARAM_FAILED set to assert,
so the tests will fail if a validation check fails, and programs don't
need to provide their own definition of mbedtls_param_failed().
2019-06-13 16:51:59 +02:00
Máté Varga c5de4623e8 Making version features easily ROM-able when using Arm C compiler. 2019-06-12 12:26:37 +02:00
Gilles Peskine 4bac9a4c4b New function to get key slot statistics
New function mbedtls_psa_get_stats to obtain some data about how many
key slots are in use. This is intended for debugging and testing
purposes.
2019-06-05 16:38:42 +02:00
Jaeden Amero 2de07f1dd1 ssl: Don't access non-existent encrypt_then_mac field
When MBEDTLS_SSL_ENCRYPT_THEN_MAC is enabled, but not
MBEDTLS_SSL_SOME_MODES_USE_MAC, mbedtls_ssl_derive_keys() and
build_transforms() will attempt to use a non-existent `encrypt_then_mac`
field in the ssl_transform.

    Compile [ 93.7%]: ssl_tls.c
    [Error] ssl_tls.c@865,14: 'mbedtls_ssl_transform {aka struct mbedtls_ssl_transform}' ha
s no member named 'encrypt_then_mac'
    [ERROR] ./mbed-os/features/mbedtls/src/ssl_tls.c: In function 'mbedtls_ssl_derive_keys'
:
    ./mbed-os/features/mbedtls/src/ssl_tls.c:865:14: error: 'mbedtls_ssl_transform {aka str
uct mbedtls_ssl_transform}' has no member named 'encrypt_then_mac'
         transform->encrypt_then_mac = session->encrypt_then_mac;
                  ^~

Change mbedtls_ssl_derive_keys() and build_transforms() to only access
`encrypt_then_mac` if `encrypt_then_mac` is actually present.

Add a regression test to detect when we have regressions with
configurations that do not include any MAC ciphersuites.

Fixes d56ed2491b ("Reduce size of `ssl_transform` if no MAC ciphersuite is enabled")
2019-06-05 14:09:29 +01:00
Jaeden Amero 7654161dbf psa: Add NV seed as an entropy source when needed
When MBEDTLS_PSA_INJECT_ENTROPY is used, we now require also defining
MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES. When
MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES is defined, we do not add entropy
sources by default. This includes the NV seed entropy source, which the
PSA entropy injection API is built upon.

The PSA entropy injection feature depends on using NV seed as an entropy
source. Add NV seed as an entropy source for PSA entropy injection.

Fixes e3dbdd8d90 ("Gate entropy injection through a dedicated configuration option")
2019-06-05 11:09:38 +01:00
Gilles Peskine bfcae2e436 Improve documentation of psa_internal_allocate_key_slot 2019-06-05 11:39:57 +02:00
Gilles Peskine 70e085a7d9 Simplify psa_open_key
Simplify psa_open_key now that the old method for key creation
(returning a handle to a slot with no key material) no longer exists.
2019-06-05 11:34:54 +02:00
Gilles Peskine 267c65666a Simplify key slot allocation
Now that psa_allocate_key() is no longer a public function, expose
psa_internal_allocate_key_slot() instead, which provides a pointer to
the slot to its caller.
2019-06-05 11:34:54 +02:00
Gilles Peskine d2d45c1738 Convert cipher and pk to PSA attribute-based key creation
This fixes the build under MBEDTLS_USE_PSA_CRYPTO.
2019-06-05 11:34:54 +02:00
Gilles Peskine f46f81ceb5 Remove obsolete key creation functions
Remove the key creation functions from before the attribute-based API,
i.e. the key creation functions that worked by allocating a slot, then
setting metadata through the handle and finally creating key material.
2019-06-05 11:34:54 +02:00
Hanno Becker 3cddba887a Improve documentation of mbedtls_x509_get_ext()
- Explain the use of explicit ASN.1 tagging for the extensions structuree
- Remove misleading comment which suggests that mbedtls_x509_get_ext()
  also parsed the header of the first extension, which is not the case.
2019-06-04 13:59:55 +01:00
Hanno Becker 6ccfb18ab1 Always return a high-level error code from X.509 module
Some functions within the X.509 module return an ASN.1 low level
error code where instead this error code should be wrapped by a
high-level X.509 error code as in the bulk of the module.

Specifically, the following functions are affected:
- mbedtls_x509_get_ext()
- x509_get_version()
- x509_get_uid()

This commit modifies these functions to always return an
X.509 high level error code.

Care has to be taken when adapting `mbetls_x509_get_ext()`:
Currently, the callers `mbedtls_x509_crt_ext()` treat the
return code `MBEDTLS_ERR_ASN1_UNEXPECTED_TAG` specially to
gracefully detect and continue if the extension structure is not
present. Wrapping the ASN.1 error with
`MBEDTLS_ERR_X509_INVALID_EXTENSIONS` and adapting the check
accordingly would mean that an unexpected tag somewhere
down the extension parsing would be ignored by the caller.

The way out of this is the following: Luckily, the extension
structure is always the last field in the surrounding structure,
so if there is some data remaining, it must be an Extension
structure, so we don't need to deal with a tag mismatch gracefully
in the first place.

We may therefore wrap the return code from the initial call to
`mbedtls_asn1_get_tag()` in `mbedtls_x509_get_ext()` by
`MBEDTLS_ERR_X509_INVALID_EXTENSIONS` and simply remove
the special treatment of `MBEDTLS_ERR_ASN1_UNEXPECTED_TAG`
in the callers `x509_crl_get_ext()` and `x509_crt_get_ext()`.

This renders `mbedtls_x509_get_ext()` unsuitable if it ever
happened that an Extension structure is optional and does not
occur at the end of its surrounding structure, but for CRTs
and CRLs, it's fine.

The following tests need to be adapted:
- "TBSCertificate v3, issuerID wrong tag"
  The issuerID is optional, so if we look for its presence
  but find a different tag, we silently continue and try
  parsing the subjectID, and then the extensions. The tag '00'
  used in this test doesn't match either of these, and the
  previous code would hence return LENGTH_MISMATCH after
  unsucessfully trying issuerID, subjectID and Extensions.
  With the new code, any data remaining after issuerID and
  subjectID _must_ be Extension data, so we fail with
  UNEXPECTED_TAG when trying to parse the Extension data.
- "TBSCertificate v3, UIDs, invalid length"
  The test hardcodes the expectation of
  MBEDTLS_ERR_ASN1_INVALID_LENGTH, which needs to be
  wrapped in MBEDTLS_ERR_X509_INVALID_FORMAT now.

Fixes #2431.
2019-06-04 13:59:48 +01:00
Hanno Becker 12f62fb82c Obey bounds of ASN.1 substructures
When parsing a substructure of an ASN.1 structure, no field within
the substructure must exceed the bounds of the substructure.
Concretely, the `end` pointer passed to the ASN.1 parsing routines
must be updated to point to the end of the substructure while parsing
the latter.

This was previously not the case for the routines
- x509_get_attr_type_and_value(),
- mbedtls_x509_get_crt_ext(),
- mbedtls_x509_get_crl_ext().
These functions kept using the end of the parent structure as the
`end` pointer and would hence allow substructure fields to cross
the substructure boundary. This could lead to successful parsing
of ill-formed X.509 CRTs.

This commit fixes this.

Care has to be taken when adapting `mbedtls_x509_get_crt_ext()`
and `mbedtls_x509_get_crl_ext()`, as the underlying function
`mbedtls_x509_get_ext()` returns `0` if no extensions are present
but doesn't set the variable which holds the bounds of the Extensions
structure in case the latter is present. This commit addresses
this by returning early from `mbedtls_x509_get_crt_ext()` and
`mbedtls_x509_get_crl_ext()` if parsing has reached the end of
the input buffer.

The following X.509 parsing tests need to be adapted:
- "TBSCertificate, issuer two inner set datas"
  This test exercises the X.509 CRT parser with a Subject name
  which has two empty `AttributeTypeAndValue` structures.
  This is supposed to fail with `MBEDTLS_ERR_ASN1_OUT_OF_DATA`
  because the parser should attempt to parse the first structure
  and fail because of a lack of data. Previously, it failed to
  obey the (0-length) bounds of the first AttributeTypeAndValue
  structure and would try to interpret the beginning of the second
  AttributeTypeAndValue structure as the first field of the first
  AttributeTypeAndValue structure, returning an UNEXPECTED_TAG error.
- "TBSCertificate, issuer, no full following string"
  This test exercises the parser's behaviour on an AttributeTypeAndValue
  structure which contains more data than expected; it should therefore
  fail with MBEDTLS_ERR_ASN1_LENGTH_MISMATCH. Because of the missing bounds
  check, it previously failed with UNEXPECTED_TAG because it interpreted
  the remaining byte in the first AttributeTypeAndValue structure as the
  first byte in the second AttributeTypeAndValue structure.
- "SubjectAltName repeated"
  This test should exercise two SubjectAltNames extensions in succession,
  but a wrong length values makes the second SubjectAltNames extension appear
  outside of the Extensions structure. With the new bounds in place, this
  therefore fails with a LENGTH_MISMATCH error. This commit adapts the test
  data to put the 2nd SubjectAltNames extension inside the Extensions
  structure, too.
2019-06-04 10:15:09 +01:00
Hanno Becker ff552f7d56 Re-generate library/certs.c from script 2019-06-03 17:46:56 +01:00
Hanno Becker 92b4f8131c Use strict syntax to annotate origin of test data in certs.c
This allows to auto-generate them from scripts.
2019-06-03 17:46:56 +01:00
Hanno Becker 3217c8d7e8 Allow DHM self test to run without MBEDTLS_PEM_PARSE_C 2019-06-03 17:46:56 +01:00
Hanno Becker 960e588278 Document origin of hardcoded certificates in library/certs.c
All of them are copied from (former) CRT and key files in `tests/data_files`.
For files which have been regenerated since they've been copied to `certs.c`,
update the copy.

Add declarations for DER encoded test CRTs to certs.h

Add DER encoded versions of CRTs to certs.c

fix comment in certs.c

Don't use (signed) char for DER encoded certificates

Consistently use `const char *` for test CRTs regardless of encoding

Remove non-sensical and unused PW variable for DER encoded key

Provide test CRTs in PEM and DER fmt, + pick suitable per config

This commit modifies `certs.h` and `certs.c` to start following the
following pattern for the provided test certificates and files:

- Raw test data is named `NAME_ATTR1_ATTR2_..._ATTRn`

  For example, there are
     `TEST_CA_CRT_{RSA|EC}_{PEM|DER}_{SHA1|SHA256}`.

- Derived test data with fewer attributes, iteratively defined as one
  of the raw test data instances which suits the current configuration.

  For example,
     `TEST_CA_CRT_RSA_PEM`
  is one of `TEST_CA_CRT_RSA_PEM_SHA1` or `TEST_CA_CRT_RSA_PEM_SHA256`,
  depending on whether SHA-1 and/or SHA-256 are defined in the current
  config.

Add missing public declaration of test key password

Fix signedness and naming mismatches

Further improve structure of certs.h and certs.c

Fix definition of mbedtls_test_cas test CRTs depending on config

Remove semicolon after macro string constant in certs.c
2019-06-03 17:46:56 +01:00
Hanno Becker e8d6afd627 Add debug line witnessing receipt of unexpected CID 2019-06-03 16:07:50 +01:00