Commit Graph

4988 Commits

Author SHA1 Message Date
Hanno Becker
53ade9fa62 MD: Implement config dep'n inlining of mbedtls_md_process() 2019-09-09 09:45:57 +01:00
Hanno Becker
993691d9ba MD: Implement config dep'n inlining of mbedtls_md_finish() 2019-09-09 09:45:57 +01:00
Hanno Becker
fdef5ac13b MD: Implement config dep'n inlining of mbedtls_md_update() 2019-09-09 09:45:57 +01:00
Hanno Becker
527f7c9307 MD: Demonstrate config-dep'n API inlining for mbedtls_md_starts() 2019-09-09 09:45:57 +01:00
Hanno Becker
c4e4210aab Introduce md_internal.h
Recall that in the default configuration, Mbed TLS provides access
digest implementations through two layers of indirection:

1) Call of MD API (e.g. mbedtls_md_update())
2) Call of function pointer from MD info structure
3) Actual digest implementation (e.g. mbedtls_sha256_update()).

Ideally, if only a single digest is enabled - say SHA-256 - then calling
mbedtls_md_update() should _directly_ jump to mbedtls_sha256_update(),
with both layers of indirection removed. So far, however, setting
MBEDTLS_MD_SINGLE_HASH will only remove the second - function pointer -
layer of indirection, while keeping the non-inlined stub implementations
of e.g. mbedtls_md_update() around.

This commit is a step towards allowing to define implementations of
the MD API as `static inline` in case we know that they are so small
that they should be defined in md.h and not in md.c.

In a nutshell, the approach is as follows: For an MD API function
mbedtls_md_xxx() that should be inlin-able, introduce its implementation
as a `static inline` wrapper `mbedtls_md_xxx_internal()` in md.h,
and then define mbedtls_md_xxx() either in md.h or in md.c, by just
calling mbedtls_md_xxx_internal().

Moving the implementations of those MD API functions that should be
inlinable to md.h requires the presence of both the MD info struct
and all specific digest wrapper functions in md.h, and this is what
this commit ensures, by moving them from md.c into a new internal
header file md_internal.h. Implementing the aforementioned wrappers for
those MD API that should be inlinable is left for subsequent commits.
2019-09-09 09:45:57 +01:00
Hanno Becker
3f7d270c18 md.c: Avoid overly long lines 2019-09-09 09:45:57 +01:00
Hanno Becker
3a98eab2c4 Don't return function pointers from MD info getters
ARMC5 appears to use the heuristic that as soon as a function's address
is taken, the function can no longer be removed from the resulting object
file (which is not necessarily true if all uses of the functions address
can be inlined).

Circumvent this lack of optimization by not returning function pointers.
2019-09-09 09:45:57 +01:00
Hanno Becker
08cf43a9ec Fix typo MBEDTLS_SSL_CONF_SINGLE_HASH -> MBEDTLS_MD_SINGLE_HASH 2019-09-09 09:45:57 +01:00
Hanno Becker
bdaf0ea5d9 Make MD info getters always inline 2019-09-09 09:45:57 +01:00
Hanno Becker
ccb2b62f0a Remove handle from MD context in single hash config 2019-09-09 09:45:57 +01:00
Hanno Becker
1292c35c03 Add config.h option to hardcode choice of single MD algorithm
This commit introduces the configuration option

  MBEDTLS_MD_SINGLE_HASH

which can be used to hardcode support for a single digest algorithm
at compile-time, at the benefit of reduced code-size.

To use, it needs to be defined to evaluate to a macro of the form
MBEDTLS_MD_INFO_{DIGEST}, and macros MBEDTLS_MD_INFO_{DIGEST}_FIELD
must be defined, giving rise to the various aspects (name, type,
size, ...) of the chosen digest algorithm. MBEDTLS_MD_INFO_SHA256
provides an example, but other algorithms can be added if needed.

At the moment, the effect of using MBEDTLS_MD_SINGLE_HASH is that
the implementation of the MD API (e.g. mbedtls_md_update()) need no
longer to through the abstraction of the mbedtls_md_info structures
by calling their corresponding function pointers fields (akin to
virtual functions in C++), but the directly call the corresponding
core digest function (such as mbedtls_sha256_update()).

Therefore, MBEDTLS_MD_SINGLE_HASH so far removes the second layer
of indirection in the chain

  User calls MD API -> MD API calls underlying digest impl'n
                    -> Core digest impl'n does the actual work,

but the first indirection remains, as the MD API remains untouched
and cannot yet be inlined. Studying to what extend inlining the
shortened MD API implementations would lead to further code-savings
is left for a later commit.
2019-09-09 09:45:57 +01:00
Hanno Becker
d03949e2a4 Remove md_wrap.c and md_internal.h 2019-09-09 09:45:57 +01:00
Hanno Becker
d3827c74d5 Introduce getter for MD handle from MD context 2019-09-09 09:45:57 +01:00
Hanno Becker
62a44d43b0 Allow defining MD information structs through macros
In builds enabling only a single MD digest, we want to be able to
implement the MD info getter functions by returning compile-time
constants matching the fields of the MD info structures used so far.

To avoid information duplication hardening maintainability, this
commit introduces the possibility of providing the various aspects
of a particular digest implementation by defining macros
MBEDTLS_MD_INFO_DIGEST_FIELD (e.g. MBEDTLS_MD_INFO_SHA256_SIZE)
and to generate the corresponding mbedtls_md_info instance from
this set of macros, via the new macro MBEDTLS_MD_INFO().

This way, we'll be able to switch between MD info based builds
and single-digest builds without information duplication.
2019-09-09 09:45:57 +01:00
Hanno Becker
0e7fc3166d Inline md_wrap.c in md.c
md_wrap.c doesn't expose any public functionality and doesn't
need to be present as a separate compilation unit.
2019-09-09 09:45:57 +01:00
Hanno Becker
530387eaa3 Introduce getter functions for MD info fields
This commit continues the introduction of the MD digest implementation
abstraction layer given by `mbedtls_md_handle_t` by adding getter
functions returning the various properties of an implementation
(e.g. name, digest type, digest size). For the existing implementation,
these are just structure field accesses; however, in configurations
hardcoding the choice of a fixed digest algorithm, we'll be able to
implement them as inline functions returning compile-time constants.
2019-09-09 09:45:57 +01:00
Hanno Becker
a5cedbcd3f Introduce MD handle type
As has been previously done for ciphersuites, this commit introduces
a zero-cost abstraction layer around the type

  mbedtls_md_info const *

whose valid values represent implementations of message digest algorithms.

Access to a particular digest implementation can be requested by name or
digest ID through the API mbedtls_md_info_from_xxx(), which either returns
a valid implementation or NULL, representing failure.

This commit replaces such uses of `mbedtls_md_info const *` by an abstract
type `mbedtls_md_handle_t` whose valid values represent digest implementations,
and which has a designated invalid value MBEDTLS_MD_INVALID_HANDLE.

The purpose of this abstraction layer is to pave the way for builds which
support precisely one digest algorithm. In this case, mbedtls_md_handle_t
can be implemented as a two-valued type, with one value representing the
invalid handle, and the unique valid value representing the unique enabled
digest.
2019-09-09 09:45:57 +01:00
Manuel Pégourié-Gonnard
7f2c3e4034 Remove dependency of ssl_cookie on SHA-224
Cookies are fully opaque so we can change the hash used at any time, it's not
part of the API.

The cookie module handles truncation, so it's simpler to always use SHA-256
rather than check if SHA-224 is available.
2019-09-09 10:21:30 +02:00
Manuel Pégourié-Gonnard
efd344894d Completely ignore is224 if SHA-224 is disabled 2019-09-09 10:21:30 +02:00
Manuel Pégourié-Gonnard
394c5fb24b Implement NO_SHA224 in MD layer as well 2019-09-09 10:21:30 +02:00
Manuel Pégourié-Gonnard
abebdd16ef Adapt SHA-256 selftest to NO_SHA224 2019-09-09 10:21:30 +02:00
Manuel Pégourié-Gonnard
8463d29156 Implement MBEDTLS_SHA256_NO_SHA224 2019-09-09 10:21:30 +02:00
Manuel Pégourié-Gonnard
9b781b2880 Add MBEDTLS_SHA256_NO_SHA244 option (unimplemented) 2019-09-09 09:06:56 +02:00
Simon Butcher
d82db9d48c Merge remote-tracking branch 'origin/pr/649' into baremetal 2019-09-07 12:46:12 +01:00
Simon Butcher
d91adcf7f5 Merge remote-tracking branch 'origin/pr/624' into baremetal 2019-09-07 12:44:42 +01:00
Jaeden Amero
fcb8711f6f Bump version to Mbed TLS 2.16.3 2019-09-06 13:27:00 +01:00
Teppo Järvelin
f69e641e03 Changed x509_internal.h methods as static.
Moved some functions under defined to get rid of compiler warnings.
Functions moved under defines:
 - mbedtls_x509_get_alg
 - mbedtls_x509_get_alg_null
 - mbedtls_x509_get_time
 - mbedtls_x509_get_ext
 - mbedtls_x509_sig_alg_gets
 - mbedtls_x509_key_size_helper

