Commit graph

4266 commits

Author SHA1 Message Date
Darryl Green
940d72c3e8 psa: Refactor psa_import_key()
Create a new function psa_import_key_into_slot() from psa_import_key().
This is common functionality that will be used both when importing a
key and loading a key from persistent storage.
2018-11-20 15:21:22 +00:00
Moran Peker
96ebf9efcf psa: Add magic header to storage backend
Add a magic header to the storage format used with files. The
header is used as an initial check that the data is what we expect,
rather than garbage data.
2018-11-20 15:21:22 +00:00
Darryl Green
db2b8db715 psa: Add storage implementation for files
Add new functions, psa_load_persistent_key(),
psa_free_persistent_key_data(), and psa_save_persistent_key(), for
managing persistent keys. These functions load to or save from our
internal representation of key slots. Serialization is a concern of the
storage backend implementation and doesn't abstraction-leak into the
lifetime management code.

An initial implementation for files is provided. Additional storage
backends can implement this interface for other storage types.
2018-11-20 15:21:22 +00:00
Jaeden Amero
818eab2e76 Merge tag 'mbedtls-2.14.0' into feature-psa
Mbed TLS version 2.14.0

Resolved conflicts in include/mbedtls/config.h,
tests/scripts/check-files.py, and yotta/create-module.sh by removing yotta.

Resolved conflicts in tests/.jenkins/Jenkinsfile by continuing to run
mbedtls-psa job.
2018-11-19 19:25:56 +00:00
Simon Butcher
c1b9892177 Update library version number to 2.14.0 2018-11-19 18:31:40 +00:00
Hanno Becker
1aaedc03d4 Add implementation of TLS-1.2 PSK-to-MS key derivation 2018-11-19 11:24:25 +00:00
Gilles Peskine
93f8500e2e Fix unused variables warning if MBEDTLS_ECDH_C is off
depends-pkalgs.pl passes.
2018-11-16 16:43:31 +01:00
Gilles Peskine
346797d7b9 Add missing cleanup on failure in psa_key_agreement
If psa_key_derivation_internal() fails, it's up to the caller to clean
up. Do this, and add a note at the top of
psa_key_derivation_internal() and its auxiliary functions.

There is no non-regression test because at the moment the only way to
trigger an error is a borderline low-memory condition and we don't
have the means to trigger this.
2018-11-16 16:09:27 +01:00
Gilles Peskine
a05219c70b Add some missing compilation guards
Add missing checks for defined(MBEDTLS_MD_C) around types and
functions that require it (HMAC, HKDF, TLS12_PRF).

Add missing checks for defined(MBEDTLS_ECDSA_DETERMINISTIC) around
code that calls mbedtls_ecdsa_sign_det().

Add missing checks for defined(MBEDTLS_ECDH_C) around ECDH-specific
functions.
2018-11-16 16:09:24 +01:00
Hanno Becker
353e45361d Don't call memcpy() with 0-length arguments
The standard prohibits calling memcpy() with NULL pointer
arguments, even if the size argument is 0.

The TLS-1.2 PRF generator setup function previously called
memcpy() with the label and salt as the source, even if
they were of length 0, as exercised by the derive_key_policy
test case in the PSA crypto test suite.

This commit adds guards around the memcpy() calls so that they
are only executed of salt or label have positive length, respectively.
2018-11-16 11:24:59 +00:00
Hanno Becker
3b339e2342 Simplify psa_generator_tls12_prf_generate_next_block() 2018-11-16 11:24:59 +00:00
Hanno Becker
580fba1431 Dynamically allocate A(i) + seed buffer for TLS-1.2 PRF 2018-11-16 11:24:59 +00:00
Hanno Becker
c8a41d71cb Add implementation of TLS-1.2 PRF 2018-11-16 11:24:55 +00:00
Gilles Peskine
b408661be9 ECDH: check that the keys are on the same curve
In psa_key_agreement_ecdh, check that the public key is on the same
curve as the private key. The underlying mbedtls API doesn't check.

If the curves don't match, psa_key_agreement_ecdh is practically
guaranteed to return INVALID_ARGUMENT anyway, because way the code is
written, the public point is interpreted on the curve of the private
point, and it is rejected because the point is not on the curve. This
is why the test case "PSA key agreement setup: ECDH, raw: public key
on different curve" passed even before adding this check.
2018-11-14 21:17:16 +01:00
Gilles Peskine
88714d78b8 Allow ECDH-only public key in ECDH
In ECDH key agreement, allow a public key with the OID id-ECDH, not
just a public key with the OID id-ecPublicKey.

Public keys with the OID id-ECDH are not permitted by psa_import_key,
at least for now. There would be no way to use the key for a key
agreement operation anyway in the current API.
2018-11-14 21:17:16 +01:00
Gilles Peskine
211a436f2e Document that key agreement produces a maximum-capacity generator 2018-11-14 21:15:37 +01:00
Gilles Peskine
b7ecdf0509 Implement ECDH 2018-11-14 21:15:37 +01:00
Gilles Peskine
01d718cee8 New API function: psa_key_agreement
Set up a generator from a key agreement.
2018-11-14 21:15:37 +01:00
Gilles Peskine
8feb3a886d Support key derivation with non-predefined capacity
psa_key_derivation requires the caller to specify a maximum capacity.
This commit adds a special value that indicates that the maximum
capacity should be the maximum supported by the algorithm. This is
currently meant only for selection algorithms used on the shared
secret produced by a key agreement.
2018-11-14 21:15:37 +01:00
Gilles Peskine
751d965dfc Implement PSA_ALG_SELECT_RAW 2018-11-14 21:15:37 +01:00
Gilles Peskine
cce18aec4c Split off psa_key_derivation_internal
Refactor psa_key_derivation to prepare for key agreement algorithms
which need to plug into key derivation after argument validation.
2018-11-14 21:15:37 +01:00
Gilles Peskine
e19b7d54d0 Revert "New function mbedtls_rsa_get_bitlen"
This reverts commit 1d26709dbd.
2018-11-12 19:14:34 +01:00
Gilles Peskine
86a440b638 Reject non-byte-aligned RSA keys
On key import and key generation, for RSA, reject key sizes that are
not a multiple of 8. Such keys are not well-supported in Mbed TLS and
are hardly ever used in practice.

