Commit graph

4483 commits

Author SHA1 Message Date
Hanno Becker 2e24c3b672 Provide standalone version of ssl_decrypt_buf
Analogous to the previous commit, but concerning the record decryption
routine `ssl_decrypt_buf`.

An important change regards the checking of CBC padding:
Prior to this commit, the CBC padding check always read 256 bytes at
the end of the internal record buffer, almost always going past the
boundaries of the record under consideration. In order to stay within
the bounds of the given record, this commit changes this behavior by
always reading the last min(256, plaintext_len) bytes of the record
plaintext buffer and taking into consideration the last `padlen` of
these for the padding check. With this change, the memory access
pattern and runtime of the padding check is entirely determined by
the size of the encrypted record, in particular not giving away
any information on the validity of the padding.

The following depicts the different behaviors:

1) Previous CBC padding check

1.a) Claimed padding length <= plaintext length

  +----------------------------------------+----+
  |   Record plaintext buffer   |          | PL |
  +----------------------------------------+----+
                                 \__ PL __/

                                +------------------------------------...
                                |  read for padding check            ...
                                +------------------------------------...
                                                |
                                                 contents discarded
                                                 from here

1.b) Claimed padding length > plaintext length

  +----------------------------------------+----+
  |   Record plaintext buffer              | PL |
  +----------------------------------------+----+
                                           +-------------------------...
                                           |  read for padding check ...
                                           +-------------------------...
                                                |
                                                 contents discarded
                                                 from here

2) New CBC padding check

  +----------------------------------------+----+
  |   Record plaintext buffer   |          | PL |
  +----------------------------------------+----+
                                 \__ PL __/

        +---------------------------------------+
        |        read for padding check         |
        +---------------------------------------+
                                |
                                 contents discarded
                                 until here
2019-04-25 12:58:21 +01:00
Hanno Becker 9eddaebda5 Provide standalone version of ssl_encrypt_buf
The previous version of the record encryption function
`ssl_encrypt_buf` takes the entire SSL context as an argument,
while intuitively, it should only depend on the current security
parameters and the record buffer.

Analyzing the exact dependencies, it turned out that in addition
to the currently active `ssl_transform` instance and the record
information, the encryption function needs access to
- the negotiated protocol version, and
- the status of the encrypt-then-MAC extension.

This commit moves these two fields into `ssl_transform` and
changes the signature of `ssl_encrypt_buf` to only use an instance
of `ssl_transform` and an instance of the new `ssl_record` type.
The `ssl_context` instance is *solely* kept for the debugging macros
which need an SSL context instance.

The benefit of the change is twofold:
1) It avoids the need of the MPS to deal with instances of
   `ssl_context`. The MPS should only work with records and
   opaque security parameters, which is what the change in
   this commit makes progress towards.
2) It significantly eases testing of the encryption function:
   independent of any SSL context, the encryption function can
   be passed some record buffer to encrypt alongside some arbitrary
   choice of parameters, and e.g. be checked to not overflow the
   provided memory.
2019-04-25 12:58:21 +01:00
Hanno Becker 52344c2972 Correct space needed for MAC in case of NULL cipher
The macro constant `MBEDTLS_SSL_MAC_ADD` defined in `ssl_internal.h`
defines an upper bound for the amount of space needed for the record
authentication tag. Its definition distinguishes between the
presence of an ARC4 or CBC ciphersuite suite, in which case the maximum
size of an enabled SHA digest is used; otherwise, `MBEDTLS_SSL_MAC_ADD`
is set to 16 to accomodate AEAD authentication tags.

This assignment has a flaw in the situation where confidentiality is
not needed and the NULL cipher is in use. In this case, the
authentication tag also uses a SHA digest, but the definition of
`MBEDTLS_SSL_MAC_ADD` doesn't guarantee enough space.

The present commit fixes this by distinguishing between the presence
of *some* ciphersuite using a MAC, including those using a NULL cipher.
For that, the previously internal macro `SSL_SOME_MODES_USE_MAC` from
`ssl_tls.c` is renamed and moved to the public macro
`MBEDTLS_SOME_MODES_USE_MAC` defined in `ssl_internal.h`.
2019-04-25 12:58:21 +01:00
Hanno Becker e694c3ef3e Remove ciphersuite_info from ssl_transform
Prior to this commit, the security parameter struct `ssl_transform`
contained a `ciphersuite_info` field pointing to the information
structure for the negotiated ciphersuite. However, the only
information extracted from that structure that was used in the core
encryption and decryption functions `ssl_encrypt_buf`/`ssl_decrypt_buf`
was the authentication tag length in case of an AEAD cipher.

The present commit removes the `ciphersuite_info` field from the
`ssl_transform` structure and adds an explicit `taglen` field
for AEAD authentication tag length.

This is in accordance with the principle that the `ssl_transform`
structure should contain the raw parameters needed for the record
encryption and decryption functions to work, but not the higher-level
information that gave rise to them. For example, the `ssl_transform`
structure implicitly contains the encryption/decryption keys within
their cipher contexts, but it doesn't contain the SSL master or
premaster secrets. Likewise, it contains an explicit `maclen`, while
the status of the 'Truncated HMAC' extension -- which  determines the
value of `maclen` when the `ssl_transform` structure is created in
`ssl_derive_keys` -- is not contained in `ssl_transform`.

The `ciphersuite_info` pointer was used in other places outside
the encryption/decryption functions during the handshake, and for
these functions to work, this commit adds a `ciphersuite_info` pointer
field to the handshake-local `ssl_handshake_params` structure.
2019-04-25 12:58:21 +01:00
Hanno Becker 88aaf652b1 Remove key length field from ssl_transform
The `ssl_transform` security parameter structure contains opaque
cipher contexts for use by the record encryption/decryption functions
`ssl_decrypt_buf`/`ssl_encrypt_buf`, while the underlying key material
is configured once in `ssl_derive_keys` and is not explicitly dealt with
anymore afterwards. In particular, the key length is not needed
explicitly by the encryption/decryption functions but is nonetheless
stored in an explicit yet superfluous `keylen` field in `ssl_transform`.
This commit removes this field.
2019-04-25 12:57:19 +01:00
Jaeden Amero 3956a847e6 Merge remote-tracking branch 'origin/pr/2092' into development
* origin/pr/2092:
  Add more missing parentheses around macro parameters
  Add further missing brackets around macro parameters
  Adapt ChangeLog
  Improve macro hygiene
2019-04-24 11:17:21 +01:00
Jaeden Amero f790a6cbee Merge remote-tracking branch 'origin/pr/2536' into development
* origin/pr/2536:
  Update crypto submodule
  Minor fixes in get certificate policies oid test
  Add certificate policy oid x509 extension
2019-04-17 10:52:54 +01:00
Jaeden Amero 7a1c4eb826 Merge remote-tracking branch 'origin/pr/2567' into development
* origin/pr/2567:
  Don't use debug level 1 for informational messages
2019-04-16 15:08:39 +01:00
Jaeden Amero fe7106755e Merge remote-tracking branch 'origin/pr/2539' into development
Resolve conflicts by performing the following:
  - Ensure calls to mbedtls_x509_crt_verify_* are made with callbacks

* origin/pr/2539:
  Make CRT callback tests more robust
  Rename constant in client2.c
  Fix typo
  Add test for configuration specific CRT callback
  Fix doxygen documentation of mbedtls_ssl_set_verify()
  Add test exercising context-specific CRT callback to ssl-opt.sh
  Add cmd to use context-specific CRT callback in ssl_client2
  Implement context-specific verification callbacks
  Add context-specific CRT verification callbacks
  Improve documentation of mbedtls_ssl_conf_verify()
2019-04-16 15:05:18 +01:00
Jaeden Amero ff34d43720 Merge remote-tracking branch 'origin/pr/2532' into development
* origin/pr/2532: (29 commits)
  Document and test flags in x509_verify
  Fix style issues and a typo
  Fix name to function call
  Address comments for x509 tests
  Address review comments regarding ssl_client2 and ssl tests
  Remove mbedtls_ from the static function name
  Change docs according to review comments
  Change the verify function naming
  Fix ssl_client2 and ssl_server2 if !PLATFORM_C
  Correct placement of usage macro in ssl_client2
  Update version_features.c
  Remove trailing whitespace in test_suite_x509parse.function
  Update query_config.c
  Add ssl-opt.sh tests for trusted CA callbacks
  Only run X.509 CRT verification tests with CA callback tests if !CRL
  Minor fixes to CA callback tests
  Declare CA callback type even if feature is disabled
  Implement X.509 CRT verification using CA callback
  Add prototype for CRT verification with static and dynamic CA list
  Make use of CA callback if present when verifying peer CRT chain
  ...
