Commit graph

5821 commits

Author SHA1 Message Date
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
Gilles Peskine 7e0cff90b9 Move attribute fields to a substructure
Move the "core attributes" to a substructure of psa_key_attribute_t.
The motivation is to be able to use the new structure
psa_core_key_attributes_t internally.
2019-07-30 20:58:27 +02:00
Gilles Peskine e60d1d08a4 SE keys: save the bit size in storage
For a key in a secure element, save the bit size alongside the slot
number.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Provide functions to look up a driver by its lifetime and to retrieve
the method table from an entry.
2019-07-12 11:47:50 +02:00
Ashley Duncan eb33978fa8 Remove use of CMAKE_SOURCE_DIR
Remove use of CMAKE_SOURCE_DIR in case mbedtls is built from within
another CMake project. Define MBEDTLS_DIR to ${CMAKE_CURRENT_SOURCE_DIR}
in the main CMakeLists.txt file and refer to that when defining target
include paths to enable mbedtls to be built as a sub project.

Fixes #2609

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

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

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

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

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

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

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

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

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

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

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

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

Fixes #2609

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

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

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

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

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

This fixes #2671 (no easy way to make MBEDTLS_PARAM_FAILED assert)
without breaking backward compatibility. With this change,
`config.pl full` runs tests with MBEDTLS_PARAM_FAILED set to assert,
so the tests will fail if a validation check fails, and programs don't
need to provide their own definition of mbedtls_param_failed().
2019-06-13 16:51:59 +02:00
Máté Varga c5de4623e8 Making version features easily ROM-able when using Arm C compiler. 2019-06-12 12:26:37 +02:00
Jaeden Amero b1c72f56b1 Update library version to 2.18.0
Increase the SO versions of libmbedx509 and libmbedtls due to the
addition of fields in publicly visible (non-opaque) structs:
  - mbedtls_ssl_config
  - mbedtls_ssl_context
  - mbedtls_x509_crt
2019-06-11 17:19:35 +01:00
k-stachowiak c4638cc640 Change size of preallocated buffer for pk_sign() calls 2019-06-06 13:20:48 +02:00
Gilles Peskine 4bac9a4c4b New function to get key slot statistics
New function mbedtls_psa_get_stats to obtain some data about how many
key slots are in use. This is intended for debugging and testing
purposes.
2019-06-05 16:38:42 +02:00
Jaeden Amero 2de07f1dd1 ssl: Don't access non-existent encrypt_then_mac field
When MBEDTLS_SSL_ENCRYPT_THEN_MAC is enabled, but not
MBEDTLS_SSL_SOME_MODES_USE_MAC, mbedtls_ssl_derive_keys() and
build_transforms() will attempt to use a non-existent `encrypt_then_mac`
field in the ssl_transform.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

This commit fixes this.

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

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

Add declarations for DER encoded test CRTs to certs.h

Add DER encoded versions of CRTs to certs.c

fix comment in certs.c

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

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

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

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

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

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

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

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

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

Add missing public declaration of test key password

Fix signedness and naming mismatches

Further improve structure of certs.h and certs.c

Fix definition of mbedtls_test_cas test CRTs depending on config

Remove semicolon after macro string constant in certs.c
2019-06-03 17:46:56 +01:00
Hanno Becker e8d6afd627 Add debug line witnessing receipt of unexpected CID 2019-06-03 16:07:50 +01:00
Hanno Becker 92d30f5bcf Fix indentation in debug message in ssl_tls.c 2019-06-03 16:07:50 +01:00
Hanno Becker 8e55b0f852 Improve comment in ssl_parse_record_header() 2019-06-03 16:07:50 +01:00
Hanno Becker 615ef17b67 Allow passing NULL pointers to mbedtls_ssl_get_peer_cid()
This commit modifies mbedtls_ssl_get_peer_cid() to also allow passing
NULL pointers in the arguments for the peer's CID value and length, in
case this information is needed.

For example, some users might only be interested in whether the use of
the CID was negotiated, in which case both CID value and length pointers
can be set to NULL. Other users might only be interested in confirming
that the use of CID was negotiated and the peer chose the empty CID,
in which case the CID value pointer only would be set to NULL.
It doesn't make sense to pass a NULL pointer for the CID length but a
non-NULL pointer for the CID value, as the caller has no way of telling
the length of the returned CID - and this case is therefore forbidden.
2019-06-03 16:07:50 +01:00
Hanno Becker a0e20d04b2 Rename MBEDTLS_SSL_CID to MBEDTLS_SSL_DTLS_CONNECTION_ID
Files modified via

sed -i 's/MBEDTLS_SSL_CID\([^_]\|$\)/MBEDTLS_SSL_DTLS_CONNECTION_ID\1/g' **/*.c **/*.h **/*.sh **/*.function
2019-06-03 16:07:50 +01:00
Hanno Becker ebcc9137ca Consistently reference CID draft through name + URL 2019-06-03 16:07:50 +01:00
Hanno Becker d1f203557f Slightly reorder CID debug messages during creation of transforms 2019-06-03 16:07:50 +01:00
Hanno Becker 4cac442211 Update references to CID draft to version 5 2019-06-03 16:07:50 +01:00
Hanno Becker 611ac77127 Fix mbedtls_ssl_conf_cid() to not depend on macro constant values
The previous implementation of mbedtls_ssl_conf_cid() relied on
MBEDTLS_SSL_UNEXPECTED_CID_IGNORE being defined as 1.
2019-06-03 16:07:50 +01:00
Hanno Becker 5d12467fad Remove warnings about unfinished CID implementation
The implementation is complete now.
2019-06-03 16:07:50 +01:00
Hanno Becker 8367ccc03b Allow to configure the stack's behaviour on unexpected CIDs
This commit modifies the CID configuration API mbedtls_ssl_conf_cid_len()
to allow the configuration of the stack's behaviour when receiving an
encrypted DTLS record with unexpected CID.
2019-06-03 16:07:50 +01:00
Hanno Becker c37c96a3c5 Add specific SSL error code for unexpected CIDs
Currently, the stack silently ignores DTLS frames with an unexpected CID.
However, in a system which performs CID-based demultiplexing before passing
datagrams to the Mbed TLS stack, unexpected CIDs are a sign of something not
working properly, and users might want to know about it.

This commit introduces an SSL error code MBEDTLS_ERR_SSL_UNEXPECTED_CID
which the stack can return in response to an unexpected CID. It will
conditionally be put to use in subsequent commits.
2019-06-03 16:07:50 +01:00
Hanno Becker b9ec44fcf6 Remove restriction on value of MBEDTLS_SSL_CID_PADDING_GRANULARITY 2019-06-03 16:07:50 +01:00
Hanno Becker 2cdc5c3cf9 Make signed to unsigned integer truncation cast explicit 2019-06-03 16:07:50 +01:00
Hanno Becker b1aa1b3616 Allow the configuration of padding when using CID extension 2019-06-03 16:07:50 +01:00
Hanno Becker 4c3eb7c919 Set CID pointer to default value even for TLS
There are two options:
1. Don't set it, and don't use it during record protection,
   guarding the respective paths by a check whether TLS or
   DTLS is used.
2. Set it to the default value even for TLS, and avoid the
   protocol-dependent branch during record protection.