The previous commit removed support for non-byte-aligned keys at the
PSA level. This commit actively rejects such keys and adds
corresponding tests (test keys generated with "openssl genrsa").
2018-11-12 19:14:18 +01:00
Gilles Peskine
aac64a2839 Remove support for non-byte-aligned RSA keys
Remove the need for an extra function mbedtls_rsa_get_bitlen. Use
mbedtls_rsa_get_len, which is only correct for keys whose size is a
multiple of 8. Key sizes that aren't a multiple of 8 are extremely
rarely used, so in practice this is not a problematic limitation.
2018-11-12 18:37:42 +01:00
Simon Butcher
de13963d66 Merge remote-tracking branch 'restricted/pr/520' into development-restricted-proposed 2018-11-12 14:30:16 +00:00
Simon Butcher
cdd1a6c872 Merge remote-tracking branch 'restricted/pr/510' into development-restricted-proposed 2018-11-12 14:29:14 +00:00
Simon Butcher
e51d4b336b Merge remote-tracking branch 'public/pr/2054' into development-proposed 2018-11-09 19:57:53 +00:00
Ron Eldor
9924bdc792 Deprecate hardware acceleration errors
Deprecate the module-specific XXX_HW_ACCEL_FAILED and
XXX_FEATURE_UNAVAILABLE errors, as alternative implementations should now
return `MBEDTLS_ERR_PLATFORM_HW_FAILED` and
`MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED`.
2018-11-09 15:01:07 +00:00
Ron Eldor
bcca58c6cd Add common feature unavailable error
Add a common error for the feature unavailable, in the
platform module.
2018-11-09 13:57:37 +00:00
Simon Butcher
d83448b736 Merge remote-tracking branch 'public/pr/2052' into development-restricted-proposed 2018-11-07 12:59:14 +00:00
Simon Butcher
53b45ec881 Merge remote-tracking branch 'public/pr/2079' into development-restricted-proposed 2018-11-07 12:58:44 +00:00
Simon Butcher
bbc31b4827 Merge remote-tracking branch 'public/pr/2085' into development-restricted-proposed 2018-11-07 12:57:38 +00:00
Simon Butcher
93a9b497e0 Merge remote-tracking branch 'public/pr/2077' into development-restricted-proposed 2018-11-07 12:57:24 +00:00
Simon Butcher
241823aab8 Merge remote-tracking branch 'public/pr/1641' into development-restricted-proposed 2018-11-07 12:55:47 +00:00
Simon Butcher
42ab4ae033 Merge remote-tracking branch 'public/pr/2167' into development-restricted-proposed 2018-11-07 12:54:45 +00:00
Simon Butcher
51b6abbbf2 Merge remote-tracking branch 'public/pr/2165' into development-proposed 2018-11-06 22:55:14 +00:00
Ron Eldor
2981d8f161 Change to positive flow for all cases
Use the `rs_ctx` only when `MBEDTLS_ECP_RESTARTABLE` is defined.
2018-11-05 18:08:46 +02:00
Ron Eldor
93ace0199b Revert positive flow check
Revert changes for checking whether `MBEDTLS_ECP_RESTARTABLE`
is defined, since it broke the CI. The context is used whether the
restartable feature is defined or not.
2018-11-05 17:50:07 +02:00
Ron Eldor
b430d9f262 Change to positive checks
1. Checge to check for `MBEDTLS_ECP_RESTARTABLE` for all definitions
of `rs_ctx`.
2. Remove checks for `_ALT` when using `rs_ctx` as they cannot coexist
with the Restartable configuration.
2018-11-05 17:18:29 +02:00
Ron Eldor
19779c4739 Some style and documentation fixes
1. Change description of of hte `MBEDTLS_ECP_RESTARTABLE`
in the configuration file.
2. Change check for compilation of `rs_ctx` to positive flow.
2018-11-05 16:58:13 +02:00
Ron Eldor
5ed8c1eded Avoid using restartable and alternative ECP imp.
1. Add a check that MBEDTLS_ECP_RESTARTABLE is not defined
   along any EC* alternative implementation.
2. Add a closing comment foran `#endif`.
2018-11-05 14:04:26 +02:00
Hanno Becker
b75ffb5061 Don't perform binary comparison of CRL issuer and CA subject
Previously, when checking whether a CRT was revoked through
one of the configured CRLs, the library would only consider
those CRLs whose `issuer` field binary-matches the `subject`
field of the CA that has issued the CRT in question. If those
fields were not binary equivalent, the corresponding CRL was
discarded.

This is not in line with RFC 5280, which demands that the
comparison should be format- and case-insensitive. For example:

- If the same string is once encoded as a `PrintableString` and
  another time as a `UTF8String`, they should compare equal.
- If two strings differ only in their choice of upper and lower case
  letters, they should compare equal.

This commit fixes this by using the dedicated x509_name_cmp()
function to compare the CRL issuer with the CA subject.

