Commit graph

5826 commits

Author SHA1 Message Date
Gilles Peskine
e80c7e49e7
Merge pull request #278 from ARMmbed/dev/yanesca/iotcrypt-767-ecdsa-timing-side-channel
ECDSA timing side channel due to non-constant-time integer comparison
2019-11-12 11:44:13 +01:00
Jaeden Amero
90bc6b8143
Merge pull request #281 from AndrzejKurek/IOTCRYPT-968-zeroize-aes-variables
Zeroize local AES variables before exiting the function
2019-11-12 10:38:20 +00:00
Gilles Peskine
95b9f601fd
Merge pull request #280 from ARMmbed/dev/yanesca/iotcrypt-958-ecdsa-side-channel-fix
ECDSA: Fix side channel vulnerability
2019-11-12 11:34:39 +01:00
Andrzej Kurek
96ae5cd087 Zeroize local AES variables before exiting the function
This issue has been reported by Tuba Yavuz, Farhaan Fowze, Ken (Yihang) Bai,
Grant Hernandez, and Kevin Butler (University of Florida) and
Dave Tian (Purdue University).

In AES encrypt and decrypt some variables were left on the stack. The value
of these variables can be used to recover the last round key. To follow best
practice and to limit the impact of buffer overread vulnerabilities (like
Heartbleed) we need to zeroize them before exiting the function.
2019-11-12 03:05:51 -05:00
Gilles Peskine
2ad5e45de6
Merge pull request #314 from gilles-peskine-arm/pkwrite_ECPrivateKey_size-crypto
Fix pk_write with EC key to use a constant size for the private value
2019-11-08 19:30:51 +01:00
Jaeden Amero
b14a4ff840
Merge pull request #316 from Patater/stop-reentrant-transaction
Stop transactions from being reentrant
2019-11-08 14:59:39 +00:00
Janos Follath
307024207a mpi_lt_mpi_ct: fix condition handling
The code previously only set the done flag if the return value was one.
This led to overriding the correct return value later on.
2019-11-05 15:13:00 +00:00
Gilles Peskine
2700cfbdd5 Fix pk_write with an EC key to write a constant-length private value
When writing a private EC key, use a constant size for the private
value, as specified in RFC 5915. Previously, the value was written
as an ASN.1 INTEGER, which caused the size of the key to leak
about 1 bit of information on average, and could cause the value to be
1 byte too large for the output buffer.
2019-11-05 15:32:53 +01:00
irwir
6527bd6dfc Fix issue #2718 (condition always false) 2019-11-04 19:52:26 +03:00
Janos Follath
67ce647ff0 ct_lt_mpi_uint: cast the return value explicitely
The return value is always either one or zero and therefore there is no
risk of losing precision. Some compilers can't deduce this and complain.
2019-11-04 10:39:20 +00:00
Janos Follath
c50e6d5edb mbedtls_mpi_lt_mpi_ct: simplify condition
In the case of *ret we might need to preserve a 0 value throughout the
loop and therefore we need an extra condition to protect it from being
overwritten.

The value of done is always 1 after *ret has been set and does not need
to be protected from overwriting. Therefore in this case the extra
condition can be removed.
2019-11-04 10:39:20 +00:00
Janos Follath
5e614cef15 Rename variable for better readability 2019-11-04 10:39:20 +00:00
Janos Follath
bb5147f165 mbedtls_mpi_lt_mpi_ct: Improve documentation 2019-11-04 10:39:20 +00:00
Janos Follath
73ba9ec9a6 Make mbedtls_mpi_lt_mpi_ct more portable
The code relied on the assumptions that CHAR_BIT is 8 and that unsigned
does not have padding bits.

In the Bignum module we already assume that the sign of an MPI is either
-1 or 1. Using this, we eliminate the above mentioned dependency.
2019-11-04 10:39:20 +00:00
Janos Follath
3f6f0e44eb Document ct_lt_mpi_uint 2019-11-04 10:39:20 +00:00
Janos Follath
4abc172360 mpi_lt_mpi_ct: make use of unsigned consistent 2019-11-04 10:39:20 +00:00
Janos Follath
a0f732ba06 ct_lt_mpi_uint: make use of biL 2019-11-04 10:39:20 +00:00
Janos Follath
0e5532d6cf Change mbedtls_mpi_cmp_mpi_ct to check less than
The signature of mbedtls_mpi_cmp_mpi_ct() meant to support using it in
place of mbedtls_mpi_cmp_mpi(). This meant full comparison functionality
and a signed result.

To make the function more universal and friendly to constant time
coding, we change the result type to unsigned. Theoretically, we could
encode the comparison result in an unsigned value, but it would be less
intuitive.

Therefore we won't be able to represent the result as unsigned anymore
and the functionality will be constrained to checking if the first
operand is less than the second. This is sufficient to support the
current use case and to check any relationship between MPIs.

The only drawback is that we need to call the function twice when
checking for equality, but this can be optimised later if an when it is
needed.
2019-11-04 10:39:20 +00:00
Janos Follath
1fc97594da mbedtls_mpi_cmp_mpi_ct: remove multiplications
Multiplication is known to have measurable timing variations based on
the operands. For example it typically is much faster if one of the
operands is zero. Remove them from constant time code.
2019-11-04 10:39:20 +00:00
Janos Follath
d80080c884 Remove excess vertical space 2019-11-04 10:39:20 +00:00
Janos Follath
b2590790f2 Remove declaration after statement
Visual Studio 2013 does not like it for some reason.
2019-11-04 10:39:20 +00:00
Janos Follath
a779b4601e Fix side channel vulnerability in ECDSA 2019-11-04 10:39:20 +00:00
Janos Follath
ee6abcedfd Add new, constant time mpi comparison 2019-11-04 10:39:20 +00:00
Alexander K
d19a193738 Fix code review comments:
1. variable name accoriding to the Mbed TLS coding style;
2. add a comment explaining safety of the optimization;
3. safer T2 initialization and memory zeroing on the function exit;
2019-11-01 18:20:42 +03:00
Mykhailo Sopiha
20180ca919 Add ASN.1 ENUMERATED tag support
Add ASN.1 ENUMERATED [1] tag to supported tag list.

1. https://tools.ietf.org/html/rfc3641#page-8

Signed-off-by: Mykhailo Sopiha <mykhailo.sopiha@linaro.org>
2019-10-31 19:17:26 +02:00
Alexander K
35d6d46169 Small performance improvement of mbedtls_mpi_div_mpi():
1. don't use dynamic allocator for fixed size T2;
2. move T2 initialization out of the inner loop.
2019-10-31 14:46:45 +03:00
Arto Kinnunen
7f8089b2ec Fix mbedtls_ssl_check_record usage with ext buf
Record checking fails if mbedtls_ssl_check_record() is called with
external buffer. Received record sequence number is available in the
incoming record but it is not available in the ssl contexts `in_ctr`-
variable that is used when decoding the sequence number.

To fix the problem, temporarily update ssl context `in_ctr` to
point to the received record header and restore value later.
2019-10-29 13:51:37 +02:00
irwir
6c0da64094 Shorter version of mbedtls_ssl_send_fatal_handshake_failure 2019-10-28 19:54:04 +03:00
Jaeden Amero
2ce22a5079 Stop transactions from being reentrant
We want to explicitly disallow creating new transactions when a
transaction is already in progress. However, we were incorrectly
checking for the existence of the injected entropy file before
continuing with creating a transaction. This meant we could have a
transaction already in progress and would be able to still create a new
transaction. It also meant we couldn't start a new transaction if any
entropy had been injected. Check the transaction file instead of the
injected entropy file in order to prevent multiple concurrent
transactions.
2019-10-28 15:25:10 +00:00
Gilles Peskine
e9a3454e09 CTR_DRBG: grab a nonce from the entropy source if needed
Change the default entropy nonce length to be nonzero in some cases.
Specifically, the default nonce length is now set in such a way that
the entropy input during the initial seeding always contains enough
entropy to achieve the maximum possible security strength per
NIST SP 800-90A given the key size and entropy length.

If MBEDTLS_CTR_DRBG_ENTROPY_LEN is kept to its default value,
mbedtls_ctr_drbg_seed() now grabs extra entropy for a nonce if
MBEDTLS_CTR_DRBG_USE_128_BIT_KEY is disabled and either
MBEDTLS_ENTROPY_FORCE_SHA256 is enabled or MBEDTLS_SHA512_C is
disabled. If MBEDTLS_CTR_DRBG_USE_128_BIT_KEY is enabled, or if
the entropy module uses SHA-512, then the default value of
MBEDTLS_CTR_DRBG_ENTROPY_LEN does not require a second call to the
entropy function to achieve the maximum security strength.

This choice of default nonce size guarantees NIST compliance with the
maximum security strength while keeping backward compatibility and
performance high: in configurations that do not require grabbing more
entropy, the code will not grab more entropy than before.
2019-10-23 19:46:57 +02:00
Gilles Peskine
0ed378aa02 CTR_DRBG: explicitly set entropy_nonce_len=0 when desired
No behavior change. Prepare for a future version that will set the
entropy nonce length to a nonzero value by default.
2019-10-23 19:46:56 +02:00
Gilles Peskine
97f59ab527 CTR_DRBG: add the possibility of grabbing entropy for a nonce
Add a new function mbedtls_ctr_drbg_set_nonce_len() which configures
the DRBG instance to call f_entropy a second time during the initial
seeding to grab a nonce.

The default nonce length is 0, so there is no behavior change unless
the user calls the new function.
2019-10-23 19:46:56 +02:00
Gilles Peskine
9be5098061 CTR_DRBG: add the possibility of grabbing entropy for a nonce
Add a new function mbedtls_ctr_drbg_set_nonce_len() which configures
the DRBG instance to call f_entropy a second time during the initial
seeding to grab a nonce.

The default nonce length is 0, so there is no behavior change unless
the user calls the new function.
2019-10-23 19:46:56 +02:00
Gilles Peskine
dbd3f7c68d mbedtls_ctr_drbg_reseed: Minor readability improvement
No semantic change.
2019-10-23 19:46:56 +02:00
Gilles Peskine
379561feff fixup! CTR_DRBG: support set_entropy_len() before seed()
Update a comment that referred to a now-removed function.
2019-10-23 19:46:56 +02:00
k-stachowiak
67badb4451 Secure array index in its bounds 2019-10-22 13:25:06 +02:00
Jaeden Amero
b1c7197166
Merge pull request #299 from gilles-peskine-arm/drbg-set_entropy_len
Allow xxx_drbg_set_entropy_len before xxx_drbg_seed
2019-10-18 15:39:03 +01:00
Jaeden Amero
719ae74253
Merge pull request #2884 from AndrzejKurek/iotssl-2886-fix-parallel-make-jobs-2
Fix parallel make jobs for shared target
2019-10-18 14:18:55 +01:00
Janos Follath
247c4d3c88 ECDSA: Fix side channel vulnerability
The blinding applied to the scalar before modular inversion is
inadequate. Bignum is not constant time/constant trace, side channel
attacks can retrieve the blinded value, factor it (it is smaller than
RSA keys and not guaranteed to have only large prime factors). Then the
key can be recovered by brute force.