This commit picks option 2.
2019-06-03 16:07:50 +01:00
Hanno Becker 4a4af9fcbe Fix typo in comment 2019-06-03 16:07:50 +01:00
Hanno Becker 22a59fdca8 Remove indicators and warnings about unfinished CID implementation 2019-06-03 16:07:50 +01:00
Hanno Becker 05154c3897 Re-enable passing CIDs to record transforms 2019-06-03 16:07:50 +01:00
Hanno Becker 16ded98bef Don't fail on record with unexpected CID
This commit changes the stack's behaviour when facing a record
with a non-matching CID. Previously, the stack failed in this
case, while now we silently skip over the current record.
2019-06-03 16:07:50 +01:00
Hanno Becker 938489a1bc Re-enable CID comparison when decrypting CID-based records 2019-06-03 16:07:50 +01:00
Hanno Becker ca59c2b486 Implement parsing of CID-based records
Previously, ssl_get_next_record() would fetch 13 Bytes for the
record header and hand over to ssl_parse_record_header() to parse
and validate these. With the introduction of CID-based records, the
record length is not known in advance, and parsing and validating
must happen at the same time. ssl_parse_record_header() is therefore
rewritten in the following way:
1. Fetch and validate record content type and version.
2. If the record content type indicates a record including a CID,
   adjust the record header pointers accordingly; here, we use the
   statically configured length of incoming CIDs, avoiding any
   elaborate CID parsing mechanism or dependency on the record
   epoch, as explained in the previous commit.
3. Fetch the rest of the record header (note: this doesn't actually
   fetch anything, but makes sure that the datagram fetched in the
   earlier call to ssl_fetch_input() contains enough data).
4. Parse and validate the rest of the record header as before.
2019-06-03 16:07:50 +01:00
Hanno Becker 6430faf098 Adapt record encryption/decryption routines to change of record type
This commit modifies the code surrounding the invocations of
ssl_decrypt_buf() and ssl_encrypt_buf() to deal with a change
of record content type during CID-based record encryption/decryption.
2019-06-03 16:07:50 +01:00
Hanno Becker f9c6a4bea1 Add pointers to in/out CID fields to mbedtls_ssl_context
mbedtls_ssl_context contains pointers in_buf, in_hdr, in_len, ...
which point to various parts of the header of an incoming TLS or
DTLS record; similarly, there are pointers out_buf, ... for
outgoing records.

This commit adds fields in_cid and out_cid which point to where
the CID of incoming/outgoing records should reside, if present,
namely prior to where the record length resides.

Quoting https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-04:

   The DTLSInnerPlaintext value is then encrypted and the CID added to
   produce the final DTLSCiphertext.

        struct {
            ContentType special_type = tls12_cid; /* 25 */
            ProtocolVersion version;
            uint16 epoch;
            uint48 sequence_number;
            opaque cid[cid_length];               // New field
            uint16 length;
            opaque enc_content[DTLSCiphertext.length];
        } DTLSCiphertext;

For outgoing records, out_cid is set in ssl_update_out_pointers()
based on the settings in the current outgoing transform.

For incoming records, ssl_update_in_pointers() sets in_cid as if no
CID was present, and it is the responsibility of ssl_parse_record_header()
to update the field (as well as in_len, in_msg and in_iv) when parsing
records that do contain a CID. This will be done in a subsequent commit.

Finally, the code around the invocations of ssl_decrypt_buf()
and ssl_encrypt_buf() is adapted to transfer the CID from the
input/output buffer to the CID field in the internal record
structure (which is what ssl_{encrypt/decrypt}_buf() uses).

Note that mbedtls_ssl_in_hdr_len() doesn't need change because
it infers the header length as in_iv - in_hdr, which will account
for the CID for records using such.
2019-06-03 16:07:50 +01:00
Hanno Becker 6cbad5560d Account for additional record expansion when using CIDs
Using the Connection ID extension increases the maximum record expansion
because
- the real record content type is added to the plaintext
- the plaintext may be padded with an arbitrary number of
  zero bytes, in order to prevent leakage of information
  through package length analysis. Currently, we always
  pad the plaintext in a minimal way so that its length
  is a multiple of 16 Bytes.

This commit adapts the various parts of the library to account
for that additional source of record expansion.
2019-06-03 16:07:50 +01:00
Hanno Becker ad4a137965 Add CID configuration API
Context:
The CID draft does not require that the length of CIDs used for incoming
records must not change in the course of a connection. Since the record
header does not contain a length field for the CID, this means that if
CIDs of varying lengths are used, the CID length must be inferred from
other aspects of the record header (such as the epoch) and/or by means
outside of the protocol, e.g. by coding its length in the CID itself.

Inferring the CID length from the record's epoch is theoretically possible
in DTLS 1.2, but it requires the information about the epoch to be present
even if the epoch is no longer used: That's because one should silently drop
records from old epochs, but not the entire datagrams to which they belong
(there might be entire flights in a single datagram, including a change of
epoch); however, in order to do so, one needs to parse the record's content
length, the position of which is only known once the CID length for the epoch
is known. In conclusion, it puts a significant burden on the implementation
to infer the CID length from the record epoch, which moreover mangles record
processing with the high-level logic of the protocol (determining which epochs
are in use in which flights, when they are changed, etc. -- this would normally
determine when we drop epochs).

Moreover, with DTLS 1.3, CIDs are no longer uniquely associated to epochs,
but every epoch may use a set of CIDs of varying lengths -- in that case,
it's even theoretically impossible to do record header parsing based on
the epoch configuration only.

We must therefore seek a way for standalone record header parsing, which
means that we must either (a) fix the CID lengths for incoming records,
or (b) allow the application-code to configure a callback to implement
an application-specific CID parsing which would somehow infer the length
of the CID from the CID itself.

Supporting multiple lengths for incoming CIDs significantly increases
complexity while, on the other hand, the restriction to a fixed CID length
for incoming CIDs (which the application controls - in contrast to the
lengths of the CIDs used when writing messages to the peer) doesn't
appear to severely limit the usefulness of the CID extension.

Therefore, the initial implementation of the CID feature will require
a fixed length for incoming CIDs, which is what this commit enforces,
in the following way:

In order to avoid a change of API in case support for variable lengths
CIDs shall be added at some point, we keep mbedtls_ssl_set_cid(), which
includes a CID length parameter, but add a new API mbedtls_ssl_conf_cid_len()
which applies to an SSL configuration, and which fixes the CID length that
any call to mbetls_ssl_set_cid() which applies to an SSL context that is bound
to the given SSL configuration must use.

While this creates a slight redundancy of parameters, it allows to
potentially add an API like mbedtls_ssl_conf_cid_len_cb() later which
could allow users to register a callback which dynamically infers the
length of a CID at record header parsing time, without changing the
rest of the API.
2019-06-03 16:07:50 +01:00
Hanno Becker 5903de45b6 Split mbedtls_ssl_hdr_len() in separate functions for in/out records
The function mbedtls_ssl_hdr_len() returns the length of the record
header (so far: always 13 Bytes for DTLS, and always 5 Bytes for TLS).

With the introduction of the CID extension, the lengths of record
headers depends on whether the records are incoming or outgoing,
and also on the current transform.

Preparing for this, this commit splits mbedtls_ssl_hdr_len() in two
-- so far unmodified -- functions mbedtls_ssl_in_hdr_len() and
mbedtls_ssl_out_hdr_len() and replaces the uses of mbedtls_ssl_hdr_len()
according to whether they are about incoming or outgoing records.