Fixes #1784.
2018-11-05 11:54:06 +00:00
Hanno Becker
1f8527f1cf Move static x509_name_cmp() in library/x509_crt.c
A subsequent change will need this function earlier
within the file.
2018-11-05 11:54:06 +00:00
Simon Butcher
06f88e9c42 Merge remote-tracking branch 'public/pr/2007' into development-proposed 2018-11-04 19:12:57 +00:00
Simon Butcher
76646a4bac Merge remote-tracking branch 'public/pr/1777' into development-proposed 2018-11-04 18:51:36 +00:00
Simon Butcher
2705beaeef Merge remote-tracking branch 'public/pr/2095' into development-proposed 2018-11-04 18:48:04 +00:00
Hanno Becker
710f203541 Merge branch 'iotssl-1770' into development_thomas_dee 2018-11-02 10:52:49 +00:00
Hanno Becker
cec1c2685f Break overly long line in library/x509_create.c 2018-11-02 10:52:38 +00:00
Hanno Becker
ee334a3a5c Remove Doxygen tags from documentation of private structure 2018-11-02 10:52:38 +00:00
Hanno Becker
beffcd8d4a Update hardcoded certificates in library/certs.c
library/certs.c provides some hardcoded certificates that
are used e.g. by the test applications ssl_server2, ssl_client2
in case no certificates are provided on the command line.

The certificates used are from the tests/data_files folder
and have been updated in the latest commits. This commit
updates their copies in certs.c. It also adds comments
indicating the files from which the data is taken, in
order to ease update in the future.
2018-11-02 10:52:38 +00:00
Hanno Becker
6e1adee42b Regenerate test files
Previous commits have added or modified build instructions for
server1*, server2*, server5*, test-ca*, cli-rsa* in the Makefile
tests/data_files/Makefile, or the apps they invoke have been changed.

This commit regenerates those files to make sure they are in match with
the build instructions.
2018-11-02 10:52:38 +00:00
Hanno Becker
cb93813e04 Don't perform binary comparison of CRL issuer and CA subject
Previously, when checking whether a CRT was revoked through
one of the configured CRLs, the library would only consider
those CRLs whose `issuer` field binary-matches the `subject`
field of the CA that has issued the CRT in question. If those
fields were not binary equivalent, the corresponding CRL was
discarded.

This is not in line with RFC 5280, which demands that the
comparison should be format- and case-insensitive. For example:

- If the same string is once encoded as a `PrintableString` and
  another time as a `UTF8String`, they should compare equal.
- If two strings differ only in their choice of upper and lower case
  letters, they should compare equal.

This commit fixes this by using the dedicated x509_name_cmp()
function to compare the CRL issuer with the CA subject.

Fixes #1784.
2018-11-02 10:49:09 +00:00
Hanno Becker
0f6903d84c Move static x509_name_cmp() in library/x509_crt.c
A subsequent change will need this function earlier
within the file.
2018-11-02 10:49:08 +00:00
Ron Eldor
2b161c33be Fix compilation issue
Fix compilation error when both `MBEDTLS_ECP_RESTARTABLE` and the
alternative definition of ECDH function are defined.
2018-11-01 16:18:20 +02:00
Ron Eldor
936d284f4d Minor fixes
1. Fix unused symbols compilation warnings.
2. Add comments for the closing `endif`.
2018-11-01 13:05:52 +02:00
Ron Eldor
8493f80e65 conditionaly compile ECDH and ECDSA alt functions
Return the condition compilation flags surrounding
`mbedtls_ecdh_compute_shared()`, `mbedtls_ecdh_gen_public()`,
`mbedtls_ecdsa_sign()` and `mbedtls_ecdsa_verify()` that were accidentally
removed in a previous merge.
Resolves #2163
2018-11-01 11:32:15 +02:00
Gilles Peskine
52b9018cf7 psa_export_key: for raw-byte keys, zero the end of the output buffer
Skip all writing to the target buffer if its size is 0, since in this
case the pointer might be invalid and this would cause the calls to
memcpy and memset to have undefined behavior.
2018-10-31 14:10:06 +01:00
Gilles Peskine
188c71e382 Private EC key format: change to raw secret value (export)
Change the import/export format of private elliptic curve keys from
RFC 5915 to the raw secret value. This commit updates the export code.
2018-10-31 14:10:06 +01:00
Gilles Peskine
f76aa7789b Private EC key format: change to raw secret value (doc, import)
Change the import/export format of private elliptic curve keys from
RFC 5915 to the raw secret value. This commit updates the format
specification and the import code, but not the export code.
2018-10-31 14:10:06 +01:00
Simon Butcher
7904f94550 Merge remote-tracking branch 'public/pr/1099' into development-proposed 2018-10-28 18:10:37 +00:00
Simon Butcher
17a0fab345 Merge remote-tracking branch 'public/pr/2111' into development-proposed 2018-10-28 16:22:18 +00:00
Simon Butcher
a07d86e8af Merge remote-tracking branch 'public/pr/1902' into development 2018-10-27 18:36:55 +01:00
Simon Butcher
ef263ebcd7 Merge remote-tracking branch 'public/pr/1993' into development 2018-10-27 18:36:28 +01:00
Hanno Becker
b10c66073f Detect unsigned integer overflow in mbedtls_ecp_check_budget()
This commit modifies a bounds check in `mbedtls_ecp_check_budget()` to
be correct even if the requested number of ECC operations would overflow
the operation counter.
2018-10-26 15:09:35 +01:00
Simon Butcher
169712e15a Merge remote-tracking branch 'restricted/pr/390' into development 2018-10-24 18:34:30 +01:00
Jaeden Amero
a74faba27a aes: xts: Correct NIST 80-38E to 800-38E
Correct a typo in an AES XTS implementation comment where the relevant
NIST standard was incorrectly referred to as NIST 80-38E instead of NIST
800-38E.
2018-10-23 12:07:18 +01:00
Jaeden Amero
8381fcb3f9 aes: xts: Update inaccurate comments
It is inaccurate to call a data unit a "sector". A disk sector is a
common use case for the data unit, but there exist other types of data
units that are not sectors.
2018-10-23 12:07:18 +01:00
Darryl Green
6c0f94cbd0 Add better handling when deleting files on Windows
Windows complains if you try to delete a file that doesn't exist.
Makefiles now check if the files exist before trying to delete them.
2018-10-23 12:03:31 +01:00
Manuel Pégourié-Gonnard
a966fdea72 Fix some documentation typos and improve a comment 2018-10-23 10:41:11 +02:00
Manuel Pégourié-Gonnard
ca29fdf569 Fix some typos in documentation and comments 2018-10-22 09:56:53 +02:00
Gilles Peskine
e0e9c7c417 New macro PSA_ALG_FULL_LENGTH_MAC
Provide a documented way of constructing the full-length MAC algorithm
from a truncated version.
2018-10-17 18:30:47 +02:00
Gilles Peskine
57fbdb1939 Use a public macro for AEAD tag length variations
Avoid depending on the encoding of algorithms inside psa_crypto.c.
2018-10-17 18:30:47 +02:00
Hanno Becker
dd3ab13da3 Fail when encountering invalid CBC padding in EtM records
This commit changes the behavior of the record decryption routine
`ssl_decrypt_buf()` in the following situation:
1. A CBC ciphersuite with Encrypt-then-MAC is used.
2. A record with valid MAC but invalid CBC padding is received.
In this situation, the previous code would not raise and error but
instead forward the decrypted packet, including the wrong padding,
to the user.