Reducing the blinded value makes factoring useless because the adversary
can only recover pk*t+z*N instead of pk*t.
2019-10-17 10:18:51 +01:00
Gilles Peskine
150d577780
Merge pull request #292 from gilles-peskine-arm/psa-destroy_0
Make psa_close_key(0) and psa_destroy_key(0) succeed
2019-10-14 11:21:54 +02:00
Gilles Peskine
b16841ee69 Fixed -Wunused warnings when building without asymmetric crypto 2019-10-11 18:21:08 +02:00
Gilles Peskine
50ed86b6b9 CTR_DRBG: support set_entropy_len() before seed()
mbedtls_ctr_drbg_seed() always set the entropy length to the default,
so a call to mbedtls_ctr_drbg_set_entropy_len() before seed() had no
effect. Change this to the more intuitive behavior that
set_entropy_len() sets the entropy length and seed() respects that and
only uses the default entropy length if there was no call to
set_entropy_len().

This removes the need for the test-only function
mbedtls_ctr_drbg_seed_entropy_len(). Just call
mbedtls_ctr_drbg_set_entropy_len() followed by
mbedtls_ctr_drbg_seed(), it works now.
2019-10-11 18:04:12 +02:00
Gilles Peskine
8bf5613336 CTR_DRBG: Don't use functions before they're defined
Move the definitions of mbedtls_ctr_drbg_seed_entropy_len() and
mbedtls_ctr_drbg_seed() to after they are used. This makes the code
easier to read and to maintain.
2019-10-11 18:04:12 +02:00
Gilles Peskine
8f7921ec4b HMAC_DRBG: support set_entropy_len() before seed()
mbedtls_hmac_drbg_seed() always set the entropy length to the default,
so a call to mbedtls_hmac_drbg_set_entropy_len() before seed() had no
effect. Change this to the more intuitive behavior that
set_entropy_len() sets the entropy length and seed() respects that and
only uses the default entropy length if there was no call to
set_entropy_len().
2019-10-11 18:04:12 +02:00
Gilles Peskine
3cdb3da3a0
Merge pull request #297 from gilles-peskine-arm/asn1_get_int-undefined_shift
Fix int overflow in mbedtls_asn1_get_int
2019-10-11 17:31:16 +02:00
Gilles Peskine
e5e9081b76
Merge pull request #287 from gilles-peskine-arm/ctr_drbg-doc-nist-crypto
DRBG documentation improvements
2019-10-11 16:57:45 +02:00
Gilles Peskine
37570e8152 mbedtls_asn1_get_int: fix int overflow
Fix a signed int overflow in mbedtls_asn1_get_int() for numbers
between INT_MAX+1 and UINT_MAX (typically 0x80000000..0xffffffff).
This was undefined behavior which in practice would typically have
resulted in an incorrect value, but which may plausibly also have
caused the postcondition (*p == initial<*p> + len) to be violated.

Credit to OSS-Fuzz.
2019-10-10 19:29:27 +02:00
Gilles Peskine
9fd9794d10 mbedtls_asn1_get_int: explain the logic
No behavior change.
2019-10-10 19:27:53 +02:00
Gilles Peskine
36029387de
Merge pull request #285 from gilles-peskine-arm/psa-se_driver-validate_save_persistent
SE driver: make persistent data work
2019-10-09 18:35:33 +02:00
Gilles Peskine
85485c7338 Always gather MBEDTLS_ENTROPY_BLOCK_SIZE bytes of entropy
mbedtls_entropy_func returns up to MBEDTLS_ENTROPY_BLOCK_SIZE bytes.
This is the output of a hash function and does not indicate how many
bytes of entropy went into the hash computation.

Enforce that mbedtls_entropy_func gathers a total of
MBEDTLS_ENTROPY_BLOCK_SIZE bytes or more from strong sources. Weak
sources don't count for this calculation. This is complementary to the
per-source threshold mechanism.

In particular, we define system sources with a threshold of 32. But
when using SHA-512 for the entropy accumulator,
MBEDTLS_ENTROPY_BLOCK_SIZE = 64, so users can expect 64 bytes' worth
of entropy. Before, you only got 64 bytes of entropy if there were two
sources. Now you get 64 bytes of entropy even with a single source
with a threshold of 32.
2019-10-09 13:53:47 +02:00
Andrzej Kurek
8028cb19f4 Makefile: add path prefixes to other versions of libmbedcrypto library 2019-10-08 10:10:43 -04:00
Gilles Peskine
1841cf43ee Make psa_close_key(0) and psa_destroy_key(0) succeed 2019-10-08 15:57:27 +02:00
Andrzej Kurek
8af3923815 Add a recipe for libmbedcrypto with a path prefix
This caused problems when running multiple jobs at once, since
there was no target matching libmbedcrypto.so with the path
prefix. It only worked if it was built first, since such file was found.
Additionally,  building of libmbedcrypto.so now waits for the static .a version.
Previously, recipes for both libmbedcrypto.a and libmbedcrypto.so could run
independently when running parallel jobs, which resulted in the .o files
being built twice. It could sometimes be a problem, since linking would start
when building one of the object files was still in progress (the previous one
existed). This in turn resulted in reading (and trying to link) a malformed file.
The "|" character is followed by "order-only-prerequisites", and in this case,
makes linking of the shared version of the library wait for the .a file.
Since it's guaranteed to be always built in the "all" target, it's fine to do that.
All of the .o files are only built once thanks to this change.
2019-10-07 09:19:18 -04:00
Gilles Peskine
e96658d3f5 Update error.c after a crypto submodule update 2019-10-04 19:23:00 +02:00
Jaeden Amero
9ab7c07f1f
Merge pull request #75 from gilles-peskine-arm/asn1-tests-without-x509
ASN.1 tests without x509
2019-10-04 12:30:01 +01:00
Gilles Peskine
1540e5bd04 Move MBEDTLS_CTR_DRBG_USE_128_BIT_KEY to the correct section
It's an on/off feature, so it should be listed in version_features.
2019-10-04 11:16:24 +02:00
Gilles Peskine
d5536d8a5b SE driver: Fix loading of persistent data
The persistent data was not loaded correctly (the code was loading 0
bytes instead of the correct size).
2019-10-01 16:55:29 +02:00
Gilles Peskine
c84c70a83c SE driver: save the persistent data after calling p_init 2019-10-01 15:41:42 +02:00
Gilles Peskine
d9348f218e SE driver: call the p_init method during psa_crypto_init() 2019-10-01 15:22:29 +02:00
Gilles Peskine
5ec3a30edb SE driver: validate_slot_number: support changing persistent data
Add a parameter to the p_validate_slot_number method to allow the
driver to modify the persistent data.

With the current structure of the core, the persistent data is already
updated. All it took was adding a way to modify it.
2019-10-01 14:27:23 +02:00
Gilles Peskine
3efcebbc5e SE support: Use a transaction when registering a key
When registering a key in a secure element, go through the transaction
mechanism. This makes the code simpler, at the expense of a few extra
storage operations. Given that registering a key is typically very
rare over the lifetime of a device, this is an acceptable loss.

Drivers must now have a p_validate_slot_number method, otherwise
registering a key is not possible. This reduces the risk that due to a
mistake during the integration of a device, an application might claim
a slot in a way that is not supported by the driver.
2019-10-01 14:18:35 +02:00
Gilles Peskine
006c1b5f4e Prefer initializing ret to error values
These initial values shouldn't be used, but in case they accidentally
get used after a code change, fail safe.
2019-09-30 17:29:54 +02:00
Benjamin Kier
7edad28036 Fixed possibly undefined variable warnings by initializing variables to 0. 2019-09-30 17:24:08 +02:00
Gilles Peskine
9a562d471e
Merge pull request #277 from jack-fortanix/faster-pbkdf2
Improve speed of PBKDF2 by caching the digest state of the passphrase
2019-09-30 15:53:49 +02:00
Gilles Peskine
b64bf0638f Parse HelloVerifyRequest: avoid buffer overread at the start
In ssl_parse_hello_verify_request, we read 3 bytes (version and cookie
length) without checking that there are that many bytes left in
ssl->in_msg. This could potentially read from memory outside of the
ssl->receive buffer (which would be a remotely exploitable
crash).
2019-09-27 14:02:44 +02:00
Gilles Peskine
b51130dd5c Parse HelloVerifyRequest: avoid buffer overread on the cookie
In ssl_parse_hello_verify_request, we print cookie_len bytes without
checking that there are that many bytes left in ssl->in_msg. This
could potentially log data outside the received message (not a big
deal) and could potentially read from memory outside of the receive
buffer (which would be a remotely exploitable crash).
2019-09-27 14:00:36 +02:00
Gilles Peskine
bdcca14076 Merge remote-tracking branch 'upstream-public/pr/2858' into development 2019-09-27 11:08:51 +02:00
irwir
89af51ff39 Resolve #2801 - remove repetitive assignment to ssl->in_msg (the first value was never used) 2019-09-26 21:04:56 +03:00
irwir
734f0cf65e Resolve #2800 - move declaration to avoid unused variable warning in case MBEDTLS_SSL_PROTO_DTLS was undefined 2019-09-26 21:03:24 +03:00
irwir
40883e91a6 Resolve #2717 - remove erroneous sizeof (the operator was applied to constant integer number) 2019-09-26 21:00:56 +03:00
Gilles Peskine
178c9aa966 Key derivation: forbid output_key without input_key
If none of the inputs to a key derivation is a
PSA_KEY_DERIVATION_INPUT_SECRET passed with
psa_key_derivation_input_key(), forbid
psa_key_derivation_output_key(). It usually doesn't make sense to
derive a key object if the secret isn't itself a proper key.
2019-09-24 18:39:03 +02:00
Gilles Peskine
b8965193a0 Use the constant PSA_KEY_TYPE_NONE rather than 0
No behavior change, just a readability improvement.
2019-09-24 18:39:03 +02:00
Gilles Peskine
46d7faf195 Don't jump past a variable declaration
This is valid C99 (since the variable in question is not a VLA and is
not used) but not accepted by IAR 8.20.
2019-09-24 18:39:03 +02:00
Gilles Peskine
593773d9f2 Consistently abort key derivation operations on input error 2019-09-24 18:39:03 +02:00
Gilles Peskine
224b0d656a Key derivation: allow both keys and direct inputs
Allow a direct input as the SECRET input step in a key derivation, in
addition to allowing DERIVE keys. This makes it easier for
applications to run a key derivation where the "secret" input is
obtained from somewhere else. This makes it possible for the "secret"
input to be empty (keys cannot be empty), which some protocols do (for
example the IV derivation in EAP-TLS).

Conversely, allow a RAW_DATA key as the INFO/LABEL/SALT/SEED input to a key
derivation, in addition to allowing direct inputs. This doesn't
improve security, but removes a step when a personalization parameter
is stored in the key store, and allows this personalization parameter
to remain opaque.