2019-04-16 14:42:11 +01:00
Ron Eldor e82341646a Add certificate policy oid x509 extension
Add the `MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES` to the list
of supported x509 extensions, in `mbedtls_oid_get_x509_ext_type()`.
2019-04-16 13:26:54 +03:00
Jaeden Amero e6d5a501ba Merge remote-tracking branch 'origin/pr/2558' into development
* origin/pr/2558:
  Skip uncritical unsupported extensions
2019-04-15 13:13:26 +01:00
Hanno Becker 4c8c7aa95e Don't use debug level 1 for informational messages 2019-04-10 09:26:53 +01:00
Ron Eldor df48efa77a Skip uncritical unsupported extensions
Skip extensions that have support in the `oid` layer`, but
no parser found in the x509 layer, in case these are not critical.
2019-04-10 11:06:53 +03:00
Jaeden Amero aa3402018e Merge remote-tracking branch 'origin/pr/2535' into development
* origin/pr/2535:
  Add Wisun Fan device extended key usage
2019-04-05 14:36:08 +01:00
Jaeden Amero d192ba4ef1 Merge remote-tracking branch 'origin/pr/2463' into development
* origin/pr/2463:
  Fix a rebase error
  Wrap lines at 80 columns
  Add NIST keywrap as a cipher mode
  Fix errors in AEAD test function
2019-04-05 14:15:40 +01:00
Jaeden Amero 62ab1f9961 Merge remote-tracking branch 'origin/pr/2405' into development
* origin/pr/2405:
  Fix ChangeLog entry ordering
  Fix typo
  Add non-regression test for buffer overflow
  Improve documentation of mbedtls_mpi_write_string()
  Adapt ChangeLog
  Fix 1-byte buffer overflow in mbedtls_mpi_write_string()
2019-04-05 14:08:49 +01:00
Jaeden Amero 1b86e4c881 Merge remote-tracking branch 'origin/pr/2106' into development
* origin/pr/2106:
  x509.c: Fix potential memory leak in X.509 self test
2019-04-05 13:47:06 +01:00
Hanno Becker efb440afec Add test exercising context-specific CRT callback to ssl-opt.sh 2019-04-03 13:11:20 +01:00
Hanno Becker 8927c83312 Implement context-specific verification callbacks 2019-04-03 12:53:28 +01:00
Ron Eldor b6dc105456 Add Wisun Fan device extended key usage
Add the Wisun extended key usage oid and tests.
2019-04-03 13:48:50 +03:00
Jack Lloyd 5f28999433 Wrap lines at 80 columns 2019-04-02 10:07:28 -07:00
Jack Lloyd ffdf28851d Add NIST keywrap as a cipher mode
Closes #2003 see also #1658
2019-04-02 10:02:55 -07:00
Jarno Lamsa 9822c0d2f1 Fix name to function call 2019-04-01 16:59:48 +03:00
Jarno Lamsa 2ee67a66f4 Remove mbedtls_ from the static function name 2019-04-01 14:59:33 +03:00
Jarno Lamsa 31d9db6195 Change the verify function naming
Change the naming to reflect that the function uses a new ca callback
feature to distinguish different callbacks.
2019-04-01 14:33:49 +03:00
Hanno Becker fed5d9d1e9 Update version_features.c 2019-03-28 17:07:12 +00:00
Hanno Becker f53893b00c Implement X.509 CRT verification using CA callback 2019-03-28 16:13:44 +00:00
Hanno Becker 3116fb362c Add prototype for CRT verification with static and dynamic CA list
So far, there were the following CRT verification functions:
- `mbedtls_x509_crt_verify()` -- no profile, no restartable ECC
- `mbedtls_x509_crt_verify_with_profile()` -- profile, no restartable ECC
- `mbedtls_x509_crt_verify_restartable()` -- profile, restartable ECC
all publicly declared and offering increasing functionality.

On the implementation-side,
- `mbedtls_x509_crt_verify()` resolves to
  a call to `mbedtls_x509_crt_verify_with_profile()` setting
  the profile to `NULL`, and
- `mbedtls_x509_crt_verify_with_profile()`
  resolves to a call to ``mbedtls_x509_crt_verify_restartable()`
  setting the ECC restart context to NULL.

This commit adds two more functions to this zoo:
- `mbedtls_x509_crt_verify_with_cb()`
- `x509_crt_verify_restartable_cb()`

Here, `mbedtls_x509_crt_verify_with_cb()` is similar to
`mbedtls_x509_crt_verify_with_profile()` but uses a CA callback
instead of a static CA list, and no restart context.

`x509_crt_verify_restartable_cb()` is similar to
`mbedtls_x509_crt_verify_restartable()` but allows to either use
a static list of trusted CAs _or_ a trusted CA callback.

On the implementation-side,
- the body of `mbedtls_x509_crt_verify_restartable()` is moved to
  `x509_crt_verify_restartable_cb()`, and the new version of
  `mbedtls_x509_crt_verify_restartable()` just resolves to
  `x509_crt_verify_restartable_cb()` with the trusted CA callback
  set to NULL.
- The new function `mbedtls_x509_crt_verify_with_cb()`
  forward to `x509_crt_verify_restartable_cb()` with the restart
  context set to `NULL`.

There's no change to the implementation yet, and in particular,
`mbedtls_x509_crt_verify_with_cb()` isn't yet usable.
2019-03-28 16:13:43 +00:00
Hanno Becker afd0b0a1a7 Make use of CA callback if present when verifying peer CRT chain 2019-03-28 16:13:43 +00:00
Hanno Becker 5adaad9846 Add X.509 CA callback to SSL configuration and implement setter API 2019-03-28 16:13:43 +00:00
Hanno Becker 8bf74f37dc Add SSL configuration API for trusted CA callbacks 2019-03-28 16:13:38 +00:00
Jaeden Amero 57773d4ede Merge remote-tracking branch 'restricted/pr/551' into development
* restricted/pr/551:
  ECP: Clarify test descriptions
  ECP: remove extra whitespaces
  Fix ECDH secret export for Mongomery curves
  Improve ECP test names
  Make ecp_get_type public
  Add more tests for ecp_read_key
  ECP: Catch unsupported import/export
  Improve documentation of mbedtls_ecp_read_key
  Fix typo in ECP module
  Remove unnecessary cast from ECP test
  Improve mbedtls_ecp_point_read_binary tests
  Add Montgomery points to ecp_point_write_binary
  ECDH: Add test vectors for Curve25519
  Add little endian export to Bignum
  Add mbedtls_ecp_read_key
  Add Montgomery points to ecp_point_read_binary
  Add little endian import to Bignum
2019-03-27 17:01:24 +00:00
Jaeden Amero 0ea33776ce Merge remote-tracking branch 'restricted/pr/552' into development
Ensure this merge passes tests by auto-generating query_config.c, adding
MBEDTLS_ECDH_LEGACY_CONTEXT to it.

* restricted/pr/552:
  Fix mbedtls_ecdh_get_params with new ECDH context
  Test undefining MBEDTLS_ECDH_LEGACY_CONTEXT in all.sh
  Define MBEDTLS_ECDH_LEGACY_CONTEXT in config.h
  Add changelog entry for mbedtls_ecdh_get_params robustness
  Fix ecdh_get_params with mismatching group
  Add test case for ecdh_get_params with mismatching group
  Add test case for ecdh_calc_secret
  Fix typo in documentation
2019-03-27 17:01:16 +00:00
Jaeden Amero c73fde725b Merge remote-tracking branch 'origin/pr/2531' into development
Ensure tests pass when the submodule is used by updating the list of
crypto tests to include test_suite_oid in both tests/CMakeLists.txt and
tests/Makefile.

* origin/pr/2531:
  Add changeLog entry
  Add certificate policy of type any policy id
2019-03-27 16:52:08 +00:00
Jaeden Amero 3930e18c3c Merge remote-tracking branch 'origin/pr/2509' into development
* origin/pr/2509:
  all.sh: Generate seedfile for crypto submodule tests
  Update crypto submodule to test with private headers
  tests: Use globbing in test suite exclusion list
  Update crypto submodule to Mbed Crypto development
  tests: Test crypto via the crypto submodule