This commit changes this behavior to return the error
MBEDTLS_ERR_SSL_INVALID_MAC instead.

While erroneous, the previous behavior does not constitute a
security flaw since it can only happen for properly authenticated
records, that is, if the peer makes a mistake while preparing the
padded plaintext.
2018-10-17 14:43:14 +01:00
Gilles Peskine
f8a8fe60f8 Fix memory leak with AEAD with non-default tag lengths
When freeing the key context, choose the context format based on the
base algorithm value stored in the operation object.
2018-10-17 13:54:48 +02:00
Gilles Peskine
8cac2e628e Translate GCM_BAD_INPUT to INVALID_ARGUMENT, not NOT_SUPPORTED 2018-10-17 13:54:48 +02:00
Gilles Peskine
99b7d6b700 Wipe sensitive data in psa_mac_verify_finish
Wipe the whole MAC intermediate buffer, not just the requested MAC
size. With truncated MAC algorithms, the requested MAC size may be
smaller than what is written to the intermediate buffer.
2018-10-17 13:54:47 +02:00
Gilles Peskine
87b0ac49f8 Fix possible buffer overread in psa_mac_finish_internal (CMAC) 2018-10-17 13:54:47 +02:00
Gilles Peskine
6d72ff9e79 Document that the minimum truncated MAC length is implementation-defined 2018-10-17 13:54:47 +02:00
Manuel Pégourié-Gonnard
b25cb603bb Add a comment to clarify code flow 2018-10-16 11:48:09 +02:00
Manuel Pégourié-Gonnard
a5a3e40c4e Fix missing dereference.
Went unnoticed because it was only on a defensive code path, in an internal
function, so not exercised.
2018-10-16 11:27:23 +02:00
Manuel Pégourié-Gonnard
90f31b71a8 Improve readability by moving counter decrement
Avoid the slightly awkward rs_ctx-> i = i + 1
2018-10-16 10:45:24 +02:00
Manuel Pégourié-Gonnard
a58e011ac0 Fix alignment in a macro definition 2018-10-16 10:42:47 +02:00
Manuel Pégourié-Gonnard
b843b15a02 Fix function name to fit conventions 2018-10-16 10:41:31 +02:00
Manuel Pégourié-Gonnard
c0edc96704 Add comment on internal function API 2018-10-16 10:38:19 +02:00
Manuel Pégourié-Gonnard
d8b73f2312 Remove unnecessary calls to init() from free()
Our API makes no guarantee that you can use a context after free()ing it
without re-init()ing it first, so better not give the wrong impression that we
do, while it's not policy and the rest of the code might not allow it.
2018-10-16 10:34:13 +02:00
Manuel Pégourié-Gonnard
c37423fa76 Fix misleading sub-state name and comments
The enum constant had 'ske' in its name while this was a sub-state of the
"write client key exchange" state; corresponding issue in the comment.
2018-10-16 10:28:17 +02:00
Ron Eldor
5267b62248 Change error description
1. Change error description to a clearer one.
2. Change value in the error codes ranges description.
2018-10-15 18:44:42 +03:00
Ron Eldor
a27190b774 Rename platform error code and value
Rename the PLATFORM HW error, to avoid ABI breakage with Mbed OS.
The value changed as well, as previous value was not in the range of
Mbed TLS low level error codes.
2018-10-15 16:33:43 +03:00
Manuel Pégourié-Gonnard
ee68cff813 Fix or improve some comments (and whitespace) 2018-10-15 15:27:49 +02:00
Manuel Pégourié-Gonnard
f0bbd7e3fd Misc documentation fixes/improvements. 2018-10-15 13:22:41 +02:00
Manuel Pégourié-Gonnard
6346a75dfb Merge branch 'development' into iotssl-1260-non-blocking-ecc-restricted
* development:
  ssl-opt.sh: change expected output for large srv packet test with SSLv3
  Adapt ChangeLog
  Fix bug in SSL ticket implementation removing keys of age < 1s
  ssl-opt.sh: Add DTLS session resumption tests
  Add ChangeLog entry
  Fix typo
  Fix hmac_drbg failure in benchmark, with threading
  Remove trailing whitespace
  Remove trailing whitespace
  ssl_server2: add buffer overhead for a termination character
  Add missing large and small packet tests for ssl_server2
  Added buffer_size and response_size options for ssl-server2. Added appropriate tests.