There is no need to change the signature of mbedtls_ssl_{in/out}_hdr_len()
in preparation for its dependency on the currently active transform,
since the SSL context is passed as an argument, and the currently
active transform is referenced from that.
2019-06-03 16:07:50 +01:00
Hanno Becker f661c9c39c Add helper function to check validity of record content type
With the introduction of the CID feature, the stack needs to be able
to handle a change of record content type during record protection,
which in particular means that the record content type check will
need to move or be duplicated.

This commit introduces a tiny static helper function which checks
the validity of record content types, which hopefully makes it
easier to subsequently move or duplicate this check.
2019-06-03 16:07:50 +01:00
Hanno Becker 37ae952923 Move dropping of unexpected AD records to after record decryption
With the introduction of the CID extension, the record content type
may change during decryption; we must therefore re-consider every
record content type check that happens before decryption, and either
move or duplicate it to ensure it also applies to records whose
real content type is only revealed during decryption.

This commit does this for the silent dropping of unexpected
ApplicationData records in DTLS. Previously, this was caught
in ssl_parse_record_header(), returning
MBEDTLS_ERR_SSL_UNEXPECTED_RECORD which in ssl_get_next_record()
would lead to silent skipping of the record.

When using CID, this check wouldn't trigger e.g. when delayed
encrypted ApplicationData records come on a CID-based connection
during a renegotiation.

This commit moves the check to mbedtls_ssl_handle_message_type()
and returns MBEDTLS_ERR_SSL_NON_FATAL if it triggers, which leads
so silent skipover in the caller mbedtls_ssl_read_record().
2019-06-03 16:07:50 +01:00
Hanno Becker 79594fd0d4 Set pointer to start of plaintext at record decryption time
The SSL context structure mbedtls_ssl_context contains several pointers
ssl->in_hdr, ssl->in_len, ssl->in_iv, ssl->in_msg pointing to various
parts of the record header in an incoming record, and they are setup
in the static function ssl_update_in_pointers() based on the _expected_
transform for the next incoming record.
In particular, the pointer ssl->in_msg is set to where the record plaintext
should reside after record decryption, and an assertion double-checks this
after each call to ssl_decrypt_buf().

This commit removes the dependency of ssl_update_in_pointers() on the
expected incoming transform by setting ssl->in_msg to ssl->in_iv --
the beginning of the record content (potentially including the IV) --
and adjusting ssl->in_msg after calling ssl_decrypt_buf() on a protected
record.

Care has to be taken to not load ssl->in_msg before calling
mbedtls_ssl_read_record(), then, which was previously the
case in ssl_parse_server_hello(); the commit fixes that.
2019-06-03 16:07:50 +01:00
Hanno Becker 82e2a3961c Treat an invalid record after decryption as fatal
If a record exhibits an invalid feature only after successful
authenticated decryption, this is a protocol violation by the
peer and should hence lead to connection failure. The previous
code, however, would silently ignore such records. This commit
fixes this.

So far, the only case to which this applies is the non-acceptance
of empty non-AD records in TLS 1.2. With the present commit, such
records lead to connection failure, while previously, they were
silently ignored.

With the introduction of the Connection ID extension (or TLS 1.3),
this will also apply to records whose real content type -- which
is only revealed during authenticated decryption -- is invalid.
2019-06-03 16:07:50 +01:00
Hanno Becker 6e7700df17 Expain rationale for handling of consecutive empty AD records 2019-06-03 16:07:50 +01:00
Hanno Becker 76a79ab4a2 Don't allow calling CID API outside of DTLS 2019-06-03 16:07:50 +01:00
Hanno Becker 95e4bbcf6c Fix additional data calculation if CID is disabled
In contrast to other aspects of the Connection ID extension,
the CID-based additional data for MAC computations differs from
the non-CID case even if the CID length is 0, because it
includes the CID length.
2019-06-03 14:47:36 +01:00
Hanno Becker af05ac067b Remove unnecessary empty line in ssl_tls.c 2019-06-03 14:47:36 +01:00
Hanno Becker 07dc97db8c Don't quote DTLSInnerPlaintext structure multiple times 2019-06-03 14:47:36 +01:00
Hanno Becker d3f8c79ea0 Improve wording in ssl_build_inner_plaintext() 2019-06-03 14:47:36 +01:00
Hanno Becker edb24f8eec Remove unnecessary whitespace in ssl_extract_add_data_from_record() 2019-06-03 14:47:36 +01:00
Hanno Becker 92fb4fa802 Reduce stack usage for additional data buffers in record dec/enc 2019-06-03 14:47:36 +01:00
Hanno Becker c4a190bb0f Add length of CID to additional data used for record protection
Quoting the CID draft 04:

   -  Block Ciphers:

       MAC(MAC_write_key, seq_num +
           tls12_cid +                     // New input
           DTLSPlaintext.version +
           cid +                           // New input
           cid_length +                    // New input
           length_of_DTLSInnerPlaintext +  // New input
           DTLSInnerPlaintext.content +    // New input
           DTLSInnerPlaintext.real_type +  // New input
           DTLSInnerPlaintext.zeros        // New input
       )

And similar for AEAD and Encrypt-then-MAC.
2019-06-03 14:47:36 +01:00
Hanno Becker d5aeab1e8a Improve documentation of ssl_extract_add_data_from_record() 2019-06-03 14:47:36 +01:00
Hanno Becker 43c24b8da9 Fix missing compile-time guards around CID-only constants 2019-06-03 14:47:36 +01:00
Hanno Becker f44e55de5e Remove TODO 2019-06-03 14:47:36 +01:00
Hanno Becker 75f080f4b6 Use MBEDTLS_ namespace for internal CID length constant 2019-06-03 14:47:36 +01:00
Hanno Becker 8a7f972202 Skip copying CIDs to SSL transforms until CID feature is complete
This commit temporarily comments the copying of the negotiated CIDs
into the established ::mbedtls_ssl_transform in mbedtls_ssl_derive_keys()
until the CID feature has been fully implemented.

While mbedtls_ssl_decrypt_buf() and mbedtls_ssl_encrypt_buf() do
support CID-based record protection by now and can be unit tested,
the following two changes in the rest of the stack are still missing
before CID-based record protection can be integrated:
- Parsing of CIDs in incoming records.
- Allowing the new CID record content type for incoming records.
- Dealing with a change of record content type during record
  decryption.

Further, since mbedtls_ssl_get_peer_cid() judges the use of CIDs by
the CID fields in the currently transforms, this change also requires
temporarily disabling some grepping for ssl_client2 / ssl_server2
debug output in ssl-opt.sh.
2019-06-03 14:47:36 +01:00
Hanno Becker 8b3eb5ab82 Implement inner plaintext parsing/writing for CID-based connections 2019-06-03 14:47:36 +01:00
Hanno Becker cab87e68b6 Incorporate CID into MAC computations during record protection
This commit modifies ssl_decrypt_buf() and ssl_encrypt_buf()
to include the CID into authentication data during record
protection.