2019-03-27 14:45:26 +00:00
Jaeden Amero d5d01a0435 Merge remote-tracking branch 'origin/pr/2525' into development
* origin/pr/2525:
  Update library version to 2.17.0
2019-03-26 14:50:06 +00:00
Ron Eldor 11ee07191f Add certificate policy of type any policy id
Add a function for getting the certificate policy. Currently only
"Any Policy" is supported.
2019-03-26 14:41:07 +02:00
Jaeden Amero 3f8d78411a Update library version to 2.17.0 2019-03-19 16:12:55 +00:00
Jaeden Amero 57f4d9e4fe Update crypto submodule to test with private headers
Update the crypto submodule to the top of the Mbed Crypto development
branch. This brings in a version of Mbed Crypto that enables building
Mbed Crypto tests that depend on private headers, like
'psa_crypto_invasive.h'.

This also requires updating our config.h to include new configuration
options added to Mbed Crypto. MBEDTLS_PSA_ITS_FILE_C replaces
MBEDTLS_PSA_CRYPTO_STORAGE_FILE_C and MBEDTLS_PSA_CRYPTO_STORAGE_ITS_C.
MBEDTLS_PSA_INJECT_ENTROPY replaces MBEDTLS_PSA_HAS_ITS_IO.
2019-03-19 15:45:09 +00:00
Janos Follath 80470627e2 Fix typo 2019-03-06 13:43:02 +00:00
Jaeden Amero a96f4fe94e Merge remote-tracking branch 'origin/pr/2380' into development
* origin/pr/2380:
  Fix backwards config dependency on oid.c
  Fix backwards include of x509.h in oid.h
2019-03-05 16:37:40 +00:00
Jaeden Amero 0a9f9b20b6 Merge remote-tracking branch 'origin/pr/2317' into development
* origin/pr/2317:
  Update ChangeLog
  all.sh: Test MBEDTLS_MPI_WINDOW_SIZE=1
  Fix DEADCODE in mbedtls_mpi_exp_mod()
2019-03-05 16:33:42 +00:00
Jaeden Amero db2c2ce881 Merge remote-tracking branch 'origin/pr/2158' into development
* origin/pr/2158:
  Whitespace fix for ccm, gcm, and pkcs5
  Rename remaining test data
  Rename globals to avoid shadowing by various function arguments
2019-03-05 16:29:53 +00:00
Jaeden Amero c851b08a49 Merge remote-tracking branch 'origin/pr/1818' into development
* origin/pr/1818:
  Move ChangeLog entry from Bugfix to Changes section
  Adapt ChangeLog
  Return from debugging functions if SSL context is unset
2019-03-05 16:27:38 +00:00
Jaeden Amero 7df1bec82b Merge remote-tracking branch 'origin/pr/1520' into development
* origin/pr/1520:
  Use certificates from data_files and refer them
  Specify server certificate to use in SHA-1 test
  refactor CA and SRV certificates into separate blocks
  refactor SHA-1 certificate defintions and assignment
  refactor server SHA-1 certificate definition into a new block
  define TEST_SRV_CRT_RSA_SOME in similar logic to TEST_CA_CRT_RSA_SOME
  server SHA-256 certificate now follows the same logic as CA SHA-256 certificate
  add entry to ChangeLog
2019-03-05 16:24:11 +00:00
Simon Butcher 535ee4a35b Merge remote-tracking branch 'public/pr/2421' into development
* public/pr/2421: (68 commits)
  Fix unused variable warning in ssl_parse_certificate_coordinate()
  Add missing compile time guard in ssl_client2
  Update programs/ssl/query_config.c
  ssl_client2: Reset peer CRT info string on reconnect
  Add further debug statements on assertion failures
  Fix typo in documentation of ssl_parse_certificate_chain()
  Add debug output in case of assertion failure
  Fix typo in SSL ticket documentation
  Add config sanity check for !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE
  ssl_client2: Zeroize peer CRT info buffer when reconnecting
  Reintroduce numerous ssl-opt.sh tests if !MBEDTLS_SSL_KEEP_PEER_CERT
  ssl_client2: Extract peer CRT info from verification callback
  Improve documentation of mbedtls_ssl_get_peer_cert()
  Improve documentation of MBEDTLS_SSL_KEEP_PEER_CERTIFICATE
  Fix indentation of Doxygen comment in ssl_internal.h
  Set peer CRT length only after successful allocation
  Remove question in comment about verify flags on cli vs. server
  Remove misleading and redundant guard around restartable ECC field
  Add test for !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE to all.sh
  Free peer CRT chain immediately after verifying it
  ...
2019-03-01 12:46:07 +00:00
Simon Butcher 195bddebcc Merge remote-tracking branch 'restricted/pr/528' into development
* restricted/pr/528:
  Update query_config.c
  Fix failure in SSLv3 per-version suites test
  Adjust DES exclude lists in test scripts
  Clarify 3DES changes in ChangeLog
  Fix documentation for 3DES removal
  Exclude 3DES tests in test scripts
  Fix wording of ChangeLog and 3DES_REMOVE docs
  Reduce priority of 3DES ciphersuites
2019-03-01 12:45:45 +00:00
Simon Butcher 74ac6e3fec Merge remote-tracking branch 'public/pr/2028' into development
* public/pr/2028:
  Update the crypto submodule to a78c958
  Fix ChangeLog entry to correct release version
  Fix typo in x509write test data
  Add ChangeLog entry for unused bits in bitstrings
  Improve docs for named bitstrings and their usage
  Add tests for (named) bitstring to suite_asn1write
  Add new function mbedtls_asn1_write_named_bitstring()
2019-03-01 12:44:19 +00:00
Simon Butcher bbed914b41 Merge remote-tracking branch 'public/pr/2447' into development
* public/pr/2447:
  Unbump version to 0.0.0
2019-03-01 12:41:25 +00:00
Andres Amaya Garcia 4a512281ec Reduce priority of 3DES ciphersuites 2019-03-01 10:19:27 +01:00
Hanno Becker 84d9d2734f Fix unused variable warning in ssl_parse_certificate_coordinate()
This was triggered in client-only builds.
2019-03-01 08:10:46 +00:00
Andres Amaya Garcia 6e95914f0e Add new function mbedtls_asn1_write_named_bitstring()
Add a new function mbedtls_asn1_write_named_bitstring() that removes
trailing 0s at the end of DER encoded bitstrings. The function is
implemented according to Hanno Becker's suggestions.

This commit also changes the functions x509write_crt_set_ns_cert_type
and crt_set_key_usage to call the new function as the use named
bitstrings instead of the regular bitstrings.
2019-02-28 09:36:30 +00:00
Janos Follath f607813f53 ECP: remove extra whitespaces 2019-02-26 17:02:37 +00:00
Janos Follath 52ff8e9387 Fix ECDH secret export for Mongomery curves
We only switched to little endian for Curve25519, but all Montgomery
curves require little endian byte order.
2019-02-26 16:49:52 +00:00
Janos Follath df9295b7ec Make ecp_get_type public
The ecp_get_type function comes handy in higher level modules and tests
as well. It is not inline anymore, to enable alternative implementations
to implement it for themselves.
2019-02-26 16:49:42 +00:00
Janos Follath 28eb06df16 ECP: Catch unsupported import/export
mbedtls_ecp_read_key() module returned without an error even when
importing keys corresponding to the requested group was not
implemented.