Solving a conflict in tests/ssl-opt.sh: two set of tests were added at the
same place (just after large packets):
- restartable ECC tests (in this branch)
- server-side large packets (in development)

Resolution was to move the ECC tests after the newly added server large packet
ones.
2018-10-15 11:26:17 +02:00
Hanno Becker
805f2e11bd Add missing zeroization of buffered handshake messages
This commit ensures that buffers holding fragmented or
future handshake messages get zeroized before they are
freed when the respective handshake message is no longer
needed. Previously, the handshake message content would
leak on the heap.
2018-10-12 16:50:37 +01:00
Andrzej Kurek
748face36f ssl_tls: fix maximum output length
set maximum output length to MBEDTLS_SSL_OUT_CONTENT_LEN instead of
MBEDTLS_SSL_MAX_CONTENT_LEN.
2018-10-11 07:20:19 -04:00
Hanno Becker
780f0a4cc1 Reinitialize PK ctx in mbedtls_pk_parse_key before reuse are free
Context: This commit makes a change to mbedtls_pk_parse_key() which
is responsible for parsing of private keys. The function doesn't know
the key format in advance (PEM vs. DER, encrypted vs. unencrypted) and
tries them one by one, resetting the PK context in between.

Issue: The previous code resets the PK context through a call to
mbedtls_pk_free() along, lacking the accompanying mbedtls_pk_init()
call. Practically, this is not an issue because functionally
mbedtls_pk_free() + mbedtls_pk_init() is equivalent to mbedtls_pk_free()
with the current implementation of these functions, but strictly
speaking it's nonetheless a violation of the API semantics according
to which xxx_free() functions leave a context in uninitialized state.
(yet not entirely random, because xxx_free() functions must be idempotent,
so they cannot just fill the context they operate on with garbage).

Change: The commit adds calls to mbedtls_pk_init() after those calls
to mbedtls_pk_free() within mbedtls_pk_parse_key() after which the
PK context might still be used.
2018-10-11 11:31:15 +01:00
Hanno Becker
cfa2e33fd2 Omit runtime configuration of calloc/free if macro config enabled
This commit removes the definition of the API function

`mbedtls_platform_set_calloc_free()`

from `library/platform.c` in case the macros

`MBEDTLS_PLATFORM_CALLOC_MACRO`
`MBEDTLS_PLATFORM_FREE_MACRO`

for compile time configuration of calloc/free are set.

This is in line with the corresponding header `mbedtls/platform.h`
which declares `mbedtls_platform_set_calloc_free()` only if
`MBEDTLS_PLATFORM_{CALLOC/FREE}_MACRO` are not defined.

Fixes #1642.
2018-10-11 11:04:20 +01:00
Hanno Becker
8df10232cf Add explicit unsigned-to-signed integer conversion
The previous code triggered a compiler warning because of a comparison
of a signed and an unsigned integer.

The conversion is safe because `len` is representable by 16-bits,
hence smaller than the maximum integer.
2018-10-10 15:48:39 +01:00
Darryl Green
e3f95ed25b Fix bias in random number generation in Miller-Rabin test
When a random number is generated for the Miller-Rabin primality test,
if the bit length of the random number is larger than the number being
tested, the random number is shifted right to have the same bit length.
This introduces bias, as the random number is now guaranteed to be
larger than 2^(bit length-1).

Changing this to instead zero all bits higher than the tested numbers
bit length will remove this bias and keep the random number being
uniformly generated.
2018-10-09 16:36:53 +01:00
Janos Follath
a0b67c2f3e Bignum: Deprecate mbedtls_mpi_is_prime()
When using a primality testing function the tolerable error rate depends
on the scheme in question, the required security strength and wether it
is used for key generation or parameter validation. To support all use
cases we need more flexibility than what the old API provides.
2018-10-09 16:36:53 +01:00
Janos Follath
da31fa137a Bignum: Fix prime validation vulnerability
The input distribution to primality testing functions is completely
different when used for generating primes and when for validating
primes. The constants used in the library are geared towards the prime
generation use case and are weak when used for validation. (Maliciously
constructed composite numbers can pass the test with high probability)

The mbedtls_mpi_is_prime() function is in the public API and although it
is not documented, it is reasonable to assume that the primary use case
is validating primes. The RSA module too uses it for validating key
material.
2018-10-09 16:36:53 +01:00
Janos Follath
b728c29114 Bignum: Remove dead code
Both variables affected by the code are overwritten before their next
read.
2018-10-09 16:33:27 +01:00
Janos Follath
b8fc1b02ee RSA: Use MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR 2018-10-09 16:33:27 +01:00
Janos Follath
f301d23ceb Bignum: Improve primality test for FIPS primes
The FIPS 186-4 RSA key generation prescribes lower failure probability
in primality testing and this makes key generation slower. We enable the
caller to decide between compliance/security and performance.

This python script calculates the base two logarithm of the formulas in
HAC Fact 4.48 and was used to determine the breakpoints and number of
rounds:

def mrpkt_log_2(k, t):
    if t <= k/9.0:
        return 3*math.log(k,2)/2+t-math.log(t,2)/2+4-2*math.sqrt(t*k)
    elif t <= k/4.0:
        c1 = math.log(7.0*k/20,2)-5*t
        c2 = math.log(1/7.0,2)+15*math.log(k,2)/4.0-k/2.0-2*t
        c3 = math.log(12*k,2)-k/4.0-3*t
        return max(c1, c2, c3)
    else:
        return math.log(1/7.0)+15*math.log(k,2)/4.0-k/2.0-2*t
2018-10-09 16:33:27 +01:00
Andrzej Kurek
ef43ce6e25 Dtls: change the way unlimited mtu is set for client hello messages 2018-10-09 08:24:12 -04:00
Hanno Becker
1624e2e8bb Avoid overly long lines X.509 DN attr array def in x509_create.c 2018-10-08 14:52:20 +01:00
Hanno Becker
35b6854e54 Replace reference to RFC 3280 by reference to newer RFC 5280 2018-10-08 14:47:38 +01:00
Hanno Becker
cfc47bab69 Correct some indentation and line lengths in x509_create.c 2018-10-08 14:45:42 +01:00
Hanno Becker
d355e69aed Rename tag to default_tag in x509_attr_descriptor_t 2018-10-08 14:44:32 +01:00
Hanno Becker
d2c9009e5a Improve documentation of x509_attr_descriptor_t 2018-10-08 14:42:34 +01:00
Gilles Peskine
23cc2ff9a8 Add support for non-default-tag-size AEAD (CCM and GCM) 2018-10-08 14:42:11 +02:00
Gilles Peskine
edf9a6576d Refactor AEAD setup into a common function
There was a lot of repetition between psa_aead_encrypt and
psa_aead_decrypt. Refactor the code into a new function psa_aead_setup.
The new code should behave identically except that in some cases where
multiple error conditions apply, the code may now return a different
error code.

Internally, I rearranged some of the code:

* I removed a check that the key type was in CATEGORY_SYMMETRIC because
  it's redundant with mbedtls_cipher_info_from_psa which enumerates
  supported key types explicitly.
* The order of some validations is different to allow the split between
  setup and data processing. The code now calls a more robust function
  psa_aead_abort in case of any error after the early stage of the setup.
2018-10-08 14:42:11 +02:00
Gilles Peskine
d911eb7915 Add support for truncated MAC algorithms 2018-10-08 14:42:11 +02:00
Hanno Becker
0c161d1956 Fix bounds check in ssl_parse_server_psk_hint()
In the previous bounds check `(*p) > end - len`, the computation
of `end - len` might underflow if `end` is within the first 64KB
of the address space (note that the length `len` is controlled by
the peer). In this case, the bounds check will be bypassed, leading
to `*p` exceed the message bounds by up to 64KB when leaving
`ssl_parse_server_psk_hint()`. In a pure PSK-based handshake,
this doesn't seem to have any consequences, as `*p*` is not accessed
afterwards. In a PSK-(EC)DHE handshake, however, `*p` is read from
in `ssl_parse_server_ecdh_params()` and `ssl_parse_server_dh_params()`
which might lead to an application crash of information leakage.
2018-10-08 13:40:50 +01:00
Andrzej Kurek
6290dae909 Disable dtls fragmentation for ClientHello messages
Set the handshake mtu to unlimited when encountering a ClienHello message and
reset it to its previous value after writing the record.
2018-10-05 08:06:01 -04:00
Simon Butcher
d2642584cb Make inclusion of stdio.h conditional in x509_crt.c
stdio.h was being included both conditionally if MBEDTLS_FS_IO was
defined, and also unconditionally, which made at least one of them
redundant.

This change removes the unconditional inclusion of stdio.h and makes it
conditional on MBEDTLS_PLATFORM_C.
2018-10-03 15:11:19 +01:00
Jaeden Amero
3725bb2d6d rsa: pss: Enable use of big hashes with small keys
It should be valid to RSASSA-PSS sign a SHA-512 hash with a 1024-bit or
1032-bit RSA key, but with the salt size being always equal to the hash
size, this isn't possible: the key is too small.

To enable use of hashes that are relatively large compared to the key
size, allow reducing the salt size to no less than the hash size minus 2
bytes. We don't allow salt sizes smaller than the hash size minus 2
bytes because that too significantly changes the security guarantees the
library provides compared to the previous implementation which always
used a salt size equal to the hash size. The new calculated salt size
remains compliant with FIPS 186-4.

We also need to update the "hash too large" test, since we now reduce
the salt size when certain key sizes are used. We used to not support
1024-bit keys with SHA-512, but now we support this by reducing the salt
size to 62. Update the "hash too large" test to use a 1016-bit RSA key
with SHA-512, which still has too large of a hash because we will not
reduce the salt size further than 2 bytes shorter than the hash size.