It does not yet implement the new DTLSInnerPlaintext format
from https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-04
2019-06-03 14:47:36 +01:00
Hanno Becker 1c1f046804 Replace 'ingoing' -> 'incoming' in CID debug messages 2019-06-03 14:43:16 +01:00
Hanno Becker c5f2422116 Document behaviour of mbedtls_ssl_get_peer_cid() for empty CIDs 2019-06-03 14:43:16 +01:00
Hanno Becker 5a29990367 Improve structure of client-side CID extension parsing
Group configuring CID values together.
2019-06-03 14:43:16 +01:00
Hanno Becker 2262648b69 Improve debugging output of client-side CID extension parsing 2019-06-03 14:43:16 +01:00
Hanno Becker 08556bf8fb Improve structure of ssl_parse_cid_ext()
Group configuring CID values together.
2019-06-03 14:43:16 +01:00
Hanno Becker a34ff5b9a2 Correct compile-time guard around CID extension writing func on srv 2019-06-03 14:43:16 +01:00
Hanno Becker b7ee0cf3f9 Make integer truncation explicit in mbedtls_ssl_set_cid() 2019-06-03 14:43:16 +01:00
Hanno Becker b1f89cd602 Implement mbedtls_ssl_get_peer_cid() 2019-06-03 14:43:16 +01:00
Hanno Becker 4bf7465840 Copy CIDs into SSL transform if use of CID has been negotiated 2019-06-03 14:43:16 +01:00
Hanno Becker a8373a11c0 Implement parsing of CID extension in ServerHello 2019-06-03 14:43:16 +01:00
Hanno Becker 51de2d3f69 Implement writing of CID extension in ServerHello 2019-06-03 14:43:16 +01:00
Hanno Becker 89dcc881d4 Implement parsing of CID extension in ClientHello 2019-06-03 14:43:16 +01:00
Hanno Becker 49770ffd93 Implement writing of CID extension in ClientHello 2019-06-03 14:43:16 +01:00
Hanno Becker ca092246a7 Allow configuring own CID fields through mbedtls_ssl_get_peer_cid() 2019-06-03 14:43:16 +01:00
Hanno Becker 35c36a6760 Guard CID implementations by MBEDTLS_SSL_CID 2019-06-03 14:42:08 +01:00
Hanno Becker f1f9a82320 Add warnings about status of implementation of CID API 2019-06-03 14:42:08 +01:00
Hanno Becker f8542cf620 Add dummy implementations for CID API 2019-06-03 14:42:08 +01:00
Hanno Becker f8c10269d1 Update version_features.c 2019-06-03 14:42:08 +01:00
Hanno Becker 8b0f9e6388 Allow DHM selftest to run if MBEDTLS_PEM_PARSE_C is unset
If MBEDTLS_PEM_PARSE_C is unset, the DHM selftest fails because
it uses PEM encoded test data.

This commit fixes this by providing the DER encoded form of the
test data instead in case MBEDTLS_PEM_PARSE_C is unset.
2019-05-31 17:28:59 +01:00
Gilles Peskine 6f3c30e9db Merge follow-up: remove unused code from the development branch 2019-05-29 09:58:59 +02:00
Gilles Peskine 2938268fb4 Merge remote-tracking branch 'upstream-crypto/development' into psa-api-1.0-beta-merge_development_20190524
Conflicts:
* library/ssl_cli.c, library/ssl_tls.c:
  Removed on the development branch. Keep them removed.
* include/psa/crypto_extra.h, library/psa_crypto_storage.c,
  tests/suites/test_suite_psa_crypto.data,
  tests/suites/test_suite_psa_crypto.function,
  tests/suites/test_suite_psa_crypto_persistent_key.data,
  tests/suites/test_suite_psa_crypto_slot_management.data,
  tests/suites/test_suite_psa_crypto_slot_management.function:
  Modified on the development branch only to implement the enrollment
  algorithm, which has been reimplemented on the API branch.
  Keep the API branch.
2019-05-29 09:57:29 +02:00
Gilles Peskine 110aff4c38 Enrollment algorithm in policy: implement persistent keys 2019-05-27 14:08:28 +02:00
Gilles Peskine f25c9ec02e Minor documentation improvements 2019-05-27 14:08:27 +02:00
Gilles Peskine 96f0b3b1d3 Keys may allow a second algorithm
Add a second permitted algorithm to key policies.

This commit includes smoke tests that do not cover psa_copy_key.
2019-05-27 14:08:27 +02:00
Jaeden Amero 2ab5cf658f Merge remote-tracking branch 'origin/pr/2403' into development
* origin/pr/2403: (24 commits)
  crypto: Update to Mbed Crypto 8907b019e7
  Create seedfile before running tests
  crypto: Update to Mbed Crypto 81f9539037
  ssl_cli.c : add explicit casting to unsigned char
  Generating visualc files - let Mbed TLS take precedence over crypto
  Add a link to the seedfile for out-of-tree cmake builds
  Adjust visual studio file generation to always use the crypto submodule
  all.sh: unparallelize mingw tests
  all.sh - disable parallelization for shared target tests
  config.pl: disable PSA_ITS_FILE and PSA_CRYPTO_STORAGE for baremetal
  all.sh: unset crypto storage define in a psa full config cmake asan test
  all.sh: unset FS_IO-dependent defines for tests that do not have it
  curves.pl - change test script to not depend on the implementation
  Export the submodule flag to sub-cmakes
  Disable MBEDTLS_ECP_RESTARTABLE in full config
  Export the submodule flag to sub-makes
  Force the usage of crypto submodule
  Fix crypto submodule usage in Makefile
  Documentation rewording
  Typo fixes in documentation
  ...
2019-05-23 09:08:55 +01:00
Andrzej Kurek ade9e28d9f ssl_cli.c : add explicit casting to unsigned char
Signal casting from size_t to unsigned char explicitly, so that the compiler
does not raise a warning about possible loss of data on MSVC, targeting
64-bit Windows.
2019-05-23 03:01:35 -04:00
Andrzej Kurek 346747cd24 Force the usage of crypto submodule
Remove all.sh tests exercising the optional usage of submodule
2019-05-23 03:01:35 -04:00
Manuel Pégourié-Gonnard 45be3d8136 Fix compile guard for static function in ssl
The guard for the definition of the function was different from the guard on
its only use - make it the same.

This has been caught by tests/scripts/key-exchanges.pl. It had not been caught
by this script in earlier CI runs, because previously USE_PSA_CRYPTO was
disabled in the builds used by this script; enabling it uncovered the issue.
2019-05-23 03:01:35 -04:00
Manuel Pégourié-Gonnard d8167e85d6 Build from submodule by default (make, cmake)
Adapt tests in all.sh:
- tests with submodule enabled (default) no longer need to enable it
  explicitly, and no longer need runtime tests, as those are now handled by
all other test cases in this script
- tests with submodule disabled (old default) now need to disable it
  explicitly, and execute some runtime tests, as those are no longer tested
anywhere else in this script

Adapt documentation in Readme: remove the section "building with submodule"
and replace it with a new section before the other building sections.
Purposefully don't document how to build not from the submodule, as that
option is going away soon.
2019-05-23 03:01:35 -04:00
Ron Eldor 5aebeeb5f4 Set next sequence of subject_alt_names to NULL
Set the next sequence of the subject_alt_name to NULL when deleting
sequence on failure in `get_subject_alt_name()`.
Found by Philippe Antoine. Credit to OSS-Fuzz.
2019-05-22 16:50:24 +03:00
Jaeden Amero 8d4d4f55f0 Makefile: Use full paths to refer to parent files
When running lcov, files can't be found relative to the parent project
(Mbed TLS) root. Use full, non-relative paths to refer to files used in
building Mbed Crypto from Mbed TLS in order to enable lcov to locate the
files properly.
2019-05-22 13:54:52 +01:00
Jaeden Amero 496c176d90
Merge pull request #266 from ARMmbed/psa-policy_alg2-poc
Keys may allow a second algorithm
2019-05-22 11:55:01 +01:00
Gilles Peskine 549ea8676a Minor documentation improvements 2019-05-22 11:45:59 +02:00
Gilles Peskine 81efb391eb Enrollment algorithm in policy: implement persistent keys 2019-05-21 17:06:35 +02:00
Gilles Peskine 2c86ebc2f8 EC key pair import: check the buffer size
When importing a private elliptic curve key, require the input to have
exactly the right size. RFC 5915 requires the right size (you aren't
allowed to omit leading zeros). A different buffer size likely means
that something is wrong, e.g. a mismatch between the declared key type
and the actual data.
2019-05-21 17:06:27 +02:00
Gilles Peskine d6f371b1ba Keys may allow a second algorithm
Add a second permitted algorithm to key policies.