Left one function (mbedtls_x509_write_names) as non static as it increased code size.
2019-09-06 10:03:36 +03:00
Teppo Järvelin
c3e5716aaf Some minor struct optimizations. 2019-09-06 07:58:36 +03:00
Jaeden Amero
89408672eb Merge remote-tracking branch 'origin/mbedtls-2.16' into mbedtls-2.16-restricted
* origin/mbedtls-2.16:
  Changelog entry
  Check for zero length and NULL buffer pointer
  ssl-opt.sh: wait for proxy to start before running the script further
  Adapt ChangeLog
  Fix mpi_bigendian_to_host() on bigendian systems
2019-09-05 18:14:55 +01:00
Hanno Becker
7bcf2b5875 Introduce version comparing functions
This zero-cost abstraction allows to change the internal encoding
of TLS/DTLS versions in the future.
2019-09-05 17:37:55 +01:00
Jaeden Amero
c3bfb20a41 Merge remote-tracking branch 'origin/pr/2645' into mbedtls-2.16
* origin/pr/2645:
  Adapt ChangeLog
  Fix mpi_bigendian_to_host() on bigendian systems
2019-09-05 17:37:13 +01:00
Jaeden Amero
71db1de226 Merge remote-tracking branch 'origin/pr/2793' into mbedtls-2.16
* origin/pr/2793:
  Changelog entry
  Check for zero length and NULL buffer pointer
2019-09-05 15:57:34 +01:00
Manuel Pégourié-Gonnard
0cfb6efad4 Add work-around for non-C99 compilers 2019-09-05 14:07:01 +02:00
Manuel Pégourié-Gonnard
c7abba3796 Use static inline function unconditionally
No need to play tricks with macros and functions depending on whether
SHA256_SMALLER is enabled or not, with a static inline function all common
compilers (tested with arm-gcc, armcc5, arm-clang) will Do The Right Thing
depending on whether we told them to optimize for size or speed.
2019-09-05 12:09:59 +02:00
Hanno Becker
683d84a5d7 Fixup TinyCrypt PK parse: Correct function name in comment 2019-09-04 16:19:49 +01:00
Hanno Becker
f45d9da878 Fixup certs.c: Remove redundant TinyCrypt guard 2019-09-04 16:19:49 +01:00
Hanno Becker
d2929b5626 Fixup TinyCrypt PK wrap: Check TinyCrypt signature return code 2019-09-04 16:19:49 +01:00
Hanno Becker
96d34d57ec TinyCrypt PK Wrap: Remove dependency on ASN.1 writing
The TinyCrypt PK signature wrapper uses ASN.1 writing functions
for length and tag, accounting for the only dependency of the
baremetal build on ASN.1 writing.

Since all lengths to be encoded are below 128 Bytes and are hence
ASN.1 encoded as single Bytes, the dependency on ASN.1 writing can
be removed at low complexity by writing the length and tags directly.
2019-09-04 16:19:49 +01:00
Hanno Becker
358b3006ee TinyCrypt ECDHE-PSK: Implement CliKeyExchange parsing 2019-09-04 16:19:49 +01:00
Hanno Becker
982da7ee0a TinyCrypt ECDHE-PSK: Implement mbedtls_ssl_psk_derive_premaster() 2019-09-04 16:19:49 +01:00
Hanno Becker
d91ede14c4 TinyCrypt ECDHE-PSK: Implement ClientKeyExchange writing 2019-09-04 16:19:49 +01:00
Hanno Becker
c7effc04c1 TinyCrypt SSL: Extend scope use of TC in CliKeyExchange writing
Extend scope of TC in ECDH-param extraction from CRT

Previously, TinyCrypt was only used for ECDHE-ECDSA/RSA ciphersuites.
This commit is a step towards using it for _all_ ciphersuites involving
ECDHE (specifically: ECDHE, ECDHE-PSK, static ECDH), extending the scope
of the use of TinyCrypt in the writing of the ClientKeyExchange message.
2019-09-04 16:19:49 +01:00
Hanno Becker
7352bd141e TinyCrypt SSL: Extend scope of SrvKeyExchange parsing
Extend scope of TC in ECDH-param extraction from CRT

Previously, TinyCrypt was only used for ECDHE-ECDSA/RSA ciphersuites.
This commit is a step towards using it for _all_ ciphersuites involving
ECDHE (specifically: ECDHE, ECDHE-PSK, static ECDH), extending the scope
of the use of TinyCrypt in the parsing of the ServerKeyExchange message.
2019-09-04 16:19:49 +01:00
Hanno Becker
40ee0d450d Fixup: Correct #else and #endif comments in SrvKeyExch writing 2019-09-04 16:19:49 +01:00
Hanno Becker
b42e2388ff TinyCrypt SSL: Extend scope of CliKeyExchange parsing
Previously, TinyCrypt was only used for ECDHE-ECDSA/RSA ciphersuites.
This commit is a step towards using it for _all_ ciphersuites involving
ECDHE (specifically: ECDHE, ECDHE-PSK, static ECDH), extending the scope
of the use of TinyCrypt in the parsing of the ClientKeyExchange message.
2019-09-04 16:19:49 +01:00
Hanno Becker
8ea7da2250 TinyCrypt SSL: Extend scope of TC-based SrvKeyExch writing
Previously, TinyCrypt was only used for ECDHE-ECDSA/RSA ciphersuites.
This commit is a step towards using it for _all_ ciphersuites involving
ECDHE (specifically: ECDHE, ECDHE-PSK, static ECDH), extending the scope
of the use of TinyCrypt in the writing of the ServerKeyExchange message.
2019-09-04 16:19:49 +01:00
Hanno Becker
b3a244847d TinyCrypt SSL: Impl. ECDH-param extraction from CRT for TinyCrypt 2019-09-04 16:19:49 +01:00
Hanno Becker
ecf5d3fdb1 TinyCrypt SSL: Extend scope of use of TC in PMS derivation
Extend scope of TC in ECDH-param extraction from CRT

Previously, TinyCrypt was only used for ECDHE-ECDSA/RSA ciphersuites.
This commit is a step towards using it for _all_ ciphersuites involving
ECDHE (specifically: ECDHE, ECDHE-PSK, static ECDH), extending the scope
of the use of TinyCrypt in the assembly of the PMS.
2019-09-04 16:19:49 +01:00
Hanno Becker
2e80173dfc Fixup: Correct wrong comment ssl_prepare_server_key_exchange() 2019-09-04 16:19:49 +01:00
Hanno Becker
27b7e50dcd TinyCrypt SSL: Declare EC-related TLS RFC constants in SSL namespace
mbedtls/ecp.h defines constants

   MBEDTLS_ECP_PF_UNCOMPRESSED
   MBEDTLS_ECP_PF_COMPRESSED
   MBEDTLS_ECP_TLS_NAMED_CURVE

which regard the encoding of elliptic curves and curve point formats in TLS.
As such, they should be defined in the SSL namespace. Asides, this will help
replacing the legacy ECC crypto by alternative ECC implementations.
2019-09-04 16:19:49 +01:00
Hanno Becker
ee902df678 TinyCrypt SSL: Implement mbedtls_ssl_check_curve() for TinyCrypt 2019-09-04 16:19:49 +01:00
Hanno Becker
7e9c2e0d81 TinyCrypt SSL: Adapt ssl_parse_certificate_verify() to TinyCrypt 2019-09-04 16:17:45 +01:00
Hanno Becker
461fa723a1 TinyCrypt SSL: Adapt ssl_check_key_curve() to TinyCrypt 2019-09-04 16:17:45 +01:00
Hanno Becker
59e7b08b8a TinyCrypt X.509: Adapt profiles to use TinyCrypt curve identifier 2019-09-04 16:17:45 +01:00
Hanno Becker
88889c618e Fixup: Add missing TinyCrypt guards 2019-09-04 16:17:45 +01:00
Hanno Becker
d931ad2aca Implement x509_profile_check_key() for TinyCrypt-based PK context 2019-09-04 16:17:45 +01:00
Hanno Becker
1521ec501c Remove TinyCrypt PRNG configuration from ssl_cli.c
The TinyCrypt PRNG is configured in mbedtls_ssl_setup().
2019-09-04 16:17:25 +01:00
Hanno Becker
dfb949bb4e Fixup: Use TC ECC type instead of uint32_t during pubkey parsing
Using explicit enumerated types avoids type confusion.
2019-09-04 16:17:25 +01:00
Hanno Becker
28332a5642 TinyCrypt PK write: Impl. PK writing helpers for TC-based PK context 2019-09-04 16:17:25 +01:00
Hanno Becker
64a81b03aa TinyCrypt PK write: Make PK writing helpers accept PK context
This prepares the ground for TinyCrypt-based implementations of
these helpers.
2019-09-04 16:17:25 +01:00
Hanno Becker
c64d5af9ab Fixup: Don't use legacy ECC error code from TinyCrypt
We want to be able to remove legacy ECC entirely when using TinyCrypt,
including their identifiers.
2019-09-04 16:17:25 +01:00
Hanno Becker
da77971ec8 Fixup: Rename mbedtls_uecc_pk -> mbedtls_pk_uecc
This is in line with the naming of the analogous function mbedtls_pk_ec
used for legacy ECC PK contexts.
2019-09-04 16:17:25 +01:00
Hanno Becker
8cf2f5e466 TinyCrypt PK parse: Move TC-based EC public key parsing code-block
Keep code-paths handling legacy-ECC vs. TinyCrypt together
for better readability.
2019-09-04 16:17:25 +01:00
Hanno Becker
3bef643987 Fixup: Guard numerous legacy-ECC PK parse functions by !TinyCrypt 2019-09-04 16:17:25 +01:00
Hanno Becker
d336f721c0 Fixup: Add missing TinyCrypt guard in ECC private key parsing
PEM-encoded keys with PEM header

  -----BEGIN EC PRIVATE KEY-----
  ...
  -----END EC PRIVATE KEY-----