We change this and return an error when the requested group is not
supported and make the remaining import/export functions more robust.
2019-02-26 16:48:40 +00:00
Janos Follath 7780096f3b Fix typo in ECP module 2019-02-26 16:48:40 +00:00
Hanno Becker bd5580abb1 Add further debug statements on assertion failures 2019-02-26 14:38:09 +00:00
Hanno Becker 353a6f0d50 Fix typo in documentation of ssl_parse_certificate_chain() 2019-02-26 14:38:09 +00:00
Hanno Becker 62d58ed975 Add debug output in case of assertion failure 2019-02-26 14:38:09 +00:00
Hanno Becker 6883874013 Fix typo in SSL ticket documentation 2019-02-26 14:38:09 +00:00
Hanno Becker accc5998ae Set peer CRT length only after successful allocation 2019-02-26 14:38:09 +00:00
Hanno Becker 3acc9b9042 Remove question in comment about verify flags on cli vs. server 2019-02-26 14:38:09 +00:00
Hanno Becker 6b8fbab290 Free peer CRT chain immediately after verifying it
If we don't need to store the peer's CRT chain permanently, we may
free it immediately after verifying it. Moreover, since we parse the
CRT chain in-place from the input buffer in this case, pointers from
the CRT structure remain valid after freeing the structure, and we
use that to extract the digest and pubkey from the CRT after freeing
the structure.
2019-02-26 14:38:09 +00:00
Hanno Becker 0056eab3cd Parse peer's CRT chain in-place from the input buffer 2019-02-26 14:38:09 +00:00
Hanno Becker ae553dde3a Free peer's public key as soon as it's no longer needed
On constrained devices, this saves a significant amount of RAM that
might be needed for subsequent expensive operations like ECDHE.
2019-02-26 14:38:09 +00:00
Hanno Becker b9d4479080 Correct compile-time guards for ssl_clear_peer_cert()
It is used in `mbedtls_ssl_session_free()` under
`MBEDTLS_X509_CRT_PARSE_C`, but defined only if
`MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED`.

Issue #2422 tracks the use of
`MBEDTLS_KEY_EXCHANGE__WITH_CERT_ENABLED` instead of
`MBEDTLS_X509_CRT_PARSE_C` for code and fields
related to CRT-based ciphersuites.
2019-02-26 14:38:09 +00:00
Hanno Becker e68245750a Guard mbedtls_ssl_get_peer_cert() by new compile-time option 2019-02-26 14:38:09 +00:00
Hanno Becker b6c5eca2d5 Adapt mbedtls_ssl_parse_certificate() to removal of peer_cert field 2019-02-26 14:38:09 +00:00
Hanno Becker 13c327d500 Adapt ssl_clear_peer_cert() to removal of peer_cert field 2019-02-26 14:38:09 +00:00
Hanno Becker 6d1986e6f5 Adapt mbedtls_ssl_session_copy() to removal of peer_cert field 2019-02-26 14:38:09 +00:00
Hanno Becker 94cc26dfa6 Adapt session ticket implementation to removal of peer_cert field 2019-02-26 14:38:09 +00:00
Hanno Becker 2a831a4ba7 Adapt client auth detection in ssl_parse_certificate_verify()
The server expects a CertificateVerify message only if it has
previously received a Certificate from the client.

So far, this was detected by looking at the `peer_cert` field
in the current session. Preparing to remove the latter, this
commit changes this to instead determine the presence of a peer
certificate by checking the new `peer_cert_digest` pointer.
2019-02-26 14:38:09 +00:00
Hanno Becker a1ab9be367 Adapt server-side signature verification to use raw public key
We must dispatch between the peer's public key stored as part of
the peer's CRT in the current session structure (situation until
now, and future behaviour if MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is
enabled), and the sole public key stored in the handshake structure
(new, if MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is disabled).
2019-02-26 14:38:09 +00:00
Hanno Becker a6899bb89d Adapt client-side signature verification to use raw public key
We must dispatch between the peer's public key stored as part of
the peer's CRT in the current session structure (situation until
now, and future behaviour if MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is
enabled), and the sole public key stored in the handshake structure
(new, if MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is disabled).
2019-02-26 14:38:09 +00:00
Hanno Becker be7f50866d Adapt ssl_get_ecdh_params_from_cert() to use raw public key
We must dispatch between the peer's public key stored as part of
the peer's CRT in the current session structure (situation until
now, and future behaviour if MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is
enabled), and the sole public key stored in the handshake structure
(new, if MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is disabled).
2019-02-26 14:38:09 +00:00
Hanno Becker c7d7e29b46 Adapt ssl_write_encrypted_pms() to use raw public key
We must dispatch between the peer's public key stored as part of
the peer's CRT in the current session structure (situation until
now, and future behaviour if MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is
enabled), and the sole public key stored in the handshake structure
(new, if MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is disabled).
2019-02-26 14:38:09 +00:00
Hanno Becker a27475335a Make a copy of peer's raw public key after verifying its CRT chain
This commit modifies `mbedtls_ssl_parse_certificate()` to store a
copy of the peer's public key after parsing and verifying the peer's
CRT chain.

So far, this leads to heavy memory duplication: We have the CRT chain
in the I/O buffer, then parse (and, thereby, copy) it to a
`mbedtls_x509_crt` structure, and then make another copy of the
peer's public key, plus the overhead from the MPI and ECP structures.

This inefficiency will soon go away to a significant extend, because:
- Another PR adds functionality to parse CRTs without taking
  ownership of the input buffers. Applying this here will allow
  parsing and verifying the peer's chain without making an additional
  raw copy. The overhead reduces to the size of `mbedtls_x509_crt`,
  the public key, and the DN structures referenced in the CRT.
- Once copyless parsing is in place and the removal of the peer CRT
  is fully implemented, we can extract the public key bounds from
  the parsed certificate and then free the entire chain before
  parsing the public key again. This means that we never store
  the parsed public key twice at the same time.
2019-02-26 14:38:09 +00:00
Hanno Becker 75173121fe Add field for peer's raw public key to TLS handshake param structure
When removing the (session-local) copy of the peer's CRT chain, we must
keep a handshake-local copy of the peer's public key, as (naturally) every
key exchange will make use of that public key at some point to verify that
the peer actually owns the corresponding private key (e.g., verify signatures
from ServerKeyExchange or CertificateVerify, or encrypt a PMS in a RSA-based
exchange, or extract static (EC)DH parameters).

This commit adds a PK context field `peer_pubkey` to the handshake parameter
structure `mbedtls_handshake_params_init()` and adapts the init and free
functions accordingly. It does not yet make actual use of the new field.
2019-02-26 14:38:09 +00:00
Hanno Becker 494dd7a6b4 Add raw public key buffer bounds to mbedtls_x509_crt struct
This commit adds an ASN.1 buffer field `pk_raw` to `mbedtls_x509_crt`
which stores the bounds of the raw public key data within an X.509 CRT.

This will be useful in subsequent commits to extract the peer's public
key from its certificate chain.
2019-02-26 14:38:09 +00:00
Hanno Becker a887d1a5b6 Remove peer CRT from cache if !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE 2019-02-26 14:38:09 +00:00
Hanno Becker c966bd16be Remove peer CRT from tickets if !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE 2019-02-26 14:38:09 +00:00
Hanno Becker c5fcbb33c0 Add peer CRT digest to session tickets
This commit changes the format of session tickets to include
the digest of the peer's CRT if MBEDTLS_SSL_KEEP_PEER_CERTIFICATE
is disabled.

This commit does not yet remove the peer CRT itself.
2019-02-26 14:38:09 +00:00
Hanno Becker 3dad311ef0 Parse and verify peer CRT chain in local variable
`mbedtls_ssl_parse_certificate()` parses the peer's certificate chain
directly into the `peer_cert` field of the `mbedtls_ssl_session`
structure being established. To allow to optionally remove this field
from the session structure, this commit changes this to parse the peer's
chain into a local variable instead first, which can then either be freed
after CRT verification - in case the chain should not be stored - or
mapped to the `peer_cert` if it should be kept. For now, only the latter
is implemented.
2019-02-26 14:38:09 +00:00
Hanno Becker 177475a3aa Mitigate triple handshake attack by comparing digests only
This paves the way for the removal of the peer CRT chain from
`mbedtls_ssl_session`.
2019-02-26 14:38:09 +00:00
Hanno Becker 6bbd94c4eb Compute digest of peer's end-CRT in mbedtls_ssl_parse_certificate() 2019-02-26 14:38:09 +00:00
Hanno Becker 9198ad1101 Extend mbedtls_ssl_session by buffer holding peer CRT digest 2019-02-26 14:38:09 +00:00
Hanno Becker 8d84fd83ff Update version_features.c 2019-02-26 14:38:09 +00:00
Hanno Becker 8273df8383 Re-classify errors on missing peer CRT
mbedtls_ssl_parse_certificate() will fail if a ciphersuite requires
a certificate, but none is provided. While it is sensible to double-
check this, failure should be reported as an internal error and not
as an unexpected message.
2019-02-26 14:38:09 +00:00
Hanno Becker 0329f75a93 Increase robustness and documentation of ticket implementation 2019-02-26 14:38:09 +00:00
Hanno Becker aee8717877 Simplify session cache implementation via mbedtls_ssl_session_copy() 2019-02-26 14:38:09 +00:00
Hanno Becker 52055ae91f Give ssl_session_copy() external linkage
A subsequent commit will need this function in the session ticket
and session cache implementations. As the latter are server-side,
this commit also removes the MBEDTLS_SSL_CLI_C guard.