This commit includes smoke tests that do not cover psa_copy_key.
2019-05-21 17:06:03 +02:00
Jaeden Amero 3d07ffade2 Merge remote-tracking branch 'tls/development' into development
Resolve conflicts by performing the following operations:
    - Reject changes to files removed during the creation of Mbed Crypto
      from Mbed TLS.
    - Reject the addition of certificates that would not be used by any
      tests, including rejecting the addition of Makefile rules to
      generate these certificates.
    - Reject changes to error.c referencing modules that are not part of
      Mbed Crypto.

* origin/development: (80 commits)
  Style fix
  Fix test data
  Update test data
  Add some negative test cases
  Fix minor issues
  Add ChangeLog entry about listing all SAN
  Remove unneeded whitespaces
  Fix mingw CI failures
  Initialize psa_crypto in ssl test
  Check that SAN is not malformed when parsing
  Documentation fixes
  Fix ChangeLog entry
  Fix missing tls version test failures
  Fix typo
  Fix ChangeLog entry location
  Add changeLog entry
  Add test for export keys functionality
  Add function to retrieve the tls_prf type
  Add tests for the public tls_prf API
  Add public API for tls_prf
  ...
2019-05-21 08:57:44 +01:00
Jaeden Amero 31d1432233 Merge remote-tracking branch 'origin/pr/2530' into development
* origin/pr/2530: (27 commits)
  Style fix
  Fix test data
  Update test data
  Add some negative test cases
  Fix minor issues
  Add ChangeLog entry about listing all SAN
  Check that SAN is not malformed when parsing
  Documentation fixes
  Fix ChangeLog entry
  Fail in case critical crt policy not supported
  Update SAN parsing documentation
  change the type of hardware_module_name member
  Change mbedtls_x509_subject_alternative_name
  Add length checking in certificate policy parsing
  Rephrase x509_crt extension member description
  Rephrase changeLog entries
  Remove redundant memset()
  Propogate error when parsing SubjectAltNames
  Tidy up style in x509_info_subject_alt_name
  Print unparseable SubjectAlternativeNames
  ...
2019-05-20 18:02:25 +01:00
Jaeden Amero 9ebcf9b00a Merge remote-tracking branch 'origin/pr/2538' into development
* origin/pr/2538:
  Remove unneeded whitespaces
  Fix mingw CI failures
  Initialize psa_crypto in ssl test
  Fix missing tls version test failures
  Fix typo
  Fix ChangeLog entry location
  Add changeLog entry
  Add test for export keys functionality
  Add function to retrieve the tls_prf type
  Add tests for the public tls_prf API
  Add public API for tls_prf
  Add eap-tls key derivation in the examples.
  Add ChangeLog entry
  Add an extra key export function
  Have the temporary buffer allocated dynamically
  Zeroize secret data in the exit point
  Add a single exit point in key derivation function
2019-05-20 10:58:36 +01:00
Ron Eldor 6aeae9e962 Style fix
Add whitespace before parenthesis.
2019-05-20 12:00:36 +03:00
Gilles Peskine eff4942202
Merge pull request #268 from ARMmbed/psa-error_tampering_detected
Rename PSA_ERROR_TAMPERING_DETECTED to PSA_ERROR_CORRUPTION_DETECTED
2019-05-17 11:06:09 +02:00
Gilles Peskine 35ef36b62f Rename psa_generate_random_key back to psa_generate_key
generate_key is a more classical name. The longer name was only
introduced to avoid confusion with getting a key from a generator,
which is key derivation, but we no longer use the generator
terminology so this reason no longer applies.

perl -i -pe 's/psa_generate_random_key/psa_generate_key/g' $(git ls-files)
2019-05-17 10:56:57 +02:00
Gilles Peskine c93b80c350 Rename *KEYPAIR* to *KEY_PAIR*
Be consistent with PUBLIC_KEY.

perl -i -pe 's/KEYPAIR/KEY_PAIR/g' $(git ls-files)
2019-05-17 10:56:57 +02:00
Gilles Peskine 4b3eb69271 Rename PSA_ERROR_TAMPERING_DETECTED to ..._CORRUPTION_DETECTED
“Tampering detected” was misleading because in the real world it can
also arise due to a software bug. “Corruption detected” is neutral and
more precisely reflects what can trigger the error.

perl -i -pe 's/PSA_ERROR_TAMPERING_DETECTED/PSA_ERROR_CORRUPTION_DETECTED/gi' $(git ls-files)
2019-05-16 21:35:18 +02:00
Gilles Peskine be697d8324 Shorten the name of psa_key_agreement_raw_shared_secret
There is less of a risk of confusion with the KA+KDF function now.
2019-05-16 18:55:25 +02:00
Gilles Peskine cf7292e257 Wrap and reindent some lines
After renaming several identifiers, re-wrap and re-indent some lines
to make the code prettier.
2019-05-16 18:55:25 +02:00
Gilles Peskine 51ae0e4b79 Rename "generator" to "operation"
Generators are now key derivation operations.

Keep "random generator" intact.
2019-05-16 18:55:25 +02:00
Gilles Peskine cbe6650394 Rename generator-related internal identifiers
perl -pe 's/crypto_generator/key_derivation/gi' $(git ls-files)
    perl -pe 's/_generator/_key_derivation/gi' $(git ls-files)
2019-05-16 18:55:25 +02:00
Gilles Peskine 03410b5c5f Rename PSA_KDF_STEP_xxx -> PSA_KEY_DERIVATION_INPUT_xxx
More consistent with the new function names.
2019-05-16 18:55:25 +02:00
Gilles Peskine a99d3fbd05 Rename generator functions to psa_key_derivation_xxx
Generators are mostly about key derivation (currently: only about key
derivation). "Generator" is not a commonly used term in cryptography.
So favor "derivation" as terminology. Call a generator a key
derivation operation structure, since it behaves like other multipart
operation structures. Furthermore, the function names are not fully
consistent.

In this commit, I rename the functions to consistently have the prefix
"psa_key_derivation_". I used the following command:

    perl -i -pe '%t = (
        psa_crypto_generator_t => "psa_key_derivation_operation_t",
        psa_crypto_generator_init => "psa_key_derivation_init",
        psa_key_derivation_setup => "psa_key_derivation_setup",
        psa_key_derivation_input_key => "psa_key_derivation_input_key",
        psa_key_derivation_input_bytes => "psa_key_derivation_input_bytes",
        psa_key_agreement => "psa_key_derivation_key_agreement",
        psa_set_generator_capacity => "psa_key_derivation_set_capacity",
        psa_get_generator_capacity => "psa_key_derivation_get_capacity",
        psa_generator_read => "psa_key_derivation_output_bytes",
        psa_generate_derived_key => "psa_key_derivation_output_key",
        psa_generator_abort => "psa_key_derivation_abort",
        PSA_CRYPTO_GENERATOR_INIT => "PSA_KEY_DERIVATION_OPERATION_INIT",
        PSA_GENERATOR_UNBRIDLED_CAPACITY => "PSA_KEY_DERIVATION_UNLIMITED_CAPACITY",
        ); s/\b(@{[join("|", keys %t)]})\b/$t{$1}/ge' $(git ls-files)