The RSA private key used for the test was generated using "openssl
genrsa 1016" using OpenSSL 1.1.1-pre8.

    $ openssl genrsa 1016
    Generating RSA private key, 1016 bit long modulus (2 primes)
    ..............++++++
    ....++++++
    e is 65537 (0x010001)
    -----BEGIN RSA PRIVATE KEY-----
    MIICVwIBAAKBgACu54dKTbLxUQBEQF2ynxTfDze7z2H8vMmUo9McqvhYp0zI8qQK
    yanOeqmgaA9iz52NS4JxFFM/2/hvFvyd/ly/hX2GE1UZpGEf/FnLdHOGFhmnjj7D
    FHFegEz/gtbzLp9X3fOQVjYpiDvTT0Do20EyCbFRzul9gXpdZcfaVHNLAgMBAAEC
    gYAAiWht2ksmnP01B2nF8tGV1RQghhUL90Hd4D/AWFJdX1C4O1qc07jRBd1KLDH0
    fH19WocLCImeSZooGCZn+jveTuaEH14w6I0EfnpKDcpWVAoIP6I8eSdAttrnTyTn
    Y7VgPrcobyq4WkCVCD/jLUbn97CneF7EHNspXGMTvorMeQJADjy2hF5SginhnPsk
    YR5oWawc6n01mStuLnloI8Uq/6A0AOQoMPkGl/CESZw+NYfe/BnnSeckM917cMKL
    DIKAtwJADEj55Frjj9tKUUO+N9eaEM1PH5eC7yakhIpESccs/XEsaDUIGHNjhctK
    mrbbWu+OlsVRA5z8yJFYIa7gae1mDQJABjtQ8JOQreTDGkFbZR84MbgCWClCIq89
    5R3DFZUiAw4OdS1o4ja+Shc+8DFxkWDNm6+C63g/Amy5sVuWHX2p9QI/a69Cxmns
    TxHoXm1w9Azublk7N7DgB26yqxlTfWJo+ysOFmLEk47g0ekoCwLPxkwXlYIEoad2
    JqPh418DwYExAkACcqrd9+rfxtrbCbTXHEizW7aHR+fVOr9lpXXDEZTlDJ57sRkS
    SpjXbAmylqQuKLqH8h/72RbiP36kEm5ptmw2
    -----END RSA PRIVATE KEY-----
2018-09-27 18:23:08 +01:00
Simon Butcher
c86993e33c Merge remote-tracking branch 'public/pr/1970' into development 2018-09-27 09:48:54 +01:00
Gilles Peskine
159ebf3b8e
Merge pull request #142 from ARMmbed/psa-metadata_validation
Algorithm and key type encoding validation
2018-09-24 10:38:39 +02:00
Janos Follath
7c025a9f50 Generalize dh_flag in mbedtls_mpi_gen_prime
Setting the dh_flag to 1 used to indicate that the caller requests safe
primes from mbedtls_mpi_gen_prime. We generalize the functionality to
make room for more flags in that parameter.
2018-09-21 16:30:07 +01:00
Jaeden Amero
3bfe5f0388
Merge pull request #150 from ARMmbed/psa-rsa-verify-error
Don't return INVALID_PADDING on an invalid RSA signature
2018-09-21 16:15:10 +01:00
Jaeden Amero
40363fe3f5
Merge pull request #139 from ARMmbed/psa-PSA_ALG-block_cipher_padding
Correct and simplify block-based cipher modes
2018-09-21 09:38:27 +01:00
Gilles Peskine
00709fafb8 Rename PSA_ALG_HMAC_HASH to PSA_ALG_HMAC_GET_HASH
Be consistent with other GET_HASH macros.
2018-09-20 12:00:21 +02:00
Gilles Peskine
daea26f70f Correct and simplify block-based cipher modes
OFB and CFB are streaming modes. XTS is a not a cipher mode but it
doesn't use a separate padding step. This leaves only CBC as a block
cipher mode that needs a padding step.

Since CBC is the only mode that uses a separate padding step, and is
likely to remain the only mode in the future, encode the padding mode
directly in the algorithm constant, rather than building up an
algorithm value from a chaining mode and a padding mode. This greatly
simplifies the interface as well as some parts of the implementation.
2018-09-20 11:58:22 +02:00
thomas-dee
eba6c9bb50 changes requested by @hanno-arm
- renamed `mbedtls_asn1_write_any_string` to `mbedtls_asn1_write_tagged_string`
 - renamed `x509_at_oid_from_name` to `x509_attr_descr_from_name`
2018-09-19 09:10:37 +02:00
Gilles Peskine
ef12c63de0 RSA verification: don't report an invalid padding error
Mbed TLS distinguishes "invalid padding" from "valid padding but the
rest of the signature is invalid". This has little use in practice and
PSA doesn't report this distinction. We just report "invalid
signature".
2018-09-17 14:33:43 +02:00
itayzafrir
90d8c7a728 Ensure the module is initialized in key based functions 2018-09-16 12:15:47 +03:00
itayzafrir
0adf0fc31c Ensure the module is initialized in psa_generate_random 2018-09-16 12:15:46 +03:00
Gilles Peskine
78b3bb670d Change the bitwise encoding of key type categories
There were only 5 categories (now 4). Reduce the category mask from 7
bits to 3.

Combine unformatted, not-necessarily-uniform keys (HMAC, derivation)
with raw data.

Reintroduce a KEY_TYPE_IS_UNSTRUCTURED macro (which used to exist
under the name KEY_TYPE_IS_RAW_DATA macro) for key types that don't
have any structure, including both should-be-uniform keys (such as
block cipher and stream cipher keys) and not-necessarily-uniform
keys (such as HMAC keys and secrets for key derivation).
2018-09-14 10:02:29 +01:00
itayzafrir
534bd7c33b Add missing calls to psa_cipher_abort in cipher functions 2018-09-14 10:02:29 +01:00
itayzafrir
40835d4e56 Add missing calls to psa_hash_abort in hash functions 2018-09-14 10:02:29 +01:00
Jaeden Amero
df3b74f168 Merge pull request #125 from ARMmbed/key_slot_index-fix
Fix off-by-one errors in key slot index limits
2018-09-14 10:02:29 +01:00
Gilles Peskine
9a05634558 psa_crypto_free: destroy the last slot
The last slot in the array was not freed due to an off-by-one error.