Add test cases that explore step/key-type-and-keyhood combinations.
2019-09-24 18:39:03 +02:00
Jack Lloyd
71657493f1 Improve speed of PBKDF2 by caching the digest state of the passphrase 2019-09-23 19:15:54 -04:00
Gilles Peskine
311f54d0ee tls_prf: support an empty master secret
In TLS, the master secret is always a key. But EAP-TLS uses the TLS
PRF to derive an IV with an empty string for the "secret" input. The
code always stored the secret into a key slot before calling the TLS
PRF, but this doesn't work when the secret is empty, since PSA Crypto
no longer supports empty keys. Add a special case for an empty secret.
2019-09-23 18:19:22 +02:00
Gilles Peskine
a291413a1e
Merge pull request #257 from gilles-peskine-arm/psa-remove_zero_length_keys
Forbid zero-length keys
2019-09-19 13:07:41 +02:00
Jaeden Amero
914a5071b4 Bump Mbed TLS version to 2.19.1 2019-09-18 13:42:36 +01:00
k-stachowiak
95b68ef5ae Improve clarity of a memory operation call 2019-09-16 12:21:00 +02:00
Gilles Peskine
89cc74f447 Fix signature size checks in psa_asymmetric_verify for RSA
The signature must have exactly the same length as the key, it can't
be longer. Fix #258

If the signature doesn't have the correct size, that's an invalid
signature, not a problem with an output buffer size. Fix the error code.

Add test cases.
2019-09-13 11:39:11 +02:00
Gilles Peskine
4019f0e914 Immediately reject 0-size signature buffer when signing
In psa_asymmetric_sign, immediately reject an empty signature buffer.
This can never be right.

Add test cases (one RSA and one ECDSA).

Change the SE HAL mock tests not to use an empty signature buffer.
2019-09-12 22:05:59 +02:00
Gilles Peskine
f916894ef3 Remove special handling for zero-length keys
Zero-length keys are rejected at creation time, so we don't need any
special handling internally.

When exporting a key, we do need to take care of the case where the
output buffer is empty, but this is easy: an empty output buffer is
never valid.
2019-09-12 19:21:37 +02:00
Gilles Peskine
0f84d6245b Reject keys of size 0
Implement the prohibition on keys of size 0.
2019-09-12 19:03:13 +02:00
Jaeden Amero
fa63645ec8 ssl: Remove key exporter bug workaround
It is no longer necessary to cast the randbytes to non-const when
exporting keys.
2019-09-12 15:18:25 +01:00
Gilles Peskine
aac3853348 Fix long-standing bug in error code description
MBEDTLS_ERR_ASN1_INVALID_DATA is documented as "not used", but it has
been used since the PolarSSL days.
2019-09-11 18:16:11 +02:00
Gilles Peskine
09c0a2364b mbedtls_asn1_store_named_data: clarify val allocation behavior
Document how mbedtls_asn1_store_named_data allocates val.p in the new
or modified entry.

Change the behavior to be more regular, always setting the new length
to val_len. This does not affect the previous documented behavior
since this aspect was not documented. This does not affect current
usage in Mbed TLS's X.509 module where calls with the same OID always
use the same size for the associated value.
2019-09-11 15:46:45 +02:00
Gilles Peskine
1dbab67ce8 Improve mbedtls_asn1_write_int to support values >255
mbedtls_asn1_write_int had an undocumented restriction to values that
fit in a single octet. Fix this.

Negative integers are still not supported.
2019-09-11 15:46:45 +02:00
Gilles Peskine
e40d1207eb mbedtls_asn1_get_bitstring_null: fix rejection of short inputs
Fix improper rejection of bitstrings with length less than 2.
2019-09-11 15:46:44 +02:00
Gilles Peskine
f7d6acd475 mbedtls_asn1_get_int: allow leading zeros properly
Allow any number of leading zeros, not just based on sizeof(int).
2019-09-11 15:46:44 +02:00
Jaeden Amero
cc5aeee278
Merge pull request #248 from RonEld/stack_overflow_in_hmac_fix
Fix a buffer overflow in hmac_setup_internal
2019-09-11 13:55:18 +01:00
Jaeden Amero
18c7b9fdaa
Merge pull request #210 from tempesta-tech/extra-mbedtls_ecp_group_free
Remove extra mbedtls_ecp_group_free()
2019-09-10 18:51:43 +01:00
Jaeden Amero
9298dca14d
Merge pull request #185 from gilles-peskine-arm/harvard-md
Remove method dispatch from md
2019-09-10 18:38:39 +01:00
Alexander K
56a74cdcc9 Replace 0 by MBEDTLS_ECP_DP_NONE to avoid IAR compiler complains 2019-09-10 17:58:20 +03:00
Ron Eldor
296eca6e76 Fix a buffer overflow in hmac_setup_internal
At the end of `psa_hmac_setup_internal()`, the ipad is cleared.
However, the size that was given to clear was `key_len` which is larger
than the size of `ipad`.
2019-09-10 15:21:37 +03:00
Jaeden Amero
92348d1c49 Merge remote-tracking branch 'crypto/development' into development-restricted
* crypto/development: (77 commits)
  all.sh: disable MEMORY_BUFFER_ALLOC in cmake asan build
  Unify gcc and clang cmake flags to test with UBsan
  Add an input check in psa_its_set
  Remove storage errors from psa_generate_random
  Update getting_started.md
  Update based on Jaeden's comments.
  Update getting_started.md
  Fix return code warnings
  Update getting_started.md
  Fix warnings
  Add PSA_ERROR_STORAGE_FAILURE to psa_cipher_generate_iv
  Remove errorneous insert
  Add STORAGE_FAILURE everywhere + add missing codes
  Add storage failure to psa_mac_verify_finish
  Add storage failure to psa_mac_sign_finish
  Add PSA_ERROR_STORAGE_FAILURE to psa_aead_*_setup functions
  Added PSA_ERROR_BAD_STATE to functions with operations
  Added extra bad state case to psa_hash_setup
  Add missing return codes to psa_generate_key
  Add PSA_ERROR_BUFFER_TOO_SMALL to psa_mac_compute
  ...
2019-09-06 08:56:21 +01:00
Alexander K
77233ec411 Fix misprint 2019-09-05 21:37:39 +03:00
Jaeden Amero
595643c514
Merge pull request #222 from jainvikas8/zeroize-check
Check for zero length and NULL buffer pointer.
2019-09-05 17:35:40 +01:00
Jaeden Amero
c12cb5236b
Merge pull request #239 from AndrzejKurek/psa-its-file-fixes
Remove a potential call to fwrite with null buffer. Add UBsan testing
2019-09-05 16:40:08 +01:00
Jaeden Amero
826907736f Merge remote-tracking branch 'origin/pr/2623' into development
* origin/pr/2623:
  Adapt ChangeLog
  Fix mpi_bigendian_to_host() on bigendian systems
2019-09-05 14:43:46 +01:00
Andrzej Kurek
dc22d8d022 Add an input check in psa_its_set 2019-09-05 09:34:34 -04:00
Darryl Green
5e843fa133 Use safer deterministic function in psa_ecdsa_sign 2019-09-05 14:06:34 +01:00
Janos Follath
896a294211 Correct deterministic ECDSA behavior
We were still reusing the internal HMAC-DRBG of the deterministic ECDSA
for blinding. This meant that with cryptographically low likelyhood the
result was not the same signature as the one the deterministic ECDSA
algorithm has to produce (however it is still a valid ECDSA signature).

To correct this we seed a second HMAC-DRBG with the same seed to restore
correct behavior. We also apply a label to avoid reusing the bits of the
ephemeral key for a different purpose and reduce the chance that they
leak.

This workaround can't be implemented in the restartable case without
penalising the case where external RNG is available or completely
defeating the purpose of the restartable feature, therefore in this case
the small chance of incorrect behavior remains.
2019-09-05 11:18:58 +01:00
Janos Follath
e65e0597a8 Deprecate the old deterministic ECDSA function
The current interface does not allow passing an RNG, which is needed for
blinding. Using the scheme's internal HMAC-DRBG results the same
blinding values for the same key and message, diminishing the
effectiveness of the countermeasure. A new function
`mbedtls_ecdsa_det_ext` is available to address this problem.
2019-09-05 11:18:58 +01:00
Janos Follath
dca667ac80 Add a safer deterministic ECDSA function
`mbedtls_ecdsa_sign_det` reuses the internal HMAC-DRBG instance to
implement blinding. The advantage of this is that the algorithm is
deterministic too, not just the resulting signature. The drawback is
that the blinding is always the same for the same key and message.
This diminishes the efficiency of blinding and leaks information about
the private key.

A function that takes external randomness fixes this weakness.
2019-09-05 11:18:58 +01:00
Jaeden Amero
c04305f036 Merge remote-tracking branch 'crypto/development' into development-restricted
* crypto/development: (863 commits)
  crypto_platform: Fix typo
  des: Reduce number of self-test iterations
  Fix -O0 build for Aarch64 bignum multiplication.
  Make GNUC-compatible compilers use the right mbedtls_t_udbl again on Aarch64 builds.
  Add optimized bignum multiplication for Aarch64.
  Enable 64-bit limbs for all Aarch64 builds.
  HMAC DRBG: Split entropy-gathering requests to reduce request sizes
  psa: Use application key ID where necessary
  psa: Adapt set_key_id() for when owner is included
  psa: Add PSA_KEY_ID_INIT
  psa: Don't duplicate policy initializer
  crypto_extra: Use const seed for entropy injection
  getting_started: Update for PSA Crypto API 1.0b3
  Editorial fixes.
  Cross reference 'key handles' from INVALID_HANDLE
  Update documentation for psa_destroy_key
  Update documentation for psa_close_key
  Update psa_open_key documentation
  Remove duplicated information in psa_open_key
  Initialize key bits to max size + 1 in psa_import_key
  ...
2019-09-05 11:11:38 +01:00
Jaeden Amero
8096969905
Merge pull request #139 from Patater/des-faster-and-typo-fix
Make DES self-test faster, and fix a typo
2019-09-04 12:18:39 +01:00
Vikas Katariya
52fa174a5a Check for zero length and NULL buffer pointer.
In reference to issue https://github.com/ARMmbed/mbed-crypto/issues/49
2019-09-04 11:31:35 +01:00
Jaeden Amero
f66e7ea7f3
Merge pull request #178 from mpg/sha512-smaller
New config.h option to make SHA-512 smaller
2019-09-04 10:19:28 +01:00
Jaeden Amero
355b4b0c25 des: Reduce number of self-test iterations
Tiny slow processors take a long time to go through 10,000 iterations.
Try with 100 iterations instead.

Fixes https://github.com/ARMmbed/mbedtls/issues/807
2019-09-04 10:11:45 +01:00
Jaeden Amero
481659a9c0 Merge remote-tracking branch 'origin/development' into development-restricted
* origin/development:
  Fix uninitialized variable in x509_crt
  Add a ChangeLog entry for mbedtls_net_close()
  Added mbedtls_net_close and use it in ssl_fork_server to correctly disassociate the client socket from the parent process and the server socket from the child process.
  Add ChangeLog entry
  fix memory leak in mpi_miller_rabin()
2019-09-03 19:42:19 +01:00
Jaeden Amero
3d7005f851 Merge remote-tracking branch 'tls/pr/2363' into development
* origin/pr/2363:
  Add ChangeLog entry
  fix memory leak in mpi_miller_rabin()