2019-05-16 18:55:21 +02:00
Jaeden Amero 99e8d26a75
Merge pull request #104 from gilles-peskine-arm/psa-global_key_id
Make key ids global and define their range
2019-05-16 17:11:59 +01:00
Ron Eldor a291391775 Fix minor issues
1. Typo fix.
2. Change byte by byte coipy to `memcpy`.
3. Remove parenthesis in switch cases.
2019-05-16 16:17:38 +03:00
Jaeden Amero 16ab39102e
Merge pull request #102 from gilles-peskine-arm/psa-aead_multipart-delay
Multipart AEAD buffer output sizes
2019-05-16 13:34:21 +01:00
Jaeden Amero 76be7f9c70
Merge pull request #108 from gilles-peskine-arm/psa-copy_key-policy
Add policy usage flag to copy a key
2019-05-16 12:08:13 +01:00
Jaeden Amero 826e326d2e
Merge pull request #107 from gilles-peskine-arm/psa-curve_size_macro
PSA: EC curve size macro
2019-05-16 11:59:41 +01:00
Gilles Peskine e2f62ba9ec Fix unused variable in builds without storage 2019-05-16 00:31:48 +02:00
Gilles Peskine c9d910bed6 EC key pair import: check the buffer size
When importing a private elliptic curve key, require the input to have
exactly the right size. RFC 5915 requires the right size (you aren't
allow to omit leading zeros). A different buffer size likely means
that something is wrong, e.g. a mismatch between the declared key type
and the actual data.
2019-05-16 00:18:48 +02:00
Gilles Peskine 73676cbc50 Put handle parameter last: psa_import_key
In psa_import_key, change the order of parameters to pass
the pointer where the newly created handle will be stored last.
This is consistent with most other library functions that put inputs
before outputs.
2019-05-15 23:16:07 +02:00
Gilles Peskine 98dd779eb5 Put handle parameter last: psa_generate_derived_key
In psa_generate_derived_key, change the order of parameters to pass
the pointer where the newly created handle will be stored last.
This is consistent with most other library functions that put inputs
before outputs.
2019-05-15 20:15:31 +02:00
Gilles Peskine f9fbc38e66 Declare key id 0 as invalid
In keeping with other integral types, declare 0 to be an invalid key
identifier.

Documented, implemented and tested.
2019-05-15 18:42:09 +02:00
Ron Eldor dbbd96652c Check that SAN is not malformed when parsing
Add a call to `mbedtls_x509_parse_subject_alt_name()` during
certificate parsing, to verify the certificate is not malformed.
2019-05-15 15:46:03 +03:00
Ron Eldor c8b5f3f520 Documentation fixes
Rephrase documentation of the SAN to make it clearer.
2019-05-15 15:15:55 +03:00
Ron Eldor d2f25f7ea8 Fix missing tls version test failures
Add checks for tls_prf tests with the relevant tls version configuration.
2019-05-15 14:54:22 +03:00
Ron Eldor 0810f0babd Fix typo
Fix typo `returnn` -> `return`
2019-05-15 13:58:13 +03:00
Ron Eldor cf28009839 Add function to retrieve the tls_prf type
Add `tls_prf_get_type()` static function that returns the
`mbedtls_tls_prf_types` according to the used `tls_prf` function.
2019-05-15 13:57:39 +03:00
Ron Eldor 51d3ab544f Add public API for tls_prf
Add a public API for key derivation, introducing an enum for `tls_prf`
type.
2019-05-15 13:53:02 +03:00
Ron Eldor b7fd64ce2b Add eap-tls key derivation in the examples.
Add support for eap-tls key derivation functionality,
in `ssl_client2` and `ssl_server2` reference applications.
2019-05-15 13:41:42 +03:00
Ron Eldor f5cc10d93b Add an extra key export function
Add an additional function `mbedtls_ssl_export_keys_ext_t()`
for exporting key, that adds additional information such as
the used `tls_prf` and the random bytes.
2019-05-15 13:38:39 +03:00
Ron Eldor 3b350856ff Have the temporary buffer allocated dynamically
Change `tmp` buffer to be dynamically allocated, as it is now
dependent on external label given as input, in `tls_prf_generic()`.
2019-05-15 13:38:39 +03:00
Ron Eldor a9f9a73920 Zeroize secret data in the exit point
Zeroize the secret data in `mbedtls_ssl_derive_keys()`
in the single exit point.
2019-05-15 13:38:39 +03:00
Ron Eldor e699270908 Add a single exit point in key derivation function
Add a single exit point in `mbedtls_ssl_derive_keys()`.
2019-05-15 13:38:39 +03:00
Ron Eldor 8b0c3c91e6 Fail in case critical crt policy not supported
In case the certificate policy is not of type `AnyPolicy`
set the returned error code to `MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE`
and continue parsing. If the extension is critical, return error anyway,
unless `MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION` is configured.
Fail parsing on any other error.
2019-05-15 12:20:00 +03:00
Gilles Peskine c160d9ec83 psa_copy_key: enforce PSA_KEY_USAGE_COPY
Implement the check and add a negative test.
2019-05-14 14:32:03 +02:00
Gilles Peskine 8e0206aa26 New usage flag PSA_KEY_USAGE_COPY
Document the new flag and allow its use.
2019-05-14 14:24:28 +02:00
Ron Eldor f05f594acb change the type of hardware_module_name member
Change the type of `hardware_module_name` struct from
`mbedtls_x509_name` to a unique struct, to distinguish it from the
named data type.
2019-05-13 19:23:08 +03:00
Ron Eldor 890819a597 Change mbedtls_x509_subject_alternative_name
Make `mbedtls_x509_subject_alternative_name` to be a single item
rather than a list. Adapt the subject alternative name parsing function,
to receive a signle `mbedtls_x509_buf` item from the subject_alt_names
sequence of the certificate.
2019-05-13 19:23:07 +03:00
Ron Eldor 0806379e3e Add length checking in certificate policy parsing
Change the extension parsing to `policy_end` and verify that
the policy and qualifiers length don't exceed the end of the extension.
2019-05-13 16:38:39 +03:00
Jaeden Amero 1fe90fab30
Merge pull request #101 from gilles-peskine-arm/psa-key_attributes-verify_attributes
Check unused attributes in import and copy
2019-05-13 11:48:40 +01:00
Janos Follath 293c3dae6d Remove redundant memset()
The preceding calloc() already zeroizes that memory area, therfore the
memset() is not necessary. Compilers are likely to optimize this out,
but it still can be confusing to readers.
2019-05-10 15:53:03 +01:00
Janos Follath 6c379b4b80 Propogate error when parsing SubjectAltNames
The previous behaviour of mbedtls_x509_parse_subject_alternative_name()
was to silently ignore errors coming from x509_get_other_name(). The
current commit fixes it and returns with an error.
2019-05-10 14:17:16 +01:00
Janos Follath 2f0ec1e3bf Tidy up style in x509_info_subject_alt_name 2019-05-10 11:06:31 +01:00
Janos Follath 22f605fbab Print unparseable SubjectAlternativeNames
In x509_info_subject_alt_name() we silently dropped names that we
couldn't parse because they are not supported or are malformed. (Being
malformed might mean damaged file, but can be a sign of incompatibility
between applications.)