For now, the function is declared in ssl_internal.h and hence not
part of the public API.
2019-02-26 14:38:09 +00:00
Hanno Becker c7bd780e02 Allow passing any X.509 CRT chain to ssl_parse_certificate_chain()
This commit modifies the helper `ssl_parse_certificate_chain()` to
accep any target X.509 CRT chain instead of hardcoding it to
`session_negotiate->peer_cert`. This increases modularity and paves
the way towards removing `mbedtls_ssl_session::peer_cert`.
2019-02-26 14:38:09 +00:00
Hanno Becker 6863619a2f Introduce helper function for peer CRT chain verification 2019-02-26 14:38:09 +00:00
Hanno Becker fcd9e71cdf Don't progress TLS state machine on peer CRT chain parsing error 2019-02-26 14:38:09 +00:00
Hanno Becker 77adddc9e9 Make use of macro and helper detecting whether CertRequest allowed
This commit simplifies the client-side code for outgoing CertificateVerify
messages, and server-side code for outgoing CertificateRequest messages and
incoming CertificateVerify messages, through the use of the macro

   `MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED`

indicating whether a ciphersuite allowing CertificateRequest messages
is enabled in the configuration, as well as the helper function

   `mbedtls_ssl_ciphersuite_cert_req_allowed()`

indicating whether a particular ciphersuite allows CertificateRequest
messages.

These were already used in the client-side code to simplify the
parsing functions for CertificateRequest messages.
2019-02-26 14:38:09 +00:00
Hanno Becker 28f2fcd08d Add helper function to check whether a CRT msg is expected
This commit adds a helper function `ssl_parse_certificate_coordinate()`
which checks whether a `Certificate` message is expected from the peer.

The logic is the following:
- For ciphersuites which don't use server-side CRTs, no Certificate
  message is expected (neither for the server, nor the client).
- On the server, no client certificate is expected in the following cases:
  * The server server didn't request a Certificate, which is controlled
    by the `authmode` setting.
  * A RSA-PSK suite is used; this is the only suite using server CRTs
    but not allowing client-side authentication.
2019-02-26 14:38:09 +00:00
Hanno Becker 7177a88a36 Introduce helper function to determine whether suite uses server CRT
This commit introduces a static helper function

   `mbedtls_ssl_ciphersuite_uses_srv_cert()`

which determines whether a ciphersuite may make use of server-side CRTs.

This function is in turn uses in `mbedtls_ssl_parse_certificate()` to
skip certificate parsing for ciphersuites which don't involve CRTs.

Note: Ciphersuites not using server-side CRTs don't allow client-side CRTs
either, so it is safe to guard `mbedtls_ssl_{parse/write}_certificate()`
this way.

Note: Previously, the code uses a positive check over the suites

- MBEDTLS_KEY_EXCHANGE_PSK
- MBEDTLS_KEY_EXCHANGE_DHE_PSK
- MBEDTLS_KEY_EXCHANGE_ECDHE_PSK
- MBEDTLS_KEY_EXCHANGE_ECJPAKE,

while now, it uses a negative check over `mbedtls_ssl_ciphersuite_uses_srv_cert()`,
which checks for the suites

- MBEDTLS_KEY_EXCHANGE_RSA
- MBEDTLS_KEY_EXCHANGE_RSA_PSK
- MBEDTLS_KEY_EXCHANGE_DHE_RSA
- MBEDTLS_KEY_EXCHANGE_ECDH_RSA
- MBEDTLS_KEY_EXCHANGE_ECDHE_RSA
- MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA
- MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA

This is equivalent since, together, those are all ciphersuites.
Quoting ssl_ciphersuites.h:

```
typedef enum {
    MBEDTLS_KEY_EXCHANGE_NONE = 0,
    MBEDTLS_KEY_EXCHANGE_RSA,
    MBEDTLS_KEY_EXCHANGE_DHE_RSA,
    MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,
    MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,
    MBEDTLS_KEY_EXCHANGE_PSK,
    MBEDTLS_KEY_EXCHANGE_DHE_PSK,
    MBEDTLS_KEY_EXCHANGE_RSA_PSK,
    MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,
    MBEDTLS_KEY_EXCHANGE_ECDH_RSA,
    MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,
    MBEDTLS_KEY_EXCHANGE_ECJPAKE,
} mbedtls_key_exchange_type_t;
```
2019-02-26 14:38:09 +00:00
Hanno Becker 2148993900 Use helper macro to detect whether some ciphersuite uses CRTs 2019-02-26 14:38:09 +00:00
Hanno Becker 6bdfab2ccc Unify state machine update in mbedtls_ssl_parse_certificate()
The handler `mbedtls_ssl_parse_certificate()` for incoming `Certificate`
messages contains many branches updating the handshake state. For easier
reasoning about state evolution, this commit introduces a single code-path
updating the state machine at the end of `mbedtls_ssl_parse_certificate()`.
2019-02-26 14:38:09 +00:00
Hanno Becker 7a955a043e Clear peer's CRT chain outside before parsing new one
If an attempt for session resumption fails, the `session_negotiate` structure
might be partially filled, and in particular already contain a peer certificate
structure. This certificate structure needs to be freed before parsing the
certificate sent in the `Certificate` message.

This commit moves the code-path taking care of this from the helper
function `ssl_parse_certificate_chain()`, whose purpose should be parsing
only, to the top-level handler `mbedtls_ssl_parse_certificate()`.

The fact that we don't know the state of `ssl->session_negotiate` after
a failed attempt for session resumption is undesirable, and a separate
issue #2414 has been opened to improve on this.
2019-02-26 14:38:09 +00:00
Hanno Becker 4a55f638e2 Introduce helper to check for no-CRT notification from client
This commit introduces a server-side static helper function
`ssl_srv_check_client_no_crt_notification()`, which checks if
the message we received during the incoming certificate state
notifies the server of the lack of certificate on the client.

For SSLv3, such a notification comes as a specific alert,
while for all other TLS versions, it comes as a `Certificate`
handshake message with an empty CRT list.
2019-02-26 14:38:09 +00:00
Hanno Becker a028c5bbd8 Introduce CRT counter to CRT chain parsing function
So far, we've used the `peer_cert` pointer to detect whether
we're parsing the first CRT, but that will soon be removed
if `MBEDTLS_SSL_KEEP_PEER_CERTIFICATE` is unset.
2019-02-26 14:38:09 +00:00
Hanno Becker 1294a0b260 Introduce helper function to clear peer CRT from session structure
This commit introduces a helper function `ssl_clear_peer_cert()`
which frees all data related to the peer's certificate from an
`mbedtls_ssl_session` structure. Currently, this is the peer's
certificate itself, while eventually, it'll be its digest only.
2019-02-26 14:38:09 +00:00
Hanno Becker f852b1c035 Break overly long line in definition of mbedtls_ssl_get_session() 2019-02-26 14:38:09 +00:00
Hanno Becker 60848e6574 Don't reuse CRT from initial handshake during renegotiation
After mitigating the 'triple handshake attack' by checking that
the peer's end-CRT didn't change during renegotation, the current
code avoids re-parsing the CRT by moving the CRT-pointer from the
old session to the new one. While efficient, this will no longer
work once only the hash of the peer's CRT is stored beyond the
handshake.

This commit removes the code-path moving the old CRT, and instead
frees the entire peer CRT chain from the initial handshake as soon
as the 'triple handshake attack' protection has completed.
2019-02-26 14:38:09 +00:00
Janos Follath ffbd7e8ff3 Improve mbedtls_ecp_point_read_binary tests
Renamed the tests because they are explicitly testing Curve25519 and
nothing else. Improved test coverage, test documentation and extended
in-code documentation with a specific reference to the standard as well.
2019-02-25 11:49:54 +00:00
Janos Follath 7caf8e452f Add Montgomery points to ecp_point_write_binary
The library is able to perform computations and cryptographic schemes on
curves with x coordinate ladder representation. Here we add the
capability to export such points.
2019-02-22 15:42:18 +00:00
Janos Follath ab0f71a22a ECDH: Add test vectors for Curve25519
The test vectors added are published in RFC 7748.
2019-02-22 15:42:03 +00:00
Janos Follath e344d0f6fc Add little endian export to Bignum
The function `mbedtls_mpi_write_binary()` writes big endian byte order,
but we need to be able to write little endian in some caseses. (For
example when handling keys corresponding to Montgomery curves.)