were previously not parsed in configurations using TinyCrypt
instead of legacy ECC crypto.
2019-09-04 16:17:25 +01:00
Hanno Becker
75f8d3276f TinyCrypt PK parse: Remove MBEDTLS_PK_ECDSA during pubkey parsing
The PK type MBEDTLS_PK_ECDSA is never returned from
`mbedtls_pk_info_from_type()`. Instead, EC keys either
are identified as MBEDTLS_PK_ECKEY_DH (in case they
must only be used for ECDHE) or MBEDTLS_PK_ECKEY (in
case they can be used for any algorithm).
2019-09-04 16:17:25 +01:00
Hanno Becker
e65697c351 TinyCrypt PK parse: Handle each PK type precisely once 2019-09-04 16:17:25 +01:00
Hanno Becker
d45f383b01 TinyCrypt PK parse: Impl. EC public key derivation in TC-based ECDSA 2019-09-04 16:17:25 +01:00
Hanno Becker
7e38c37302 TinyCrypt PK parse: Pass TC keypair structure to ECDSA pubkey parse 2019-09-04 16:17:25 +01:00
Hanno Becker
68d5478d8d TinyCrypt PK parse: Simplify TinyCrypt public key parsing 2019-09-04 16:17:25 +01:00
Hanno Becker
aebffdd363 TinyCrypt PK parse: Add comments to #endif's indicating condition 2019-09-04 16:17:25 +01:00
Hanno Becker
d7e0cd001c TinyCrypt PK wrap: Add short documentation for extract_ecdsa_sig_int 2019-09-04 16:17:25 +01:00
Hanno Becker
9653d80518 TinyCrypt PK wrap: Implement check_pair PK wrapper 2019-09-04 16:17:25 +01:00
Hanno Becker
4102972d31 TinyCrypt PK wrap: Implement alloc/free PK wrappers 2019-09-04 16:17:25 +01:00
Hanno Becker
11cb2637e7 TinyCrypt PK wrap: Simplify guards in pk_wrap.c
With TinyCrypt and legacy ECC mutually exclusive, we don't have
to use #if TINYCRYPT #else #if LEGACY #endif #endif anymore, but
can add the TC and legacy based ECC implementations independently.
2019-09-04 16:17:25 +01:00
Hanno Becker
8ea35458e4 Fixup: TinyCrypt PK verify wrapper uecc_ecdsa_verify_wrap()
- TinyCrypt uses `0` for errors.
- The first argument to uECC_verify() should be the public key,
  but the previous code passed the beginning of the entire
  private-public key structure.
2019-09-04 16:17:25 +01:00
Hanno Becker
9c7a359cc4 Fixup: uecc_ecdsa_sign_wrap() in pk_wrap.c
The previous code passed `2 * NUM_ECC_BYTES` as the size limit for
the ECDSA signature, which fails to account for space required by
ASN.1 headers.
2019-09-04 16:17:25 +01:00
Hanno Becker
9a62f2dbfb Fixup: get_bitlen() PK API in TinyCrypt-based ECDSA
- Return number of bits and not number of bytes
- Return length of private key and not length of public key.
2019-09-04 16:17:25 +01:00
Hanno Becker
496b83ff1b Fixup: Correct include paths for TinyCrypt header files
TinyCrypt header files are expected in 'tinycrypt' folder
relative to the include path.
2019-09-04 16:17:25 +01:00
Hanno Becker
ad353f289b Fixup: Minor style corrections around use of TinyCrypt 2019-09-04 16:17:25 +01:00
Hanno Becker
e8f1448306 Fixup: Remove references to PSA from TinyCrypt wrapper code 2019-09-04 16:17:25 +01:00
Hanno Becker
adf11e13a4 Fixup: Impl. MBEDTLS_PK_ECKEY, not MBEDTLS_PK_ECDSA, via TinyCrypt
The PK-type MBEDTLS_PK_ECDSA isn't really used by the library.
Especially, when parsing a generic EC key, a PK context of type
MBEDTLS_PK_ECKEY will be requested. Hence, to drop in TinyCrypt
for the legacy-ECC implementation, the PK type that TinyCrypt
implements must be MBEDTLS_PK_ECKEY.
2019-09-04 16:17:25 +01:00
Hanno Becker
8d49ba3b78 Fixup: Definition of TinyCrypt OID descriptor structure 2019-09-04 16:17:25 +01:00
Jarno Lamsa
7cb5c11067 Missing uECC ECDSA flagging 2019-09-04 16:17:25 +01:00
Jarno Lamsa
ad78931fb3 Signature wrapper for uECC 2019-09-04 16:17:25 +01:00
Jarno Lamsa
9c9e77a8ad Actually use the parse functions 2019-09-04 16:17:25 +01:00
Jarno Lamsa
b176092656 Parse private key in uecc format
Parse the private key from cert in uecc format.
Accept only P-256 curve.
2019-09-04 16:17:25 +01:00
Jarno Lamsa
42b83db1eb Verify sign wrapper functionality for uECC 2019-09-04 16:17:25 +01:00
Simon Butcher
e1c5608370 Merge remote-tracking branch 'origin/pr/650' into baremetal 2019-09-04 12:53:09 +01:00
Simon Butcher
42e4e723e8 Merge remote-tracking branch 'origin/pr/648' into baremetal 2019-09-04 12:42:35 +01:00
Simon Butcher
8afa0883af Merge remote-tracking branch 'origin/pr/641' into baremetal 2019-09-04 12:17:33 +01:00
Vikas Katariya
0c34499805 Check for zero length and NULL buffer pointer
In reference to issue https://github.com/ARMmbed/mbed-crypto/issues/49
2019-09-04 11:19:38 +01:00
Jaeden Amero
e7e55158f8 Merge remote-tracking branch 'origin/mbedtls-2.16' into mbedtls-2.16-restricted
* origin/mbedtls-2.16:
  Fix uninitialized variable in x509_crt
  Fix the license header of hkdf
  Add ChangeLog entry
  fix memory leak in mpi_miller_rabin()
2019-09-03 19:43:13 +01:00
Jaeden Amero
fe1d66d3e2 Merge remote-tracking branch 'origin/pr/2813' into mbedtls-2.16
* origin/pr/2813:
  Fix uninitialized variable in x509_crt
2019-09-03 16:34:23 +01:00
Jaeden Amero
adb4fa5921 Merge remote-tracking branch 'origin/pr/2398' into mbedtls-2.16
* origin/pr/2398:
  Add ChangeLog entry
  fix memory leak in mpi_miller_rabin()
2019-09-03 16:32:54 +01:00
Teppo Järvelin
ffaba55e5d Changed x509.c to be one single compilation unit for all x509 files. 2019-09-03 16:29:41 +03:00
Manuel Pégourié-Gonnard
d6fba18328
Merge pull request #643 from hanno-arm/secp256r1-baremetal
[Baremetal] Add Secp256r1 test certificates
2019-09-02 08:49:20 +02:00
Jaeden Amero
f85a15e090 Merge remote-tracking branch 'origin/mbedtls-2.16' into mbedtls-2.16-restricted
* origin/mbedtls-2.16:
  HMAC DRBG: Split entropy-gathering requests to reduce request sizes
2019-08-30 14:32:05 +01:00
Hanno Becker
8398582658 Fix SSL context deserialization
The SSL context maintains a set of 'out pointers' indicating the
address at which to write the header fields of the next outgoing
record. Some of these addresses have a static offset from the
beginning of the record header, while other offsets can vary
depending on the active record encryption mechanism: For example,
if an explicit IV is in use, there's an offset between the end
of the record header and the beginning of the encrypted data to
allow the explicit IV to be placed in between; also, if the DTLS
Connection ID (CID) feature is in use, the CID is part of the
record header, shifting all subsequent information (length, IV, data)
to the back.
When setting up an SSL context, the out pointers are initialized
according to the identity transform + no CID, and it is important
to keep them up to date whenever the record encryption mechanism
changes, which is done by the helper function ssl_update_out_pointers().

During context deserialization, updating the out pointers according
to the deserialized record transform went missing, leaving the out
pointers the initial state. When attemping to encrypt a record in
this state, this lead to failure if either a CID or an explicit IV
was in use. This wasn't caught in the tests by the bad luck that
they didn't use CID, _and_ used the default ciphersuite based on
ChaChaPoly, which doesn't have an explicit IV. Changing either of
this would have made the existing tests fail.

This commit fixes the bug by adding a call to ssl_update_out_pointers()
to ssl_context_load() implementing context deserialization.

Extending test coverage is left for a separate commit.
2019-08-30 13:27:16 +01:00
Andy Gross
3fc6f9d16d Fix uninitialized variable in x509_crt
This patch fixes an issue we encountered with more stringent compiler
warnings.  The signature_is_good variable has a possibility of being
used uninitialized.  This patch moves the use of the variable to a
place where it cannot be used while uninitialized.