2019-09-03 19:32:45 +01:00
Jaeden Amero
8dd6bc7ac4 Merge remote-tracking branch 'origin/pr/2803' into development
* origin/pr/2803:
  Add a ChangeLog entry for mbedtls_net_close()
  Added mbedtls_net_close and use it in ssl_fork_server to correctly disassociate the client socket from the parent process and the server socket from the child process.
2019-09-03 16:41:51 +01:00
Jaeden Amero
3f0fc38735 Merge remote-tracking branch 'origin/pr/2795' into development
* origin/pr/2795:
  Fix uninitialized variable in x509_crt
2019-09-03 16:33:59 +01:00
Jaeden Amero
4cf0e7e4d2 Merge remote-tracking branch 'origin/development' into development-restricted
* origin/development: (42 commits)
  Handle deleting non-existant files on Windows
  Update submodule
  Use 3rdparty headers from the submodule
  Add Everest components to all.sh
  3rdparty: Add config checks for Everest
  Fix macros in benchmark.c
  Update generated files
  3rdparty: Fix inclusion order of CMakeLists.txt
  Fix trailing whitespace
  ECDH: Fix inclusion of platform.h for proper use of MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED
  ECDH: Fix use of ECDH API in full handshake benchmark
  ECDH: Removed unnecessary calls to mbedtls_ecp_group_load in ECDH benchmark
  ECDH: Fix Everest x25519 make_public
  Fix file permissions
  3rdparty: Rename THIRDPARTY_OBJECTS
  3rdparty: Update description of MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED
  3rdparty: Fix Makefile coding conventions
  ECDSA: Refactor return value checks for mbedtls_ecdsa_can_do
  Add a changelog entry for Everest ECDH (X25519)
  Document that curve lists can include partially-supported curves
  ...
2019-08-30 16:24:18 +01:00
Jaeden Amero
49fcbeab14 Merge remote-tracking branch 'origin/pr/2799' into development
Manually edit ChangeLog to ensure correct placement of ChangeLog notes.

* origin/pr/2799: (42 commits)
  Handle deleting non-existant files on Windows
  Update submodule
  Use 3rdparty headers from the submodule
  Add Everest components to all.sh
  3rdparty: Add config checks for Everest
  Fix macros in benchmark.c
  Update generated files
  3rdparty: Fix inclusion order of CMakeLists.txt
  Fix trailing whitespace
  ECDH: Fix inclusion of platform.h for proper use of MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED
  ECDH: Fix use of ECDH API in full handshake benchmark
  ECDH: Removed unnecessary calls to mbedtls_ecp_group_load in ECDH benchmark
  ECDH: Fix Everest x25519 make_public
  Fix file permissions
  3rdparty: Rename THIRDPARTY_OBJECTS
  3rdparty: Update description of MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED
  3rdparty: Fix Makefile coding conventions
  ECDSA: Refactor return value checks for mbedtls_ecdsa_can_do
  Add a changelog entry for Everest ECDH (X25519)
  Document that curve lists can include partially-supported curves
  ...
2019-08-30 15:50:45 +01:00
Darryl Green
9b9a790be6 Handle deleting non-existant files on Windows
If we try to delete a non-existant file using del on Windows, as
can happen when running make clean, del will throw an error. Make
the Makefiles more robust by only deleting files if they exist.
2019-08-30 15:45:46 +01:00
Jaeden Amero
d031378ff5 Merge remote-tracking branch 'origin/development' into development-restricted
* origin/development:
  Update library version to 2.19.0
  ssl-opt.sh: Add var's of context s11n tests for ChaChaPoly,CCM,GCM
  ssl-opt.sh: Duplicate context serialization tests for CID
  Fix SSL context deserialization
2019-08-30 15:30:58 +01:00
Jaeden Amero
379964a7b6 Merge remote-tracking branch 'origin/pr/2814' into development
* origin/pr/2814:
  Update library version to 2.19.0
2019-08-30 14:40:57 +01:00
Darryl Green
fe997c646b Update library version to 2.19.0 2019-08-30 13:02:16 +01:00
Andy Gross
1f62714db8 Fix uninitialized variable in x509_crt
This patch fixes an issue we encountered with more stringent compiler
warnings.  The signature_is_good variable has a possibility of being
used uninitialized.  This patch moves the use of the variable to a
place where it cannot be used while uninitialized.

Signed-off-by: Andy Gross <andy.gross@linaro.org>
2019-08-30 14:48:36 +03:00
Jaeden Amero
822b8f65bd
Merge pull request #238 from hanno-arm/hmac_drbg_entropy_incompatibility_fix-crypto
HMAC DRBG: Split entropy-gathering requests to reduce request sizes
2019-08-30 12:15:16 +01:00
Hanno Becker
361b10d1c4 Fix SSL context deserialization
The SSL context maintains a set of 'out pointers' indicating the
address at which to write the header fields of the next outgoing
record. Some of these addresses have a static offset from the
beginning of the record header, while other offsets can vary
depending on the active record encryption mechanism: For example,
if an explicit IV is in use, there's an offset between the end
of the record header and the beginning of the encrypted data to
allow the explicit IV to be placed in between; also, if the DTLS
Connection ID (CID) feature is in use, the CID is part of the
record header, shifting all subsequent information (length, IV, data)
to the back.
When setting up an SSL context, the out pointers are initialized
according to the identity transform + no CID, and it is important
to keep them up to date whenever the record encryption mechanism
changes, which is done by the helper function ssl_update_out_pointers().

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

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

Extending test coverage is left for a separate commit.
2019-08-30 12:14:25 +01:00
Hanno Becker
a823d4c7f0 HMAC DRBG: Split entropy-gathering requests to reduce request sizes
According to SP800-90A, the DRBG seeding process should use a nonce
of length `security_strength / 2` bits as part of the DRBG seed. It
further notes that this nonce may be drawn from the same source of
entropy that is used for the first `security_strength` bits of the
DRBG seed. The present HMAC DRBG implementation does that, requesting
`security_strength * 3 / 2` bits of entropy from the configured entropy
source in total to form the initial part of the DRBG seed.

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

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

Fixes #237.
2019-08-30 11:16:24 +01:00
Janos Follath
4f055f4ca2 Use 3rdparty headers from the submodule 2019-08-29 16:12:38 +01:00
Christoph M. Wintersteiger
54d09ad0df 3rdparty: Rename THIRDPARTY_OBJECTS 2019-08-29 16:12:38 +01:00
Christoph M. Wintersteiger
655ddababa 3rdparty: Add additional build facilities for 3rd-party code 2019-08-29 16:12:38 +01:00
Christoph M. Wintersteiger
89f36aeb2a Add new 3rdparty build scripts 2019-08-29 16:12:38 +01:00
Christoph M. Wintersteiger
e14c779615 ECDH: Everest: Remove unnecessary file 2019-08-29 16:12:38 +01:00
Christoph M. Wintersteiger
f4bee2fbf7 ECDH: Use LOCAL_CFLAGS instead of CFLAGS 2019-08-29 16:12:38 +01:00
Christoph M. Wintersteiger
977d89ab29 ECDH: Include Everest Curve25519 in build scripts 2019-08-29 16:12:38 +01:00
Jaeden Amero
f0716542c4
Merge pull request #140 from yanesca/everest_integration
Everest integration
2019-08-29 16:02:49 +01:00
Jaeden Amero
64f264332f Merge remote-tracking branch 'origin/development' into development-restricted
* origin/development:
  Update the crypto submodule
  Use multipart PSA key derivation API
  platform: Include stdarg.h where needed
  Update Mbed Crypto to contain mbed-crypto#152
  CMake: Add a subdirectory build regression test
  README: Enable builds as a CMake subproject
  ChangeLog: Enable builds as a CMake subproject
  Remove use of CMAKE_SOURCE_DIR
  Update library version to 2.18.0
2019-08-29 14:14:05 +01:00
Jaeden Amero
98d5685b70
Merge pull request #232 from Patater/psa-crypto-api-1.0b3
Make fixes related to using Mbed Crypto as a service
2019-08-29 13:50:10 +01:00
Jaeden Amero
3ec504738e Merge remote-tracking branch 'origin/pr/2807' into development
* origin/pr/2807:
  platform: Include stdarg.h where needed
  Update Mbed Crypto to contain mbed-crypto#152
  CMake: Add a subdirectory build regression test
  README: Enable builds as a CMake subproject
  ChangeLog: Enable builds as a CMake subproject
  Remove use of CMAKE_SOURCE_DIR
  Update library version to 2.18.0
2019-08-29 12:24:47 +01:00
Jaeden Amero
21db2a94a4
Merge pull request #229 from k-stachowiak/IOTCRYPT-791-remove-legacy-psa-key-derivation
Remove legacy psa key derivation
2019-08-29 11:31:23 +01:00
Jaeden Amero
6fa62a5b8f psa: Use application key ID where necessary
Avoid compiler errors when MBEDTLS_PSA_CRYPTO_KEY_FILE_ID_ENCODES_OWNER
is set by using the application ID type.

    [Error] psa_crypto_slot_management.c@175,9: used type 'psa_key_id_t' (aka 'psa_key_file_id_t') where arithmetic or pointer type is required
2019-08-28 17:24:27 +01:00
Jaeden Amero
932e496ef5
Merge pull request #224 from tempesta-tech/development
Remove unused TG variable in mbedtls_mpi_gcd()
2019-08-27 12:05:21 +01:00
Jaeden Amero
4e0db5642a Merge branch 'mbedtls-2.18' into development
Bring Mbed TLS 2.18.0 and 2.18.1 release changes back into the
development branch. We had branched to release 2.18.0 and 2.18.1 in
order to allow those releases to go out without having to block work on
the `development` branch.

Manually resolve conflicts in the Changelog by moving all freshly addded
changes to a new, unreleased version entry.

Reject changes to include/mbedtls/platform.h made in the mbedtls-2.18
branch, as that file is now sourced from Mbed Crypto.

* mbedtls-2.18:
  platform: Include stdarg.h where needed
  Update Mbed Crypto to contain mbed-crypto#152
  CMake: Add a subdirectory build regression test
  README: Enable builds as a CMake subproject
  ChangeLog: Enable builds as a CMake subproject
  Remove use of CMAKE_SOURCE_DIR
  Update library version to 2.18.0
2019-08-27 11:18:28 +01:00
Jaeden Amero
f1cdceae0d Merge remote-tracking branch 'origin/development' into development-restricted
* origin/development: (114 commits)
  Don't redefine calloc and free
  Add changelog entry to record checking
  Fix compiler warning
  Add debug messages
  Remove duplicate entries from ChangeLog
  Fix parameter name in doxygen
  Add missing guards for mac usage
  Improve reability and debugability of large if
  Fix a typo in a comment
  Fix MSVC warning
  Fix compile error in reduced configurations
  Avoid duplication of session format header
  Implement config-checking header to context s11n
  Provide serialisation API only if it's enabled
  Fix compiler warning: comparing signed to unsigned
  Actually reset the context on save as advertised
  Re-use buffer allocated by handshake_init()
  Enable serialisation tests in ssl-opt.sh
  Change requirements for setting timer callback
  Add setting of forced fields when deserializing
  ...