Used `echo xx | tac -rs ..` to transform the test data to little endian.
2019-02-22 15:41:31 +00:00
Janos Follath 171a7efd02 Add mbedtls_ecp_read_key
The private keys used in ECDH differ in the case of Weierstrass and
Montgomery curves. They have different constraints, the former is based
on big endian, the latter little endian byte order. The fundamental
approach is different too:
- Weierstrass keys have to be in the right interval, otherwise they are
  rejected.
- Any byte array of the right size is a valid Montgomery key and it
  needs to be masked before interpreting it as a number.

Historically it was sufficient to use mbedtls_mpi_read_binary() to read
private keys, but as a preparation to improve support for Montgomery
curves we add mbedtls_ecp_read_key() to enable uniform treatment of EC
keys.

For the masking the `mbedtls_mpi_set_bit()` function is used. This is
suboptimal but seems to provide the best trade-off at this time.
Alternatives considered:
- Making a copy of the input buffer (less efficient)
- removing the `const` constraint from the input buffer (breaks the api
and makes it less user friendly)
- applying the mask directly to the limbs (violates the api between the
modules and creates and unwanted dependency)
2019-02-22 15:39:03 +00:00
Janos Follath 59b813c7be Add Montgomery points to ecp_point_read_binary
The library is able to perform computations and cryptographic schemes on
curves with x coordinate ladder representation. Here we add the
capability to import such points.
2019-02-22 15:38:46 +00:00
Janos Follath a778a94b7d Add little endian import to Bignum
The function `mbedtls_mpi_read_binary()` expects big endian byte order,
but we need to be able to read from little endian in some caseses. (For
example when handling keys corresponding to Montgomery curves.)

Used `echo xx | tac -rs .. | tr [a-z] [A-Z]` to transform the test data
to little endian and `echo "ibase=16;xx" | bc` to convert to decimal.
2019-02-22 15:38:32 +00:00
Jaeden Amero 86016a03a1 Merge remote-tracking branch 'origin/pr/2338' into development 2019-02-22 12:55:30 +00:00
Gilles Peskine 3081629de4 Fix mbedtls_ecdh_get_params with new ECDH context
The new check for matching groups in mbedtls_ecdh_get_params only worked
with legacy ECDH contexts. Make it work with the new context format.
2019-02-22 13:04:23 +01:00
Gilles Peskine 43f564f29d Define MBEDTLS_ECDH_LEGACY_CONTEXT in config.h
Define MBEDTLS_ECDH_LEGACY_CONTEXT in config.h instead of hard-coding
this in ecdh.h so that its absence can be tested. Document it as
experimental so that we reserve the right to change it in the future.
2019-02-22 13:04:20 +01:00
Jaeden Amero 461bd3dcca Merge remote-tracking branch 'origin/pr/2454' into development 2019-02-22 10:32:44 +00:00
Jaeden Amero 9f47f82218 Merge remote-tracking branch 'origin/pr/2391' into development 2019-02-22 10:32:44 +00:00
Jaeden Amero 8963b0311c Merge remote-tracking branch 'origin/pr/2411' into development 2019-02-22 10:32:44 +00:00
Gilles Peskine 0b1b71d712 Fix ecdh_get_params with mismatching group
If mbedtls_ecdh_get_params is called with keys belonging to
different groups, make it return an error the second time, rather than
silently interpret the first key as being on the second curve.

This makes the non-regression test added by the previous commit pass.
2019-02-22 10:21:46 +01:00
Jaeden Amero 3497323f79 Initialize PSA Crypto operation contexts
It is now required to initialize PSA Crypto operation contexts before
calling psa_*_setup(). Otherwise, one gets a PSA_ERROR_BAD_STATE error.
2019-02-20 10:58:55 +00:00
Hanno Becker 26d02e1327 Add more missing parentheses around macro parameters 2019-02-19 17:59:57 +00:00
Hanno Becker 818bac55ef Add further missing brackets around macro parameters 2019-02-19 17:59:57 +00:00
Hanno Becker 1eeca41472 Improve macro hygiene
This commit improves hygiene and formatting of macro definitions
throughout the library. Specifically:
- It adds brackets around parameters to avoid unintended
  interpretation of arguments, e.g. due to operator precedence.
- It adds uses of the `do { ... } while( 0 )` idiom for macros that
  can be used as commands.
2019-02-19 17:59:00 +00:00
Hanno Becker 0a94a64bbd Add debugging output to confirm that PSA was used for ECDHE 2019-02-18 16:42:02 +00:00
Hanno Becker c14a3bb5a6 Make variable in ssl_write_client_key_exchange() more descriptive 2019-02-18 16:42:02 +00:00
Hanno Becker 4a63ed421c Implement ClientKeyExchange writing in PSA-based ECDHE suites
- Populate the ECDH private key slot with a fresh private EC key
  designated for the correct algorithm.
- Export the public part of the ECDH private key from PSA and
  reformat it to suite the format of the ClientKeyExchange message.
- Perform the PSA-based ECDH key agreement and store the result
  as the premaster secret for the connection.
2019-02-18 16:42:01 +00:00
Hanno Becker bb89e2727f Implement ServerKeyExchange parsing for PSA-based ECDHE suites
- Reformat the server's ECDH public key to make it suitable
  for the PSA key agreement API. Currently, the key agreement
  API needs a full SubjectPublicKeyInfo structure, while the
  TLS ServerKeyExchange message only contains a ECPoint structure.
2019-02-18 16:42:01 +00:00
k-stachowiak 28cb6fbd47 Unbump version to 0.0.0 2019-02-18 12:01:03 +01:00
Ron Eldor 3467dcf452 Use certificates from data_files and refer them
Use the server certificate from `data_files` folder, for formality,
and refer to the source, for easier reproduction.
2019-02-12 15:30:26 +02:00
Jaeden Amero 6f7703df3a rsa: Enable use of zero-length null output
Enable handling of zero-length null output in PKCS1 v1.5 decryption.
Prevent undefined behavior by avoiding a memcpy() to zero-length null
output buffers.
2019-02-11 03:39:51 -05:00
Gilles Peskine 004f87b98d RSA encryption: accept input=NULL if ilen=0
In mbedtls_rsa_rsaes_oaep_encrypt and
mbedtls_rsa_rsaes_pkcs1_v15_encrypt, if the input length is 0 (which
is unusual and mostly useless, but permitted) then it is fine for the
input pointer to be NULL. Don't return an error in this case.

When `input` is NULL, `memcpy( p, input, ilen )` has undefined behavior
even if `ilen` is zero. So skip the `memcpy` call in this case.
Likewise, in `mbedtls_rsa_rsaes_oaep_decrypt`, skip the `memcpy` call if
`*olen` is zero.
2019-02-11 03:39:21 -05:00
Hanno Becker 46f34d0ac0 Fix style issue and wording 2019-02-08 14:26:41 +00:00
Hanno Becker c1e18bdf06 Fix memory leak 2019-02-08 14:26:41 +00:00
Hanno Becker e2734e2be4 Improve formatting of ssl_parse_certificate_chain() 2019-02-08 14:26:41 +00:00
Hanno Becker 84879e32ef Add compile-time guards around helper routine 2019-02-08 14:26:41 +00:00
Hanno Becker def9bdc152 Don't store the peer CRT chain twice during renegotiation
Context: During a handshake, the SSL/TLS handshake logic constructs
an instance of ::mbedtls_ssl_session representing the SSL session
being established. This structure contains information such as the
session's master secret, the peer certificate, or the session ticket
issues by the server (if applicable).
During a renegotiation, the new session is constructed aside the existing
one and destroys and replaces the latter only when the renegotiation is
complete. While conceptually clear, this means that during the renegotiation,
large pieces of information such as the peer's CRT or the session ticket
exist twice in memory, even though the original versions are removed
eventually.