Signed-off-by: Andy Gross <andy.gross@linaro.org>
2019-08-30 14:46:03 +03:00
Hanno Becker
fb1b7e1db9 HMAC DRBG: Split entropy-gathering requests to reduce request sizes
According to SP800-90A, the DRBG seeding process should use a nonce
of length `security_strength / 2` bits as part of the DRBG seed. It
further notes that this nonce may be drawn from the same source of
entropy that is used for the first `security_strength` bits of the
DRBG seed. The present HMAC DRBG implementation does that, requesting
`security_strength * 3 / 2` bits of entropy from the configured entropy
source in total to form the initial part of the DRBG seed.

However, some entropy sources may have thresholds in terms of how much
entropy they can provide in a single call to their entropy gathering
function which may be exceeded by the present HMAC DRBG implementation
even if the threshold is not smaller than `security_strength` bits.
Specifically, this is the case for our own entropy module implementation
which only allows requesting at most 32 Bytes of entropy at a time
in configurations disabling SHA-512, and this leads to runtime failure
of HMAC DRBG when used with Mbed Crypto' own entropy callbacks in such
configurations.

This commit fixes this by splitting the seed entropy acquisition into
two calls, one requesting `security_strength` bits first, and another
one requesting `security_strength / 2` bits for the nonce.

Fixes #237.
2019-08-30 12:16:06 +01:00
Manuel Pégourié-Gonnard
fc8adbadb5 Merge branch 'mbedtls-2.16' into baremetal-2.16-20190827
* mbedtls-2.16: (21 commits)
  Exclude DTLS 1.2 only with older OpenSSL
  Document the rationale for the armel build
  Switch armel build to -Os
  Add a build on ARMv5TE in ARM mode
  Add changelog entry for ARM assembly fix
  bn_mul.h: require at least ARMv6 to enable the ARM DSP code
  Changelog entry for test certificates update
  Change worktree_rev to HEAD for rev-parse
  Add ChangeLog entry for entropy_nv_seed test case fix
  entropy_nv_seed: cope with SHA-256
  entropy_nv_seed: clean up properly
  Add ChangeLog entry for undefined behavior fix in test_suite_nist_kw
  Don't call memset after calloc
  Adapt ChangeLog
  ECP restart: Don't calculate address of sub ctx if ctx is NULL
  Update certificates to expire in 2029
  Update soon to be expired crl
  Test that a shared library build produces a dynamically linked executable
  Test that the shared library build with CMake works
  Add a test of MBEDTLS_CONFIG_FILE
  ...
2019-08-30 13:08:33 +02:00
Hanno Becker
f6cc7423aa Prescribe inlining of tls_prf_generic()
The NO_INLINE annotation of tls_prf_sha256() and tls_prf_sha384() from
the last commit surprisingly had an influence on ARMC5 compilation in
that tls_prf_generic() was no longer automatically inlined into
tls_prf_sha256() if only the latter was enabled (and is the point
where tls_prf_generic() is called). This commit forces inlining
of tls_prf_generic() in this case.
2019-08-29 16:02:11 +01:00
Hanno Becker
2793f740a9 Forbid inlining of some functions to reduce code-size on ARMC6
Usually, compilers are clever enough to pick the best inlining
strategy, but in this instance, it appears that compiling on ARMC6,
the compilers inlines xxx_prf_yyy() and xxx_calc_finished_yyy()
even though it really shouldn't. Forbid inlining through the use
of __attribute__((noinline)).
2019-08-29 16:02:10 +01:00
Hanno Becker
298a47064c Force inlining of ssl_populate_transform() if used only once
Somehow, at least ARMC5 isn't able to recognize this automatically.
Since some of the arguments to ssl_populate_transform() are compile-
time constants in reduced configurations, inlining leads to slightly
shorter code.
2019-08-29 16:02:10 +01:00
Hanno Becker
fc7429eef4 Remove forward declarations of calc_finished functions in ssl_tls.c 2019-08-29 16:02:09 +01:00
Hanno Becker
cf87c5e0a1 Avoid forward declarations of calc_verify functions in ssl_tls.c 2019-08-29 16:01:32 +01:00
Hanno Becker
8671e7b9f7 Remove redundant SHA-1 code-path in TLS-1.2 handling of CrtVrfy
SHA-1 is no longer offered nor accepted for the client's CertificateVerify
message in TLS 1.2. See 0a64170.
2019-08-29 16:01:32 +01:00
Hanno Becker
2f41b248c1 Remove calc_verify SSL function pointer 2019-08-29 16:01:32 +01:00
Hanno Becker
8443491280 Make SSL checksum update function inline
This saves a few bytes in configurations where only one hash
is enabled, and configurations allowing multiple hashes probably
don't care about code-size anyway.
2019-08-29 16:01:31 +01:00
Hanno Becker
8a4b59049b Remove checksum update function pointer from SSL handshake params 2019-08-29 16:01:31 +01:00
Hanno Becker
533f5b1d8d Remove ssl_optimize_checksum()
This function is called on client-only once the ciphersuite has
been chosen and it it is known which digest the client will need
for the handshake transcript throughout the handshake, and causes
all other unneeded handshake transcripts to be discontinued.

(On the server, we cannot call this function because we don't know
 which hash the client will those in its CertificateVerify message).

However, the benefit of this call is marginal, since transcript hash
computation is negligible compared to asymmetric crypto, and moreover
the handshake transcript contexts for the unused digests are still
stored in the SSL handshake parameter structure and not freed until
the end of the handshake.

Finally, if we're running on a _really_ constrained client, there
will be only one hash function enabled anyway, and in this case
the checksum optimization has no effect.

This commit therefore removes checksum optimization altogether,
saving some code on constrained systems.
2019-08-29 16:01:31 +01:00
Hanno Becker
c2fb759f3b Remove TLS calc_finished function pointer from SSL handshake params 2019-08-29 16:01:31 +01:00
Hanno Becker
39c7f7e3de Remove TLS PRF function pointer from SSL handshake parameters 2019-08-29 16:01:30 +01:00
Manuel Pégourié-Gonnard
7228167843
Merge pull request #647 from hanno-arm/hmac_drbg_entropy_fix-baremetal
[Baremetal] Fix incompatibility between HMAC DRBG and entropy module
2019-08-28 09:20:38 +02:00
Manuel Pégourié-Gonnard
87f57f6df0
Merge pull request #642 from jarvte/mbedtls_ssl_set_hostname_to_optional
[baremetal] Make function mbedtls_ssl_set_hostname(...) as optional
2019-08-28 09:20:20 +02:00
Hanno Becker
4598e49916 Don't use P-256 test CRTs if P-256 is known to be disabled 2019-08-27 11:41:37 +01:00
Hanno Becker
31c95e1e94 Fix and improve documentation of HMAC DRBG
- a comment regarding the implementation of hmac_drbg_reseed_core()
  was misplaced.
- add more references to the standard, and add details on how the
  comments in the code refer to various parts of the standard.
2019-08-27 09:22:09 +01:00
Hanno Becker
b3a06e66d8 hmac_drbg.c: Rename hmac_drbg_reseed_internal->hmac_drbg_reseed_core 2019-08-27 09:21:44 +01:00
Teppo Järvelin
4009d8f377 Make function mbedtls_ssl_set_hostname(...) as optional
Now function mbedtls_ssl_set_hostname is compile-time configurable
in config.h with define MBEDTLS_X509_REMOVE_HOSTNAME_VERIFICATION.
This affects to many x509 API's. See config.h for details.
2019-08-27 10:47:08 +03:00
Hanno Becker
eab304caf5 HMAC DRBG: Split entropy-gathering requests to reduce request sizes
According to SP800-90A, the DRBG seeding process should use a nonce
of length `security_strength / 2` bits as part of the DRBG seed. It
further notes that this nonce may be drawn from the same source of
entropy that is used for the first `security_strength` bits of the
DRBG seed. The present HMAC DRBG implementation does that, requesting
`security_strength * 3 / 2` bits of entropy from the configured entropy
source in total to form the initial part of the DRBG seed.

However, some entropy sources may have thresholds in terms of how much
entropy they can provide in a single call to their entropy gathering
function which may be exceeded by the present HMAC DRBG implementation
even if the threshold is not smaller than `security_strength` bits.
Specifically, this is the case for our own entropy module implementation
which only allows requesting at most 32 Bytes of entropy at a time
in configurations disabling SHA-512, and this leads to runtime failure
of HMAC DRBG when used with Mbed TLS' own entropy callbacks in such
configurations.