Amend the fill_slots test to serve as a non-regression test for this
issue: without this bug fix, it would cause a memory leak.
2018-09-14 10:02:29 +01:00
Gilles Peskine
996deb18cc Fix buffer overflow in the slot array
Slots are numbered from 1, but the slot array is a C array so it's
numbered from 0.

Add a non-regression test.
2018-09-14 10:02:29 +01:00
Darryl Green
9e2d7a09f1 Add ifdefs for psa_internal_export_key function
MBEDTLS_PK_WRITE_C only requires either MBEDTLS_RSA_C or MBEDTLS_ECP_C to be defined.
Added wrappers to handle the cases where only one has been defined.
Moved mbedtls_pk_init to be within the ifdefs, so it's only called if appropriate.
2018-09-14 10:02:28 +01:00
Darryl Green
8800136156 Fix key parameter in psa_key_derivation to use correct type 2018-09-14 10:02:28 +01:00
Darryl Green
8f8aa8f931 Add ifdef for MBEDTLS_ECP_C around ecc_group_to_psa functions
These are unused if MBEDTLS_ECP_C isn't defined.
2018-09-14 10:02:28 +01:00
Darryl Green
5cc689a821 Add handling for (sometimes) unused parameters 2018-09-14 10:02:28 +01:00
Gilles Peskine
9f900a8b25 Merge pull request #105 from ARMmbed/psa-derive_hkdf
PSA key derivation: simple-ish interface, HKDF
2018-09-12 16:50:07 +03:00
Gilles Peskine
08542d8037 Fix psa_generator_import_key for DES
In psa_generator_import_key, if generating a DES or 3DES key, set the
parity bits.

Add tests for deriving a DES key. Also test deriving an AES key while
I'm at it.
2018-09-12 16:50:07 +03:00
Gilles Peskine
d54931c7c4 HKDF: be more robust if we reach the maximum ouptut length
In psa_generator_hkdf_read, return BAD_STATE if we're trying to
construct more output than the algorithm allows. This can't happen
through the API due to the capacity limit, but it could potentially
happen in an internal call.

Also add a test case that verifies that we can set up HKDF with its
maximum capacity and read up to the maximum capacity.
2018-09-12 16:50:05 +03:00
Gilles Peskine
bef7f14f8e Implement HKDF 2018-09-12 16:44:05 +03:00
Gilles Peskine
ea0fb4975c Add framework for simple key derivation
New key type PSA_KEY_TYPE_DERIVE. New usage flag PSA_KEY_USAGE_DERIVE.
New function psa_key_derivation.

No key derivation algorithm is implemented yet. The code may not
compile with -Wunused.

Write some unit test code for psa_key_derivation. Most of it cannot be
used yet due to the lack of a key derivation algorithm.
2018-09-12 16:44:04 +03:00
Gilles Peskine
eab56e4159 Add generator API
Add an API for byte generators: psa_crypto_generator_t,
PSA_CRYPTO_GENERATOR_INIT, psa_crypto_generator_init,
psa_get_generator_capacity, psa_generator_read,
psa_generator_import_key, psa_generator_abort.

This commit does not yet implement any generator algorithm, it only
provides the framework. This code may not compile with -Wunused.
2018-09-12 16:41:12 +03:00
Gilles Peskine
9aa369eafb HMAC: improve robustness checks on hash/block size
In psa_mac_setup and psa_hmac_setup_internal, perform a sanity check
on the hash size and the hash block size respectively. These sanity
checks should only trigger on an incompletely or incorrectly
implemented hash function.

Remove the check on the block size in psa_hmac_finish_internal
because at this point it has already been checked and used.
2018-09-12 16:41:12 +03:00
Gilles Peskine
1e6bfdff5e psa_hmac_setup_internal: fix double call of psa_hash_setup
In the common case (key no longer than the block size), psa_hash_setup
was being called twice in succession. With current implementations
this is just a small performance loss, but potentially with
alternative implementations this could have lead to a memory leak.
2018-09-12 16:41:12 +03:00
Gilles Peskine
b3fc05d776 psa_asymmetric_{encrypt,decrypt}: reject salt when not allowed
In psa_asymmetric_encrypt and psa_asymmetric_decrypt, if the algorithm
does not use a salt, require the salt to be empty.
2018-09-12 16:41:12 +03:00
Gilles Peskine
ff94abdf3a Make psa_hmac_setup_internal more standalone
Call psa_hash_setup in psa_hmac_setup_internal rather than
psa_mac_init. This makes it easier to use psa_hmac_setup_internal on
its own (for the sake of using HMAC internally inside the library).
2018-09-12 16:41:12 +03:00
Gilles Peskine
b8be288374 psa_hmac_setup_internal: add some missing cleanup on failure
Clean ipad if hashing the key failed.
2018-09-12 16:41:12 +03:00
Gilles Peskine
9688997301 MAC setup: support 0-length HMAC key
Avoid undefined behavior when using a 0-length HMAC key (Asan
complained).
2018-09-12 16:41:12 +03:00
Gilles Peskine
072ac56a03 Implement OAEP
Implement RSAES-OAEP encryption and decryption.

Test it to the same level as PKCS#1 v1.5.
2018-09-12 16:41:12 +03:00
Gilles Peskine
01126fae7f Isolate HMAC code into its own functions
Create internal functions for HMAC operations. This prepares for two
things: separating crypto-sensitive code from argument decoding and
validation, and using HMAC for other purposes than a MAC inside the
library (e.g. HMAC_DRBG, HKDF).

No intended observable behavior change in this commit.
2018-09-12 16:41:12 +03:00