This commit removes the simultaneous presence of two peer CRT chains
in memory during renegotiation, in the following way:
- Unlike in the case of SessionTickets handled in the previous commit,
  we cannot simply free the peer's CRT chain from the previous handshake
  before parsing the new one, as we need to verify that the peer's end-CRT
  hasn't changed to mitigate the 'Triple Handshake Attack'.
- Instead, we perform a binary comparison of the original peer end-CRT
  with the one presented during renegotiation, and if it succeeds, we
  avoid re-parsing CRT by moving the corresponding CRT pointer from the
  old to the new session structure.
- The remaining CRTs in the peer's chain are not affected by the triple
  handshake attack protection, and for them we may employ the canonical
  approach of freeing them before parsing the remainder of the new chain.

Note that this commit intends to not change any observable behavior
of the stack. In particular:
- The peer's CRT chain is still verified during renegotiation.
- The tail of the peer's CRT chain may change during renegotiation.
2019-02-08 14:26:41 +00:00
Hanno Becker b2964cbe14 SSL/TLS client: Remove old session ticket on renegotiation
Context: During a handshake, the SSL/TLS handshake logic constructs
an instance of ::mbedtls_ssl_session representing the SSL session
being established. This structure contains information such as the
session's master secret, the peer certificate, or the session ticket
issues by the server (if applicable).

During a renegotiation, the new session is constructed aside the existing
one and destroys and replaces the latter only when the renegotiation is
complete. While conceptually clear, this means that during the renegotiation,
large pieces of information such as the peer's CRT or the session ticket
exist twice in memory, even though the original versions are removed
eventually.

This commit starts removing this memory inefficiency by freeing the old
session's SessionTicket before the one for the new session is allocated.
2019-02-08 14:26:41 +00:00
Hanno Becker 1a65dcd44f Add a new X.509 API call for copy-less parsing of CRTs
Context:
The existing API `mbedtls_x509_parse_crt_der()` for parsing DER
encoded X.509 CRTs unconditionally makes creates a copy of the
input buffer in RAM. While this comes at the benefit of easy use,
-- specifically: allowing the user to free or re-use the input
buffer right after the call -- it creates a significant memory
overhead, as the CRT is duplicated in memory (at least temporarily).
This might not be tolerable a resource constrained device.

As a remedy, this commit adds a new X.509 API call

   `mbedtls_x509_parse_crt_der_nocopy()`

which has the same signature as `mbedtls_x509_parse_crt_der()`
and almost the same semantics, with one difference: The input
buffer must persist and be unmodified for the lifetime of the
established instance of `mbedtls_x509_crt`, that is, until
`mbedtls_x509_crt_free()` is called.
2019-02-08 14:24:58 +00:00
Jaeden Amero fb236739da Revert "Forbid passing NULL input buffers to RSA encryption routines"
Resolve incompatibilties in the RSA module where changes made for
parameter validation prevent Mbed Crypto from working. Mbed Crypto
depends on being able to pass zero-length buffers that are NULL to RSA
encryption functions.

This reverts commit 2f660d047d.
2019-02-08 08:43:31 -05:00
Andrzej Kurek 3c2b15d31e Update version_features file 2019-02-08 02:38:45 -05:00
Andrzej Kurek 8a2e97c2df Merge development-psa commit 80b5662 into development-psa-merged branch
Adjust crypto submodule version to use new, forked crypto version accordingly.
2019-02-05 06:02:51 -05:00
Andrzej Kurek d142856846 cipher: remove unnecessary precondition
Already checked by parameter validation macros
2019-02-05 05:11:03 -05:00
Andrzej Kurek efed323698 pk: restructure precondition check 2019-02-05 05:09:05 -05:00
Jaeden Amero 80b566267f Merge remote-tracking branch 'origin/pr/2386' into development-psa 2019-02-04 16:42:23 +00:00
Jaeden Amero d18b264eaf Merge remote-tracking branch 'origin/pr/2382' into development-psa 2019-02-04 16:41:46 +00:00
Jaeden Amero 65408c5f92 Merge remote-tracking branch 'origin/pr/2355' into development-psa 2019-02-04 16:41:12 +00:00
Hanno Becker 23cfea01e8 Improve documentation of mbedtls_mpi_write_string() 2019-02-04 09:45:07 +00:00
Hanno Becker c983c81a23 Fix 1-byte buffer overflow in mbedtls_mpi_write_string()
This can only occur for negative numbers. Fixes #2404.
2019-02-01 16:41:30 +00:00
Andrzej Kurek de5a007316 Merge development commit f352f7 into development-psa 2019-02-01 07:03:03 -05:00
Hanno Becker 65935d90c9 Add missing include to library/pkwrite.c 2019-02-01 11:55:03 +00:00
Hanno Becker 493c171a1c Adapt mbedtls_pk_write_pubkey_der() to the new PSA public key format
Context: There are two public key writing functions in Mbed TLS. First,
mbedtls_pk_write_pubkey(), which exports a public key in the form of a
SubjectPublicKey structure containing the raw keying material
(for example, EC point coordinates for an EC public key, without
reference to the underlying curve). Secondly, mbedtls_pk_write_pubkey_der(),
which exports a public key in the form of a SubjectPublicKeyInfo structure,
wrapping the SubjectPublicKey structure by additional information
identifying the type of public key (and for ECC, e.g., it'd also contain
the ECC group identifier). The implementation of mbedtls_pk_write_pubkey_der()
calls mbedtls_pk_write_pubkey() first and then adds the corresponding
algorithm identifier wrapper.

Both of these functions need to be provided for PSA-based opaque PK contexts,
based on PSA's public key export function.

Previously, PSA used the SubjectPublicKeyInfo structure as its export format,
so mbedtls_pk_write_pubkey_der() could be easily implemented, while
mbedtls_pk_write_pubkey() would need to trim the output of the PSA export.

The previous implementation of mbedtls_pk_write_pubkey() is not quite right
because it calls PSA export doesn't do any trimming, hence exporting the large
SubjectPublicKeyInfo structure instead of the small SubjectPublicKey.
mbedtls_pk_write_pubkey_der(), in turn, immediately returns after calling
mbedtls_pk_write_pubkey(), hence also returning the SubjectPublicKeyInfo
structure, which is correct.

By now, the PSA public key export format has changed to the smaller
SubjectPublicKey structure. This means that, now, mbedtls_pk_write_pubkey()
can be implemented by just calling the PSA export, and that
mbedtls_pk_write_pubkey_der() needs to add the algorithm information around
it, just as in the other types of PK contexts. While not correct for the
old format, the existing code for mbedtls_pk_write_pubkey() is therefore
correct for the new PSA public key format, and needs no change apart from
the missing pointer shift in the last commit.

The implementation of mbedtls_pk_write_pubkey_der() needs a special code
path for PSA-based opaque PK contexts, as the PK context only contains
the PSA key handle, and the PSA API needs to be used to extract the
underlying EC curve to be able to write the AlgorithmParameter structure
that's part of the SubjectPublicKeyInfo structure.

That's what this commit does, (hopefully) making both
mbedtls_pk_write_pubkey() and mbedtls_pk_write_pubkey_der() export
the correctly formatted public key based on the new PSA public key format.
2019-02-01 10:25:25 +00:00
Hanno Becker 4fb8db23b9 Update pointer in PSA-based mbedtls_pk_write_pubkey() 2019-02-01 09:57:20 +00:00
Andrzej Kurek f093a3dc61 Use ecdh_setup instead of ecp_group_load
Align files with development to ensure the same state of repositories.
2019-02-01 02:50:36 -05:00
Peter Kolbus e6bcad3f79 Fix DEADCODE in mbedtls_mpi_exp_mod()
In mbedtls_mpi_exp_mod(), the limit check on wsize is never true when
MBEDTLS_MPI_WINDOW_SIZE is at least 6. Wrap in a preprocessor guard
to remove the dead code and resolve a Coverity finding from the
DEADCODE checker.