This commit adds code notifying the user that there is something, but
we can't parse it.
2019-05-10 10:57:44 +01:00
Janos Follath ab23cd1eae Remove unneeded checks from x509_get_other_name
Lengths are aleady checked in mbedtls_asn1_get_len() which is called in
mbedtls_asn1_get_tag(), therefore it is not necessary to check
the lengths explicitly afterwards.

Also with the previous flow data was left in the output buffer on some
errors.
2019-05-09 15:05:30 +01:00
Ron Eldor 74d9acc144 Add support for certificate policies extension
Add support for certificate policies, as defined in rfc 5280.
Currently support only `anyPolicy` policy.
2019-05-07 17:05:45 +03:00
Ron Eldor b2dc3fa72e Suppport otherName of type hardware module name
Add support of parsing of subject alternative name, of type otherName.
Currently supports only hardware module name, as defined in rfc 4108.
2019-05-07 17:04:57 +03:00
Gilles Peskine f9666595e1 Implement and test the new key identifier range
Only allow creating keys in the application (user) range. Allow
opening keys in the implementation (vendor) range as well.

Compared with what the implementation allowed, which was undocumented:
0 is now allowed; values from 0x40000000 to 0xfffeffff are now
forbidden.
2019-05-06 18:56:30 +02:00
Gilles Peskine 225010fdf7 Remove lifetime parameter from psa_open_key
Change the scope of key identifiers to be global, rather than
per lifetime. As a result, you now need to specify the lifetime of a
key only when creating it.
2019-05-06 18:52:22 +02:00
Jack Lloyd 5d9c9636fa Add support for RSA PKCSv1.5 signatures using RIPEMD-160 2019-05-06 12:15:17 -04:00
Gilles Peskine 26869f2d9b Implement ChaCha20 and ChaCha20-Poly1305
Smoke tests: test data for ChaCha20 calculated with PyCryptodome; test
vector from RFC 7539 for ChaCha20-Poly1305.
2019-05-06 15:59:44 +02:00
Gilles Peskine f7e7b01a25 Minor refactoring in AEAD code
Make it a little easier to add ChaCha20-Poly1305.

This also fixes the error code in case mbedtls_gcm_setkey() fails with
a status that doesn't map to INVALID_ARGUMENT.
2019-05-06 15:59:44 +02:00
Gilles Peskine ff2d200fa5 Always include platform.h for MBEDTLS_ERR_PLATFORM_xxx
Recognize MBEDTLS_ERR_PLATFORM_xxx in mbedtls_to_psa_error().
2019-05-06 15:59:44 +02:00
Hanno Becker 67d42597a9 Avoid use of large stack buffers in mbedtls_x509_write_crt_pem()
This commit rewrites mbedtls_x509write_crt_pem() to not use
a statically size stack buffer to temporarily store the DER
encoded form of the certificate to be written.

This is not necessary because the DER-to-PEM conversion
accepts overlapping input and output buffers.
2019-05-04 08:13:23 +01:00
Hanno Becker def4305168 Perform CRT writing in-place on the output buffer
The CRT writing routine mbedtls_x509write_crt_der() prepares the TBS
(to-be-signed) part of the CRT in a temporary stack-allocated buffer,
copying it to the actual output buffer at the end of the routine.

This comes at the cost of a very large stack buffer. Moreover, its size
must be hardcoded to an upper bound for the lengths of all CRTs to be
written through the routine. So far, this upper bound was set to 2Kb, which
isn't sufficient some larger certificates, as was reported e.g. in #2631.

This commit fixes this by changing mbedtls_x509write_crt_der() to write
the certificate in-place in the output buffer, thereby avoiding the use
of a statically sized stack buffer for the TBS.

Fixes #2631.
2019-05-04 07:54:36 +01:00
Hanno Becker 6ad3fd105c Adapt x509write_crt.c to coding style
Avoid lines longer than 80 characters and fix indentation.
2019-05-04 07:38:39 +01:00
Gilles Peskine 4ce2a9dcbf Check unused attributes in import and copy
In psa_import_key and psa_copy_key, some information comes from the
key data (input buffer or source key) rather than from the attributes:
key size for import, key size and type and domain parameters for copy.
If an unused attribute is nonzero in the attribute structure, check
that it matches the correct value. This protects against application
errors.
2019-05-03 16:57:15 +02:00
Adrian L. Shaw 5a5a79ae2a Rename psa_generate_key() and psa_generator_import_key() 2019-05-03 15:44:28 +01:00
Jaeden Amero 75d9a333ce Merge remote-tracking branch 'origin/pr/1633' into development
* origin/pr/1633: (26 commits)
  Fix uninitialized variable access in debug output of record enc/dec
  Adapt PSA code to ssl_transform changes
  Ensure non-NULL key buffer when building SSL test transforms
  Catch errors while building SSL test transforms
  Use mbedtls_{calloc|free}() in SSL unit test suite
  Improve documentation of mbedtls_record
  Adapt record length value after encryption
  Alternative between send/recv transform in SSL record test suite
  Fix memory leak on failure in test_suite_ssl
  Rename ssl_decrypt_buf() to mbedtls_ssl_decrypt_buf() in comment
  Add record encryption/decryption tests for ARIA to SSL test suite
  Improve documentation of mbedtls_ssl_transform
  Double check that record expansion is as expected during decryption
  Move debugging output after record decryption
  Add encryption/decryption tests for small records
  Add tests for record encryption/decryption
  Reduce size of `ssl_transform` if no MAC ciphersuite is enabled
  Remove code from `ssl_derive_keys` if relevant modes are not enabled
  Provide standalone version of `ssl_decrypt_buf`
  Provide standalone version of `ssl_encrypt_buf`
  ...
2019-05-02 09:08:43 +01:00
Hanno Becker 031d6335b7 Fix mpi_bigendian_to_host() on bigendian systems
The previous implementation of mpi_bigendian_to_host() did
a byte-swapping regardless of the endianness of the system.

Fixes #2622.
2019-05-01 17:09:11 +01:00
Jaeden Amero 7b3603c6d8 Merge remote-tracking branch 'tls/development' into development
Resolve merge conflicts by performing the following actions:

- Reject changes to deleted files.
- Reject changes to generate_errors.pl and generate_visualc_files.pl.
  Don't add an 'include-crypto' option which would attempt to use the
  non-existent crypto submodule.
- list-identifiers.sh had the `--internal` option added to it, which
  lists identifiers only in internal headers. Add PSA-specific internal
  headers to list-identifiers.sh.

* origin/development: (40 commits)
  Document the scripts behaviour further
  Use check_output instead of Popen
  all.sh: Require i686-w64-mingw32-gcc version >= 6
  generate_visualc_files.pl: add mbedtls source shadowing by crypto
  generate_errors.pl: refactor and simplify the code
  Start unused variable with underscore
  Correct documentation
  generate_errors.pl: typo fix
  revert changes to generate_features.pl and generate_query_config.pl
  Check that the report directory is a directory
  Use namespaces instead of full classes
  Fix pylint issues
  Don't put abi dumps in subfolders
  Add verbose switch to silence all output except the final report
  Fetch the remote crypto branch, rather than cloning it
  Prefix internal functions with underscore
  Add RepoVersion class to make handling of many arguments easier
  Reduce indentation levels
  Improve documentation
  Use optional arguments for setting repositories
  ...