2019-08-27 10:09:10 +01:00
Jaeden Amero
85c78b48a9
Merge pull request #225 from RonEld/iotssl_2739
Remove a redundant function call
2019-08-23 17:43:58 +01:00
Jarno Lamsa
b7b486cfd1 Fix compiler warning
Fix a compiler warning when MBEDTLS_SHA512_C isn't defined.
2019-08-23 13:11:31 +03:00
Jarno Lamsa
8c51b7cd94 Add debug messages
Add debug messages to easier identify which condition fails
with usage restrictions in mbedtls_ssl_context_save()
2019-08-23 13:11:31 +03:00
Jarno Lamsa
c84bd24224 Add missing guards for mac usage
There were couple of cases where guards were missing when
no ciphersuites are using mac.
2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
e458869b3f Improve reability and debugability of large if
Breaking into a series of statements makes things easier when stepping through
the code in a debugger.

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

Also expand a bit on the reasons for these restrictions.
2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
4ca930f8b9 Fix a typo in a comment 2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
f041f4e19c Fix MSVC warning
We know the length of the ALPN string is always less than 255, so the cast to
uint8_t is safe.
2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
9a96fd7ac3 Fix compile error in reduced configurations
Found by running scripts/baremetal.h --rom --gcc --check after adding
MBEDTLS_SSL_CONTEXT_SERIALIZATION to baremetal.h
2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
45ac1f0c92 Avoid duplication of session format header 2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
4e9370ba91 Implement config-checking header to context s11n
Modelled after the config-checking header from session s11n.

The list of relevant config flags was established by manually checking the
fields serialized in the format, and which config.h flags they depend on.
This probably deserves double-checking by reviewers.
2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
5c0e377532 Provide serialisation API only if it's enabled 2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
5ea13b854a Fix compiler warning: comparing signed to unsigned
Since the type of cid_len is unsigned but shorter than int, it gets
"promoted" to int (which is also the type of the result), unless we make the
other operand an unsigned int which then forces the expression to unsigned int
as well.
2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
9df5a82079 Actually reset the context on save as advertised
Also fix some wording in the documentation while at it.
2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
142ba736d9 Re-use buffer allocated by handshake_init()
This fixes a memory leak as well (found by running ssl-opt.sh in an Asan
build).
2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
0eb3eac023 Add setting of forced fields when deserializing 2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
c86c5df081 Add saved fields from top-level structure 2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
c2a7b891a1 Add transform (de)serialization 2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
b9dfc9fd30 Fix English in comments 2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
4b7e6b925f Add session saving/loading
For now, the header (version+format bytes) is duplicated. This might be
optimized later.
2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
4c90e858b5 Add (stub) header writing and checking
The number of meaning of the flags will be determined later, when handling the
relevant struct members. For now three bytes are reserved as an example, but
this number may change later.
2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
0ff76407d2 Add usage checks in context_load() 2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
00400c2bf6 Document internal serialisation format
This mainly follows the design document (saving all fields marked "saved" in
the main structure and the transform sub-structure) with two exceptions:

- things related to renegotiation are excluded here (there weren't quite in
  the design document as the possibility of allowing renegotiation was still
on the table, which is no longer is) - also, ssl.secure_renegotiation (which
is not guarded by MBEDTLS_SSL_RENEGOTIATION because it's used in initial
handshakes even with renegotiation disabled) is still excluded, as we don't
need it after the handshake.

- things related to Connection ID are added, as they weren't present at the
  time the design document was written.

The exact format of the header (value of the bitflag indicating compile-time
options, whether and how to merge it with the serialized session header) will
be determined later.
2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
1aaf66940e Implement usage checks in context_save()
Enforce restrictions indicated in the documentation.

This allows to make some simplifying assumptions (no need to worry about
saving IVs for CBC in TLS < 1.1, nor about saving handshake data) and
guarantees that all values marked as "forced" in the design document have the
intended values and can be skipped when serialising.

Some of the "forced" values are not checked because their value is a
consequence of other checks (for example, session_negotiated == NULL outside
handshakes). We do however check that session and transform are not NULL (even
if that's also a consequence of the initial handshake being over) as we're
going to dereference them and static analyzers may appreciate the info.
2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
96fb0ee9cf Save Hello random bytes for later use 2019-08-23 13:11:31 +03:00
Manuel Pégourié-Gonnard
6d8f128790 Fix typos, grammar and wording in documentation 2019-08-23 12:52:29 +03:00
Manuel Pégourié-Gonnard
ac87e28bb2 Declare and document ssl_context_save()/load()
Also introduce stub definitions so that things compile and link.
2019-08-23 12:52:29 +03:00
Manuel Pégourié-Gonnard
afa8f71700 Add new config MBEDTLS_SSL_CONTEXT_SERIALIZATION
This is enabled by default as we generally enable things by default unless
there's a reason not to (experimental, deprecated, security risk).

We need a compile-time option because, even though the functions themselves
can be easily garbage-collected by the linker, implementing them will require
saving 64 bytes of Client/ServerHello.random values after the handshake, that
would otherwise not be needed, and people who don't need this feature
shouldn't have to pay the price of increased RAM usage.
2019-08-23 12:52:29 +03:00
Hanno Becker
be34e8e9c0 Remove reference to outdated compile-time option 2019-08-23 12:51:21 +03:00
Hanno Becker
f9b3303eb9 Introduce specific error for ver/cfg mismatch on deserialization
This commit introduces a new SSL error code

  `MBEDTLS_ERR_SSL_VERSION_MISMATCH`

which can be used to indicate operation failure due to a
mismatch of version or configuration.

It is put to use in the implementation of `mbedtls_ssl_session_load()`
to signal the attempt to de-serialize a session which has been serialized
in a build of Mbed TLS using a different version or configuration.
2019-08-23 12:51:21 +03:00
Hanno Becker
3e08866e06 Use def'n consts for bits in config-identifier of serialized data 2019-08-23 12:51:21 +03:00
Hanno Becker
dc28b6c5e1 Note that ver+fmt bytes in serialized data must not be removed 2019-08-23 12:51:21 +03:00
Hanno Becker
50b596666d Improve doc'n of config-identifying bitfield in serialized session 2019-08-23 12:51:21 +03:00
Hanno Becker
f37d91830a Session serialization: Fail with BAD_INPUT_DATA if buffer too small 2019-08-23 12:51:21 +03:00
Hanno Becker
94ef3b35f4 Encode relevant parts of the config in serialized session header
This commit makes use of the added space in the session header to
encode the state of those parts of the compile-time configuration
which influence the structure of the serialized session in the
present version of Mbed TLS. Specifically, these are
- the options which influence the presence/omission of fields
  from mbedtls_ssl_session (which is currently shallow-copied
  into the serialized session)
- the setting of MBEDTLS_X509_CRT_PARSE_C, which determines whether
  the serialized session contains a CRT-length + CRT-value pair after
  the shallow-copied mbedtls_ssl_session instance.
- the setting of MBEDTLS_SSL_SESSION_TICKETS, which determines whether
  the serialized session contains a session ticket.
2019-08-23 12:51:21 +03:00
Hanno Becker
f878707b8f Add configuration identifier to serialized SSL sessions
This commit adds space for two bytes in the header of serizlied
SSL sessions which can be used to determine the structure of the
remaining serialized session in the respective version of Mbed TLS.

Specifically, if parts of the session depend on whether specific
compile-time options are set or not, the setting of these options
can be encoded in the added space.

This commit doesn't yet make use of the fields.
2019-08-23 12:51:21 +03:00
Hanno Becker
a835da5cb1 Add Mbed TLS version to SSL sessions
The format of serialized SSL sessions depends on the version and the
configuration of Mbed TLS; attempts to restore sessions established
in different versions and/or configurations lead to undefined behaviour.

This commit adds an 3-byte version header to the serialized session
generated and cleanly fails ticket parsing in case a session from a
non-matching version of Mbed TLS is presented.
2019-08-23 12:51:21 +03:00
Manuel Pégourié-Gonnard
f743c03ea7 Add new ABI-independent format for serialization 2019-08-23 12:50:17 +03:00
Manuel Pégourié-Gonnard
51a0bfd9bc Fix bug in cert digest serialisation
This bug was present since cert digest had been introduced, which highlights
the need for testing.

While at it, fix a bug in the comment explaining the format - this was
introduced by me copy-pasting to hastily from current baremetal, that has a
different format (see next PR in the series for the same in development).
2019-08-23 12:48:41 +03:00
Manuel Pégourié-Gonnard
686adb4d54 Normalize spelling to serialiZation
We have explicit recommendations to use US spelling for technical writing, so
let's apply this to code as well for uniformity. (My fingers tend to prefer UK
spelling, so this needs to be fixed in many places.)