Change-Id: Ice7739031a9e8249283a04de11150565b613ae89
2019-01-31 19:37:51 -06:00
Andrzej Kurek c470b6b021 Merge development commit 8e76332 into development-psa
Additional changes to temporarily enable running tests:
ssl_srv.c and test_suite_ecdh use mbedtls_ecp_group_load instead of
mbedtls_ecdh_setup
test_suite_ctr_drbg uses mbedtls_ctr_drbg_update instead of 
mbedtls_ctr_drbg_update_ret
2019-01-31 08:20:20 -05:00
Jaeden Amero f352f75f6b Merge remote-tracking branch 'origin/pr/2332' into development 2019-01-30 15:53:00 +00:00
Jaeden Amero 91af329a55 Merge remote-tracking branch 'origin/pr/2214' into development 2019-01-30 15:08:25 +00:00
Jaeden Amero 14eca249f1 Merge remote-tracking branch 'origin/pr/2213' into development 2019-01-30 15:01:20 +00:00
Jaeden Amero dac9f45e5a Merge remote-tracking branch 'origin/pr/1551' into development 2019-01-30 13:24:55 +00:00
Jaeden Amero e6e2686cf8 Merge remote-tracking branch 'origin/pr/2055' into development
Resolve conflicts in ctr_drbg.c where zeroization had been added upon
exit.
2019-01-30 13:23:03 +00:00
Jaeden Amero 730ecdf3b1 Merge remote-tracking branch 'origin/pr/2371' into development 2019-01-30 13:15:40 +00:00
Andrzej Kurek 2ad229725c ssl_tls: add psa_hash_abort when reseting checksum 2019-01-30 03:32:12 -05:00
Andrzej Kurek 972fba51ed ssl_tls: rename sha_512_psa to sha_384_psa 2019-01-30 03:29:12 -05:00
Andrzej Kurek eb342241a5 ssl_tls: use PSA to compute running handshake hash for TLS 1.2 2019-01-29 09:14:33 -05:00
Hanno Becker ccf574e030 Fix outdated comment in ecdsa_verify_wrap() 2019-01-29 08:26:15 +00:00
Andrzej Kurek 2d4faa6afa ssl_tls: remove redundant status check 2019-01-29 03:14:15 -05:00
Andrzej Kurek 2f76075b78 ssl_tls: adjust to the new key policy initialization and key allocation 2019-01-28 08:08:15 -05:00
Andrzej Kurek ac5dc3423a Fix key allocation for tls_prf_generic 2019-01-28 07:49:56 -05:00
Andrzej Kurek 3317126819 ssl_tls: add missing return brackets 2019-01-28 07:49:56 -05:00
Andrzej Kurek 70737ca827 ssl_tls: add key destruction upon generator failure 2019-01-28 07:49:56 -05:00
Andrzej Kurek c929a82a6b Implement tls_prf_generic using the PSA API 2019-01-28 07:49:56 -05:00
Andrzej Kurek 5615dabeef ssl_tls: remove line breaks from a debug message 2019-01-28 07:04:19 -05:00
Andrzej Kurek e85414edd0 ssl-opt: add a check for PSA computation of digest of ServerKeyExchange 2019-01-28 07:04:19 -05:00
Andrzej Kurek 814feffd15 Whitespace, logging and documentation fixes
Introduce a psa_status_t status to handle return values.
Add a debug message with API usage description.
2019-01-28 07:04:19 -05:00
Andrzej Kurek d6db9be598 Adapt mbedtls_ssl_get_key_exchange_md_tls1_2 to PSA hashing 2019-01-28 07:04:19 -05:00
Hanno Becker a98511164f Adapt ecdsa_verify_wrap() to new EC public key format
Previously, PSA used SubjectPublicKeyInfo structures to serialize EC public keys.
This has recently been changed to using ECPoint structures instead, but the wrapper
making PSA ECDSA verification available through Mbed TLS' PK API hasn't yet been
adapted accordingly - which is what this commit does.

Luckily, Mbed TLS' PK API offers two functions mbedtls_pk_write_pubkey()
and mbedtls_pk_write_pubkey_der(), the latter exporting a SubjectPublicKeyInfo
structure and the former exporting an ECPoint structure in case of EC public
keys. For the adaptation of the ECDSA wrapper ecdsa_verify_wrap() it is therefore
sufficient to use mbedtls_pk_write_pubkey() instead of mbedtls_pk_write_pubkey_der().
2019-01-28 11:45:19 +00:00
Manuel Pégourié-Gonnard 430a66f19a Fix backwards config dependency on oid.c
The file oid.c had conditional inclusion of functions based on a config.h
define that belongs to X.509, which is backwards. For now, just include those
functions unconditionally and rely on the linker to garbage-collect them if
not used.

In the longer term X.509-specific functions are likely to be removed from
libmbedcrypto, but at this step the goal is to preserve the API (and even ABI)
of libmbedcrypto for as long as possible while separating the source trees of
Mbed Crypto and Mbed TLS.
2019-01-28 10:31:39 +01:00
Manuel Pégourié-Gonnard c49ada41d4 Fix backwards include of x509.h in oid.h
As agreed during the workshop, temporarily move definitions to oid.h even if
they might not semantically belong here, as a short-term measure allowing to
build libmbecrypto on its own (without X.509 files present in the source tree)
but still provide all the things Mbed TLS currently expects, and more
specifically preserve the API and ABI exposed by libmbedtls.
2019-01-28 09:26:19 +01:00
Hanno Becker f99c2ec9d7 PSA: Adapt pk.c, pk_wrap.c, cipher.c to new key policy init API 2019-01-25 14:36:07 +00:00
Hanno Becker e34f636f8d PSA: Adapt cipher.c, pk.c, pk_wrap.c to new key slot allocation API 2019-01-25 14:31:06 +00:00
Antonin Décimo 36e89b5b71 Fix #2370, minor typos and spelling mistakes 2019-01-24 10:37:40 +01:00
Simon Butcher 8e763329ad Merge remote-tracking branch 'public/pr/2040' into development 2019-01-23 10:28:25 +01:00
Simon Butcher d4e327c4ff Merge remote-tracking branch 'public/pr/2345' into development 2019-01-23 10:14:52 +01:00
ILUXONCHIK acfee8eb04 refactor CA and SRV certificates into separate blocks 2019-01-17 00:35:40 +02:00
ILUXONCHIK 2bd7f99685 refactor SHA-1 certificate defintions and assignment
As per refactoring suggestion that I made in #1520.
2019-01-17 00:32:36 +02:00
ILUXONCHIK d94b3e7368 refactor server SHA-1 certificate definition into a new block 2019-01-17 00:29:18 +02:00
ILUXONCHIK 2f27790565 define TEST_SRV_CRT_RSA_SOME in similar logic to TEST_CA_CRT_RSA_SOME 2019-01-17 00:25:26 +02:00
ILUXONCHIK 914df7937d server SHA-256 certificate now follows the same logic as CA SHA-256 certificate 2019-01-17 00:25:26 +02:00
Andrzej Kurek c0a1be08a0 Fix indentation of documentation 2019-01-15 03:33:35 -05:00
Andrzej Kurek 62594a8b12 pk_wrap: pass curve size instead of a larger size of the exported key
Whitespace fixes
2019-01-14 05:14:18 -05:00
Andrzej Kurek 93a38a3101 pk: wrap curve_id before passing it to PSA
Add a helper function in PSA utils
2019-01-14 05:09:46 -05:00
Andrzej Kurek a62a58ece5 cipher: fixed key ownership scope
Indicate key ownership earlier, so that it gets destroyed on faulty policy setting.
2019-01-14 05:01:28 -05:00
Hanno Becker a9375b35c0 Avoid MSVC compiler warning
MSVC warns about use of unary `-` operator on unsigned integers.
2019-01-10 09:21:24 +00:00
Hanno Becker 783f9c3514 Fix signed-to-unsigned integer conversion warning in X.509 module
Fixes #2212.
2019-01-10 09:21:24 +00:00
Ron Eldor adb5234aa9 Return error code of underlying function.
Return the error code if failed, instead of returning value `1`.
If not failed, return the call of the underlying function,
in `mbedtls_ecdsa_genkey()`.
2019-01-10 10:47:42 +02:00
Andrzej Kurek ee3c435063 Whitespace fix for ccm, gcm, and pkcs5
Fix whitespace mistakes  in ccm, gcm, and pkcs5.
2019-01-10 03:17:34 -05:00
Michał Janiszewski c79e92b802 Rename remaining test data 2019-01-10 03:14:00 -05:00
Michał Janiszewski 9aeea93cc3 Rename globals to avoid shadowing by various function arguments
It's easier and more telling to rename the globals used only for test,
rather than rename all the shadowing function arguments.
2019-01-10 03:14:00 -05:00