2019-05-01 14:12:43 +01:00
Jaeden Amero 4e952f6ebd Regenerate errors.c
Autogenerate errors.c There are changes in error.c due to updating the
crypto submodule to a version that no longer has the SSL, X.509, or net
modules. The errors are correctly sourced from Mbed TLS and not Mbed
Crypto, but they do move around within the file due to how the error
generator script is written.
2019-04-30 16:47:36 +01:00
Jaeden Amero 461fd58fb2
Merge pull request #71 from Patater/remove-non-crypto
Remove non-crypto code
2019-04-30 11:10:51 +01:00
Jaeden Amero d29db1f8ab Makefile: Remove extra debug print
Remove debug print added to print list of source files used in making
libmbedcrypto.

Fixes 92da0bd862 ("Makefile: Use generated source files from parent").
2019-04-29 15:06:33 +01:00
Gilles Peskine 9bc88c6e2c Document the key creation flow (start, variable, finish, and fail) 2019-04-28 11:48:29 +02:00
Gilles Peskine e56e878207 Remove extra parameter from psa_generate_key
Read extra data from the domain parameters in the attribute structure
instead of taking an argument on the function call.

Implement this for RSA key generation, where the public exponent can
be set as a domain parameter.

Add tests that generate RSA keys with various public exponents.
2019-04-26 17:37:50 +02:00
Gilles Peskine 772c8b16b4 psa_get_domain_parameters: for RSA, if e=65537, output an empty string 2019-04-26 17:37:21 +02:00
Gilles Peskine b699f07af0 Switch psa_{get,set}_domain_parameters to attributes
Change psa_get_domain_parameters() and psa_set_domain_parameters() to
access a psa_key_attributes_t structure rather than a key handle.

In psa_get_key_attributes(), treat the RSA public exponent as a domain
parameter and read it out. This is in preparation for removing the
`extra` parameter of psa_generate_key() and setting the RSA public
exponent for key generation via domain parameters.

In this commit, the default public exponent 65537 is not treated
specially, which allows us to verify that test code that should be
calling psa_reset_key_attributes() after retrieving the attributes of
an RSA key is doing so properly (if it wasn't, there would be a memory
leak), even if the test data happens to use an RSA key with the
default public exponent.
2019-04-26 17:37:08 +02:00
Jaeden Amero 18d4789947 CMake: Use generated source files from parent
When building as a submodule of a parent project, like Mbed TLS, use the
parent projects generated source files (error.c, version.c,
version_features.c)
2019-04-26 15:41:33 +01:00
Jaeden Amero 92da0bd862 Makefile: Use generated source files from parent
When building as a submodule of a parent project, like Mbed TLS, use the
parent projects generated source files (error.c, version.c,
version_features.c)
2019-04-26 15:41:33 +01:00
Jaeden Amero 8df5de42e2 Makefile: Output to explicit target
Don't depend on the C compiler's default output file name and path. Make
knows what it wants to build and where it should go, and this may not
always align with the C compiler default, so tell the C compilter to
output to the Make target explicitly.
2019-04-26 14:00:02 +01:00
Hanno Becker 1f10d7643f Fix uninitialized variable access in debug output of record enc/dec 2019-04-26 13:34:37 +01:00
Gilles Peskine 3a4f1f8e46 Set the key size as an attribute
Instead of passing a separate parameter for the key size to
psa_generate_key and psa_generator_import_key, set it through the
attributes, like the key type and other metadata.
2019-04-26 13:49:28 +02:00
Gilles Peskine 30afafd527 Fix build errors with MBEDTLS_PSA_CRYPTO_STORAGE_C disabled 2019-04-25 17:42:32 +02:00
Gilles Peskine 3495b58fcf Fix loading of 0-sized key on platforms where malloc(0)=NULL 2019-04-25 17:42:32 +02:00
Hanno Becker 22bf145599 Adapt PSA code to ssl_transform changes 2019-04-25 12:58:21 +01:00
Hanno Becker 78f839df94 Adapt record length value after encryption 2019-04-25 12:58:21 +01:00
Hanno Becker b2ca87d289 Rename ssl_decrypt_buf() to mbedtls_ssl_decrypt_buf() in comment 2019-04-25 12:58:21 +01:00
Hanno Becker 29800d2fd1 Double check that record expansion is as expected during decryption 2019-04-25 12:58:21 +01:00
Hanno Becker 1c0c37feed Move debugging output after record decryption
The debugging call printing the decrypted record payload happened
before updating ssl->in_msglen.
2019-04-25 12:58:21 +01:00
Hanno Becker a18d1320da Add tests for record encryption/decryption
This commit adds tests exercising mutually inverse pairs of
record encryption and decryption transformations for the various
transformation types allowed in TLS: Stream, CBC, and AEAD.
2019-04-25 12:58:21 +01:00
Hanno Becker d56ed2491b Reduce size of ssl_transform if no MAC ciphersuite is enabled
The hash contexts `ssl_transform->md_ctx_{enc/dec}` are not used if
only AEAD ciphersuites are enabled. This commit removes them from the
`ssl_transform` struct in this case, saving a few bytes.
2019-04-25 12:58:21 +01:00
Hanno Becker 8031d06cb2 Remove code from ssl_derive_keys if relevant modes are not enabled
This commit guards code specific to AEAD, CBC and stream cipher modes
in `ssl_derive_keys` by the respective configuration flags, analogous
to the guards that are already in place in the record decryption and
encryption functions `ssl_decrypt_buf` resp. `ssl_decrypt_buf`.
2019-04-25 12:58:21 +01:00
Hanno Becker 2e24c3b672 Provide standalone version of ssl_decrypt_buf
Analogous to the previous commit, but concerning the record decryption
routine `ssl_decrypt_buf`.

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

The following depicts the different behaviors:

1) Previous CBC padding check

1.a) Claimed padding length <= plaintext length

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

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

1.b) Claimed padding length > plaintext length

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

2) New CBC padding check

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

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

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

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

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

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

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

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

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

The `ciphersuite_info` pointer was used in other places outside
the encryption/decryption functions during the handshake, and for
these functions to work, this commit adds a `ciphersuite_info` pointer
field to the handshake-local `ssl_handshake_params` structure.
2019-04-25 12:58:21 +01:00
Hanno Becker 88aaf652b1 Remove key length field from ssl_transform
The `ssl_transform` security parameter structure contains opaque
cipher contexts for use by the record encryption/decryption functions
`ssl_decrypt_buf`/`ssl_encrypt_buf`, while the underlying key material
is configured once in `ssl_derive_keys` and is not explicitly dealt with
anymore afterwards. In particular, the key length is not needed
explicitly by the encryption/decryption functions but is nonetheless
stored in an explicit yet superfluous `keylen` field in `ssl_transform`.
This commit removes this field.
2019-04-25 12:57:19 +01:00
Jaeden Amero a4308b29a4 Remove unused TLS, NET, and X.509 files
We've removed all software that depends on or uses the TLS, NET, and
X.509 modules. This means TLS, NET, and X.509 are unused and can be
removed. Remove TLS, NET, and X.509.
2019-04-25 11:46:21 +01:00
Jaeden Amero bb1f701212 config: Remove X.509 options
Note that this fails check-names.sh because options that TLS and X.509
files use are no longer present in config.h.
2019-04-25 11:46:21 +01:00
Jaeden Amero 1c66e48670 config: Remove TLS and NET options
Remove TLS and NET options from config files and scripts.

Note that this fails check-names.sh because options that TLS and NET
files use are no longer present in config.h.
2019-04-25 11:46:21 +01:00