sed -i 's/\([Ss]eriali\)s/\1z/g' **/*.[ch] **/*.function **/*.data ChangeLog
2019-08-23 12:48:41 +03:00
Manuel Pégourié-Gonnard
a3d831b9e6 Add test for session_load() from small buffers
This uncovered a bug that led to a double-free (in practice, in general could
be free() on any invalid value): initially the session structure is loaded
with `memcpy()` which copies the previous values of pointers peer_cert and
ticket to heap-allocated buffers (or any other value if the input is
attacker-controlled). Now if we exit before we got a chance to replace those
invalid values with valid ones (for example because the input buffer is too
small, or because the second malloc() failed), then the next call to
session_free() is going to call free() on invalid pointers.

This bug is fixed in this commit by always setting the pointers to NULL right
after they've been read from the serialised state, so that the invalid values
can never be used.

(An alternative would be to NULL-ify them when writing, which was rejected
mostly because we need to do it when reading anyway (as the consequences of
free(invalid) are too severe to take any risk), so doing it when writing as
well is redundant and a waste of code size.)

Also, while thinking about what happens in case of errors, it became apparent
to me that it was bad practice to leave the session structure in an
half-initialised state and rely on the caller to call session_free(), so this
commit also ensures we always clear the structure when loading failed.
2019-08-23 12:48:41 +03:00
Manuel Pégourié-Gonnard
26f982f50e Improve save API by always updating olen
This allows callers to discover what an appropriate size is. Otherwise they'd
have to either try repeatedly, or allocate an overly large buffer (or some
combination of those).

Adapt documentation an example usage in ssl_client2.
2019-08-23 12:48:41 +03:00
Manuel Pégourié-Gonnard
b5e4e0a395 Add mbedtls_ssl_get_session_pointer()
Avoid useless copy with mbedtls_ssl_get_session() before serialising.

Used in ssl_client2 for testing and demonstrating usage, but unfortunately
that means mbedtls_ssl_get_session() is no longer tested, which will be fixed
in the next commit.
2019-08-23 12:48:41 +03:00
Manuel Pégourié-Gonnard
35eb802103 Add support for serialisation session with ticket
On client side, this is required for the main use case where of serialising a
session for later resumption, in case tickets are used.

On server side, this doesn't change much as ticket_len will always be 0.

This unblocks testing the functions by using them in ssl_client2, which will
be done in the next commit.
2019-08-23 12:48:41 +03:00
Manuel Pégourié-Gonnard
a3e7c65101 Move session save/load function to ssl_tls.c
This finishes making these functions public. Next step is to get them tested,
but there's currently a blocker for that, see next commit (and the commit
after it for tests).
2019-08-23 12:48:41 +03:00
Manuel Pégourié-Gonnard
8faa70e810 Use more specific name in debug message for testing
While 'session hash' is currently unique, so suitable to prove that the
intended code path has been taken, it's a generic enough phrase that in the
future we might add other debug messages containing it in completely unrelated
code paths. In order to future-proof the accuracy of the test, let's use a
more specific string.
2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
d91efa47c0 Fix alignment issues 2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
47e33e11f7 Clarify comment about TLS versions
The previous comment used "TLS" as a shortcut for "TLS 1.0/1.1" which was
confusing. This partially reflected the names of the calc_verify/finished that
go ssl, tls (for 1.0/1.1) tls_shaxxx (for 1.2), but still it's clearer to be
explicit in the comment - and perhaps in the long term the function names
could be clarified instead.
2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
7fa1407adb Remove redundant debug message.
Two consecutive messages (ie no branch between them) at the same level are not
needed, so only keep the one that has the most information.
2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
6fa57bfae5 Remove 'session' input from populate_tranform()
When using this function to deserialize, it's not a problem to have a session
structure as input as we'll have one around anyway (most probably freshly
deserialised).

However for tests it's convenient to be able to build a transform without
having a session structure around.

Also, removing this structure from parameters makes the function signature
more uniform, the only exception left being the ssl param at the end that's
hard to avoid for now.
2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
31d3ef11f5 Fix typo in comment 2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
a7505d18eb Enforce promise to not use whole ssl context
Configs with no DEBUG_C are used for example in test-ref-configs.pl, which also
runs parts of compat.sh or ssl-opt.sh on them, so the added 'ssl = NULL'
statements will be exercised in those tests at least.
2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
c864f6a209 Partially rm 'ssl' input from populate_transform() 2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
9b108c242d Remove "handshake" input from populate_transform() 2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
344460c913 Work around bug in key exporter API
https://github.com/ARMmbed/mbedtls/issues/2759
2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
cba40d92bd Start refining parameters of populate_transform()
Parameters 'handshake' and 'ssl' will be replaced with more fine-grained
inputs in follow-up commits.
2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
d73b47fe2e Move compress_buf allocation to derive_keys 2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
040a9517b5 Move handling of randbytes to derive_keys() 2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
de718b99b5 Make calc_verify() return the length as well
Simplifies ssl_compute_hash(), but unfortunately not so much the other uses.
2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
0d56aaac7b Constify ssl_context param of calc_verify() 2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
de047adfb4 Improve signature of ssl_compute_master()
Make it more explicit what's used. Unfortunately, we still need ssl as a
parameter for debugging, and because calc_verify wants it as a parameter (for
all TLS versions except SSL3 it would actually only need handshake, but SSL3
also accesses session_negotiate).

It's also because of calc_verify that we can't make it const yet, but see next
commit.
2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
85680c49ef Reduce indentation in ssl_compute_master()
Exit earlier when there's noting to do.

For a small diff, review with 'git show -w'.
2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
9951b712bd Start extracting ssl_compute_master()
For now just moving code around, not changing indentation. Calling convention
and signature are going to be adjusted in upcoming commits.
2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
8d2805c784 Fix signature of ssl_set_transform_prfs() 2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
1b00c4f5b3 Start extraction ssl_set_handshake_prfs()
For now just moving code around, will improve signature in the next commit.
2019-08-23 12:45:33 +03:00
Manuel Pégourié-Gonnard
e59ae23868 Start splitting populate_transform() out of derive_keys()
This is currently a dummy, just introducing the new name.
2019-08-23 12:45:33 +03:00
Robert Larsen
df8e511381 Added mbedtls_net_close and use it in ssl_fork_server to correctly
disassociate the client socket from the parent process and the server
socket from the child process.
2019-08-23 10:57:03 +02:00
Jaeden Amero
833899ee37 Merge remote-tracking branch 'origin/development' into development-restricted
* origin/development: (51 commits)
  Fix possibly-lossy conversion warning from MSVC
  Reintroduce length 0 check for records
  Don't use memcpy() for 2-byte copy operation
  Remove integer parsing macro
  Fix alignment in record header parsing routine
  Don't disallow 'record from another epoch' log msg in proxy ref test
  Make sure 'record from another epoch' is displayed for next epoch
  Implement record checking API
  Mark ssl_parse_record_header() as `const` in SSL context
  Make mbedtls_ssl_in_hdr_len() CID-unaware
  Remove duplicate setting of ssl->in_msgtype and ssl->in_msglen
  Move update of in_xxx fields in ssl_get_next_record()
  Move update of in_xxx fields outside of ssl_prepare_record_content()
  Reduce dependency of ssl_prepare_record_content() on in_xxx fields
  Move ssl_update_in_pointers() to after record hdr parsing
  Mark DTLS replay check as `const` on the SSL context
  Move updating the internal rec ptrs to outside of rec hdr parsing
  Mark ssl_decrypt_buf() as `const in the input SSL context
  Adapt ssl_prepare_record_content() to use SSL record structure
  Use record length from record structure when fetching content in TLS
  ...
2019-08-22 17:10:45 +01:00
Jaeden Amero
beec142010 Merge remote-tracking branch 'origin/pr/2790' into development
* origin/pr/2790: (40 commits)
  Fix possibly-lossy conversion warning from MSVC
  Reintroduce length 0 check for records
  Don't use memcpy() for 2-byte copy operation
  Remove integer parsing macro
  Fix alignment in record header parsing routine
  Don't disallow 'record from another epoch' log msg in proxy ref test
  Make sure 'record from another epoch' is displayed for next epoch
  Implement record checking API
  Mark ssl_parse_record_header() as `const` in SSL context
  Make mbedtls_ssl_in_hdr_len() CID-unaware
  Remove duplicate setting of ssl->in_msgtype and ssl->in_msglen
  Move update of in_xxx fields in ssl_get_next_record()
  Move update of in_xxx fields outside of ssl_prepare_record_content()
  Reduce dependency of ssl_prepare_record_content() on in_xxx fields
  Move ssl_update_in_pointers() to after record hdr parsing
  Mark DTLS replay check as `const` on the SSL context
  Move updating the internal rec ptrs to outside of rec hdr parsing
  Mark ssl_decrypt_buf() as `const in the input SSL context
  Adapt ssl_prepare_record_content() to use SSL record structure
  Use record length from record structure when fetching content in TLS
  ...
2019-08-22 11:09:15 +01:00
Jaeden Amero
9a09f511b5 Merge remote-tracking branch 'origin/pr/2781' into development
* origin/pr/2781:
  Documentation fixes according to review
  Remove unused label in ssl_client2/ssl_server2
  Add missing word in documentation of mbedtls_ssl_check_record()
  cli/srv ex: Add dbg msg if record checking gives inconsistent result
  Fix minor issues in documentation of mbedtls_ssl_check_record()
  State that record checking is DTLS only and doesn't check content type
  Update version_features.c
  Pass dgrams to mbedtls_ssl_check_record in ssl_client2/server2
  Add IO wrappers to ssl_server2 as interm's between NET and SSL layer
  Add IO wrappers to ssl_client2 as interm's between NET and SSL layer
  Introduce configuration option and API for SSL record checking
2019-08-22 11:08:52 +01:00
Darryl Green
0892d0fbbf Initialize key bits to max size + 1 in psa_import_key
In psa_import_key, the key bits value was uninitialized before
calling the secure element driver import function. There is a
potential issue if the driver returns PSA_SUCCESS without setting
the key bits. This shouldn't happen, but shouldn't be discounted
either, so we initialize the key bits to an invalid issue.
2019-08-21 16:56:16 +01:00
Darryl Green
572a16e694 Merge branch 'psa-api-1.0-beta' into api-to-development 2019-08-21 10:31:12 +01:00
Jaeden Amero
4245d4a2c8 Merge branch 'development' into development-restricted
* development:
  Rename local variables
  Update submodule
  Update Visual studio project file
  Move the examples to PSA 1.0
  Use psa_raw_key_agreement
  Remove calls to psa_allocate_key
  Make variable naming consistent
  Update psa_create_key to PSA 1.0
  Update psa_import_key to PSA 1.0
  Update psa_generator_abort to PSA 1.0
  Update psa_generator_read to PSA 1.0
  Update psa_crypto_generator_t to PSA 1.0
  Update psa_key_agreement to PSA 1.0
  Update GENERATOR_INIT macro to PSA 1.0
  Update KEYPAIR macros to PSA 1.0
2019-08-20 10:28:14 +01:00
Christoph M. Wintersteiger
c25df6848b Fix code style 2019-08-19 13:37:46 +01:00
Christoph M. Wintersteiger
2c69d10bac 3rdparty: Adjust use of Everest in ecp_supported_curves 2019-08-19 13:37:46 +01:00
Christoph M. Wintersteiger
bfc8eb2b78 Revert "ECDH: Fix memory leaks due to context re-initialization"
This reverts commit 2340f03c597b923c0f427c76b4c3d2cd11638410.
2019-08-19 13:37:46 +01:00
Christoph M. Wintersteiger
d8c45d5550 Revert "ECDH: Fix context initialization"
This reverts commit 4a43d14146220e8550d6ad87cb798f74ce9ee209.
2019-08-19 13:37:46 +01:00
Christoph M. Wintersteiger
30bc9cebda ECDH: Fix context initialization 2019-08-19 13:37:46 +01:00
Christoph M. Wintersteiger
2f563e3482 ECDH: Fix memory leaks due to context re-initialization 2019-08-19 13:37:46 +01:00
Christoph M. Wintersteiger
2be66d44a5 ECDH: Remove duplicate lines of code 2019-08-19 13:37:46 +01:00
Christoph M. Wintersteiger
cb31073e1c ECP: add Curve448 to ecp_supported_curves 2019-08-19 13:37:46 +01:00
Christoph M. Wintersteiger
4061f04acd ECDH: Remove unnecessary #include 2019-08-19 13:37:46 +01:00
Christoph M. Wintersteiger
2d4725f204 3rdparty: Rename THIRDPARTY_OBJECTS 2019-08-19 13:37:46 +01:00
Christoph M. Wintersteiger
3ff60bcf1a ECDH/ECDSA: Fix indentation 2019-08-19 13:37:46 +01:00
Gilles Peskine
20b3ef3cad Add mbedtls_ecdh_can_do
All curves can currently do ECDH, but to make the API symmetric and
future-proof, add mbedtls_ecdh_can_do() to go with mbedtls_ecdsa_can_do().
2019-08-19 13:37:46 +01:00
Christoph M. Wintersteiger
6ea2dea1c5 3rdparty: Add additional build facilities for 3rd-party code 2019-08-19 13:37:46 +01:00
Christoph M. Wintersteiger
ea24394c03 ECDH: Fix whitespace and permission problems 2019-08-19 13:36:44 +01:00
Christoph M. Wintersteiger
0082f9df6f ECDSA: Add mbedtls_ecdsa_can_do 2019-08-19 13:36:44 +01:00
Christoph M. Wintersteiger
62dddd08fd Add new 3rdparty build scripts 2019-08-19 13:36:44 +01:00
Christoph M. Wintersteiger
2e724a18a1 ECDH: Fix Everest ECDH side type 2019-08-19 13:36:44 +01:00
Christoph M. Wintersteiger
24fbceff50 ECDH: Everest: Remove unnecessary file 2019-08-19 13:36:44 +01:00
Christoph M. Wintersteiger
34811a8db2 ECDH: Use LOCAL_CFLAGS instead of CFLAGS 2019-08-19 13:36:44 +01:00
Christoph M. Wintersteiger
c3cbddecb5 ECDH: Fix whitespace, permissions 2019-08-19 13:36:44 +01:00
Christoph M. Wintersteiger
4936beb513 ECDH: Clean up the interface to Everest code 2019-08-19 13:36:44 +01:00
Christoph M. Wintersteiger
86e36c4c2b ECDH: Replace hex literal with decimal in ecp.c 2019-08-19 13:36:44 +01:00
Christoph M. Wintersteiger
fba94e9726 ECDH: Fix error code in mbedtls_ecdsa_sign 2019-08-19 13:36:44 +01:00
Christoph M. Wintersteiger
78c9c461cf ECDH: Fix typo in ecdh.c 2019-08-19 13:36:44 +01:00
Christoph M. Wintersteiger
c9f737b4ba ECDH: Enable Everest Curve25519 in ECDH/ECDSA/ECP 2019-08-19 13:36:44 +01:00
Christoph M. Wintersteiger
d5fd766c49 ECDH: Include Everest Curve25519 in build scripts 2019-08-19 13:36:44 +01:00
Ron Eldor
c95d9eedbf Remove a redundant function call
Remove a call to `mbedtls_mpi_bitlen()` since the returned value is
overwritten in the line after. This is redundant since da31fa137a.
Fixes #2377.
2019-08-18 17:24:09 +03:00
k-stachowiak
81053a5584 Use multipart PSA key derivation API 2019-08-17 11:43:35 +02:00
Alexander K
e8ad49f069 Remove unused TG variable in mbedtls_mpi_gcd() 2019-08-16 16:16:07 +03:00
Alexander K
79a11fa0d6 Explicitly nullify grp->id instead of freeing. 2019-08-16 16:10:34 +03:00
Janos Follath
da6ac01963 Rename local variables 2019-08-16 13:47:29 +01:00
Janos Follath
df3b0892ce Use psa_raw_key_agreement
In PSA 1.0 raw key agreement has been moved from
psa_key_derivation_key_agreement() to its own separate function call,
called psa_raw_key_agreement().
2019-08-16 13:37:32 +01:00
Janos Follath
1239d70870 Remove calls to psa_allocate_key
In PSA 1.0 keys are allocated implicitly by other functions
(like psa_import_key) and psa_allocate_key is not needed and does not
exist anymore.
2019-08-16 13:37:32 +01:00
Janos Follath
53b8ec27a2 Make variable naming consistent 2019-08-16 13:37:32 +01:00
Janos Follath
7bb5e6b4da Update psa_create_key to PSA 1.0 2019-08-16 13:37:32 +01:00
Janos Follath
ed73b04c6e Update psa_import_key to PSA 1.0 2019-08-16 13:36:15 +01:00
Janos Follath
bd096101b5 Update psa_generator_abort to PSA 1.0 2019-08-16 11:45:55 +01:00
Janos Follath
6de99db449 Update psa_generator_read to PSA 1.0 2019-08-16 11:45:55 +01:00
Janos Follath
8dee877e8a Update psa_crypto_generator_t to PSA 1.0 2019-08-16 11:45:55 +01:00
Janos Follath
7d7ded85fb Update psa_key_agreement to PSA 1.0 2019-08-16 11:45:55 +01:00
Janos Follath
7374ee6139 Update GENERATOR_INIT macro to PSA 1.0 2019-08-16 11:45:55 +01:00
Janos Follath
3d158ebd2f Update KEYPAIR macros to PSA 1.0 2019-08-16 11:45:53 +01:00
Jaeden Amero
89e7655691 Merge remote-tracking branch 'crypto/pr/212' into development
* crypto/pr/212: (337 commits)
  Make TODO comments consistent
  Fix PSA tests
  Fix psa_generate_random for >1024 bytes
  Add tests to generate more random than MBEDTLS_CTR_DRBG_MAX_REQUEST
  Fix double free in psa_generate_key when psa_generate_random fails
  Fix copypasta in test data
  Avoid a lowercase letter in a macro name
  Correct some comments
  Fix PSA init/deinit in mbedtls_xxx tests when using PSA
  Make psa_calculate_key_bits return psa_key_bits_t
  Adjust secure element code to the new ITS interface
  More refactoring: consolidate attribute validation
  Fix policy validity check on key creation.
  Add test function for import with a bad policy
  Test key creation with an invalid type (0 and nonzero)
  Remove "allocated" flag from key slots
  Take advantage of psa_core_key_attributes_t internally #2
  Store the key size in the slot in memory
  Take advantage of psa_core_key_attributes_t internally: key loading
  Switch storage functions over to psa_core_key_attributes_t
  ...
2019-08-16 11:02:31 +01:00
Jaeden Amero
58f11d010b Merge branch 'development' into development-restricted
* development:
  Update crypto to a repo with latest crypto
  Update Mbed Crypto
  tls: Remove duplicate psa_util.h include
  Remove unused cryptography test files
  Remove crypto C files
  Remove files sourced from Mbed Crypto
  config: Fix Doxygen link to MBEDTLS_PARAM_FAILED
  Use mbedtls-based path for includes
  check-names: Consider crypto-sourced header files
2019-08-16 10:14:40 +01:00
Jaeden Amero
9d20e1f2c4 Merge remote-tracking branch 'tls/development' into development
Resolve conflicts by performing the following actions:
- Reject changes to ChangeLog, as Mbed Crypto doesn't have one
- Reject changes to tests/compat.sh, as Mbed Crypto doesn't have it
- Reject changes to programs/fuzz/onefile.c, as Mbed Crypto doesn't have
  it
- Resolve minor whitespace differences in library/ecdsa.c by taking the
  version from Mbed TLS upstream.

* origin/development:
  Honor MBEDTLS_CONFIG_FILE in fuzz tests
  Test that a shared library build produces a dynamically linked executable
  Test that the shared library build with CMake works
  Add a test of MBEDTLS_CONFIG_FILE
  Exclude DTLS 1.2 only with older OpenSSL
  Document the rationale for the armel build
  Switch armel build to -Os
  Add a build on ARMv5TE in ARM mode
  Add changelog entry for ARM assembly fix
  bn_mul.h: require at least ARMv6 to enable the ARM DSP code
  Adapt ChangeLog
  ECP restart: Don't calculate address of sub ctx if ctx is NULL
2019-08-15 15:49:46 +01:00
Jaeden Amero
922013e46d tls: Remove duplicate psa_util.h include
Don't include psa_util.h twice. It's enough to include it once.
2019-08-15 15:44:50 +01:00
Jaeden Amero
a0aee30644 Remove crypto C files
Remove unused cryptography C files, as these are sourced from Mbed
Crypto now.
2019-08-15 15:44:50 +01:00
Gilles Peskine
4017d882dd Merge remote-tracking branch 'upstream-restricted/development-proposed' into development-restricted-proposed 2019-08-14 18:38:42 +02:00
Gilles Peskine
60b29d6bfd Merge remote-tracking branch 'upstream-restricted/pr/503' into development-restricted-proposed 2019-08-14 18:37:59 +02:00
Manuel Pégourié-Gonnard
7e821b5bcd Fix possibly-lossy conversion warning from MSVC
ssl_tls.c(4876): warning C4267: '=': conversion from 'size_t' to 'uint8_t', possible loss of data
2019-08-14 15:08:09 +01:00
Hanno Becker
d417cc945c Reintroduce length 0 check for records 2019-08-14 15:08:08 +01:00
Hanno Becker
d0b66d08bb Don't use memcpy() for 2-byte copy operation
Manual copying is slightly shorter here.
2019-08-14 15:08:08 +01:00
Hanno Becker
9eca276768 Remove integer parsing macro
If this is introduced, it should be defined in a prominent place
and put to use throughout the library, but this is left for another
time.
2019-08-14 15:08:08 +01:00
Hanno Becker
f5466258b4 Fix alignment in record header parsing routine 2019-08-14 15:08:08 +01:00
Hanno Becker
552f747216 Make sure 'record from another epoch' is displayed for next epoch
The test 'DTLS proxy: delay ChangeCipherSpec' from ssl-opt.sh
relies on this.
2019-08-14 15:08:08 +01:00
Hanno Becker
5422981052 Implement record checking API
This commit implements the record checking API

   mbedtls_ssl_check_record()

on top of the restructured incoming record stack.

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

  ssl_parse_record_header()
  mbedtls_ssl_decrypt_buf()

now operate on instances of the SSL record structure mbedtls_record
instead of the previous mbedtls_ssl_context::in_xxx fields.
2019-08-14 15:08:08 +01:00
Hanno Becker
331de3df9a Mark ssl_parse_record_header() as const in SSL context 2019-08-14 15:08:08 +01:00
Hanno Becker
b0fe0eedce Remove duplicate setting of ssl->in_msgtype and ssl->in_msglen 2019-08-14 15:06:44 +01:00
Hanno Becker
44d89b2d53 Move update of in_xxx fields in ssl_get_next_record()
ssl_get_next_record() updates the legacy in_xxx fields in two places,
once before record decryption and once after. Now that record decryption
doesn't use or affect the in_xxx fields anymore, setting up the these
legacy fields can entirely be moved to the end of ssl_get_next_record(),
which is what this comit does.

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

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

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

One exception is the handling of possible client reconnects,
which happens in the case then ssl_parse_record_header() returns
MBEDTLS_ERR_SSL_UNEXPECTED_RECORD; since ssl_check_client_reconnect()
so far uses the in_xxx fields, they need to be derived from the
record structure beforehand.
2019-08-14 15:06:06 +01:00
Hanno Becker
605949f84c Mark ssl_decrypt_buf() as `const in the input SSL context
In fact, the SSL context is only used to access the debug callback.
2019-08-14 15:06:06 +01:00
Hanno Becker
fdf660426d Adapt ssl_prepare_record_content() to use SSL record structure 2019-08-14 15:06:06 +01:00
Hanno Becker
a31756619c Use record length from record structure when fetching content in TLS 2019-08-14 15:06:06 +01:00
Hanno Becker
f50da50c04 Use record structure when remembering offset of next record in dgram 2019-08-14 15:06:06 +01:00
Hanno Becker
4acada35f5 Use SSL record structure when skipping over unexpected record 2019-08-14 15:06:06 +01:00
Hanno Becker
519f15dbba Adapt ssl_buffer_future_record() to work with SSL record structure 2019-08-14 15:06:05 +01:00
Hanno Becker
e5e7e7833c Setup SSL record structure in ssl_parse_record_header()
This commit makes a first step towards modularizing the incoming record
processing by having it operate on instances of the structure mbedtls_record
representing SSL records.

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

This commit does not yet remove the ssl->in_xxx fields, but makes a step
towards extending the lifetime of mbedtls_record structure representing
incoming records, by modifying ssl_parse_record_header() to setup an
instance of mbedtls_record, and setting the ssl->in_xxx fields from that
instance. The instance so-constructed isn't used further so far, and in
particular it is not yet consolidated with the instance set up for use
in ssl_decrypt_record(). That's for a later commit.
2019-08-14 15:06:04 +01:00
Gilles Peskine
1435767d2a Merge remote-tracking branch 'upstream-public/pr/2753' into development 2019-08-14 16:00:11 +02:00
Hanno Becker
37cfe73c92 Minor documentation improvements in ssl_parse_record_header() 2019-08-14 14:45:20 +01:00
Hanno Becker
955a5c98df Check for sufficient datagram size in ssl_parse_record_header()
Previously, ssl_parse_record_header() did not check whether the current
datagram is large enough to hold a record of the advertised size. This
could lead to records being silently skipped over or backed up on the
basis of an invalid record length. Concretely, the following would happen:

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

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

In the new logic this commit introduces, `ssl_handle_possible_reconnect()` is
part of `ssl_check_client_reconnect()` which is triggered _after_
`ssl_parse_record_header()` found an unexpected record, which is already in
the code-path eventually dropping the record; we want to leave this code-path
only if a valid cookie has been found and we want to reset, but do nothing
otherwise. That's why `ssl_handle_possible_reconnect()` now returns `0` unless
a valid cookie has been found or a fatal error occurred.
2019-08-14 14:41:06 +01:00
Gilles Peskine
0ed1df6206
Merge pull request #184 from hanno-arm/ecp_restartable_offset
Fix fragile method for passing from ECDSA to ECP restart contexts
2019-08-14 15:40:08 +02:00
Hanno Becker
4894873b92 Remove redundant minimum length check
Availability of sufficient incoming data should be checked when
it is needed, which is in mbedtls_ssl_fetch_input(), and this
function has the necessary bounds checks in place.
2019-08-14 14:34:49 +01:00
Hanno Becker
20016654c3 Remove unnecessary backup of explicit IV in AEAD record decryption
There is no need to hold back the explicit IV for AEAD ciphers.
2019-08-14 14:34:26 +01:00
Hanno Becker
d96a652d80 Improve documentation of mbedtls_ssl_decrypt_buf() 2019-08-14 14:34:04 +01:00
Hanno Becker
c957e3b5f8 Remove redundant length check during record header parsing
The check is in terms of the internal input buffer length and is
hence likely to be originally intended to protect against overflow
of the input buffer when fetching data from the underlying
transport in mbedtls_ssl_fetch_input(). For locality of reasoning,
it's better to perform such a check close to where it's needed,
and in fact, mbedtls_ssl_fetch_input() _does_ contain an equivalent
bounds check, too, rendering the bounds check in question redundant.
2019-08-14 14:33:39 +01:00
Hanno Becker
e2b786d40f Remove misleading comment in mbedtls_ssl_decrypt_buf()
The comment doesn't seem to relate to the code that follows.
2019-08-14 14:33:09 +01:00
Hanno Becker
47ebaa2205 Remove assertion in mbedtls_ssl_decrypt_buf()
mbedtls_ssl_decrypt_buf() asserts that the passed transform is not NULL,
but the function is only invoked in a single place, and this invocation
is clearly visible to be within a branch ensuring that the incoming
transform isn't NULL. Remove the assertion for the benefit of code-size.
2019-08-14 14:32:39 +01:00
Hanno Becker
d96e10bf23 Check architectural bound for max record payload len in one place
The previous code performed architectural maximum record length checks
both before and after record decryption. Since MBEDTLS_SSL_IN_CONTENT_LEN
bounds the maximum length of the record plaintext, it suffices to check
only once after (potential) decryption.

This must not be confused with the internal check that the record
length is small enough to make the record fit into the internal input
buffer; this is done in mbedtls_ssl_fetch_input().
2019-08-14 14:31:58 +01:00
Hanno Becker
3be264e2c3 Remove redundant length-0 checks for incoming unprotected records 2019-08-14 14:30:51 +01:00
k-stachowiak
012dcc4b87 Remove PSA_PRE_1_0_KEY_DERIVATION and the corresponding code 2019-08-13 18:42:40 +02:00
k-stachowiak
0b74cf85ea Remove psa_key_derivation() and associated static functions 2019-08-13 18:42:27 +02:00
Gilles Peskine
c9d7f94a65 Add issue numbers for some missing parts of secure element support 2019-08-13 16:17:16 +02:00
Gilles Peskine
4b7f340fbf Clean up status code handling inside psa_destroy_key
Adopt a simple method for tracking whether there was a failure: each
fallible operation sets overall_status, unless overall_status is
already non-successful. Thus in case of multiple failures, the
function always reports whatever failed first. This may not always be
the right thing, but it's simple.

This revealed a bug whereby if the only failure was the call to
psa_destroy_se_key(), i.e. if the driver reported a failure or if the
driver lacked support for destroying keys, psa_destroy_key() would
ignore that failure.

For a key in a secure element, if creating a transaction file fails,
don't touch storage, but close the key in memory. This may not be
right, but it's no wronger than it was before. Tracked in
https://github.com/ARMmbed/mbed-crypto/issues/215
2019-08-13 15:58:36 +02:00
Gilles Peskine
9ce31c466d Note about destroying a key with other open handles
https://github.com/ARMmbed/mbed-crypto/issues/214
2019-08-13 15:14:20 +02:00
Gilles Peskine
caec27821f SE keys: make psa_destroy_key remove the key from storage 2019-08-13 15:11:49 +02:00
Gilles Peskine
3f7cd62ff5 Document better what wiping a key slot does not do
When a key slot is wiped, a copy of the key material may remain in
operations. This is undesirable, but does not violate the safety of
the code. Tracked in https://github.com/ARMmbed/mbed-crypto/issues/86
2019-08-13 15:01:08 +02:00
Janos Follath
1d57a20cbe Make TODO comments consistent 2019-08-13 12:15:34 +01:00
Gilles Peskine
edc6424d77 SE driver support: Implement sign and verify hooks 2019-08-09 16:43:35 +02:00
Gilles Peskine
11792086cc SE keys: implement and smoke-test p_generate 2019-08-09 16:43:35 +02:00
Gilles Peskine
f3801fff77 Update import_key and generate_key SE methods to the current API
The methods to import and generate a key in a secure element drivers
were written for an earlier version of the application-side interface.
Now that there is a psa_key_attributes_t structure that combines all
key metadata including its lifetime (location), type, size, policy and
extra type-specific data (domain parameters), pass that to drivers
instead of separate arguments for each piece of metadata. This makes
the interface less cluttered.

Update parameter names and descriptions to follow general conventions.

Document the public-key output on key generation more precisely.
Explain that it is optional in a driver, and when a driver would
implement it. Declare that it is optional in the core, too (which
means that a crypto core might not support drivers for secure elements
that do need this feature).

Update the implementation and the tests accordingly.
2019-08-09 16:43:35 +02:00
Gilles Peskine
a5f8749812 SE key registration: call p_validate_slot_number
When registering a key in a secure element, if the driver has a
p_validate_slot_number method, call it.
2019-08-09 15:05:32 +02:00
Gilles Peskine
d772958ffc New function mbedtls_psa_register_se_key
Register an existing key in a secure element.

Minimal implementation that doesn't call any driver method and just
lets the application declare whatever it wants.
2019-08-09 15:05:21 +02:00
Gilles Peskine
e88c2c1338 Pass the key creation method to drivers
Pass the key creation method (import/generate/derive/copy) to the
driver methods to allocate or validate a slot number. This allows
drivers to enforce policies such as "this key slot can only be used
for keys generated inside the secure element".
2019-08-09 14:59:31 +02:00
Gilles Peskine
df17914e01 psa_start_key_creation: take the method as a parameter
Let psa_start_key_creation know what type of key creation this is. This
will be used at least for key registration in a secure element, which
is a peculiar kind of creation since it uses existing key material.
2019-08-09 14:54:03 +02:00
Gilles Peskine
059d9d3fc5
Merge pull request #182 from gilles-peskine-arm/ecp-factorize-reduction
Replace some macros by functions in ecp
2019-08-08 19:16:27 +02:00
Janos Follath
8aa7e9bc56 Merge branch 'psa-api-1.0-beta' into merge-psa-api-branch-into-development 2019-08-08 14:40:23 +01:00
Gilles Peskine
46d9439a5e Support slot_number attribute when creating a key
Allow the application to choose the slot number in a secure element,
rather than always letting the driver choose.

With this commit, any application may request any slot. In an
implementation with isolation, it's up to the service to filter key
creation requests and apply policies to limit which applications can
request which slot.
2019-08-08 11:02:30 +02:00
Gilles Peskine
edbed5670a Rename psa_internal_allocate_key_slot to psa_get_empty_key_slot
This function no longer modifies anything, so it doesn't actually
allocate the slot. Now, it just returns the empty key slot, and it's
up to the caller to cause the slot to be in use (or not).
2019-08-08 10:58:09 +02:00
Gilles Peskine
094dac1d12 Fix copypasta 2019-08-08 10:58:09 +02:00
Gilles Peskine
013f5474cf Fix erasure of external flags
This didn't break anything now, but would have broken things once we
start to add internal flags.
2019-08-08 10:58:09 +02:00
Gilles Peskine
5a68056755 Rename internal macro to pass check-names.sh
check-names.sh rejects MBEDTLS_XXX identifiers that are not defined in
a public header.
2019-08-08 10:58:09 +02:00
Gilles Peskine
c8000c005a Add slot_number attribute
Add a slot_number field to psa_key_attributes_t and getter/setter
functions. Since slot numbers can have the value 0, indicate the
presence of the field via a separate flag.

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

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

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

Fix #207
2019-08-07 13:43:09 +02:00
Gilles Peskine
1b9505c451 Correct some comments 2019-08-07 10:59:45 +02:00
Hanno Becker
7132c4a6c8 Update version_features.c 2019-08-06 11:25:45 +03:00
Hanno Becker
cfe457921a Introduce configuration option and API for SSL record checking 2019-08-06 10:09:08 +03:00
Gilles Peskine
41f2de9da2
Merge pull request #638 from ARMmbed/development-proposed
Merge development into development-restricted
2019-08-05 11:06:20 +02:00
Gilles Peskine
01655daeee
Merge pull request #2417 from RonEld/2734
Update soon to be expired crl
2019-08-03 13:38:14 +02:00
Vikas Katariya
21599b6622 Return right error code.
Issue : 126
https://github.com/ARMmbed/mbed-crypto/issues/126

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

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

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

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

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

Write accessor functions for flags.

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

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

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

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

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

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

Test that key import, generation and derivation reject overly large
sizes.
2019-07-30 20:58:33 +02:00