This commit fixes this by splitting the seed entropy acquisition into
two calls, one requesting `security_strength` bits first, and another
one requesting `security_strength / 2` bits for the nonce.
2019-08-26 15:39:23 +01:00
Hanno Becker
75bc82702f Load raw certificate and key data from files to certs.c 2019-08-23 11:39:46 +01:00
Hanno Becker
ba7082cc43 Add prototypes for Secp256r1 test CRTs and keys to certs.c 2019-08-23 11:39:45 +01:00
Simon Butcher
6617a24056 Merge remote-tracking branch 'origin/pr/633' into baremetal 2019-08-21 13:46:18 +01:00
Simon Butcher
f0f01e1f0a Merge remote-tracking branch 'origin/pr/630' into baremetal 2019-08-14 16:53:38 +01:00
Simon Butcher
434ab19164 Merge remote-tracking branch 'origin/pr/629' into baremetal 2019-08-14 16:53:13 +01:00
Simon Butcher
0863b2a259 Merge remote-tracking branch 'origin/pr/612' into baremetal 2019-08-14 16:50:13 +01:00
Gilles Peskine
6d079baba8 Merge remote-tracking branch 'upstream-restricted/mbedtls-2.16-proposed' into mbedtls-2.16-restricted 2019-08-14 16:39:36 +02:00
Gilles Peskine
4d7c74811b Merge remote-tracking branch 'upstream-restricted/pr/503' into mbedtls-2.16-restricted 2019-08-14 16:39:24 +02:00
Gilles Peskine
33f66ba6fd Merge remote-tracking branch 'upstream-restricted/pr/556' into mbedtls-2.16-restricted 2019-08-14 16:38:26 +02:00
Gilles Peskine
3a930650c8 Merge remote-tracking branch 'upstream-restricted/pr/613' into mbedtls-2.16-restricted 2019-08-14 16:36:30 +02:00
Gilles Peskine
b963f23b82 Merge remote-tracking branch 'upstream-public/pr/2751' into mbedtls-2.16 2019-08-14 16:00:37 +02:00
Hanno Becker
a9d5c452f3 Remove mbedtls_ssl_transform::minlen 2019-08-13 15:04:39 +01:00
Hanno Becker
b72fc6a648 Don't use const var in initialization of another const var
ARM Compiler doesn't like it.
2019-08-12 18:01:48 +01:00
Hanno Becker
8295ff0b04 tinyCrypt: Don't store public ECDH-share in handshake struct
Instead, write it to the message buffer directly.
2019-08-12 18:01:47 +01:00
Hanno Becker
b1626fb619 tinyCrypt: Remove check for Secp256r1 in SrvKeyExch writing
The use of tinyCrypt is restricted Secp256r1-only, and a check in
ssl_ciphersuite_is_match() ensures that an EC ciphersuite is chosen
only if the client advertised support for Secp256r1, too.
2019-08-12 18:01:47 +01:00
Hanno Becker
9cf087d2e7 Use tinyCrypt only for ECDHE-RSA/ECDSA in SrvKeyExch writing
In a way inconsistent with the rest of the library restricting the
use of tinyCrypt to pure-ECDHE, the previous ServerKeyExchange writing
routine would use tinyCrypt also for ECDHE-PSK-based ciphersuites.
This commit fixes this.
2019-08-12 18:01:47 +01:00
Hanno Becker
7a19633c99 tinyCrypt: Avoid unused var warning by marking vars as unused 2019-08-12 18:01:47 +01:00
Hanno Becker
29d165565c Add MBEDTLS_ECDH_C guards to ECDH code-paths using legacy ECDH
Previously, MBEDTLS_KEY_EXCHANGE_ECDH[E]_XXX_ENABLED would imply
that MBEDTLS_ECDH_C is set, but with the introduction of tinyCrypt
as an alternative ECDH implementation, this is no longer the case.
2019-08-12 18:01:40 +01:00
Hanno Becker
975b9ee3c8 Fix guards around use of legacy ECDH context
mbedtls_ssl_handshake_params::ecdh_ctx should only be guarded
by MBEDTLS_ECDH_C, not by MBEDTLS_ECDSA_C.
2019-08-12 17:05:38 +01:00
Hanno Becker
621113fd3a tinyCrypt: Write client's key share 2019-08-12 17:05:38 +01:00
Hanno Becker
a3c2c1712c tinyCrypt: Share ECDH secret calculation code-path 2019-08-12 17:05:38 +01:00
Hanno Becker
75f12d1eb9 tinyCrypt: Add ServerKeyExchange parsing code 2019-08-12 17:05:38 +01:00
Hanno Becker
d849c7ca19 tinyCrypt: Hardcode ECDH parameter header
Saves a few bytes of code when tinyCrypt is used.
2019-08-12 17:05:38 +01:00
Hanno Becker
d089fad925 tinyCrypt: Adapt RNG wrapper to return 0 on failure 2019-08-12 17:05:38 +01:00
Hanno Becker
ef982d57bf tinyCrypt: Bind RNG wrapper to tinyCrypt in mbedtls_ssl_setup() 2019-08-12 17:05:38 +01:00
Jarno Lamsa
e12aafbdc7 tinyCrypt: Initial commit towards ECDHE support
This commit is a first step towards using uECC for ECDH
during TLS handshakes.
2019-08-12 17:05:38 +01:00
Hanno Becker
3328b1822a Move ssl_process_in_server_key_exchange to avoid func use-before-def 2019-08-12 17:05:03 +01:00
Hanno Becker
4e46709800 Document precoditions on some HS parsing/writing functions
Eventually, all HS parsing/writing functions should take an arbitrary buffer +
length pair as their argument, and return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL if
the provided buffer is too short. So far, we've only made a first step by
allowing to pass an arbitrary buffer, but don't yet add bounds checks
throughout. While deliberate for now, this must be clearly documented.
2019-08-12 17:05:03 +01:00
Hanno Becker
7d552fad65 Avoid collision of ssl_xxx_key_exchange_yyy() func names in cli/srv
This makes grepping the functions more difficult, and also leads to compilation failures
when trying to build the library from a single source file (which might be useful for
code-size reasons).
2019-08-12 17:05:03 +01:00
Hanno Becker
48e526b380 Document parameter precondition for ssl_rsa_generate_partial_pms() 2019-08-12 17:05:03 +01:00
Hanno Becker
aa49620f6e Minor documentation improvement to ssl_rsa_encrypt_partial_pms() 2019-08-12 17:05:03 +01:00
Hanno Becker
084694dd57 Fix copy-pasta in documentation for outgoing CliKeyExchange 2019-08-12 17:05:03 +01:00
Hanno Becker
44a29f4a6f Remove redundant use of local variable in CliKeyExch writing 2019-08-12 17:05:03 +01:00
Hanno Becker
ae22dd3820 Simplify logic of restartable ECDHE in CliKeyExch writing 2019-08-12 17:05:03 +01:00
Hanno Becker
91cf7693b9 Remove restartable ECP return code check from ECDH suite handling
mbedtls_ecdh_read_params() is not restartable.
2019-08-12 17:05:03 +01:00
Manuel Pégourié-Gonnard
fb02e96cf5 Fix indentation to a multiple of 4 spaces 2019-08-12 17:05:03 +01:00
Manuel Pégourié-Gonnard
8793fab635 Fix two typos in comments 2019-08-12 17:05:03 +01:00
Hanno Becker
587c1ae195 Make IAR happy by dummy-initializing an unused variable
IAR doesn't like `((void) var);` as a means to indicate an unused
variable if that variable hasn't been initialized before. Make it
happy by initializing the variable before.
2019-08-12 17:05:03 +01:00
Hanno Becker
7ba0a886bd Fix 'set but not used' ARM compiler warning 2019-08-12 17:05:03 +01:00
Hanno Becker
a855cb635d Avoid unused variable warning in ServerKeyExchange parsing
ssl_server_key_exchange_parse() is compiled even if there's no ciphersuite
enabled which uses it (for example, that's the case in RSA-only builds).
The rationale for that is to avoid cluttering the code with numerous
compile-time guards. A consequence, however, is the top of
ssl_server_key_exchange_parse() contains declarations for variables
which are never put to use, and rightfully leading to compiler warnings.

This commit silences these warnings by putting `((void) VAR);` statements
in the branch which detects if we ever happen to call the function in an
unexpected ciphersuite.
2019-08-12 17:05:03 +01:00
Hanno Becker
868cb586cc Rename SSL_PROC_CHK -> MBEDTLS_SSL_CHK 2019-08-12 17:05:03 +01:00
Hanno Becker
572d448ab2 Enforce NULL context for hardcoded RNG 2019-08-12 17:05:03 +01:00
Hanno Becker
9a12243b01 Introduce getter function for RNG context 2019-08-12 17:05:03 +01:00
Hanno Becker
9db697e8c6 Async operations: Simplify restart logic 2019-08-12 17:05:03 +01:00
Hanno Becker
4ec73cb251 Restructure SrvKeyExchange: Move parsing code 2019-08-12 17:05:03 +01:00
Hanno Becker
8b7b879143 Restructure SrvKeyExchange: Move msg skipping for PSK and RSA-PSK
In the PSK and RSA-PSK ciphersuites, the ServerKeyExchange message
MAY be skipped. This commit moves the code-path peeking at the
incoming message to decide whether it's probably a ServerKeyExchange
to the new coordination function ssl_server_key_exchange_coordinate().
2019-08-12 17:05:03 +01:00
Hanno Becker
eb76c20496 Restructure SrvKeyExchange: Move code for skipping SrvKeyExchange
This commit moves the code checking whether a SrvKeyExchange message
is expected or not to the new function ssl_srv_key_exchange_coordinate().

Note that the potential static DH extraction is done prior to the
coordination step.
2019-08-12 17:05:03 +01:00
Hanno Becker
fca604d355 Restructure SrvKeyExchange: Move static DH parameter extraction
This code moves the code-path that extracts static DH parameters
from the server's CRT (if applicable) to the new function
ssl_server_key_exchange_prepare().
2019-08-12 17:05:03 +01:00
Hanno Becker
04769ddb84 Restructure SrvKeyExchange: Add frame for structure
This commit adds declarations and dummy implementations for
the restructured incoming server key exchange handling that
will replace the previous ssl_parse_server_key_exchange().

The entry point for the SrvKeyExchange handling that is called
from the handshake state machine is

   `ssl_process_server_key_exchange()`,

splitting the processing into the following steps:

- Preparation: For a static DH key exchange, extract
               DH parameters from the server's CRT.
- Coordination: Check if a SrvKeyExchange message is expected
  (e.g., it isn't for a RSA-based key exchange)
- Reading: Fetch and check content and handshake type
           of incoming message.
- Parsing: Parse and store the ServerKeyExchange message.
- Postprocessing: Update handstate state machine.

The subsequent commits will scatter the code from the previous
monolithic function ssl_parse_server_key_exchange() among those
dedicated functions, commenting out each part of
ssl_parse_server_key_exchange() that has already been dealt with.
This gradual progression is meant to ease reviewing. Once all
code has been moved and all changes explained,
ssl_parse_server_key_exchange() will be removed.
2019-08-12 17:05:03 +01:00
Hanno Becker
09d236419e Share code between In-CliKeyExch and Out-CliKeyExch
The postprocessing code for the server-side incoming client key
exchange and the client-side outgoing client key exchange both
contain the same code-paths for building the premaster secret
depending on the chosen ciphersuite (e.g., for ECDHE-PSK,
concatenating the ECDHE secret with the chosen PSK).

This commit moves this common code to ssl_tls.c, allowing
client- and server-side to share it.
2019-08-12 17:05:03 +01:00
Hanno Becker
d116e82268 Restructure incoming CliKeyExch: Shorten postprocessing
This commit subsumes multiple branches of
ssl_client_key_exchange_postprocess() that call
mbedtls_ssl_psk_derive_premaster().
2019-08-12 17:05:03 +01:00
Hanno Becker
2eb716d626 Restructure incoming CliKeyExch: Remove old code
The code from the previous function ssl_parse_client_key_exchange()
has been entirely moved to one of the newly introduced subroutines
and is no longer needed. This commit removes it.
2019-08-12 17:05:03 +01:00
Hanno Becker
e7c4eed9b8 Restructure incoming CliKeyExch: Parsing code 2019-08-12 17:05:03 +01:00
Hanno Becker
1e23af8fa8 Restructure incoming CliKeyExch: Move PMS assembly code
After parsing and performing key generation operations,
the server-side incoming ClientKeyExchange handling includes
code-paths to assembly the PreMasterSecret (PMS) from the
available keying material, the exact assembly procedure
depending on which ciphersuite is in use. E.g., in an
(EC)DHE-PSK ciphersuite, the (EC)DHE secret would be concatenated
with the PSK to form the PMS.

This assembly of the PMS logically comes done after the ClientKeyExchange
has been parsed and the respective keying material has been generated,
and this commit moves it to the new postprocessing function
ssl_client_key_exchange_postprocess().
2019-08-12 17:05:03 +01:00
Hanno Becker
dc8bfb9001 Restructure incoming CliKeyExch: Move key derivation code
This commit moves the generation of the master secret and session keys
from the premaster secret (done in mbedtlsssl_derive_keys()) from the
previous ClientKeyExchange parsing function ssl_parse_client_key_exchange()
to the new postprocessing function ssl_client_key_exchange_postprocess().
2019-08-12 17:05:03 +01:00
Hanno Becker
7ec345d95f Restructure incoming CliKeyExch: Add frame for restructuring
This commit adds declarations and dummy implementations for
the restructured incoming client key exchange handling that
will replace the previous ssl_parse_client_key_exchange().

The entry point for the CliKeyExchange handling that is called
from the handshake state machine is

   `ssl_process_client_key_exchange()`,

splitting the processing into the following steps:

- Fetching: Read next message from the messaging layer
            and check that it has the correct type.
            The ClientKeyExchange message is never
            omitted, so there is no ambiguity in what
            to expect, and hence no dedicated preparation
            step as for other handshake states.
- Parsing:  Parse the ClientKeyExchange message and
            use the information in it to derive keying
            material such as the shared (EC)DHE secret.
- Postprocessing:
            Compute the session keys from the available
            keying material. This splits in two steps:
            (1) Build the PreMasterSecret (PMS) from the
                available keying material, e.g. concatenate
                the (EC)DHE secret with a PSK, if used.
            (2) Extract the MasterSecret and Session Keys
                from the PreMasterSecret.

The subsequent commits will scatter the code from the previous
monolithic function ssl_parse_client_key_exchange() among those
dedicated functions, commenting out each part of
ssl_parse_client_key_exchange() that has already been dealt with.
This gradual progression is meant to ease reviewing. Once all
code has been moved and all changes explained,
ssl_parse_client_key_exchange() will be removed.
2019-08-12 17:05:03 +01:00
Hanno Becker
4f68b04018 Restructure outgoing CliKeyExch: Remove old code
The code from the previous function ssl_write_client_key_exchange()
has been entirely moved to one of the newly introduced subroutines
and is no longer needed. This commit removes it.
2019-08-12 17:05:03 +01:00
Hanno Becker
87e3c9aae8 Restructure outgoing CliKeyExch: Move writing code
This commit moves the code responsible for
(a) generating the client's private and public (EC)DHE keys
(b) writing it to the message buffer
to the new writing function ssl_client_key_exchange_write().

As mentioned in the previous commit message, (a) and (b) are
currently inseparable at the (EC)DHE API level, which is why
(a) can't be moved to the preparation step.
2019-08-12 17:05:03 +01:00
Hanno Becker
01290c7240 Restructure outgoing CliKeyExch: Move RSA/RSA-PSK PMS generation
For RSA or RSA-PSK exchanges, the PMS contains 46 random bytes
picked by the client. These bytes are generated prior to the
writing of the ClientKeyExchange message.

This commit splits the previous function ssl_write_encrypted_pms() into
PPMS-GEN: ssl_rsa_generate_partial_pms()
PPMS-ENC: ssl_rsa_encrypt_partial_pms().
The prefix 'partial' is meant to emphasize that the generation of the PMS
is not always entirely done by these functions: For RSA-PSK e.g., the
PSK still needs to be added.

The two calls of ssl_write_encrypted_pms() in
ssl_write_client_key_exchange() will split in calls of the functions
PPMS-GEN and PPMS-ENC each, with PPMS-GEN being moved to the new
preparation function ssl_client_key_exchange_prepare() in this commit,
and PPMS-ENC being moved to ssl_client_key_exchange_write() in the
next commit.
2019-08-12 17:05:03 +01:00
Hanno Becker
6fb638b2fb Restructure outgoing CliKeyExch: Move PMS assembly code
After and performing key generation operations,
the client-side outgoing ClientKeyExchange handling includes
code-paths to assembly the PreMasterSecret (PMS) from the
available keying material, the exact assembly procedure
depending on which ciphersuite is in use. E.g., in an
(EC)DHE-PSK ciphersuite, the (EC)DHE secret would be concatenated
with the PSK to form the PMS.

This assembly of the PMS logically can be done after the ClientKeyExchange
has been written and the respective keying material has been generated,
and this commit moves it to the new postprocessing function
ssl_client_key_exchange_postprocess().

Ideally, the PMS assembly could be done prior to writing the
ClientKeyExchange message, but the (EC)DHE API does currently
not allow splitting secret-generation and secret-export; as
long as that's the case, we to generation and exporting in the
message writing function, forcing PMS assembly to be done in
the postprocessing.
2019-08-12 17:05:03 +01:00
Hanno Becker
5d397686a9 Restructure outgoing CliKeyExch: Add frame for new structure
This commit adds declarations and dummy implementations for
the restructured outgoing client key exchange handling that
will replace the previous ssl_write_client_key_exchange().

The entry point for the CliKeyExchange handling that is called
from the handshake state machine is

   `ssl_process_client_key_exchange()`,

splitting the processing into the following steps:

- Preparation
  Compute the keying material to be sent.
  * For (EC)DH: Pick parameters and compute PMS.
  * For ECJPAKE: Run round 2
  * For RSA: Encrypt PMS
- Writing: Prepare the writing of a new messae.
- Postprocessing: Update handstate state machine.

The subsequent commits will scatter the code from the previous
monolithic function ssl_write_client_key_exchange() among those
dedicated functions, commenting out each part of
ssl_write_client_key_exchange() that has already been dealt with.
This gradual progression is meant to ease reviewing. Once all
code has been moved and all changes explained,
ssl_write_client_key_exchange() will be removed.
2019-08-12 17:05:03 +01:00
Simon Butcher
7c1380d9d4 Merge remote-tracking branch 'origin/pr/619' into baremetal 2019-08-09 14:05:50 +01:00
Gilles Peskine
c3c738e0fe
Merge pull request #639 from ARMmbed/mbedtls-2.16-proposed
Merge mbedtls-2.16 into mbedtls-2.16-restricted
2019-08-05 11:06:37 +02:00
Manuel Pégourié-Gonnard
f3a15b3de0 Fix possibly-lossy conversion warning from MSVC
ssl_tls.c(4876): warning C4267: '=': conversion from 'size_t' to 'uint8_t', possible loss of data
2019-08-02 10:17:15 +02:00
Hanno Becker
8844055b0e Remove compression field from SSL session if compression disabled 2019-08-01 10:11:20 +02:00
Hanno Becker
ec01408389 Reintroduce length 0 check for records 2019-08-01 09:51:54 +02:00
Hanno Becker
8061c6e894 Don't use memcpy() for 2-byte copy operation
Manual copying is slightly shorter here.
2019-08-01 09:51:54 +02:00
Hanno Becker
7b5ba84624 Remove integer parsing macro
If this is introduced, it should be defined in a prominent place
and put to use throughout the library, but this is left for another
time.
2019-08-01 09:51:54 +02:00
Hanno Becker
618176126c Fix alignment in record header parsing routine 2019-08-01 09:51:54 +02:00
Hanno Becker
c1c173cadf Make sure 'record from another epoch' is displayed for next epoch
The test 'DTLS proxy: delay ChangeCipherSpec' from ssl-opt.sh
relies on this.
2019-08-01 09:51:53 +02:00
Hanno Becker
03e2db6f35 Implement record checking API
This commit implements the record checking API

   mbedtls_ssl_check_record()

on top of the restructured incoming record stack.

Specifically, it makes use of the fact that the core processing routines

  ssl_parse_record_header()
  mbedtls_ssl_decrypt_buf()

now operate on instances of the SSL record structure mbedtls_record
instead of the previous mbedtls_ssl_context::in_xxx fields.
2019-08-01 09:51:53 +02:00
Hanno Becker
21fc61c7a7 Mark ssl_parse_record_header() as const in SSL context 2019-08-01 09:51:53 +02:00
Hanno Becker
c360dcc679 [API break] Remove mbedtls_ssl_context::in_iv field
After the rewrite of incoming record processing to use the internal
SSL record structure mbedtls_record (which contains the data_offset
field to indicate where the IV resides), this field is no longer
necessary.

Note: This is an API break.
2019-08-01 09:51:53 +02:00
Hanno Becker
05413d9041 Remove duplicate setting of ssl->in_msgtype and ssl->in_msglen 2019-08-01 09:51:53 +02:00
Hanno Becker
bd70c8e771 Move update of in_xxx fields in ssl_get_next_record()
ssl_get_next_record() updates the legacy in_xxx fields in two places,
once before record decryption and once after. Now that record decryption
doesn't use or affect the in_xxx fields anymore, setting up the these
legacy fields can entirely be moved to the end of ssl_get_next_record(),
which is what this comit does.

This commit solely moves existing code, but doesn't yet simplify the
now partially redundant settings of the in_xxx fields. This will be
done in a separate commit.
2019-08-01 09:51:53 +02:00
Hanno Becker
bf256cdb0b Move update of in_xxx fields outside of ssl_prepare_record_content()
Multiple record attributes such as content type and payload length
may change during record decryption, and the legacy in_xxx fields
in the SSL context therefore need to be updated after the record
decryption routine ssl_decrypt_buf() has been called.

After the previous commit has made ssl_prepare_record_content()
independent of the in_xxx fields, setting them can be moved
outside of ssl_prepare_record_content(), which is what this
commit does.
2019-08-01 09:51:53 +02:00
Hanno Becker
106f3dab57 Reduce dependency of ssl_prepare_record_content() on in_xxx fields 2019-08-01 09:51:53 +02:00
Hanno Becker
68379720b6 Move ssl_update_in_pointers() to after record hdr parsing
Previously, ssl_update_in_pointers() ensured that the in_xxx pointers
in the SSL context are set to their default state so that the record
header parsing function ssl_parse_record_header() could make use of them.
By now, the latter is independent of these pointers, so they don't need
to be setup before calling ssl_parse_record_header() anymore.
However, other parts of the messaging stack might still depend on it
(to be studied), and hence this commit does not yet reomve
ssl_update_in_pointers() entirely.
2019-08-01 09:51:53 +02:00
Hanno Becker
fc55172c41 Mark DTLS replay check as const on the SSL context 2019-08-01 09:51:53 +02:00
Hanno Becker
6941245852 Move updating the internal rec ptrs to outside of rec hdr parsing
The stack maintains pointers mbedtls_ssl_context::in_xxx pointing to
various parts of the [D]TLS record header. Originally, these fields
were determined and set in ssl_parse_record_header(). By now,
ssl_parse_record_header() has been modularized to setup an instance
of the internal SSL record structure mbedtls_record, and to derive
the old in_xxx fields from that.

This commit takes a further step towards removing the in_xxx fields
by deriving them from the established record structure _outside_ of
ssl_parse_record_header() after the latter has succeeded.

One exception is the handling of possible client reconnects,
which happens in the case then ssl_parse_record_header() returns
MBEDTLS_ERR_SSL_UNEXPECTED_RECORD; since ssl_check_client_reconnect()
so far uses the in_xxx fields, they need to be derived from the
record structure beforehand.
2019-08-01 09:51:53 +02:00
Hanno Becker
40478be987 Mark ssl_decrypt_buf() as `const in the input SSL context
In fact, the SSL context is only used to access the debug callback.
2019-08-01 09:51:52 +02:00
Hanno Becker
a89610aaf2 Adapt ssl_prepare_record_content() to use SSL record structure 2019-08-01 09:51:52 +02:00
Hanno Becker
9babbf7e75 Use record length from record structure when fetching content in TLS 2019-08-01 09:51:52 +02:00
Hanno Becker
2720f4c33c Use record structure when remembering offset of next record in dgram 2019-08-01 09:51:52 +02:00
Hanno Becker
2528ee09ac Use SSL record structure when skipping over unexpected record 2019-08-01 09:51:52 +02:00
Hanno Becker
af5bcfc765 Adapt ssl_buffer_future_record() to work with SSL record structure 2019-08-01 09:51:52 +02:00
Hanno Becker
c6e7c573d9 Setup SSL record structure in ssl_parse_record_header()
This commit makes a first step towards modularizing the incoming record
processing by having it operate on instances of the structure mbedtls_record
representing SSL records.

So far, only record encryption/decryption operate in terms of record
instances, but the rest of the parsing doesn't. In particular,
ssl_parse_record_header() operates directly on the fixed input buffer,
setting the various ssl->in_xxx pointers and fields, and only directly
before/after calling ssl_decrypt_buf() these fields a converted to/from
mbedtls_record instances.

This commit does not yet remove the ssl->in_xxx fields, but makes a step
towards extending the lifetime of mbedtls_record structure representing
incoming records, by modifying ssl_parse_record_header() to setup an
instance of mbedtls_record, and setting the ssl->in_xxx fields from that
instance. The instance so-constructed isn't used further so far, and in
particular it is not yet consolidated with the instance set up for use
in ssl_decrypt_record(). That's for a later commit.
2019-08-01 09:51:52 +02:00
Hanno Becker
6c0e53ce6f Minor documentation improvements in ssl_parse_record_header() 2019-08-01 09:51:51 +02:00
Hanno Becker
e04527755b Check for sufficient datagram size in ssl_parse_record_header()
Previously, ssl_parse_record_header() did not check whether the current
datagram is large enough to hold a record of the advertised size. This
could lead to records being silently skipped over or backed up on the
basis of an invalid record length. Concretely, the following would happen:

1) In the case of a record from an old epoch, the record would be
   'skipped over' by setting next_record_offset according to the advertised
   but non-validated length, and only in the subsequent mbedtls_ssl_fetch_input()
   it would be noticed in an assertion failure if the record length is too
   large for the current incoming datagram.
   While not critical, this is fragile, and also contrary to the intend
   that MBEDTLS_ERR_SSL_INTERNAL_ERROR should never be trigger-able by
   external input.
2) In the case of a future record being buffered, it might be that we
   backup a record before we have validated its length, hence copying
   parts of the input buffer that don't belong to the current record.
   This is a bug, and it's by luck that it doesn't seem to have critical
   consequences.

This commit fixes this by modifying ssl_parse_record_header() to check that
the current incoming datagram is large enough to hold a record of the
advertised length, returning MBEDTLS_ERR_SSL_INVALID_RECORD otherwise.
2019-08-01 09:51:51 +02:00
Hanno Becker
a61925fa51 Don't send an alert when receiving a record of unknown ContentType
We don't send alerts on other instances of ill-formed records,
so why should we do it here? If we want to keep it, the alerts
should rather be sent ssl_get_next_record().
2019-08-01 09:51:49 +02:00
Hanno Becker
dc4d62748c Don't call ssl_fetch_input for record content fetch in DTLS
As explained in the previous commit, if mbedtls_ssl_fetch_input()
is called multiple times, all but the first call are equivalent to
bounds checks in the incoming datagram.
2019-08-01 09:50:27 +02:00
Hanno Becker
29823466a1 Don't call ssl_fetch_input for record hdr size check in DTLS
In DTLS, if mbedtls_ssl_fetch_input() is called multiple times without
resetting the input buffer in between, the non-initial calls are functionally
equivalent to mere bounds checks ensuring that the incoming datagram is
large enough to hold the requested data. In the interest of code-size
and modularity (removing a call to a non-const function which is logically
const in this instance), this commit replaces such a call to
mbedtls_ssl_fetch_input() by an explicit bounds check in
ssl_parse_record_header().
2019-08-01 09:50:27 +02:00
Hanno Becker
de7d6d33e5 Move size-check for DTLS record header with CID to DTLS-only branch 2019-08-01 09:50:27 +02:00
Hanno Becker
87b5626d73 Check same-port-reconnect from client outside of record hdr parsing
Previously, `ssl_handle_possible_reconnect()` was part of
`ssl_parse_record_header()`, which was required to return a non-zero error
code to indicate a record which should not be further processed because it
was invalid, unexpected, duplicate, .... In this case, some error codes
would lead to some actions to be taken, e.g. `MBEDTLS_ERR_SSL_EARLY_MESSAGE`
to potential buffering of the record, but eventually, the record would be
dropped regardless of the precise value of the error code. The error code
`MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED` returned from
`ssl_handle_possible_reconnect()` did not receive any special treatment and
lead to silent dopping of the record - in particular, it was never returned
to the user.

In the new logic this commit introduces, `ssl_handle_possible_reconnect()` is
part of `ssl_check_client_reconnect()` which is triggered _after_
`ssl_parse_record_header()` found an unexpected record, which is already in
the code-path eventually dropping the record; we want to leave this code-path
only if a valid cookie has been found and we want to reset, but do nothing
otherwise. That's why `ssl_handle_possible_reconnect()` now returns `0` unless
a valid cookie has been found or a fatal error occurred.
2019-08-01 09:50:27 +02:00
Hanno Becker
07d420d6ad Remove unnecessary backup of explicit IV in AEAD record decryption
There is no need to hold back the explicit IV for AEAD ciphers.
2019-08-01 09:50:27 +02:00
Hanno Becker
8244cfa8bc Remove redundant minimum length check
Availability of sufficient incoming data should be checked when
it is needed, which is in mbedtls_ssl_fetch_input(), and this
function has the necessary bounds checks in place.
2019-08-01 09:50:27 +02:00
Hanno Becker
6d3db0fa25 Improve documentation of mbedtls_ssl_decrypt_buf() 2019-08-01 09:50:26 +02:00
Hanno Becker
9520b31860 Remove misleading comment in mbedtls_ssl_decrypt_buf()
The comment doesn't seem to relate to the code that follows.
2019-08-01 09:50:26 +02:00
Hanno Becker
b603bd34bc Remove assertion in mbedtls_ssl_decrypt_buf()
mbedtls_ssl_decrypt_buf() asserts that the passed transform is not NULL,
but the function is only invoked in a single place, and this invocation
is clearly visible to be within a branch ensuring that the incoming
transform isn't NULL. Remove the assertion for the benefit of code-size.
2019-08-01 09:50:26 +02:00
Hanno Becker
f024285034 Check architectural bound for max record payload len in one place
The previous code performed architectural maximum record length checks
both before and after record decryption. Since MBEDTLS_SSL_IN_CONTENT_LEN
bounds the maximum length of the record plaintext, it suffices to check
only once after (potential) decryption.

This must not be confused with the internal check that the record
length is small enough to make the record fit into the internal input
buffer; this is done in mbedtls_ssl_fetch_input().
2019-08-01 09:50:26 +02:00
Hanno Becker
408a2742b3 Remove redundant length-0 checks for incoming unprotected records 2019-08-01 09:50:26 +02:00
Hanno Becker
1c26845777 Remove redundant length check during record header parsing
The check is in terms of the internal input buffer length and is
hence likely to be originally intended to protect against overflow
of the input buffer when fetching data from the underlying
transport in mbedtls_ssl_fetch_input(). For locality of reasoning,
it's better to perform such a check close to where it's needed,
and in fact, mbedtls_ssl_fetch_input() _does_ contain an equivalent
bounds check, too, rendering the bounds check in question redundant.
2019-08-01 09:50:26 +02:00
Manuel Pégourié-Gonnard
f1358acdc7 Fix bug in MBEDTLS_X509_CRT_REMOVE_TIME
When looking for a parent, all candidates were considered time-invalid due to
the #ifdef incorrectly including the `parent_valid = 1` line.

When MBEDTLS_HAVE_TIME_DATE is unset the time-validity of certificates is
never checked and always treated as valid. This is usually achieved by proper
usage of mbedtls_x509_time_is_past() and mbedtls_x509_time_is_future() (and
their definition when we don't HAVE_TIME_DATE).

Here the calls to these functions needs to be guarded by
MBEDTLS_X509_CRT_REMOVE_TIME as they access struct members whose presence is
controlled by this option. But the "valid" branch should still always be taken.

(Note: MBEDTLS_X509_CRT_REMOVE_TIME being set forces MBEDTLS_HAVE_TIME_DATE to
be unset, as enforce by check_config.h.)

This bug was found by `all.sh test_baremetal` - no need for a new test.
2019-07-30 16:56:58 +02:00
Manuel Pégourié-Gonnard
80eaddfc36 Clean generated *.su file and gitignore them 2019-07-30 16:56:58 +02:00
Manuel Pégourié-Gonnard
0d1db20490 Fix bug in skip_date() (MBEDTLS_X509_CRT_REMOVE_TIME)
Asserting `*p == end` right after setting `end = *p + len` will always fail
unless `len == 0`, which is never the case with properly-formed certificates.

The function x509_skip_dates() is modelled after x509_get_dates() which between
setting `end` and comparing it to `*p` calls mbedtls_x509_get_time() which
advances `*p` to the expected value, which is why this test works in
get_dates().

Since `skip_dates()` has `skip`, not `validate` in its name, and the entire
point of `MBEDTLS_X509_CRT_REMOVE_TIME` is to save code, we don't want to
call the relatively large functions needed to properly parse (and validate)
dates before throwing the parsed dates away, we can just fast-forward to the
end of the sequence.

This makes updating `end` and comparing it to `*p` after the fast-forward
redundant, as the comparison will always be true (unlike the case where we
actually parse the contents of the sequence).

This bug was found by `all.sh test_baremetal` - no need for a new test.
2019-07-30 16:56:25 +02:00
Hanno Becker
93de2965d0 Fix rebase slip 2019-07-30 16:56:25 +02:00
Hanno Becker
82ff6f1e17 Update version_features.c 2019-07-30 16:33:40 +03:00
Hanno Becker
02f2609551 Introduce configuration option and API for SSL record checking 2019-07-30 15:38:40 +03:00
Manuel Pégourié-Gonnard
cdb83e7c88
Merge pull request #616 from mpg/context-s11n
[baremetal] Implement context serialization
2019-07-30 00:07:23 +02:00
Manuel Pégourié-Gonnard
69a3e417d8 Improve reability and debugability of large if
Breaking into a series of statements makes things easier when stepping through
the code in a debugger.

Previous comments we stating the opposite or what the code tested for (what we
want vs what we're erroring out on) which was confusing.

Also expand a bit on the reasons for these restrictions.
2019-07-29 12:32:02 +02:00
Manuel Pégourié-Gonnard
18332c5c6c Improve getter for renegotiation enabled 2019-07-29 12:17:52 +02:00
Manuel Pégourié-Gonnard
7c575d29dc
Merge pull request #605 from ARMmbed/x509_ondemand_remove_unneeded_fields
[Baremetal] Allow removal of unneeded fields in X.509 CRT structures
2019-07-29 11:58:58 +02:00
Manuel Pégourié-Gonnard
b3bb31bd90 Introduce getter function for disable_renego 2019-07-26 16:37:45 +02:00
Manuel Pégourié-Gonnard
14e2a8ac06 Fix a typo in a comment 2019-07-26 16:31:53 +02:00
Hanno Becker
42a6b04c4a Don't forget about pending alerts after ssl_get_next_record()
ssl_get_next_record() may pend fatal alerts in response to receiving
invalid records. Previously, however, those were never actually sent
because there was no code-path checking for pending alerts.

This commit adds a call to ssl_send_pending_fatal_alert() after
the invocation of ssl_get_next_record() to fix this.
2019-07-26 07:25:20 +01:00
Hanno Becker
b82350b25f Introduce helper function to send pending fatal alerts 2019-07-26 07:25:02 +01:00
Hanno Becker
c8f529995f Rename pend_alert_msg -> pending_fatal_alert_msg 2019-07-25 12:59:24 +01:00
Hanno Becker
2e8d133ebf Reintroduce return code checking when sending NoRenego alert 2019-07-25 12:58:48 +01:00
Hanno Becker
3caf7189f9 Remove field to store level of pending alert
Pending alerts is so far only used for fatal alerts.
2019-07-25 12:58:44 +01:00
Hanno Becker
de62da9d3c Use separate functions to pend fatal and non-fatal alerts 2019-07-24 13:45:35 +01:00
Hanno Becker
1facd552fc Replace xxx_send_alert by xxx_pend_alert to save code 2019-07-24 13:20:27 +01:00
Hanno Becker
f46e1ce812 Introduce SSL helper function to mark pending alerts 2019-07-24 13:20:27 +01:00
Manuel Pégourié-Gonnard
7af7375473 Fix MSVC warning
We know the length of the ALPN string is always less than 255, so the cast to
uint8_t is safe.
2019-07-24 00:58:27 +02:00
Manuel Pégourié-Gonnard
2cc9223a3b Fix compile error in reduced configurations
Found by running scripts/baremetal.h --rom --gcc --check after adding
MBEDTLS_SSL_CONTEXT_SERIALIZATION to baremetal.h
2019-07-23 17:22:39 +02:00
Simon Butcher
3b014fc23a Merge remote-tracking branch 'origin/pr/604' into baremetal 2019-07-23 16:16:24 +01:00
Simon Butcher
6fe6b437da Merge remote-tracking branch 'origin/pr/589' into baremetal 2019-07-23 16:10:56 +01:00
Simon Butcher
c0b3633194 Merge remote-tracking branch 'origin/pr/627' into baremetal 2019-07-23 16:06:07 +01:00
Manuel Pégourié-Gonnard
7ce9446e4c Avoid duplication of session format header 2019-07-23 17:02:11 +02:00
Manuel Pégourié-Gonnard
a7cd4830ee Implement config-checking header to context s11n
Modelled after the config-checking header from session s11n.

The list of relevant config flags was established by manually checking the
fields serialized in the format, and which config.h flags they depend on.
This probably deserves double-checking by reviewers.
2019-07-23 17:02:10 +02:00