Compare commits

...
Sign in to create a new pull request.

1636 commits

Author SHA1 Message Date
Shelly Liberman
c6a7e6b0c4 Enhancement fixes
Co-authored-by: Andrzej Kurek <andrzej.kurek@arm.com>
Signed-off-by: Shelly Liberman <shelly.liberman@arm.com>
2020-08-05 15:40:15 +03:00
shelib01
4062d6ca68 Add user pointer and data size duplication to ssl context.
Signed-off-by: Shelly Liberman <shelly.liberman@arm.com>
2020-08-05 15:01:05 +03:00
Andrzej Kurek
7e6075b7fd
Merge pull request #3499 from AndrzejKurek/fi-duplicate-buffers-revert
Revert a part of the sensitive information duplication changes
2020-07-21 11:03:50 +02:00
Andrzej Kurek
cf3e35cc58
Revert a part of sensitive information duplication from tinycrypt
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
2020-07-15 22:32:30 -04:00
Andrzej Kurek
afec8853c5
Revert a part of the sensitive information duplication changes
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
2020-07-15 16:31:27 -04:00
Andrzej Kurek
c417c783e5
Merge pull request #3481 from AndrzejKurek/fi_duplicate_buffers_2
Duplicate sensitive buffer and buffer length information
2020-07-15 11:56:36 +02:00
Andrzej Kurek
45e719983f
Minor formatting and cosmetic changes
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
2020-07-08 10:09:44 -04:00
Andrzej Kurek
ca60937cf9
Add buffer and context clearing upon suspected FI
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
2020-07-08 09:25:49 -04:00
Andrzej Kurek
0919b142b6
Formatting changes
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
2020-07-06 15:28:59 -04:00
Andrzej Kurek
84bde419e1
Add FI countermeasures to the ssl module
This commit adds mainly buffer pointer and length duplication and checks,
but also some hamming distance and return values checking improvements.
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
2020-07-06 15:27:34 -04:00
Andrzej Kurek
74f7d0f03d
Duplicate sensitive buffer and buffer length information
Detect FI attacks on buffer pointers and buffer lengths.
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
2020-07-06 14:28:12 -04:00
Shelly Liberman
a24c8414cf
Merge pull request #3439 from piotr-now/fic_switch
Add FI countermeasures for sensitive switch instructions
2020-07-05 10:55:13 +03:00
Andrzej Kurek
1206cf1ff4
Merge pull request #3467 from AndrzejKurek/cipher-wrap-aes-128-optimize
Wrap AES 192 and 256 info structures in an !AES_ONLY_128_BIT_KEY_LENGTH define
2020-07-01 10:36:58 +01:00
Piotr Nowicki
78fc139121 Add FI countermeasures for sensitive switch instructions
Signed-off-by: Piotr Nowicki <piotr.nowicki@arm.com>
2020-06-30 14:11:52 +02:00
Andrzej Kurek
77647bd03b
Wrap AES 192 and 256 info structures in !AES_ONLY_128_BIT_KEY_LENGTH
This reduces the code size by not compiling in unnecessary info structures
when using only 128 bit AES.
Co-authored by: AnttiKauppila <antti.kauppila@arm.com>
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
2020-06-30 05:03:19 -04:00
Andrzej Kurek
98c847a483
Merge pull request #3395 from AndrzejKurek/sha-flow_ctrl
Add flow control to sha256
2020-06-22 11:30:53 +01:00
Andrzej Kurek
e5425a0944
Merge pull request #3408 from AndrzejKurek/hamming-distance-improvements
Hamming distance improvements
2020-06-22 08:28:55 +01:00
Andrzej Kurek
3a0df03364
Increase the Hamming distance of uECC_generate_random_int returns
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
2020-06-12 06:32:13 -04:00
Piotr Nowicki
f523c47578
Merge pull request #3403 from piotr-now/sca_memmove
Add mbedtls_platform_memmove() as a secured memcmp()
2020-06-10 14:52:02 +02:00
Piotr Nowicki
ce0aab4474 Add new error code PLATFORM_ALLOC_FAILED for mbedtls_platform_memmove()
Signed-off-by: Piotr Nowicki <piotr.nowicki@arm.com>
2020-06-10 13:51:32 +02:00
Andrzej Kurek
78f77eb4e6
Add flow control to sha256
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
2020-06-10 05:12:34 -04:00
Piotr Nowicki
c520b90507
Merge pull request #3390 from piotr-now/rndelay_comment
Add comment for mbedtls_platform_random_delay() and returning an FAULT_DETECTED error on potential FI attack detection
2020-06-10 09:13:10 +02:00
Piotr Nowicki
5d5841f450 Add mbedtls_platform_memmove() as a secured memcmp()
Signed-off-by: Piotr Nowicki <piotr.nowicki@arm.com>
2020-06-09 14:31:55 +02:00
Piotr Nowicki
e048b91d25 Add returning a FAULT_DETECTED error on suspected FI attacks
The change applies to the places where we prevent double synchronous
FI attacks with random delay, and where we do not respond to their
detection. The response to such an attack should be to return the
appropriate error code.

Signed-off-by: Piotr Nowicki <piotr.nowicki@arm.com>
2020-06-09 12:00:42 +02:00
Andrzej Kurek
8f52a8a8c0
Improve the Hamming distance of ssl_hs_is_proper_fragment return values
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
2020-06-08 11:02:22 -04:00
Andrzej Kurek
090365fe60
Improve the usage of uECC_RNG_Function
Since the mbed TLS implementation of rng wrapper returns the size of random
data generated upon success - check for it explicitly.
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
2020-06-08 11:00:51 -04:00
Piotr Nowicki
b06ec05dc0 Add comment for mbedtls_platform_random_delay()
Signed-off-by: Piotr Nowicki <piotr.nowicki@arm.com>
2020-06-08 14:21:38 +02:00
Andrzej Kurek
478b05c34c
Merge pull request #3355 from AndrzejKurek/fi_error_codes
Change the default value of status variables to an error
2020-06-08 08:57:33 +01:00
Andrzej Kurek
fd56f409b3
Change the default value of status variables to an error
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
2020-06-05 12:26:07 -04:00
Andrzej Kurek
0da03c70e9
Merge pull request #3379 from AndrzejKurek/fi_check_loops
Add flow control to tinycrypt verification
2020-06-01 17:05:41 +01:00
Andrzej Kurek
e601bcee00
Add flow control to tinycrypt verification
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
2020-06-01 07:31:15 -04:00
Piotr Nowicki
e071e42480
Merge pull request #3336 from piotr-now/baremetal_flowmon
Increasing resistance to fault injection attacks related with memory operations.
2020-06-01 08:09:26 +02:00
Piotr Nowicki
f0ab6d62ac Added some descriptions of functions
Signed-off-by: Piotr Nowicki <piotr.nowicki@arm.com>
2020-05-27 15:35:44 +02:00
Piotr Nowicki
1a9d33e8c8 Start comparison from a random location in the uECC_vli_equal.
This increases security and increases resistance to the side channel leakage.

Signed-off-by: Piotr Nowicki <piotr.nowicki@arm.com>
2020-05-27 15:34:49 +02:00
Andrzej Kurek
fc7c69df25
Merge pull request #3330 from AndrzejKurek/merge-2.16-8b34fef
Merge mbedtls-2.16 commit 8b34fef into baremetal
2020-05-27 10:00:59 +01:00
Andrzej Kurek
8ac4a55402
test_suite_x509parse: shorten test names
Change "Certificate" to "CRT" to shorten the test name and blend in
between surrounding tests.
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
2020-05-25 10:21:14 -04:00
Andrzej Kurek
220e61478f
Add a x509 prerequisite in x509_internal.h
Lack of this requirement caused warning when compiling the 
x509 test suites with config-thread.h from example configs,
resulting in an error when running from test-ref-configs.pl.
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
2020-05-21 10:13:38 -04:00
Manuel Pégourié-Gonnard
13bebd0edb
Keep SSL context const when hw accel is disabled
Signed-off-by: Manuel Pégourié-Gonnard <manuel.pegourie-gonnard@arm.com>
2020-05-21 10:13:26 -04:00
Andrzej Kurek
e861e704c0
Rename md_info_t to md_handle_t in test_suite_entropy
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
2020-05-21 10:13:11 -04:00
Manuel Pégourié-Gonnard
731d7c0dcc
Fix lack of cookie check on hard reconnect
Section 4.2.8 of RFC 6347 describes how to handle the case of a DTLS client
establishing a new connection using the same UDP quartet as an already active
connection, which we implement under the compile option
MBEDTLS_SSL_DLTS_CLIENT_PORT_REUSE. Relevant excerpts:

    [the server] MUST NOT destroy the existing
    association until the client has demonstrated reachability either by
    completing a cookie exchange or by completing a complete handshake
    including delivering a verifiable Finished message.
    [...]
    The reachability requirement prevents
    off-path/blind attackers from destroying associations merely by
    sending forged ClientHellos.

Our code chooses to use a cookie exchange for establishing reachability, but
unfortunately that check was effectively removed in a recent refactoring,
which changed what value ssl_handle_possible_reconnect() needs to return in
order for ssl_get_next_record() (introduced in that refactoring) to take the
proper action. Unfortunately, in addition to changing the value, the
refactoring also changed a return statement to an assignment to the ret
variable, causing the function to reach the code for a valid cookie, which
immediately destroys the existing association, effectively bypassing the
cookie verification.

This commit fixes that by immediately returning after sending a
HelloVerifyRequest when a ClientHello without a valid cookie is found. It also
updates the description of the function to reflect the new return value
convention (the refactoring updated the code but not the documentation).

The commit that changed the return value convention (and introduced the bug)
is 2fddd3765e, whose commit message explains the
change.

Note: this bug also indirectly caused the ssl-opt.sh test case "DTLS client
reconnect from same port: reconnect" to occasionally fail due to a race
condition between the reception of the ClientHello carrying a valid cookie and
the closure of the connection by the server after noticing the ClientHello
didn't carry a valid cookie after it incorrectly destroyed the previous
connection, that could cause that ClientHello to be invisible to the server
(if that message reaches the server just before it does `net_close()`). A
welcome side effect of this commit is to remove that race condition, as the
new connection will immediately start with a ClientHello carrying a valid
cookie in the SSL input buffer, so the server will not call `net_close()` and
not risk discarding a better ClientHello that arrived in the meantime.

Signed-off-by: Manuel Pégourié-Gonnard <manuel.pegourie-gonnard@arm.com>
2020-05-21 10:12:25 -04:00
Piotr Nowicki
4aaa34c03f Add flow monitor protection to mbedtls_platform_memcmp()
Signed-off-by: Piotr Nowicki <piotr.nowicki@arm.com>
2020-05-20 16:50:24 +02:00
Andrzej Kurek
825ebd483f
Merge mbedtls 2.16.6 into baremetal
Conflicts:
mbedtls.doxyfile - PROJECT_NAME - mbed TLS v2.16.6 chosen.
doc_mainpage.h - mbed TLS v2.16.6 version chosen.
hmac_drbg.h - line 260, extended description chosen.
            - line 313, extended description chosen.
            - line 338, extended description chosen.
version.h - 2.16.6 chosen.
CMakeLists.txt - 2.16.6 chosen.
test_suite_version.data - 2.16.6 chosen.
Makefile - 141 - manual correction - baremetal version of C_SOURCE_FILES
                 with variables for directories plus 2.16.6 CTAGS addition.
pkparse.c - lines 846 onwards - the asn1_get_nonzero_mpi implementation chosen.
ssl_tls.c - line 5269 - edited manually, left the ret=0, because baremetal has
            a different behaviour since commit 87b5626, but added a debug
            message that's new in 2.16.6.    
all.sh:
- component_build_deprecated - chosen the refactored version from 2.16.6,
                               but with extra flags from baremetal.
- rest of the _no_xxx tests - merged make options to have PTHREAD=1 and
                              other changes from 2.16.6 (like -O1 instead of -O0).
- component_build_arm_none_eabi_gcc_no_64bit_multiplication - added 
                              TINYCRYPT_BUILD=0 to the 2.16.6 version of make.

x509/req_app.c - left baremetal log but with mbedtls_exit( 0 ) call.
x509/crl_app.c - left baremetal log but with mbedtls_exit( 0 ) call.
x509/cert_app.c - left baremetal log but with mbedtls_exit( 0 ) call.
ssl/ssl_mail_client.c - left baremetal log but with mbedtls_exit( 0 ) call.
ssl/ssl_pthread_server.c - left baremetal log but with mbedtls_exit( 0 ) call.
ssl/ssl_fork_server.c - left baremetal log but with mbedtls_exit( 0 ) call.
ssl_client1.c - line 54 - left baremetal log but with mbedtls_exit( 0 ) call.
ssl_client2.c - line 54 - left baremetal log but with mbedtls_exit( 0 ) call.
              - line 132 - new options of both branches added.
              - skip close notify handled as in 2.16.6, but with `ssl` instead of `&ssl`.
              - Merged the 2.16.6 usage split with additional baremetal usages.
              - Merged options from baremetal and 2.16.6.
ssl_server.c - left baremetal log but with mbedtls_exit( 0 ) call.
ssl_server2.c - Merged the 2.16.6 usage split with additional baremetal usages.
config.pl - fixed missing defines from the documentation, removed duplicates,
            and reorganised so that the documentation and excluded list
            are ordered in the same way.
test_suite_x509parse.data - only added the two new pathlen tests.
x509_crt.c - change the return code by removing
             MBEDTLS_ERR_X509_INVALID_EXTENSIONS, since it's added by
             x509_crt_frame_parse_ext not by an "or", but by "+=".
Changelog - Assigned all entries to appropriate sections.
ssl-opt.sh - line 8263 - merged options.
           - removed lines 1165 - 1176 - there was a duplicate test, probably
             an artifact of previous merges.
check-files.py - sticked to old formatting.

Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
2020-05-18 11:47:25 -04:00
Simon Butcher
2d21e3e47b
Merge pull request #3044 from sbutcher-arm/merge-2.16-sprint27
[baremetal] Update `baremetal` branch with updates from `mbedtls-2.16` branch
2020-04-03 15:31:46 +01:00
Janos Follath
f3a13486f4 Revert "Merge pull request #3012 from Patater/dev/jp-bennett/development-2.16"
This reverts commit 7550e857bf, reversing
changes made to d0c2575324.

stat() will never return S_IFLNK as the file type, as stat()
explicitly follows symlinks.

Fixes #3005.
2020-03-13 17:08:43 +00:00
Gilles Peskine
a4c1c4b55d Test GCC and Clang with common build options
Goals:
* Build with common compilers with common options, so that we don't
  miss a (potentially useful) warning only triggered with certain
  build options.
* A previous commit removed -O0 test jobs, leaving only the one with
  -m32. We have inline assembly that is disabled with -O0, falling
  back to generic C code. This commit restores a test that runs the
  generic C code on a 64-bit platform.
2020-03-13 17:06:18 +00:00
Gilles Peskine
06c1e23960 Replace -O0 by -O1 or -Os in most components
Gcc skips some analyses when compiling with -O0, so we may miss
warnings about things like uninitialized variables.
2020-03-13 17:06:18 +00:00
Gilles Peskine
f5faa25cf4 shrink tests: clearer description 2020-03-13 16:23:45 +00:00
Gilles Peskine
7313e2caff Move test functions from Lilliput to Blefuscu
We normally represent bignums in big-endian order and there is no
reason to deviate here.
2020-03-13 16:23:45 +00:00
Gilles Peskine
8830bd2447 Minor comment improvement 2020-03-13 16:23:45 +00:00
Gilles Peskine
0660747057 Improve comments in mpi_shrink 2020-03-13 16:23:45 +00:00
Gilles Peskine
51c2e06eb8 mpi_copy: make the 0 case slightly more robust
If Y was constructed through functions in this module, then Y->n == 0
iff Y->p == NULL. However we do not prevent filling mpi structures
manually, and zero may be represented with n=0 and p a valid pointer.
Most of the code can cope with such a representation, but for the
source of mbedtls_mpi_copy, this would cause an integer underflow.
Changing the test for zero from Y->p==NULL to Y->n==0 causes this case
to work at no extra cost.
2020-03-13 16:23:45 +00:00
Gilles Peskine
edb621b84a Better coverage for copy and swap
Cover more cases: different signs, different zeronesses, repeated
argument.
2020-03-13 16:23:45 +00:00
Gilles Peskine
16fca92e3d Bignum copy/shrink: More precise test case descriptions 2020-03-13 16:23:45 +00:00
Gilles Peskine
95ce7dab34 Fix duplicated Bugfix section in the changelog 2020-03-13 16:23:45 +00:00
Gilles Peskine
a32e45d632 Add changelog entry 2020-03-13 16:21:44 +00:00
Manuel Pégourié-Gonnard
d817f54077 De-duplicate SHA1-independent test in ssl-opt.sh
The splitting of this test into two versions depending on whether SHA-1 was
allowed by the server was a mistake in
5d2511c4d4 - the test has nothing to do with
SHA-1 in the first place, as the server doesn't request a certificate from
the client so it doesn't matter if the server accepts SHA-1 or not.
2020-03-13 16:21:44 +00:00
Manuel Pégourié-Gonnard
7006ca10d9 Fix ssl-opt.sh for GnuTLS versions rejecting SHA-1
While the whole script makes (often implicit) assumptions about the version of
GnuTLS used, generally speaking it should work out of the box with the version
packaged on our reference testing platform, which is Ubuntu 16.04 so far.

With the update from Jan 8 2020 (3.4.10-4ubuntu1.6), the patches for rejecting
SHA-1 in certificate signatures were backported, so we should avoid presenting
SHA-1 signed certificates to a GnuTLS peer in ssl-opt.sh.
2020-03-13 16:21:44 +00:00
Jack Lloyd
32b6e6984d Parse RSA parameters DP, DQ and QP from PKCS1 private keys
Otherwise these values are recomputed in mbedtls_rsa_deduce_crt, which
currently suffers from side channel issues in the computation of QP
(see https://eprint.iacr.org/2020/055). By loading the pre-computed
values not only is the side channel avoided, but runtime overhead of
loading RSA keys is reduced.

Discussion in https://github.com/ARMmbed/mbed-crypto/issues/347

Backport of https://github.com/ARMmbed/mbed-crypto/pull/352
2020-03-13 16:21:44 +00:00
Manuel Pégourié-Gonnard
9a5c8d4b5b Fix previous ChangeLog merging error 2020-03-13 16:21:44 +00:00
Manuel Pégourié-Gonnard
7489f81be7 Fix contributor names in ChangeLog 2020-03-13 16:21:44 +00:00
Jaeden Amero
99999b73b1 Add ChangeLog entry
Add a ChangeLog entry for Jonathan Bennett's contribution which allows
loading symlinked certificates.
2020-03-13 16:21:44 +00:00
Jonathan Bennett
b9082ed820 Allow loading symlinked certificates
When mbedtls_x509_crt_parse_path() checks each object in the supplied path, it only processes regular files. This change makes it also accept a symlink to a file. Fixes #3005.

This was observed to be a problem on Fedora/CentOS/RHEL systems, where the ca-bundle in the default location is actually a symlink.
2020-03-13 15:37:54 +00:00
Gilles Peskine
0f14c15842 Add missing return code check on calls to mbedtls_md() 2020-03-13 15:37:54 +00:00
Gilles Peskine
a48fe01f15 Check that mbedtls_mpi_grow succeeds 2020-03-13 15:37:54 +00:00
Gilles Peskine
010efeb5a2 Remove redundant block_size validity check
Check the value only once, as soon as we've obtained it.
2020-03-13 15:37:54 +00:00
Manuel Pégourié-Gonnard
aa377cf111 Fix incrementing pointer instead of value
This was introduced by a hasty search-and-replace that didn't account for C's
operator precedence when changing those variables to pointer types.
2020-03-13 15:37:54 +00:00
Gilles Peskine
c0213a91ab Add changelog entry for the unchecked mbedtls_md call 2020-03-13 15:37:03 +00:00
Gilles Peskine
140f50206e Add missing return code check on call to mbedtls_md() 2020-03-13 15:36:05 +00:00
Janos Follath
e7b49d3cd1 Bump version to Mbed TLS 2.16.4 2020-03-13 15:36:05 +00:00
Manuel Pégourié-Gonnard
10a7f626d9 Add test for record compression in ssl-opt.sh
Deprecated but still needs to be tested.
2020-03-13 15:36:05 +00:00
Gilles Peskine
8b7f03f172 Catch AES failure in mbedtls_ctr_drbg_random
The functions mbedtls_ctr_drbg_random() and
mbedtls_ctr_drbg_random_with_add() could return 0 if an AES function
failed. This could only happen with alternative AES
implementations (the built-in implementation of the AES functions
involved never fail), typically due to a failure in a hardware
accelerator.

Bug reported and fix proposed by Johan Uppman Bruce and Christoffer
Lauri, Sectra.
2020-03-13 15:36:04 +00:00
Gilles Peskine
bcdd8bcfcf Enable more test cases without MBEDTLS_MEMORY_DEBUG
None of the test cases in tests_suite_memory_buffer_alloc actually
need MBEDTLS_MEMORY_DEBUG. Some have additional checks when
MBEDTLS_MEMORY_DEBUG but all are useful even without it. So enable
them all and #ifdef out the parts that require DEBUG.
2020-03-13 15:27:12 +00:00
Gilles Peskine
6a1ec6abea More accurate test case description 2020-03-13 15:27:12 +00:00
Gilles Peskine
8064dbb646 Clarify that the "FATAL" message is expected
The test case "Memory buffer small buffer" emits a message
"FATAL: verification of first header failed". In this test case, it's
actually expected, but it looks weird to see this message from a
passing test. Add a comment that states this explicitly, and modify
the test description to indicate that the failure is expected, and
change the test function name to be more accurate.

Fix #309
2020-03-13 15:27:12 +00:00
Andrzej Kurek
a8405447aa Zeroize local AES variables before exiting the function
This issue has been reported by Tuba Yavuz, Farhaan Fowze, Ken (Yihang) Bai,
Grant Hernandez, and Kevin Butler (University of Florida) and
Dave Tian (Purdue University).

In AES encrypt and decrypt some variables were left on the stack. The value
of these variables can be used to recover the last round key. To follow best
practice and to limit the impact of buffer overread vulnerabilities (like
Heartbleed) we need to zeroize them before exiting the function.
2020-03-13 15:27:12 +00:00
Janos Follath
e9db2aa5b4 mpi_lt_mpi_ct: fix condition handling
The code previously only set the done flag if the return value was one.
This led to overriding the correct return value later on.
2020-03-13 15:25:40 +00:00
Janos Follath
47b56a159e mpi_lt_mpi_ct: Add further tests
The existing tests did not catch a failure that came up at integration
testing. Adding the missing test cases to trigger the bug.
2020-03-13 15:25:40 +00:00
Janos Follath
006b207de6 mpi_lt_mpi_ct: Fix test numbering 2020-03-13 15:25:40 +00:00
Janos Follath
d2aa4aa454 mpi_lt_mpi_ct perform tests for both limb size
The corner case tests were designed for 32 and 64 bit limbs
independently and performed only on the target platform. On the other
platform they are not corner cases anymore, but we can still exercise
them.
2020-03-13 15:25:40 +00:00
Janos Follath
3d2b769d1c ct_lt_mpi_uint: cast the return value explicitely
The return value is always either one or zero and therefore there is no
risk of losing precision. Some compilers can't deduce this and complain.
2020-03-13 15:25:40 +00:00
Janos Follath
44e40c0792 mbedtls_mpi_lt_mpi_ct: add tests for 32 bit limbs
The corner case tests were designed for 64 bit limbs and failed on 32
bit platforms because the numbers in the test ended up being stored in a
different number of limbs and the function (correctly) returnd an error
upon receiving them.
2020-03-13 15:25:40 +00:00
Janos Follath
c8256e7020 mbedtls_mpi_lt_mpi_ct: simplify condition
In the case of *ret we might need to preserve a 0 value throughout the
loop and therefore we need an extra condition to protect it from being
overwritten.

The value of done is always 1 after *ret has been set and does not need
to be protected from overwriting. Therefore in this case the extra
condition can be removed.
2020-03-13 15:25:40 +00:00
Janos Follath
ec4c42a95f Rename variable for better readability 2020-03-13 15:25:40 +00:00
Janos Follath
cf7eeef2cc mbedtls_mpi_lt_mpi_ct: Improve documentation 2020-03-13 15:25:40 +00:00
Janos Follath
aa9e7a4717 Make mbedtls_mpi_lt_mpi_ct more portable
The code relied on the assumptions that CHAR_BIT is 8 and that unsigned
does not have padding bits.

In the Bignum module we already assume that the sign of an MPI is either
-1 or 1. Using this, we eliminate the above mentioned dependency.
2020-03-13 15:25:40 +00:00
Janos Follath
f8dbfd4f05 Bignum: Document assumptions about the sign field 2020-03-13 15:25:40 +00:00
Janos Follath
eb8fcf8181 Add more tests for mbedtls_mpi_lt_mpi_ct 2020-03-13 15:25:40 +00:00
Janos Follath
3be2fa44e1 mpi_lt_mpi_ct test: hardcode base 16 2020-03-13 15:25:40 +00:00
Janos Follath
3480947667 Document ct_lt_mpi_uint 2020-03-13 15:25:40 +00:00
Janos Follath
afa5342452 mpi_lt_mpi_ct: make use of unsigned consistent 2020-03-13 15:25:40 +00:00
Janos Follath
a830377142 ct_lt_mpi_uint: make use of biL 2020-03-13 15:25:40 +00:00
Janos Follath
8faf1d627b Change mbedtls_mpi_cmp_mpi_ct to check less than
The signature of mbedtls_mpi_cmp_mpi_ct() meant to support using it in
place of mbedtls_mpi_cmp_mpi(). This meant full comparison functionality
and a signed result.

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

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

The only drawback is that we need to call the function twice when
checking for equality, but this can be optimised later if an when it is
needed.
2020-03-13 15:25:40 +00:00
Janos Follath
81c9fe5f2c mbedtls_mpi_cmp_mpi_ct: remove multiplications
Multiplication is known to have measurable timing variations based on
the operands. For example it typically is much faster if one of the
operands is zero. Remove them from constant time code.
2020-03-13 15:25:40 +00:00
Janos Follath
fd9797b595 Remove excess vertical space 2020-03-13 15:25:40 +00:00
Janos Follath
78ed22b404 Remove declaration after statement
Visual Studio 2013 does not like it for some reason.
2020-03-13 15:25:40 +00:00
Janos Follath
fc2a826ab4 Fix side channel vulnerability in ECDSA 2020-03-13 15:25:39 +00:00
Janos Follath
7ce3a25316 Add tests to constant time mpi comparison 2020-03-13 15:25:39 +00:00
Janos Follath
c514ce474a Add new, constant time mpi comparison 2020-03-13 15:25:39 +00:00
Gilles Peskine
a5e2d86c3f Note that mbedtls_ctr_drbg_seed() must not be called twice
You can't reuse a CTR_DRBG context without free()ing it and
re-init()ing it. This generally happened to work, but was never
guaranteed. It could have failed with alternative implementations of
the AES module because mbedtls_ctr_drbg_seed() calls
mbedtls_aes_init() on a context which is already initialized if
mbedtls_ctr_drbg_seed() hasn't been called before, plausibly causing a
memory leak.

Calling free() and seed() with no intervening init fails when
MBEDTLS_THREADING_C is enabled and all-bits-zero is not a valid mutex
representation.
2020-03-13 15:25:39 +00:00
Gilles Peskine
216040d46f Fix CTR_DRBG benchmark
You can't reuse a CTR_DRBG context without free()ing it and
re-init()ing. This generally happened to work, but was never
guaranteed. It could have failed with alternative implementations of
the AES module because mbedtls_ctr_drbg_seed() calls
mbedtls_aes_init() on a context which is already initialized if
mbedtls_ctr_drbg_seed() hasn't been called before, plausibly causing a
memory leak. Calling free() and seed() with no intervening init fails
when MBEDTLS_THREADING_C is enabled and all-bits-zero is not a valid
mutex representation. So add the missing free() and init().
2020-03-13 15:25:39 +00:00
Janos Follath
d69ae8c21d Add ChangeLog entry 2020-03-13 15:25:39 +00:00
Janos Follath
6bd8c0ae2a ECDSA: Fix side channel vulnerability
The blinding applied to the scalar before modular inversion is
inadequate. Bignum is not constant time/constant trace, side channel
attacks can retrieve the blinded value, factor it (it is smaller than
RSA keys and not guaranteed to have only large prime factors). Then the
key can be recovered by brute force.

Reducing the blinded value makes factoring useless because the adversary
can only recover pk*t+z*N instead of pk*t.
2020-03-13 15:25:39 +00:00
Gilles Peskine
bb3d55665e Changelog entry for xxx_drbg_set_entropy_len before xxx_drbg_seed 2020-03-13 15:25:39 +00:00
Gilles Peskine
20dbfb9938 CTR_DRBG: support set_entropy_len() before seed()
mbedtls_ctr_drbg_seed() always set the entropy length to the default,
so a call to mbedtls_ctr_drbg_set_entropy_len() before seed() had no
effect. Change this to the more intuitive behavior that
set_entropy_len() sets the entropy length and seed() respects that and
only uses the default entropy length if there was no call to
set_entropy_len().

The former test-only function mbedtls_ctr_drbg_seed_entropy_len() is
no longer used, but keep it for strict ABI compatibility.
2020-03-13 15:25:39 +00:00
Gilles Peskine
f0bf757f9c CTR_DRBG: Don't use functions before they're defined
Move the definitions of mbedtls_ctr_drbg_seed_entropy_len() and
mbedtls_ctr_drbg_seed() to after they are used. This makes the code
easier to read and to maintain.
2020-03-13 15:25:39 +00:00
Gilles Peskine
1d2a9e88c3 HMAC_DRBG: support set_entropy_len() before seed()
mbedtls_hmac_drbg_seed() always set the entropy length to the default,
so a call to mbedtls_hmac_drbg_set_entropy_len() before seed() had no
effect. Change this to the more intuitive behavior that
set_entropy_len() sets the entropy length and seed() respects that and
only uses the default entropy length if there was no call to
set_entropy_len().
2020-03-13 15:24:20 +00:00
Gilles Peskine
6e2cb64a97 'make test' must fail if Asan fails
When running 'make test' with GNU make, if a test suite program
displays "PASSED", this was automatically counted as a pass. This
would in particular count as passing:
* A test suite with the substring "PASSED" in a test description.
* A test suite where all the test cases succeeded, but the final
  cleanup failed, in particular if a sanitizer reported a memory leak.

Use the test executable's return status instead to determine whether
the test suite passed. It's always 0 on PASSED unless the executable's
cleanup code fails, and it's never 0 on any failure.

Fix ARMmbed/mbed-crypto#303
2020-03-13 15:24:20 +00:00
Gilles Peskine
6eec4ab323 Asan make builds: avoid sanitizer recovery
Some sanitizers default to displaying an error message and recovering.
This could result in a test being recorded as passing despite a
complaint from the sanitizer. Turn off sanitizer recovery to avoid
this risk.
2020-03-13 15:24:20 +00:00
Gilles Peskine
b3e54396fa Use UBsan in addition to Asan with 'make test'
When building with make with the address sanitizer enabled, also
enable the undefined behavior sanitizer.
2020-03-13 15:24:19 +00:00
Gilles Peskine
3ccb7f18e0 Unify ASan options in make builds
Use a common set of options when building with Asan without CMake.
2020-03-13 15:24:19 +00:00
Gilles Peskine
6b5e60c26c config.pl full: exclude MBEDTLS_CTR_DRBG_USE_128_BIT_KEY
This is a variant toggle, not an extra feature, so it should be tested
separately.
2020-03-13 15:22:14 +00:00
Gilles Peskine
d41a95e223 mbedtls_hmac_drbg_set_entropy_len() only matters when reseeding
The documentation of HMAC_DRBG erroneously claimed that
mbedtls_hmac_drbg_set_entropy_len() had an impact on the initial
seeding. This is in fact not the case: mbedtls_hmac_drbg_seed() forces
the entropy length to its chosen value. Fix the documentation.
2020-03-13 15:22:14 +00:00
Gilles Peskine
5fc111fe69 mbedtls_ctr_drbg_set_entropy_len() only matters when reseeding
The documentation of CTR_DRBG erroneously claimed that
mbedtls_ctr_drbg_set_entropy_len() had an impact on the initial
seeding. This is in fact not the case: mbedtls_ctr_drbg_seed() forces
the initial seeding to grab MBEDTLS_CTR_DRBG_ENTROPY_LEN bytes of
entropy. Fix the documentation and rewrite the discussion of the
entropy length and the security strength accordingly.
2020-03-13 15:22:14 +00:00
Gilles Peskine
4c57b20247 mbedtls_ctr_drbg_seed: correct maximum for len 2020-03-13 15:22:14 +00:00
Gilles Peskine
5953660a6a Add a note about CTR_DRBG security strength to config.h 2020-03-13 15:22:14 +00:00
Gilles Peskine
e1dc2de900 Move MBEDTLS_CTR_DRBG_USE_128_BIT_KEY to the correct section
It's an on/off feature, so it should be listed in version_features.
2020-03-13 15:22:14 +00:00
Gilles Peskine
6e36d0b33c CTR_DRBG: more consistent formatting and wording
In particular, don't use #MBEDTLS_xxx on macros that are undefined in
some configurations, since this would be typeset with a literal '#'.
2020-03-13 15:22:14 +00:00
Gilles Peskine
9640403fa0 CTR_DRBG documentation: further wording improvements 2020-03-13 15:22:14 +00:00
Gilles Peskine
7b674eac64 CTR_DRBG: Improve the explanation of security strength
Separate the cases that achieve a 128-bit strength and the cases that
achieve a 256-bit strength.
2020-03-13 15:22:14 +00:00
Gilles Peskine
7df4b7b3b6 CTR_DRBG: make it easier to understand the security strength
Explain how MBEDTLS_CTR_DRBG_ENTROPY_LEN is set next to the security
strength statement, rather than giving a partial explanation (current
setting only) in the documentation of MBEDTLS_CTR_DRBG_ENTROPY_LEN.
2020-03-13 15:22:14 +00:00
Gilles Peskine
56f628ca26 HMAC_DRBG: note that the initial seeding grabs entropy for the nonce 2020-03-13 15:22:14 +00:00
Gilles Peskine
beddfdcd7f Use standard terminology to describe the personalization string
NIST and many other sources call it a "personalization string", and
certainly not "device-specific identifiers" which is actually somewhat
misleading since this is just one of many things that might go into a
personalization string.
2020-03-13 15:22:13 +00:00
Gilles Peskine
57553fa2f0 Do note that xxx_drbg_random functions reseed with PR enabled 2020-03-13 15:22:13 +00:00
Gilles Peskine
20a3846725 Consistently use \c NULL and \c 0 2020-03-13 15:22:13 +00:00
Gilles Peskine
9e2543bd4f Also mention HMAC_DRBG in the changelog entry
There were no tricky compliance issues for HMAC_DBRG, unlike CTR_DRBG,
but mention it anyway. For CTR_DRBG, summarize the salient issue.
2020-03-13 15:22:13 +00:00
Gilles Peskine
ccb38381e8 HMAC_DRBG: improve the documentation of the entropy length 2020-03-13 15:21:09 +00:00
Gilles Peskine
4bfe4540f3 HMAC_DRBG documentation improvements clarifications
Improve the formatting and writing of the documentation based on what
had been done for CTR_DRBG.

Document the maximum size and nullability of some buffer parameters.
2020-03-13 15:21:08 +00:00
Gilles Peskine
f17079d960 More CTR_DRBG documentation improvements and clarifications 2020-03-13 12:03:12 +00:00
Gilles Peskine
34693b5dd6 Add a test component with malloc(0) returning NULL
Exercise the library functions with calloc returning NULL for a size
of 0. Make this a separate job with UBSan (and ASan) to detect
places where we try to dereference the result of calloc(0) or to do
things like

    buf = calloc(size, 1);
    if (buf == NULL && size != 0) return INSUFFICIENT_MEMORY;
    memcpy(buf, source, size);

which has undefined behavior when buf is NULL at the memcpy call even
if size is 0.

This is needed because other test components jobs either use the system
malloc which returns non-NULL on Linux and FreeBSD, or the
memory_buffer_alloc malloc which returns NULL but does not give as
useful feedback with ASan (because the whole heap is a single C
object).
2020-03-13 12:03:12 +00:00
Gilles Peskine
99d76f8805 Add a calloc self-test
Add a very basic test of calloc to the selftest program. The selftest
program acts in its capacity as a platform compatibility checker rather
than in its capacity as a test of the library.

The main objective is to report whether calloc returns NULL for a size
of 0. Also observe whether a free/alloc sequence returns the address
that was just freed and whether a size overflow is properly detected.
2020-03-13 12:03:12 +00:00
Gilles Peskine
c32f74cf8e Fix wording 2020-03-13 12:03:12 +00:00
Gilles Peskine
03642fa026 Remove warning that the previous expanded discussion has obsoleted 2020-03-13 12:03:12 +00:00
Gilles Peskine
2d83fe1383 CTR_DRBG: improve the discussion of entropy length vs strength 2020-03-13 12:03:12 +00:00
Gilles Peskine
bb2b8da7d7 CTR_DRBG: Finish an unfinished paragraph 2020-03-13 12:03:12 +00:00
Gilles Peskine
ca28583e95 CTR_DRBG documentation: add changelog entry
This is a documentation-only change, but one that users who care about
NIST compliance may be interested in, to review if they're using the
module in a compliant way.
2020-03-13 12:03:12 +00:00
Gilles Peskine
e3dc5942c5 CTR_DRBG: Document the security strength and SP 800-90A compliance
Document that a derivation function is used.

Document the security strength of the DRBG depending on the
compile-time configuration and how it is set up. In particular,
document how the nonce specified in SP 800-90A is set.

Mention how to link the ctr_drbg module with the entropy module.
2020-03-13 12:01:28 +00:00
Gilles Peskine
c1c9292d2f CTR_DRBG: Document the maximum size of some parameters 2020-03-13 12:01:28 +00:00
Gilles Peskine
da5ccce88e CTR_DRBG documentation clarifications
* State explicit whether several numbers are in bits or bytes.
* Clarify whether buffer pointer parameters can be NULL.
* Explain the value of constants that are dependent on the configuration.
2020-03-13 12:01:28 +00:00
Simon Butcher
eb7428cc33 Merge remote-tracking branch 'public/pr/3093' into baremetal 2020-03-10 15:17:39 +00:00
Manuel Pégourié-Gonnard
f0658b18dc Add detection for zlib headers to all.sh
Signed-off-by: Simon Butcher <simon.butcher@arm.com>
2020-03-09 17:39:04 +00:00
Manuel Pégourié-Gonnard
ae48d86cb1 Fix bug in record decompression
ssl_decompress_buf() was operating on data from the ssl context, but called at
a point where this data is actually in the rec structure. Call it later so
that the data is back to the ssl structure.

Signed-off-by: Simon Butcher <simon.butcher@arm.com>
2020-03-09 17:39:04 +00:00
Manuel Pégourié-Gonnard
079864ef54 Add test for record compression in ssl-opt.sh
Deprecated but still needs to be tested.

Signed-off-by: Simon Butcher <simon.butcher@arm.com>
2020-03-09 17:39:04 +00:00
Manuel Pégourié-Gonnard
df59bfc9d6 Add all.sh components with ZLIB enabled
ZLIB support is deprecated, but until it's removed it should still be tested.

Signed-off-by: Simon Butcher <simon.butcher@arm.com>
2020-03-09 17:39:04 +00:00
Gilles Peskine
e4d4b1f3d3 Add changelog entry for the zlib support fix
Signed-off-by: Simon Butcher <simon.butcher@arm.com>
2020-03-09 17:39:04 +00:00
jiblime
92af9a9792 Fixes definition error when the deprecated MBEDTLS_ZLIB_SUPPORT and ENABLE_ZLIB_SUPPORT macro are defined/enabled for zlib support in mbedtls
100% tests passed, 0 tests failed out of 85

https://github.com/ARMmbed/mbedtls/blob/mbedtls-2.19.1/library/ssl_tls.c#L1842

https://github.com/ARMmbed/mbedtls/blob/mbedtls-2.19.1/library/ssl_tls.c#L1862
Signed-off-by: Simon Butcher <simon.butcher@arm.com>
2020-03-09 17:39:04 +00:00
Simon Butcher
8eefb9b3b8 Merge remote-tracking branch 'public/pr/2986' into baremetal 2020-01-30 19:49:37 +00:00
Arto Kinnunen
17540ab74c Fix usage of randomized number in AES
-Fix usage of randomized bits (do not reuse the bits)
-Update comments
2020-01-21 12:01:42 +02:00
Arto Kinnunen
311ab594d7 Flag SCA_CM encrypt/decrypt functions
There is a 50% performance drop in the SCA_CM enabled encrypt and
decrypt functions. Therefore use the older version of encrypt/decypt
functions when SCA_CM is disabled.
2020-01-21 12:01:42 +02:00
Arto Kinnunen
2b24f4280f AES review corrections
-Do not reuse any part of randomized number, use separate byte for
 each purpose.
-Combine some separate loops together to get rid of gap between them
-Extend usage of flow_control
2020-01-21 12:01:42 +02:00
Arto Kinnunen
98c93af1ef Randomize number of AES dummy calculation rounds
Use either 4 or 5 dummy rounds in AES encryption/decryption.
2020-01-21 12:01:42 +02:00
Arto Kinnunen
2eb678f5e8 Update AES SCA countermeasures
-Add dummy rounds to the start and/or end of the AES calculation
 rounds.
2020-01-21 12:01:42 +02:00
Arto Kinnunen
28ecfb002f Merge remote-tracking branch 'upstream/pr/2983' into baremetal
* upstream/pr/2983:
  Fix mbedtls_strerror to work with all wanted codes
2020-01-17 11:21:53 +02:00
Arto Kinnunen
ca1978b7d5 Merge remote-tracking branch 'upstream/pr/2982' into baremetal
* upstream/pr/2982:
  Use mbedtls_platform_memset in data_randomize
  Protect get/put on secret data on AES-module
2020-01-17 11:21:41 +02:00
Arto Kinnunen
d1340e455c Merge remote-tracking branch 'upstream/pr/2980' into baremetal
* upstream/pr/2980:
  Protect get/put on secret data on sha256-module
2020-01-17 11:21:32 +02:00
Arto Kinnunen
10a2ffde5d Merge remote-tracking branch 'upstream/pr/2945' into baremetal
* upstream/pr/2945:
  Rename macro MBEDTLS_MAX_RAND_DELAY
  Update signature of mbedtls_platform_random_delay
  Replace mbedtls_platform_enforce_volatile_reads 2
  Replace mbedtls_platform_enforce_volatile_reads
  Add more variation to random delay countermeasure
  Add random  delay to enforce_volatile_reads
  Update comments of mbedtls_platform_random_delay
  Follow Mbed TLS coding style
  Add random delay function to platform_utils
2020-01-17 11:21:16 +02:00
Jarno Lamsa
8f8c0bdfc7 Use mbedtls_platform_memset in data_randomize
More secure memset should be used here instead
of standard memset.
2020-01-10 08:19:37 +02:00
Jarno Lamsa
282db8e3f8 Protect get/put on secret data on AES-module
When reading the input, buffer will be initialised with random data
and the reading will start from a random offset. When writing the data,
the output will be initialised with random data and the writing will start
from a random offset.
2020-01-10 08:19:37 +02:00
Teppo Järvelin
5bc072f737 Fix mbedtls_strerror to work with all wanted codes 2020-01-09 14:22:32 +02:00
Arto Kinnunen
b148651e49 Rename macro MBEDTLS_MAX_RAND_DELAY
MBEDTLS_MAX_RAND_DELAY renamed to MAX_RAND_DELAY to get CI passing.
2020-01-09 11:11:23 +02:00
Arto Kinnunen
ac6d226939 Update signature of mbedtls_platform_random_delay
Skip parameter and return value from mbedtls_platform_random_delay
to make it more resistant for FI attacks.
2020-01-09 10:19:07 +02:00
Simon Butcher
05ca9d46c1 Merge remote-tracking branch 'public/pr/2979' into baremetal 2020-01-08 18:15:52 +00:00
Simon Butcher
282911eabf Merge remote-tracking branch 'public/pr/2978' into baremetal 2020-01-08 18:14:21 +00:00
Simon Butcher
01d78fcefe Merge remote-tracking branch 'public/pr/2971' into baremetal 2020-01-08 18:10:44 +00:00
Simon Butcher
2d9c0eb215 Merge remote-tracking branch 'public/pr/2948' into baremetal 2020-01-08 18:08:28 +00:00
Simon Butcher
4b3b8c208e Merge remote-tracking branch 'public/pr/2886' into baremetal 2020-01-08 17:53:43 +00:00
Simon Butcher
5dc7faf56e Merge remote-tracking branch 'public/pr/2956' into baremetal 2020-01-08 17:53:16 +00:00
Jarno Lamsa
bb86c52430 Protect get/put on secret data on sha256-module
When reading the input, the buffer will be initialised with random data
and the reading will start from a random offset. When writing the data,
the output will be initialised with random data and the writing will
start from a random offset.
2020-01-08 10:45:51 +02:00
Teppo Järvelin
cafb6c91b0 Clear internal decrypted buffer after read 2020-01-08 10:25:16 +02:00
Arto Kinnunen
0a8f87f5eb Remove entropy source overwrite in baremetal_test
-Do not overwrite MBEDTLS_ENTROPY_MAX_SOURCES in baremetal_test.h
-Skip tests that are not suitable for low number of entropy sources
2020-01-07 14:48:33 +02:00
Arto Kinnunen
7195571681 Replace mbedtls_platform_enforce_volatile_reads 2
Replace remaining mbedtls_platform_enforce_volatile_reads() with
mbedtls_platform_random_delay().
2020-01-07 10:47:58 +02:00
Arto Kinnunen
e91f0dc905 Replace mbedtls_platform_enforce_volatile_reads
Replace function mbedtls_platform_enforce_volatile_reads() with
mbedtls_platform_random_delay().
2020-01-07 10:47:58 +02:00
Arto Kinnunen
dbf2b43ceb Add more variation to random delay countermeasure
Add more variation to the random delay function by xor:ing two
variables. It is not enough to increment just a counter to create a
delay as it will be visible as uniform delay that can be easily
removed from the trace by analysis.
2020-01-07 10:47:58 +02:00
Arto Kinnunen
0490485be5 Add random delay to enforce_volatile_reads
Add a random delay to mbedtls_platform_enforce_volatile_reads() as a
countermeasure to fault injection attacks.
2020-01-07 10:47:58 +02:00
Arto Kinnunen
9a506e7424 Update comments of mbedtls_platform_random_delay 2020-01-07 10:47:58 +02:00
Arto Kinnunen
b47b105838 Follow Mbed TLS coding style 2020-01-07 10:47:58 +02:00
Arto Kinnunen
4c63b98e94 Add random delay function to platform_utils
Add delay function to platform_utils. The function will delay
program execution by incrementing local variable randomised number of
times.
2020-01-07 10:47:58 +02:00
Teppo Järvelin
c2fa3eaa81 Removed dead code after optimization in tinycrypt 2020-01-05 12:02:37 +02:00
Teppo Järvelin
8f7e36fc98 Coverity fixes, check hmac return values 2020-01-05 12:02:37 +02:00
Teppo Järvelin
0b1d7d946d Coverity fix: dead error condition removed from ecc.c 2020-01-05 12:02:04 +02:00
Simon Butcher
7d2434fac2 Merge remote-tracking branch 'public/pr/2973' into baremetal 2020-01-03 15:52:36 +00:00
Darryl Green
029fe86c53 Fix some pylint warnings
Fix a too-long line to meet PEP8 standards
2020-01-03 13:41:20 +00:00
Simon Butcher
1b370a63ec Merge remote-tracking branch 'public/pr/2960' into baremetal 2019-12-27 18:18:22 +00:00
Simon Butcher
58813498f7 Merge remote-tracking branch 'public/pr/2957' into baremetal 2019-12-27 18:18:04 +00:00
Jarno Lamsa
5aa4c07b85 Minor review fixes 2019-12-20 13:09:27 +02:00
Jarno Lamsa
015aa44b93 Make authmode volatile
This is to enforce reading it from memory for the double
check to prevent compiler from optimising it away.
2019-12-20 12:09:37 +02:00
Jarno Lamsa
af60cd7698 Protect the peer_authenticated flag more
Add more protection to the flag preventing attacker
possibly to glitch using faulty certificate.
2019-12-20 10:50:33 +02:00
Jarno Lamsa
616fbe177c Increase hamming distance for authmode
Prevent glitching mode by single bit flipping.
2019-12-19 17:07:35 +02:00
Jarno Lamsa
8d09e5744c Increase hamming distance for session resume flag
This is to prevent glitching a single bit for the resume flag.
2019-12-19 17:07:35 +02:00
Jarno Lamsa
489dccd158 Adress review comments 2019-12-19 17:07:35 +02:00
Jarno Lamsa
88db2ae9a0 Use Platform fault when double check fails 2019-12-19 17:07:35 +02:00
Jarno Lamsa
f5b6af01d3 Fix double check in entropy_gather_internal
The double check was wrong way, glitching either check
could have compromised the flow there.
2019-12-19 17:07:29 +02:00
Jarno Lamsa
afff4d0679 Remove unused flag 2019-12-19 14:41:56 +02:00
Jarno Lamsa
06164057b3 Check that we have all the proper keys
The proper keys should be set at the end of
the handshake, if not, fail the handshake.
2019-12-19 14:40:36 +02:00
Jarno Lamsa
e1621d4700 Check that the peer_authenticated flag
Check that the peer has been authenticated in the end
of the handshake.
2019-12-19 14:29:24 +02:00
Jarno Lamsa
ba4730fe4c Protect setting of peer_authenticated flag
Use flow counting and double checks when setting the flag.
Also protect the flow to prevent causing a glitch.
2019-12-19 09:43:25 +02:00
Jarno Lamsa
4031a45019 Protect key_derivation_done flag
The flag is used to track that the key derivation
has been done.
2019-12-19 09:43:25 +02:00
Jarno Lamsa
67f0a1e833 Protect setting of premaster_generated flag
The flag is used for tracking if the premaster has
been succesfully generated. Note that when resuming
a session, the flag should not be used when trying to
notice if all the key generation/derivation has been done.
2019-12-19 09:43:19 +02:00
Jarno Lamsa
98801af26b Protect setting of hello_random flag
The handshake flag tells when the handshake hello.random
is set and can be used later to decide if we have the correct
keys.
2019-12-19 09:02:02 +02:00
Jarno Lamsa
b57d7fd568 Add flags for protecting TLS state machine
Flags are there to prevent skipping vital parts of the TLS
handshake.
2019-12-19 09:01:54 +02:00
Jarno Lamsa
6122b59042 Address review comments 2019-12-19 07:56:10 +02:00
Jarno Lamsa
46afd5d8fa Fix CI issues
Default flow assumes failure causes multiple issues with
compatibility tests when the return value is initialised
with error value in ssl_in_server_key_exchange_parse.
The function would need a significant change in structure for this.
2019-12-19 07:56:10 +02:00
Jarno Lamsa
91dbb79ae4 Fix error return code 2019-12-19 07:56:10 +02:00
Jarno Lamsa
b83a2136d6 Protect the return value from mbedtls_pk_verify
Add double checks to the return value and default flow assumes
failure.
2019-12-19 07:56:10 +02:00
Jarno Lamsa
47aab8da8a Protect return value from mbedtls_pk_verify
Use double checks and default flow assumes failure.
2019-12-19 07:56:10 +02:00
Jarno Lamsa
83a56a630a Double check mbedtls_pk_verify
The verification could be skipped in server, changed the default flow
so that the handshake status is ever updated if the verify
succeeds, and that is checked twice.
2019-12-19 07:56:10 +02:00
Jarno Lamsa
9e8e820993 Increase hamming distance for some error codes
The MBEDTLS_ERR_SSL_WANT_READ and MBEDTLS_ERR_SSL_WANT_WRITE are
errors that can be ignored, so increase the hamming distance between
them and the non-ignorable errors and keep still some distance from
a success case. This mitigates an attack where single bit-flipping could
change a non-ignorable error to being an ignorable one.
2019-12-19 07:56:10 +02:00
Jarno Lamsa
acb5eb00ca Add a double check to protect from glitch
Check that the encryption has been done for the outbut buffer.
This is to ensure that glitching out the encryption doesn't
result as a unecrypted buffer to be sent.
2019-12-19 07:56:10 +02:00
Jarno Lamsa
d05da1fa45 Add double check for checking if source is strong
To prevent glitching past a strong source.
2019-12-19 07:56:10 +02:00
Jarno Lamsa
552e8f2d6a Add double check to entropy-loop
To prevent glitching and going through without strong source
2019-12-19 07:56:10 +02:00
Jarno Lamsa
4708d66af5 Change the mbedtls_ssl_states values
The changed values have now the minimum hamming distance
of 16 from each other. This is to prevent changing the state
by just flipping one bit.
2019-12-19 07:56:10 +02:00
Jarno Lamsa
b01800974f Use invalid state
If mismatch in the state has been noticed, use
the invalid state.
2019-12-19 07:56:10 +02:00
Jarno Lamsa
70abd7aadc Add enumeration for invalid state
The invalid state can be used when state-mismatch is noticed.
The invalid state should report a FI-alert upwards.
2019-12-19 07:56:10 +02:00
Jarno Lamsa
2b20516b60 Make TLS state changes explicit
This is to enable hardening the security when changing
states in state machine so that the state cannot be changed by bit flipping.
The later commit changes the enumerations so that the states have large
hamming distance in between them to prevent this kind of attack.
2019-12-19 07:56:10 +02:00
Manuel Pégourié-Gonnard
a4b421819b Fix way to access the RNG for ECDSA counter-measures
Duplicating the g_rng_function variable in ecc_dsa.c means it's not the same
as set in ecc.c, resulting if no randomisation here. The proper way to access
the RNG function from outside ecc.c is uECC_get_rng(), so use that.

This is a side-port of upstream commit
87d74dd8d64a99aaa188961fe763d0841c5abfef

I've verified that there are no other occurrences (the duplication of
g_rng_function in ecc_dh.c had already been removed earlier when centralising
projective coordinate randomisation to mult_safer()).
2019-12-18 10:29:58 +01:00
Simon Butcher
171f422109 Merge remote-tracking branch 'public/pr/2952' into baremetal 2019-12-13 14:51:40 +00:00
Simon Butcher
e76c638d6f Merge remote-tracking branch 'public/pr/2925' into baremetal 2019-12-13 14:51:29 +00:00
Arto Kinnunen
6ce4988768 AES FI resistance
Add FI countermeasures to AES.
2019-12-10 15:00:37 +02:00
Arto Kinnunen
76deef9fca Update AES SCA random number function
-Replace usage of rand() with mbedtls_platform_random_in_range()
-Prevent for-ever loop by hardcoding SCA countermeasure position in
 case of used random function is always returning constant number.
2019-12-10 14:54:43 +02:00
Arto Kinnunen
f44f7d465a AES CM review corrections
-Use separate control bytes for start and final round to get them
 randomized separately.
-Remove struct name.
-Fix comments and follow Mbed TLS coding style.
2019-12-10 14:54:43 +02:00
Arto Kinnunen
34139ba9fc Updates to AES countermeasures
-Update comments regarding flag MBEDTLS_AES_SCA_COUNTERMEASURES
-Remove MBEDTLS_AES_SCA_COUNTERMEASURES dependency check
-More comments and coding style changes
2019-12-10 14:54:43 +02:00
Arto Kinnunen
be1bb06acd Enable AES countermeasures in baremetal config
Enable AES countermeasures in baremetal configuration.
2019-12-10 14:54:43 +02:00
Arto Kinnunen
7543901b6a Follow Mbed TLS coding style
Fix remaining if-clauses.
2019-12-10 14:54:43 +02:00
Arto Kinnunen
425137a0fa Follow Mbed TLS coding style
-Fix multiple for clauses
-Remove redundant check
2019-12-10 14:54:43 +02:00
Arto Kinnunen
c3532c2339 Improve SCA CM AES performance
SCA CM implementation caused AES performance drop. For example
AES-CCM-128 calculation speed was dropped from 240 KB/s to 111 KB/s.
(-54%), Similarily AES-CBC-128 calculation speed was dropped from
536 KB/s to 237 KB/s (-56%).

Use functions instead of macros to reduce code indirections and
therefore increase performance. Now the performance is 163 KB/s for
AES-CCM-128 (-32%) and 348 KB/s for AES-CBC-128 (-35%).

When SCA countermeasures are activated the performance is as follows:
122 KB/s for AES-CCM-128 (-49%) and 258 KB/s for AES-CBC-128 (-52%)
compared to the original AES implementation.
2019-12-10 14:54:43 +02:00
Arto Kinnunen
172836a281 Rework AES countermeasures implementation
Use control bytes to instruct AES calculation rounds. Each
calculation round has a control byte that indicates what data
(real/fake) is used and if any offset is required for AES data
positions.

First and last AES calculation round are calculated with SCA CM data
included. The calculation order is randomized by the control bytes.

Calculations between the first and last rounds contains 3 SCA CMs
in randomized positions.
2019-12-10 14:54:43 +02:00
Arto Kinnunen
b2be92e2c7 Update AES SCA flag to version_features.c 2019-12-10 14:54:43 +02:00
Arto Kinnunen
43980a09e0 Add AES SCA countermeasures to query_config
Add MBEDTLS_AES_SCA_COUNTERMEASURES flag to query_config so that
flag value can be queried.
2019-12-10 14:54:43 +02:00
Arto Kinnunen
2231138c18 Disable AES SCA countermeasures from full config
Disable AES SCA countermeasures from full config. Otherwise
check_config will break the builds due inproper configuration.
2019-12-10 14:54:43 +02:00
Arto Kinnunen
45a475f293 Follow Mbed TLS coding style 2019-12-10 14:54:43 +02:00
Arto Kinnunen
430ac13112 Add config and test for AES SCA countermeasures
- Add configuration for AES_SCA_COUNTERMEASURES to config.h. By
  default the feature is disabled.
- Add AES_SCA_COUNTERMEASURES configuration check to check_config.h
- Add AES_SCA_COUNTERMEASURES test to all.sh
2019-12-10 14:54:43 +02:00
Arto Kinnunen
f93d55e3ce Add SCA countermeasures to AES calculation
- 3 additional dummy AES rounds calculated with random data for each
  AES encryption/decryption
- additional rounds can be occur in any point in sequence of rounds
2019-12-10 14:54:43 +02:00
Manuel Pégourié-Gonnard
645896e0ea Fix undefined order of volatile access
Found by the IAR compiler.

While at it, make 'diff' non-volatile in uECC_check_curve_integrity(), as
there is no good reason to make it volatile, and making it volatile only
increases the code size and the burden of defining access ordering.
2019-12-05 16:02:17 +01:00
Simon Butcher
0252cd6876 Merge remote-tracking branch 'public/pr/2940' into baremetal 2019-12-05 14:32:54 +00:00
Simon Butcher
501c466d01 Merge remote-tracking branch 'public/pr/2934' into baremetal 2019-12-05 14:32:44 +00:00
Simon Butcher
5b45c6e1b3 Merge remote-tracking branch 'public/pr/2932' into baremetal 2019-12-05 14:32:31 +00:00
Simon Butcher
7c5de360da Merge remote-tracking branch 'public/pr/2922' into baremetal 2019-12-05 14:31:03 +00:00
Simon Butcher
098846287f Merge remote-tracking branch 'public/pr/2918' into baremetal 2019-12-05 14:27:29 +00:00
Arto Kinnunen
de657fca6b Revert "Disable use of HRNG in SCA-hardened mem-functions"
This reverts commit 1e96b46b03.
2019-12-04 16:30:54 +02:00
Jarno Lamsa
83d7881cec Make VS compiler happy
It doesn't seem to like using unary - to unsigned values.
2019-12-04 14:40:57 +02:00
Teppo Järvelin
e06e039f7a Fix basic-build-test.sh to work in different env
Also added possibility to run only unit tests
2019-11-29 11:05:11 +02:00
Manuel Pégourié-Gonnard
766c9e9781 Improve description of ERR_PLATFORM_FAULT_DETECTED 2019-11-29 09:40:08 +01:00
Manuel Pégourié-Gonnard
65be6b48de Add compile guard in platform.h
We may want to include it just for the errors it defines without having all of
the other defines that only make sense when PLATFORM_C is enabled.
2019-11-28 12:51:45 +01:00
Arto Kinnunen
ec37a89bf3 Save ROM by using int instead of char
Save 20 bytes of ROM by changing variable type from char to int.
2019-11-28 13:43:02 +02:00
Manuel Pégourié-Gonnard
231bf52691 Fix indentation level in one place 2019-11-28 12:22:43 +01:00
Manuel Pégourié-Gonnard
e1cb8846e7 Add loop integrity check to curve param check
Also make the reference result static const while at it.
2019-11-28 12:21:34 +01:00
Manuel Pégourié-Gonnard
9ca11fc892 Fix issues found by the CI
- MSVC doesn't like -1u
- We need to include platform.h for MBEDTLS_ERR_PLATFORM_FAULT_DETECTED - in
  some configurations it was already included indirectly, but not in all
configurations, so better include it directly.
2019-11-28 12:07:01 +01:00
Manuel Pégourié-Gonnard
6bdc6809da Initialise variables to failing values 2019-11-28 10:40:03 +01:00
Manuel Pégourié-Gonnard
5c3066a4f6 Add double-checking in some critical places 2019-11-27 13:01:10 +01:00
Manuel Pégourié-Gonnard
98e1fe0796 Add flow control in uECC_vli_equal loop 2019-11-27 12:52:54 +01:00
Manuel Pégourié-Gonnard
9d6a535ba1 Return and propagate UECC_FAULT_DETECTED
This commit first changes the return convention of EccPoint_mult_safer() so
that it properly reports when faults are detected. Then all functions that
call it need to be changed to (1) follow the same return convention and (2)
properly propagate UECC_FAULT_DETECTED when it occurs.

Here's the reverse call graph from EccPoint_mult_safer() to the rest of the
library (where return values are translated to the MBEDTLS_ERR_ space) and test
functions (where expected return values are asserted explicitly).

EccPoint_mult_safer()
    EccPoint_compute_public_key()
        uECC_compute_public_key()
            pkparse.c
            tests/suites/test_suite_pkparse.function
        uECC_make_key_with_d()
        uECC_make_key()
            ssl_cli.c
            ssl_srv.c
            tests/suites/test_suite_pk.function
            tests/suites/test_suite_tinycrypt.function
    uECC_shared_secret()
        ssl_tls.c
        tests/suites/test_suite_tinycrypt.function
    uECC_sign_with_k()
        uECC_sign()
            pk.c
            tests/suites/test_suite_tinycrypt.function

Note: in uECC_sign_with_k() a test for uECC_vli_isZero(p) is suppressed
because it is redundant with a more thorough test (point validity) done at the
end of EccPoint_mult_safer(). This redundancy was introduced in a previous
commit but not noticed earlier.
2019-11-26 12:54:06 +01:00
Manuel Pégourié-Gonnard
4d6186beb0 Rename ATTACK_DETECTED to FAULT_DETECTED
We don't know for sure it's an attack, it could be the hardware failing
randomly as well.
2019-11-26 12:54:06 +01:00
Manuel Pégourié-Gonnard
2b90961b8d Add integrity check for curve parameters
We don't really need a secure hash for that, something like CRC32 would
probably be enough - but we have SHA-256 handy, not CRC32, so use that for the
sake of simplicity.
2019-11-26 12:54:06 +01:00
Manuel Pégourié-Gonnard
1a5337179f Remove curve parameter from public functions 2019-11-26 12:54:06 +01:00
Manuel Pégourié-Gonnard
be5f833c9c Remove curve parameter from (semi-)internal functions
By semi-internal I mean functions that are only public because they're used in
more than once compilation unit in the library (for example in ecc.c and
ecc_dsa.c) but should not really be part of the public-facing API.
2019-11-26 12:54:06 +01:00
Manuel Pégourié-Gonnard
bc3f49011a Remove struct curve entirely 2019-11-26 12:54:06 +01:00
Manuel Pégourié-Gonnard
677b7f6c42 Fix direct use of struct instead of abstract type 2019-11-26 12:54:06 +01:00
Manuel Pégourié-Gonnard
ffd13996fd Move b from curve structure to its own constant
Same motivation as for the other parameters. This is the last one, making the
curve structure empty, so it's left with a dummy parameter for legal reasons.
2019-11-26 12:54:04 +01:00
Manuel Pégourié-Gonnard
a6115087a0 Move G from struct curve to its own constant 2019-11-26 12:53:13 +01:00
Manuel Pégourié-Gonnard
356d8594d7 Move n from struct curve to its own constant 2019-11-26 12:52:57 +01:00
Manuel Pégourié-Gonnard
4d8777cbb6 Move p from curve structure to its own constant
This removes an indirection, which both makes the code smaller and decreases
the number of glitching opportunities for an attacker.
2019-11-26 12:51:58 +01:00
Arto Kinnunen
c5bbdd411c Include platform.h in hmac_drbg.c and md.c
Include platform.h to find MBEDTLS_ERR_PLATFORM_FAULT_DETECTED.
2019-11-25 17:32:28 +02:00
Arto Kinnunen
5299a42f25 Update HMAC and MD FI countermeasures
-Return error value by default.
-Success is returned only after checking internal states.
-Append flow_control to cover also last function call.
2019-11-25 16:29:10 +02:00
Arto Kinnunen
5b36693774 Harden hmac_drbg and md against fault injection
-Add flow monitor, loop integrity check and variable doubling to
 harden mbedtls_hmac_drbg_update_ret.

-Use longer hamming distance for nonce usage in hmac_drbg_reseed_core

-Return actual value instead of success in mbedtls_hmac_drbg_seed and
 mbedtls_hmac_drbg_seed_buf

-Check illegal condition in hmac_drbg_reseed_core.

-Double buf/buf_len variables in mbedtls_hmac_drbg_random_with_add

-Add more hamming distance to MBEDTLS_HMAC_DRBG_PR_ON/OFF
2019-11-25 13:45:44 +02:00
Simon Butcher
45fd0d68d9 Add USE_TINYCRYPT build option to CMake files
Adds the USE_TINYCRYPT build option to the CMake build files. Default is
enabled.
2019-11-22 16:56:17 +00:00
Simon Butcher
9699887185 Add Makefile option to exclude TinyCrypt files
Added an additional Makefile option of 'TINYCRYPT_BUILD' to exclude the
TinyCrypt source files from the build. This allows some tests to exclude those
files as and when necessary.

Specifically this includes in all.sh the test
'component_build_arm_none_eabi_gcc_no_64bit_multiplication' which was failing as
64bit cannot be disabled in TinyCrypt, and check-names.sh as TinyCrypt obviously
does not conform to Mbed TLS naming conventions.
2019-11-22 15:09:39 +00:00
Simon Butcher
35e535a74a Remove TinyCrypt config condition in source files
This commit removes from the TinyCrypt header and source code files, the
configuration condition on MBEDTLS_USE_TINYCRYPT to include the file
contents.

This is to allow use of the library by the Factory Tool without enabling
MBEDTLS_USE_TINYCRYPT, and also removes a modification we've made to make the
code closer to the upstream TinyCrypt making it easier to maintain.
2019-11-21 17:54:16 +00:00
Manuel Pégourié-Gonnard
30833f2a07 Remove num_n_bits member from curve structure 2019-11-21 15:37:22 +01:00
Manuel Pégourié-Gonnard
72c1764c00 Remove num_bytes member from curve structure
Reduces code size and size of the structure.
2019-11-21 15:37:22 +01:00
Manuel Pégourié-Gonnard
1765933ab2 Remove num_words member from curve structure
Saves code size, and makes the curve structure simpler.
2019-11-21 15:37:22 +01:00
Manuel Pégourié-Gonnard
1c6f7eae2d Remove function pointers from curve structure
They're not needed in practice, and removing them decreases the code size
slightly and provides less opportunities for an attacker.
2019-11-21 15:37:22 +01:00
Manuel Pégourié-Gonnard
e714332563 Add pre and post-validation to mult_safer()
Validating the input is always a good idea. Validating the output protects
against some fault injections that would make the result invalid.

Note: valid_point() implies that the point is not zero.

Adding validation to mult_safer() makes it redundant in
compute_shared_secret().
2019-11-21 15:37:22 +01:00
Manuel Pégourié-Gonnard
41ab8cb6cb Centralize everything to EccPoint_mult_safer()
This will make easier to add future counter-measures in a single place.

In practice this change means that:

- compute_public_key() now uses projective coordinate randomisation, which it
  should as this is a protection against Template Attacks for example.
- mult_safer() now checks that the result is not the point at infinity, which
  it can as the result is indeed never expected to be that
2019-11-21 15:37:22 +01:00
Manuel Pégourié-Gonnard
18761926a8 Fix double-check for bad signature
In the previous version, it was enough for the attacker to glitch the
top-level 'if' to skip the entire block. We want two independent blocks here,
so that an attacker can only succeed with two successive glitches.
2019-11-21 15:32:45 +01:00
Manuel Pégourié-Gonnard
4c9b556e38 Add double-check for flags == 0 in crt_verify()
Also move to "default flow assumes failure" while at it.
2019-11-21 15:32:45 +01:00
Manuel Pégourié-Gonnard
ea7eab1fde Add redundancy (Hamming distance) to cert flags
Before this commit, if a certificate only had one issue (for example, if the
"untrusted" bit was the only set in flags), an attacker that could flip this
single bit between the moment it's set and the moment flags are checked before
returning from mbedtls_x509_crt_verify() could make the entire verification
routine appear to succeed (return 0 with no bit set in flags).

Avoid that by making sure that flags always has either 0 or at least 9 bits
set during the execution of the function. However, to preserve the API, clear
the 8 extra bits before returning. This doesn't open the door to other
attacks, as fortunately the API already had redundancy: either both flags and
the return value are 0, or flags has bits set and the return value is non-zero
with at least 16 bits set (assuming 32-bit 2-complement ints).
2019-11-21 15:32:45 +01:00
Manuel Pégourié-Gonnard
81c1fc4132 Add double check on bad signature flagging 2019-11-21 15:32:45 +01:00
Manuel Pégourié-Gonnard
f66657ac44 Use large Hamming distance for signature validity
If signature_is_good is 0 (invalid) of 1 (valid), then it's all too easy for
an active physical attacker to turn invalid into valid by flipping a single
bit in RAM, on the bus or in a CPU register.

Use a special value to represent "valid" that can't easily be reached by
flipping a few bits.
2019-11-21 15:32:45 +01:00
Manuel Pégourié-Gonnard
d1e55dfce6 Add double check on cert signature verification
x509_crt_check_signature() directly returns the return value of
pk_verify_xxx() without looking at it, so nothing to do here. But its caller
compares the value to 0, which ought to be double-checked.
2019-11-21 15:32:45 +01:00
Manuel Pégourié-Gonnard
72a8c9e7dc Force some compilers to respect volatile reads
Inspection of the generated assembly showed that before this commit, armcc 5
was optimizing away the successive reads to the volatile local variable that's
used for double-checks. Inspection also reveals that inserting a call to an
external function is enough to prevent it from doing that.

The tested versions of ARM-GCC, Clang and Armcc 6 (aka armclang) all keep the
double read, with our without a call to an external function in the middle.

The inserted function can also be changed to insert a random delay if
desired in the future, as it is appropriately places between the reads.
2019-11-21 15:14:59 +01:00
Manuel Pégourié-Gonnard
ca7b5ab5ef Use double-checking of critical value in pk_verify()
Also change the flow so that the default return value is a failing one.
2019-11-21 15:14:59 +01:00
Manuel Pégourié-Gonnard
324c6e9cc9 Add error code MBEDTLS_ERR_PLATFORM_FAULT_DETECTED
This can be used by Mbed TLS functions in any module to signal that a fault
attack is likely happening, so this can be appropriately handled by the
application (report, fall back to safer mode or even halt, etc.)
2019-11-21 15:14:59 +01:00
Manuel Pégourié-Gonnard
e6d6f17738 Add double-checking of critical value in uECC_verify()
This hardens against attacks that glitch the conditional branch by making it
necessary for the attacker to inject two consecutive faults instead of one. If
desired, we could insert a random delay in order to further protect against
double-glitch attacks.

Also, when a single glitch is detected we report it.
2019-11-21 15:14:59 +01:00
Manuel Pégourié-Gonnard
2b6312b7d9 Harden return value of uECC_vli_equal()
Previously it was returning 0 or 1, so flipping a single bit in the return
value reversed its meaning. Now it's returning the diff itself.

This is safe because in the two places it's used (signature verification and
point validation), invalid values will have a large number of bits differing
from the expected value, so diff will have a large Hamming weight.

An alternative would be to return for example -!(diff == 0), but the
comparison itself is prone to attacks (glitching the appropriate flag in the
CPU flags register, or the conditional branch if the comparison uses one). So
we'd need to protect the comparison, and it's simpler to just skip it and
return diff itself.
2019-11-21 15:12:44 +01:00
Manuel Pégourié-Gonnard
10d8e8ed64 Use safer return values in uECC_verify()
This is a first step in protecting against fault injection attacks: the
attacker can no longer change failure into success by flipping a single bit.
Additional steps are needed to prevent other attacks (instruction skip etc)
and will be the object of future commits.

The return value of uECC_vli_equal() should be protected as well, which will
be done in a future commit as well.
2019-11-21 15:12:44 +01:00
Manuel Pégourié-Gonnard
c05f1506f4 Introduce return values for tinycrypt functions
Currently functions that may return success or failure tend to do so by
returning 0 or 1. If an active physical attacker can flip a bit in memory or
registers at the right time, they may easily change a failure value into a
success value, with potentially catastrophic security consequences.

As typical attackers can only flip a few bits, an element of protection
against such attacks is to ensure a sufficient Hamming distance between
failure values and the success value. This commit introduces such values,
which will put to use in critical functions in future commits.

In addition to SUCCESS and FAILURE, a third value ATTACK_DETECTED is
introduced, which can be used later when suspicious-looking events are noticed
(static data changed when it shouldn't, double condition checking returning
inconsistent results, etc.).

Values are chosen so that Hamming distances are large, and that no value is
the complement of another, in order to avoid unwanted compiler optimisations.

Note: the error values used by Mbed TLS are already safe (assuming 32-bit
integers) as they are of the form -x with x in the range [1, 2^15) so their
Hamming distance with the success value (0) is at least 17, so it's hard for
an attacker to turn an error value into the success value (or vice-versa).
2019-11-21 15:10:02 +01:00
Simon Butcher
a3877007e6 Merge remote-tracking branch 'public/pr/2876' into baremetal 2019-11-20 12:00:18 +00:00
Simon Butcher
c759b88194 Merge remote-tracking branch 'public/pr/2889' into baremetal 2019-11-20 12:00:06 +00:00
Simon Butcher
b2af693900 Merge remote-tracking branch 'public/pr/2910' into baremetal 2019-11-20 11:59:55 +00:00
Simon Butcher
4965466614 Merge remote-tracking branch 'public/pr/2930' into baremetal 2019-11-20 11:59:46 +00:00
Manuel Pégourié-Gonnard
1e96b46b03 Disable use of HRNG in SCA-hardened mem-functions
This is a temporary work-around for an integration issue.

A future task will re-integrate randomness into these functions are their
entire point is to be randomized; this is really just temporary.
2019-11-19 11:49:05 +01:00
Manuel Pégourié-Gonnard
c881486bb2 Fix off-by-one number of extra operations
This caused a performance issue.
2019-11-05 10:32:37 +01:00
Manuel Pégourié-Gonnard
ad166d8db7 Also check curve in verify()
This is the only function that performs computations without calling
EccPoint_mult_safer() and that didn't have that guard yet.
2019-11-04 15:53:24 +01:00
Manuel Pégourié-Gonnard
913534837a Hardcode numwords in vli_modInv 2019-11-04 15:53:22 +01:00
Manuel Pégourié-Gonnard
3e20adf533 Hardcode numwords in vli_modMult 2019-11-04 15:53:20 +01:00
Manuel Pégourié-Gonnard
10349e4912 Hardcode numwords in vli_mmod 2019-11-04 15:53:19 +01:00
Manuel Pégourié-Gonnard
1b0875d863 Hardcode numwords in vli_modSub 2019-11-04 15:53:17 +01:00
Manuel Pégourié-Gonnard
0779be7f31 Hardcode numwords in vli_modAdd 2019-11-04 15:53:14 +01:00
Manuel Pégourié-Gonnard
5e3baf2303 Hardcode numwords in vli_rshift1 2019-11-04 15:53:12 +01:00
Manuel Pégourié-Gonnard
2cb3eea922 Hardcode numwords in vli_cmp 2019-11-04 15:53:10 +01:00
Manuel Pégourié-Gonnard
129b42ea2e Hardcode numwords in vli_sub 2019-11-04 15:53:09 +01:00
Manuel Pégourié-Gonnard
2eca3d367b Hardcode numwords in vli_equal 2019-11-04 15:53:07 +01:00
Manuel Pégourié-Gonnard
a752191191 Hardcode numwords in vli_cpm_unsafe 2019-11-04 15:53:03 +01:00
Manuel Pégourié-Gonnard
cbbb0f034b Hardcode numwords in vli_set() 2019-11-04 15:52:43 +01:00
Manuel Pégourié-Gonnard
2bf5a129cf Hardcode numwords in semi-internal vli_numBits() 2019-11-04 15:52:43 +01:00
Manuel Pégourié-Gonnard
94e48498ef Hardcode numwords in semi-internal vli_clear() 2019-11-04 15:52:43 +01:00
Manuel Pégourié-Gonnard
f3899fc0ea hardcode numwords in semi-internal vli_isZero 2019-11-04 15:52:43 +01:00
Manuel Pégourié-Gonnard
02d9d21fd6 Hardcode numwords in internal vli_add
Saves 40 bytes
2019-11-04 15:52:37 +01:00
Manuel Pégourié-Gonnard
78a7e351fe Use macros for number of bits and words 2019-11-04 12:31:37 +01:00
Manuel Pégourié-Gonnard
c3ec14c87f Harcode curve in semi-internal modMult function
Saves 80 bytes of code size.
2019-11-04 12:23:11 +01:00
Manuel Pégourié-Gonnard
3645ac93f5 Start hardcoding curve in internal functions
Saves 68 byte of code size.
2019-11-04 12:20:22 +01:00
Manuel Pégourié-Gonnard
27926d63b7 Remove less-safe mult function from public API
This doesn't change code size, but makes it easier to remove unneeded
parameters later (less possible entry points).
2019-11-04 11:26:46 +01:00
Manuel Pégourié-Gonnard
ef238283d5 Add ECCPoint_mult_safer() function
This avoids the need for each calling site to manually regularize the scalar
and randomize coordinates, which makes for simpler safe use and saves 50 bytes
of code size in the library.
2019-11-04 11:19:30 +01:00
Manuel Pégourié-Gonnard
c78d86b499 Remove some internal functions that aren't needed
This saves 10 bytes of code size, and makes it a bit easier to remove unused
parameters later (fewer prototypes to change).
2019-11-04 10:18:42 +01:00
Manuel Pégourié-Gonnard
86c4f81408 Improve documentation of internal function 2019-10-31 13:07:58 +01:00
Manuel Pégourié-Gonnard
d5e503ec33 Rename wait_state_t to ecc_wait_state_t
Even though this is type name is purely internal to a single C file, let's
reduce the potential for clashes with other wait state types which might be
added elsewhere in the library and become visible here (for example through
platform_util.h).
2019-10-31 13:07:58 +01:00
Manuel Pégourié-Gonnard
d467116e59 Make wait_state smaller
Previous size was 3584 bytes which is not acceptable on constrained systems
(especially on the stack). This was a misguided attempt at minimizing the
number of calls to the RNG function in order to minimize impact on
performance, but clearly this does not justify using that much RAM and a
compromise had to be found.
2019-10-31 13:07:52 +01:00
Manuel Pégourié-Gonnard
938f53f1fb Actually use randomized mult when relevant
While at it, loose the 'curve' argument in internal randomized functions, for
the same reasons we lost 'num_words' in uECC_vli_mult_rnd(): we only have one
curve so we don't need this, and hardcoding it saves a bit of code size and
speed, which is welcome to slightly reduce the impact of the counter-measure
on both of them.
2019-10-31 13:07:52 +01:00
Manuel Pégourié-Gonnard
14ab9c2879 Add random delays to multi-precision multiplication
This is a counter-measure to make horizontal attacks harder. Horizontal
attacks work with a single trace by noticing when intermediate computations
within that trace happen on the same operands.

We'll try to make that harder for an attacker to achieve that by introducing
random delays based on extra computation and extra random accesses to input in
the multi-precision multiplication (which is the dominant operation and the target of
horizontal attacks known so far). This should make it hard for the attacker to
compare two multiplications.

This first commit introduces the new function for multiplication with random
delay - future commits will ensure it is used all the way up to the top-level
scalar multiplication routine.
2019-10-31 13:07:52 +01:00
Manuel Pégourié-Gonnard
6ee7a4e01c Validate peer's public key in ECDH
This protects against invalid curve attacks.

(It's also a tiny step in the direction of protecting against some fault
injection attacks.)
2019-10-31 13:07:52 +01:00
Manuel Pégourié-Gonnard
4a658a01c6 Add projective coordinates randomization in ECDSA
Why: this protects against potential side-channels attacks. This
counter-measure is for example effective against Template SPA. Also, the
bignum arithmetic as implemented in TinyCrypt isn't entirely regular, which
could in principle be exploited by an attacker; randomizing the coordinates
makes this less likely to happen.

Randomizing projective coordinates is also a well-known countermeasure to DPA.
In the context of the scalar multiplication in ECDSA, DPA isn't a concern
since it requires multiple measurements with various base points and the same
scalar, and the scalar mult in ECDSA is the opposite: the base point's always
the same and the scalar is always unique. But we want protection against the
other attacks as well.

How: we use the same code fragment as in uECC_shared_secret in ecc_dh.c,
adapted as follows: (1) replace p2 with k2 as that's how it's called in this
function; (2) adjust how errors are handled.

The code might not be immediately clear so here are a few more details:
regularize_k() takes two arrays as outputs, and the return value says which one
should be passed to ECCPoint_mult(). The other one is free for us to re-use to
generate a random number to be used as the initial Z value for randomizing
coordinates (otherwise the initial Z value is 1), thus avoiding the use of an
extra stack buffer.
2019-10-31 13:07:52 +01:00
Jarno Lamsa
2e2fa5e352 Adress review comments 2019-10-30 15:08:26 +02:00
Jarno Lamsa
77c4fcc96e Use DER encoded keys with tinycrypt
PEM and BASE64 aren't used with baremetal config by default
and using DER encoded key enables the test without enabling PEM
and BASE64.
2019-10-30 15:00:01 +02:00
Jarno Lamsa
6ba32cac5c Add authentication tests for baremetal config 2019-10-30 15:00:01 +02:00
Jarno Lamsa
6f54fe72f2 Add a bad version of server11 certificate
The certificate has a corrupted public key and signature.
Generating it through Makefile isn't trivial and since it is
a corrupted certificate, that shouldn't be accepted, there
shouldn't be a need to generate it again anyway.
2019-10-30 14:59:23 +02:00
Teppo Järvelin
d49d2b6d4f Changed mbedtls_platform_memset/cpy/cmp in selftest functions back to original methods 2019-10-30 14:07:04 +02:00
Teppo Järvelin
6f4e030166 Changed mbedtls_platform_memcpy to memcpy in places which don't handle critical data
and under baremetal define
2019-10-30 14:07:04 +02:00
Teppo Järvelin
b5c4671a80 Changed mbedtls_platform_memcpy back to memcpy for selftest and test functions 2019-10-30 14:07:04 +02:00
Teppo Järvelin
3137fb271a Added include platform_util.h to padlock.c to fix compile with all defines variants 2019-10-30 14:07:04 +02:00
Teppo Järvelin
91d7938761 Changed every memcpy to SCA equivalent mbedtls_platform_memcpy
This makes physical attacks more difficult.
2019-10-30 14:07:04 +02:00
Jarno Lamsa
b514cd3626 Remove dependency to MBEDTLS_ERROR_C
The test is already checking for return value
No need to check for MBEDTLS_ERROR_C -dependent print
2019-10-30 10:34:54 +02:00
Jarno Lamsa
d342805134 Added Forced ECC ciphersuite with CCM tests 2019-10-30 10:34:54 +02:00
Jarno Lamsa
c40184b44a Add test for small server packet
To allow testing with ECDHE-ECDSA with DTLS
2019-10-30 10:34:54 +02:00
Jarno Lamsa
0ed68089ee Add test for small client packet
Enable testing with ECDHE-ECDSA with DTLS
2019-10-30 10:34:54 +02:00
Jarno Lamsa
c5118b7664 Add a new keyUsage test for p256 using DTLS 2019-10-30 10:34:54 +02:00
Jarno Lamsa
ff434c2ef3 Add test for enforcing extended master secret
Only add test when both are enforcing. This is configured in baremetal.h
and is checked in the check_cmdline_compat, would render other cases
with baremetal.h to skipped.
2019-10-30 10:34:54 +02:00
Jarno Lamsa
5b944b5793 define MBEDTLS_FS_IO
This is needed for the tests using certificate-files.
2019-10-30 10:34:54 +02:00
Jarno Lamsa
7544195a44 Remove echo FORCE SKIP
This was probably an artifact from testing the cmdline_compat-stuff.
Currently only pollutes the output.
2019-10-30 10:34:54 +02:00
Simon Butcher
aeecf04be3 Merge remote-tracking branch 'public/pr/2907' into baremetal 2019-10-29 15:42:52 +00:00
Simon Butcher
8b2c642994 Merge remote-tracking branch 'public/pr/2904' into baremetal 2019-10-29 15:31:48 +00:00
Simon Butcher
f5a64048b7 Merge remote-tracking branch 'public/pr/2892' into baremetal 2019-10-29 15:30:38 +00:00
Simon Butcher
9d36fa16f8 Merge remote-tracking branch 'public/pr/2891' into baremetal 2019-10-29 15:25:26 +00:00
Simon Butcher
a85b3e4dde Merge remote-tracking branch 'public/pr/2890' into baremetal 2019-10-29 14:41:13 +00:00
Simon Butcher
2f99f3d8a2 Merge remote-tracking branch 'public/pr/2850' into baremetal 2019-10-29 14:24:33 +00:00
Arto Kinnunen
8a8488c1cf Fix mbedtls_ssl_check_record usage with ext buf
Record checking fails if mbedtls_ssl_check_record() is called with
external buffer. Received record sequence number is available in the
incoming record but it is not available in the ssl contexts `in_ctr`-
variable that is used when decoding the sequence number.

To fix the problem, temporarily update ssl context `in_ctr` to
point to the received record header and restore value later.
2019-10-29 11:13:33 +02:00
Teppo Järvelin
7800719551 Adjusted buf allocated from heap in ssl_client2 to be as small as possible 2019-10-25 14:30:33 +03:00
Teppo Järvelin
614efc268e Moved allocation checks to correct place in ssl_server2.c 2019-10-25 11:03:20 +03:00
Arto Kinnunen
4ecfbd3b16 Fix tests to work in Mbed OS test environment
Update x509parse and x509write test suites to include "x509.c" from
correct location.
2019-10-24 15:48:47 +03:00
Teppo Järvelin
99082aeac7 Fixed CI tests by overriding value MBEDTLS_ENTROPY_MAX_SOURCES
Override define MBEDTLS_ENTROPY_MAX_SOURCES from 1 to 3 in baremetal_test.h

mbedtls_entropy_init adds 2 sources already so max must be 3 so that
one source can be added with mbedtls_entropy_add_source.
2019-10-24 15:03:33 +03:00
Arto Kinnunen
0fa65aabf0 Review corrections
-Guard additional static variables with AES_ONLY_ENCRYPT
-Update config.h description about memory savings
-Update test: fix typo in all.sh and adjust compiler flags
2019-10-24 12:19:50 +03:00
Arto Kinnunen
c0a8bd40fc Tests for AES encypt only 2019-10-24 12:19:43 +03:00
Arto Kinnunen
1480444e8e Add config option for AES encryption only
-Add config option for AES encyption only to config.h. Feature is
 disabled by default.
-Enable AES encrypt only feature in baremetal.h configuration
-Remove AES encypt only feature from full config
2019-10-24 12:19:33 +03:00
Arto Kinnunen
366c13eaad Update AES 128-bit key test
Flag out 192/256-bit key tests from test_suite_cipher.gcm
2019-10-24 09:49:23 +03:00
Arto Kinnunen
4c003ca80c Update AES 128-key test
- Unset MBEDTLS_PADLOCK_C in aes_only_128_bit_keys test to get RAM
  optimised version tested
- Use compiler flag "-O1" instead of "-Wall -Wextra" to see warnings
2019-10-24 09:49:23 +03:00
Arto Kinnunen
5ed870da72 Adjust AES RAM usage according to config options
Do not reserve additionl space for mbedtls_aes_context if config
option AES_ONLY_128_BIT_KEY_LENGTH is used and PADLOCK_C is not used.
This reduces RAM usage by 96 bytes.

In baremetal configuration reserve space for 10 128-bit keys in order
to save 112 bytes of heap.
2019-10-24 09:49:23 +03:00
Arto Kinnunen
5bdafa21e0 Update version_features.c 2019-10-24 09:49:23 +03:00
Arto Kinnunen
265d162d07 Update AES-128 bit configuration
- Do not include MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH to full config
  as it requires also MBEDTLS_CTR_DRBG_USE_128_BIT_KEY

- Update check_config to check availability of flags:
   MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH
   MBEDTLS_CTR_DRBG_USE_128_BIT_KEY
2019-10-24 09:49:23 +03:00
Arto Kinnunen
60b11064c5 Update configuration
Move MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH to proper place in config.h
2019-10-24 09:49:23 +03:00
Arto Kinnunen
4ab702b24a Add AES 128-bit key dependency to tests
- Do not run tests that are using 192/256-bit keys if only
  128-bit keys are allowed for AES.
- Add AES 128-bit-only test to all.sh
2019-10-24 09:49:23 +03:00
Arto Kinnunen
77b9cfcea9 AES: add config option for 128-bit keys
Add configuration options to support only 128-bit key lengths in AES
calculation.
2019-10-24 09:49:23 +03:00
Simon Butcher
e2bf54d3d1 Merge remote-tracking branch 'public/pr/2877' into baremetal 2019-10-23 14:53:29 +01:00
Simon Butcher
713e5c365d Merge remote-tracking branch 'public/pr/2880' into baremetal 2019-10-23 14:52:27 +01:00
Simon Butcher
a26fb4c64f Merge remote-tracking branch 'public/pr/2870' into baremetal 2019-10-23 14:51:37 +01:00
Teppo Järvelin
3d414bfb65 Increased MEMORY_HEAP_SIZE to 140000 in ssl_server2 to get CI passing. 2019-10-22 14:44:13 +03:00
Teppo Järvelin
11e881b536 Changed entropy to be allocated from stack to heap in ssl_server2 2019-10-22 14:44:13 +03:00
Teppo Järvelin
8e0e48199b Changed main buf to be allocated from heap in ssl_client2 2019-10-22 14:44:13 +03:00
Teppo Järvelin
8e0fe19a6a Various changes to get CI passing after changes in ssl_server and client stack to heap 2019-10-22 14:43:56 +03:00
Manuel Pégourié-Gonnard
66491e1840 Fix undefined references to hardware_poll()
Ultimately, mbedtls_hardware_poll() is going to be provided by the
OS/environment when running on target. But for on-host programs and tests, we
need to define (a fake version) in each program that we want to be able to
link.

A previous commit took care of ssl_client2 and ssl_server2. But if we want to
be able to compile all programs, we need to modify each of them. This doesn't
seem useful, so instead let's just build the programs we need for testing -
this means only udp_proxy needs fixing in addition to what's already done.

This issue went unnoticed in the PR that introduced the new all.sh component,
because at that time the platform_memxxx() functions were not actually used in
the library (nor in programs), so the linker could live with
mbedtls_hardware_poll() not being defined, as it wasn't called anywhere. This
changed when we started using the new platform_memxxx() functions in the
library.
2019-10-22 12:50:13 +02:00
Jarno Lamsa
08d6cf2070 Modify the test_baremetal in all.sh
Allow it to run the whole ssl-opt.sh instead of filtering only to
Default, DTLS
2019-10-22 13:32:26 +03:00
Jarno Lamsa
33281d5546 Add requires entries for tests
To be able to pass the ssl_opt.sh with the baremetal configuration
2019-10-22 13:32:26 +03:00
Manuel Pégourié-Gonnard
3d01f2313b Use plain memset() in HMAC-DRBG seeding
The line above the memset() relies on the fact that V is all-zero at that
point (see the comment above), so it doesn't contain a sensitive value.
2019-10-22 10:03:07 +02:00
Manuel Pégourié-Gonnard
895454da01 Use plain memset() for public data in ssl_tls.c
- out_ctr is public because it's transmited over the wire in DTLS (and in TLS
  it can be inferred by a passive network attacker just by counting records).
- handshake mask is not a secret because it can be inferred by a passive
  network attacker just logging record sequence number seen so far.
2019-10-22 10:03:07 +02:00
Manuel Pégourié-Gonnard
ee0c35fbf5 Use plain memset() for session ID and Hello.Random
Those are public values (transmitted in the clear over the wire).
2019-10-22 10:03:07 +02:00
Manuel Pégourié-Gonnard
6bf30be457 Use plain memset() for signature transcoding
By nature, signatures don't need to be kept secret.
2019-10-22 10:03:07 +02:00
Manuel Pégourié-Gonnard
54526c3c89 Use plain memset() for freshly allocated objects
This commits reverts to plain memset() for cases like:

    some_type foo;
    memset( &foo, 0, sizeof( foo ) );

(Sometimes there is code between declaration in memset(), but it doesn't
matter as long as it doesn't touch foo.)

The reasoning is the same as in the previous commit: the stack shouldn't
contain sensitive data as we carefully wipe it after use.
2019-10-22 10:03:07 +02:00
Manuel Pégourié-Gonnard
994193326b Use plain memset() in context init functions
We call xxx_init() on a structure when it has been freshly allocated (on the
stack or heap).

At this point it contains random-looking data none of which should be
sensitive, as all sensitive data is wiped using mbedtls_platform_zeroize()
when we're done using it and the memory area is going to be reclaimed (by
exiting the function or free()ing the buffer).
2019-10-22 10:03:07 +02:00
Manuel Pégourié-Gonnard
14f33e74c0 Use platform_memset() in platform_zeroize()
We're using zeroize in many places in order to erase secrets, so we really
need it to be as secure as possible.
2019-10-22 10:03:07 +02:00
Manuel Pégourié-Gonnard
5220781b98 Fix missing include in some files
Add it in all files that use mbedtls_plaform_memset() but didn't already
include platfom_util.h.

In some configurations it just happened to work, either because it was
included indirectly or because the part of the code that used that function
was disabled, but it some configurations it broke, so let's fix it properly.
2019-10-22 10:03:07 +02:00
Manuel Pégourié-Gonnard
7a346b866c Replace memset() with mbedtls_platform_memset()
Steps:

1. sed -i 's/\bmemset(\([^)]\)/mbedtls_platform_memset(\1/g' library/*.c tinycrypt/*.c include/mbedtls/*.h scripts/data_files/*.fmt

2. Manually edit library/platform_util.c to revert to memset() in the
implementations of mbedtls_platform_memset() and mbedtls_platform_memcpy()

3. egrep -n '\<memset\>' library/*.c include/mbedtls/*.h tinycrypt/*.c
The remaining occurrences are in three categories:
    a. From point 2 above.
    b. In comments.
    c. In the initialisation of memset_func, to be changed in a future commit.
2019-10-22 10:03:07 +02:00
Teppo Järvelin
52c9ecb408 Fixed memory leak in ssl_server2.c main
Allocations are now done after command line parsing.
Added more checks if allocations are needed and fixed
baremetal tests with these defines.
2019-10-15 14:21:29 +03:00
Teppo Järvelin
ff1ce269d0 Fixed to compile: ssl_async_keys is not a pointer but was treated that way when giving to functions. 2019-10-14 08:14:34 +03:00
Hanno Becker
ead3aae8d9 Reduce number of entropy sources to 1 in baremetal configuration 2019-10-10 11:47:28 +03:00
Hanno Becker
c828432920 Make use of copy-less CRT parsing API in ssl_client2/ssl_server2 2019-10-10 11:47:28 +03:00
Hanno Becker
7d864c494a ssl_client2/ssl_server2: Use heap for various structures
This commit modifies the example programs ssl_client2 and ssl_server2
to allocate various structures on the heap instead of the stack. This
allows more fine-grained memory usage tracking via valgrind massif.
2019-10-10 11:47:28 +03:00
Simon Butcher
f0963f7141 Merge remote-tracking branch 'public/pr/2867' into baremetal 2019-10-08 18:57:31 +01:00
Simon Butcher
f7881ad2b7 Merge remote-tracking branch 'public/pr/2865' into baremetal 2019-10-08 18:42:04 +01:00
Simon Butcher
3a9d8a54e4 Merge remote-tracking branch 'public/pr/2881' into baremetal 2019-10-08 18:39:34 +01:00
Manuel Pégourié-Gonnard
0a9b44ddaa Merge branch 'mbedtls-2.16' into baremetal-2.16-20191004
* mbedtls-2.16: (25 commits)
  Fix compilation error
  Add const to variable
  Fix endianity issue when reading uint32
  Increase test suite timeout
  Reduce stack usage of test_suite_pkcs1_v15
  Reduce stack usage of test_suite_pkcs1_v21
  Reduce stack usage of test_suite_rsa
  Reduce stack usage of test_suite_pk
  Enable MBEDTLS_MEMORY_DEBUG in memory buffer alloc test in all.sh
  Remove unnecessary memory buffer alloc and memory backtrace unsets
  Disable DTLS proxy tests for MEMORY_BUFFER_ALLOC test
  all.sh: restructure memory allocator tests
  Add missing dependency in memory buffer alloc set in all.sh
  Don't set MBEDTLS_MEMORY_DEBUG through `scripts/config.pl full`
  Add cfg dep MBEDTLS_MEMORY_DEBUG->MBEDTLS_MEMORY_BUFFER_ALLOC_C
  Add all.sh run with full config and ASan enabled
  Add all.sh run with MBEDTLS_MEMORY_BUFFER_ALLOC_C enabled
  Update documentation of exceptions for `config.pl full`
  Adapt all.sh to removal of buffer allocator from full config
  Disable memory buffer allocator in full config
  ...
2019-10-07 12:44:09 +02:00
Jarno Lamsa
c4315e6d5e Address review comments for documentation 2019-10-04 15:42:39 +03:00
Jarno Lamsa
1881ef53b7 Move the definition of function in zeroize
There is a static dependency in the test system for
this file. To prevent the issue from happening, move
the definition to the end of file so that the last
return in the main remains in the same line.
2019-10-04 15:02:57 +03:00
Jarno Lamsa
990135eb4e Add all.sh entry 2019-10-04 14:50:50 +03:00
Teppo Järvelin
0efac53cdc Review fixes: fixed comments to be more accurate and changed one memcmp to safer version 2019-10-04 13:21:08 +03:00
Jarno Lamsa
642596e931 Adapt the example programs
Adapt the example programs if MBEDTLS_ENTROPY_HARDWARE_ALT
is defined.
2019-10-04 12:52:42 +03:00
Jarno Lamsa
f098b26b83 Add rng for the test suites 2019-10-04 12:51:45 +03:00
Teppo Järvelin
707ceb88f0 Replaced mbedtls_ssl_safer_memcmp with mbedtls_platform_memcmp
Saves some bytes and mbedtls_platform_memcmp is a bit safer for side channel
attacks.
2019-10-04 08:52:00 +03:00
Teppo Järvelin
650343cdcd Changed mbedtls_platform_memcmp to memcmp for places that don't have critical data and are under baremetal
Changed back because we don't wan't to slow down the performance more than we must.
2019-10-04 07:35:55 +03:00
Jarno Lamsa
39a9d40f84 Update documentation for the RNG-function 2019-10-03 13:49:35 +03:00
Jarno Lamsa
436d18dcaa Prevent a 0-modulus
If given range for a random is [0, 0), return 0.
Modulus 0 is undefined behaviour.
2019-10-03 13:49:35 +03:00
Jarno Lamsa
e29e8a49b8 Use MBEDTLS_ENTROPY_HARDWARE_ALT
Use MBEDTLS_ENTROPY_HARDWARE_ALT instead of a new global RNG
flag. When this flag is enabled, the platform provides the RNG.
When running unit tests, rnd_std_rand should be used by overriding
the mbedtls_hardware_poll.
2019-10-03 13:49:34 +03:00
Teppo Järvelin
61f412eb58 Changed every memcmp to SCA equivalent mbedtls_platform_memcmp
This makes physical attacks more difficult.
Selftest memcmp functions were not changed.
2019-10-03 13:14:33 +03:00
Manuel Pégourié-Gonnard
51f65e4b86 Standardize prototypes of platform_memcpy/memset
As replacements of standard library functions, they should have the same
prototype, including return type.

While it doesn't usually matter when used directly, it does when the address
of the function is taken, as done with memset_func, used for implementing
mbedtls_platform_zeroize().
2019-10-03 07:59:58 +03:00
Jarno Lamsa
a1e5054d91 Fix issues in CI 2019-10-02 12:52:39 +03:00
Jarno Lamsa
77a0e07f80 Add return value doxygen 2019-10-02 08:39:32 +03:00
Jarno Lamsa
7cb902737b Use bitwise comparison in memcmp
It is safer than == operator.
2019-10-02 08:32:51 +03:00
Jarno Lamsa
32db938463 Fix buffer initalisation
Initialise the buffer tail with random data instead of
given value.
2019-10-02 08:25:57 +03:00
Jarno Lamsa
f5ebe2a7ce Make RNG exclude the given maximum value
The RNG will give numbers in range of [0, num), so that
the given maximum is excluded.
2019-10-02 08:23:11 +03:00
Jarno Lamsa
0ff7109b7c Fix style issues 2019-10-02 08:18:29 +03:00
Jarno Lamsa
5aee8cab2a Update query_config 2019-10-01 16:10:03 +03:00
Jarno Lamsa
f65e9de57b Change rng-function return-type 2019-10-01 16:09:35 +03:00
Jarno Lamsa
7d28155b30 Add doxygen for the platform-functions 2019-10-01 15:56:17 +03:00
Jarno Lamsa
a19673222b Change the rng-function name
Change the name to mbedtls_platform_random_in_range
2019-10-01 15:31:08 +03:00
Jarno Lamsa
21d6a201ee Add missing typecast for memset 2019-10-01 15:20:13 +03:00
Jarno Lamsa
d82e559a48 Add a config flag for the global RNG
The global RNG should be provided by the application depending on
the RNG used there. (I.e. TRNG)
2019-10-01 14:54:41 +03:00
Arto Kinnunen
d19867293d Harmonize static function compiler flags
Warnings are treated as errors in Mbed TLS test. An error
"ssl_parse_client_hello_v2’ defined but not used" can occur in some
specific configurations and therefore tests will break.

Use similar flags for static function "ssl_parse_client_hello_v2" as
what is used when calling the function to prevent the compilation
warning/error.
2019-09-30 10:26:29 +03:00
Jarno Lamsa
0736325d80 Add FI/SCA compliant versions of mem-functions
Add FI/SCA compliant memset, memcmp and memcpy-functions
to platform_util. Also add a stub implementation of a global
RNG-function.
2019-09-30 09:40:03 +03:00
Arto Kinnunen
cfbeb76dd2 ssl-opt.sh: Adjust authentication test flags 2
Require MBEDTLS_X509_MAX_INTERMEDIATE_CA to be exactly 8 in
authentication tests.
2019-09-27 13:43:05 +03:00
Arto Kinnunen
13db25fbe9 ssl-opt.sh: Fix requires_config_value_exactly
Fix comparison bug in requires_config_value_exactly.
2019-09-27 13:06:25 +03:00
Arto Kinnunen
c457ab1c2b ssl-opt.sh: Adjust authentication test flags
Require MBEDTLS_X509_MAX_INTERMEDIATE_CA to be exactly 8 in one
authentication test.
2019-09-27 12:00:51 +03:00
Arto Kinnunen
a1e980695b ssl-opt.sh: Modify test sets based on config value 2
Adjust tests set configuration based on review comments.
2019-09-26 19:35:16 +03:00
Arto Kinnunen
3f1190d15b sslopt.sh: Modify test sets based on config value
query_opt is used to read Mbed TLS configuration values instead of
config.pl script. Now MBEDTLS_SSL_MAX_CONTENT_LEN value is correctly
read and some tests needs to be removed from the test set when value
of MBEDTLS_SSL_MAX_CONTENT_LEN is too small for the test.
2019-09-26 17:18:57 +03:00
Arto Kinnunen
aef8678c7f Revert spacing in programs/makefile APPS
Do not modify spacing in programs/Makefile APPS.
2019-09-26 14:54:11 +03:00
Arto Kinnunen
7821352483 ssl-opt.sh: use query_config to read flag value
To avoid dependency to "config.pl" use query_config test program to
read Mbed TLS flag values.
2019-09-26 11:06:39 +03:00
Arto Kinnunen
c0d2fa7f0b Update Makefiles and revert changes to config.pl
-Add comments to Makefiles about test env auto-detection
-Fix indentation
-Remove parent folder from include dirs
-Do not use environment variable for defining config file because
 env variable usage is not fully implemented
-Revert changes to config.pl
2019-09-26 10:33:56 +03:00
Simon Butcher
85b495b30a Merge remote-tracking branch 'origin/pr/652' into baremetal 2019-09-25 16:37:07 +01:00
Arto Kinnunen
5e639ed026 Add comments to Makefiles
Add missing comment to Makefiles about purpose of the change.
2019-09-25 17:08:39 +03:00
Arto Kinnunen
8307802824 Enable tests in Mbed OS environment
Update Makefiles and config.pl to adapt to directory structure used
in Mbed OS.
2019-09-25 16:23:17 +03:00
Hanno Becker
ab9a29bd2c ssl-opt.sh: Reuse query config test program for requires_config_xxx
This commit reimplements the helper functions
- requires_config_enabled
- requires_config_disabled
in ssl-opt.sh in terms of the programs/test/query_config
programs which allows to query the configuration in which
Mbed TLS was built.

This removes the dependency of ssl-opt.sh from the config
that was used to build the library.
2019-09-25 16:09:15 +03:00
Simon Butcher
bf77960368 Merge remote-tracking branch 'public/pr/2849' into baremetal 2019-09-24 15:29:55 +01:00
Simon Butcher
8d0684dd06 Merge remote-tracking branch 'public/pr/2835' into baremetal 2019-09-24 15:28:35 +01:00
Simon Butcher
810ee06689 Merge remote-tracking branch 'public/pr/2830' into baremetal 2019-09-24 15:17:54 +01:00
Manuel Pégourié-Gonnard
d2c24869ae baremetal.sh: include total in ROM report 2019-09-20 10:29:29 +02:00
Manuel Pégourié-Gonnard
15be0eeae4 baremetal.sh: extract ROM reporting to a function 2019-09-20 10:25:29 +02:00
Manuel Pégourié-Gonnard
8b5e6bd6ae Improve some internal documentation 2019-09-20 08:57:18 +02:00
Manuel Pégourié-Gonnard
6d229f8af0 Adapt EC-JPAKE test suite to hardcodable hash 2019-09-19 12:07:58 +02:00
Manuel Pégourié-Gonnard
a77e9b5b35 Make sub-context statically allocated
This makes a mbedtls_pk_context memory-wise equivalent to a
mbedtls_uecc_keypair and removes a dynamic allocation, making the PK layer
zero-cost in terms of memory when PK_SINGLE_TYPE is enabled.
2019-09-19 10:45:14 +02:00
Manuel Pégourié-Gonnard
073c1e1391 Remove pk_info from pk_context_t with SINGLE_TYPE
In very reduced configurations, we don't want the overhead of maintaining a
bool just to remember if the context is valid and checking that bit at every
point of entry.

Note: so far this validity bit also served as a proxy to ensure that pk_ctx
was valid (currently this is a pointer to a dynamically-allocated buffer). In
the next series of commits, this will be changed to a statically-allocated
buffer, so there will be no question about its validity.

In the end (after this commit and the next series), a pk_context_t will be
(memory-wise) just the same as a mbedtls_uecc_keypair when SINGLE_TYPE is
enabled - meaning the PK layer will have zero memory overhead in that case.
2019-09-19 10:45:14 +02:00
Manuel Pégourié-Gonnard
2829bbf59b Remove dependency from SSL on PK internals
So far, with MBEDTLS_SSL_KEEP_PEER_CERTIFICATE disabled, the SSL module relied
on a undocumented feature of the PK module: that you can distinguish between
contexts that have been setup and context that haven't. This feature is going
to go away in the case of PK_SINGLE_TYPE, as we'll soon (as in: the next
commit does that) no longer be storing the (now two-valued) pk_info member.

Note even with this change, we could still distinguish if the context has been
set up by look if pk_ctx is NULL or not, but this is also going away in the
near future (a few more commits down the road), so not a good option either.
2019-09-19 10:45:14 +02:00
Manuel Pégourié-Gonnard
4223ce4fca Introduce macro-based read access to ctx->pk_info 2019-09-19 10:45:14 +02:00
Manuel Pégourié-Gonnard
f8b7c7f0ac Implement two-valued handle type 2019-09-19 10:45:14 +02:00
Manuel Pégourié-Gonnard
020d9ba4ed Introduce abstraction mbedtls_pk_handle_t
This is the first in a series of commit aimed at removing the pk_info
structures when we're building with MBEDTLS_PK_SINGLE_TYPE enabled.

Introducing this abstraction allows us to later make it a two-valued type
(valid, invalid) instead, which is much lighter.
2019-09-19 10:45:14 +02:00
Manuel Pégourié-Gonnard
08620cbb62 Implement static dispatch with SINGLE_PK_TYPE
For optional functions, we introduce an extra macro to tell if the function is
omitted. As the C preprocessor doesn't directly support comparing strings,
testing if the _FUNC macro is defined to NULL isn't obvious. One could
probably play tricks to avoid the need for _OMIT macros, but the small amount
of (entirely local) duplication here is probably a lesser evil than extra
preprocessor complexity.
2019-09-19 10:45:14 +02:00
Manuel Pégourié-Gonnard
8cd288932b Clean up merged pk_wrap in pk.c
- remove redundant includes
- add "title" comment on each section
2019-09-19 10:45:14 +02:00
Manuel Pégourié-Gonnard
4ed179f693 Merge pk_wrap into pk.c
We want public functions to resolve to the internal wrappers at compile-time.
For this we need the wrappers to be visible from where the public functions
are defined. A simple declaration is not enough if we want the compiler to be
able to inline the wrapper and eliminate function overhead.

This commit just copies verbatim the contents of pk_wrap.c into pk.c. The next
commit will clean up the result (redundant includes etc.).
2019-09-19 10:45:14 +02:00
Manuel Pégourié-Gonnard
342cecf1f7 Introduce macro-based access to info members
For now, this is only used in order to defined the uecc instance of pk_info,
but in subsequent commits this can be used to implement static dispatch.
2019-09-19 10:45:14 +02:00
Manuel Pégourié-Gonnard
1c1cc0d373 Add config.h option MBEDTLS_PK_SINGLE_HASH
No effect for now, just declaring it here, implemented in subsequent commits.

The option requires MBEDTLS_USE_TINYCRYPT and is incompatible with
MBEDTLS_PK_RSA_ALT_SUPPORT and MBEDTLS_RSA_C.

Currently users (including the X.509 and SSL libraries) assume that if both PK
and RSA are enabled, then RSA is available through PK. If we allowed RSA to be
enabled together with PK_SINGLE_TYPE, we'd break that assumption. Going
through the code to find all place that rely on that assumption and fix them
would be cumbersome, and people who want PK_SINGLE_TYPE are unlikely to care
about RSA anyway, so let's just make them incompatible.

This is also consistent with what's done in the MD module: MD_SINGLE_HASH
requires that exactly one hash be enabled.
2019-09-19 10:45:14 +02:00
Manuel Pégourié-Gonnard
26b807dae8 Fix bug in pkwrite with TinyCrypt but no RSA
This is pre-existing, fixing is required to make a newly added test pass.
2019-09-19 10:45:14 +02:00
Manuel Pégourié-Gonnard
f4afbf926e Fix missing include in some pkey programs
The programs assume that including "pk.h" brings up "bignum.h". When
MBEDTLS_USE_TINYCRYPT is enabled and MBEDTLS_RSA_C is disabled, that
assumption no longer holds. Fix that by explicitly including bignum.h from the
programs that need it.

This is a bug pre-existing to this PR, fixed here to enable the inclusion of a
test with a config that happens to reveal it.
2019-09-19 10:45:14 +02:00
Manuel Pégourié-Gonnard
097628f871 Fix undeclared dependency on RSA_ALT in tests 2019-09-19 10:45:14 +02:00
Manuel Pégourié-Gonnard
57d96cddf5 Move NULL check inside accessor function
This achieves two related goals:

1. Those members are now only accessed via the accessor function (except in
code paths that we don't care about: those guarded by
MBEDTLS_PK_RSA_ALT_SUPPORT or MBEDTLS_ECP_RESTARTABLE)
2. When we turn on compile-time dispatch, we don't obviously don't want to
keep a runtime NULL check.

For debug this requires changing the signature or the accessor function to
return int; this is done without changing the signature of the accessed
function.
2019-09-19 10:45:14 +02:00
Manuel Pégourié-Gonnard
2d9466f1db Minor preparatory changes in mbedtls_pk_check_pair()
1. Mark an RSA-alt-specific code path as such.
2. Move NULL check for wrapper function closer to the use of that function.

Those are in preparation of the next commit.
2019-09-19 10:45:14 +02:00
Manuel Pégourié-Gonnard
c10f092a87 Add accessor functions for members of pk_info
This is the first commit in a series aiming at implementing optional
compile-time dispatch when a single PK type is hardcoded. At the end of this
series, the functions introduced here will directly resolve to the correct
function at compile-time when this (to be created) option is enabled.
2019-09-19 10:45:14 +02:00
Manuel Pégourié-Gonnard
e5a0b366f8 Merge branch 'baremetal' into baremetal-2.16-20190909
* baremetal: (78 commits)
  Review corrections 6
  Review corrections 5
  Minor changes to tinycrypt README
  Typos in the tinycrypt README
  Addition of copyright statements to tinycrypt files
  Add LICENSE and README for tinycrypt
  Add SPDX lines to each imported TinyCrypt file
  Review corrections 4
  Review corrections 3
  Review corrections 2
  Review corrections
  Update signature of BE conversion functions
  Use function for 16/24/32-bit BE conversion
  x509.c: Minor readability improvement
  x509_crt.c: Indicate guarding condition in #else branch
  X.509: Don't remove verify callback by default
  Fix Doxygen warnings regarding removed verify cb+ctx parameters
  ECC restart: Use optional verification mode in bad signature test
  Re-implement verify chain if vrfy cbs are disabled
  Add zero-cost abstraction layer for CRT verification chain
  ...
2019-09-12 09:58:14 +02:00
Manuel Pégourié-Gonnard
3cdfa0c2cc Fix ChangeLog by grouping baremetal entries
In previous merges, ChangeLog entries from the baremetal branch got mixed with
entries from the 2.16 branch, which resulted in a confusing and unhelpful log.
Restore some order by grouping all baremetal entries in their own section.
2019-09-11 13:02:18 +02:00
Teppo Järvelin
f950e28456 Changed generate_visualc_files.pl to exclude x509_xxx files 2019-09-11 08:50:34 +03:00
Simon Butcher
e8144aa8ea Merge remote-tracking branch 'origin/pr/657' into baremetal 2019-09-10 14:59:14 +01:00
Simon Butcher
88b535a47e Merge remote-tracking branch 'origin/pr/654' into baremetal 2019-09-10 14:54:28 +01:00
Simon Butcher
303d399f42 Merge remote-tracking branch 'origin/pr/609' into baremetal 2019-09-10 14:50:04 +01:00
Simon Butcher
9bdd13b2e7 Merge remote-tracking branch 'origin/pr/621' into baremetal 2019-09-10 14:49:35 +01:00
Simon Butcher
e901566f55 Merge remote-tracking branch 'origin/pr/658' into baremetal 2019-09-10 12:55:03 +01:00
Teppo Järvelin
fc6df59db0 Fixing windows build: don't compile c files which are included 2019-09-10 14:04:36 +03:00
Manuel Pégourié-Gonnard
fa4cbe0422 Fix conflict in EC private key writing
On the mbedtls-2.16 side, there was a change in commit
a7cfdad82e (PR r#503) in order to write
fixed-length private keys. It added a new helper function
pk_write_ec_private() for that.

On the baremetal side, there were changes in order to add a tinycrypt-based
implementation. It added a new helper function pk_write_ec_privkey() with two
implementations (with or without tinycrypt).

This commit keeps the function pk_write_ec_privkey() but changes its
implementation in the non-tinycrypt configuration in order to match the
implementation of pk_write_ec_private(), which is in turn removed it was only
used in that place.

The tinycrypt version of pk_write_ec_private() was already writing
constant-length private keys, so there is nothing to change here.
2019-09-10 12:20:43 +02:00
Manuel Pégourié-Gonnard
8abd0a0c84 Merge branch 'mbedtls-2.16' into baremetal-2.16-20190909
* mbedtls-2.16: (28 commits)
  Bump version to Mbed TLS 2.16.3
  Changelog entry
  Check for zero length and NULL buffer pointer
  ssl-opt.sh: wait for proxy to start before running the script further
  Fix uninitialized variable in x509_crt
  HMAC DRBG: Split entropy-gathering requests to reduce request sizes
  Fix the license header of hkdf
  Add a change log entry
  Add a test for mlaformed ECJPAKE context
  Fix handling of md failure
  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
  Adapt ChangeLog
  Fix mpi_bigendian_to_host() on bigendian systems
  Add ChangeLog entry for new function
  Add ChangeLog entry
  Correct deterministic ECDSA behavior
  Add warning for alternative ECDSA implementations
  ...
2019-09-10 11:27:14 +02:00
Arto Kinnunen
3d7439e90f Review corrections 6
-Explicitly discard unnecessary return values of
 mbedtls_platform_put_uintXX_be by adding void casting.
2019-09-10 11:30:40 +03:00
Arto Kinnunen
84eeb4fd96 Review corrections 5
-Remove unintentional type chaneg (size_t to uint32_t)
 -Follow mbedtls coding style in trace message
2019-09-10 10:32:30 +03:00
Simon Butcher
389b16d9f9 Minor changes to tinycrypt README
Qualification of title and addition of copyright statement in tinycrypt
README
2019-09-09 18:40:17 +01:00
Simon Butcher
05ab73224a Typos in the tinycrypt README 2019-09-09 17:40:20 +01:00
Simon Butcher
92c3d1f4f4 Addition of copyright statements to tinycrypt files
Each of the tinycrypt files have had some very minor changes, so need a
copyright statement.
2019-09-09 17:37:08 +01:00
Simon Butcher
4f58d696e2 Add LICENSE and README for tinycrypt
This commit adds a LICENSE file and README file to tinycrypt, to help auditing
of the source code for licenses and also to indicate the origin of the work.
2019-09-09 17:36:58 +01:00
Simon Butcher
cffedb548f Add SPDX lines to each imported TinyCrypt file
Out of the 6 tinycrypt files included in Mbed TLS, this commit adds SPDX lines
to each for the BSD 3 Clause licence.
2019-09-09 17:34:51 +01:00
Arto Kinnunen
9b3b19407a Review corrections 4
- Try to follow english grammar in function documentation
- Fix too long line
- Remove additional brackets
- Follow mbedtls coding style in for-statement
2019-09-09 17:21:18 +03:00
Arto Kinnunen
a3fa06e62a Review corrections 3
-Remove additional trace cause by rebase
-Update remaining 16/24/32-bit values to use functions, this uses
 additional 36 bytes.
2019-09-09 17:21:18 +03:00
Arto Kinnunen
4f4849a379 Review corrections 2
-Fix MSVC compiler warnings about size_t to uint32_t conversions by
 updating GET/PUT functions signature to use size_t.
-Add type casts to functions calling GET/PUT conversions
-Remove additional space after return statement
2019-09-09 17:21:18 +03:00
Arto Kinnunen
6e3f09b431 Review corrections
-Fix compiler warnings by typecast
 -Add missing brackets to few places
 -Remove additional line change
2019-09-09 17:21:18 +03:00
Arto Kinnunen
ee9bfca823 Update signature of BE conversion functions 2019-09-09 17:21:18 +03:00
Arto Kinnunen
0b62ce8ed4 Use function for 16/24/32-bit BE conversion
Use functions for 16/24/32-bit big endian conversion to save ROM.
2019-09-09 17:21:18 +03:00
Simon Butcher
7fce190774 Merge remote-tracking branch 'origin/pr/635' into HEAD 2019-09-09 14:20:03 +01:00
Simon Butcher
b8ec79f8a0 Merge remote-tracking branch 'origin/pr/645' into HEAD 2019-09-09 13:59:54 +01:00
Hanno Becker
392a8d0e64 x509.c: Minor readability improvement 2019-09-09 09:55:31 +01:00
Hanno Becker
14b0a68083 x509_crt.c: Indicate guarding condition in #else branch 2019-09-09 09:55:31 +01:00
Hanno Becker
cd239f8839 X.509: Don't remove verify callback by default 2019-09-09 09:55:31 +01:00
Hanno Becker
cd839c9aa7 Fix Doxygen warnings regarding removed verify cb+ctx parameters 2019-09-09 09:55:31 +01:00
Hanno Becker
03d7746927 ECC restart: Use optional verification mode in bad signature test
This way, the verification failure string will still be printed
even if verification callbacks are disabled, allowing to increase
test coverage.
2019-09-09 09:55:31 +01:00
Hanno Becker
8d6d320603 Re-implement verify chain if vrfy cbs are disabled
This commit re-implements the previously introduced internal
verification chain API in the case where verification callbacks
are disabled. In this situation, it is not necessary to maintain
the list of individual certificates and flags comprising the
verification chain - instead, it suffices to just keep track
of the length and the total (=merged) flags.
2019-09-09 09:55:31 +01:00
Hanno Becker
adc282a5e8 Add zero-cost abstraction layer for CRT verification chain
When verifying an X.509 certificate, the current verification logic
maintains an instance of the internal mbedtls_x509_crt_verify_chain
structure representing the state of the verification process. This
instance references the list of certificates that comprise the chain
built so far together with their verification flags. This information
must be stored during verification because it's being passed to the
verification callback at the end of verification - if the user has
specified those.

If the user hasn't specified a verification callback, it is not
necessary to maintain the list of CRTs, and it is also not necessary
to maintain verification flags for each CRT individually, as they're
merged at the end of the verification process.

To allow a readable simplification of the code in case no verification
callbacks are used, this commit introduces a zero-cost abstraction layer
for the functionality that's required from the verification chain structure:
- init/reset
- add a new CRT to the chain
- get pointer to current CRT flags
- add flags to EE certificate
- get current chain length
- trigger callbacks and get final (merged) flags
This gives flexibility for re-implementing the verification chain
structure, e.g. in the case where no verification callbacks are
provided, and there's hence no need to store CRTs and flags
individually. This will be done in a later commit.
2019-09-09 09:55:31 +01:00
Hanno Becker
9ec3fe0d43 Introduce configuration option to remove CRT verification callbacks 2019-09-09 09:55:31 +01:00
Hanno Becker
56d1b2389c Fixup: Don't assume that alt SHA256 impln's have trivial init/free 2019-09-09 09:45:57 +01:00
Hanno Becker
18c8936a73 Fixup: Correct Doxygen file name primitive in md_internal.h 2019-09-09 09:45:57 +01:00
Hanno Becker
f6cc3cd2a5 Fixup: Typo in check_config.h entry for single hash encoding 2019-09-09 09:45:57 +01:00
Hanno Becker
f207562cdc Fixup: Typo in all.sh component description for single-MD hardcoding 2019-09-09 09:45:57 +01:00
Hanno Becker
55fdae04f7 Fixup: Improve comment on helper macros in md_internal.h 2019-09-09 09:45:57 +01:00
Hanno Becker
3252c4d913 Fixup MD: Avoid always-false pointer comparison
When MBEDTLS_MD_SINGLE_HASH is set, both the underlying digest context
and the HMAC data are embedded into the mbedtls_md_context; otherwise,
they're dynamically allocated and referenced from mbedtls_md_context.

When the HMAC data is embedded in mbedtls_md_context, it's unnecessary
to check whether mbedtls_md_context::hmac_ctx is NULL, because that's
never the case in defined behaviour, but the check has kept for
uniformity so far. However, contrary to the expectation that compilers
would silently remove this check as always false, ARMC6 complains about
it, breaking some tests in all.sh.

This commit fixes this by guarding checks for

   mbedtls_md_context::hmac_ctx == NULL

by !MBEDTLS_MD_SINGLE_HASH.
2019-09-09 09:45:57 +01:00
Hanno Becker
94f48e0052 MD: Use no-op for context SHA-256 init() and free()
When MBEDTLS_MD_SINGLE_HASH is set, the underlying digest's
context is embedded into mbedtls_md_context_t, which is
zeroized before the underlying digest's init() function
is called. For those digests where initialization is
zeroization, the init() call can therefore be omitted.

Similarly, when free()-ing an mbedtls_md_context_t, the
entire context is zeroized in the end, hence if the
underlying digest's free() function is zeroization,
it can be omitted.
2019-09-09 09:45:57 +01:00
Hanno Becker
64b0623cbb MD: Implement config dep'n inlining of mbedtls_md_setup() 2019-09-09 09:45:57 +01:00
Hanno Becker
52e36bc1a1 MD: Embed digest context structure into MD wrapper context 2019-09-09 09:45:57 +01:00
Hanno Becker
4a99765f94 MD: Introduce macro for initialization function 2019-09-09 09:45:57 +01:00
Hanno Becker
6deddf761a MD: Introduce macro for underlying context type 2019-09-09 09:45:57 +01:00
Hanno Becker
c290847719 Fixup md.h: Fix use of inline keyword in MSVC 2019-09-09 09:45:57 +01:00
Hanno Becker
7a78fe409b Fixup: Avoid unused function warning for MD wrappers 2019-09-09 09:45:57 +01:00
Hanno Becker
d73aabd1c2 Fixup: Declare digest info structures as static
They're defined and used within library/md.c only and hence
need not be of external linkage.
2019-09-09 09:45:57 +01:00
Hanno Becker
53ade9fa62 MD: Implement config dep'n inlining of mbedtls_md_process() 2019-09-09 09:45:57 +01:00
Hanno Becker
993691d9ba MD: Implement config dep'n inlining of mbedtls_md_finish() 2019-09-09 09:45:57 +01:00
Hanno Becker
fdef5ac13b MD: Implement config dep'n inlining of mbedtls_md_update() 2019-09-09 09:45:57 +01:00
Hanno Becker
527f7c9307 MD: Demonstrate config-dep'n API inlining for mbedtls_md_starts() 2019-09-09 09:45:57 +01:00
Hanno Becker
7a7b7227cb Add dummy def of MBEDTLS_MD_INFO_SHA256 to make check-names.sh happy 2019-09-09 09:45:57 +01:00
Hanno Becker
c4e4210aab Introduce md_internal.h
Recall that in the default configuration, Mbed TLS provides access
digest implementations through two layers of indirection:

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

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

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

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

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

Circumvent this lack of optimization by not returning function pointers.
2019-09-09 09:45:57 +01:00
Hanno Becker
08cf43a9ec Fix typo MBEDTLS_SSL_CONF_SINGLE_HASH -> MBEDTLS_MD_SINGLE_HASH 2019-09-09 09:45:57 +01:00
Hanno Becker
8fbacf941f check_config.h: Check MBEDTLS_MD_SINGLE_HASH is used with single MD
This commit modifies check_config.h to check that precisely one
hash is enabled if MBEDTLS_MD_SINGLE_HASH is set.

This is not only a reasonable expectation, it is also necessary,
because test suites assume that if a digest is enabled, it is also
accessible through the MD abstraction layer.
2019-09-09 09:45:57 +01:00
Hanno Becker
c763e9dc70 Add test for MD hardcoding to all.sh 2019-09-09 09:45:57 +01:00
Hanno Becker
bdaf0ea5d9 Make MD info getters always inline 2019-09-09 09:45:57 +01:00
Hanno Becker
d9bf935725 Disable invalid argument MD test case
With the removal of the MD handle from the MD context, it's a precondition
for any MD API outside of mbedtls_md_init() and mbedtls_md_setup() that
the MD context has been successfully setup by precisely those functions
beforehand, and hence must be bound to the single enabled valid MD handle.
2019-09-09 09:45:57 +01:00
Hanno Becker
c94fc6c0c2 Add MBEDTLS_ALWAYS_INLINE macro to platform_util.h 2019-09-09 09:45:57 +01:00
Hanno Becker
d806d9da89 Use SHA-256 as single hardcoded hash in baremetal configuration 2019-09-09 09:45:57 +01:00
Hanno Becker
ccb2b62f0a Remove handle from MD context in single hash config 2019-09-09 09:45:57 +01:00
Hanno Becker
1292c35c03 Add config.h option to hardcode choice of single MD algorithm
This commit introduces the configuration option

  MBEDTLS_MD_SINGLE_HASH

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

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

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

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

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

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

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

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

  mbedtls_md_info const *

whose valid values represent implementations of message digest algorithms.

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

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

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

The cookie module handles truncation, so it's simpler to always use SHA-256
rather than check if SHA-224 is available.
2019-09-09 10:21:30 +02:00
Manuel Pégourié-Gonnard
81ed9fb277 Exclude SHA-224 from some reduced config examples
Besides the value as an example, this is usefull for testing the option, via
test-ref-configs.pl (which is included in all.sh).
2019-09-09 10:21:30 +02:00
Manuel Pégourié-Gonnard
efd344894d Completely ignore is224 if SHA-224 is disabled 2019-09-09 10:21:30 +02:00
Manuel Pégourié-Gonnard
0956e3ebed Exclude NO_SHA224 option from scripts/config.pl
As a negative option that removes a feature it should be excluded.
2019-09-09 10:21:30 +02:00
Manuel Pégourié-Gonnard
e06cc3109c Add MBEDTLS_SHA256_NO_SHA224 to baremetal.h 2019-09-09 10:21:30 +02:00
Manuel Pégourié-Gonnard
394c5fb24b Implement NO_SHA224 in MD layer as well 2019-09-09 10:21:30 +02:00
Manuel Pégourié-Gonnard
5a26ff3cf9 Declare dependencies on !NO_SHA224 in test suites 2019-09-09 10:21:30 +02:00
Manuel Pégourié-Gonnard
abebdd16ef Adapt SHA-256 selftest to NO_SHA224 2019-09-09 10:21:30 +02:00
Manuel Pégourié-Gonnard
8463d29156 Implement MBEDTLS_SHA256_NO_SHA224 2019-09-09 10:21:30 +02:00
Manuel Pégourié-Gonnard
9b781b2880 Add MBEDTLS_SHA256_NO_SHA244 option (unimplemented) 2019-09-09 09:06:56 +02:00
Jarno Lamsa
28012e2ea2 Remove redundant rng wrapper 2019-09-09 08:42:11 +03:00
Jarno Lamsa
f35f35bcbe Use rnd_std_rand for generating hash 2019-09-09 08:19:56 +03:00
Jarno Lamsa
a7e0f632fc Add unit tests for primitive test vectors
Add a unit test for both ECDSA and ECDH, testing
reference test vectors for secp256r1.
2019-09-09 08:19:56 +03:00
Jarno Lamsa
34fcbfe287 Add rng for the tinycrypt tests
Use rnd_std_rand for the rng.
2019-09-09 08:19:56 +03:00
Jarno Lamsa
6c2f76e9cd Add a unit test for ECDSA
Add a basic unit test for the ECDSA part of the tinycrypt.
It generates keys, signs and verifies. Modified from tinycrypt
tests found in tinycrypt-repository.
2019-09-09 08:19:56 +03:00
Jarno Lamsa
7c5dc6b20a Add test suite for tinycrypt
Initially add a test for ECDH-part.
2019-09-09 08:19:56 +03:00
Simon Butcher
0e895727be Merge remote-tracking branch 'origin/pr/656' into baremetal 2019-09-07 12:48:28 +01:00
Simon Butcher
d82db9d48c Merge remote-tracking branch 'origin/pr/649' into baremetal 2019-09-07 12:46:12 +01:00
Simon Butcher
d91adcf7f5 Merge remote-tracking branch 'origin/pr/624' into baremetal 2019-09-07 12:44:42 +01:00
Simon Butcher
2da461e657 Merge remote-tracking branch 'origin/pr/655' into baremetal 2019-09-07 12:35:54 +01:00
Simon Butcher
e501c8d308 Merge remote-tracking branch 'origin/pr/644' into baremetal 2019-09-07 12:34:46 +01:00
Hanno Becker
d5cfe6fbd0 Use native DTLS version encoding if only DTLS is enabled
This commit changes the internal identifiers

  MBEDTLS_SSL_MINOR_VERSION_XXX

in DTLS-only builds to match the version encoding used by the
DTLS standard, encoding DTLS 1.0 as 255 and DTLS 1.2 as DTLS 1.0.
Accordingly, the version comparison functions introduced in the
previous commit must be re-implemented, as older version have
_larger_ identifiers now.

Further, since we identify DTLS 1.0 as MBEDTLS_SSL_MINOR_VERSION_2
and DTLS 1.2 as MBEDTLS_SSL_MINOR_VERSION_3, what remains is to
define MBEDTLS_SSL_MINOR_VERSION_{0|1}. While these don't have any
meaning meaning in DTLS, they still need to be set and obey the
ordering in the sense that the version comparison functions '<='
should attest that

  MBEDTLS_SSL_MINOR_VERSION_i '<=' MBEDTLS_SSL_MINOR_VERSION_j

for i <= j. Since '<=' is actually >= and the wire format value
for DTLS 1.0 == MBEDTLS_SSL_MINOR_VERSION_2 is the 255, this
forces us to use values beyond 255, and hence to extend the
storage type for minor versions from uint8_t to uint16_t.
2019-09-06 10:35:41 +01:00
Teppo Järvelin
f69e641e03 Changed x509_internal.h methods as static.
Moved some functions under defined to get rid of compiler warnings.
Functions moved under defines:
 - mbedtls_x509_get_alg
 - mbedtls_x509_get_alg_null
 - mbedtls_x509_get_time
 - mbedtls_x509_get_ext
 - mbedtls_x509_sig_alg_gets
 - mbedtls_x509_key_size_helper

Left one function (mbedtls_x509_write_names) as non static as it increased code size.
2019-09-06 10:03:36 +03:00
Teppo Järvelin
c3e5716aaf Some minor struct optimizations. 2019-09-06 07:58:36 +03:00
Hanno Becker
7bcf2b5875 Introduce version comparing functions
This zero-cost abstraction allows to change the internal encoding
of TLS/DTLS versions in the future.
2019-09-05 17:37:55 +01:00
Hanno Becker
963d49f79a ssl-opt.sh: Remove now-redundant explicit DTLS dependencies
Dependencies on DTLS are now auto-detected from the command line.
2019-09-05 14:55:56 +01:00
Hanno Becker
a43f85c9b2 ssl-opt.sh: Auto-skip tests depending on DTLS 2019-09-05 14:51:20 +01:00
Hanno Becker
fcda6ddae1 Fixup: Correct typo in DTLS only component of all.sh 2019-09-05 14:50:00 +01:00
Hanno Becker
baac25d2bf Add DTLS-only build + test to all.sh 2019-09-05 13:57:01 +01:00
Hanno Becker
73b72d1890 ssl-opt.sh: Auto-skip tests using TLS if TLS is disabled 2019-09-05 13:57:01 +01:00
Hanno Becker
d016e44e3c Baremetal config: Remove deprecated functions
This doesn't make a difference after link time optimization
because they aren't used, but it yields more accurate code-size
figures from baremetal.sh.
2019-09-05 13:37:03 +01:00
Hanno Becker
fceba69c25 Baremetal config: Remove MBEDTLS_SSL_TICKETS_C
This doesn't make a difference after link time optimization because
tickets aren't used, but it yields more accurate code-size figures
from baremetal.sh.
2019-09-05 13:36:49 +01:00
Manuel Pégourié-Gonnard
0cfb6efad4 Add work-around for non-C99 compilers 2019-09-05 14:07:01 +02:00
Manuel Pégourié-Gonnard
8bf8f2ebde Improve documentation in config.h 2019-09-05 13:08:21 +02:00
Manuel Pégourié-Gonnard
c7abba3796 Use static inline function unconditionally
No need to play tricks with macros and functions depending on whether
SHA256_SMALLER is enabled or not, with a static inline function all common
compilers (tested with arm-gcc, armcc5, arm-clang) will Do The Right Thing
depending on whether we told them to optimize for size or speed.
2019-09-05 12:09:59 +02:00
Teppo Järvelin
30185bb82b struct optimization for mbedtls_record 2019-09-05 08:54:13 +03:00
Teppo Järvelin
22854511bb struct optimization for mbedtls_ssl_transform 2019-09-05 08:54:13 +03:00
Teppo Järvelin
d689a67af2 struct optimization for mbedtls_x509_crl 2019-09-05 08:54:13 +03:00
Teppo Järvelin
648fbbad8f struct optimization for mbedtls_ssl_context 2019-09-05 08:54:13 +03:00
Teppo Järvelin
1cd48143c3 struct optimization for mbedtls_ssl_handshake_params 2019-09-05 08:54:13 +03:00
Hanno Becker
d601854548 Fixup TinyCrypt Tests: Remove redundant guards 2019-09-04 16:19:49 +01:00
Hanno Becker
683d84a5d7 Fixup TinyCrypt PK parse: Correct function name in comment 2019-09-04 16:19:49 +01:00
Hanno Becker
f45d9da878 Fixup certs.c: Remove redundant TinyCrypt guard 2019-09-04 16:19:49 +01:00
Hanno Becker
d2929b5626 Fixup TinyCrypt PK wrap: Check TinyCrypt signature return code 2019-09-04 16:19:49 +01:00
Hanno Becker
96d34d57ec TinyCrypt PK Wrap: Remove dependency on ASN.1 writing
The TinyCrypt PK signature wrapper uses ASN.1 writing functions
for length and tag, accounting for the only dependency of the
baremetal build on ASN.1 writing.

Since all lengths to be encoded are below 128 Bytes and are hence
ASN.1 encoded as single Bytes, the dependency on ASN.1 writing can
be removed at low complexity by writing the length and tags directly.
2019-09-04 16:19:49 +01:00
Hanno Becker
1b82685dc9 Fixup debug.h and ssl_internal.h: Add missing include of ecdh.h
Previously, this wasn't necessary because ecdh.h was included
through ssl.h, but now that this is no longer the case (because
ssl.h doesn't use ECDH), we have to include it explicitly.
2019-09-04 16:19:49 +01:00
Hanno Becker
82a7a21982 Fixup: Correct inclusion of legacy ECP headers in ssl.h
Previously, ecp.h was included only if MBEDTLS_ECDH_C was set,
which broke the build in configurations using ECDSA, but not ECDH.
An example of such a config is configs/config-thread.h, which
uses ECJPAKE exclusively.

Moreover, the inclusion of ecdh.h isn't needed, because the header
only uses constants defined in the ECP module.
2019-09-04 16:19:49 +01:00
Hanno Becker
a007e0db47 baremetal.h: Use TinyCrypt curve identifier 2019-09-04 16:19:49 +01:00
Hanno Becker
fe08844bac TinyCrypt Test: Include ECDH and ECDHE-PSK in all.sh TinyCrypt test 2019-09-04 16:19:49 +01:00
Hanno Becker
6f212d0a16 TinyCrypt ECDH/ECDHE-PSK: Allow TinyCrypt-based ECDH and ECDHE-PSK 2019-09-04 16:19:49 +01:00
Hanno Becker
6f7680491b TinyCrypt ECDHE-PSK: Adapt dummy structure approximating PMS length 2019-09-04 16:19:49 +01:00
Hanno Becker
358b3006ee TinyCrypt ECDHE-PSK: Implement CliKeyExchange parsing 2019-09-04 16:19:49 +01:00
Hanno Becker
982da7ee0a TinyCrypt ECDHE-PSK: Implement mbedtls_ssl_psk_derive_premaster() 2019-09-04 16:19:49 +01:00
Hanno Becker
d91ede14c4 TinyCrypt ECDHE-PSK: Implement ClientKeyExchange writing 2019-09-04 16:19:49 +01:00
Hanno Becker
c7effc04c1 TinyCrypt SSL: Extend scope use of TC in CliKeyExchange writing
Extend scope of TC in ECDH-param extraction from CRT

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

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

Previously, TinyCrypt was only used for ECDHE-ECDSA/RSA ciphersuites.
This commit is a step towards using it for _all_ ciphersuites involving
ECDHE (specifically: ECDHE, ECDHE-PSK, static ECDH), extending the scope
of the use of TinyCrypt in the assembly of the PMS.
2019-09-04 16:19:49 +01:00
Hanno Becker
8b3408f1a8 TinyCrypt Test: Run ssl-opt.sh without restrictions
Previously, the TinyCrypt component in all.sh restricted the ssl-opt.sh
to the 'Default, DTLS' test, due to implicit dependencies on Secp384r1.
These dependencies are now explicit and ssl-opt.sh skips corresponding
tests accordingly, so we can introduce a full run of ssl-opt.sh into
the TinyCrypt test in all.sh.
2019-09-04 16:19:49 +01:00
Hanno Becker
69c6cde728 ssl-opt.sh: Detect use of CRTs using Secp384R1 and potentially skip
This commit modifies ssl-opt.sh to autodetect the use of test certificates
server5.* server6.* test-ca2.* using Secp384r1, and skips the corresponding
tests if MBEDTLS_ECP_DP_SECP384R1_ENABLED isn't set.
2019-09-04 16:19:49 +01:00
Hanno Becker
6b2b22164c depends-pkalgs.pl: Unset all EC curves when testing !MBEDTLS_ECP_C 2019-09-04 16:19:49 +01:00
Hanno Becker
325eb337bd TinyCrypt Test: Disable all legacy ECCs in TinyCrypt all.sh test 2019-09-04 16:19:49 +01:00
Hanno Becker
054deecb8a check_config.h: Add dep'n of ECC per-curve options on MBEDTLS_ECP_C 2019-09-04 16:19:49 +01:00
Hanno Becker
4873fde059 TinyCrypt Test: Expand scope of compatibility testing for TinyCrypt
Previously, the TinyCrypt all.sh test restricted the run of compat.sh
to DTLS 1.2 and listed a few explicit ciphersuites.

This commit widens the scope of the test by testing any ciphersuite
based on ECDHE-ECDSA, regardless of TLS/DTLS or the particular version.

Further, it doesn't exclude SHA-384 as done previously.
2019-09-04 16:19:49 +01:00
Hanno Becker
7c2cd3e9d3 TinyCrypt Test: Force use of Secp256r1 CRTs and Keys in all.sh test
This commit uses the flexibility of being able to chose CRTs and keys
to be used by compat.sh through predefined environment variables to
force the use of Secp256r1 certificates and keys in the all.sh test
for TinyCrypt.
2019-09-04 16:19:49 +01:00
Hanno Becker
70c7373f81 compat.sh: Introduce env variable for CRTs, CAs and keys
This commit introduces environment variables

- SRV_ECDSA_CRT
- SRV_ECDSA_KEY
- CLI_ECDSA_CRT
- CLI_ECDSA_KEY
- SRV_RSA_CRT
- SRV_RSA_KEY
- CLI_RSA_CRT
- CLI_RSA_KEY
- CA_FILE

to tests/compat.sh which hold the path of the CA, client and server
certificate and key files to use by the script.

This is a preparatory step towards switching to a different set of
certificates and keys in case the configuration doesn't match the
certificates in use so far (e.g.: the ECDSA certificates use Secp384r1,
so if that's disabled, ECDSA tests will fail).
2019-09-04 16:19:49 +01:00
Hanno Becker
2e80173dfc Fixup: Correct wrong comment ssl_prepare_server_key_exchange() 2019-09-04 16:19:49 +01:00
Hanno Becker
b251e01a0f Remove legacy ECC from baremetal.h 2019-09-04 16:19:49 +01:00
Hanno Becker
bd52604f9a Remove PK and CSR writing functionality from baremetal.h 2019-09-04 16:19:49 +01:00
Hanno Becker
61b05e572b Remove dependency of MBEDTLS_X509_USE_C on MBEDTLS_BIGNUM_C
There is no apparent direct dependency, and the indirect dependency
through the RSA and legacy ECP modules is already encoded in the
chain

   MBEDTLS_X509_USE_C
-> MBEDTLS_PK_PARSE_C
-> MBEDTLS_PK_C
-> MBEDTLS_RSA_C || MBEDTLS_ECP_C
-> MBEDTLS_BIGNUM_C

which will be modified to

   MBEDTLS_X509_USE_C
-> MBEDTLS_PK_PARSE_C
-> MBEDTLS_PK_C
-> MBEDTLS_RSA_C || MBEDTLS_ECP_C || MBEDTLS_USE_TINYCRYPT

in which case MBEDTLS_BIGNUM_C is not needed for MBEDTLS_X509_USE_C
if only MBEDTLS_USE_TINYCRYPT is set, but not MBEDTLS_RSA_C or
MBEDTLS_ECP_C.
2019-09-04 16:19:49 +01:00
Hanno Becker
d82f60da36 Directly include stdint.h from asn1.h
asn1.h uses uint8_t which is defined in stdint.h.

This wasn't caught earlier by the luck that whenever asn1.h
was included, another header was included earlier that did in
turn include stdint.h.
2019-09-04 16:19:49 +01:00
Hanno Becker
e8c52ff191 Guard CRT writing structure by MBEDTLS_X509_CRT_WRITE_C 2019-09-04 16:19:49 +01:00
Hanno Becker
6cf97b7fc6 Don't unconditionally include ecp.h in ssl.h
Remark: Including ecp.h is actually redundant because it's
also included from ecdh.h. However, it's good practice to
explicitly include header files that are being used directly,
and ssl.h does use MBEDTLS_ECP_MAX_BYTES which is defined in ecp.h.
2019-09-04 16:19:49 +01:00
Hanno Becker
728a38b40d TinyCrypt SSL: Adapt calculation of maximum PMS size in ssl.h
ssl.h contains a dummy union of fields each large enough to
hold the PMS for a particular ciphersuite. In particular, for
pure-ECDH ciphersuites, it contains a field large enough to
hold the ECDH shared secret in any of the enabled curves.

So far, this upper bound was unconditionally chosen to be
MBEDTLS_ECP_MAX_BYTES from the ECP module.

With the introduction of TinyCrypt as an alternative implementation
for ECDH, we need to
- guard the use of MBEDTLS_ECP_MAX_BYTES because MBEDTLS_ECP_C
  is no longer implied by the surrounding MBEDTLS_KEY_EXCHANGE_XXX
  guards
- add another field which contains the maximum length of shared
  ECDH secrets for curves supported by TinyCrypt.
2019-09-04 16:19:49 +01:00
Hanno Becker
27b7e50dcd TinyCrypt SSL: Declare EC-related TLS RFC constants in SSL namespace
mbedtls/ecp.h defines constants

   MBEDTLS_ECP_PF_UNCOMPRESSED
   MBEDTLS_ECP_PF_COMPRESSED
   MBEDTLS_ECP_TLS_NAMED_CURVE

which regard the encoding of elliptic curves and curve point formats in TLS.
As such, they should be defined in the SSL namespace. Asides, this will help
replacing the legacy ECC crypto by alternative ECC implementations.
2019-09-04 16:19:49 +01:00
Hanno Becker
ee902df678 TinyCrypt SSL: Implement mbedtls_ssl_check_curve() for TinyCrypt 2019-09-04 16:19:49 +01:00
Hanno Becker
7e9c2e0d81 TinyCrypt SSL: Adapt ssl_parse_certificate_verify() to TinyCrypt 2019-09-04 16:17:45 +01:00
Hanno Becker
461fa723a1 TinyCrypt SSL: Adapt ssl_check_key_curve() to TinyCrypt 2019-09-04 16:17:45 +01:00
Hanno Becker
59e7b08b8a TinyCrypt X.509: Adapt profiles to use TinyCrypt curve identifier 2019-09-04 16:17:45 +01:00
Hanno Becker
88889c618e Fixup: Add missing TinyCrypt guards 2019-09-04 16:17:45 +01:00
Hanno Becker
8239fad855 TinyCrypt Config: Don't set MBEDTLS_USE_TINYCRYPT in config.pl full 2019-09-04 16:17:45 +01:00
Hanno Becker
490277c8a2 TinyCrypt Config: Allow TC replacing legacy ECDSA in check_config.h 2019-09-04 16:17:45 +01:00
Hanno Becker
0e83f7252f TinyCrypt Test: Don't expect ECP error code
We want to be able to remove all legacy ECC entirely when using TinyCrypt.
In particular, we cannot rely on legacy ECC identifiers.
2019-09-04 16:17:45 +01:00
Hanno Becker
6e2fddec7e TinyCrypt Test: Disable det-ECDSA x509write test for TinyCrypt
TinyCrypt only implements non-deterministic ECDSA.
2019-09-04 16:17:45 +01:00
Hanno Becker
179c15f6b0 TinyCrypt Test: Add PK priv'key test for TinyCrypt-based Secp256r1
Even though exhaustive testing of TinyCrypt is left for later,
without this test we don't have any evidence that PK writing
works for TinyCrypt-based PK context.
2019-09-04 16:17:45 +01:00
Hanno Becker
3eb0ee23a0 TinyCrypt Test: Disable x509parse tests that don't apply to TC
TinyCrypt only supports Secp256r1, so skip all tests in test_suite_x509parse
which use different curves, while splitting those which rely on Secp256r1
alone into two tests: one for legacy ECC, and one for TinyCrypt.

Studying and improving the TinyCrypt test coverage is left for a later commit.
2019-09-04 16:17:45 +01:00
Hanno Becker
d931ad2aca Implement x509_profile_check_key() for TinyCrypt-based PK context 2019-09-04 16:17:45 +01:00
Hanno Becker
06e2bf6d01 TinyCrypt Test: Disable CRT print test in test_suite_debug if TC on 2019-09-04 16:17:45 +01:00
Hanno Becker
1521ec501c Remove TinyCrypt PRNG configuration from ssl_cli.c
The TinyCrypt PRNG is configured in mbedtls_ssl_setup().
2019-09-04 16:17:25 +01:00
Hanno Becker
fdd294a79f TinyCrypt Test: Skip pkwrite test cases that don't apply to TinyCrypt
The current pkwrite tests involving ECC all use curves different
from Secp256r1, so they don't apply to TinyCrypt.

Adding tests for TinyCrypt is left to a later commit.
2019-09-04 16:17:25 +01:00
Hanno Becker
d84dbe559f TinyCrypt Test: Adapt pub/prv ECC key parsing tests to TinyCrypt 2019-09-04 16:17:25 +01:00
Hanno Becker
dfb949bb4e Fixup: Use TC ECC type instead of uint32_t during pubkey parsing
Using explicit enumerated types avoids type confusion.
2019-09-04 16:17:25 +01:00
Hanno Becker
28332a5642 TinyCrypt PK write: Impl. PK writing helpers for TC-based PK context 2019-09-04 16:17:25 +01:00
Hanno Becker
64a81b03aa TinyCrypt PK write: Make PK writing helpers accept PK context
This prepares the ground for TinyCrypt-based implementations of
these helpers.
2019-09-04 16:17:25 +01:00
Hanno Becker
c64d5af9ab Fixup: Don't use legacy ECC error code from TinyCrypt
We want to be able to remove legacy ECC entirely when using TinyCrypt,
including their identifiers.
2019-09-04 16:17:25 +01:00
Hanno Becker
c10c9bfc10 TinyCrypt Test: Add guards to ECDSA verify tests from PK test suite
- The underlying test vectors are for Secp192r1, while TinyCrypt uses Secp256r1.
- The test implementation is specific to the structure of legacy-ECC PK ctxs.

Addition of analogous tests for TinyCrypt-based ECC PK contexts are left
for a later commit.
2019-09-04 16:17:25 +01:00
Hanno Becker
251d7523fe TinyCrypt Test: Adapt 'PK utils: ECKEY' test in PK test suite 2019-09-04 16:17:25 +01:00
Hanno Becker
da77971ec8 Fixup: Rename mbedtls_uecc_pk -> mbedtls_pk_uecc
This is in line with the naming of the analogous function mbedtls_pk_ec
used for legacy ECC PK contexts.
2019-09-04 16:17:25 +01:00
Hanno Becker
8cf2f5e466 TinyCrypt PK parse: Move TC-based EC public key parsing code-block
Keep code-paths handling legacy-ECC vs. TinyCrypt together
for better readability.
2019-09-04 16:17:25 +01:00
Hanno Becker
3bef643987 Fixup: Guard numerous legacy-ECC PK parse functions by !TinyCrypt 2019-09-04 16:17:25 +01:00
Hanno Becker
d336f721c0 Fixup: Add missing TinyCrypt guard in ECC private key parsing
PEM-encoded keys with PEM header

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

were previously not parsed in configurations using TinyCrypt
instead of legacy ECC crypto.
2019-09-04 16:17:25 +01:00
Hanno Becker
f2bf115057 TinyCrypt Test: Initialize TinyCrypt RNG in test suites if enabled 2019-09-04 16:17:25 +01:00
Hanno Becker
75f8d3276f TinyCrypt PK parse: Remove MBEDTLS_PK_ECDSA during pubkey parsing
The PK type MBEDTLS_PK_ECDSA is never returned from
`mbedtls_pk_info_from_type()`. Instead, EC keys either
are identified as MBEDTLS_PK_ECKEY_DH (in case they
must only be used for ECDHE) or MBEDTLS_PK_ECKEY (in
case they can be used for any algorithm).
2019-09-04 16:17:25 +01:00
Hanno Becker
e65697c351 TinyCrypt PK parse: Handle each PK type precisely once 2019-09-04 16:17:25 +01:00
Hanno Becker
d45f383b01 TinyCrypt PK parse: Impl. EC public key derivation in TC-based ECDSA 2019-09-04 16:17:25 +01:00
Hanno Becker
7e38c37302 TinyCrypt PK parse: Pass TC keypair structure to ECDSA pubkey parse 2019-09-04 16:17:25 +01:00
Hanno Becker
68d5478d8d TinyCrypt PK parse: Simplify TinyCrypt public key parsing 2019-09-04 16:17:25 +01:00
Hanno Becker
aebffdd363 TinyCrypt PK parse: Add comments to #endif's indicating condition 2019-09-04 16:17:25 +01:00
Hanno Becker
d7e0cd001c TinyCrypt PK wrap: Add short documentation for extract_ecdsa_sig_int 2019-09-04 16:17:25 +01:00
Hanno Becker
9653d80518 TinyCrypt PK wrap: Implement check_pair PK wrapper 2019-09-04 16:17:25 +01:00
Hanno Becker
4102972d31 TinyCrypt PK wrap: Implement alloc/free PK wrappers 2019-09-04 16:17:25 +01:00
Hanno Becker
11cb2637e7 TinyCrypt PK wrap: Simplify guards in pk_wrap.c
With TinyCrypt and legacy ECC mutually exclusive, we don't have
to use #if TINYCRYPT #else #if LEGACY #endif #endif anymore, but
can add the TC and legacy based ECC implementations independently.
2019-09-04 16:17:25 +01:00
Hanno Becker
b1074979b8 all.sh: Remove default + TinyCrypt test from all.sh
TinyCrypt and legacy ECC are mutually exclusive by now, and this
commit removes the all.sh test which exercises both simultaenously.
2019-09-04 16:17:25 +01:00
Hanno Becker
52c52f3c2f check_config: Forbid simultaenous use of TinyCrypt and legacy ECC 2019-09-04 16:17:25 +01:00
Hanno Becker
a417459ab1 Fixup: Remove trailing whitespace in oid.h 2019-09-04 16:17:25 +01:00
Hanno Becker
8ea35458e4 Fixup: TinyCrypt PK verify wrapper uecc_ecdsa_verify_wrap()
- TinyCrypt uses `0` for errors.
- The first argument to uECC_verify() should be the public key,
  but the previous code passed the beginning of the entire
  private-public key structure.
2019-09-04 16:17:25 +01:00
Hanno Becker
9c7a359cc4 Fixup: uecc_ecdsa_sign_wrap() in pk_wrap.c
The previous code passed `2 * NUM_ECC_BYTES` as the size limit for
the ECDSA signature, which fails to account for space required by
ASN.1 headers.
2019-09-04 16:17:25 +01:00
Hanno Becker
9a62f2dbfb Fixup: get_bitlen() PK API in TinyCrypt-based ECDSA
- Return number of bits and not number of bytes
- Return length of private key and not length of public key.
2019-09-04 16:17:25 +01:00
Hanno Becker
496b83ff1b Fixup: Correct include paths for TinyCrypt header files
TinyCrypt header files are expected in 'tinycrypt' folder
relative to the include path.
2019-09-04 16:17:25 +01:00
Hanno Becker
ad353f289b Fixup: Minor style corrections around use of TinyCrypt 2019-09-04 16:17:25 +01:00
Hanno Becker
e8f1448306 Fixup: Remove references to PSA from TinyCrypt wrapper code 2019-09-04 16:17:25 +01:00
Hanno Becker
adf11e13a4 Fixup: Impl. MBEDTLS_PK_ECKEY, not MBEDTLS_PK_ECDSA, via TinyCrypt
The PK-type MBEDTLS_PK_ECDSA isn't really used by the library.
Especially, when parsing a generic EC key, a PK context of type
MBEDTLS_PK_ECKEY will be requested. Hence, to drop in TinyCrypt
for the legacy-ECC implementation, the PK type that TinyCrypt
implements must be MBEDTLS_PK_ECKEY.
2019-09-04 16:17:25 +01:00
Hanno Becker
483fd66d21 Fixup: Don't reference legacy ECP curve identifier in check_config.h 2019-09-04 16:17:25 +01:00
Hanno Becker
49ac40b81b Fixup: Don't reference legacy ECP curve identifier in config.h
TinyCrypt should be used as a replacement of legacy ECC. In particular,
there shouldn't be any use of identifiers from the legacy ECC module.

So far, there's the configuration option

  MBEDTLS_SSL_CONF_SINGLE_EC_GRP_ID

that's relevant if MBEDTLS_SSL_CONF_SINGLE_CURVE is set, and which in
this case must resolve to an identifier of type mbedtls_ecp_group_id
indicating which single curve to enable.

With the introduction of TinyCrypt, we must either change the type
of this option to mbedtls_uecc_group_id, or introduce a separate
compilation option.

In order to avoid type confusion, this commit follows tha latter
approach, introducing the configuration option

  MBEDTLS_SSL_CONF_SINGLE_UECC_GRP_ID

that indicatesthe TinyCrypt group identifier of the single curve
to use (must be Secp256r1) if MBEDTLS_SSL_CONF_SINGLE_CURVE
and MBEDTLS_USE_TINYCRYPT are set.
2019-09-04 16:17:25 +01:00
Hanno Becker
8d49ba3b78 Fixup: Definition of TinyCrypt OID descriptor structure 2019-09-04 16:17:25 +01:00
Jarno Lamsa
7cb5c11067 Missing uECC ECDSA flagging 2019-09-04 16:17:25 +01:00
Jarno Lamsa
ad78931fb3 Signature wrapper for uECC 2019-09-04 16:17:25 +01:00
Jarno Lamsa
9c9e77a8ad Actually use the parse functions 2019-09-04 16:17:25 +01:00
Jarno Lamsa
b176092656 Parse private key in uecc format
Parse the private key from cert in uecc format.
Accept only P-256 curve.
2019-09-04 16:17:25 +01:00
Jarno Lamsa
42b83db1eb Verify sign wrapper functionality for uECC 2019-09-04 16:17:25 +01:00
Simon Butcher
e1c5608370 Merge remote-tracking branch 'origin/pr/650' into baremetal 2019-09-04 12:53:09 +01:00
Simon Butcher
42e4e723e8 Merge remote-tracking branch 'origin/pr/648' into baremetal 2019-09-04 12:42:35 +01:00
Simon Butcher
a5e29e31c8 Merge remote-tracking branch 'origin/pr/646' into baremetal 2019-09-04 12:41:05 +01:00
Simon Butcher
8afa0883af Merge remote-tracking branch 'origin/pr/641' into baremetal 2019-09-04 12:17:33 +01:00
Teppo Järvelin
ffaba55e5d Changed x509.c to be one single compilation unit for all x509 files. 2019-09-03 16:29:41 +03:00
Hanno Becker
2ccdab8ef3 Fixup alignment in ssl_server2 2019-09-03 09:01:49 +01:00
Hanno Becker
10da2a39be Fix unused variable warnings in ssl_client2/ssl_server2 2019-09-03 08:59:36 +01:00
Hanno Becker
801de73ad6 Remove CTR DRBG from baremetal test configuration 2019-09-03 08:59:36 +01:00
Hanno Becker
c973fdee72 all.sh: Add test exercising configurations without CTR DRBG 2019-09-03 08:59:05 +01:00
Hanno Becker
7f1c805b23 Allow ssl_client2/ssl_server2 to use HMAC DRBG instead of CTR DRBG
So far, ssl_client2 and ssl_server2 were relying on MBEDTLS_CTR_DRBG_C
being set. This commit adapts them to use HMAC DRBG in case CTR DRBG
is disabled in the configuration.

Note that disabling CTR DRBG in favor of HMAC DRBG can be useful on
constrained systems because Mbed TLS' HMAC DRBG is slightly smaller,
and moreover needed anyway as part of deterministic ECDSA.
2019-09-03 08:59:05 +01:00
Hanno Becker
df9633b21c Add missing dependency of RSA test on CTR DRBG 2019-09-03 08:59:05 +01:00
Manuel Pégourié-Gonnard
d6fba18328
Merge pull request #643 from hanno-arm/secp256r1-baremetal
[Baremetal] Add Secp256r1 test certificates
2019-09-02 08:49:20 +02:00
Hanno Becker
2e72dd8b9a ssl-opt.sh: Add var's of context s11n tests for ChaChaPoly,CCM,GCM
This commit splits each test in ssl-opt.sh related to context serialization
in three tests, exercising the use of CCM, GCM and ChaChaPoly separately.

The reason is that the choice of primitive affects the presence and size
of an explicit IV, and we should test that space for those IVs is correctly
restored during context deserialization; in fact, this was not the case
previously, as fixed in the last commit, and was not caught by the tests
because only ChaChaPoly was tested.
2019-08-30 13:27:16 +01:00
Hanno Becker
e80c1b07cb ssl-opt.sh: Duplicate context serialization tests for CID
This commit introduces a variant of each existing test for
context serialization in ssl-opt.sh that also uses the DTLS
Connection ID feature.
2019-08-30 13:27:16 +01:00
Hanno Becker
8398582658 Fix SSL context deserialization
The SSL context maintains a set of 'out pointers' indicating the
address at which to write the header fields of the next outgoing
record. Some of these addresses have a static offset from the
beginning of the record header, while other offsets can vary
depending on the active record encryption mechanism: For example,
if an explicit IV is in use, there's an offset between the end
of the record header and the beginning of the encrypted data to
allow the explicit IV to be placed in between; also, if the DTLS
Connection ID (CID) feature is in use, the CID is part of the
record header, shifting all subsequent information (length, IV, data)
to the back.
When setting up an SSL context, the out pointers are initialized
according to the identity transform + no CID, and it is important
to keep them up to date whenever the record encryption mechanism
changes, which is done by the helper function ssl_update_out_pointers().

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

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

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

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

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

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

This commit therefore removes checksum optimization altogether,
saving some code on constrained systems.
2019-08-29 16:01:31 +01:00
Hanno Becker
c2fb759f3b Remove TLS calc_finished function pointer from SSL handshake params 2019-08-29 16:01:31 +01:00
Hanno Becker
39c7f7e3de Remove TLS PRF function pointer from SSL handshake parameters 2019-08-29 16:01:30 +01:00
Manuel Pégourié-Gonnard
7228167843
Merge pull request #647 from hanno-arm/hmac_drbg_entropy_fix-baremetal
[Baremetal] Fix incompatibility between HMAC DRBG and entropy module
2019-08-28 09:20:38 +02:00
Manuel Pégourié-Gonnard
87f57f6df0
Merge pull request #642 from jarvte/mbedtls_ssl_set_hostname_to_optional
[baremetal] Make function mbedtls_ssl_set_hostname(...) as optional
2019-08-28 09:20:20 +02:00
Hanno Becker
4598e49916 Don't use P-256 test CRTs if P-256 is known to be disabled 2019-08-27 11:41:37 +01:00
Hanno Becker
31c95e1e94 Fix and improve documentation of HMAC DRBG
- a comment regarding the implementation of hmac_drbg_reseed_core()
  was misplaced.
- add more references to the standard, and add details on how the
  comments in the code refer to various parts of the standard.
2019-08-27 09:22:09 +01:00
Hanno Becker
b3a06e66d8 hmac_drbg.c: Rename hmac_drbg_reseed_internal->hmac_drbg_reseed_core 2019-08-27 09:21:44 +01:00
Teppo Järvelin
4009d8f377 Make function mbedtls_ssl_set_hostname(...) as optional
Now function mbedtls_ssl_set_hostname is compile-time configurable
in config.h with define MBEDTLS_X509_REMOVE_HOSTNAME_VERIFICATION.
This affects to many x509 API's. See config.h for details.
2019-08-27 10:47:08 +03:00
Hanno Becker
843f5bb06c ssl-opt.sh: Configure trusted CA explicitly
ssl_client2 and ssl_server2 either allow loading specific CRTs
and CAs from files, or to leave them unspecified, in which case
they're automatically picked from the test certificates.

The test certificates should be chosen in a way that when
not specifying any CRT or CA parameters, the automatically
chosen ones match - but if one of them is specified but not
the other, one should not expect tests to succeed.

With the recent switch to Secp256r1-based test certificates,
the default test certificates have changed, which breaks some
ssl-opt.sh tests which specify the server CRT explicitly but
not the client trusted CAs.

This commit fixes this by specifying the client's trusted CA
explicitly in accordance with the explicitly specified server CRT.
2019-08-27 06:39:11 +01:00
Hanno Becker
213ae2c7a8 Add ChangeLog entry 2019-08-26 15:45:33 +01:00
Hanno Becker
eab304caf5 HMAC DRBG: Split entropy-gathering requests to reduce request sizes
According to SP800-90A, the DRBG seeding process should use a nonce
of length `security_strength / 2` bits as part of the DRBG seed. It
further notes that this nonce may be drawn from the same source of
entropy that is used for the first `security_strength` bits of the
DRBG seed. The present HMAC DRBG implementation does that, requesting
`security_strength * 3 / 2` bits of entropy from the configured entropy
source in total to form the initial part of the DRBG seed.

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

This commit fixes this by splitting the seed entropy acquisition into
two calls, one requesting `security_strength` bits first, and another
one requesting `security_strength / 2` bits for the nonce.
2019-08-26 15:39:23 +01:00
Hanno Becker
75bc82702f Load raw certificate and key data from files to certs.c 2019-08-23 11:39:46 +01:00
Hanno Becker
ba7082cc43 Add prototypes for Secp256r1 test CRTs and keys to certs.c 2019-08-23 11:39:45 +01:00
Hanno Becker
e7124b557d Remove Secp384r1 from baremetal_test config
Previously, configs/baremetal_test.h added MBEDTLS_ECP_DP_SECP384R1_ENABLED
because we didn't have sufficient test certificates using Secp256r1. Now that
these test certificates have been added, we can successfully run
ssl_client2 and ssl_server2 with just Secp256r1 enabled.
2019-08-23 11:33:20 +01:00
Hanno Becker
4a4047c326 Add script to auto-generate certs.c
This commit adds the script scripts/generate_certs.sh which
parses library/certs.c and inserts certificate and key files
for any block of the form

   /* BEGIN FILE [string|binary] [variable|macro] NAME FILE */
   ...
   /* END FILE */

Here, the first argument string / binary indicates whether the
file should be inserted as a string or as a binary array. The
second argument indicates whether the resulting object should
be registered as a C variable or a macro.

This script allows to easily update certs.c in case any of the
test certificates from tests/data_files change, or new test
certificates / keys need to be added.
2019-08-23 11:33:20 +01:00
Hanno Becker
585dfc4f56 Add Secp256R1 test keys and CRTs 2019-08-23 11:33:20 +01:00
Hanno Becker
4efd089ed5 Add build instructions for CRTs and keys using P-256 2019-08-23 11:33:20 +01:00
Simon Butcher
6617a24056 Merge remote-tracking branch 'origin/pr/633' into baremetal 2019-08-21 13:46:18 +01:00
Simon Butcher
7d8a807daf Merge remote-tracking branch 'origin/pr/637' into baremetal 2019-08-21 13:46:07 +01:00
Simon Butcher
f0f01e1f0a Merge remote-tracking branch 'origin/pr/630' into baremetal 2019-08-14 16:53:38 +01:00
Simon Butcher
434ab19164 Merge remote-tracking branch 'origin/pr/629' into baremetal 2019-08-14 16:53:13 +01:00
Simon Butcher
0863b2a259 Merge remote-tracking branch 'origin/pr/612' into baremetal 2019-08-14 16:50:13 +01:00
Hanno Becker
a9d5c452f3 Remove mbedtls_ssl_transform::minlen 2019-08-13 15:04:39 +01:00
Hanno Becker
0f36e7bfa3 Explain why RNG ctx parameter is kept in MBEDTLS_SSL_CONF_RNG 2019-08-13 11:36:34 +01:00
Hanno Becker
665d698972 Fix typo in documentation of MBEDTLS_SSL_CONF_RNG in config.h 2019-08-13 11:36:29 +01:00
Jarno Lamsa
7ba6288c37 Add all.sh tests for testing tinycrypt
One test for running with MBEDTLS_ECDH_C on and one
for running MBEDTLS_ECDH_C off. Run ssl-opt.sh with Default, DTLS
and compatibility tests with TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA.
2019-08-13 13:01:13 +03:00
Hanno Becker
3a33679ab1 Fix style issue in ssl_internal.h 2019-08-12 18:01:48 +01:00
Jarno Lamsa
b4983468e1 Add documentation for MBEDTLS_USE_TINYCRYPT
Add documentation about requiring the usage of
a single EC and an external RNG-function.
2019-08-12 18:01:48 +01:00
Hanno Becker
19bf09ee92 Remove standalone tinyCrypt tests from all.sh
tinyCrypt is still tested in the baremetal tests since it
is enabled in baremetal.h. Tests for minimal modifictions
of the default / full config enabling tinyCrypt will be
added elsewhere.
2019-08-12 18:01:48 +01:00
Hanno Becker
b72fc6a648 Don't use const var in initialization of another const var
ARM Compiler doesn't like it.
2019-08-12 18:01:48 +01:00
Hanno Becker
8295ff0b04 tinyCrypt: Don't store public ECDH-share in handshake struct
Instead, write it to the message buffer directly.
2019-08-12 18:01:47 +01:00
Hanno Becker
b1626fb619 tinyCrypt: Remove check for Secp256r1 in SrvKeyExch writing
The use of tinyCrypt is restricted Secp256r1-only, and a check in
ssl_ciphersuite_is_match() ensures that an EC ciphersuite is chosen
only if the client advertised support for Secp256r1, too.
2019-08-12 18:01:47 +01:00
Hanno Becker
9175c21b72 tinyCrypt: Move key buffers to end of mbedtls_ssl_handshake_params
This saves considerable amount of code on Thumb due to single-instruction
load/stores for fields preceding these buffers.
2019-08-12 18:01:47 +01:00
Hanno Becker
af9ff4ab9d tinyCrypt: Enforce matching setting of MBEDTLS_SSL_CONF_SINGLE_EC
We support only Secp256r1 through tinyCrypt, so enforce this by requiring
that MBEDTLS_SSL_CONF_SINGLE_EC is set and fixes that curve.
2019-08-12 18:01:47 +01:00
Hanno Becker
9cf087d2e7 Use tinyCrypt only for ECDHE-RSA/ECDSA in SrvKeyExch writing
In a way inconsistent with the rest of the library restricting the
use of tinyCrypt to pure-ECDHE, the previous ServerKeyExchange writing
routine would use tinyCrypt also for ECDHE-PSK-based ciphersuites.
This commit fixes this.
2019-08-12 18:01:47 +01:00
Hanno Becker
cdce332d8c Remove MBEDTLS_ECDH_C from baremetal configuration
Baremetal uses the tinyCrypt implementation of ECDHE.
2019-08-12 18:01:47 +01:00
Hanno Becker
7a19633c99 tinyCrypt: Avoid unused var warning by marking vars as unused 2019-08-12 18:01:47 +01:00
Hanno Becker
29d165565c Add MBEDTLS_ECDH_C guards to ECDH code-paths using legacy ECDH
Previously, MBEDTLS_KEY_EXCHANGE_ECDH[E]_XXX_ENABLED would imply
that MBEDTLS_ECDH_C is set, but with the introduction of tinyCrypt
as an alternative ECDH implementation, this is no longer the case.
2019-08-12 18:01:40 +01:00
Hanno Becker
975b9ee3c8 Fix guards around use of legacy ECDH context
mbedtls_ssl_handshake_params::ecdh_ctx should only be guarded
by MBEDTLS_ECDH_C, not by MBEDTLS_ECDSA_C.
2019-08-12 17:05:38 +01:00
Hanno Becker
49dc8edd26 Don't require MBEDTLS_ECDH_C for ECDHA-{ECDSA|RSA}-based suites
The ECDHE key derivation in such suites is now also supported
through tinyCrypt, enabled via MBEDTLS_USE_TINYCRYPT.
2019-08-12 17:05:38 +01:00
Hanno Becker
00a9b6df77 tinyCrypt: Enforce global RNG
tinyCrypt uses a global RNG without context parameter while Mbed TLS in its
default configuration uses RNG+CTX bound to the SSL configuration.

This commit restricts the use of tinyCrypt to configurations that use a
global RNG function with NULL context by setting MBEDTLS_SSL_CONF_RNG in
the configuration. This allows to define a wrapper RNG to be used by
tinyCrypt which maps to this global hardcoded RNG.
2019-08-12 17:05:38 +01:00
Hanno Becker
621113fd3a tinyCrypt: Write client's key share 2019-08-12 17:05:38 +01:00
Hanno Becker
a3c2c1712c tinyCrypt: Share ECDH secret calculation code-path 2019-08-12 17:05:38 +01:00
Hanno Becker
75f12d1eb9 tinyCrypt: Add ServerKeyExchange parsing code 2019-08-12 17:05:38 +01:00
Hanno Becker
d849c7ca19 tinyCrypt: Hardcode ECDH parameter header
Saves a few bytes of code when tinyCrypt is used.
2019-08-12 17:05:38 +01:00
Hanno Becker
d089fad925 tinyCrypt: Adapt RNG wrapper to return 0 on failure 2019-08-12 17:05:38 +01:00
Hanno Becker
ef982d57bf tinyCrypt: Bind RNG wrapper to tinyCrypt in mbedtls_ssl_setup() 2019-08-12 17:05:38 +01:00
Hanno Becker
c6c0fe6c5f Add MBEDTLS_USE_TINYCRYPT to baremetal configuration 2019-08-12 17:05:38 +01:00
Jarno Lamsa
e12aafbdc7 tinyCrypt: Initial commit towards ECDHE support
This commit is a first step towards using uECC for ECDH
during TLS handshakes.
2019-08-12 17:05:38 +01:00
Hanno Becker
36ae758798 Include Mbed TLS config in tinycrypt compilation units 2019-08-12 17:05:38 +01:00
Hanno Becker
3328b1822a Move ssl_process_in_server_key_exchange to avoid func use-before-def 2019-08-12 17:05:03 +01:00
Hanno Becker
4e46709800 Document precoditions on some HS parsing/writing functions
Eventually, all HS parsing/writing functions should take an arbitrary buffer +
length pair as their argument, and return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL if
the provided buffer is too short. So far, we've only made a first step by
allowing to pass an arbitrary buffer, but don't yet add bounds checks
throughout. While deliberate for now, this must be clearly documented.
2019-08-12 17:05:03 +01:00
Hanno Becker
7d552fad65 Avoid collision of ssl_xxx_key_exchange_yyy() func names in cli/srv
This makes grepping the functions more difficult, and also leads to compilation failures
when trying to build the library from a single source file (which might be useful for
code-size reasons).
2019-08-12 17:05:03 +01:00
Hanno Becker
48e526b380 Document parameter precondition for ssl_rsa_generate_partial_pms() 2019-08-12 17:05:03 +01:00
Hanno Becker
aa49620f6e Minor documentation improvement to ssl_rsa_encrypt_partial_pms() 2019-08-12 17:05:03 +01:00
Hanno Becker
084694dd57 Fix copy-pasta in documentation for outgoing CliKeyExchange 2019-08-12 17:05:03 +01:00
Hanno Becker
44a29f4a6f Remove redundant use of local variable in CliKeyExch writing 2019-08-12 17:05:03 +01:00
Hanno Becker
ae22dd3820 Simplify logic of restartable ECDHE in CliKeyExch writing 2019-08-12 17:05:03 +01:00
Hanno Becker
2fc84cebf6 Remove unused restartable ECC state for SrvKeyExchange
Previously, ssl_ecrs_ske_start_processing was used to indicate that
the ServerKeyExchange has been fetched from the record layer, but
that parsing its ECDHE parameter component has been preempted by the
restartable ECP feature. On re-entry of ssl_parse_server_key_exchange()
in this state, the code would directly jump into the parsing routine.
However, the only non-reentrant code that's jumped over this way is
the record fetching routine mbedtls_ssl_parse_record(), which is now
made re-entrant by setting `ssl->keep_current_message = 1` in case of
pre-emption due to restartable ECC.

The ssl_ecrs_ske_start_processing state is therefore redundant and
can be removed, which is what this commit does.
2019-08-12 17:05:03 +01:00
Hanno Becker
91cf7693b9 Remove restartable ECP return code check from ECDH suite handling
mbedtls_ecdh_read_params() is not restartable.
2019-08-12 17:05:03 +01:00
Manuel Pégourié-Gonnard
fb02e96cf5 Fix indentation to a multiple of 4 spaces 2019-08-12 17:05:03 +01:00
Manuel Pégourié-Gonnard
8793fab635 Fix two typos in comments 2019-08-12 17:05:03 +01:00
Hanno Becker
587c1ae195 Make IAR happy by dummy-initializing an unused variable
IAR doesn't like `((void) var);` as a means to indicate an unused
variable if that variable hasn't been initialized before. Make it
happy by initializing the variable before.
2019-08-12 17:05:03 +01:00
Hanno Becker
7ba0a886bd Fix 'set but not used' ARM compiler warning 2019-08-12 17:05:03 +01:00
Hanno Becker
a855cb635d Avoid unused variable warning in ServerKeyExchange parsing
ssl_server_key_exchange_parse() is compiled even if there's no ciphersuite
enabled which uses it (for example, that's the case in RSA-only builds).
The rationale for that is to avoid cluttering the code with numerous
compile-time guards. A consequence, however, is the top of
ssl_server_key_exchange_parse() contains declarations for variables
which are never put to use, and rightfully leading to compiler warnings.

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

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

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

   `ssl_process_server_key_exchange()`,

splitting the processing into the following steps:

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

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

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

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

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

   `ssl_process_client_key_exchange()`,

splitting the processing into the following steps:

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

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

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

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

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

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

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

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

   `ssl_process_client_key_exchange()`,

splitting the processing into the following steps:

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

The subsequent commits will scatter the code from the previous
monolithic function ssl_write_client_key_exchange() among those
dedicated functions, commenting out each part of
ssl_write_client_key_exchange() that has already been dealt with.
This gradual progression is meant to ease reviewing. Once all
code has been moved and all changes explained,
ssl_write_client_key_exchange() will be removed.
2019-08-12 17:05:03 +01:00
Simon Butcher
88eda1a11c Merge remote-tracking branch 'origin/pr/636' into baremetal 2019-08-09 14:07:12 +01:00
Simon Butcher
7c1380d9d4 Merge remote-tracking branch 'origin/pr/619' into baremetal 2019-08-09 14:05:50 +01:00
Manuel Pégourié-Gonnard
f3a15b3de0 Fix possibly-lossy conversion warning from MSVC
ssl_tls.c(4876): warning C4267: '=': conversion from 'size_t' to 'uint8_t', possible loss of data
2019-08-02 10:17:15 +02:00
Manuel Pégourié-Gonnard
39581c7cf4 Merge branch 'mbedtls-2.16' into baremetal-2.16-20190801
* mbedtls-2.16:
  Fix parsing issue when int parameter is in base 16
  Refactor receive_uint32()
  Refactor get_byte function
  Make the script portable to both pythons
  Update the test encoding to support python3
  update the test script
  tests: Limit each log to 10 GiB
2019-08-01 11:05:18 +02:00
Manuel Pégourié-Gonnard
646a466ae2
Merge pull request #628 from hanno-arm/hardcoding_tests-baremetal
[Baremetal] Add all.sh tests for hardcoded SSL configuration options
2019-08-01 10:53:51 +02:00
Hanno Becker
8844055b0e Remove compression field from SSL session if compression disabled 2019-08-01 10:11:20 +02:00
Hanno Becker
ec01408389 Reintroduce length 0 check for records 2019-08-01 09:51:54 +02:00
Hanno Becker
8061c6e894 Don't use memcpy() for 2-byte copy operation
Manual copying is slightly shorter here.
2019-08-01 09:51:54 +02:00
Hanno Becker
7b5ba84624 Remove integer parsing macro
If this is introduced, it should be defined in a prominent place
and put to use throughout the library, but this is left for another
time.
2019-08-01 09:51:54 +02:00
Hanno Becker
618176126c Fix alignment in record header parsing routine 2019-08-01 09:51:54 +02:00
Hanno Becker
e03eb7bb64 Don't disallow 'record from another epoch' log msg in proxy ref test
It happens regularly in test runs that the server example application
shuts down a connection, goes into waiting mode for a new connection,
and then receives the encrypted ClosureAlert from the client. The only
reason why this does currently not trigger the 'record from another epoch'
message is that we handle ClientHello parsing outside of the main record
stack because we want to be able to detect SSLv2 ClientHellos. However,
this is likely to go away, and once it happens, we'll see the log message.
Further, when record checking is used, every record, including the mentioned
closure alert, is passed to the record checking API before being passed to
the rest of the stack, which leads to the log message being printed.

In summary, grepping for 'record from another epoch' is a fragile way
of checking whether a reordered message has arrived. A more reliable
way is to grep for 'Buffer record from epoch' which is printed when
a record from a future epoch is actually buffered, and 'ssl_buffer_message'
which is the function buffering a future handshake message.
2019-08-01 09:51:53 +02:00
Hanno Becker
c1c173cadf Make sure 'record from another epoch' is displayed for next epoch
The test 'DTLS proxy: delay ChangeCipherSpec' from ssl-opt.sh
relies on this.
2019-08-01 09:51:53 +02:00
Hanno Becker
5579c5399b Add x509_internal.h to cpp_dummy_build.cpp 2019-08-01 09:51:53 +02:00
Hanno Becker
03e2db6f35 Implement record checking API
This commit implements the record checking API

   mbedtls_ssl_check_record()

on top of the restructured incoming record stack.

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

  ssl_parse_record_header()
  mbedtls_ssl_decrypt_buf()

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

Note: This is an API break.
2019-08-01 09:51:53 +02:00
Hanno Becker
f903dc8354 Make mbedtls_ssl_in_hdr_len() CID-unaware
The function mbedtls_ssl_in_hdr_len() is supposed to return the length
of the record header of the current incoming record. With the advent
of the DTLS Connection ID, this length is only known at runtime and
hence so far needed to be derived from the internal in_iv pointer
pointing to the beginning of the payload of the current incooing
record.

By now, however, those uses of mbedtls_ssl_in_hdr_len() where the
presence of a CID would need to be detected have been removed
(specifically, ssl_parse_record_header() doesn't use it anymore
when checking that the current datagram is large enough to hold
the record header, including the CID), and it's sufficient to
statically return the default record header sizes of 5 / 13 Bytes
for TLS / DTLS.
2019-08-01 09:51:53 +02:00
Hanno Becker
05413d9041 Remove duplicate setting of ssl->in_msgtype and ssl->in_msglen 2019-08-01 09:51:53 +02:00
Hanno Becker
bd70c8e771 Move update of in_xxx fields in ssl_get_next_record()
ssl_get_next_record() updates the legacy in_xxx fields in two places,
once before record decryption and once after. Now that record decryption
doesn't use or affect the in_xxx fields anymore, setting up the these
legacy fields can entirely be moved to the end of ssl_get_next_record(),
which is what this comit does.

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

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

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

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

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

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

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

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

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

This must not be confused with the internal check that the record
length is small enough to make the record fit into the internal input
buffer; this is done in mbedtls_ssl_fetch_input().
2019-08-01 09:50:26 +02:00
Hanno Becker
408a2742b3 Remove redundant length-0 checks for incoming unprotected records 2019-08-01 09:50:26 +02:00
Hanno Becker
1c26845777 Remove redundant length check during record header parsing
The check is in terms of the internal input buffer length and is
hence likely to be originally intended to protect against overflow
of the input buffer when fetching data from the underlying
transport in mbedtls_ssl_fetch_input(). For locality of reasoning,
it's better to perform such a check close to where it's needed,
and in fact, mbedtls_ssl_fetch_input() _does_ contain an equivalent
bounds check, too, rendering the bounds check in question redundant.
2019-08-01 09:50:26 +02:00
Manuel Pégourié-Gonnard
6852e95c2a
Merge pull request #618 from hanno-arm/record_checking_api-baremetal
[Baremetal] Record checking: API, Documentation and Stubs
2019-07-30 17:11:46 +02:00
Manuel Pégourié-Gonnard
2b29a37c91 Fix compile bugs in examples with hardcoded I/O callbacks
These were found by `all.sh test_baremetal`, so no need for a new test.
2019-07-30 17:07:38 +02:00
Manuel Pégourié-Gonnard
f1358acdc7 Fix bug in MBEDTLS_X509_CRT_REMOVE_TIME
When looking for a parent, all candidates were considered time-invalid due to
the #ifdef incorrectly including the `parent_valid = 1` line.

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

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

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

This bug was found by `all.sh test_baremetal` - no need for a new test.
2019-07-30 16:56:58 +02:00
Manuel Pégourié-Gonnard
80eaddfc36 Clean generated *.su file and gitignore them 2019-07-30 16:56:58 +02:00
Manuel Pégourié-Gonnard
d64a2f72e6 Fix wrong ifdef in ssl_server2 & add test for it
This was found as a warning when running scripts/baremetal.sh --ram
--build-only manually, but it should have been found in a more automated way.
Adding -Werror so that future such issues will be caught by all.sh
(component_test_baremetal already invokes baremetal.sh --ram --build-only).
2019-07-30 16:56:43 +02:00
Manuel Pégourié-Gonnard
0d1db20490 Fix bug in skip_date() (MBEDTLS_X509_CRT_REMOVE_TIME)
Asserting `*p == end` right after setting `end = *p + len` will always fail
unless `len == 0`, which is never the case with properly-formed certificates.

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

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

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

This bug was found by `all.sh test_baremetal` - no need for a new test.
2019-07-30 16:56:25 +02:00
Hanno Becker
62daad3b9a all.sh: Adhere to convention that build_ prefixes build-only tests 2019-07-30 16:56:25 +02:00
Hanno Becker
93de2965d0 Fix rebase slip 2019-07-30 16:56:25 +02:00
Hanno Becker
b7769e4fc0 Remove wrong reference to ARMCC in all.sh test name 2019-07-30 16:56:25 +02:00
Hanno Becker
c4296a3bbb Modify all.sh test names to reflect use of ARMCC 2019-07-30 16:56:25 +02:00
Hanno Becker
28d2a88173 Fix indentation in three example programs 2019-07-30 16:56:25 +02:00
Hanno Becker
e7895aae2c Add all.sh test for baremetal.h runtime test 2019-07-30 16:56:25 +02:00
Hanno Becker
a1f3c521e7 Add --build-only option to baremetal.sh --ram
This option builds the library, tests and example programs
in a minimally modified baremetal.h configuration (modifications
from baremetal_test.h) but doesn't execute any tests.
2019-07-30 16:56:25 +02:00
Hanno Becker
fe1bd781de Add all.sh test for hardcoded elliptic curve 2019-07-30 16:56:25 +02:00
Hanno Becker
7cedd8bed2 Remove overly strict guard in ssl_server2
get_auth_mode() is needed for a change of authmode through SNI,
which is possible even if the original authmode is hardcoded.
2019-07-30 16:56:18 +02:00
Hanno Becker
6dd8e1c54d Add all.sh test for hardcoded miscellaneous SSL config options 2019-07-30 16:50:27 +02:00
Hanno Becker
41e5a6871d Example apps: Don't use runtime IO config API if CBs are hardcoded
Multiple example applications still use mbedtls_ssl_set_bio() even
if the I/O callbacks are hardcoded. This commit fixes this.
2019-07-30 16:50:27 +02:00
Hanno Becker
2a0cd5a031 Add all.sh test for hardcoded IO callbacks 2019-07-30 16:48:20 +02:00
Hanno Becker
9fb3f1eaf2 Add all.sh test for hardcoded SSL version 2019-07-30 16:48:20 +02:00
Hanno Becker
32bbe4a66b Remove unused label in ssl_client2/ssl_server2 2019-07-30 16:33:40 +03:00
Hanno Becker
e29dfb2157 Add missing word in documentation of mbedtls_ssl_check_record() 2019-07-30 16:33:40 +03:00
Hanno Becker
83b8c3b8eb cli/srv ex: Add dbg msg if record checking gives inconsistent result 2019-07-30 16:33:40 +03:00
Hanno Becker
c2b08d1251 Fix minor issues in documentation of mbedtls_ssl_check_record() 2019-07-30 16:33:40 +03:00
Hanno Becker
bec8885b7d State that record checking is DTLS only and doesn't check content type 2019-07-30 16:33:40 +03:00
Hanno Becker
82ff6f1e17 Update version_features.c 2019-07-30 16:33:40 +03:00
Hanno Becker
de9e36e6b3 Pass dgrams to mbedtls_ssl_check_record in ssl_client2/server2 2019-07-30 16:33:40 +03:00
Hanno Becker
fe24b3b269 Add IO wrappers to ssl_server2 as interm's between NET and SSL layer 2019-07-30 16:33:40 +03:00
Hanno Becker
14219feb27 Add IO wrappers to ssl_client2 as interm's between NET and SSL layer 2019-07-30 15:44:43 +03:00
Hanno Becker
02f2609551 Introduce configuration option and API for SSL record checking 2019-07-30 15:38:40 +03:00
Manuel Pégourié-Gonnard
f010eba833
Merge pull request #632 from hanno-arm/baremetal_sh_debug-baremetal
[Baremetal] Add `--debug` option to `baremetal.sh`
2019-07-30 00:07:45 +02:00
Manuel Pégourié-Gonnard
cdb83e7c88
Merge pull request #616 from mpg/context-s11n
[baremetal] Implement context serialization
2019-07-30 00:07:23 +02:00
Manuel Pégourié-Gonnard
69a3e417d8 Improve reability and debugability of large if
Breaking into a series of statements makes things easier when stepping through
the code in a debugger.

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

Also expand a bit on the reasons for these restrictions.
2019-07-29 12:32:02 +02:00
Manuel Pégourié-Gonnard
18332c5c6c Improve getter for renegotiation enabled 2019-07-29 12:17:52 +02:00
Manuel Pégourié-Gonnard
d04850507d
Merge pull request #634 from hanno-arm/single_ec_doc-baremetal
[Baremetal] Fix single-EC documentation
2019-07-29 11:59:12 +02:00
Manuel Pégourié-Gonnard
7c575d29dc
Merge pull request #605 from ARMmbed/x509_ondemand_remove_unneeded_fields
[Baremetal] Allow removal of unneeded fields in X.509 CRT structures
2019-07-29 11:58:58 +02:00
Manuel Pégourié-Gonnard
7d33b7e2b9
Merge pull request #610 from ARMmbed/delay_alerts-baremetal
[Baremetal] Delay sending alerts
2019-07-29 11:58:44 +02:00
Manuel Pégourié-Gonnard
b3bb31bd90 Introduce getter function for disable_renego 2019-07-26 16:37:45 +02:00
Manuel Pégourié-Gonnard
14e2a8ac06 Fix a typo in a comment 2019-07-26 16:31:53 +02:00
Hanno Becker
fcb721d733 Correct documentation on use of alert pending 2019-07-26 12:47:16 +01:00
Hanno Becker
dd69119b32
Update include/mbedtls/ssl_internal.h
Mention where an internal function is defined instead of just saying that it's internal.

Co-Authored-By: Gilles Peskine <gilles.peskine@arm.com>
2019-07-26 09:59:18 +01:00
Hanno Becker
2736d1983c Fix and improve documentation of MBEDTLS_SSL_CONF_SINGLE_EC 2019-07-26 07:53:39 +01:00
Hanno Becker
42a6b04c4a Don't forget about pending alerts after ssl_get_next_record()
ssl_get_next_record() may pend fatal alerts in response to receiving
invalid records. Previously, however, those were never actually sent
because there was no code-path checking for pending alerts.

This commit adds a call to ssl_send_pending_fatal_alert() after
the invocation of ssl_get_next_record() to fix this.
2019-07-26 07:25:20 +01:00
Hanno Becker
b82350b25f Introduce helper function to send pending fatal alerts 2019-07-26 07:25:02 +01:00
Hanno Becker
0a4c78f7c2 Add --debug option to baremetal.sh 2019-07-25 15:49:17 +01:00
Hanno Becker
50d53212ef Document mbedtls_ssl_context::pending_fatal_alert_msg 2019-07-25 12:59:24 +01:00
Hanno Becker
c8f529995f Rename pend_alert_msg -> pending_fatal_alert_msg 2019-07-25 12:59:24 +01:00
Hanno Becker
d829d0fbd0 Remove return value from mbedtls_ssl_pend_fatal_alert()
This function is often called when there's already an error code to handle,
and one of the reasons to introduce the pending of alerts was to _not_ have
another potential error code to take care of. Reflect this by making `void`
the return type of `mbedtls_ssl_pend_fatal_alert()`.
2019-07-25 12:59:24 +01:00
Hanno Becker
eeabfa460c Note that mbedtls_ssl_pend_fatal_alert() must only be called once 2019-07-25 12:59:17 +01:00
Hanno Becker
2e8d133ebf Reintroduce return code checking when sending NoRenego alert 2019-07-25 12:58:48 +01:00
Hanno Becker
3caf7189f9 Remove field to store level of pending alert
Pending alerts is so far only used for fatal alerts.
2019-07-25 12:58:44 +01:00
Hanno Becker
de62da9d3c Use separate functions to pend fatal and non-fatal alerts 2019-07-24 13:45:35 +01:00
Hanno Becker
1f5a793124 Use attribute always_inline only for GCC and ARM compiler 2019-07-24 13:20:42 +01:00
Hanno Becker
1facd552fc Replace xxx_send_alert by xxx_pend_alert to save code 2019-07-24 13:20:27 +01:00
Hanno Becker
f46e1ce812 Introduce SSL helper function to mark pending alerts 2019-07-24 13:20:27 +01:00
Manuel Pégourié-Gonnard
7af7375473 Fix MSVC warning
We know the length of the ALPN string is always less than 255, so the cast to
uint8_t is safe.
2019-07-24 00:58:27 +02:00
Manuel Pégourié-Gonnard
2cc9223a3b Fix compile error in reduced configurations
Found by running scripts/baremetal.h --rom --gcc --check after adding
MBEDTLS_SSL_CONTEXT_SERIALIZATION to baremetal.h
2019-07-23 17:22:39 +02:00
Simon Butcher
3b014fc23a Merge remote-tracking branch 'origin/pr/604' into baremetal 2019-07-23 16:16:24 +01:00
Simon Butcher
6fe6b437da Merge remote-tracking branch 'origin/pr/589' into baremetal 2019-07-23 16:10:56 +01:00
Simon Butcher
c0b3633194 Merge remote-tracking branch 'origin/pr/627' into baremetal 2019-07-23 16:06:07 +01:00
Simon Butcher
25b5579a09 Merge remote-tracking branch 'origin/pr/626' into baremetal 2019-07-23 16:03:21 +01:00
Manuel Pégourié-Gonnard
7ce9446e4c Avoid duplication of session format header 2019-07-23 17:02:11 +02:00
Manuel Pégourié-Gonnard
a7cd4830ee Implement config-checking header to context s11n
Modelled after the config-checking header from session s11n.

The list of relevant config flags was established by manually checking the
fields serialized in the format, and which config.h flags they depend on.
This probably deserves double-checking by reviewers.
2019-07-23 17:02:10 +02:00
Manuel Pégourié-Gonnard
4c1d06e429 Provide serialisation API only if it's enabled 2019-07-23 17:02:10 +02:00
Manuel Pégourié-Gonnard
73a4636ca4 Adapt to hardcoded single version 2019-07-23 17:02:10 +02:00
Manuel Pégourié-Gonnard
2f3fa62a0a Fix compiler warning: comparing signed to unsigned
Since the type of cid_len is unsigned but shorter than int, it gets
"promoted" to int (which is also the type of the result), unless we make the
other operand an unsigned int which then forces the expression to unsigned int
as well.
2019-07-23 17:02:10 +02:00
Manuel Pégourié-Gonnard
bc847caa33 Actually reset the context on save as advertised
Also fix some wording in the documentation while at it.
2019-07-23 17:02:10 +02:00
Manuel Pégourié-Gonnard
ff22200fab Re-use buffer allocated by handshake_init()
This fixes a memory leak as well (found by running ssl-opt.sh in an Asan
build).
2019-07-23 17:02:10 +02:00
Manuel Pégourié-Gonnard
0d83271a45 Enable serialisation tests in ssl-opt.sh
They currently pass in a default build.
2019-07-23 17:02:10 +02:00
Manuel Pégourié-Gonnard
86dfa0cfc9 Change requirements for setting timer callback
The code wants timer callbacks to be set (checked in fetch_input()), and can't
easily check whether we're using nbio, so it seems easier to require the
callbacks to be always set rather than only with nbio as was previously done.
2019-07-23 17:02:10 +02:00
Manuel Pégourié-Gonnard
138079d7d6 Add setting of forced fields when deserializing 2019-07-23 17:02:10 +02:00
Manuel Pégourié-Gonnard
16d1485a3d Add saved fields from top-level structure 2019-07-23 17:02:10 +02:00
Manuel Pégourié-Gonnard
c981229b04 Fix memory leak in client/server2
context_buf was never free()d. Moreover, since we want to free it on error
paths as well, and even properly zeroize it in order to demonstrate good
memory hygiene, we need to make it and its length main()-scoped.
2019-07-23 17:02:10 +02:00
Manuel Pégourié-Gonnard
322f3c7377 Add transform (de)serialization 2019-07-23 17:02:10 +02:00
Manuel Pégourié-Gonnard
8175816200 Fix English in comments 2019-07-23 17:02:10 +02:00
Manuel Pégourié-Gonnard
3b23c7d2d2 Improve demo/testing code in client/server2
Previously it was missing reset in case 1, and in case 2 the code was never
executed as the option value was reset to 0.

Tighten checking of return values of save(NULL, 0) now that it works.

Also, improve the printed output as well as the comments.

I checked manually that everything now works and fail in the expected way:
save, reset-or-reinit and load all succeed, but the subsequent read or write
fails.
2019-07-23 17:02:10 +02:00
Manuel Pégourié-Gonnard
f1f3e529a5 Add session saving/loading
For now, the header (version+format bytes) is duplicated. This might be
optimized later.
2019-07-23 17:02:09 +02:00
Manuel Pégourié-Gonnard
d0dd10469b 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-07-23 17:02:09 +02:00
Manuel Pégourié-Gonnard
5e534baaec Add usage checks in context_load() 2019-07-23 17:02:09 +02:00
Manuel Pégourié-Gonnard
b6163ef175 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-07-23 17:02:09 +02:00
Manuel Pégourié-Gonnard
569ed6ba56 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-07-23 17:02:09 +02:00
Manuel Pégourié-Gonnard
a3024eef7b Save Hello random bytes for later use 2019-07-23 17:02:09 +02:00
Hanno Becker
f28ce6e40e Fix typo in config.h 2019-07-22 13:12:47 +01:00
Hanno Becker
95d1b93c69 Don't reset timer during mbedtls_ssl_setup()
At that point, the timer might not yet be configured.

The timer is reset at the following occasions:

- when it is initially configured through
    mbedtls_ssl_set_timer_cb() or
    mbedtls_ssl_set_timer_cb_cx()
- when a session is reset in mbedtls_ssl_session_reset()
- when a handshake finishes via mbedtls_ssl_handshake_wrap()
2019-07-22 11:15:28 +01:00
Hanno Becker
ffb45b9ea5 Add test for hardcoded timer callbacks to all.sh 2019-07-22 11:15:28 +01:00
Hanno Becker
af5d8abf26 Don't call memset on NULL pointer in NIST KW test suite
Note: There's no need to call `memset()` after `calloc()`
because `calloc()` includes zeroization.
2019-07-22 11:15:12 +01:00
Hanno Becker
981f81dc30 Add missing uses of mbedtls_ssl_get_minor() 2019-07-19 16:12:54 +01:00
Hanno Becker
ce8bdf82a1 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:56:09 +01:00
Hanno Becker
3c3c42b1f4 Update query_config.c 2019-07-18 13:55:16 +01:00
Manuel Pégourié-Gonnard
100c057d0d Make SHA256_SMALLER option yield even smaller code 2019-07-17 12:15:05 +02:00
Hanno Becker
56595f4f7b Allow hardcoding single signature hash at compile-time
This commit introduces the option MBEDTLS_SSL_CONF_SINGLE_HASH
which can be used to register a single supported signature hash
algorithm at compile time. It replaces the runtime configuration
API mbedtls_ssl_conf_sig_hashes() which allows to register a _list_
of supported signature hash algorithms.

In contrast to other options used to hardcode configuration options,
MBEDTLS_SSL_CONF_SINGLE_HASH isn't a numeric option, but instead it's
only relevant if it's defined or not. To actually set the single
supported hash algorithm that should be supported, numeric options

MBEDTLS_SSL_CONF_SINGLE_HASH_TLS_ID
MBEDTLS_SSL_CONF_SINGLE_HASH_MD_ID

must both be defined and provide the TLS ID and the Mbed TLS internal
ID and the chosen hash algorithm, respectively.
2019-07-17 10:19:27 +01:00
Hanno Becker
f1bc9e1c69 Introduce helper functions to traverse signature hashes 2019-07-17 10:19:27 +01:00
Hanno Becker
0af717b520 Don't use mbedtls_ssL_set_calc_verify_md writing CertificateRequest
mbedtls_ssl_set_calc_verify_md() serves two purposes:
(a) It checks whether a hash algorithm is suitable to be used
    in the CertificateVerify message.
(b) It updates the function callback pointing to the function that
    computes handshake transcript for the CertificateVerify message
    w.r.t. the chosen hash function.

Step (b) is only necessary when receiving the CertificateVerify
message, while writing the CertificateRequest only involves (a).

This commit modifies the writing code for the CertificateRequest
message to inline the check (a) and thereby avoiding the call to
mbedtls_ssl_calc_verify_md().
2019-07-17 10:19:27 +01:00
Hanno Becker
627fbee41a Don't offer SHA-1 in CertificateRequest message in TLS 1.2
mbedtls_ssL_set_calc_verify_md() is used to select valid hashes when
writing the server's CertificateRequest message, as well as to verify
and act on the client's choice when reading its CertificateVerify
message.

If enabled at compile-time and configured via mbedtls_ssl_conf_sig_hashes()
the current code also offers SHA-1 in TLS 1.2. However, the SHA-1-based
handshake transcript in TLS 1.2 is different from the SHA-1 handshake
transcript used in TLS < 1.2, and we only maintain the latter
(through ssl_update_checksum_md5sha1()), but not the former.
Concretely, this will lead to CertificateVerify verification failure
if the client picks SHA-1 for the CertificateVerify message in a TLS 1.2
handshake.

This commit removes SHA-1 from the list of supported hashes in
the CertificateRequest message, and adapts two tests in ssl-opt.sh
which expect SHA-1 to be listed in the CertificateRequest message.
2019-07-17 10:19:27 +01:00
Hanno Becker
0a6417041e Remove redundant check in mbedtls_ssl_set_calc_verify_md()
mbedtls_ssl_set_calc_verify_md() is only called from places
where it has been checked that TLS 1.2 is being used. The
corresponding compile-time and runtime guards checking the
version in mbedtls_ssl_set_calc_verify_md() are therefore
redundant and can be removed.
2019-07-17 10:19:25 +01:00
Simon Butcher
ae3f8511fd Merge remote-tracking branch 'origin/pr/615' into baremetal 2019-07-15 19:24:44 +01:00
Simon Butcher
feb1cee36e Merge remote-tracking branch 'origin/pr/602' into baremetal 2019-07-15 19:24:11 +01:00
Simon Butcher
5f7436f757 Merge remote-tracking branch 'origin/pr/593' into baremetal 2019-07-15 19:23:54 +01:00
Hanno Becker
7ae3026d5d [Fixup] Minor changes addressing review feedback 2019-07-12 15:25:03 +01:00
Hanno Becker
7decea9ea9 Simplify supported EC extension writing code
The previous code writes the content (the EC curve list) of the extension
before writing the extension length field at the beginning, which is common
in the library in places where we don't know the length upfront. Here,
however, we do traverse the EC curve list upfront to infer its length
and do the bounds check, so we can reorder the code to write the extension
linearly and hence improve readability.
2019-07-12 15:25:03 +01:00
Hanno Becker
c1096e7514 Allow hardcoding single supported elliptic curve
This commit introduces the option MBEDTLS_SSL_CONF_SINGLE_EC
which can be used to register a single supported elliptic curve
at compile time. It replaces the runtime configuration API
mbedtls_ssl_conf_curves() which allows to register a _list_
of supported elliptic curves.

In contrast to other options used to hardcode configuration options,
MBEDTLS_SSL_CONF_SINGLE_EC isn't a numeric option, but instead it's
only relevant if it's defined or not. To actually set the single
elliptic curve that should be supported, numeric options

MBEDTLS_SSL_CONF_SINGLE_EC_TLS_ID
MBEDTLS_SSL_CONF_SINGLE_EC_GRP_ID

must both be defined and provide the TLS ID and the Mbed TLS internal
ID and the chosen curve, respectively.
2019-07-12 15:25:03 +01:00
Hanno Becker
ee24f8cecb Remove unnecessary check for presence of supported EC list
For both client/server the EC curve list is assumed not to be NULL:

- On the client-side, it's assumed when writing the
  supported elliptic curve extension:

    c54ee936d7/library/ssl_cli.c (L316)

- On the server, it is assumed when searching for a
  suitable curve for the ECDHE exchange:

    c54ee936d7/library/ssl_srv.c (L3200)

It is therefore not necessary to check this in mbedtls_ssl_check_curve().
2019-07-12 15:25:03 +01:00
Hanno Becker
a4a9c696c1 Introduce helper macro for traversal of supported EC TLS IDs 2019-07-12 15:25:03 +01:00
Hanno Becker
80855881ec Remove unnecessary guards in client-side EC curve extension writing
ssl_write_supported_elliptic_curves_ext() is guarded by

```
    #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
       defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
```

each of which implies (by check_config.h) that MBEDTLS_ECP_C
is enabled.
2019-07-12 15:25:03 +01:00
Hanno Becker
84fb902ea5 Work on client-provided supported EC TLS ID list in-place 2019-07-12 15:25:01 +01:00
Hanno Becker
004619fa25 Store TLS curve ID instead of information structure
This will reduce the number of grp ID <-> tls ID <-> curve info structs
conversions once a single EC can be hardcoded through its TLS ID.
2019-07-12 15:19:43 +01:00
Hanno Becker
90f7b75354 Fix unused variable warning in SSL test suite 2019-07-12 15:15:08 +01:00
Hanno Becker
ac8c984784 SSL tests: Skip tests using version not matching hardcoded version 2019-07-12 15:15:08 +01:00
Hanno Becker
930fbf60d6 Add TEST_ASSUME macro to allow skipping tests at runtime
This commit adds a macro TEST_ASSUME to the test infrastructure
which allows to skip tests based on unmet conditions determined
at runtime.
2019-07-12 15:15:08 +01:00
Hanno Becker
d82a03084f ssl-opt.sh: Detect mismatching cmd line and hardcoded version config 2019-07-12 15:15:08 +01:00
Hanno Becker
72e5ffc9d6 Remove ver cfg in ssl_client2/ssl_server2 if ver hardcoded 2019-07-12 15:15:08 +01:00
Hanno Becker
33b9b25a48 Remove SSL version configuration API if versions are hardcoded 2019-07-12 15:15:08 +01:00
Hanno Becker
cb8774b6e8 Enforce that all SSL version bounds must be hardcoded simultaneously 2019-07-12 15:15:08 +01:00
Hanno Becker
94c40d17f7 [Fixup] Fix typos in documentation of min/max version macros 2019-07-12 15:15:08 +01:00
Hanno Becker
0a92b8156d Remove mbedtls_ssl_transform::minor_ver if the version is hardcoded 2019-07-12 15:15:08 +01:00
Hanno Becker
0f902b71a8 Add new compile-time options to programs/ssl/query_config.c 2019-07-12 15:15:07 +01:00
Hanno Becker
f1c2a33189 Note in SSL doc'n that version bounds can be set at compile-time 2019-07-12 15:15:07 +01:00
Hanno Becker
18729aeaac Guard RSA-only max_major/minor_ver fields from SSL handshake params
The fields
- mbedtls_ssl_handshake_params::max_major_ver,
- mbedtls_ssl_handshake_params::max_minor_ver
are used only for server-side RSA-based key exchanges
can be removed otherwise.
2019-07-12 15:15:07 +01:00
Hanno Becker
7b628e5b88 Make mbedtls_ssl_read/write_version static inline
Reasons:
- If the transport type is fixed at compile-time,
  mbedtls_ssl_read_version() and mbedtls_ssl_write_version()
  are called with a compile-time determined `transport`
  parameter, so the transport-type branch in their body
  can be eliminated at compile-time.
- mbedtls_ssl_read_version() is called with addresses of
  local variables, which so far need to be put on the stack
  to be addressable. Inlining the call allows to read directly
  into the registers holding these local variables.

This saves 60 bytes w.r.t. the measurement performed by

> ./scripts/baremetal.sh --rom --gcc
2019-07-12 15:15:07 +01:00
Hanno Becker
381eaa5976 Remove min/maj version from SSL context if only one version enabled
If the minor/major version is enforced at compile-time, the `major_ver`
and `minor_ver` fields in `mbedtls_ssl_context` are redundant and can
be removed.
2019-07-12 15:15:07 +01:00
Hanno Becker
2881d80138 Introduce getter function for max/min SSL version
This is a first step towards hardcoding ssl->{major|minor}_ver
in configurations which accept only a single version.
2019-07-12 15:15:06 +01:00
Hanno Becker
3fa1ee567c Set SSL minor version only after validation 2019-07-12 15:14:53 +01:00
Hanno Becker
e965bd397e Allow hardcoding of min/max minor/major SSL version at compile-time
This commit introduces the numeric compile-time constants

- MBEDTLS_SSL_CONF_MIN_MINOR_VER
- MBEDTLS_SSL_CONF_MAX_MINOR_VER
- MBEDTLS_SSL_CONF_MIN_MAJOR_VER
- MBEDTLS_SSL_CONF_MAX_MAJOR_VER

which, when defined, overwrite the runtime configurable fields
mbedtls_ssl_config::min_major_ver etc. in the SSL configuration.

As for the preceding case of the ExtendedMasterSecret configuration,
it also introduces and puts to use getter functions for these variables
which evaluate to either a field access or the macro value, maintaining
readability of the code.

The runtime configuration API mbedtls_ssl_conf_{min|max}_version()
is kept for now but has no effect if MBEDTLS_SSL_CONF_XXX are set.
This is likely to be changed in a later commit but deliberately omitted
for now, in order to be able to study code-size benefits earlier in the
process.
2019-07-12 15:14:51 +01:00
Simon Butcher
fabfb8578a Merge remote-tracking branch 'origin/pr/603' into baremetal 2019-07-10 15:40:32 +01:00
Simon Butcher
92bb0e954b Merge remote-tracking branch 'origin/pr/606' into baremetal 2019-07-10 15:40:09 +01:00
Simon Butcher
133294eb4a Merge remote-tracking branch 'origin/mbedtls-2.16' into baremetal 2019-07-10 11:38:01 +01:00
Hanno Becker
14a4a44e60 Remove mbedtls_ssl_conf_dbg() if !MBEDTLS_DEBUG_C 2019-07-08 11:32:50 +01:00
Hanno Becker
272063abfd Don't store debug func ptr cb + ctx in SSL config if !DEBUG_C
Note: This is an structure-API breaking change that we might
      not be able to upstream.
2019-07-08 11:32:10 +01:00
Hanno Becker
9e720e07e1 Add note that def'n of MBEDTLS_SUITE_XXX is just for check-names.sh 2019-07-08 11:24:36 +01:00
Hanno Becker
779d79dcd7 Restore static inline qualif'n of some helpers in ssl_ciphersuites.h 2019-07-08 11:23:25 +01:00
Hanno Becker
efe1327fef Add test to all.sh exercising hardcoded ciphersuite 2019-07-08 11:23:25 +01:00
Hanno Becker
91900362f5 Modify default test in ssl-opt.sh to not expect particular primitive 2019-07-08 11:23:25 +01:00
Hanno Becker
e4b355a1ed Remove redundant hardcoded ciphersuite identifier 2019-07-08 11:23:25 +01:00
Hanno Becker
870bcd3a6e Highlight precondition of ciphersuite getter functions 2019-07-08 11:23:25 +01:00
Hanno Becker
a1552ac37c Use "unknown" instead of NULL as name of unknown ciphersuite 2019-07-08 11:23:25 +01:00
Hanno Becker
9b3ec12863 Add missing spaces at the end of comments 2019-07-08 11:23:24 +01:00
Hanno Becker
f4d6b49352 Allow use of continue in single-ciphersuite 'loops' 2019-07-08 11:23:24 +01:00
Hanno Becker
c5db66af2f Update query_config.c 2019-07-08 11:23:24 +01:00
Hanno Becker
d89e8cb427 Don't break comment lines prematurely in ssl_ciphersuites.h 2019-07-08 11:23:24 +01:00
Hanno Becker
67fb16e59d Make ciphersuite helpers static inline if only one suite enabled
This commit restructures ssl_ciphersuites.h and ssl_ciphersuites.c to
define all ciphersuite helper functions static inline in ssl_ciphersuites.h
if MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE is set, and to otherwise put their
definitions in ssl_ciphersuites.c.
2019-07-08 11:23:24 +01:00
Hanno Becker
73f4cb126d Rename XXX_SINGLE_CIPHERSUITE -> XXX_CONF_SINGLE_CIPHERSUITE
This is in line with the other configurations options used
to hardcoded aspects of the SSL configuration.
2019-07-08 11:23:24 +01:00
Hanno Becker
e02758c9c8 Remove ciphersuite from SSL session if single suite hardcoded
If MBEDTLS_SSL_SINGLE_CIPHERSUITE is enabled, the type

  mbedtls_ssl_ciphersuite_handle_t

is logically a boolean (concretely realized as `unsigned char`),
containing the invalid handle and the unique valid handle, which
represents the single enabled ciphersuite.

The SSL session structure mbedtls_ssl_session contains an instance
of mbedtls_ssl_ciphersuite_handle_t which is guaranteed to be valid,
and which is hence redundant in any two-valued implementation of
mbedtls_ssl_ciphersuite_handle_t.

This commit replaces read-uses of

  mbedtls_ssl_session::ciphersuite_info

by a getter functions which, and defines this getter function
either by just reading the field from the session structure
(in case MBEDTLS_SSL_SINGLE_CIPHERSUITE is disabled), or by
returning the single valid ciphersuite handle (in case
MBEDTLS_SSL_SINGLE_CIPHERSUITE is enabled) and removing the
field from mbedtls_ssl_session in this case.
2019-07-08 11:23:24 +01:00
Hanno Becker
6ace4657b6 Remove ciphersuite from SSL config if single suite hardcoded
If MBEDTLS_SSL_SINGLE_CIPHERSUITE is enabled, it overwrites
the runtime configuration of supported ciphersuites, which
includes both the configuration API and the fields which are
used to store the configuration. Both are therefore no longer
needed and should be removed for the benefit of code-size,
memory usage, and API clarity (no accidental hiccup of runtime
vs. compile-time configuration possible).

The configuration API mbedtls_ssl_conf_ciphersuites() has
already been removed in case MBEDTLS_SSL_SINGLE_CIPHERSUITE,
and this commit removes the field

  mbedtls_ssl_config::ciphersuite_list

which it updates.
2019-07-08 11:23:24 +01:00
Hanno Becker
df64596733 Remove ciphersuite from handshake params if single suite hardcoded
If MBEDTLS_SSL_SINGLE_CIPHERSUITE is enabled, the type

  mbedtls_ssl_ciphersuite_handle_t

is logically a boolean (concretely realized as `unsigned char`),
containing the invalid handle and the unique valid handle, which
represents the single enabled ciphersuite.

The SSL handshake structure mbedtls_ssl_handshake_params contains
an instance of mbedtls_ssl_ciphersuite_handle_t which is guaranteed
to be valid, and which is hence redundant in any two-valued
implementation of mbedtls_ssl_ciphersuite_handle_t.

This commit replaces read-uses of

  mbedtls_ssl_handshake_params::ciphersuite_info

by a getter functions which, and defines this getter function
either by just reading the field from the handshake structure
(in case MBEDTLS_SSL_SINGLE_CIPHERSUITE is disabled), or by
returning the single valid ciphersuite handle (in case
MBEDTLS_SSL_SINGLE_CIPHERSUITE is enabled) and removing the
field from mbedtls_ssl_handshake_params in this case.
2019-07-08 11:23:24 +01:00
Hanno Becker
2d46b4f2a1 Adapt ClientHello parsing to case of single hardcoded ciphersuite
This commit adapts the ClientHello parsing routines in ssl_srv.c
to use the ciphersuite traversal macros

  MBEDTLS_SSL_BEGIN_FOR_EACH_CIPHERSUITE
  MBEDTLS_SSL_END_FOR_EACH_CIPHERSUITE

introduced in the last commit, thereby making them work
both with and without MBEDTLS_SSL_SINGLE_CIPHERSUITE.

Another notable change concerns the ssl_ciphersuite_match:
Previous, this function would take a ciphersuite ID and a
pointer to a destination ciphersuite info structure as input
and write eithe NULL or a valid ciphersuite info structure
to that destination address, depending on whether the suite
corresponding to the given ID was suitable or not. The
function would always return 0 outside of a fatal error.
This commit changes this to ssl_ciphersuite_is_match() which
instead already takes a ciphersuite handle (which outside
of a hardcoded ciphersuite is the same as the ptr to a
ciphersuite info structure) and returns 0 or 1 (or a
negative error code in case of a fatal error) indicating
whether the suite corresponding to the handle was acceptable
or not. The conversion of the ciphersuite ID to the ciphersuite
info structure is done prior to calling ssl_ciphersuite_is_match().
2019-07-08 11:23:17 +01:00
Hanno Becker
1499027d02 Adapt ClientHello writing to case of single hardcoded ciphersuite
This commit modifies the ClientHello writing routine ssl_write_client_hello
in ssl_cli.c to switch between
(a) listing all runtime configured ciphersuites
    (in case MBEDTLS_SSL_SINGLE_CIPHERSUITE is not defined)
(b) listing just the single hardcoded ciphersuite
    (in case MBEDTLS_SSL_SINGLE_CIPHERSUITE is defined)

The approach taken is to introduce a pair of helper macros

  MBEDTLS_SSL_BEGIN_FOR_EACH_CIPHERSUITE( ssl, ver, info )
  MBEDTLS_SSL_END_FOR_EACH_CIPHERSUITE

which when delimiting a block of code lead to that block of
code being run once for each ciphersuite that's enabled in the
context `ssl` and version `ver`, referenced through the (fresh)
`info` variable. Internally, this is implemented either through
a plain `for` loop traversing the runtime configured ciphersuite
list (if MBEDTLS_SSL_SINGLE_CIPHERSUITE is disabled) or by just
hardcoding `info` to the single enabled ciphersuite (if
MBEDTLS_SSL_SINGLE_CIPHERSUITE is enabled).

These helper macros will prove useful whereever previous code
traversed the runtime configured ciphersuite list, but adaptations
of those occasions outside ClientHello writing are left for later
commits.
2019-07-08 11:17:53 +01:00
Hanno Becker
5cce936e62 Add compile-time option to hardcode choice of single ciphersuite 2019-07-08 11:17:53 +01:00
Hanno Becker
b09132d33a Introduce framework for macro-based definitions of ciphersuites
This commit is a step towards the goal of allowing to hardcode the choice
of a single ciphersuite at compile-time. The hoped for benefit of this is
that whereever a ciphersuite attribute is queried and checked against a
compile-time constant, the check can be recognized as either true or false
at compile-time, hence leading to a code-size reduction.

For this to work, the ciphersuite attribute getter functions
mbedtls_ssl_suite_get_xxx() will be modified to return something
the compiler can recognize as a compile-time constant. In particular,
in order to avoid relying on constant propagation abilities of the
compiler, these functions should ideally return constant symbols
(instead of, say, fields in a globally const structure instance).

This puts us in the following situation: On the one hand, there's the
array of ciphersuite information structures defining the attribute of
those ciphersuites the stack knows about. On the other hand, we need
direct access to those fields through constant symbols in the getter
functions.

In order to avoid any duplication of information, this commit exemplifies
how ciphersuites can be conveniently defined on the basis of macro
definitions, and how the corresponding instances of the ciphersuite
information structure can be auto-generated from this.

In the approach, to add support for a ciphersuite with official name
NAME (such as TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8), the following macro
constants need to be defined in ssl_ciphersuites.h:

  MBEDTLS_SUITE__ NAME __ID
  MBEDTLS_SUITE__ NAME __NAME
  MBEDTLS_SUITE__ NAME __CIPHER
  MBEDTLS_SUITE__ NAME __MAC
  ...

To make check-names.sh happy, one also needs a dummy macro

  MBEDTLS_SUITE__ NAME()

These ciphersuite attribute values can then be queried via

  MBEDTLS_SSL_SUITE_ID( NAME_MACRO )
  ...

where NAME_MACRO can be any macro expanding to a defined NAME.

Further, a convenience macro

  MBEDTLS_SSL_SUITE_INFO( NAME_MACRO )

is provided that again takes a macro NAME_MACRO expanding to a
defined NAME, and itself expands to an instance of
mbedtls_ssl_ciphersuite_info_t using the macro attributes
defined for NAME. This macro is then used in ssl_ciphersuites.c
when defining the array of known ciphersuite information structures,
(a) without duplicating the information, and (b) with increased
readability, because there's only one line for each ciphersuite.
2019-07-08 11:17:53 +01:00
Hanno Becker
473f98f2e0 Introduce ciphersuite handle type
This commit introduces an internal zero-cost abstraction layer for
SSL ciphersuites: Instead of addressing ciphersuites via pointers
to instances of mbedtls_ssl_ciphersuite_t and accessing their fields
directly, this commit introduces an opaque type

  mbedtls_ssl_ciphersuite_handle_t,

and getter functions

  mbedtls_ssl_suite_get_xxx()

operating on ciphersuite handles.

The role of NULL is played by a new macro constant

  MBEDTLS_SSL_CIPHERSUITE_INVALID_HANDLE

which results of functions returning handles can be checked against.
(For example, when doing a lookup of a ciphersuite from a peer-provided
ciphersuite ID in the per's Hello message).

The getter functions have the validity of the handle as a precondition
and are undefined if the handle is invalid.

So far, there's only one implementation of this abstraction layer, namely

  mbedtls_ssl_ciphersuite_handle_t being mbedtls_ssl_ciphersuite_t const *

and

  getter functions being field accesses.

In subsequent commits, however, the abstraction layer will be useful
to save code in the situation where only a single ciphersuite is enabled.
2019-07-08 11:17:53 +01:00
Hanno Becker
65382f250d Make ssl.h independent of ssl_ciphersuites.h
Previously, ssl.h included ssl_ciphersuites.h to have access to the
helper macros MBEDTLS_KEY_EXCHANGE_XXX_ENABLED, and for no other
reason. This commit moves the definitions of these macros to ssl.h,
thereby removing the dependency of ssl.h on ssl_ciphersuites.h.
2019-07-08 11:17:06 +01:00
Manuel Pégourié-Gonnard
5455afd74e
Merge pull request #599 from ARMmbed/baremetal-ec-preparation
[Baremetal] Avoid heap-allocation for client-supported elliptic curves
2019-07-05 14:16:41 +02:00
Manuel Pégourié-Gonnard
0ec3ed0419
Merge pull request #596 from ARMmbed/static_config_funcptr-baremetal
[Baremetal] Allow compile-time configuration of function pointer callbacks
2019-07-05 14:16:30 +02:00
Hanno Becker
56ab3ea5ad [Fixup] Fix alignment of comment in config.h 2019-07-04 16:40:10 +01:00
Hanno Becker
600ddf45c3 Update query_config.c and version_features.c 2019-07-04 14:05:00 +01:00
Hanno Becker
d07614c529 Introduce MBEDTLS_X509_CRT_REMOVE_SUBJECT_ISSUER_ID removing IDs 2019-07-04 14:04:03 +01:00
Hanno Becker
843b71a1df Introduce MBEDTLS_X509_CRT_REMOVE_TIME removing time fields from CRT 2019-07-04 14:04:03 +01:00
Hanno Becker
6f61b7bb5c Remove 'CRT fallback' during X.509 CRT verification if !TIME_DATE 2019-07-04 14:03:26 +01:00
Hanno Becker
c00cceaa3f Move def'n of X.509 time-verif funcs to hdr if no time available 2019-07-04 14:03:26 +01:00
Hanno Becker
d3b2fcb7c6 Don't store client-supported ECs in heap-allocated buffer
So far, the client-proposed list of elliptic curves was stored for the
duration of the entire handshake in a heap-allocated buffer referenced
from mbedtls_ssl_handshake_params::curves. It is used in the following
places:
1) When the server chooses a suitable ciphersuite, it checks that
   it has a certificate matching the ciphersuite; in particular, if
   the ciphersuite involves ECDHE, the server needs an EC certificate
   with a curve suitable for the client.
2) When performing the ECDHE key exchange, the server choose one
   curve among those proposed by the client which matches the server's
   own supported curve configuration.

This commit removes the hold back the entire client-side curve list
during the handshake, by performing (1) and (2) on during ClientHello
parsing, and in case of (2) only remembering the curve chosen for ECDHE
within mbedtls_ssl_handshake_params.
2019-07-04 12:41:08 +01:00
Hanno Becker
31d9bded31 [Fixup] Fix rebase 2019-07-04 11:57:11 +01:00
Hanno Becker
99b6b6b6c9 Fix outdated documentation of effect of hardcoded timer cb's on API 2019-07-04 11:34:40 +01:00
Hanno Becker
1f1e9eff06 Fix outdated documentation of effect of hardcoded I/O cb's on API 2019-07-04 11:33:09 +01:00
Hanno Becker
572a5d84d6 Minor improvement in documentation of hardcoded config func ptrs 2019-07-04 11:31:36 +01:00
Hanno Becker
65f6f38097 Update outdated comment on effect of hardcoding RNG on API 2019-07-04 11:28:34 +01:00
Hanno Becker
62327abd65 [Fixup] Fix typo in check_config.h using #define instead of #error 2019-07-04 10:29:44 +01:00
Hanno Becker
0ae6b244c8 Allow compile-time configuration of timer callbacks
Introduces
- MBEDTLS_SSL_CONF_SET_TIMER
- MBEDTLS_SSL_CONF_GET_TIMER
which allows to configure timer callbacks at compile-time.

Impact on code-size:

|  | GCC 8.2.1 | ARMC5 5.06 | ARMC6 6.12 |
| --- | --- | --- | --- |
| `libmbedtls.a` before | 23379 | 23981 | 26941 |
| `libmbedtls.a` after | 23351 | 23953 | 26869 |
| gain in Bytes | 28 | 28 | 72 |
2019-07-04 10:29:44 +01:00
Hanno Becker
a58a896172 Allow compile-time configuration of I/O function pointers
Introduce the compile-time options
- MBEDTLS_SSL_CONF_RECV
- MBEDTLS_SSL_CONF_SEND
- MBEDTLS_SSL_CONF_RECV_TIMEOUT
which can be used to configure the callbacks for the underlying
transport at compile-time.

Code-size impact:

|  | GCC 8.2.1 | ARMC5 5.06 | ARMC6 6.12 |
| --- | --- | --- | --- |
| `libmbedtls.a` before | 23471 | 24077 | 27045 |
| `libmbedtls.a` before | 23379 | 23981 | 26941 |
| gain in Bytes | 92 | 96 | 104 |
2019-07-04 10:28:55 +01:00
Hanno Becker
ece325c8dd Allow compile-time configuration of PRNG in SSL module
Introduces MBEDTLS_SSL_CONF_RNG to allow configuring the
RNG to be used by the SSL module at compile-time.

Impact on code-size:

|  | GCC 8.2.1 | ARMC5 5.06 | ARMC6 6.12 |
| --- | --- | --- | --- |
| `libmbedtls.a` before | 23535 | 24089 | 27103 |
| `libmbedtls.a` after | 23471 | 24077 | 27045 |
| gain in Bytes | 64 | 12 | 58 |
2019-07-04 10:27:41 +01:00
Manuel Pégourié-Gonnard
1841f84c79
Merge pull request #611 from mpg/baremetal-proposed
Baremetal proposed
2019-07-04 08:30:19 +02:00
Manuel Pégourié-Gonnard
b391766802 Fix unused variable that happened during merge
Fix an "unused variable" warning that happened in some configurations
(without EC, found by depend-pkalg.pl) and was not present in any parent PR
but only in the result of merging them: one of the PRs clarified the
distinction between `ret` and `verify_ret` and the other removed one
occurrence of using `ret`, and the conjunction of the two made `ret` unused in
some cases. Resolving by reducing the scope of that variable.
2019-07-03 11:24:24 +02:00
Manuel Pégourié-Gonnard
de8869c529 Merge remote-tracking branch 'restricted/pr/608' into baremetal-proposed
* restricted/pr/608:
  programs: Make `make clean` clean all programs always
  ssl_tls: Enable Suite B with subset of ECP curves
  windows: Fix Release x64 configuration
  timing: Remove redundant include file
  net_sockets: Fix typo in net_would_block()
  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
  Update library to 2.16.2
  Use 'config.pl baremetal' in all.sh
  Clarify ChangeLog entry for fix to #1628
  Fix #2370, minor typos and spelling mistakes
  Add Changelog entry for clang test-ref-configs.pl fix
  Enable more compiler warnings in tests/Makefile
  Change file scoping of test helpers.function
2019-07-03 10:31:46 +02:00
Manuel Pégourié-Gonnard
7ee1d4838f Merge remote-tracking branch 'restricted/pr/607' into baremetal-proposed
* restricted/pr/607:
  baremetal: Use Oz when building with armclang
2019-07-03 10:26:29 +02:00
Manuel Pégourié-Gonnard
44ba6b0d26 Merge remote-tracking branch 'restricted/pr/594' into baremetal-proposed
* restricted/pr/594:
  Adapt baremetal.h and baremetal.sh
  Don't incl. CAs in CertReq message in baremetal build
  Allow config'n of incl of CertificateReq CA list Y/N at compile-time
  Allow configuration of endpoint (cli/srv) at compile-time
  Allow configuration of read timeouts at compile-time
  Allow configuration of ConnectionID at compile-time
  Allow compile-time configuration of legacy renegotiation
  Allow compile-time configuration of authentication mode
  Allow compile-time configuration of DTLS badmac limit
  Allow compile-time configuration of DTLS anti replay
2019-07-03 10:22:28 +02:00
Manuel Pégourié-Gonnard
37261e6f6b Merge remote-tracking branch 'restricted/pr/601' into baremetal-proposed
* restricted/pr/601: (27 commits)
  Fix compile-time guard for optional field in struct
  Move code to reduce probability of conflicts
  Fix typos caught by check-names.sh
  Clarify conditions related to resumption in client
  Introduce getter function for renego_status
  Add getter function for handshake->resume
  Remove now-redundant code
  Remove cache callbacks from config on client
  Fix a few style issues
  Expand documentation of new options a bit
  Fix renaming oversight in documentation
  Remove backticks in doxygen in config.h
  Declare dependency on tickets for two ssl-opt.sh tests
  Exclude new negative options from config.pl full
  Restore config.h defaults
  Address review comments
  Fix ssl_cli resumption guards
  Fix check-files, check-names and check-generated-features
  Add test to all.sh
  Add changelog entry
  ...
2019-07-03 10:04:13 +02:00
Manuel Pégourié-Gonnard
417d2ce076 Merge remote-tracking branch 'restricted/pr/584' into baremetal-proposed
* restricted/pr/584: (140 commits)
  Remove superfluous new line in x509.c
  Add comment about X.509 name comparison of buffer with itself
  [Fixup] Add missing PK release call in Cert Verify parsing
  Fix guard controlling whether nested acquire calls are allowed
  Add X.509 CRT test for nested calls for CRT frame / PK acquire
  Don't return threading error on release()-without-acquire() calls
  Don't allow nested CRT acquire()-calls if MBEDTLS_X509_ALWAYS_FLUSH
  Make X.509 CRT cache reference counting unconditional
  Remove memory buffer alloc from i386 test in all.sh
  Don't mention pk_sign() in the context of public-key contexts
  Don't use assertion for failures of mbedtls_x509_crt_x_acquire()
  Fix copy pasta in x509_crt.h
  Reference copy-less versions of X.509 CRT frame/PK getters
  x509_crt.c: Add blank line to increase readability
  [FIXUP] Fix bug in ASN.1 traversal of silently ignored tag
  [FIXUP] Fix typo in declaration of mbedtls_x509_memcasecmp()
  Move signature-info extraction out of MBEDTLS_X509_REMOVE_INFO
  Fix certificate validity checking logic to work with !TIME_DATE
  Simplify X.509 CRT version check in UID parsing
  Remove unused variable warning in on-demand X.509 parsing
  ...
2019-07-03 10:03:45 +02:00
Hanno Becker
b1d720c016 Remove superfluous new line in x509.c 2019-07-02 16:47:57 +01:00
Hanno Becker
3aa121660e Add comment about X.509 name comparison of buffer with itself 2019-07-02 16:47:40 +01:00
Hanno Becker
3b876acff4 Adapt baremetal.h and baremetal.sh 2019-07-02 16:42:45 +01:00
Hanno Becker
f3400da3ca Don't incl. CAs in CertReq message in baremetal build
This commit modifies the baremetal configuration to disables the inclusion
of the list of accepted CAs in the CertificateRequest message sent by the
server.

Impact on code-size:

|  | GCC 8.2.1 | ARMC5 5.06 | ARMC6 6.12 |
| --- | --- | --- | --- |
| `libmbedtls.a` before | 23099 | 23781 | 26639 |
| `libmbedtls.a` before  | 22995 | 23689 | 26515 |
| gain in Bytes | 104 | 92 | 124 |
2019-07-02 16:42:45 +01:00
Hanno Becker
c2cfdaa693 Allow config'n of incl of CertificateReq CA list Y/N at compile-time
Introduces MBEDTLS_SSL_CONF_CERT_REQ_CA_LIST which allows to configure
at compile-time whether a CA list should be included in the
CertificateRequest message sent by the server.

Impact on code-size:

|  | GCC 8.2.1 | ARMC5 5.06 | ARMC6 6.12 |
| --- | --- | --- | --- |
| `libmbedtls.a` before  | 23131 | 23805 | 26673 |
| `libmbedtls.a` after | 23099 | 23781 | 26639 |
| gain in Bytes | 32 | 24 | 34 |
2019-07-02 16:42:45 +01:00
Hanno Becker
2d9623f7d5 Allow configuration of endpoint (cli/srv) at compile-time
Introduces MBEDTLS_SSL_CONF_ENDPOINT to allow to choose between
server- or client-builds at compile-time.

Impact on code-size:

|  | GCC 8.2.1 | ARMC5 5.06 | ARMC6 6.12 |
| --- | --- | --- | --- |
| `libmbedtls.a` (client only) before  | 18355 | 18815 | 21485 |
| `libmbedtls.a` (client only) after | 18219 | 18683 | 21347 |
| gain in Bytes (client only) | 136 | 132 | 138 |
| `libmbedtls.a` (server only) before  | 18715 | 18987 | 21883 |
| `libmbedtls.a` (server only) after | 18595 | 18823 | 21717 |
| gain in Bytes (server only) | 120 | 164 | 166 |
2019-07-02 16:42:41 +01:00
Hanno Becker
1f835fa22b Allow configuration of read timeouts at compile-time
Introduces compile-time constants
- MBEDTLS_SSL_CONF_READ_TIMEOUT
- MBEDTLS_SSL_CONF_HS_TIMEOUT_MIN
- MBEDTLS_SSL_CONF_HS_TIMEOUT_MAX
which allow to configure the read timeouts and
minimum/maximum handshake timeout at compile time.

Impact on code-size:

|  | GCC 8.2.1 | ARMC5 5.06 | ARMC6 6.12 |
| --- | --- | --- | --- |
| `libmbedtls.a` before  | 23147 | 23781 | 26703 |
| `libmbedtls.a` after | 23131 | 23753 | 26673 |
| gain in Bytes | 16 | 28 | 30 |
2019-07-02 16:42:10 +01:00
Hanno Becker
e0200dad63 Allow configuration of ConnectionID at compile-time
Introduces
- MBEDTLS_SSL_CONF_CID_LEN and
- MBEDTLS_SSL_CONF_IGNORE_UNEXPECTED_CID
to control
- the length of incoming CIDs
- the behaviour in receipt of unexpected CIDs
at compile-time.

Impact on code-size:

|  | GCC 82.1 | ARMC5 5.06 | ARMC6 6.12 |
| --- | --- | --- | --- |
| `libmbedtls.a` before | 23223 | 23865 | 26775 |
| `libmbedtls.a` after  | 23147 | 23781 | 26703 |
| gain in Bytes | 76 | 84 | 72 |
2019-07-02 16:41:35 +01:00
Hanno Becker
b0b2b67568 Allow compile-time configuration of legacy renegotiation
Introduces MBEDTLS_SSL_CONF_ALLOW_LEGACY_RENEGOTIATION
allowing to configure enforcing secure renegotiation at
compile-time.

Impact on code-size:

|  | GCC | ARMC5 | ARMC6 |
| --- | --- | --- | --- |
| `libmbedtls.a` after  | 23379 | 23929 | 27727 |
| `libmbedtls.a` before | 23307 | 23865 | 27615 |
| gain in Bytes | 72 | 64 | 112 |
2019-07-02 16:41:34 +01:00
Hanno Becker
acd4fc0ac9 Allow compile-time configuration of authentication mode
Introduces MBEDTLS_SSL_CONF_AUTHMODE to fix the authentication
mode (none, optional, mandatory) at compile-time.

Impact on code-size:

|  | GCC | ARMC5 | ARMC6 |
| --- | --- | --- | --- |
| `libmbedtls.a` before | 23487 | 24025 | 27885 |
| `libmbedtls.a` after  | 23379 | 23929 | 27727 |
| gain in Bytes | 108 | 96 | 157 |
2019-07-02 16:41:29 +01:00
Hanno Becker
de67154658 Allow compile-time configuration of DTLS badmac limit
Introduces MBEDTLS_SSL_CONF_BADMAC_LIMIT to fix the maximum
number of records with bad MAC tolerated in DTLS at compile-time.

Impact on code-size:

|  | GCC | ARMC5 | ARMC6 |
| --- | --- | --- | --- |
| `libmbedtls.a` before  | 23511 | 24049 | 27903 |
| `libmbedtls.a` after | 23487 | 24025 | 27885 |
| gain in Bytes | 24 | 24 | 18 |
2019-07-02 16:40:50 +01:00
Hanno Becker
bc6b59859f [Fixup] Add missing PK release call in Cert Verify parsing
mbedtls_ssl_read() can fail non-fatally, in which case
ssl_parse_certificate_verify() returned immediately without
calling mbedtls_x509_crt_pk_release(), which in turn lead
to a fatal error because of nested acquire calls in the
next call to the function.
2019-07-02 15:36:44 +01:00
Manuel Pégourié-Gonnard
7b80c64de4 Fix compile-time guard for optional field in struct 2019-07-02 16:24:55 +02:00
Manuel Pégourié-Gonnard
1772c9fac5 Move code to reduce probability of conflicts
There are a number of PRs in flight that are going to append to the list of
getter functions for harcodeable SSL conf items, so leave that list at the end
in order to avoid conflicts between this PR and the SSL conf ones.
2019-07-02 15:18:36 +02:00
Manuel Pégourié-Gonnard
c27fabfb6f Fix typos caught by check-names.sh 2019-07-02 15:13:18 +02:00
Manuel Pégourié-Gonnard
93c8262d4a Clarify conditions related to resumption in client 2019-07-02 15:13:18 +02:00
Manuel Pégourié-Gonnard
754b9f32db Introduce getter function for renego_status
While not strictly related to this PR, this change improves readability in
some resumption-related runtime conditions that previously had rather ugly
preprocessor directives in the middle of already complex predicates.
2019-07-02 15:13:18 +02:00
Manuel Pégourié-Gonnard
3652e99100 Add getter function for handshake->resume
This makes the code more readable by having fewer #ifdefs all over the place.
2019-07-02 15:13:18 +02:00
Manuel Pégourié-Gonnard
44b10761cc Remove now-redundant code
Due to previous change of conditions, this is now in the 'else' branch of 'if
resume == 1' and the only allowed values are 0 or 1, so setting to 0 is
redundant.
2019-07-02 15:12:29 +02:00
Manuel Pégourié-Gonnard
33cb3e1c7e Remove cache callbacks from config on client
The session cache is only server-side. This also aligns the conditions
guarding those fields with the condition guarding the function setting them -
no need to have the fields if we can't set them.

This preserves the API and ABI in the default config as it only affects
non-default configs.
2019-07-02 15:12:29 +02:00
Manuel Pégourié-Gonnard
594a1bbc4f Fix a few style issues 2019-07-02 15:12:29 +02:00
Manuel Pégourié-Gonnard
320eb7ac4e Expand documentation of new options a bit 2019-07-02 15:12:29 +02:00
Manuel Pégourié-Gonnard
8a0944cb99 Fix renaming oversight in documentation 2019-07-02 15:12:29 +02:00
Manuel Pégourié-Gonnard
e431563269 Remove backticks in doxygen in config.h 2019-07-02 15:12:29 +02:00
Manuel Pégourié-Gonnard
f1c6ad4c5f Declare dependency on tickets for two ssl-opt.sh tests
See https://github.com/ARMmbed/mbedtls/issues/2712
2019-07-02 15:12:29 +02:00
Manuel Pégourié-Gonnard
26ac9c4d1f Exclude new negative options from config.pl full 2019-07-02 15:12:29 +02:00
Manuel Pégourié-Gonnard
f130b1024a Restore config.h defaults
We want those changes only in config/baremetal.h, not in the default config.
2019-07-02 15:12:29 +02:00
Jarno Lamsa
29f2dd0a7b Address review comments 2019-07-02 15:12:29 +02:00
Jarno Lamsa
dbf6073fa3 Fix ssl_cli resumption guards 2019-07-02 15:12:29 +02:00
Jarno Lamsa
4f74f6d301 Fix check-files, check-names and check-generated-features 2019-07-02 15:12:29 +02:00
Jarno Lamsa
0905c3da11 Add test to all.sh 2019-07-02 15:12:29 +02:00
Jarno Lamsa
18f0662541 Add changelog entry 2019-07-02 15:12:29 +02:00
Jarno Lamsa
ac57e82c7d Doxygen for new config options 2019-07-02 15:12:29 +02:00
Jarno Lamsa
5b52b27519 Skip resumption tests if resumption not defined 2019-07-02 15:12:29 +02:00
Jarno Lamsa
5165169a05 Fix test issues 2019-07-02 15:12:29 +02:00
Jarno Lamsa
085e8a507e Enable new configs in baremetal config
Enable MBEDTLS_SSL_SESSION_CACHE and
MBEDTLS_SESSION_RESUMPTION in baremetal config.
2019-07-02 15:12:29 +02:00
Jarno Lamsa
59bd12bf14 Add new config MBEDTLS_SSL_SESSION_RESUMPTION
Add a new configuration option MBEDTLS_SSL_SESSION_RESUMPTION
to enable/disable the session resumption feature including
ticket and cache based session resumption.
2019-07-02 15:12:29 +02:00
Jarno Lamsa
590bf51cbb Enable MBEDTLS_SSL_SESSION_CACHE by default 2019-07-02 15:12:29 +02:00
Jarno Lamsa
7be14065e2 Add config MBEDTLS_SSL_SESSION_CACHE
Add configuration option MBEDTLS_SSL_SESSION_CACHE to control
enabling/disabling of the cache based session resumption.
2019-07-02 15:12:29 +02:00
Hanno Becker
410322f23e Fix guard controlling whether nested acquire calls are allowed
Resource counting as a safe-guard against nested acquire calls
is implemented if and only if MBEDTLS_X509_ALWAYS_FLUSH is disabled
_or_ MBEDTLS_THREADING_C is enabled.
2019-07-02 13:37:12 +01:00
Hanno Becker
abd929c89c Merge branch 'mbedtls-2.16' into baremetal-2.16-01_07_19 2019-07-01 11:25:42 +01:00
Jaeden Amero
691aa961b1 baremetal: Use Oz when building with armclang
Oz is allowed to make size optimizations that make the code slower,
where Os isn't. Optimize with Oz, as we care more about having a small
code footprint than having fast code.
2019-07-01 11:21:36 +01:00
Hanno Becker
7ab8a2e2a0 Add X.509 CRT test for nested calls for CRT frame / PK acquire 2019-06-28 15:52:54 +01:00
Hanno Becker
69c303360e Don't return threading error on release()-without-acquire() calls
Previously, a call to mbedtls_x509_crt_xxx_release() would return
MBEDTLS_ERR_THREADING_MUTEX_ERROR if usage counter for the frame/PK
was 0. Now that resource counting can also be used outside of
threading support, this is no longer adequate, and this commit
changes the return code to MBEDTLS_ERR_X509_FATAL_ERROR; while
generic, this at least matches the top-level module.
2019-06-28 15:47:53 +01:00
Hanno Becker
fc99a09cc4 Don't allow nested CRT acquire()-calls if MBEDTLS_X509_ALWAYS_FLUSH
Forbidding nested calls to acquire() allows to remove the reference
counting logic and hence saving some bytes of code. This is valuable
because MBEDTLS_X509_ALWAYS_FLUSH is likely to be used on constrained
systems where code-size is limited.
2019-06-28 14:48:32 +01:00
Hanno Becker
a4bfaa8204 Make X.509 CRT cache reference counting unconditional
Previously, reference counting for the CRT frames and PK contexts
handed out by mbedtls_x509_crt_{frame|pk}_acquire() was implemented
only in case threading support was enabled, which leaves the door
open for a potential use-after-free should a single-threaded application
use nested calls to mbedtls_x509_crt_acquire().

Since Mbed TLS itself does not use such nested calls, it might be
preferred long-term to forbid nesting of acquire calls on the API
level, and hence get rid of reference counting in the interest of
code-size benefits. However, this can be considered as an optimization
of X.509 on demand parsing, and for now this commit introduces
reference counting unconditionally to have a safe version of
on demand parsing to build further optimizations upon.
2019-06-28 14:48:32 +01:00
Hanno Becker
94a94f6c33 Remove memory buffer alloc from i386 test in all.sh
Otherwise, the CI fails this test due to timeout.

The buffer allocator is tested e.g. in test_full_cmake_clang().
2019-06-28 14:48:32 +01:00
Hanno Becker
b653aa3d16 Don't mention pk_sign() in the context of public-key contexts 2019-06-28 14:48:32 +01:00
Hanno Becker
2224ccf390 Don't use assertion for failures of mbedtls_x509_crt_x_acquire()
These functions may afil in a regular run, e.g. due to an out of memory
error.
2019-06-28 14:48:31 +01:00
Hanno Becker
d92078fc55 Fix copy pasta in x509_crt.h 2019-06-28 14:48:31 +01:00
Hanno Becker
608de6a50d Reference copy-less versions of X.509 CRT frame/PK getters 2019-06-28 14:48:31 +01:00
Hanno Becker
ed05888195 x509_crt.c: Add blank line to increase readability 2019-06-28 14:48:31 +01:00
Manuel Pégourié-Gonnard
4e24c449e2
Merge pull request #592 from ARMmbed/static_config_extended_ms
[Baremetal] Exemplify hardcoding of SSL configuration at compile-time in the example of ExtendedMasterSecret
2019-06-28 13:49:35 +02:00
Hanno Becker
35b86a872f [FIXUP] Fix bug in ASN.1 traversal of silently ignored tag 2019-06-25 10:41:34 +01:00
Hanno Becker
2656bfe9b0 [FIXUP] Fix typo in declaration of mbedtls_x509_memcasecmp() 2019-06-25 10:41:34 +01:00
Hanno Becker
08d341211d Move signature-info extraction out of MBEDTLS_X509_REMOVE_INFO
During rebase, the definition of ::mbedtls_x509_crt_sig_info
as well as x509_crt_free_sig_info() and x509_crt_get_sig_info()
were accidentally guarded by !MBEDTLS_X509_REMOVE_INFO.

This commit moves their definition outside of that guard.
2019-06-25 10:41:31 +01:00
Hanno Becker
040c564888 Fix certificate validity checking logic to work with !TIME_DATE
If MBEDTLS_HAVE_TIME_DATE is undefined, the functions
`mbedtls_x509_time_is_past()` and `mbedtls_x509_time_is_future()`
are still defined but return `0` (that is, no time is seen to in
the past or future). To maintain functional correctness, this
means that these functions have to be called in a way where
the condition being checked for is the erroneous one: Concretely,
one shouldn't check that a CRT's `validFrom` is in the past,
or that its `validTo` is in the future, because that would
fail if !MBEDTLS_HAVE_TIME_DATE. Instead, one should check
that `validFrom` is NOT in the future, and `validTo` is NOT
in the past. That was the logic previously, but an uncautious
change during transition to X.509 on-demand parsing has
changed it. This commit fixes this.
2019-06-25 09:11:11 +01:00
Hanno Becker
97aa4363e1 Simplify X.509 CRT version check in UID parsing
WHen parsing the CRT version, we already check that
version is either 1, 2, or 3, so checking whether
version == 2 or version == 3 is equivalent to
version != 1.
2019-06-25 09:11:11 +01:00
Hanno Becker
60785d113b Remove unused variable warning in on-demand X.509 parsing 2019-06-25 09:11:11 +01:00
Hanno Becker
7c5fbbeec0 Reduce number of parallel workers in X.509 CRT threading test
The previous tests used 100 parallel workers which for EC certificates
leads to a memory usage of more than 1Mb, hence leading to an out of memory
condition in tests using the memory buffer allocator which has a pool of 1Mb.

Use 25 workers but an increased number of iterations per worker instead.
2019-06-25 09:11:11 +01:00
Hanno Becker
e908412a35 Simplify logic for issuer/subject ID parsing 2019-06-25 09:11:11 +01:00
Hanno Becker
fd64f14ef9 Remove redundant CRT version check during CRT parsing 2019-06-25 09:11:11 +01:00
Hanno Becker
938a80507a Add MBEDTLS_X509_ON_DEMAND_PARSING to baremetal config 2019-06-25 09:11:11 +01:00
Hanno Becker
b36a245654 Add comment to #endif indicating which condition was guarded 2019-06-25 09:10:57 +01:00
Hanno Becker
484caf0abc Consistently use (type *) instead of (type*) for pointer conversion 2019-06-25 09:10:57 +01:00
Hanno Becker
2ba9fbdfe9 Allow multiple concurrent readers for X.509 CRT frame and PK context
Previously, only one thread could access the parsing cache of an X.509 CRT
at a time. Firstly, this leads to significant performance penalties on
systems running many concurrent threads which share CRT structures --
for example, server threads sharing an SSL configuration containing the
server CRT. Secondly, the locking should be logically unnecessary, because
the threads are supposed to access the CRT frame and PK in a read-only,
or at least thread-safe manner.

This commit modifies the X.509 CRT cache implementation by allowing an
arbitrary number of concurrent readers, locking only the path of setting
up and clearing the cache.
2019-06-25 09:10:57 +01:00
Hanno Becker
d687ef0a91 Move X.509 threading test to separate test suite
This allows to build the library + tests via `make` without
specifying `PTHREAD=1`, in which case the X.509 threading
test suite will be silently dropped.

This is analogous to the pre-existing handling of the example
application `ssl_pthread_server`, which is only build if `PTHREAD=1`
and silently dropped otherwise.
2019-06-25 09:10:57 +01:00
Hanno Becker
22cf255e09 Force linking of pthread in 'full config' tests in all.sh 2019-06-25 09:10:57 +01:00
Hanno Becker
fa37d07a0d Make: Link test suites with pthread if PTHREAD is set 2019-06-25 09:10:57 +01:00
Hanno Becker
1ba602c2f6 CMake: Link test suites with pthread if LINK_WITH_PTHREAD set
The pre-existing LINK_WITH_PTHREAD CMake option controls whether
`pthread` should be linked into the library, but didn't apply
to the test suites so far.

This commit also links test suites to `pthread` in CMake-based
builds which have LINK_WITH_PTHREAD set.
2019-06-25 09:10:57 +01:00
Hanno Becker
fd8b7bd63f Add concurrent X.509 CRT verification test
This commit enhances the X.509 parsing test suite by a test
which exercises multiple threads concurrently verifying the
same certificate with the same set of trusted roots.
2019-06-25 09:10:57 +01:00
Hanno Becker
4b70e12dde Document mbedtls_x509_crt_pk_{acquire/release}()
In contrast to mbedtls_x509_crt_frame_acquire(), the public key context
returned by mbedtls_x509_crt_pk_acquire() cannot be marked `const` because
the caller must be able to use it e.g. for mbedtls_pk_sign() and
mbedtls_pk_verify(), which don't have `const` input parameters.

Instead, return a non-`const` context, but explicitly state that callers
must use that context in a thread-safe way.
2019-06-25 09:10:57 +01:00
Hanno Becker
b8670fcab3 Document mbedtls_x509_crt_frame_{acquire/release}() 2019-06-25 09:10:57 +01:00
Hanno Becker
5f268b3cf6 Don't allow change of CRT frame returned by x509_crt_frame_acquire() 2019-06-25 09:10:57 +01:00
Hanno Becker
9219f9e7b8 Fix yet another occasions of 'setup' vs. 'set up' typo in x509_crt.h 2019-06-25 09:10:57 +01:00
Hanno Becker
1250623ad1 Mark CRT frame argument to mbedtls_x509_xxx_from_frame() constant 2019-06-25 09:10:57 +01:00
Hanno Becker
a4dfc0d73d Move X.509 CRT cache handling functions to x509_internal.h 2019-06-25 09:10:57 +01:00
Hanno Becker
3c3d5c5836 Fix spacing in declaration of mbedtls_asn1_get_sequence_of() 2019-06-25 09:10:57 +01:00
Hanno Becker
c0dab627ce Fix typo 'setup' -> 'set up' throughout x509_crt.h 2019-06-25 09:10:57 +01:00
Hanno Becker
fd5c185ed6 Use uint16_t to store key usage field in X.509 CRT
Also, reorder the fields to avoid padding, thereby reducing the size of
mbedtls_x509_crt_frame by 2 Bytes.
2019-06-25 09:10:57 +01:00
Hanno Becker
00d390338d Move internal mbedtls_x509_crt_cache to x509_internal.h
We cannot move it to x509_crt.c because there are some static inline
function definitions in x509_crt.h which access members of
mbedtls_x509_crt_cache.
2019-06-25 09:10:57 +01:00
Hanno Becker
54f1c2cb20 Rename MBEDTLS_X509_SAFE_SNPRINTF_WITH_ERROR to _WITH_CLEANUP 2019-06-25 09:10:57 +01:00
Hanno Becker
f332a97e1b Add ASN.1 API to free linked list representation of ASN.1 sequences 2019-06-25 09:10:57 +01:00
Hanno Becker
7b8e11e724 Avoid allocating empty buffers when handling length-0 CRTs 2019-06-25 09:10:57 +01:00
Hanno Becker
0ed348a14e Update VS2010 project file 2019-06-25 09:10:57 +01:00
Hanno Becker
529f25d119 Don't use mbedtls_asn1_get_sequence_of() in x509_crt.c
This commit modifies the implementation of x509_get_ext_key_usage()
to not rely on mbedtls_asn1_get_sequence_of() but to instead use
mbedtls_asn1_traverse_sequence_of() with the same sequence-building
callback that also x509_get_subject_alt_name() uses, and which agrees
with the callback used by mbedtls_asn1_get_sequence_of().

The reason for this is that with this change, Mbed TLS itself isn't
using mbedtls_asn1_get_sequence_of() anymore, but only the more powerful
mbedtls_asn1_traverse_sequence_of(), so that unless application code
makes use of mbedtls_asn1_get_sequence_of(), its implementation
-- including the underlying sequence building callback -- will be
removed by link time garbage collection.
2019-06-25 09:10:57 +01:00
Hanno Becker
15b73b4066 Correct placement of comment on X.509 SAN parsing 2019-06-25 09:10:57 +01:00
Hanno Becker
e452add01e Comment on return value type in two internal X.509 functions 2019-06-25 09:10:57 +01:00
Hanno Becker
be0cf9b1f6 Improve formatting in x509.c 2019-06-25 09:10:57 +01:00
Hanno Becker
f6bc8886c7 Move declarations of internal X.509 functions to separate header
This makes it easier to distinguish public from internal functions;
for us, for users, and for automated API compatibility checkers.
2019-06-25 09:10:57 +01:00
Hanno Becker
1421246d44 Update version_features.c 2019-06-25 09:07:16 +01:00
Hanno Becker
a7ac412dcd Update query_config.c 2019-06-25 09:07:16 +01:00
Hanno Becker
76428359b3 Move existence check for pk/frame to mbedtls_x509_crt_provide_xxx() 2019-06-25 09:07:16 +01:00
Hanno Becker
bc685199d9 Implement MBEDTLS_X509_ALWAYS_FLUSH 2019-06-25 09:07:16 +01:00
Hanno Becker
ffcd8c39a4 Introduce compile-time option to always flush X.509 CRT caches
This commit introduces a compile-time option MBEDTLS_X509_ALWAYS_FLUSH
which controls whether releasing of CRT frames or public key contexts
associated to X.509 CRTs (or, in the future, other cached parsed X.509
structures) should lead to freeing those structures immediately.

Enabling this alongside of the MBEDTLS_X509_ON_DEMAND_PARSING leads
to significant reduction of the average RAM consumption of Mbed TLS.

The option is enabled by default to reduce the permanent RAM overhead of
MBEDTLS_X509_ON_DEMAND_PARSING in case the latter is *disabled* (default).
(Note that there is very little performance penalty enabling
MBEDTLS_X509_ALWAYS_FLUSH in case MBEDTLS_X509_ON_DEMAND_PARSING is disabled,
because hardly any parsing needs to be done to setup a CRT frame / PK context
from the legacy `mbedtls_x509_crt` structure.)
2019-06-25 09:07:16 +01:00
Hanno Becker
c6d1c3ed1c Remove frame/pk parameter from mbedtls_x509_crt_xxx_release() 2019-06-25 09:07:16 +01:00
Hanno Becker
7dbf49a518 Enable threading in all.sh test for X.509 on demand parsing 2019-06-25 09:07:16 +01:00
Hanno Becker
38f0cb487c Introduce helpers for conversion between X.509 buffer structs
This commit introduces two static helpers
- `x509_buf_to_buf_raw()`
- `x509_buf_raw_to_buf()`
which convert to/from the old `mbedtls_x509_buf` and
the new `mbedtls_x509_buf_raw` (the latter omitting the
ASN.1 tag field).
2019-06-25 09:07:16 +01:00
Hanno Becker
1e11f217d4 Solely use raw X.509 name data references including SEQUENCE header
So far, the CRT frame structure `mbedtls_x509_crt_frame` used
as `issuer_raw` and `subject_raw` the _content_ of the ASN.1
name structure for issuer resp. subject. This was in contrast
to the fields `issuer_raw` and `subject_raw` from the legacy
`mbedtls_x509_crt` structure, and caused some information
duplication by having both variants `xxx_no_hdr` and `xxx_with_hdr`
in `mbedtls_x509_crt` and `mbedtls_x509_crt_frame`.

This commit removes this mismatch by solely using the legacy
form of `issuer_raw` and `subject_raw`, i.e. those _including_
the ASN.1 name header.
2019-06-25 09:07:16 +01:00
Hanno Becker
4e021c8f50 Remove raw SubjectAltNames and ExtKeyUsage from legacy CRT struct 2019-06-25 09:07:16 +01:00
Hanno Becker
ea32d8ba2a Provide direct way of setting up a CRT frame from legacy CRT struct
Previously, `mbedtls_x509_crt_cache_provide_frame()` provided the requested
CRT frame by always parsing the raw data underlying the CRT. That's inefficient
in legacy mode, where the CRTs fields are permanently accessible through the
legacy `mbedtls_x509_crt` structure.

This commit modifies `mbedtls_x509_crt_cache_provide_frame()` in legacy mode
(that is, !MBEDTLS_X509_ON_DEMAND_PARSING) to setup the CRT frame by copying
fields from the legacy CRT structure.
2019-06-25 09:07:16 +01:00
Hanno Becker
bfabd1dfae Add test to all.sh
This commit adds a `make test` and `ssl-opt.sh` run to `all.sh`
exercising the default configuration, plus the following changes:
- MBEDTLS_SSL_KEEP_PEER_CERTIFICATE disabled
- MBEDTLS_X509_ON_DEMAND_PARSING enabled.
2019-06-25 09:07:16 +01:00
Hanno Becker
008d304d1b Adapt ChangeLog 2019-06-25 09:07:16 +01:00
Hanno Becker
5d9021e7f2 Make use of new API in ssl_server2 example application 2019-06-25 09:06:26 +01:00
Hanno Becker
4588dc4754 Update query_config.c 2019-06-25 09:06:26 +01:00
Hanno Becker
3f8f0dc3fd Use mbedtls_x509_crt_get_subject() in test_suite_x509parse test 2019-06-25 09:06:26 +01:00
Hanno Becker
5226c53e13 Modify mbedtls_x509_crt_info() to use getter API 2019-06-25 09:06:26 +01:00
Hanno Becker
7a4de9cdab Flush CRT cache after parsing
This commit modifies the CRT parsing routine to flush
the CRT cache after parsing. More specifically, the
frame cache is flushed before the PK is parsed, to
avoid storing the PK and frame in RAM at the same time.
2019-06-25 09:06:26 +01:00
Hanno Becker
828a8c08b6 Add compile-guard for < TLS1.2 path in server-side ssl_pick_cert()
Minor code-size optimization along the way.
2019-06-25 09:06:26 +01:00
Hanno Becker
c69c4465b6 Adapt test_suite_x509parse to new CRT structure 2019-06-25 09:06:26 +01:00
Hanno Becker
d8eab343d2 Adapt cert_write example program to work with new CRT structure 2019-06-25 09:06:26 +01:00
Hanno Becker
2bcc7640f8 Give x509_{sequence|name}_free() external linkage
With the introduction of `mbedtls_x509_crt_get_{issuer|name}()`,
users need an easy way of freeing the dynamic name structures these
functions return.

To that end, this commit renames `x509_{sequence|name}_free()`
to `mbedtls_x509_{sequence|name}_free()` and gives them external linkage.
2019-06-25 09:06:26 +01:00
Hanno Becker
ab6c8ea8bc Add public API to query SubjectAltNames and ExtKeyUsage extensions 2019-06-25 09:06:26 +01:00
Hanno Becker
63e6998dd7 Add public API to query subject and issuer from CRT
The legacy `mbedtls_x509_crt` contains fields `issuer/subject`
which are dynamically allocated linked list presentations of the
CRTs issuer and subject names, respectively.

The new CRT frame structure `mbedtls_x509_crt_frame`, however,
only provides pointers to the raw ASN.1 buffers for the issuer
and subject, for reasons of memory usage.

For convenience to users that previously used the `issuer`/`subject`
fields of `mbedtls_x509_crt`, this commit adds two public API functions
`mbedtls_x509_crt_get_subject()` and `mbedtls_x509_crt_get_issuer()`
which allow to request the legacy linked list presentation of the
CRTs subject / issuer names.

Similar to `mbedtls_x509_crt_get_pk()`, the returned names are owned
by the user, and must be freed through a call to `mbedtls_x509_name_free()`.
2019-06-25 09:06:26 +01:00
Hanno Becker
823efad6e8 Add public API to query for CRT frame and PK
This commit unconditionally adds two convenience API functions:
- mbedtls_x509_crt_get_frame()
- mbedtls_x509_crt_get_pk()
which allow users to extract a CRT frame or PK context
from a certificate.

The difference with the existing acquire/release API for frame and PK
contexts is that in contrast to the latter, the structures returned by
the new API are owned by the user (and, in case of the PK context, need
to be freed by him). This makes the API easier to use, but comes at the
cost of additional memory overhead.
2019-06-25 09:06:26 +01:00
Hanno Becker
180f7bf60b Add compile-time option to remove legacy CRT fields 2019-06-25 09:06:26 +01:00
Hanno Becker
b6c39fca5c Add parsing cache to mbedtls_x509_crt
This commit replaces the dummy implementation of the CRT acquire/release
framework by a cache-based implementation which remembers frame and PK
associated to a CRT across multiple `acquire/release` pairs.
2019-06-25 09:06:26 +01:00
Hanno Becker
73cd8d8adc Make use of acquire/release in ssl_parse_certificate_verify() 2019-06-25 09:06:26 +01:00
Hanno Becker
2fefa4845d Make use of acquire/release in ssl_parse_server_key_exchange() 2019-06-25 09:06:26 +01:00
Hanno Becker
39ae65cf73 Make use of acquire/release in ssl_get_ecdh_params_from_cert() 2019-06-25 09:06:26 +01:00
Hanno Becker
0c1681685c Make use of acquire/release in client-side ssl_write_encrypted_pms() 2019-06-25 09:06:26 +01:00
Hanno Becker
232f8faf00 Make use of CRT acquire/release in ssl_write_certificate_request() 2019-06-25 09:06:26 +01:00
Hanno Becker
30649f7a17 Make use of CRT acquire/release in server-side ssl_pick_cert() 2019-06-25 09:06:26 +01:00
Hanno Becker
8c13ee615f Make use of CRT acquire/release in ssl_parse_certificate_verify()
Access the peer's PK through the PK acquire/release API only.

Care has to be taken not to accidentally overwrite the return
value `ret` from the CRT chain verification.
2019-06-25 09:06:26 +01:00
Hanno Becker
6cb5f86dac Make use of CRT acquire/release in mbedtls_debug_print_crt() 2019-06-25 09:06:26 +01:00
Hanno Becker
5c03058bbc Make use of CRT acquire/release in test_suite_x509parse suite 2019-06-25 09:06:26 +01:00
Hanno Becker
8723336831 Make use of CRT acquire/release in x509_crt_verify_restartable 2019-06-25 09:06:26 +01:00
Hanno Becker
082435c011 Make use of CRT acquire/release in x509_crt_verify_name()
This commit modifies the static function `x509_crt_verify_name()` to
use the acquire/release API to access the given CRTs `subject` field.

This function is solely called from the beginning of the CRT chain
verification routine, which also needs to access the child's CRT frame.
It should therefore be considered - for a later commit - to collapse
the two acquire/release pairs to one, thereby saving some code.
2019-06-25 09:06:26 +01:00
Hanno Becker
58c35646df Make use of CRT acquire/release in CRT chain verification #2 2019-06-25 09:06:26 +01:00
Hanno Becker
bb26613d32 Make use of CRT acquire/release in x509_crt_verifycrl() 2019-06-25 09:06:26 +01:00
Hanno Becker
79ae5b68e7 Make use of CRT acquire/release in x509_serial_is_revoked() 2019-06-25 09:06:26 +01:00
Hanno Becker
e9718b451a Make use of CRT acquire/release in ExtKeyUsage checking 2019-06-25 09:06:26 +01:00
Hanno Becker
371e0e4573 Determine whether CRT is initialized or not through raw data pointer
Previously, `mbedtls_x509_crt_der_internal()` used the `version` field
(which is `0` after initialization but strictly greater than 0 once a
CRT has successfully been parsed) to determine whether an
`mbedtls_x509_crt` instance had already been setup.

Preparating for the removal of `version` from the structure, this
commit modifies the code to instead peek at the raw data pointer,
which is NULL as long as the CRT structure hasn't been setup with a CRT,
and will be kept in the new CRT structure.
2019-06-25 09:06:26 +01:00
Hanno Becker
4f869eda64 Make use of CRT acquire/release in mbedtls_x509_crt_info()
This commit adapts `mbedtls_x509_crt_info()` to no longer access
structure fields from `mbedtls_x509_crt` directly, but to instead
query for a `mbedtls_x509_crt_frame` and `mbedtls_pk_context` and
use these to extract the required CRT information.
2019-06-25 09:06:26 +01:00
Hanno Becker
343fec08ad Add version of MBEDTLS_X509_SAFE_SNPRINTF supporting cleanup section
This will be needed in debugging functions that maintain heap
allocated state, and which hence needs to be freed in case an
`snprintf()` call fails.
2019-06-25 09:06:26 +01:00
Hanno Becker
45eedf1ace Make use of CRT acquire/release in mbedtls_x509_crt_check_key_usage 2019-06-25 09:06:26 +01:00
Hanno Becker
43bf900018 Make use of CRT acquire/release searching for issuer in CRT verif.
This commit continues rewriting the CRT chain verification to use
the new acquire/release framework for CRTs. Specifically, it replaces
all member accesses of the current _parent_ CRT by accesses to the
respective frame.
2019-06-25 09:06:26 +01:00
Hanno Becker
e449e2d846 Make use of CRT acquire/release for X.509 CRT signature checking 2019-06-25 09:06:26 +01:00
Hanno Becker
5299cf87d4 Add structure holding X.509 CRT signature information
This commit introduces an internal structure `mbedtls_x509_crt_sig_info`
containing all information that has to be kept from a child CRT when searching
for a potential parent:
- The issuer name
- The signature type
- The signature
- The hash of the CRT

The structure can be obtained from a CRT frame via `x509_crt_get_sig_info()`
and freed via `x509_crt_free_sig_info()`.

The purpose of this is to reduce the amount of RAM used during CRT
chain verification; once we've extracted the signature info structure
from the current child CRT, we can free all cached data for that CRT
(frame and PK) before searching for a suitable parent. This way, there
will ultimately not be more than one frame needed at a single point
during the verification.
2019-06-25 09:06:26 +01:00
Hanno Becker
a788cab46d Check validity of potential parent before checking signature
The function `x509_crt_find_parent_in()` traverses a list of CRTs
to find a potential parent to a given CRT. So far, the logic was
the following: For each candidate,
- check basic parenting skills (mostly name match)
- verify signature
- verify validity
This order is insuitable for the new acquire/release layer of
indirection when dealing with CRTs, because we either have to
query the candidate's CRT frame twice, or query frame and PK
simultaneously.

This commit moves the validity check to the beginning of the
routine to allow querying for the frame and then for the PK.

The entry point for restartable ECC needs to be moved for that
to not forget the validity-flag while pausing ECC computations.
2019-06-25 09:06:26 +01:00
Hanno Becker
1e0677acc1 Make use of CRT acquire/release for child in CRT chain verification
During CRT verification, `x509_crt_check_signature()` checks whether a
candidate parent CRT correctly signs the current child CRT.

This commit rewrites this function to use the new acquire/release
framework for using CRTs.
2019-06-25 09:06:26 +01:00
Hanno Becker
337088aa2d Add internal API for acquire/release of CRT frames and PKs
The goal of the subsequent commits is to remove all direct uses
of the existing `mbedtls_x509_crt` apart from the `raw` buffer
and the linked list `next` pointer.

The approach is the following: Whenever a code-path needs to inspect
a CRT, it can request a frame for the CRT through the API
`x509_crt_frame_acquire()`. On success, this function returns a pointer
to a frame structure for the CRT (the origin of which is flexible and
need not concern the caller) that can be used to inspect the desired
fields. Once done, the caller hands back the frame through an explicit
call to `x509_crt_frame_release()`.

This commit also adds an inefficient dummy implementation for
`x509_crt_frame_acquire()` which always allocates a new
`mbedtls_x509_crt_frame` structure on the heap and parses it
from the raw data underlying the CRT. This will change in subsequent
commits, but it constitutes a valid implementation to test against.

Ultimately, `x509_crt_frame_acquire()` is to compute a frame for the
given CRT only once, and cache it for subsequent calls.

The need for `x509_crt_frame_release()` is the following: When
implementing `x509_crt_frame_acquire()` through a flushable cache
as indicated above, it must be ensured that no thread destroys
a cached frame structure for the time it is needed by another
thread. The `acquire/release` pair allows to explicitly delimit
the lifetime requirements for the returned frame structure.
The frame pointer must not be used after the `release` call anymore;
and in fact, the dummy implementation shows that it would
immediately lead to a memory failure.

Analogously to `x509_crt_frame_{acquire|release}()`, there's also
`x509_crt_pk_{acquire|release}()` which allows to acquire/release
a PK context setup from the public key contained within the CRT.
2019-06-25 09:06:26 +01:00
Hanno Becker
21f5567571 Introduce X.509 CRT frame structure
This commit restructures the parsing of X.509 CRTs in the following way:

First, it introduces a 'frame' structure `mbedtls_x509_crt_frame`, which
contains pointers to some structured fields of a CRT as well as copies of
primitive fields. For example, there's a pointer-length pair delimiting the raw
public key data in the CRT, but there's a C-uint8 to store the CRT version
(not a pointer-length pair delimiting the ASN.1 structure holding the version).

Setting up a frame from a raw CRT buffer does not require any memory outside
of the frame structure itself; it's just attaches a 'template' to the buffer
that allows to inspect the structured parts of the CRT afterwards.

Note that the frame structure does not correspond to a particular ASN.1
structure; for example, it contains pointers to delimit the three parts
of a CRT (TBS, SignatureAlgorithm, Signature), but also pointers to the
fields of the TBS, and pointers into the Extensions substructure of the TBS.

Further, the commit introduces an internal function `x509_crt_parse_frame()`
which sets up a frame from a raw CRT buffer, as well as several small helper
functions which help setting up the more complex structures (Subject, Issuer, PK)
from the frame.

These functions are then put to use to rewrite the existing parsing function
`mbedtls_x509_crt_parse_der_core()` by setting up a CRT frame from the input
buffer, residing on the stack, and afterwards copying the respective fields
to the actual `mbedtls_x509_crt` structure and performing the deeper parsing
through the various helper functions.
2019-06-25 09:06:26 +01:00
Hanno Becker
c6573a27a1 Convert X.509 name buffer to linked list via name traversal callback 2019-06-25 09:06:26 +01:00
Hanno Becker
6b37812a45 Add next_merged field to X.509 name comparison abort callback 2019-06-25 09:06:26 +01:00
Hanno Becker
10e6b9b2b5 Move point of re-entry for restartable X.509 verification 2019-06-25 09:06:26 +01:00
Hanno Becker
b59d3f1692 Add single function to parse ASN.1 AlgorithmIdentifier to x509.c 2019-06-25 09:06:26 +01:00
Hanno Becker
1898b68f09 Allow NULL pointer in mbedtls_x509_get_sig_alg if params not needed
Also, set `sig_opts` pointer to `NULL` if no signature algorithm
parameters are given (to reflect exactly that).
2019-06-25 09:06:26 +01:00
Hanno Becker
c84fd1cd95 Check whether CRT is revoked by passing its serial number only
CRLs reference revoked CRTs through their serial number only.
2019-06-25 09:06:26 +01:00
Hanno Becker
b3def1d341 Move length check into mbedtls_x509_memcasecmp()
At every occasion where we're using `mbedtls_x509_memcasecmp()` we're
checking that the two buffer lengths coincide before making the call.

This commit saves a few bytes of code by moving this length check
to `mbedtls_x509_memcasecmp()`.
2019-06-25 09:06:26 +01:00
Hanno Becker
f1b39bf18c Implement v3 Extension parsing through ASN.1 SEQUENCE OF traversal
This commit rewrites the v3 ext parsing routine `x509_crt_get_ext_cb()`
in terms of the generic ASN.1 SEQUENCE traversal routine.
2019-06-25 09:06:26 +01:00
Hanno Becker
c7c638eddd Implement ExtKeyUsage traversal via ASN.1 SEQUENCE OF traversal
This commit re-implements the `ExtendedKeyUsage` traversal
routine in terms of the generic ASN.1 SEQUENCE traversal routine.
2019-06-25 09:06:26 +01:00
Hanno Becker
90b9408dd0 Implement SubjectAltName traversal via ASN.1 SEQUENCE OF traversal
This commit re-implements the `SubjectAlternativeName` traversal
routine in terms of the generic ASN.1 SEQUENCE traversal routine.
2019-06-25 09:06:26 +01:00
Hanno Becker
8730610ae0 Introduce ASN.1 API for traversing ASN.1 SEQUENCEs
This commit adds a new function `mbedtls_asn1_traverse_sequence_of()`
which traverses an ASN.1 SEQUENCE and calls a user-provided callback
for each entry.

It allows to put the following constraints on the tags allowed
in the SEQUENCE:
- A tag mask and mandatory tag value w.r.t. that mask.
  A non-matching tag leads to an MBEDTLS_ERR_ASN1_UNEXPECTED_TAG error.
  For example, it the mask if 0xFF, this means that only
  a single tag will be allowed in the SEQUENCE.
- A tag mask and optional tag value w.r.t. that mask.
  A non-matching tag is silently ignored.

The main use for this flexibility is the traversal of the
`SubjectAlternativeNames` extension, where some parts of the
tag are fixed but some are flexible to indicate which type
of name the entry describes.
2019-06-25 09:06:26 +01:00
Hanno Becker
5984d30f4b Make use of cb to build linked list presentation of SubjectAltName 2019-06-25 09:06:26 +01:00
Hanno Becker
ad46219a88 Add cb to build dynamic linked list representation of SubjectAltName
This commit adds a callback for use with `x509_subject_alt_name_traverse()`
which builds the legacy dynamically allocated linked list presentation
of the `SubjectAlternativeNames` extension while traversing the raw data.
2019-06-25 09:06:26 +01:00
Hanno Becker
da410828f4 Add callback to search through SubjectAltNames extension
The current CN name verification x509_crt_verify_name() traverses
the dynamically allocated linked list presentation of the subject
alternative name extension, searching for an alternative name that
matches the desired hostname configured by the application.

Eventually, we want to remove this dynamically allocated linked list
for the benefit of reduced code size and RAM usage, and hence need to
rewrite x509_crt_verify_name() in a way that builds on the raw ASN.1
buffer holding the SubjectAlternativeNames extension.

This commit does this by using the existing SubjectAlternativeNames
traversal routine x509_subject_alt_name_traverse(), passing to it a
callback which compares the current alternative name component to the
desired hostname configured by the application.
2019-06-25 09:06:26 +01:00
Hanno Becker
2c6cc045c2 Add function to traverse raw SubjectAltName extension
This commit adds a new function `x509_subject_alt_name_traverse()`
which allows to traverse the raw ASN.1 data of a `SubjectAlternativeNames`
extension.

The `SubjectAlternativeNames` extension needs to be traversed
in the following situations:
1 Initial traversal to check well-formedness of ASN.1 data
2 Traversal to check for a particular name component
3 Building the legacy linked list presentation

Analogously to how multiple tasks related to X.509 name comparison
are implemented through the workhorse `mbedtlS_x509_name_cmp_raw()`,
the new function `x509_subject_alt_name_traverse()` allows to pass
an arbitrary callback which is called on any component of the
`SubjectAlternativeNames` extension found. This way, the above
three tasks can be implemented by passing
1 a NULL callback,
2 a name comparison callback
3 a linked list building callback.
2019-06-25 09:06:26 +01:00
Hanno Becker
2492622289 Pass raw data to x509_check_wildcard() and x509_crt_check_cn()
In preparation for rewriting the `SubjectAlternativeName` search routine
to use raw ASN.1 data, this commit changes `x509_check_wildcard()` and
`x509_check_cn()`, responsible for checking whether a name matches a
wildcard pattern, to take a raw buffer pointer and length as parameters
instead of an `mbedtls_x509_buf` instance.
2019-06-25 09:06:26 +01:00
Hanno Becker
ded167e18c Add raw buffer holding SubjectAlternativeName ext to CRT structure
This is analogous to a previous commit for the `ExtendedKeyUsage`
extension: We aim at not using dynamically allocated linked lists
to represent the components of the `SubjectAlternativeName` extension,
but to traverse the raw ASN.1 data when needed.

This commit adds a field to `mbedtls_x509_crt` containing the raw
ASN.1 buffer bounds of the `SubjectAlternativeNames` extension.
2019-06-25 09:06:26 +01:00
Hanno Becker
e1956af057 Check for extended key usage by traversing raw extension data
This commit re-implements `mbedtls_x509_crt_check_extended_key_usage()`
to not use the dynamically allocated linked list presentation of the
`ExtendedKeyUsage` but to search for the required usage by traversing
the raw ASN.1 data.
2019-06-25 09:06:26 +01:00
Hanno Becker
7ec9c368f1 Add buffer holding raw ExtKeyUsage extension data to CRT struct
The previous commits replace the use of dynamically allocated linked lists
for X.509 name inspection. This commit is the first in a series which attempts
the same for the `ExtendedKeyUsage` extension. So far, when a CRT is parsed,
the extension is traversed and converted into a dynamically allocated linked
list, which is then search through whenever the usage of a CRT needs to be
checked through `mbedtls_x509_check_extended_key_usage()`.

As a first step, this commit introduces a raw buffer holding the bounds
of the `ExtendedKeyUsage` extension to the `mbedtls_x509_crt` structure.
2019-06-25 09:06:26 +01:00
Hanno Becker
8b543b3ca8 Make use of abort condition callback in CN comparison
The previous CN name comparison function x509_crt_verify_name()
traversed the dynamically allocated linked list presentation of
the CRT's subject, comparing each entry to the desired hostname
configured by the application code.

Eventually, we want to get rid of the linked list presentation of
the CRT's subject to save both code and RAM usage, and hence need
to rewrite the CN verification routine in a way that builds on the
raw ASN.1 subject data only.

In order to avoid duplicating the code for the parsing of the nested
ASN.1 name structure, this commit performs the name search by using
the existing name traversal function mbedtls_x509_name_cmp_raw(),
passing to it a callback which checks whether the current name
component matches the desired hostname.
2019-06-25 09:06:26 +01:00
Hanno Becker
67284cce00 Add abort condition callback to mbedtls_x509_name_cmp_raw()
There are three operations that need to be performed on an X.509 name:
1 Initial traversal to check well-formedness of the ASN.1 structure.
2 Comparison between two X.509 name sequences.
3 Checking whether an X.509 name matches a client's ServerName request.

Each of these tasks involves traversing the nested ASN.1 structure,
In the interest of saving code, we aim to provide a single function
which can perform all of the above tasks.

The existing comparison function is already suitable not only for task 2,
but also for 1: One can simply pass two equal ASN.1 name buffers, in which
case the function will succeed if and only if that buffer is a well-formed
ASN.1 name.

This commit further adds a callback to `mbedtls_x509_name_cmp_raw()` which
is called after each successful step in the simultaneous name traversal and
comparison; it may perform any operation on the current name and potentially
signal that the comparison should be aborted.

With that, task 3 can be implemented by passing equal names and a callback
which aborts as soon as it finds the desired name component.
2019-06-25 09:06:26 +01:00
Hanno Becker
7dee12a38c Make use of raw comparison function in CRT verification
This commit replaces the previous calls to `mbedtls_x509_name_cmp()`
during CRT verification (to match child and parent, to check whether
a CRT is self-issued, and to match CRLs and CAs) by calls to the new
`mbedtls_x509_name_cmp_raw()` using the raw ASN.1 data; it passes the
raw buffers introduced in the last commits.

The previous name comparison function mbedtls_x509_name_cmp() is now
both unused and unneeded, and is removed.
2019-06-25 09:06:26 +01:00
Hanno Becker
f8a42862b7 Add buffers with raw issuer/subject data to CRT structure 2019-06-25 09:06:26 +01:00
Hanno Becker
a632e3638c Add buffer with raw issuer data to CRL structure
To make use of the X.509 name comparison function based on raw
ASN.1 data that was introduced in the previous commit, this commit
adds an ASN.1 buffer field `issuer_raw_no_hdr` to `mbedtls_x509_crl`
which delimits the raw contents of the CRLs `Issuer` field.

The previous field `issuer_raw` isn't suitable for that because
it includes the ASN.1 header.
2019-06-25 09:06:26 +01:00
Hanno Becker
a3a2ca1333 Provide X.509 name comparison based on raw ASN.1 data
This commit provides a new function `mbedtls_x509_name_cmp_raw()`
to x509.c for comparing to X.509 names by traversing the raw ASN.1
data (as opposed to using the dynamically allocated linked list
of `mbedtls_x509_name` structures). It has external linkage because
it will be needed in `x509_crt` and `x509_crl`, but is marked
internal and hence not part of the public API.
2019-06-25 09:06:26 +01:00
Hanno Becker
88de342c95 Move x509_name_cmp() from x509_crt.c to x509.c
This is to prepare a subsequent rewrite of `x509_name_cmp()` in terms
of the X.509 name traversal helper `x509_set_sequence_iterate()`
from `x509.c`.
2019-06-25 09:06:26 +01:00
Hanno Becker
83cd8676fa Remove sig_oid parameter from mbedtls_x509_sig_alg_gets()
The function `mbedtls_x509_sig_alg_gets()` previously needed the
raw ASN.1 OID string even though it is implicit in the PK and MD
parameters.

This commit modifies `mbedtls_x509_sig_alg_gets()` to infer the OID
and remove it from the parameters.

This will be needed for the new X.509 CRT structure which will
likely not store the signature OID.

Care has to be taken to handle the case of RSASSA-PSS correctly,
where the hash algorithm in the OID list is set to MBEDTLS_MD_NONE
because it's only determined by the algorithm parameters.
2019-06-25 09:06:26 +01:00
Hanno Becker
f226998fa2 Reduce code-size of mbedtls_asn1_get_sequence_of()
Reduce nesting of branches and remove unnecessary check at the end
of the routine.
2019-06-25 09:00:25 +01:00
Hanno Becker
b5419867cd Reduce code-size of mbedtls_asn1_get_alg()
The previous code
- checked that at least 1 byte of ASN.1 tag data is available,
- read and stored that ASN.1 tag,
- called the ASN.1 parsing function, part of which is checking
  that enough space is available and that the ASN.1 tag matches
  the expected value MBEDTLS_ASN1_OID.

Since the ASN.1 parsing function includes bounds checks,
this can be streamlined to:
- call the ASN.1 parsing function directly,
- on success, store MBEDTLS_ASN1_OID in the tag field.

This commit applies this simplification to mbedtls_asn1_get_alg().
2019-06-25 09:00:25 +01:00
Hanno Becker
30cb1ac23e Reduce code-size of mbedtls_x509_get_name()
Consider the following code-template:

   int beef();

   static int foo()
   {
        /* ... */
        ret = beef();
        if( ret != 0 )
           return( ret + HIGH_LEVEL );
        /* ... */
   }

   int bar()
   {
       /* ... */
       ret = foo();
       if( ret != 0 )
          ...
       /* ... */
   }

This leads to slightly larger code than expected, because when the
compiler inlines foo() into bar(), the sequence of return sequences
cannot be squashed, because compiler might not have knowledge that
the wrapping `ret + HIGH_LEVEL` of the return value of beef() doesn't
lead to foo() returning 0.

This can be avoided by performing error code wrapping in nested
functions calls at the top of the call chain.

This commit applies this slight optimization to mbedtls_x509_get_name().

It also moves various return statements into a single exit section,
again with the intend to save code.
2019-06-25 09:00:25 +01:00
Hanno Becker
3470d592ce Simplify implementation of mbedtls_x509_get_name()
X.509 names in ASN.1 are encoded as ASN.1 SEQUENCEs of ASN.1 SETs
of Attribute-Value pairs, one for each component in the name. (For
example, there could be an Attribute-Value pair for "DN=www.mbedtls.org").

So far, `mbedtls_x509_get_name()` parsed such names by two nested
loops, the outer one traversing the outer ASN.1 SEQUENCE and the
inner one the ASN.1 SETs.

This commit introduces a helper function `x509_set_sequence_iterate()`
which implements an iterator through an ASN.1 name buffer; the state
of the iterator is a triple consisting of
- the current read pointer
- the end of the current SET
- the end of the name buffer
The iteration step reads a new SET if the current read pointer has
reached the end of the current SET, and afterwards reads the next
AttributeValue pair.
This way, iteration through the X.509 name data can be implemented
in a single loop, which increases readability and slightly reduces
the code-size.
2019-06-25 09:00:25 +01:00
Hanno Becker
b40dc58a83 Introduce a helper macro to check for ASN.1 string tags
This commit introduces a macro `MBEDTLS_ASN1_IS_STRING_TAG`
that can be used to check if an ASN.1 tag is among the list
of string tags:
- MBEDTLS_ASN1_BMP_STRING
- MBEDTLS_ASN1_UTF8_STRING
- MBEDTLS_ASN1_T61_STRING
- MBEDTLS_ASN1_IA5_STRING
- MBEDTLS_ASN1_UNIVERSAL_STRING
- MBEDTLS_ASN1_PRINTABLE_STRING
- MBEDTLS_ASN1_BIT_STRING
2019-06-25 09:00:25 +01:00
Hanno Becker
ace04a6dc3 Move bounds check into ASN.1 parsing function
`x509_get_attr_type_value()` checks for the presence of a tag byte
and reads and stores it before calling `mbedtls_asn1_get_tag()` which
fails if either the tag byte is not present or not as expected. Therefore,
the manual check can be removed and left to `mbedtls_asn1_get_tag()`, and
the tag can be hardcoded after the call succeeded. This saves a few bytes
of code.
2019-06-25 09:00:25 +01:00
Hanno Becker
74b89f6051 Use private key to check suitability of PK type when picking srv CRT
The server-side routine `ssl_pick_cert()` is responsible for
picking a suitable CRT from the list of CRTs configured on the
server. For that, it previously used the public key context
from the certificate to check whether its type (including the
curve type for ECC keys) suits the ciphersuite and the client's
preferences.

This commit changes the code to instead use the PK context
holding the corresponding private key. For inferring the type
of the key, this makes no difference, and it removes a PK-from-CRT
extraction step which, if CRTs are stored raw, is costly in terms
of computation and memory: CRTs need to be parsed, and memory needs
to be allocated for the PK context.
2019-06-25 09:00:25 +01:00
Hanno Becker
81bb4d0378 Simplify server-side ssl_decrypt_encrypted_pms()
The server-side routine `ssl_decrypt_encrypted_pms()` is
responsible for decrypting the RSA-encrypted PMS in case of
an RSA-based ciphersuite.

Previously, the code checked that the length of the PMS sent
by the client matches the bit length of the RSA key. This commit
removes this check -- thereby removing the need to access the
server's own CRT -- because the RSA decryption routine performs
this check itself, too.
2019-06-25 09:00:25 +01:00
Hanno Becker
cd03bb2048 Introduce helper functions to free X.509 names and sequences
`mbedtls_x509_name` and `mbedtls_x509_sequence` are dynamically allocated
linked lists that need a loop to free properly. Introduce a static helper
function to do that and use it in `mbedtls_x509_crt_free()`, where the
CRT's issuer and subject names (of type `mbedtls_x509_name`) and the
SubjectAlternativeName and ExtendedKeyUsage extensions (of type
`mbedtls_x509_sequence`) need freeing. Increases code-clarity and saves
a few bytes of flash.
2019-06-25 09:00:25 +01:00
Hanno Becker
7f376f4ece Allow compile-time configuration of DTLS anti replay
Introduce MBEDTLS_SSL_CONF_ANTI_REPLAY to allow configuring
the use/nonuse of DTLS anti replay protection at compile-time.

Impact on code-size, measured with
> ./scripts/baremetal.sh --rom --gcc --armc5 --armc6

|  | GCC | ARMC5 | ARMC6 |
| --- | --- | --- | --- |
| `libmbedtls.a` before | 23559 | 24089 | 27921 |
| `libmbedtls.a` after  | 23511 | 24049 | 27903 |
| gain in Bytes | 48 | 40 | 18 |
2019-06-25 08:43:31 +01:00
Hanno Becker
af5ab918d9 Detect mismatching compile-time and cmd line config in ssl-opt.sh 2019-06-25 08:42:20 +01:00
Hanno Becker
aa9fc6dd33 Update query_config.c 2019-06-25 08:42:20 +01:00
Hanno Becker
ab1ce76682 Mention possibility of hardcoding SSL config in ssl.h 2019-06-25 08:42:20 +01:00
Hanno Becker
f765ce617f Remove ExtendedMS configuration API if hardcoded at compile-time
If the ExtendedMasterSecret extension is configured at compile-time
by setting MBEDTLS_SSL_CONF_EXTENDED_MASTER_SECRET and/or
MBEDTLS_SSL_CONF_ENFORCE_EXTENDED_MASTER_SECRET, the runtime
configuration APIs mbedtls_ssl_conf_extended_master_secret()
and mbedtls_ssl_conf_extended_master_secret_enforce() must
either be removed or modified to take no effect (or at most
check that the runtime value matches the hardcoded one, but
that would undermine the code-size benefits the hardcoding
is supposed to bring in the first place).

Previously, the API was kept but modified to have no effect.
While convenient for us because we don't have to adapt example
applications, this comes at the danger of users calling the runtime
configuration API, forgetting that the respective fields are
potentially already hardcoded at compile-time - and hence silently
using a configuration they don't intend to use.

This commit changes the approach to removing the configuration
API in case the respective field is hardcoded at compile-time,
and exemplifies it in the only case implemented so far, namely
the configuration of the ExtendedMasterSecret extension.

It adapts ssl_client2 and ssl_server2 by omitting the call to
the corresponding API if MBEDTLS_SSL_CONF_XXX are defined and
removing the command line parameters for the runtime configuration
of the ExtendedMasterSecret extension.
2019-06-25 08:42:20 +01:00
Hanno Becker
57e72c750c Move getter functions for SSL configuration to ssl_internal.h 2019-06-25 08:42:20 +01:00
Hanno Becker
4c4a2e1a0b Don't break func'def after linkage type, fixing check-names.sh 2019-06-25 08:42:20 +01:00
Hanno Becker
1ab322bb51 Remove extended_ms field from HS param if ExtendedMS enforced 2019-06-25 08:42:20 +01:00
Hanno Becker
a49ec56f51 Introduce getter function for extended_ms field in HS struct 2019-06-25 08:42:20 +01:00
Hanno Becker
3010d55a3b Introduce helper macro indicating if use of ExtendedMS is enforced 2019-06-25 08:42:20 +01:00
Hanno Becker
03b64fa6c1 Rearrange ExtendedMasterSecret parsing logic
`mbedtls_ssl_handshake_params::extended_ms` holds the state of the
ExtendedMasterSecret extension in the current handshake. Initially
set to 'disabled' for both client and server,
- the client sets it to 'enabled' as soon as it finds the ExtendedMS
  extension in the `ServerHello` and it has advertised that extension
  in its ClientHello,
- the server sets it to 'enabled' as soon as it finds the ExtendedMS
  extension in the `ClientHello` and is willing to advertise is in its
  `ServerHello`.

This commit slightly restructures this logic in prepraration for the
removal of `mbedtls_ssl_handshake_params::extended_ms` in case both
the use and the enforcement of the ExtendedMasterSecret extension have
been fixed at compile-time. Namely, in this case there is no need for
the `extended_ms` field in the handshake structure, as the ExtendedMS
must be in use if the handshake progresses beyond the Hello stage.

Paving the way for the removal of mbedtls_ssl_handshake_params::extended_ms
this commit introduces a temporary variable tracking the presence of the
ExtendedMS extension in the ClientHello/ServerHello messages, leaving
the derivation of `extended_ms` (and potential failure) to the end of
the parsing routine.
2019-06-25 08:42:20 +01:00
Hanno Becker
aabbb582eb Exemplify harcoding SSL config at compile-time in example of ExtMS
This commit is the first in a series demonstrating how code-size
can be reduced by hardcoding parts of the SSL configuration at
compile-time, focusing on the example of the configuration of
the ExtendedMasterSecret extension.

The flexibility of an SSL configuration defined a runtime vs.
compile-time is necessary for the use of Mbed TLS as a
dynamically linked library, but is undesirable in constrained
environments because it introduces the following overhead:
- Definition of SSL configuration API (code-size overhead)
  (and on the application-side: The API needs to be called)
- Additional fields in the SSL configuration (RAM overhead,
  and potentially code-size overhead if structures grow
  beyond immediate-offset bounds).
- Dereferencing is needed to obtain configuration settings.
- Code contains branches and potentially additional structure
  fields to distinguish between different configurations.

Considering the example of the ExtendedMasterSecret extension,
this instantiates as follows:
- mbedtls_ssl_conf_extended_master_secret() and
  mbedtls_ssl_conf_extended_master_secret_enforced()
  are introduced to configure the ExtendedMasterSecret extension.
- mbedtls_ssl_config contains bitflags `extended_ms` and
  `enforce_extended_master_secret` reflecting the runtime
  configuration of the ExtendedMasterSecret extension.
- Whenever we need to access these fields, we need a chain
  of dereferences `ssl->conf->extended_ms`.
- Determining whether Client/Server should write the
  ExtendedMasterSecret extension needs a branch
  depending on `extended_ms`, and the state of the
  ExtendedMasterSecret negotiation needs to be stored in a new
  handshake-local variable mbedtls_ssl_handshake_params::extended_ms.
  Finally (that's the point of ExtendedMasterSecret) key derivation
  depends on this handshake-local state of ExtendedMasterSecret.

All this is unnecessary if it is known at compile-time that the
ExtendedMasterSecret extension is used and enforced:
- No API calls are necessary because the configuration is fixed
  at compile-time.
- No SSL config fields are necessary because there are corresponding
  compile-time constants instead.
- Accordingly, no dereferences for field accesses are necessary,
  and these accesses can instead be replaced by the corresponding
  compile-time constants.
- Branches can be eliminated at compile-time because the compiler
  knows the configuration. Also, specifically for the ExtendedMasterSecret
  extension, the field `extended_ms` in the handshake structure
  is unnecessary, because we can fail immediately during the Hello-
  stage of the handshake if the ExtendedMasterSecret extension
  is not negotiated; accordingly, the non-ExtendedMS code-path
  can be eliminated from the key derivation logic.

A way needs to be found to allow fixing parts of the SSL configuration
at compile-time which removes this overhead in case it is used,
while at the same time maintaining readability and backwards
compatibility.

This commit proposes the following approach:

From the user perspective, for aspect of the SSL configuration
mbedtls_ssl_config that should be configurable at compile-time,
introduce a compile-time option MBEDTLS_SSL_CONF_FIELD_NAME.
If this option is not defined, the field is kept and configurable
at runtime as usual. If the option is defined, the field is logically
forced to the value of the option at compile time.

Internally, read-access to fields in the SSL configuration which are
configurable at compile-time gets replaced by new `static inline` getter
functions which evaluate to the corresponding field access or to the
constant MBEDTLS_SSL_CONF_FIELD_NAME, depending on whether the latter
is defined or not.

Write-access to fields which are configurable at compile-time needs
to be removed: Specifically, the corresponding API itself either
needs to be removed or replaced by a stub function without effect.
This commit takes the latter approach, which has the benefit of
not requiring any change on the example applications, but introducing
the risk of mismatching API calls and compile-time configuration,
in case a user doesn't correctly keep track of which parts of the
configuration have been fixed at compile-time, and which haven't.
Write-access for the purpose of setting defaults is simply omitted.
2019-06-25 08:42:20 +01:00
Manuel Pégourié-Gonnard
393338ca78
Merge pull request #586 from ARMmbed/remove_peer_crt_after_handshake_no_digest-baremetal
[Baremetal] Don't store peer CRT digest if renegotiation is disabled
2019-06-24 18:12:00 +02:00
Manuel Pégourié-Gonnard
79cf74a95f
Merge pull request #583 from ARMmbed/remove_peer_crt_after_handshake-baremetal
[Baremetal] Allow removal of peer certificate to reduce RAM usage
2019-06-24 18:11:46 +02:00
Manuel Pégourié-Gonnard
8dcd80ec5c
Merge pull request #578 from ARMmbed/x509_parse_bf-baremetal
[Baremetal] Enhance X.509 CRT negative parsing tests
2019-06-24 18:08:33 +02:00
Manuel Pégourié-Gonnard
cc3b7ccb04
Merge pull request #579 from Patater/bm-dont-use-non-existent-encrypt-then-mac
[Baremetal] ssl: Don't access non-existent encrypt_then_mac field
2019-06-24 18:06:53 +02:00
Hanno Becker
e256f7c9ae Add test for !KEEP_PEER_CERTIFICATE + !RENEGOTIAITON to all.sh 2019-06-19 16:56:51 +01:00
Hanno Becker
5882dd0856 Remove CRT digest from SSL session if !RENEGO + !KEEP_PEER_CERT
If `MBEDTLS_SSL_KEEP_PEER_CERTIFICATE` is not set, `mbedtls_ssl_session`
contains the digest of the peer's certificate for the sole purpose of
detecting a CRT change on renegotiation. Hence, it is not needed if
renegotiation is disabled.

This commit removes the `peer_cert_digest` fields (and friends) from
`mbedtls_ssl_session` if
   `!MBEDTLS_SSL_KEEP_PEER_CERTIFICATE + !MBEDTLS_SSL_RENEGOTIATION`,
which is a sensible configuration for constrained devices.

Apart from straightforward replacements of
   `if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)`
by
   `if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) && \
        defined(MBEDTLS_SSL_RENEGOTIATION)`,
there's one notable change: On the server-side, the CertificateVerify
parsing function is a no-op if the client hasn't sent a certificate.
So far, this was determined by either looking at the peer CRT or the
peer CRT digest in the SSL session structure (depending on the setting
of `MBEDTLS_SSL_KEEP_PEER_CERTIFICATE`), which now no longer works if
`MBEDTLS_SSL_KEEP_PEER_CERTIFICATE` is unset. Instead, this function
now checks whether the temporary copy of the peer's public key within
the handshake structure is initialized or not (which is also a
beneficial simplification in its own right, because the pubkey is
all the function needs anyway).
2019-06-19 16:56:51 +01:00
Hanno Becker
0528f82fa9 Clarify documentation of serialized session format 2019-06-19 14:59:42 +01:00
Hanno Becker
d972f005bf Use consistent error messages in check_config.h 2019-06-19 14:59:42 +01:00
Hanno Becker
17daaa5cc6 Move return statement in ssl_srv_check_client_no_crt_notification
The previous placing of the return statement made it look like there
are configurations for which no return statement is emitted; while
that's not true (if this function is used, at least some version of
TLS must be enabled), it's still clearer to move the failing return
statement to outside of all preprocessor guards.
2019-06-19 14:59:42 +01:00
Hanno Becker
2326d20361 Validate consistency of certificate hash type and length in session 2019-06-19 14:59:42 +01:00
Hanno Becker
fd5dc8ae07 Fix unused variable warning in ssl_parse_certificate_coordinate()
This was triggered in client-only builds.
2019-06-19 14:59:42 +01:00
Hanno Becker
488c8dee47 Add missing compile time guard in ssl_client2 2019-06-19 14:59:42 +01:00
Hanno Becker
b6f7241741 Update programs/ssl/query_config.c 2019-06-19 14:59:42 +01:00
Hanno Becker
b7fab76890 ssl_client2: Reset peer CRT info string on reconnect 2019-06-19 14:59:42 +01:00
Hanno Becker
c39e23ebb6 Add further debug statements on assertion failures 2019-06-19 14:59:41 +01:00
Hanno Becker
42de8f8a42 Fix typo in documentation of ssl_parse_certificate_chain() 2019-06-19 14:59:41 +01:00
Hanno Becker
e9839c001b Add debug output in case of assertion failure 2019-06-19 14:59:41 +01:00
Hanno Becker
2984bd2543 Add config sanity check for !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE 2019-06-19 14:59:41 +01:00
Hanno Becker
f9ca30d042 ssl_client2: Zeroize peer CRT info buffer when reconnecting 2019-06-19 14:59:41 +01:00
Hanno Becker
890d7ee4cb Reintroduce numerous ssl-opt.sh tests if !MBEDTLS_SSL_KEEP_PEER_CERT 2019-06-19 14:59:41 +01:00
Hanno Becker
975c463b3f ssl_client2: Extract peer CRT info from verification callback
So far, `ssl_client2` printed the CRT info for the peer's CRT
by requesting the latter through `mbedtls_ssl_get_peer_cert()`
at the end of the handshake, and printing it via
`mbedtls_x509_crt_info()`. When `MBEDTLS_SSL_KEEP_PEER_CERTIFICATE`
is disabled, this does no longer work because the peer's CRT
isn't stored beyond the handshake.

This makes some tests in `ssl-opt.sh` fail which rely on the CRT
info output for the peer certificate.

This commit modifies `ssl_client2` to extract the peer CRT info
from the verification callback, which is always called at a time
when the peer's CRT is available. This way, the peer's CRT info
is still printed if `MBEDTLS_SSL_KEEP_PEER_CERTIFICATE` is disabled.
2019-06-19 14:59:37 +01:00
Hanno Becker
24bc570814 Improve documentation of mbedtls_ssl_get_peer_cert() 2019-06-19 10:26:50 +01:00
Hanno Becker
3ed64578d2 Improve documentation of MBEDTLS_SSL_KEEP_PEER_CERTIFICATE 2019-06-19 10:26:50 +01:00
Hanno Becker
dd689316d1 Fix indentation of Doxygen comment in ssl_internal.h 2019-06-19 10:26:50 +01:00
Hanno Becker
9d64b789cf Set peer CRT length only after successful allocation 2019-06-19 10:26:50 +01:00
Hanno Becker
257ef65d94 Remove question in comment about verify flags on cli vs. server 2019-06-19 10:26:50 +01:00
Hanno Becker
e669770b52 Remove misleading and redundant guard around restartable ECC field
`MBEDTLS_SSL__ECP_RESTARTABLE` is only defined if
`MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED` is set, which
requires `MBEDTLS_X509_PARSE_C` to be set (this is checked
in `check_config.`). The additional `MBEDTLS_X509_PARSE_C`
guard around the `ecrs_peer_cert` field is therefore not
necessary; moreover, it's misleading, because it hasn't
been used consistently throughout the code.
2019-06-19 10:26:50 +01:00
Hanno Becker
92820a1dff Add test for !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE to all.sh 2019-06-19 10:26:50 +01:00
Hanno Becker
34106f6ae2 Free peer CRT chain immediately after verifying it
If we don't need to store the peer's CRT chain permanently, we may
free it immediately after verifying it. Moreover, since we parse the
CRT chain in-place from the input buffer in this case, pointers from
the CRT structure remain valid after freeing the structure, and we
use that to extract the digest and pubkey from the CRT after freeing
the structure.
2019-06-19 10:26:50 +01:00
Hanno Becker
0cc7af5be5 Parse peer's CRT chain in-place from the input buffer 2019-06-19 10:26:50 +01:00
Hanno Becker
6c83db7f7b Free peer's public key as soon as it's no longer needed
On constrained devices, this saves a significant amount of RAM that
might be needed for subsequent expensive operations like ECDHE.
2019-06-19 10:26:50 +01:00
Hanno Becker
17572473c6 Correct compile-time guards for ssl_clear_peer_cert()
It is used in `mbedtls_ssl_session_free()` under
`MBEDTLS_X509_CRT_PARSE_C`, but defined only if
`MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED`.

Issue #2422 tracks the use of
`MBEDTLS_KEY_EXCHANGE__WITH_CERT_ENABLED` instead of
`MBEDTLS_X509_CRT_PARSE_C` for code and fields
related to CRT-based ciphersuites.
2019-06-19 10:26:50 +01:00
Hanno Becker
597ffe43a1 Adapt ChangeLog 2019-06-19 10:26:50 +01:00
Hanno Becker
bfab9dfea1 Guard mbedtls_ssl_get_peer_cert() by new compile-time option 2019-06-19 10:26:17 +01:00
Hanno Becker
8b6d2cd5af Add dependency to ssl-opt.sh tests which need peer CRT debug info 2019-06-19 10:26:17 +01:00
Hanno Becker
81d11aa640 Adapt mbedtls_ssl_parse_certificate() to removal of peer_cert field 2019-06-19 10:25:02 +01:00
Hanno Becker
5062897507 Adapt ssl_clear_peer_cert() to removal of peer_cert field 2019-06-19 10:25:02 +01:00
Hanno Becker
d5258faa29 Adapt mbedtls_ssl_session_copy() to removal of peer_cert field 2019-06-19 10:25:02 +01:00
Hanno Becker
cd90126ab3 Adapt client auth detection in ssl_parse_certificate_verify()
The server expects a CertificateVerify message only if it has
previously received a Certificate from the client.

So far, this was detected by looking at the `peer_cert` field
in the current session. Preparing to remove the latter, this
commit changes this to instead determine the presence of a peer
certificate by checking the new `peer_cert_digest` pointer.
2019-06-19 10:25:02 +01:00
Hanno Becker
b265f5f191 Use mbedtls_ssl_get_peer_cert() to query peer cert in cert_app 2019-06-19 10:25:02 +01:00
Hanno Becker
0833c1082b Adapt server-side signature verification to use raw public key
We must dispatch between the peer's public key stored as part of
the peer's CRT in the current session structure (situation until
now, and future behaviour if MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is
enabled), and the sole public key stored in the handshake structure
(new, if MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is disabled).
2019-06-19 10:25:02 +01:00
Hanno Becker
69fad13853 Adapt client-side signature verification to use raw public key
We must dispatch between the peer's public key stored as part of
the peer's CRT in the current session structure (situation until
now, and future behaviour if MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is
enabled), and the sole public key stored in the handshake structure
(new, if MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is disabled).
2019-06-19 10:25:02 +01:00
Hanno Becker
53b6b7e09b Adapt ssl_get_ecdh_params_from_cert() to use raw public key
We must dispatch between the peer's public key stored as part of
the peer's CRT in the current session structure (situation until
now, and future behaviour if MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is
enabled), and the sole public key stored in the handshake structure
(new, if MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is disabled).
2019-06-19 10:25:02 +01:00
Hanno Becker
374800a231 Adapt ssl_write_encrypted_pms() to use raw public key
We must dispatch between the peer's public key stored as part of
the peer's CRT in the current session structure (situation until
now, and future behaviour if MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is
enabled), and the sole public key stored in the handshake structure
(new, if MBEDTLS_SSL_KEEP_PEER_CERTIFICATE is disabled).
2019-06-19 10:25:02 +01:00
Hanno Becker
cf291d63dd Make a copy of peer's raw public key after verifying its CRT chain
This commit modifies `mbedtls_ssl_parse_certificate()` to store a
copy of the peer's public key after parsing and verifying the peer's
CRT chain.

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

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

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

This will be useful in subsequent commits to extract the peer's public
key from its certificate chain.
2019-06-19 10:25:01 +01:00
Hanno Becker
2e6d34761f Remove peer CRT from mbedtls_ssl_session if !KEEP_PEER_CERT 2019-06-19 10:25:01 +01:00
Hanno Becker
4a2f8e584f Add peer CRT digest to session tickets
This commit changes the format of session tickets to include
the digest of the peer's CRT if MBEDTLS_SSL_KEEP_PEER_CERTIFICATE
is disabled.

This commit does not yet remove the peer CRT itself.
2019-06-19 10:25:01 +01:00
Hanno Becker
e4aeb76a2c Parse and verify peer CRT chain in local variable
`mbedtls_ssl_parse_certificate()` parses the peer's certificate chain
directly into the `peer_cert` field of the `mbedtls_ssl_session`
structure being established. To allow to optionally remove this field
from the session structure, this commit changes this to parse the peer's
chain into a local variable instead first, which can then either be freed
after CRT verification - in case the chain should not be stored - or
mapped to the `peer_cert` if it should be kept. For now, only the latter
is implemented.
2019-06-19 10:25:01 +01:00
Hanno Becker
df75938b84 Mitigate triple handshake attack by comparing digests only
This paves the way for the removal of the peer CRT chain from
`mbedtls_ssl_session`.
2019-06-19 10:25:01 +01:00
Hanno Becker
3008d2869f Compute digest of peer's end-CRT in mbedtls_ssl_parse_certificate() 2019-06-19 10:25:01 +01:00
Hanno Becker
9fb6e2e203 Extend mbedtls_ssl_session by buffer holding peer CRT digest 2019-06-19 10:25:01 +01:00
Hanno Becker
c88289a64d Update version_features.c 2019-06-19 10:25:01 +01:00
Hanno Becker
b90f655a78 Add configuration option to remove peer CRT after handshake 2019-06-19 10:25:01 +01:00
Hanno Becker
869144b3e9 Improve documentation of mbedtls_ssl_get_peer_cert() 2019-06-19 10:25:01 +01:00
Hanno Becker
f02d5501d8 Re-classify errors on missing peer CRT
mbedtls_ssl_parse_certificate() will fail if a ciphersuite requires
a certificate, but none is provided. While it is sensible to double-
check this, failure should be reported as an internal error and not
as an unexpected message.
2019-06-19 10:25:01 +01:00
Hanno Becker
a177b38618 Simplify session cache implementation via mbedtls_ssl_session_copy() 2019-06-19 10:25:01 +01:00
Hanno Becker
58fccf2f62 Give ssl_session_copy() external linkage
A subsequent commit will need this function in the session ticket
and session cache implementations. As the latter are server-side,
this commit also removes the MBEDTLS_SSL_CLI_C guard.

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

   `MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED`

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

   `mbedtls_ssl_ciphersuite_cert_req_allowed()`

indicating whether a particular ciphersuite allows CertificateRequest
messages.

These were already used in the client-side code to simplify the
parsing functions for CertificateRequest messages.
2019-06-19 10:25:01 +01:00
Hanno Becker
6b9a6f3f37 Add helper function to check whether a CRT msg is expected
This commit adds a helper function `ssl_parse_certificate_coordinate()`
which checks whether a `Certificate` message is expected from the peer.

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

   `mbedtls_ssl_ciphersuite_uses_srv_cert()`

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

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

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

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

- MBEDTLS_KEY_EXCHANGE_PSK
- MBEDTLS_KEY_EXCHANGE_DHE_PSK
- MBEDTLS_KEY_EXCHANGE_ECDHE_PSK
- MBEDTLS_KEY_EXCHANGE_ECJPAKE,

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

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

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

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

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

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

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

This commit removes the code-path moving the old CRT, and instead
frees the entire peer CRT chain from the initial handshake as soon
as the 'triple handshake attack' protection has completed.
2019-06-19 10:25:01 +01:00
Simon Butcher
e210b6616d Merge remote-tracking branch 'origin/pr/595' into baremetal 2019-06-18 17:36:54 +01:00
Simon Butcher
7400e8fb36 Merge remote-tracking branch 'origin/pr/591' into baremetal 2019-06-18 17:36:45 +01:00
Hanno Becker
eddc78a844 Fix documentation of X.509 parsing test 2019-06-18 17:29:35 +01:00
Hanno Becker
5b4a619cfe Add X.509 CRT parsing test for mixed time-encodings 2019-06-18 17:29:35 +01:00
Hanno Becker
615bda0035 Improve X.509 CRT parsing test names 2019-06-18 17:29:35 +01:00
Hanno Becker
b9df4bd8fc Add negative X.509 parsing tests for v3Ext in v1/v2 CRT 2019-06-18 17:29:35 +01:00
Hanno Becker
576f355ea6 Add negative X.509 parsing tests for IssuerID/SubjectID in v1 CRT 2019-06-18 17:29:35 +01:00
Hanno Becker
22adeeb95f Improve name of X.509 CRT parsing test 2019-06-18 17:29:35 +01:00
Hanno Becker
36023dc62b Always use the same X.509 alg structure inside and outside of TBS 2019-06-18 17:29:35 +01:00
Hanno Becker
53634e3f84 Fix test dependencies in X.509 CRT parsing suite
Most tests use an sha256WithRSAEncryption OID which isn't recognized
unless RSA and SHA-256 are enabled.
2019-06-18 17:29:35 +01:00
Hanno Becker
d061c3d7ca Fix test case name formatting in X.509 parsing suite 2019-06-18 17:29:35 +01:00
Hanno Becker
57e0693302 Use ASN.1 NULL TLVs when testing invalid tags
Previously, a test exercising the X.509 CRT parser's behaviour
on unexpected tags would use a '00' byte in place of the tag
for the expected structure. This makes reviewing the examples
harder because the binary data isn't valid DER-encoded ASN.1.

This commit uses the ASN.1 NULL TLV '05 00' to test invalid
tags, and adapts surrounding structures' length values accordingly.
This eases reviewing because now the ASN.1 structures are still
well-formed at the place where the mismatch occurs.
2019-06-18 17:29:35 +01:00
Hanno Becker
98c6b6a5f0 Shorten X.509 CRT parsing test names 2019-06-18 17:29:35 +01:00
Hanno Becker
24d93a424f Extend negative testing for X.509 Signature parsing 2019-06-18 17:28:54 +01:00
Hanno Becker
56eb0b45c9 Extend negative testing for X.509 SignatureAlgorithm parsing 2019-06-18 17:28:54 +01:00
Hanno Becker
cb60e2c917 Extend negative testing for X.509 v3 Extension parsing 2019-06-18 17:28:54 +01:00
Hanno Becker
543cc8a6fd Extend negative testing for X.509 SubjectID parsing 2019-06-18 17:28:54 +01:00
Hanno Becker
96480c1ab0 Extend negative testing for X.509 IssuerID parsing 2019-06-18 17:28:54 +01:00
Hanno Becker
1d3aab9ee8 Extend negative testing for X.509 SubjectPublicKeyInfo parsing 2019-06-18 17:28:54 +01:00
Hanno Becker
74f1d4b6cc Extend negative testing for X.509 Subject parsing 2019-06-18 17:28:54 +01:00
Hanno Becker
f3ca578a73 Extend negative testing for X.509 Validity parsing 2019-06-18 17:28:54 +01:00
Hanno Becker
f59cd6b020 Extend negative testing for X.509 Issuer parsing 2019-06-18 17:28:54 +01:00
Hanno Becker
d4b6daf70a Extend negative testing for X.509 AlgorithmIdentifier parsing 2019-06-18 17:28:54 +01:00
Hanno Becker
1a0d3740b9 Extend negative testing for X.509 Serial number parsing 2019-06-18 17:28:54 +01:00
Hanno Becker
baf32b8cea Extend negative testing for X.509 Version parsing 2019-06-18 17:28:54 +01:00
Hanno Becker
d6ea7252db Extend negative testing for X.509 TBS header parsing 2019-06-18 17:28:54 +01:00
Simon Butcher
f2ef573f2b Merge remote-tracking branch 'origin/pr/598' into baremetal 2019-06-18 15:00:02 +01:00
Simon Butcher
f1ff74574d Merge remote-tracking branch 'origin/pr/597' into baremetal 2019-06-18 14:58:37 +01:00
Simon Butcher
2ad7186a51 Merge remote-tracking branch 'origin/pr/575' into baremetal 2019-06-18 14:57:08 +01:00
Simon Butcher
0c7e36ccf8 Merge remote-tracking branch 'origin/pr/572' into baremetal 2019-06-18 14:56:13 +01:00
Hanno Becker
b2c6383b7b Add missing !MBEDTLS_X509_REMOVE_INFO guards to ssl-opt.sh 2019-06-18 11:05:44 +01:00
Hanno Becker
c6043f2b75 Address review comments 2019-06-18 11:05:44 +01:00
Peter Kolbus
b1cb0bde72 all.sh: Add test for MBEDTLS_X509_REMOVE_INFO
Add a test scenario that runs make/make test with
MBEDTLS_X509_REMOVE_INFO enabled.
2019-06-18 11:05:44 +01:00
Hanno Becker
4a156fc854 Apply guards to make ssl-opt.sh work with MBEDTLS_X509_REMOVE_INFO
Multiple tests in ssl-opt.sh grep for debug output that's omitted
if MBEDTLS_X509_REMOVE_INFO is defined. This commit modifies ssl-opt.sh
to skip those tests in this case.
2019-06-18 11:05:44 +01:00
Hanno Becker
b4d967a0a2 Remove MBEDTLS_X509_REMOVE_INFO from scripts/config.pl full 2019-06-18 11:05:44 +01:00
Hanno Becker
98f85c8c25 Add missing dependencies on !MBEDTLS_X509_REMOVE_INFO 2019-06-18 11:05:44 +01:00
Hanno Becker
02a2193f60 Rename MBEDTLS_X509_INFO to !MBEDTLS_X509_REMOVE_INFO 2019-06-18 11:05:44 +01:00
Peter Kolbus
dc470ae8af Reduce code size when mbedtls_x509_*_info() unused
Introduce MBEDTLS_X509_INFO to indicate the availability of the
mbedtls_x509_*_info() function and closely related APIs. When this is
not defined, also omit name and description from
mbedtls_oid_descriptor_t, and omit OID arrays, macros, and types that
are entirely unused. This saves several KB of code space.

Change-Id: I056312613379890e0d70e1d08c34171287c0aa17
2019-06-18 11:05:37 +01:00
Manuel Pégourié-Gonnard
31ae7facb3 Add test for build warnings with baremetal.h 2019-06-18 12:03:51 +02:00
Manuel Pégourié-Gonnard
e83b2c2a50 Fix unused variable warnings in pkparse.c
In a reduced configuration without PEM, PKCS5 or PKCS12, armc5 found that ret
was set but not used. Fixing that lead to a new warning about the variable not
being used at all. Now the variable is only declared when it's needed.
2019-06-18 11:31:59 +02:00
Manuel Pégourié-Gonnard
070f107a61 Add --check option to scripts/baremetal.sh
Only effective together with --rom, makes two changes:
- abort in case of build warnings
- skip writing statistics

The goal is to make sure we build cleanly in the configuration used for
measuring code size, with all the compilers we use, both because we care about
that configuration and those compilers, and because any warnings would cast a
shadow on the code size measurements.

Currently the build fails with armc5 due to a pre-existing warning in PK, this
will be fixed in the next commit.

The next commit will also add an all.sh component to make sure we have no
regression in the future. (Which is the motivation for --check skipping
statistics: an all.sh component should probably not leave files around.)

While at it, fix two things:

1. The call to gcc --version was redundant with the echo line below
2. WARNING_CFLAGS shouldn't be overriden with armclang, as it would remove the
-Wall -Wextra and any directory-specific warning (such as
-Wdeclaration-after-statement in library). It's meant to be overriden only
with compilers that don't accept the default value (namely armc5 here).
2019-06-18 11:28:59 +02:00
Manuel Pégourié-Gonnard
889bbc70b6 Fix unreachable code warnings with armc5
Some TLS-only code paths were not protected by an #ifdef and while some
compiler are happy to just silently remove them, armc5 complains:

Warning:  #111-D: statement is unreachable

Let's make armc5 happy.
2019-06-18 10:56:09 +02:00
Manuel Pégourié-Gonnard
19e8132e1e Add NO_TLS to configs/baremetal.h
Was missed for some reason in commit ba8b1eb5d9
2019-06-18 10:54:25 +02:00
Jarno Lamsa
8b2608b6c2 Fix style issues 2019-06-18 11:50:11 +03:00
Jarno Lamsa
29a15c2de5 Set timer callbacks with serialization 2019-06-18 11:50:11 +03:00
Jarno Lamsa
85c238018e Fix spacing 2019-06-18 11:50:11 +03:00
Jarno Lamsa
034ae84601 Fix compiler warnings 2019-06-18 11:50:11 +03:00
Jarno Lamsa
8a91c0650a Add tests for re-init flow for context serialization 2019-06-18 11:50:11 +03:00
Jarno Lamsa
b5ff6a4ced Add option for ssl-context re-initialization flow 2019-06-18 11:50:11 +03:00
Jarno Lamsa
bff4a91827 Fix spacing 2019-06-18 11:50:11 +03:00
Jarno Lamsa
f4f8ed7e82 Allow stub implementation of the context_save for now 2019-06-18 11:50:11 +03:00
Jarno Lamsa
5737ec97a6 Address review comments for code-style issues 2019-06-18 11:50:11 +03:00
Jarno Lamsa
38061f4a17 Remove mbedtls_ssl_free() and mbedtls_ssl_init() from serialization flow in test 2019-06-18 11:50:11 +03:00
Jarno Lamsa
cc281b8a54 ssl-opt.sh tests for serialization are currently using stub implementation 2019-06-18 11:50:11 +03:00
Jarno Lamsa
dcfc2a7364 Add missing slashes to tests 2019-06-18 11:50:11 +03:00
Jarno Lamsa
fa45e6005e Add serialization tests to ssl-opt.sh 2019-06-18 11:50:11 +03:00
Jarno Lamsa
cf1b6724c9 Use MBEDTLS_SSL_CONTEXT_SERIALIZATION flag 2019-06-18 11:50:11 +03:00
Jarno Lamsa
f457293b57 Serialize/deserialize for ssl_server2 2019-06-18 11:50:11 +03:00
Jarno Lamsa
654e8de163 Rely on opt.exchanges for sending after serialization 2019-06-18 11:50:11 +03:00
Jarno Lamsa
d736d08618 Serialization/deserialization in ssl_client2 2019-06-18 11:50:11 +03:00
Jarno Lamsa
0ea3cfe5bf Add option for serialization in ssl_client/server2 2019-06-18 11:50:11 +03:00
Manuel Pégourié-Gonnard
11d3282f5a Add a ChangeLog entry. 2019-06-18 10:34:15 +02:00
Manuel Pégourié-Gonnard
c84511fb1f Add check for undocumented positive option 2019-06-18 10:32:25 +02:00
Manuel Pégourié-Gonnard
41efa2109e Improve documentation of PROTO_NO_TLS 2019-06-18 10:28:52 +02:00
Manuel Pégourié-Gonnard
7667afd4fc Clarify documentation of mbedtls_ssl_context_load() 2019-06-18 10:09:27 +02:00
Manuel Pégourié-Gonnard
cc71c77b5d Fix typos, grammar and wording in documentation 2019-06-18 10:09:27 +02:00
Manuel Pégourié-Gonnard
d87601e3ef Declare and document ssl_context_save()/load()
Also introduce stub definitions so that things compile and link.
2019-06-18 10:09:27 +02:00
Manuel Pégourié-Gonnard
91fa5bade3 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-06-18 10:09:27 +02:00
Hanno Becker
1abb159e90 Merge branch 'mbedtls-2.16' into baremetal 2019-06-18 09:00:37 +01:00
Simon Butcher
c725e4b34e Merge remote-tracking branch 'origin/pr/590' into baremetal 2019-06-17 17:57:26 +01:00
Simon Butcher
01a8eb21d3 Merge remote-tracking branch 'origin/pr/585' into baremetal 2019-06-17 17:53:41 +01:00
Simon Butcher
c107850c2c Merge remote-tracking branch 'origin/pr/580' into baremetal 2019-06-17 17:48:06 +01:00
Simon Butcher
62d03b2779 Merge remote-tracking branch 'origin/pr/577' into baremetal 2019-06-17 17:46:32 +01:00
Manuel Pégourié-Gonnard
ba8b1eb5d9 Use negated option for controlling TLS support.
A positive option looks better, but comes with the following compatibility
issue: people using a custom config.h that is not based on the default
config.h and need TLS support would need to manually change their config in
order to still get TLS.

Work around that by making the public option negative. Internally the positive
option is used, though.

In the future (when preparing the next major version), we might want to switch
back to a positive option as this would be more consistent with other options
we have.
2019-06-17 15:26:34 +02:00
Hanno Becker
fc1a40b4df Remove MBEDTLS_SSL_SESSION_TICKETS from baremetal config 2019-06-13 08:59:10 +01:00
Jarno Lamsa
2e51098b34 Add changelog entry 2019-06-13 10:42:13 +03:00
Simon Butcher
5aca94eafe Merge remote-tracking branch 'origin/pr/588' into baremetal 2019-06-12 20:16:15 +01:00
Simon Butcher
214e211dfd Merge remote-tracking branch 'origin/pr/587' into baremetal 2019-06-12 20:15:50 +01:00
Simon Butcher
f49a277f34 Merge remote-tracking branch 'origin/pr/576' into baremetal 2019-06-12 20:15:00 +01:00
Hanno Becker
49f83e6748 Change order of ChangeLog sections 2019-06-12 12:43:19 +01:00
Manuel Pégourié-Gonnard
ec1c222947 Fix a few style issues 2019-06-12 10:18:26 +02:00
Jarno Lamsa
31d940ba5e Change test name 2019-06-12 10:21:33 +03:00
Jarno Lamsa
20095afc58 Changes according to review comments 2019-06-11 17:16:58 +03:00
Manuel Pégourié-Gonnard
8794a4290d Clarify a few more comments and documentation 2019-06-11 10:04:57 +02:00
Jarno Lamsa
41b359114d Add tests for enforced extended master secret flag 2019-06-10 15:51:11 +03:00
Jarno Lamsa
18b9a491e1 Disable the enforce flag by default 2019-06-10 15:23:29 +03:00
Jarno Lamsa
842be16800 Check for the enforcing and fail handshake if the peer doesn't support 2019-06-10 15:05:33 +03:00
Jarno Lamsa
d9382f85e7 Add definitions for enforce flag values 2019-06-10 10:27:14 +03:00
Jarno Lamsa
95f752e679 Fix typo 2019-06-10 10:15:49 +03:00
Jarno Lamsa
7a5e2bec75 Create a new flag for enforcing the extended master secret
If the flag is enabled, drop the connection if peer doesn't support
extended master secret extension.
2019-06-10 10:13:03 +03:00
Hanno Becker
b058556a35 Remove time from baremetal configuration 2019-06-07 17:13:51 +01:00
Hanno Becker
7cc9ca876f baremetal.sh: Print code-size summary
This commit modifies `scripts/baremetal.sh` to print the total code-size
of the SSL, X.509 and Crypto libraries are runs of

- ./scripts/baremetal.sh --rom --gcc
- ./scripts/baremetal.sh --rom --armc5
- ./scripts/baremetal.sh --rom --armc6

This eases quick investigation of the effect of changes on code-size.
2019-06-07 16:50:20 +01:00
Manuel Pégourié-Gonnard
c6d9e3a28f Clarify documentation of MBEDTLS_SSL_PROTO_TLS 2019-06-07 11:07:53 +02:00
Manuel Pégourié-Gonnard
64c1681fbc Use new macros for all TLS/DTLS tests
sed -i -e 's/\([^ ]*transport\) == MBEDTLS_SSL_TRANSPORT_DATAGRAM/MBEDTLS_SSL_TRANSPORT_IS_DTLS( \1 )/' -e 's/\([^ ]*transport\) \(!= MBEDTLS_SSL_TRANSPORT_DATAGRAM\|== MBEDTLS_SSL_TRANSPORT_STREAM\)/MBEDTLS_SSL_TRANSPORT_IS_TLS( \1 )/' library/ssl_*.c

New sizes (see 2nd-previous commit for measuring script):

```

both
   text    data     bss     dec     hex filename
   1820       0       4    1824     720 debug.o (ex library/libmbedtls.a)
      0       0       0       0       0 net_sockets.o (ex library/libmbedtls.a)
    548       0       0     548     224 ssl_cache.o (ex library/libmbedtls.a)
  11155       0     596   11751    2de7 ssl_ciphersuites.o (ex library/libmbedtls.a)
  17156       0       0   17156    4304 ssl_cli.o (ex library/libmbedtls.a)
    460       0       0     460     1cc ssl_cookie.o (ex library/libmbedtls.a)
  17649       0       0   17649    44f1 ssl_srv.o (ex library/libmbedtls.a)
    800       0       0     800     320 ssl_ticket.o (ex library/libmbedtls.a)
  39286      60       0   39346    99b2 ssl_tls.o (ex library/libmbedtls.a)
  88874      60     600   89534   15dbe (TOTALS)

DTLS-only
   text    data     bss     dec     hex filename
   1820       0       4    1824     720 debug.o (ex library/libmbedtls.a)
      0       0       0       0       0 net_sockets.o (ex library/libmbedtls.a)
    548       0       0     548     224 ssl_cache.o (ex library/libmbedtls.a)
  11155       0     596   11751    2de7 ssl_ciphersuites.o (ex library/libmbedtls.a)
  16948       0       0   16948    4234 ssl_cli.o (ex library/libmbedtls.a)
    460       0       0     460     1cc ssl_cookie.o (ex library/libmbedtls.a)
  17437       0       0   17437    441d ssl_srv.o (ex library/libmbedtls.a)
    800       0       0     800     320 ssl_ticket.o (ex library/libmbedtls.a)
  38147      60       0   38207    953f ssl_tls.o (ex library/libmbedtls.a)
  87315      60     600   87975   157a7 (TOTALS)

TLS-only
   text    data     bss     dec     hex filename
   1820       0       4    1824     720 debug.o (ex library/libmbedtls.a)
      0       0       0       0       0 net_sockets.o (ex library/libmbedtls.a)
    548       0       0     548     224 ssl_cache.o (ex library/libmbedtls.a)
  11155       0     596   11751    2de7 ssl_ciphersuites.o (ex library/libmbedtls.a)
  14912       0       0   14912    3a40 ssl_cli.o (ex library/libmbedtls.a)
    460       0       0     460     1cc ssl_cookie.o (ex library/libmbedtls.a)
  15868       0       0   15868    3dfc ssl_srv.o (ex library/libmbedtls.a)
    800       0       0     800     320 ssl_ticket.o (ex library/libmbedtls.a)
  27619      60       0   27679    6c1f ssl_tls.o (ex library/libmbedtls.a)
  73182      60     600   73842   12072 (TOTALS)
```
2019-06-06 13:19:59 +02:00
Manuel Pégourié-Gonnard
ff4bd9f405 Use new tools for all cases with TLS-specific code
This commit handles occurrences of case 2 and 3 in the following list:

1. Some DTLS-specific code with no TLS-specific code (most frequent)
2. Some specific code for each protocol
3. Some TLS-specific code with no DTLS-specific code (least frequent)

Case 3 previously had a weird structure in that the TLS-specific code was
always present, but the if structure was conditional on DTLS being enabled.
This is changed by this commit to a more logical structure where both the code
and the test are conditional on TLS being enabled.

Case 2 doesn't require any change in the code structure in general. However,
there is one occurrence where the if/else structure is simplified to assigning
the result of a boolean operation, and one occurrence where I also noticed a
useless use of `ssl_ep_len()` in a TLS-specific branch, that I turned to the
constant 0 as it makes more sense.

Case 1 will be handled in the next commit, as it can easily be handled in an
automated way - only cases 2 and 3 (sometimes) required manual intervention.

The list of occurrences for cases 2 and 3 was established manually by looking
for occurrences of '= MBEDTLS_SSL_TRANSPORT_' in the code and manually
checking if there was a TLS-specific branch.

New sizes (see previous commit for the measuring script):

```

both
   text    data     bss     dec     hex filename
   1820       0       4    1824     720 debug.o (ex library/libmbedtls.a)
      0       0       0       0       0 net_sockets.o (ex library/libmbedtls.a)
    548       0       0     548     224 ssl_cache.o (ex library/libmbedtls.a)
  11155       0     596   11751    2de7 ssl_ciphersuites.o (ex library/libmbedtls.a)
  17156       0       0   17156    4304 ssl_cli.o (ex library/libmbedtls.a)
    460       0       0     460     1cc ssl_cookie.o (ex library/libmbedtls.a)
  17649       0       0   17649    44f1 ssl_srv.o (ex library/libmbedtls.a)
    800       0       0     800     320 ssl_ticket.o (ex library/libmbedtls.a)
  39286      60       0   39346    99b2 ssl_tls.o (ex library/libmbedtls.a)
  88874      60     600   89534   15dbe (TOTALS)

DTLS-only
   text    data     bss     dec     hex filename
   1820       0       4    1824     720 debug.o (ex library/libmbedtls.a)
      0       0       0       0       0 net_sockets.o (ex library/libmbedtls.a)
    548       0       0     548     224 ssl_cache.o (ex library/libmbedtls.a)
  11155       0     596   11751    2de7 ssl_ciphersuites.o (ex library/libmbedtls.a)
  17068       0       0   17068    42ac ssl_cli.o (ex library/libmbedtls.a)
    460       0       0     460     1cc ssl_cookie.o (ex library/libmbedtls.a)
  17553       0       0   17553    4491 ssl_srv.o (ex library/libmbedtls.a)
    800       0       0     800     320 ssl_ticket.o (ex library/libmbedtls.a)
  38499      60       0   38559    969f ssl_tls.o (ex library/libmbedtls.a)
  87903      60     600   88563   159f3 (TOTALS)

TLS-only
   text    data     bss     dec     hex filename
   1820       0       4    1824     720 debug.o (ex library/libmbedtls.a)
      0       0       0       0       0 net_sockets.o (ex library/libmbedtls.a)
    548       0       0     548     224 ssl_cache.o (ex library/libmbedtls.a)
  11155       0     596   11751    2de7 ssl_ciphersuites.o (ex library/libmbedtls.a)
  14912       0       0   14912    3a40 ssl_cli.o (ex library/libmbedtls.a)
    460       0       0     460     1cc ssl_cookie.o (ex library/libmbedtls.a)
  15868       0       0   15868    3dfc ssl_srv.o (ex library/libmbedtls.a)
    800       0       0     800     320 ssl_ticket.o (ex library/libmbedtls.a)
  27619      60       0   27679    6c1f ssl_tls.o (ex library/libmbedtls.a)
  73182      60     600   73842   12072 (TOTALS)
```
2019-06-06 13:18:19 +02:00
Manuel Pégourié-Gonnard
25838b795f Introduce tools for transport-specific code
And use those tools in a few places. For now the purpose is just to validate
those tools before using them in all occurrences of transport-specific code.

The effect of these changes was measured with the following script:

```
set -eu

build() {
    printf "\n$1\n"
    CC=arm-none-eabi-gcc CFLAGS='-Werror -Os -march=armv6-m -mthumb' \
        AR=arm-none-eabi-ar LD=arm-none-eabi-ld make clean lib >/dev/null
    arm-none-eabi-size -t library/libmbedtls.a
}

git checkout -- include/mbedtls/config.h
scripts/config.pl unset MBEDTLS_NET_C
scripts/config.pl unset MBEDTLS_TIMING_C
scripts/config.pl unset MBEDTLS_FS_IO
scripts/config.pl unset MBEDTLS_ENTROPY_NV_SEED
scripts/config.pl set MBEDTLS_NO_PLATFORM_ENTROPY
build "both"

scripts/config.pl unset MBEDTLS_SSL_PROTO_TLS
build "DTLS-only"

scripts/config.pl set MBEDTLS_SSL_PROTO_TLS
scripts/config.pl unset MBEDTLS_SSL_PROTO_DTLS
scripts/config.pl unset MBEDTLS_SSL_DTLS_HELLO_VERIFY
scripts/config.pl unset MBEDTLS_SSL_DTLS_ANTI_REPLAY
scripts/config.pl unset MBEDTLS_SSL_DTLS_BADMAC_LIMIT
scripts/config.pl unset MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE
build "TLS-only"

git checkout -- include/mbedtls/config.h
```

The output of the script is as follows:

```
both
   text    data     bss     dec     hex filename
   1820       0       4    1824     720 debug.o (ex library/libmbedtls.a)
      0       0       0       0       0 net_sockets.o (ex library/libmbedtls.a)
    548       0       0     548     224 ssl_cache.o (ex library/libmbedtls.a)
  11155       0     596   11751    2de7 ssl_ciphersuites.o (ex library/libmbedtls.a)
  17160       0       0   17160    4308 ssl_cli.o (ex library/libmbedtls.a)
    460       0       0     460     1cc ssl_cookie.o (ex library/libmbedtls.a)
  17637       0       0   17637    44e5 ssl_srv.o (ex library/libmbedtls.a)
    800       0       0     800     320 ssl_ticket.o (ex library/libmbedtls.a)
  39322      60       0   39382    99d6 ssl_tls.o (ex library/libmbedtls.a)
  88902      60     600   89562   15dda (TOTALS)

DTLS-only
   text    data     bss     dec     hex filename
   1820       0       4    1824     720 debug.o (ex library/libmbedtls.a)
      0       0       0       0       0 net_sockets.o (ex library/libmbedtls.a)
    548       0       0     548     224 ssl_cache.o (ex library/libmbedtls.a)
  11155       0     596   11751    2de7 ssl_ciphersuites.o (ex library/libmbedtls.a)
  17072       0       0   17072    42b0 ssl_cli.o (ex library/libmbedtls.a)
    460       0       0     460     1cc ssl_cookie.o (ex library/libmbedtls.a)
  17565       0       0   17565    449d ssl_srv.o (ex library/libmbedtls.a)
    800       0       0     800     320 ssl_ticket.o (ex library/libmbedtls.a)
  38953      60       0   39013    9865 ssl_tls.o (ex library/libmbedtls.a)
  88373      60     600   89033   15bc9 (TOTALS)

TLS-only
   text    data     bss     dec     hex filename
   1820       0       4    1824     720 debug.o (ex library/libmbedtls.a)
      0       0       0       0       0 net_sockets.o (ex library/libmbedtls.a)
    548       0       0     548     224 ssl_cache.o (ex library/libmbedtls.a)
  11155       0     596   11751    2de7 ssl_ciphersuites.o (ex library/libmbedtls.a)
  14916       0       0   14916    3a44 ssl_cli.o (ex library/libmbedtls.a)
    460       0       0     460     1cc ssl_cookie.o (ex library/libmbedtls.a)
  15852       0       0   15852    3dec ssl_srv.o (ex library/libmbedtls.a)
    800       0       0     800     320 ssl_ticket.o (ex library/libmbedtls.a)
  27623      60       0   27683    6c23 ssl_tls.o (ex library/libmbedtls.a)
  73174      60     600   73834   1206a (TOTALS)
```

It can be seen that a DTLS-only build is now starting to be a bit smaller than
a dual-mode build, which is the purpose of the new build option.
2019-06-06 13:02:14 +02:00
Manuel Pégourié-Gonnard
e744eab3b1 Adapt defaults and programs documentation 2019-06-06 13:02:14 +02:00
Manuel Pégourié-Gonnard
a771160799 Introduce new config.h flag for TLS
For now the option has no effect.

Adapted existing example config files. The fact that I needed to do this
highlights that this is a slightly incompatible change: existing users need to
update their existing custom configs (if standalone as opposed to based on the
default config) in order to still get the same behaviour.

The alternative would be to have a negative config option (eg NO_TLS or
DTLS_ONLY) but this doesn't fit as nicely with the existing options, so
hopefully the minor incompatibility is acceptable.

I don't think it's worth adding a new component to all.sh:
- builds with both DTLS and TLS are done in the default (and full) config
- TLS-only builds are done with eg config-suite-b.h in test-ref-configs
- a DTLS-only build is done with config-thread.h in test-ref-configs
- builds with none of them (and SSL_TLS_C enabled) are forbidden
2019-06-06 12:59:48 +02:00
Jaeden Amero
fa8e6dabd2 all.sh: Perform targeted EtM tests for MAC-less configs
When testing a configuration where no ciphersuites have MAC, via
component_test_when_no_ciphersuites_have_mac(), perform a targeted test
of only encrypt-then-MAC tests within ssl-opt.sh.
2019-06-05 14:48:33 +01:00
Hanno Becker
68b856d0ac Fix style issue and wording 2019-06-05 14:25:28 +01:00
Hanno Becker
fe87027512 Fix memory leak 2019-06-05 14:25:28 +01:00
Hanno Becker
fd39919aa3 Improve formatting of ssl_parse_certificate_chain() 2019-06-05 14:25:28 +01:00
Hanno Becker
285ff0c362 Add compile-time guards around helper routine 2019-06-05 14:25:28 +01:00
Hanno Becker
1f2e466843 Adapt ChangeLog 2019-06-05 14:25:28 +01:00
Hanno Becker
33c3dc8591 Don't store the peer CRT chain twice during renegotiation
Context: During a handshake, the SSL/TLS handshake logic constructs
an instance of ::mbedtls_ssl_session representing the SSL session
being established. This structure contains information such as the
session's master secret, the peer certificate, or the session ticket
issues by the server (if applicable).
During a renegotiation, the new session is constructed aside the existing
one and destroys and replaces the latter only when the renegotiation is
complete. While conceptually clear, this means that during the renegotiation,
large pieces of information such as the peer's CRT or the session ticket
exist twice in memory, even though the original versions are removed
eventually.

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

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

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

This commit starts removing this memory inefficiency by freeing the old
session's SessionTicket before the one for the new session is allocated.
2019-06-05 14:25:28 +01:00
Jaeden Amero
2eaf2c7969 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. Fix any
unused variable warnings along the way, by additionally wrapping
function parameters with MBEDTLS_SSL_SOME_MODES_USE_MAC.

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

Fixes 92231325a7 ("Reduce size of `ssl_transform` if no MAC ciphersuite is enabled")
2019-06-05 14:22:11 +01:00
Hanno Becker
80e92ad43a Adapt ChangeLog 2019-06-05 13:18:05 +01:00
Hanno Becker
2fa5e73d8d Modify existing X.509 test for also test new copyless API
The existing test `x509parse_crt()` for X.509 CRT parsing
so far used the generic parsing API `mbedtls_x509_crt_parse()`
capable of parsing both PEM encoded and DER encoded certficates,
but was actually only used with DER encoded input data. Moreover,
as the purpose of the test is the testing of the core DER X.509 parsing
functionality, not the PEM vs. DER dispatch (which is now already tested
in the various `x509_crt_info()` tests), the call can be replaced with a
direct call to `mbedtls_x509_parse_crt_der()`.

This commit does that, and further adds to the test an analogous
call to the new API `mbedtls_x509_parse_crt_der_nocopy()` to test
copyless parsing of X.509 certificates.
2019-06-05 13:16:55 +01:00
Hanno Becker
d58b133276 Add test for mbedtls_x509_parse_file() with DER encoded CRT 2019-06-05 13:16:55 +01:00
Hanno Becker
aa8665ac26 Add a new X.509 API call for copy-less parsing of CRTs
Context:
The existing API `mbedtls_x509_parse_crt_der()` for parsing DER
encoded X.509 CRTs unconditionally makes creates a copy of the
input buffer in RAM. While this comes at the benefit of easy use,
-- specifically: allowing the user to free or re-use the input
buffer right after the call -- it creates a significant memory
overhead, as the CRT is duplicated in memory (at least temporarily).
This might not be tolerable a resource constrained device.

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

   `mbedtls_x509_parse_crt_der_nocopy()`

which has the same signature as `mbedtls_x509_parse_crt_der()`
and almost the same semantics, with one difference: The input
buffer must persist and be unmodified for the lifetime of the
established instance of `mbedtls_x509_crt`, that is, until
`mbedtls_x509_crt_free()` is called.
2019-06-05 13:16:55 +01:00
Simon Butcher
21d1c32b2b Merge remote-tracking branch 'origin/pr/574' into baremetal 2019-06-04 15:08:32 +01:00
Simon Butcher
d2cd0b8041 Merge remote-tracking branch 'origin/pr/567' into baremetal 2019-06-04 15:06:20 +01:00
Simon Butcher
2b2cbb5c0f Merge remote-tracking branch 'origin/pr/570' into baremetal 2019-06-04 15:06:07 +01:00
Simon Butcher
786ff7911c Merge remote-tracking branch 'origin/pr/568' into baremetal 2019-06-04 15:05:42 +01:00
Hanno Becker
08c78a2e32 UDP proxy: Don't attempt to dissect dgram into records when dropping
To prevent dropping the same message over and over again, the UDP proxy
test application programs/test/udp_proxy _logically_ maintains a mapping
from records to the number of times the record has already been dropped,
and stops dropping once a configurable threshold (currently 2) is passed.

However, the actual implementation deviates from this logical view
in two crucial respects:
- To keep the implementation simple and independent of
  implementations of suitable map interfaces, it only counts how
  many times a record of a given _size_ has been dropped, and
  stops dropping further records of that size once the configurable
  threshold is passed. Of course, this is not fail-proof, but a
  good enough approximation for the proxy, and it allows to use
  an inefficient but simple array for the required map.
- The implementation mixes datagram lengths and record lengths:
  When deciding whether it is allowed to drop a datagram, it
  uses the total datagram size as a lookup index into the map
  counting the number of times a package has been dropped. However,
  when updating this map, the UDP proxy traverses the datagram
  record by record, and updates the mapping at the level of record
  lengths.

Apart from this inconsistency, the introduction of the Connection ID
feature leads to yet another problem: The CID length is not part of
the record header but dynamically negotiated during (potentially
encrypted!) handshakes, and it is hence impossible for a passive traffic
analyzer (in this case our UDP proxy) to reliably parse record headers;
especially, it isn't possible to reliably infer the length of a record,
nor to dissect a datagram into records.

The previous implementation of the UDP proxy was not CID-aware and
assumed that the record length would always reside at offsets 11, 12
in the DTLS record header, which would allow it to iterate through
the datagram record by record. As mentioned, this is no longer possible
for CID-based records, and the current implementation can run into
a buffer overflow in this case (because it doesn't validate that
the record length is not larger than what remains in the datagram).

This commit removes the inconsistency in datagram vs. record length
and resolves the buffer overflow issue by not attempting any dissection
of datagrams into records, and instead only counting how often _datagrams_
of a particular size have been dropped.

There is only one practical situation where this makes a difference:
If datagram packing is used by default but disabled on retransmission
(which OpenSSL has been seen to do), it can happen that we drop a
datagram in its initial transmission, then also drop some of its records
when they retransmitted one-by-one afterwards, yet still keeping the
drop-counter at 1 instead of 2. However, even in this situation, we'll
correctly count the number of droppings from that point on and eventually
stop dropping, because the peer will not fall back to using packing
and hence use stable record lengths.
2019-06-04 13:04:28 +01:00
Hanno Becker
7bf7710f40 Remove reference to outdated compile-time option 2019-06-04 09:44:25 +01:00
Manuel Pégourié-Gonnard
f3c43dde54 Merge branch 'mbedtls-2.16' into baremetal
* mbedtls-2.16:
  test: Always use `make clean` by itself
  list-symbols.sh: if the build fails, print the build transcript
  Document "check-names.sh -v"
  all.sh: invoke check-names.sh in print-trace-on-exit mode
  Print a command trace if the check-names.sh exits unexpectedly
  Only use submodule if present
  Update change log
  Reword ssl_conf_max_frag_len documentation for clarity
  Ignore more generated files: seedfile, apidoc
  Improve .gitignore grouping and documentation
  Generate tags for Vi, for Emacs and with Global
2019-06-04 09:39:51 +02:00
Hanno Becker
5dbcc9f441 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-06-03 13:01:21 +01:00
Hanno Becker
f78af3779a Improve test for detection of ver/cfg corruption in serialized data
This commit improves the test exercising the behaviour of
session deserialization when facing an unexpected version
or config, by testing ver/cfg corruption at any bit in the
ver/cfg header of the serialized data; previously, it had
only tested the first bit of each byte.
2019-06-03 12:49:36 +01:00
Hanno Becker
08ec129dd8 Use US spelling 'serialize' instead of UK spelling 'serialise' 2019-06-03 12:49:36 +01:00
Hanno Becker
baf968cf69 Use def'n consts for bits in config-identifier of serialized data 2019-06-03 12:49:09 +01:00
Hanno Becker
b36db4f368 Note that ver+fmt bytes in serialized data must not be removed 2019-06-03 12:49:09 +01:00
Hanno Becker
26829e99b2 Improve doc'n of config-identifying bitfield in serialized session 2019-06-03 12:48:50 +01:00
Hanno Becker
1d8b6d7b12 Session serialization: Fail with BAD_INPUT_DATA if buffer too small 2019-06-03 12:48:31 +01:00
Hanno Becker
cb9ba0f43c Use consistent spelling of 'serialise/serialize' in SSL test suite 2019-06-03 12:48:16 +01:00
Hanno Becker
f99ec2618d Add negative tests for unexpected ver/cfg in session deserialization 2019-06-03 12:48:16 +01:00
Hanno Becker
41527624f6 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-06-03 12:48:16 +01:00
Hanno Becker
557fe9ffde 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-06-03 12:46:39 +01:00
Hanno Becker
b5352f0489 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-06-03 12:46:23 +01:00
Manuel Pégourié-Gonnard
c4f5080b34 Re-enable test that now works with new format
Previously the test didn't work because of embedded pointer values that
are not predictable. Now it works as we no longer serialize such values.
2019-06-03 10:53:47 +02:00
Manuel Pégourié-Gonnard
f8c355a012 Adapt buffering test to new ticket size
The size of the ticket used in this test dropped from 192 to 143 bytes, so
move all sizes used in this test down 50 bytes. Also, we now need to adapt the
server response size as the default size would otherwise collide with the new
mtu value.
2019-06-03 10:15:07 +02:00
Manuel Pégourié-Gonnard
60a4299bbf Add new ABI-independent format for serialization 2019-06-03 10:15:07 +02:00
Manuel Pégourié-Gonnard
35ccdbb636 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-06-03 09:55:16 +02:00
Manuel Pégourié-Gonnard
e0cd1d0184 Improve documentation 2019-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
4bb1b99c7f Demonstrate safe usage (zeroize) in ssl_client2 2019-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
2d8847e84d Add a ChangeLog entry for session serialisation 2019-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
749312fb8a Fix undeclared dependency on FS_IO in test code
Found by 'all.sh test_no_platform' and by 'tests/scripts/test-ref-configs.pl'.
2019-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
d1a5451fb5 Fix style issues and typos in test code 2019-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
081b15231f Fix another wrong check for errors in test code 2019-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
5363e1f496 Add list of coupled functions to struct definition 2019-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
2a62a05688 Add test that save-load is the identity
This test works regardless of the serialisation format and embedded pointers
in it, contrary to the load-save test, though it requires more maintenance of
the test code (sync the member list with the struct definition).
2019-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
aab6204dc1 Fix populate_session() and its usage in tests
Not checking the return value allowed a bug to go undetected, fix the bug and
check the return value.
2019-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
5709811dd2 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-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
98fccc3f6a Add test for session_save() on small buffers 2019-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
1ba5c68503 Disable test for load-save identity
This test appeared to be passing for the wrong reason, it's not actually not
appropriate for the current implementation. The serialised data contains
values of pointers to heap-allocated buffers. There is no reason these should
be identical after a load-save pair. They just happened to be identical when I
first ran the test due to the place of session_free() in the test code and the
fact that the libc's malloc() reused the same buffers. The test no longer
passes if other malloc() implementations are used (for example, when compiling
with asan which avoids re-using the buffer, probably for better error
detection).

So, disable this test for now (we can re-enable it when we changed how
sessions are serialised, which will be done in a future PR, hence the name of
the dummy macro in depends_on). In the next commit we're going to add a test
that save-load is the identity instead - which will be more work in testing as
it will require checking each field manually, but at least is reliable.
2019-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
16f6bb1aa3 Improve load-save test with tickets and certs 2019-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
dfa5a7ae76 Start adding unit test for session serialisation
This initial test ensures that a load-save function is the identity. It is so
far incomplete in that it only tests sessions without tickets or certificate.
This will be improved in the next commits.
2019-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
32ce596c35 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-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
57a348ba8c Add tests for session copy without serialisation 2019-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
37a5324c74 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-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
fbb44a422f Save session in serialised form in ssl_client2.
This provides basic testing for the session (de)serialisation functions, as
well as an example of how to use them.

Tested locally with tests/ssl-opt.sh -f '^Session resume'.
2019-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
ef4ae611e4 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-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
91f4ca2ed1 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-06-03 09:51:08 +02:00
Manuel Pégourié-Gonnard
2843fe10b9 Declare and document session save/load functions
The next commit with make the implementation publicly available as well.

For now the API is kept unchanged. The save function API has a serious drawback in that the user
must guess what an appropriate buffer size is.
Internally so far this didn't matter because we were only using that API for
ticket creation, and tickets are written to the SSL output buffer whose size
is fixed anyway, but for external users this might not be suitable. Improving
that is left for later.

Also, so far the functions are defined unconditionally. Whether we want to
re-use existing flags or introduce a new one is left for later.

Finally, currently suggested usage of calling get_session() then
session_save() is memory-inefficient in that get_session() already makes a
copy. I don't want to recommend accessing `ssl->session` directly as we want
to prohibit direct access to struct member in the future. Providing a clean
and efficient way is also left to a later commit.
2019-06-03 09:51:08 +02:00
Simon Butcher
0d1d76f987 Merge remote-tracking branch 'origin/pr/561' into baremetal 2019-05-29 15:09:24 +01:00
Simon Butcher
d5e1bfc6b4 Merge remote-tracking branch 'origin/pr/569' into baremetal 2019-05-24 15:07:10 +01:00
Simon Butcher
0edb924e16 Merge remote-tracking branch 'origin/pr/565' into baremetal 2019-05-24 15:06:56 +01:00
Simon Butcher
5a790f9214 Merge remote-tracking branch 'origin/pr/563' into baremetal 2019-05-24 15:06:16 +01:00
Simon Butcher
6961760eb8 Merge remote-tracking branch 'origin/pr/560' into baremetal 2019-05-24 15:05:42 +01:00
Simon Butcher
ba13ff514f Merge remote-tracking branch 'origin/pr/559' into baremetal 2019-05-24 15:05:07 +01:00
Hanno Becker
948a34adcc Add description of CID feature to ChangeLog 2019-05-24 10:23:43 +01:00
Hanno Becker
f6fb4ea632 Insert records with unexpected CID in CID tests in ssl-opt.sh 2019-05-24 10:11:23 +01:00
Hanno Becker
675c4d6d35 Add debug line witnessing receipt of unexpected CID 2019-05-24 10:11:06 +01:00
Hanno Becker
34dcf4e6f6 Add bad_cid option UDP proxy to insert unexpected CID records
This commit adds the command line option 'bad_cid' to the UDP proxy
`./programs/test/udp_proxy`. It takes a non-negative integral value N,
which if not 0 has the effect of duplicating every 1:N CID records
and modifying the CID in the first copy sent.

This is to exercise the stacks documented behaviour on receipt
of unexpected CIDs.

It is important to send the record with the unexpected CID first,
because otherwise the packet would be dropped already during
replay protection (the same holds for the implementation of the
existing 'bad_ad' option).
2019-05-24 10:07:42 +01:00
Hanno Becker
d8f7c4aa59 Fix indentation in debug message in ssl_tls.c 2019-05-23 17:03:44 +01:00
Hanno Becker
3b2bf5b214 Improve comment in ssl_parse_record_header() 2019-05-23 17:03:19 +01:00
Hanno Becker
4753e65e9b Disable Connection ID feature by default 2019-05-23 17:02:14 +01:00
Hanno Becker
f4e8ed116c Remove superfluous new line in ssl_server2 2019-05-23 17:01:43 +01:00
Hanno Becker
c8f43d82b8 Improve readability of ssl_client2/ssl_server2 usage instructions 2019-05-23 17:01:06 +01:00
Hanno Becker
b8260c64d6 Remove superfluous newline in ssl_client2 2019-05-23 17:00:23 +01:00
Hanno Becker
76581052f9 Use negative-hex format for error codes in ssl_client2/ssl_server2 2019-05-23 16:58:22 +01:00
Hanno Becker
948d2d5611 Expand CID to Connection ID in documentation of mbedtls_ssl_conf_cid 2019-05-23 16:55:50 +01:00
Hanno Becker
ac36388e3e Exemplify ways of calling mbedtls_ssl_get_peer_cid() in ssl_client2 2019-05-22 16:59:25 +01:00
Hanno Becker
633d604837 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-05-22 16:50:35 +01:00
Hanno Becker
6945983588 Rename MBEDTLS_SSL_CID->MBEDTLS_SSL_DTLS_CONNECTION_ID in SSL suite 2019-05-20 15:40:23 +01:00
Hanno Becker
2f8c804d79 Fix typo in Doxygen documentation of mbedtls_ssl_conf_cid() 2019-05-20 15:35:36 +01:00
Hanno Becker
a5a2b08a05 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-05-20 15:35:36 +01:00
Hanno Becker
3cdf8fe50b Consistently reference CID draft through name + URL 2019-05-20 15:32:36 +01:00
Hanno Becker
e582d12264 Slightly reorder CID debug messages during creation of transforms 2019-05-20 15:32:36 +01:00
Hanno Becker
cfa6be76bd Fix typo in documentation of mbedtls_ssl_context::cid_in_use 2019-05-20 15:32:36 +01:00
Hanno Becker
96f35b4f06 Improve wording of documentation of mbedtls_ssl_get_peer_cid() 2019-05-20 15:32:36 +01:00
Hanno Becker
5fcac0dc99 Slightly reword documentation of mbedtls_ssl_set_cid() 2019-05-20 15:32:36 +01:00
Hanno Becker
53f36e9230 Use full sentences in Doxygen documentation of mbedtls_ssl_set_cid() 2019-05-20 15:32:36 +01:00
Hanno Becker
dc19b41eb3 Use uniform spacing in def's of MBEDTLS_SSL_CID_{IN|OUT}_LEN_MAX 2019-05-20 15:32:36 +01:00
Hanno Becker
f83017ccd1 Improve wording in documentation of mbedtls_ssl_set_cid() 2019-05-20 15:32:36 +01:00
Hanno Becker
75b334f33a Update references to CID draft to version 5 2019-05-20 15:32:36 +01:00
Hanno Becker
ef2b8b0dcf Improve wording in documentation of MBEDTLS_SSL_CID 2019-05-20 15:32:36 +01:00
Hanno Becker
791ec6bff2 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-05-20 15:32:36 +01:00
Hanno Becker
a69b4315eb Modify MBEDTLS_SSL_UNEXPECTED_CID_{FAIL|IGNORE} to ignore by default 2019-05-20 15:32:36 +01:00
Hanno Becker
b86c2a8c5d Remove warnings about unfinished CID implementation
The implementation is complete now.
2019-05-20 15:32:36 +01:00
Hanno Becker
e8eff9a517 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-05-20 15:32:36 +01:00
Hanno Becker
7c3cdb62de 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-05-20 15:32:36 +01:00
Hanno Becker
7842609e3b Remove restriction on value of MBEDTLS_SSL_CID_PADDING_GRANULARITY 2019-05-20 15:32:36 +01:00
Hanno Becker
241947d062 Reword CID documentation 2019-05-20 15:32:36 +01:00
Hanno Becker
d23605d056 Add missing compile-time guard around CID API in ssl_server2 2019-05-20 15:32:36 +01:00
Hanno Becker
7ba3568318 Make signed to unsigned integer truncation cast explicit 2019-05-20 15:32:36 +01:00
Hanno Becker
550e1662c7 Allow the configuration of padding when using CID extension 2019-05-20 15:32:36 +01:00
Hanno Becker
9bf10ea25d 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-05-20 15:32:36 +01:00
Hanno Becker
f65ad82eba Fix typo in comment 2019-05-20 15:32:36 +01:00
Hanno Becker
84bbc51968 Add CID test not using datagram packing to ssl-opt.sh 2019-05-20 15:32:36 +01:00
Hanno Becker
6c4bc14021 UDP Proxy: Don't drop CID records
ApplicationData records are not protected against loss by DTLS
and our test applications ssl_client2 and ssl_server2 don't
implement any retransmission scheme to deal with loss of the
data they exchange. Therefore, the UDP proxy programs/test/udp_proxy
does not drop ApplicationData records.

With the introduction of the Connection ID, encrypted ApplicationData
records cannot be recognized as such by inspecting the record content
type, as the latter is always set to the CID specific content type for
protected records using CIDs, while the actual content type is hidden
in the plaintext.

To keep tests working, this commit adds CID records to the list of
content types which are protected against dropping by the UDP proxy.
2019-05-20 15:32:36 +01:00
Hanno Becker
04ca04caf2 Add Proxy tests for Connection ID to ssl-opt.sh
Also, shorten test names to avoid them being truncated on the cmd line.
2019-05-20 15:32:36 +01:00
Hanno Becker
043a2a4869 Remove indicators and warnings about unfinished CID implementation 2019-05-20 15:32:36 +01:00
Hanno Becker
ad8e2c9144 Fix mismatching debug grep in ssl-opt.sh CID tests 2019-05-20 15:32:36 +01:00
Hanno Becker
9687029d22 Add support for change of CID to ssl_client2 / ssl_server2
And add tests for various CID configuration changes during
renegotiation to ssl-opt.sh.
2019-05-20 15:32:36 +01:00
Hanno Becker
b7f9e9c9a5 Reintroduce grepping for debug messages in CID tests in ssl-opt.sh 2019-05-20 15:32:36 +01:00
Hanno Becker
4932f9f229 Re-enable passing CIDs to record transforms 2019-05-20 15:32:36 +01:00
Hanno Becker
687e0fb568 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-05-20 15:32:36 +01:00
Hanno Becker
abd7c89923 Re-enable CID comparison when decrypting CID-based records 2019-05-20 15:32:36 +01:00
Hanno Becker
8b09b73cb1 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-05-20 15:32:36 +01:00
Hanno Becker
ff3e9c2d0d 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-05-20 15:32:36 +01:00
Hanno Becker
70e7928d76 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-05-20 15:32:36 +01:00
Hanno Becker
add0190059 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-05-20 15:32:36 +01:00
Hanno Becker
eec2be9c9f 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-05-20 15:32:36 +01:00
Hanno Becker
ccc2456db9 Re-implement mbedtls_ssl_{in/out}_hdr_len() via in/out pointers 2019-05-20 15:32:36 +01:00
Hanno Becker
4339576208 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-05-20 15:32:36 +01:00
Hanno Becker
46483f11bf 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-05-20 15:32:36 +01:00
Hanno Becker
74dd3a70d8 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-05-20 15:32:36 +01:00
Hanno Becker
f5970a0945 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-05-20 15:32:36 +01:00
Hanno Becker
16e9ae2f95 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-05-20 15:32:36 +01:00
Hanno Becker
70463dbb2d Expain rationale for handling of consecutive empty AD records 2019-05-20 15:32:36 +01:00
Hanno Becker
78c430269b Don't allow calling CID API outside of DTLS 2019-05-20 15:32:36 +01:00
Hanno Becker
6943920839 Add missing dependencies in unit tests for CID-based record enc/dec
Changes generated via:
% sed -i '/.*CID [0-9]+[0-9]/{n;s/depends_on:/depends_on:MBEDTLS_SSL_CID:/}' test_suite_ssl.data
2019-05-20 15:23:27 +01:00
Hanno Becker
1f02f05f2e 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-05-20 15:17:05 +01:00
Hanno Becker
3b1a88506b Remove unnecessary empty line in ssl_tls.c 2019-05-20 15:10:50 +01:00
Hanno Becker
7dc2577f01 Don't quote DTLSInnerPlaintext structure multiple times 2019-05-20 15:08:01 +01:00
Hanno Becker
8969369a83 Improve wording in ssl_build_inner_plaintext() 2019-05-20 15:06:12 +01:00
Hanno Becker
24ce1eba66 Remove unnecessary whitespace in ssl_extract_add_data_from_record() 2019-05-20 15:01:46 +01:00
Hanno Becker
28a0c4e149 Reduce stack usage for additional data buffers in record dec/enc 2019-05-20 14:56:03 +01:00
Hanno Becker
acadb0a8c9 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-05-20 14:55:59 +01:00
Hanno Becker
99abf51056 Improve documentation of ssl_extract_add_data_from_record() 2019-05-20 14:55:30 +01:00
Hanno Becker
346a590c1c Unify documentation of internal SSL record structure
- Don't use Doxygen style comments
- Document CID and CID length fields.
2019-05-20 14:49:02 +01:00
Manuel Pégourié-Gonnard
9c5bcc9220 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-05-20 12:09:50 +02:00
Manuel Pégourié-Gonnard
762d011ece Fix alignment issues 2019-05-20 10:27:20 +02:00
Manuel Pégourié-Gonnard
42c814fdc1 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-05-20 10:12:43 +02:00
Manuel Pégourié-Gonnard
5478e1e5ed 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-05-20 10:07:29 +02:00
Hanno Becker
505089d944 Fix missing compile-time guards around CID-only constants 2019-05-17 10:23:47 +01:00
Hanno Becker
4c6fe12db8 Remove TODO 2019-05-17 10:23:47 +01:00
Hanno Becker
2e7cd5aa4c Use MBEDTLS_ namespace for internal CID length constant 2019-05-17 10:23:47 +01:00
Hanno Becker
d91dc3767f 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-05-17 10:23:47 +01:00
Hanno Becker
92c930f7c4 Implement inner plaintext parsing/writing for CID-based connections 2019-05-17 10:23:47 +01:00
Hanno Becker
d8f753bd04 Add unit tests for record protection using CID 2019-05-17 10:23:47 +01:00
Hanno Becker
36fb379f68 Record enc/dec tests: Don't take turns in sending / receiving roles
Part of the record encryption/decryption tests is to gradually
increase the space available at the front and/or at the back of
a record and observe when encryption starts to succeed. If exactly
one of the two parameters is varied at a time, the expectation is
that encryption will continue to succeed once it has started
succeeding (that's not true if both pre- and post-space are varied
at the same time).

Moreover, previously the test would take turns when choosing which
transform should be used for encryption, and which for decryption.

With the introduction of the CID feaature, this switching of transforms
doesn't align with the expectation of eventual success of the encryption,
since the overhead of encryption might be different for the parties,
because both parties may use different CIDs for their outgoing records.

This commit modifies the tests to not take turns between transforms,
but to always use the same transforms for encryption and decryption
during a single round of the test.
2019-05-17 10:23:47 +01:00
Hanno Becker
e83efe6d79 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-05-17 10:23:47 +01:00
Hanno Becker
80fe63e082 Add CID field to internal structure representing TLS records
This commit adds a static array `cid` to the internal structure
`mbedtls_record` representing encrypted and decrypted TLS records.

The expected evolution of state of this field is as follows:
- When handling an incoming record, the caller of `mbedtls_decrypt_buf()`
  has to make sure the CID array field in `mbedtls_record` has been
  properly set. Concretely, it will be copied from the CID from the record
  header during record parsing.
- During decryption in `mbedtls_decrypt_buf()`, the transforms
  incoming CID is compared to the CID in the `mbedtls_record`
  structure representing the record to be decrypted.
- For an outgoing TLS record, the caller of `mbedtls_encrypt_buf()`
  clears the CID in the `mbedtls_record` structure.
- During encryption in `mbedtls_encrypt_buf()`, the CID field in
  `mbedtls_record` will be copied from the out-CID in the transform.
2019-05-17 10:23:47 +01:00
Hanno Becker
8013b27481 Replace 'ingoing' -> 'incoming' in CID debug messages 2019-05-17 10:20:41 +01:00
Hanno Becker
cb063f5a5b Document behaviour of mbedtls_ssl_get_peer_cid() for empty CIDs 2019-05-17 10:20:41 +01:00
Hanno Becker
f885d3bba2 Improve structure of client-side CID extension parsing
Group configuring CID values together.
2019-05-17 10:20:41 +01:00
Hanno Becker
8f68f87382 Improve debugging output of client-side CID extension parsing 2019-05-17 10:20:41 +01:00
Hanno Becker
19976b5345 Improve structure of ssl_parse_cid_ext()
Group configuring CID values together.
2019-05-17 10:20:41 +01:00
Hanno Becker
fc7ff9289f Use unused extension ID as tentative ID for CID extension 2019-05-17 10:20:41 +01:00
Hanno Becker
4ce06047e1 Enable use of CID in baremetal configuration and test script 2019-05-17 10:20:41 +01:00
Hanno Becker
2e0bedcc35 Correct compile-time guard around unhexify() in ssl_server2 2019-05-17 10:20:41 +01:00
Hanno Becker
31f1668d3c Correct compile-time guard around CID extension writing func on srv 2019-05-17 10:20:41 +01:00
Hanno Becker
b4a5606e2d Make integer truncation explicit in mbedtls_ssl_set_cid() 2019-05-17 10:20:41 +01:00
Hanno Becker
6a3ff286a5 Grep for dbug msgs witnessing use of CID in ssl_client2/ssl_server2 2019-05-17 10:20:41 +01:00
Hanno Becker
0c8281aae5 Change formating of CID debug output in ssl_client2/ssl_server2 2019-05-17 10:20:41 +01:00
Hanno Becker
2de89fae8f Implement mbedtls_ssl_get_peer_cid() 2019-05-17 10:20:41 +01:00
Hanno Becker
5e2cd1422e Grep for dbg msg witnessing copying of CIDs to SSL transform 2019-05-17 10:20:41 +01:00
Hanno Becker
dd0afca3f6 Copy CIDs into SSL transform if use of CID has been negotiated 2019-05-17 10:20:41 +01:00
Hanno Becker
4f0b15faec Add fields holding in/out CIDs to SSL record transformation struct
These will be copied from the CID fields in mbedtls_ssl_handshake_params
(outgoing CID) and mbedtls_ssl_context (incoming CID) when the transformation
is set up at the end of the handshake.
2019-05-17 10:20:41 +01:00
Hanno Becker
cf2a565e3e Grep for dbg msg witnessing parsing of CID extension in ServerHello 2019-05-17 10:20:41 +01:00
Hanno Becker
1ba81f62a6 Implement parsing of CID extension in ServerHello 2019-05-17 10:20:41 +01:00
Hanno Becker
4eb0587c0f Grep for dbg msg witnessing writing of CID extension in ServerHello 2019-05-17 10:20:41 +01:00
Hanno Becker
072d4eca2e Implement writing of CID extension in ServerHello 2019-05-17 10:20:41 +01:00
Hanno Becker
c008cb5f8c Grep for dbg msg witnessing parsing of CID extension in ClientHello 2019-05-17 10:20:41 +01:00
Hanno Becker
c403b264e8 Implement parsing of CID extension in ClientHello 2019-05-17 10:20:41 +01:00
Hanno Becker
7345599a7b Grep for dbg msg witnessing writing of CID extension in ClientHello 2019-05-17 10:20:41 +01:00
Hanno Becker
39ec525e4f Implement writing of CID extension in ClientHello 2019-05-17 10:20:41 +01:00
Hanno Becker
46629717c9 Check static bounds of CID lengths in check_config.h 2019-05-17 10:20:41 +01:00
Hanno Becker
4baec2c4bf Add identifier for CID extension
Note: The current draft

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

does not yet specify the extension value, so we
use a temporary value of 42.
2019-05-17 10:20:41 +01:00
Hanno Becker
9dae9fd57b Modify CID tests in ssl-opt.sh to grep for CID config debug msgs 2019-05-17 10:20:41 +01:00
Hanno Becker
0748986178 Allow configuring own CID fields through mbedtls_ssl_get_peer_cid() 2019-05-17 10:20:41 +01:00
Hanno Becker
e5e7f621cc Add fields to SSL structures describing state and config of CID ext
* mbedtls_ssl_context gets fields indicating whether the CID extension
  should be negotiated in the next handshake, and, if yes, which CID
  the user wishes the peer to use.

  This information does not belong to mbedtls_ssl_handshake_params
  because (a) it is configured prior to the handshake, and (b) it
  applies to all subsequent handshakes.

* mbedtls_ssl_handshake_params gets fields indicating the state of CID
  negotiation during the handshake. Specifically, it indicates if the
  use of the CID extension has been negotiated, and if so, which CID
  the peer wishes us to use for outgoing messages.
2019-05-17 10:20:41 +01:00
Hanno Becker
fce6f836ba Merge branch 'mbedtls-2.16' into baremetal 2019-05-17 10:06:02 +01:00
Manuel Pégourié-Gonnard
84ef8bde68 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-05-10 10:50:04 +02:00
Manuel Pégourié-Gonnard
cf31216ace Fix typo in comment 2019-05-10 10:25:00 +02:00
Simon Butcher
724a695534 Merge remote-tracking branch 'origin/pr/562' into baremetal 2019-05-09 17:11:38 +01:00
Simon Butcher
e372d5fb8f Merge remote-tracking branch 'origin/pr/558' into baremetal 2019-05-09 17:03:18 +01:00
Simon Butcher
999ac174cc Merge remote-tracking branch 'origin/pr/566' into baremetal 2019-05-09 16:59:02 +01:00
Simon Butcher
ec998c6426 Merge remote-tracking branch 'origin/pr/564' into baremetal 2019-05-09 16:56:42 +01:00
Manuel Pégourié-Gonnard
00c99d776a Clarify origin and licensing of TinyCrypt files 2019-05-09 11:38:19 +02:00
Manuel Pégourié-Gonnard
afdc1b5cbd Consistently use the name tinycrypt over uecc
We called in tinycrypt in the file names, but uecc in config.h, all.sh and
other places, which could be confusing. Just use tinycrypt everywhere because
that's the name of the project and repo where we took the files.

The changes were made using the following commands (with GNU sed and zsh):

sed -i 's/uecc/tinycrypt/g' **/*.[ch] tests/scripts/all.sh
sed -i 's/MBEDTLS_USE_UECC/MBEDTLS_USE_TINYCRYPT/g' **/*.[ch] tests/scripts/all.sh scripts/config.pl
2019-05-09 11:24:11 +02:00
Manuel Pégourié-Gonnard
86e48c213c Enforce promise to not use whole ssl context
Configs with no DEBUG_C are use 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-05-07 10:32:19 +02:00
Manuel Pégourié-Gonnard
1d10a98f56 Partially rm 'ssl' input from populate_transform() 2019-05-07 10:31:53 +02:00
Manuel Pégourié-Gonnard
0bcfbc3e04 Remove "handshake" input from populate_transform() 2019-05-07 09:59:41 +02:00
Manuel Pégourié-Gonnard
12a3f445b6 Start refining parameters of populate_transform()
Parameters 'handshake' and 'ssl' will be replaced with more fine-grained
inputs in follow-up commits.
2019-05-07 09:59:41 +02:00
Manuel Pégourié-Gonnard
a1abb26094 Move compress_buf allocation to derive_keys 2019-05-07 09:59:41 +02:00
Manuel Pégourié-Gonnard
707728dfca Move handling of randbytes to derive_keys() 2019-05-07 09:59:41 +02:00
Manuel Pégourié-Gonnard
bcf258e077 Remove duplicated branch in ssl_compute_master() 2019-05-07 09:59:40 +02:00
Manuel Pégourié-Gonnard
a575975280 Make calc_verify() return the length as well
Simplifies ssl_compute_hash(), but unfortunately not so much the other uses.
2019-05-07 09:59:32 +02:00
Manuel Pégourié-Gonnard
ed3b7a9492 Constify ssl_context param of calc_verify() 2019-05-03 10:00:45 +02:00
Manuel Pégourié-Gonnard
c28c8895e5 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-05-03 10:00:45 +02:00
Manuel Pégourié-Gonnard
dafe5227d4 Reduce indentation in ssl_compute_master()
Exit earlier when there's noting to do.

For a small diff, review with 'git show -w'.
2019-05-03 10:00:44 +02:00
Manuel Pégourié-Gonnard
7edd5876ce 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-05-03 10:00:44 +02:00
Manuel Pégourié-Gonnard
aa3c701193 Fix signature of ssl_set_transform_prfs() 2019-05-03 10:00:44 +02:00
Jarno Lamsa
8751e35751 Remove baremetal from build component names 2019-05-02 13:04:08 +03:00
Jarno Lamsa
4498de57b8 Address review comments about all.sh 2019-05-02 11:45:57 +03:00
Jarno Lamsa
0668b8f59e Description of MBEDTLS_USE_UECC 2019-05-02 09:39:09 +03:00
Jarno Lamsa
d91f7fa26b Add native build targets for uecc baremetal config 2019-04-30 14:29:23 +03:00
Jarno Lamsa
65ea285759 Fix typo 2019-04-30 13:00:41 +03:00
Manuel Pégourié-Gonnard
52aa520c96 Start extraction ssl_set_handshake_prfs()
For now just moving code around, will improve signature in the next commit.
2019-04-30 11:54:22 +02:00
Manuel Pégourié-Gonnard
5ed5e90ec4 Start splitting populate_transform() out of derive_keys()
This is currently a dummy, just introducing the new name.
2019-04-30 11:41:40 +02:00
Jarno Lamsa
f6371ff923 Add armcc5 build for uecc and baremetal config 2019-04-30 10:10:03 +03:00
Jarno Lamsa
46132207f8 Make compiler happy when MBEDTLS_USE_UECC disabled 2019-04-29 14:29:52 +03:00
Hanno Becker
08885813c3 Fix uninitialized variable access in debug output of record enc/dec 2019-04-29 12:21:31 +02:00
Hanno Becker
a131766743 Ensure non-NULL key buffer when building SSL test transforms 2019-04-29 12:19:38 +02:00
Hanno Becker
1acadb77cb Catch errors while building SSL test transforms 2019-04-29 12:19:38 +02:00
Hanno Becker
afc528ad56 Use mbedtls_{calloc|free}() in SSL unit test suite 2019-04-29 12:19:24 +02:00
Hanno Becker
f832343c1d Improve documentation of mbedtls_record 2019-04-29 12:19:07 +02:00
Hanno Becker
c5aee96855 Adapt record length value after encryption 2019-04-29 12:19:07 +02:00
Hanno Becker
b17a1a2068 Alternative between send/recv transform in SSL record test suite 2019-04-29 12:19:07 +02:00
Hanno Becker
5c1176e53f Fix memory leak on failure in test_suite_ssl 2019-04-29 12:18:50 +02:00
Hanno Becker
30d02cdeb0 Rename ssl_decrypt_buf() to mbedtls_ssl_decrypt_buf() in comment 2019-04-29 12:18:38 +02:00
Hanno Becker
3693c72b82 Add record encryption/decryption tests for ARIA to SSL test suite 2019-04-29 12:18:27 +02:00
Hanno Becker
a198bb7359 Improve documentation of mbedtls_ssl_transform 2019-04-29 12:18:11 +02:00
Hanno Becker
93012fe8e8 Double check that record expansion is as expected during decryption 2019-04-29 12:17:58 +02:00
Hanno Becker
a795323cd5 Move debugging output after record decryption
The debugging call printing the decrypted record payload happened
before updating ssl->in_msglen.
2019-04-29 12:17:51 +02:00
Hanno Becker
d300003b2c Add encryption/decryption tests for small records
This commit adds tests to check the behavior of the record encryption
routine `ssl_encrypt_buf` when the buffer surrounding the plaintext is
too small to hold the expansion in the beginning and end (due to IV's,
padding, and MAC).

Each test starts successively increases the space available at the
beginning, end, or both, of the record buffer, and checks that the
record encryption either fails with a BUFFER_TOO_SMALL error, or
that it succeeds. Moreover, if it succeeds, it is checked that
decryption succeeds, too, and results in the original record.
2019-04-29 12:15:30 +02:00
Hanno Becker
611a83b571 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-29 12:15:21 +02:00
Hanno Becker
92231325a7 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-29 12:15:05 +02:00
Hanno Becker
f122944b7d 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-29 12:14:51 +02:00
Hanno Becker
4c6876b134 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-29 12:13:25 +02:00
Jarno Lamsa
00c0aa01b4 Exclude MBEDTLS_USE_UECC from the full config 2019-04-29 12:59:10 +03:00
Jarno Lamsa
ce3cb64aeb Fix check-names.sh 2019-04-29 12:07:43 +03:00
Hanno Becker
3307b53413 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-29 10:58:15 +02:00
Hanno Becker
4a5eeaee2e Improve documentation of mbedtls_ssl_transform 2019-04-29 10:37:01 +02:00
Hanno Becker
9d2e4b4742 Add structure representing TLS records
This commit adds a structure `mbedtls_record` whose instances
represent (D)TLS records. This structure will be used in the
subsequent adaptions of the record encryption and decryption
routines `ssl_decrypt_buf` and `ssl_encrypt_buf`, which currently
take the entire SSL context as input, but should only use the
record to be acted on as well as the record transformation to use.
2019-04-29 10:36:44 +02:00
Hanno Becker
b628a80b76 Fix definition of SSL_SOME_MODES_USE_MAC
The previous definition was lacking the case of the ARIA and DES ciphers.
2019-04-29 10:36:26 +02:00
Hanno Becker
5cc04d5ae7 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-29 10:36:09 +02:00
Hanno Becker
8759e16242 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-29 10:36:01 +02:00
Hanno Becker
e7f2df03a3 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-29 09:32:08 +02:00
Jarno Lamsa
5b871285f5 MBEDTLS_USE_UECC and MBEDTLS_NO_64BIT_MULTIPLICATION conflicting 2019-04-29 10:29:06 +03:00
Jarno Lamsa
55427964b1 Guard tinycrypt files with MBEDTLS_USE_UECC 2019-04-29 10:25:23 +03:00
Jarno Lamsa
8557fc9220 Add whitelist for uECC files for check-names.sh
Whitelist currently includes the unmatching symbols from uECC files.
This is now specific for the baremetal branch.
2019-04-26 16:22:10 +03:00
Jarno Lamsa
95de220ade Ignore tinycrypt headers from doxygen input 2019-04-25 15:11:29 +03:00
Jarno Lamsa
02493afe6c Ignore tinycrypt files from check-files.py 2019-04-25 14:56:17 +03:00
Jarno Lamsa
6fe99be972 Fix check-generated-files after creating a flag 2019-04-25 13:54:32 +03:00
Jarno Lamsa
6f519a3b22 Fix typo in CMakeLists.txt 2019-04-25 13:51:54 +03:00
Jarno Lamsa
337dad98f6 Tinycrypt support for makefile builds 2019-04-25 11:00:41 +03:00
Jarno Lamsa
187fbb1334 Use mbedtls_platform_zeroize in uecc code
ecc_dh.c used memset and gcc-specific asm-commands, changed those
to use mbedtls_platform_zeroize to allow compilation with different
compilers.
2019-04-25 09:03:19 +03:00
Simon Butcher
2e7c7cd756 Merge remote-tracking branch 'public/mbedtls-2.16' into baremetal
* public/mbedtls-2.16: (40 commits)
  Clarify comment mangled by an earlier refactoring
  Add an "out-of-box" component
  Run ssl-opt.sh on 32-bit runtime
  Fix typo in data_file generator code
  Give credit to OSS-Fuzz for #2404
  Remove ssl_cert_test sample app
  Fix the proxy seed in Travis runs
  Update library version to 2.16.1
  Fix errors in AEAD test function
  x509.c: Fix potential memory leak in X.509 self test
  Remove Circle CI script
  Fix ChangeLog entry ordering
  Fix typo
  Add non-regression test for buffer overflow
  Improve documentation of mbedtls_mpi_write_string()
  Adapt ChangeLog
  Fix 1-byte buffer overflow in mbedtls_mpi_write_string()
  Change Perl to Python in test builds
  Fix default port number information
  Silence pylint
  ...
2019-04-24 14:51:33 +01:00
Jarno Lamsa
9454dfaed4 Add a new flag for the micro-ecc 2019-04-24 16:28:59 +03:00
Jarno Lamsa
d50fd6b373 Remove unused headers from uecc sources 2019-04-24 16:19:50 +03:00
Jarno Lamsa
79e3b946db Add CMake support for uecc 2019-04-24 16:17:10 +03:00
Jarno Lamsa
18987a420b Add micro-ecc based ecc-files to mbedtls
The files are from https://github.com/intel/tinycrypt
Using commit 6e0eb53fc8403988f97345e94081b0453f47231d as a base.
2019-04-24 15:40:43 +03:00
Hanno Becker
ba8cd67467 Guard CID implementations by MBEDTLS_SSL_CID 2019-04-23 12:31:42 +01:00
Hanno Becker
b60c85c67c Indicate ssl-opt.sh CID tests only test the stub CID code 2019-04-23 12:02:34 +01:00
Hanno Becker
8d0893d0b0 Add warnings about status of implementation of CID API 2019-04-23 12:01:20 +01:00
Hanno Becker
963cb35a24 Fix use of requires_config_enabled in ssl-opt.sh
requires_config_enabled doesn't support multiple config options.
Tests having multiple configuration dependencies must be prefixed
with multiple invocations of requires_config_enabled instead.
2019-04-23 11:52:44 +01:00
Hanno Becker
4f98b6ad17 Fix typo in CID test in ssl-opt.sh 2019-04-23 11:52:14 +01:00
Hanno Becker
6dde3dd8ec Print peer CID from ssl_client2 2019-04-23 11:51:47 +01:00
Hanno Becker
8be8a95dea Print peer CID from ssl_server2 2019-04-23 11:51:40 +01:00
Hanno Becker
14751aa966 Improve wording of CID debug msg in ssl_server2 example application 2019-04-23 11:39:53 +01:00
Hanno Becker
b9b7e29536 Clarify that mbedtls_ssl_set_cid() applies to all subsequent HSs 2019-04-23 11:38:47 +01:00
Hanno Becker
d928c06d01 Document that the use of CID is disabled by default.
(Even if MBEDTLS_SSL_CID is set in config.h)
2019-04-23 11:37:38 +01:00
Hanno Becker
efde5b2e96 Reference CID Draft in Connection ID documentation in config.h 2019-04-23 11:36:56 +01:00
Simon Butcher
7326bc8577
Merge pull request #2524 from hanno-arm/baremetal_config
[Baremetal] Introduce baremetal config and scripts to measure memory usage
2019-04-12 17:19:40 +01:00
Hanno Becker
224eb0c53b Use AES-128 instead of AES-256 in baremetal ciphersuite 2019-04-10 12:24:10 +01:00
Hanno Becker
2dcdc926b6 Add basic Connection ID tests to ssl-opt.sh 2019-04-09 18:27:04 +01:00
Hanno Becker
1029acee1d ssl_server2: Add cmd line options to configure use of CID extension 2019-04-09 18:27:04 +01:00
Hanno Becker
7a7aa1943e ssl_client2: Add cmd line options to configure use of CID extension 2019-04-09 18:27:04 +01:00
Hanno Becker
ec37030afe ssl_client2: Add helper to unhexify binary command line data 2019-04-09 18:27:04 +01:00
Hanno Becker
b9e7dea082 Add dummy implementations for CID API 2019-04-09 18:26:59 +01:00
Hanno Becker
2c54db5e66 Update version_features.c 2019-04-09 18:26:59 +01:00
Hanno Becker
c8e80eeda0 Update query_config.c 2019-04-09 18:26:59 +01:00
Hanno Becker
29a54c8415 Add dep of MBEDTLS_SSL_CID on MBEDTLS_SSL_PROTO_DTLS to config check 2019-04-09 18:26:59 +01:00
Hanno Becker
6198af33a0 Add API for the use of the DTLS Connection ID extension 2019-04-09 18:26:53 +01:00
Hanno Becker
81bd97149f Add new configuration option controlling CID extension 2019-04-09 15:12:41 +01:00
Hanno Becker
7f6e808212 Remove uninitialized variable error in baremetal.sh 2019-04-03 13:48:09 +01:00
Hanno Becker
b4d8fab27e Rename generate_codesize_stats.sh to extract_codesize_stats.sh 2019-04-03 13:46:27 +01:00
Hanno Becker
275e5bfb9b Remove TODO from configs/baremetal.h 2019-04-03 13:39:31 +01:00
Hanno Becker
1373724166 Add static callgraph output to baremetal.sh --ram --stack 2019-04-03 12:17:20 +01:00
Hanno Becker
e6c3c7f52c Correct ECP optimization params in baremetal_test.sh 2019-04-03 12:04:32 +01:00
Hanno Becker
c7c20817dc Measure stack usage in baremetal script
So far, `baremetal.sh --ram --stack` ran `callgrind` to extract
a call stack in an example run of ssl_client2 and ssl_server2.
This, however, needs to be complemented with per-function stack
usage to be able to extract the maximum stack usage.

This commit adds `-fstack-usage` to the CFLAGS used when building
the library in `baremetal.sh --ram` runs, which generates *.su
files indicating the stack usage of individual functions.
2019-04-03 12:04:26 +01:00
Hanno Becker
7a097859c5 Correct usage instructions for baremetal script 2019-04-03 11:55:40 +01:00
Hanno Becker
a778959572 Don't ignore I/O and ECP heap usage in baremetal script 2019-04-03 11:31:54 +01:00
Hanno Becker
5541e4ecde Add usage instructions to baremetal heap+stack usage function 2019-04-03 11:31:43 +01:00
Hanno Becker
085ab567ae Optimize baremetal ECP configuration 2019-04-03 11:31:31 +01:00
Hanno Becker
43fa8d645b Add scripts to build, test and measure baremetal configuration 2019-03-21 15:09:41 +00:00
Hanno Becker
abc22b780f Add baremetal configuration to configs folder
This commit adds a minimal test configuration `baremetal.h` to the `configs`
folder supporting ECDHE-ECDSA-AES-CCM-8 with Secp256R1 and SHA-256 only.

The configuration lacks some options which are currently needed to
successfully build and run the example applications `ssl_client2`
and `ssl_server2`, such as `MBEDTLS_NET_C`. To still allow testing
a configuration close to `baremetal.h`, the commit also adds
`baremetal_test.h`, containing minimal amendments to `baremetal.h`
that allow building and running `ssl_client2` and `ssl_server2`.
2019-03-19 15:12:29 +00:00
359 changed files with 48951 additions and 13245 deletions

View file

@ -1,8 +1,5 @@
Notes:
* Pull requests cannot be accepted until:
- The submitter has [accepted the online agreement here with a click through](https://developer.mbed.org/contributor_agreement/)
or for companies or those that do not wish to create an mbed account, a slightly different agreement can be found [here](https://www.mbed.com/en/about-mbed/contributor-license-agreements/)
- The PR follows the [mbed TLS coding standards](https://tls.mbed.org/kb/development/mbedtls-coding-standards)
* Pull requests cannot be accepted until the PR follows the [contributing guidelines](../CONTRIBUTING.md). In particular, each commit must have at least one `Signed-off-by:` line from the committer to certify that the contribution is made under the terms of the [Developer Certificate of Origin](../dco.txt).
* This is just a template, so feel free to use/remove the unnecessary things
## Description
A few sentences describing the overall goals of the pull request's commits.

3
.gitignore vendored
View file

@ -22,6 +22,9 @@ Coverage
# generated by scripts/memory.sh
massif-*
# scripts/baremetal.sh --ram build artefacts:
*.su
# MSVC build artifacts:
*.exe
*.pdb

View file

@ -40,7 +40,27 @@ max-attributes=15
max-module-lines=2000
[MESSAGES CONTROL]
disable=
# * locally-disabled, locally-enabled: If we disable or enable a message
# locally, it's by design. There's no need to clutter the Pylint output
# with this information.
# * logging-format-interpolation: Pylint warns about things like
# ``log.info('...'.format(...))``. It insists on ``log.info('...', ...)``.
# This is of minor utility (mainly a performance gain when there are
# many messages that use formatting and are below the log level).
# Some versions of Pylint (including 1.8, which is the version on
# Ubuntu 18.04) only recognize old-style format strings using '%',
# and complain about something like ``log.info('{}', foo)`` with
# logging-too-many-args (Pylint supports new-style formatting if
# declared globally with logging_format_style under [LOGGING] but
# this requires Pylint >=2.2).
# * no-else-return: Allow the perfectly reasonable idiom
# if condition1:
# return value1
# else:
# return value2
# * unnecessary-pass: If we take the trouble of adding a line with "pass",
# it's because we think the code is clearer that way.
disable=locally-disabled,locally-enabled,logging-format-interpolation,no-else-return,unnecessary-pass
[REPORTS]
# Don't diplay statistics. Just the facts.

View file

@ -1,48 +1,64 @@
language: c
compiler:
- clang
- gcc
compiler: gcc
sudo: false
cache: ccache
# blocklist
branches:
except:
- development-psa
- coverity_scan
jobs:
include:
- name: basic checks and reference configurations
addons:
apt:
packages:
- gnutls-bin
- doxygen
- graphviz
- gcc-arm-none-eabi
- libnewlib-arm-none-eabi
language: python # Needed to get pip for Python 3
python: 3.5 # version from Ubuntu 16.04
install:
- pip install pylint==2.4.4
script:
- tests/scripts/all.sh -k 'check_*'
- tests/scripts/all.sh -k test_default_out_of_box
- tests/scripts/test-ref-configs.pl
- tests/scripts/all.sh -k build_arm_none_eabi_gcc_arm5vte build_arm_none_eabi_gcc_m0plus
- name: full configuration
script:
- tests/scripts/all.sh -k test_full_cmake_gcc_asan
- name: check compilation guards
script:
- tests/scripts/all.sh -k 'test_depends_*' 'build_key_exchanges'
- name: macOS
os: osx
compiler: clang
script:
- tests/scripts/all.sh -k test_default_out_of_box
- name: Windows
os: windows
script:
- scripts/windows_msbuild.bat v141 # Visual Studio 2017
script:
- tests/scripts/recursion.pl library/*.c
- tests/scripts/check-generated-files.sh
- tests/scripts/check-doxy-blocks.pl
- tests/scripts/check-names.sh
- tests/scripts/check-files.py
- tests/scripts/doxygen.sh
- cmake -D CMAKE_BUILD_TYPE:String="Check" .
- make
- make test
- programs/test/selftest
- OSSL_NO_DTLS=1 tests/compat.sh
- tests/ssl-opt.sh -e '\(DTLS\|SCSV\).*openssl'
- tests/scripts/test-ref-configs.pl
- tests/scripts/curves.pl
- tests/scripts/key-exchanges.pl
after_failure:
- tests/scripts/travis-log-failure.sh
env:
global:
- SEED=1
- secure: "barHldniAfXyoWOD/vcO+E6/Xm4fmcaUoC9BeKW+LwsHqlDMLvugaJnmLXkSpkbYhVL61Hzf3bo0KPJn88AFc5Rkf8oYHPjH4adMnVXkf3B9ghHCgznqHsAH3choo6tnPxaFgOwOYmLGb382nQxfE5lUdvnM/W/psQjWt66A1+k="
- secure: "FrI5d2s+ckckC17T66c8jm2jV6i2DkBPU5nyWzwbedjmEBeocREfQLd/x8yKpPzLDz7ghOvr+/GQvsPPn0dVkGlNzm3Q+hGHc/ujnASuUtGrcuMM+0ALnJ3k4rFr9xEvjJeWb4SmhJO5UCAZYvTItW4k7+bj9L+R6lt3TzQbXzg="
addons:
apt:
packages:
- doxygen
- graphviz
- gnutls-bin
coverity_scan:
project:
name: "ARMmbed/mbedtls"
notification_email: simon.butcher@arm.com
notification_email: support-mbedtls@arm.com
build_command_prepend:
build_command: make
branch_pattern: coverity_scan

View file

@ -186,6 +186,10 @@ endif(ENABLE_ZLIB_SUPPORT)
add_subdirectory(library)
add_subdirectory(include)
if(USE_TINYCRYPT)
add_subdirectory(tinycrypt)
endif()
if(ENABLE_PROGRAMS)
add_subdirectory(programs)
endif()

View file

@ -5,11 +5,6 @@ We gratefully accept bug reports and contributions from the community. There are
- As with any open source project, contributions will be reviewed by the project team and community and may need some modifications to be accepted.
- The contribution should not break API or ABI, unless there is a real justification for that. If there is an API change, the contribution, if accepted, will be merged only when there will be a major release.
Contributor License Agreement (CLA)
-----------------------------------
- All contributions, whether large or small, require a Contributor's License Agreement (CLA) to be accepted. This is because source code can possibly fall under copyright law and we need your consent to share in the ownership of the copyright.
- To accept the Contributors License Agreement (CLA), individual contributors can do this by creating an Mbed account and [accepting the online agreement here with a click through](https://developer.mbed.org/contributor_agreement/). Alternatively, for contributions from corporations, or those that do not wish to create an Mbed account, a slightly different agreement can be found [here](https://www.mbed.com/en/about-mbed/contributor-license-agreements/). This agreement should be signed and returned to Arm as described in the instructions given.
Coding Standards
----------------
- We would ask that contributions conform to [our coding standards](https://tls.mbed.org/kb/development/mbedtls-coding-standards), and that contributions are fully tested before submission, as mentioned in the [Tests](#tests) and [Continuous Integration](#continuous-integration-tests) sections.
@ -19,12 +14,13 @@ Coding Standards
Making a Contribution
---------------------
1. [Check for open issues](https://github.com/ARMmbed/mbedtls/issues) or [start a discussion](https://tls.mbed.org/discussions) around a feature idea or a bug.
1. [Check for open issues](https://github.com/ARMmbed/mbedtls/issues) or [start a discussion](https://lists.trustedfirmware.org/mailman/listinfo/mbed-tls) around a feature idea or a bug.
1. Fork the [Mbed TLS repository on GitHub](https://github.com/ARMmbed/mbedtls) to start making your changes. As a general rule, you should use the ["development" branch](https://github.com/ARMmbed/mbedtls/tree/development) as a basis.
1. Write a test which shows that the bug was fixed or that the feature works as expected.
1. Send a pull request (PR) and work with us until it gets merged and published. Contributions may need some modifications, so a few rounds of review and fixing may be necessary. We will include your name in the ChangeLog :)
1. For quick merging, the contribution should be short, and concentrated on a single feature or topic. The larger the contribution is, the longer it would take to review it and merge it.
1. Mbed TLS is released under the Apache license, and as such, all the added files should include the Apache license header.
1. All new files should include the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) standard license header where possible.
1. Ensure that each commit has at least one `Signed-off-by:` line from the committer. If anyone else contributes to the commit, they should also add their own `Signed-off-by:` line. By adding this line, contributor(s) certify that the contribution is made under the terms of the [Developer Certificate of Origin](dco.txt). The contribution licensing is described in the [License section of the README](README.md#License).
API/ABI Compatibility
---------------------
@ -46,18 +42,14 @@ Mbed TLS maintains several LTS (Long Term Support) branches, which are maintaine
When backporting to these branches please observe the following rules:
1. Any change to the library which changes the API or ABI cannot be backported.
2. All bug fixes that correct a defect that is also present in an LTS branch must be backported to that LTS branch. If a bug fix introduces a change to the API such as a new function, the fix should be reworked to avoid the API change. API changes without very strong justification are unlikely to be accepted.
3. If a contribution is a new feature or enhancement, no backporting is required. Exceptions to this may be additional test cases or quality improvements such as changes to build or test scripts.
1. Any change to the library which changes the API or ABI cannot be backported.
1. All bug fixes that correct a defect that is also present in an LTS branch must be backported to that LTS branch. If a bug fix introduces a change to the API such as a new function, the fix should be reworked to avoid the API change. API changes without very strong justification are unlikely to be accepted.
1. If a contribution is a new feature or enhancement, no backporting is required. Exceptions to this may be additional test cases or quality improvements such as changes to build or test scripts.
It would be highly appreciated if contributions are backported to LTS branches in addition to the [development branch](https://github.com/ARMmbed/mbedtls/tree/development) by contributors.
Currently maintained LTS branches are:
1. [mbedtls-2.7](https://github.com/ARMmbed/mbedtls/tree/mbedtls-2.7)
1. [mbedtls-2.16](https://github.com/ARMmbed/mbedtls/tree/mbedtls-2.16)
@ -84,12 +76,7 @@ Documentation
Mbed TLS is well documented, but if you think documentation is needed, speak out!
1. All interfaces should be documented through Doxygen. New APIs should introduce Doxygen documentation.
2. Complex parts in the code should include comments.
3. If needed, a Readme file is advised.
4. If a [Knowledge Base (KB)](https://tls.mbed.org/kb) article should be added, write this as a comment in the PR description.
5. A [ChangeLog](https://github.com/ARMmbed/mbedtls/blob/development/ChangeLog) entry should be added for this contribution.
1. Complex parts in the code should include comments.
1. If needed, a Readme file is advised.
1. If a [Knowledge Base (KB)](https://tls.mbed.org/kb) article should be added, write this as a comment in the PR description.
1. A [ChangeLog](https://github.com/ARMmbed/mbedtls/blob/development/ChangeLog) entry should be added for this contribution.

137
ChangeLog
View file

@ -1,15 +1,148 @@
mbed TLS ChangeLog (Sorted per branch, date)
= mbed TLS 2.16.x branch released xxxx-xx-xx
= mbed TLS "baremetal" branch
Bugfix
* Fix build failure with MBEDTLS_ZLIB_SUPPORT enabled. Reported by
Jack Lloyd in #2859. Fix submitted by jiblime in #2963.
Features
* Add new configuration option MBEDTLS_SSL_NO_SESSION_CACHE that enables
code size savings in configurations where cache-based session resumption is
not used.
* Add new configuration option MBEDTLS_SSL_NO_SESSION_RESUMPTION that
enables code size savings in configurations where no form of session
resumption is used.
* Add support for draft-05 of the Connection ID extension, as specified
in https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05.
The Connection ID extension allows to keep DTLS connections beyond the
lifetime of the underlying transport by adding a connection identifier
to the DTLS record header. This identifier can be used to associated an
incoming record with the correct connection data even after the peer has
changed its IP or port. The feature is enabled at compile-time by setting
MBEDTLS_SSL_DTLS_CONNECTION_ID (disabled by default), and at run-time
through the new APIs mbedtls_ssl_conf_cid() and mbedtls_ssl_set_cid().
* Add new API functions mbedtls_ssl_session_save() and
mbedtls_ssl_session_load() to allow serializing a session, for example to
store it in non-volatile storage, and later using it for TLS session
resumption.
* Add a new X.509 API call `mbedtls_x509_parse_der_nocopy()`
which allows copy-less parsing of DER encoded X.509 CRTs,
at the cost of additional lifetime constraints on the input
buffer, but at the benefit of reduced RAM consumption.
* Add new API function mbedtls_ssl_conf_extended_master_secret_enforce() to
allow enforcing the usage of ExtendedMasterSecret extension. If the
extension is used and this option is enabled, handshakes not leading to
the use of the extended master secret will be aborted. On the server,
fail the handshake if client doesn't advertise the ExtendedMasterSecret
extension. On the client, fail the handshake if the server doesn't
consent to the use of the ExtendedMasterSecret extension in its
ServerHello.
* Add new configuration option MBEDTLS_SSL_PROTO_NO_TLS that enables code
size savings in configurations where only DTLS is used.
API Changes
* Add a new X.509 API call `mbedtls_x509_parse_der_nocopy()`.
See the Features section for more information.
* Allow to opt in to the removal the API mbedtls_ssl_get_peer_cert()
for the benefit of saving RAM, by disabling the new compile-time
option MBEDTLS_SSL_KEEP_PEER_CERTIFICATE (enabled by default for
API stability). Disabling this option makes mbedtls_ssl_get_peer_cert()
always return NULL, and removes the peer_cert field from the
mbedtls_ssl_session structure which otherwise stores the peer's
certificate.
* Add a new compile-time option `MBEDTLS_X509_ON_DEMAND_PARSING`,
disabled by default, which allows to parse and cache X.509 CRTs
on demand only, at the benefit of lower RAM usage. Enabling
this option breaks the structure API of X.509 in that most
fields of `mbedtls_x509_crt` are removed, but it keeps the
X.509 function API. See the API changes section as well as
the documentation in `config.h` for more information.
Changes
* Reduce RAM consumption during session renegotiation by not storing
the peer CRT chain and session ticket twice.
= mbed TLS 2.16.6 branch released 2020-04-14
Security
* Fix side channel in ECC code that allowed an adversary with access to
precise enough timing and memory access information (typically an
untrusted operating system attacking a secure enclave) to fully recover
an ECDSA private key. Found and reported by Alejandro Cabrera Aldaya,
Billy Brumley and Cesar Pereida Garcia. CVE-2020-10932
* Fix a potentially remotely exploitable buffer overread in a
DTLS client when parsing the Hello Verify Request message.
Bugfix
* Fix compilation failure when both MBEDTLS_SSL_PROTO_DTLS and
MBEDTLS_SSL_HW_RECORD_ACCEL are enabled.
* Fix a function name in a debug message. Contributed by Ercan Ozturk in
#3013.
= mbed TLS 2.16.5 branch released 2020-02-20
Security
* Fix potential memory overread when performing an ECDSA signature
operation. The overread only happens with cryptographically low
probability (of the order of 2^-n where n is the bitsize of the curve)
unless the RNG is broken, and could result in information disclosure or
denial of service (application crash or extra resource consumption).
Found by Auke Zeilstra and Peter Schwabe, using static analysis.
* To avoid a side channel vulnerability when parsing an RSA private key,
read all the CRT parameters from the DER structure rather than
reconstructing them. Found by Alejandro Cabrera Aldaya and Billy Bob
Brumley. Reported and fix contributed by Jack Lloyd.
ARMmbed/mbed-crypto#352
Bugfix
* Fix an unchecked call to mbedtls_md() in the x509write module.
* Fix a bug in mbedtls_pk_parse_key() that would cause it to accept some
RSA keys that would later be rejected by functions expecting private
keys. Found by Catena cyber using oss-fuzz (issue 20467).
* Fix a bug in mbedtls_pk_parse_key() that would cause it to accept some
RSA keys with invalid values by silently fixing those values.
= mbed TLS 2.16.4 branch released 2020-01-15
Security
* Fix side channel vulnerability in ECDSA. Our bignum implementation is not
constant time/constant trace, so side channel attacks can retrieve the
blinded value, factor it (as it is smaller than RSA keys and not guaranteed
to have only large prime factors), and then, by brute force, recover the
key. Reported by Alejandro Cabrera Aldaya and Billy Brumley.
* Zeroize local variables in mbedtls_internal_aes_encrypt() and
mbedtls_internal_aes_decrypt() before exiting the function. The value of
these variables can be used to recover the last round key. To follow best
practice and to limit the impact of buffer overread vulnerabilities (like
Heartbleed) we need to zeroize them before exiting the function.
Issue reported by Tuba Yavuz, Farhaan Fowze, Ken (Yihang) Bai,
Grant Hernandez, and Kevin Butler (University of Florida) and
Dave Tian (Purdue University).
* Fix side channel vulnerability in ECDSA key generation. Obtaining precise
timings on the comparison in the key generation enabled the attacker to
learn leading bits of the ephemeral key used during ECDSA signatures and to
recover the private key. Reported by Jeremy Dubeuf.
* Catch failure of AES functions in mbedtls_ctr_drbg_random(). Uncaught
failures could happen with alternative implementations of AES. Bug
reported and fix proposed by Johan Uppman Bruce and Christoffer Lauri,
Sectra.
Bugfix
* Remove redundant line for getting the bitlen of a bignum, since the variable
holding the returned value is overwritten a line after.
Found by irwir in #2377.
* Support mbedtls_hmac_drbg_set_entropy_len() and
mbedtls_ctr_drbg_set_entropy_len() before the DRBG is seeded. Before,
the initial seeding always reset the entropy length to the compile-time
default.
Changes
* Add unit tests for AES-GCM when called through mbedtls_cipher_auth_xxx()
from the cipher abstraction layer. Fixes #2198.
* Clarify how the interface of the CTR_DRBG and HMAC modules relates to
NIST SP 800-90A. In particular CTR_DRBG requires an explicit nonce
to achieve a 256-bit strength if MBEDTLS_ENTROPY_FORCE_SHA256 is set.
= mbed TLS 2.16.3 branch released 2019-09-06
@ -44,6 +177,8 @@ Bugfix
* Enable Suite B with subset of ECP curves. Make sure the code compiles even
if some curves are not defined. Fixes #1591 reported by dbedev.
* Fix misuse of signed arithmetic in the HAVEGE module. #2598
* Fix incompatibility of HMAC DRBG with Mbed TLS' own entropy module that
lead to HMAC DRBG seeding failure in configurations disabling SHA-512.
* Update test certificates that were about to expire. Reported by
Bernhard M. Wiedemann in #2357.
* Fix the build on ARMv5TE in ARM mode to not use assembly instructions

67
ChangeLog.d/00README.md Normal file
View file

@ -0,0 +1,67 @@
# Pending changelog entry directory
This directory contains changelog entries that have not yet been merged
to the changelog file ([`../ChangeLog`](../ChangeLog)).
## Changelog entry file format
A changelog entry file must have the extension `*.txt` and must have the
following format:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Security
* Change description.
* Another change description.
Features
* Yet another change description. This is a long change description that
spans multiple lines.
* Yet again another change description.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The permitted changelog entry categories are as follows:
<!-- Keep this synchronized with STANDARD_CATEGORIES in assemble_changelog.py! -->
API changes
Default behavior changes
Requirement changes
New deprecations
Removals
Features
Security
Bugfix
Changes
Use “Changes” for anything that doesn't fit in the other categories, such as
performance, documentation and test improvements.
## How to write a changelog entry
Each entry starts with three spaces, an asterisk and a space. Continuation
lines start with 5 spaces. Lines wrap at 79 characters.
Write full English sentences with proper capitalization and punctuation. Use
the present tense. Use the imperative where applicable. For example: “Fix a
bug in mbedtls_xxx() ….”
Include GitHub issue numbers where relevant. Use the format “#1234” for an
Mbed TLS issue. Add other external references such as CVE numbers where
applicable.
Credit the author of the contribution if the contribution is not a member of
the Mbed TLS development team. Also credit bug reporters where applicable.
**Explain why, not how**. Remember that the audience is the users of the
library, not its developers. In particular, for a bug fix, explain the
consequences of the bug, not how the bug was fixed. For a new feature, explain
why one might be interested in the feature. For an API change or a deprecation,
explain how to update existing applications.
See [existing entries](../ChangeLog) for examples.
## How `ChangeLog` is updated
Run [`../scripts/assemble_changelog.py`](../scripts/assemble_changelog.py)
from a Git working copy
to move the entries from files in `ChangeLog.d` to the main `ChangeLog` file.

4
ChangeLog.d/bugfix.txt Normal file
View file

@ -0,0 +1,4 @@
Bugfix
* Fix the Visual Studio Release x64 build configuration for mbedtls itself.
Completes a previous fix in Mbed TLS 2.16 that only fixed the build for
the example programs. Reported in #1430 and fix contributed by irwir.

View file

@ -0,0 +1,5 @@
Bugfix
* Fix undefined behavior in X.509 certificate parsing if the
pathLenConstraint basic constraint value is equal to INT_MAX.
The actual effect with almost every compiler is the intended
behavior, so this is unlikely to be exploitable anywhere. #3197

View file

@ -0,0 +1,4 @@
Changes
* Unify the example programs termination to call mbedtls_exit() instead of
using a return command. This has been done to enable customization of the
behavior in bare metal environments.

View file

@ -2,6 +2,22 @@
DESTDIR=/usr/local
PREFIX=mbedtls_
PROGRAMS_DIR=./programs
TESTS_DIR=./tests
# Check test environment. If ../library is available then Mbed TLS is used.
# Otherwise Mbed OS environment is used.
DIR_FOR_MBED_TLS_ENV=./library
ifneq "$(wildcard $(DIR_FOR_MBED_TLS_ENV) )" ""
LIBRARY_DIR=./library
INCLUDE_DIR=./include
CONFIG_FILE=./include/mbedtls/config.h
else
LIBRARY_DIR=./src
INCLUDE_DIR=./inc
CONFIG_FILE=./inc/mbedtls/test_config.h
endif
.SILENT:
.PHONY: all no_test programs lib tests install uninstall clean test check covtest lcov apidoc apidoc_clean
@ -12,26 +28,26 @@ all: programs tests
no_test: programs
programs: lib
$(MAKE) -C programs
$(MAKE) -C $(PROGRAMS_DIR)
lib:
$(MAKE) -C library
$(MAKE) -C $(LIBRARY_DIR)
tests: lib
$(MAKE) -C tests
$(MAKE) -C $(TESTS_DIR)
ifndef WINDOWS
install: no_test
mkdir -p $(DESTDIR)/include/mbedtls
cp -rp include/mbedtls $(DESTDIR)/include
mkdir -p $(DESTDIR)/$(INCLUDE_DIR)/mbedtls
cp -rp $(INCLUDE_DIR)/mbedtls $(DESTDIR)/$(INCLUDE_DIR)
mkdir -p $(DESTDIR)/lib
cp -RP library/libmbedtls.* $(DESTDIR)/lib
cp -RP library/libmbedx509.* $(DESTDIR)/lib
cp -RP library/libmbedcrypto.* $(DESTDIR)/lib
cp -RP $(LIBRARY_DIR)/libmbedtls.* $(DESTDIR)/lib
cp -RP $(LIBRARY_DIR)/libmbedx509.* $(DESTDIR)/lib
cp -RP $(LIBRARY_DIR)/libmbedcrypto.* $(DESTDIR)/lib
mkdir -p $(DESTDIR)/bin
for p in programs/*/* ; do \
for p in $(PROGRAMS_DIR)/*/* ; do \
if [ -x $$p ] && [ ! -d $$p ] ; \
then \
f=$(PREFIX)`basename $$p` ; \
@ -40,12 +56,12 @@ install: no_test
done
uninstall:
rm -rf $(DESTDIR)/include/mbedtls
rm -rf $(DESTDIR)/$(INCLUDE_DIR)/mbedtls
rm -f $(DESTDIR)/lib/libmbedtls.*
rm -f $(DESTDIR)/lib/libmbedx509.*
rm -f $(DESTDIR)/lib/libmbedcrypto.*
for p in programs/*/* ; do \
for p in $(PROGRAMS_DIR)/*/* ; do \
if [ -x $$p ] && [ ! -d $$p ] ; \
then \
f=$(PREFIX)`basename $$p` ; \
@ -73,24 +89,24 @@ post_build:
ifndef WINDOWS
# If 128-bit keys are configured for CTR_DRBG, display an appropriate warning
-scripts/config.pl get MBEDTLS_CTR_DRBG_USE_128_BIT_KEY && ([ $$? -eq 0 ]) && \
-scripts/config.pl -f $(CONFIG_FILE) get MBEDTLS_CTR_DRBG_USE_128_BIT_KEY && ([ $$? -eq 0 ]) && \
echo '$(CTR_DRBG_128_BIT_KEY_WARNING)'
# If NULL Entropy is configured, display an appropriate warning
-scripts/config.pl get MBEDTLS_TEST_NULL_ENTROPY && ([ $$? -eq 0 ]) && \
-scripts/config.pl -f $(CONFIG_FILE) get MBEDTLS_TEST_NULL_ENTROPY && ([ $$? -eq 0 ]) && \
echo '$(NULL_ENTROPY_WARNING)'
endif
clean:
$(MAKE) -C library clean
$(MAKE) -C programs clean
$(MAKE) -C tests clean
$(MAKE) -C $(LIBRARY_DIR) clean
$(MAKE) -C $(PROGRAMS_DIR) clean
$(MAKE) -C $(TESTS_DIR) clean
ifndef WINDOWS
find . \( -name \*.gcno -o -name \*.gcda -o -name \*.info \) -exec rm {} +
endif
check: lib tests
$(MAKE) -C tests check
$(MAKE) -C $(TESTS_DIR) check
test: check
@ -99,14 +115,14 @@ ifndef WINDOWS
# make CFLAGS='--coverage -g3 -O0'
covtest:
$(MAKE) check
programs/test/selftest
tests/compat.sh
tests/ssl-opt.sh
$(PROGRAMS_DIR)/test/selftest
$(TESTS_DIR)/compat.sh
$(TESTS_DIR)/ssl-opt.sh
lcov:
rm -rf Coverage
lcov --capture --initial --directory library -o files.info
lcov --capture --directory library -o tests.info
lcov --capture --initial --directory $(LIBRARY_DIR) -o files.info
lcov --capture --directory $(LIBRARY_DIR) -o tests.info
lcov --add-tracefile files.info --add-tracefile tests.info -o all.info
lcov --remove all.info -o final.info '*.h'
gendesc tests/Descriptions.txt -o descriptions
@ -122,9 +138,11 @@ apidoc_clean:
endif
## Editor navigation files
C_SOURCE_FILES = $(wildcard include/*/*.h library/*.[hc] programs/*/*.[hc] tests/suites/*.function)
C_SOURCE_FILES = $(wildcard $(INCLUDE_DIR)/*/*.h $(LIBRARY_DIR)/*.[hc] $(PROGRAMS_DIR)/*/*.[hc] $(TESTS_DIR)/suites/*.function)
# Exuberant-ctags invocation. Other ctags implementations may require different options.
CTAGS = ctags --langmap=c:+.h.function -o
tags: $(C_SOURCE_FILES)
ctags -o $@ $(C_SOURCE_FILES)
$(CTAGS) $@ $(C_SOURCE_FILES)
TAGS: $(C_SOURCE_FILES)
etags -o $@ $(C_SOURCE_FILES)
GPATH GRTAGS GSYMS GTAGS: $(C_SOURCE_FILES)

View file

@ -1,6 +1,8 @@
README for Mbed TLS
===================
Mbed TLS is a C library that implements cryptographic primitives, X.509 certificate manipulation and the SSL/TLS and DTLS protocols. Its small code footprint makes it suitable for embedded systems.
Configuration
-------------
@ -167,21 +169,12 @@ Mbed TLS can be ported to many different architectures, OS's and platforms. Befo
- [What external dependencies does Mbed TLS rely on?](https://tls.mbed.org/kb/development/what-external-dependencies-does-mbedtls-rely-on)
- [How do I configure Mbed TLS](https://tls.mbed.org/kb/compiling-and-building/how-do-i-configure-mbedtls)
License
-------
Unless specifically indicated otherwise in a file, Mbed TLS files are provided under the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license. See [here](./apache-2.0.txt) for the full text of this license. Contributors must accept that their contributions are made under both the Apache-2.0 AND [GPL-2.0-or-later](https://spdx.org/licenses/GPL-2.0-or-later.html) licenses. This enables LTS (Long Term Support) branches of the software to be provided under either the Apache-2.0 OR GPL-2.0-or-later licenses.
Contributing
------------
We gratefully accept bug reports and contributions from the community. There are some requirements we need to fulfill in order to be able to integrate contributions:
- All contributions, whether large or small require a Contributor's License Agreement (CLA) to be accepted. This is because source code can possibly fall under copyright law and we need your consent to share in the ownership of the copyright.
- We would ask that contributions conform to [our coding standards](https://tls.mbed.org/kb/development/mbedtls-coding-standards), and that contributions should be fully tested before submission.
- As with any open source project, contributions will be reviewed by the project team and community and may need some modifications to be accepted.
To accept the Contributors Licence Agreement (CLA), individual contributors can do this by creating an Mbed account and [accepting the online agreement here with a click through](https://os.mbed.com/contributor_agreement/). Alternatively, for contributions from corporations, or those that do not wish to create an Mbed account, a slightly different agreement can be found [here](https://www.mbed.com/en/about-mbed/contributor-license-agreements/). This agreement should be signed and returned to Arm as described in the instructions given.
### Making a Contribution
1. [Check for open issues](https://github.com/ARMmbed/mbedtls/issues) or [start a discussion](https://forums.mbed.com/c/mbed-tls) around a feature idea or a bug.
2. Fork the [Mbed TLS repository on GitHub](https://github.com/ARMmbed/mbedtls) to start making your changes. As a general rule, you should use the "development" branch as a basis.
3. Write a test which shows that the bug was fixed or that the feature works as expected.
4. Send a pull request and bug us until it gets merged and published. Contributions may need some modifications, so work with us to get your change accepted. We will include your name in the ChangeLog :)
We gratefully accept bug reports and contributions from the community. Please see the [contributing guidelines](CONTRIBUTING.md) for details on how to do this.

158
configs/baremetal.h Normal file
View file

@ -0,0 +1,158 @@
/**
* \file baremetal.h
*
* \brief Test configuration for minimal baremetal Mbed TLS builds
* based on the following primitives:
* - ECDHE-ECDSA only
* - Elliptic curve SECP256R1 only
* - SHA-256 only
* - AES-CCM-8 only
*
* The library compiles in this configuration, but the example
* programs `ssl_client2` and `ssl_server2` require the
* modifications from `baremetal_test.h`.
*/
/*
* Copyright (C) 2006-2018, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_BAREMETAL_CONFIG_H
#define MBEDTLS_BAREMETAL_CONFIG_H
/* Symmetric crypto: AES-CCM only */
#define MBEDTLS_CIPHER_C
#define MBEDTLS_AES_C
#define MBEDTLS_AES_ROM_TABLES
#define MBEDTLS_AES_FEWER_TABLES
#define MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH
#define MBEDTLS_AES_ONLY_ENCRYPT
#define MBEDTLS_AES_SCA_COUNTERMEASURES
#define MBEDTLS_CCM_C
/* Asymmetric crypto: Single-curve ECC only. */
#define MBEDTLS_PK_C
#define MBEDTLS_PK_PARSE_C
#define MBEDTLS_ENTROPY_MAX_SOURCES 1
#define MBEDTLS_SSL_CONF_SINGLE_EC
#define MBEDTLS_SSL_CONF_SINGLE_UECC_GRP_ID MBEDTLS_UECC_DP_SECP256R1
#define MBEDTLS_SSL_CONF_SINGLE_EC_TLS_ID 23
#define MBEDTLS_SSL_CONF_SINGLE_SIG_HASH
#define MBEDTLS_SSL_CONF_SINGLE_SIG_HASH_MD_ID MBEDTLS_MD_SHA256
#define MBEDTLS_SSL_CONF_SINGLE_SIG_HASH_TLS_ID MBEDTLS_SSL_HASH_SHA256
/* Harcoded options in abstraction layers */
#define MBEDTLS_MD_SINGLE_HASH MBEDTLS_MD_INFO_SHA256
#define MBEDTLS_PK_SINGLE_TYPE MBEDTLS_PK_INFO_ECKEY
/* Key exchanges */
#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
#define MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE MBEDTLS_SUITE_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
/* Digests - just SHA-256 */
#define MBEDTLS_MD_C
#define MBEDTLS_SHA256_C
#define MBEDTLS_SHA256_SMALLER
#define MBEDTLS_SHA256_NO_SHA224
/* TLS options */
#define MBEDTLS_SSL_CLI_C
#define MBEDTLS_SSL_TLS_C
#define MBEDTLS_SSL_PROTO_TLS1_2
#define MBEDTLS_SSL_EXTENDED_MASTER_SECRET
#define MBEDTLS_SSL_NO_SESSION_CACHE
#define MBEDTLS_SSL_NO_SESSION_RESUMPTION
#define MBEDTLS_SSL_COOKIE_C
#define MBEDTLS_SSL_PROTO_DTLS
#define MBEDTLS_SSL_PROTO_NO_TLS
#define MBEDTLS_SSL_DTLS_ANTI_REPLAY
#define MBEDTLS_SSL_DTLS_HELLO_VERIFY
#define MBEDTLS_SSL_DTLS_BADMAC_LIMIT
#define MBEDTLS_SSL_DTLS_CONNECTION_ID
/* Compile-time fixed parts of the SSL configuration */
#define MBEDTLS_SSL_CONF_CERT_REQ_CA_LIST MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED
#define MBEDTLS_SSL_CONF_READ_TIMEOUT 0
#define MBEDTLS_SSL_CONF_HS_TIMEOUT_MIN 1000
#define MBEDTLS_SSL_CONF_HS_TIMEOUT_MAX 16000
#define MBEDTLS_SSL_CONF_CID_LEN 2
#define MBEDTLS_SSL_CONF_IGNORE_UNEXPECTED_CID MBEDTLS_SSL_UNEXPECTED_CID_IGNORE
#define MBEDTLS_SSL_CONF_ALLOW_LEGACY_RENEGOTIATION \
MBEDTLS_SSL_SECURE_RENEGOTIATION
#define MBEDTLS_SSL_CONF_AUTHMODE MBEDTLS_SSL_VERIFY_REQUIRED
#define MBEDTLS_SSL_CONF_BADMAC_LIMIT 0
#define MBEDTLS_SSL_CONF_ANTI_REPLAY MBEDTLS_SSL_ANTI_REPLAY_ENABLED
#define MBEDTLS_SSL_CONF_GET_TIMER mbedtls_timing_get_delay
#define MBEDTLS_SSL_CONF_SET_TIMER mbedtls_timing_set_delay
#define MBEDTLS_SSL_CONF_RECV mbedtls_net_recv
#define MBEDTLS_SSL_CONF_SEND mbedtls_net_send
#define MBEDTLS_SSL_CONF_RECV_TIMEOUT mbedtls_net_recv_timeout
#define MBEDTLS_SSL_CONF_RNG rng_wrap
#define MBEDTLS_SSL_CONF_MIN_MINOR_VER MBEDTLS_SSL_MINOR_VERSION_3
#define MBEDTLS_SSL_CONF_MAX_MINOR_VER MBEDTLS_SSL_MINOR_VERSION_3
#define MBEDTLS_SSL_CONF_MIN_MAJOR_VER MBEDTLS_SSL_MAJOR_VERSION_3
#define MBEDTLS_SSL_CONF_MAX_MAJOR_VER MBEDTLS_SSL_MAJOR_VERSION_3
#define MBEDTLS_SSL_CONF_EXTENDED_MASTER_SECRET \
MBEDTLS_SSL_EXTENDED_MS_ENABLED
#define MBEDTLS_SSL_CONF_ENFORCE_EXTENDED_MASTER_SECRET \
MBEDTLS_SSL_EXTENDED_MS_ENFORCE_ENABLED
#define MBEDTLS_USE_TINYCRYPT
/* X.509 CRT parsing */
#define MBEDTLS_X509_USE_C
#define MBEDTLS_X509_CRT_PARSE_C
#define MBEDTLS_X509_CHECK_KEY_USAGE
#define MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE
#define MBEDTLS_X509_REMOVE_INFO
#define MBEDTLS_X509_CRT_REMOVE_TIME
#define MBEDTLS_X509_CRT_REMOVE_SUBJECT_ISSUER_ID
#define MBEDTLS_X509_ON_DEMAND_PARSING
#define MBEDTLS_X509_ALWAYS_FLUSH
#define MBEDTLS_X509_REMOVE_VERIFY_CALLBACK
#define MBEDTLS_ASN1_PARSE_C
#define MBEDTLS_X509_REMOVE_HOSTNAME_VERIFICATION
/* RNG and PRNG */
#define MBEDTLS_NO_PLATFORM_ENTROPY
#define MBEDTLS_ENTROPY_C
#define MBEDTLS_HMAC_DRBG_C
#define MBEDTLS_OID_C
#define MBEDTLS_PLATFORM_C
/* I/O buffer configuration */
#define MBEDTLS_SSL_MAX_CONTENT_LEN 2048
/* Server-side only */
#define MBEDTLS_SSL_SRV_C
#define MBEDTLS_DEPRECATED_REMOVED
/* Fault Injection Countermeasures */
#define MBEDTLS_FI_COUNTERMEASURES
#if defined(MBEDTLS_USER_CONFIG_FILE)
#include MBEDTLS_USER_CONFIG_FILE
#endif
#include <mbedtls/check_config.h>
#endif /* MBEDTLS_BAREMETAL_CONFIG_H */

51
configs/baremetal_test.h Normal file
View file

@ -0,0 +1,51 @@
/**
* \file baremetal_test.h
*
* \brief This file contains minimal modifications to the
* baremetal configuration `baremetal.h` which allows
* example programs to compile and run.
*
* It should be used as the `MBEDTLS_USER_CONFIG_FILE`
* in builds using `baremetal.h`.
*/
/*
* Copyright (C) 2006-2018, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_BAREMETAL_USER_CONFIG_H
#define MBEDTLS_BAREMETAL_USER_CONFIG_H
/* We need test CRTs to be able to run ssl_client2 and ssl_server2. */
#define MBEDTLS_CERTS_C
/* For the network context used by ssl_client2 and ssl_server2. */
#define MBEDTLS_NET_C
/* Debug output */
#define MBEDTLS_DEBUG_C
/* The ticket implementation hardcodes AES-GCM */
#define MBEDTLS_GCM_C
/* Use Mbed TLS' timer implementation for Linux. */
#define MBEDTLS_TIMING_C
/* Needed for certificates in ssl_opt.sh */
#define MBEDTLS_FS_IO
#undef MBEDTLS_NO_PLATFORM_ENTROPY
#endif /* MBEDTLS_BAREMETAL_USER_CONFIG_H */

View file

@ -55,6 +55,9 @@
#define MBEDTLS_SSL_SRV_C
#define MBEDTLS_SSL_TLS_C
/* Save ROM by excluded SHA-2 variant that we don't need */
#define MBEDTLS_SHA256_NO_SHA224
/* Save RAM at the expense of ROM */
#define MBEDTLS_AES_ROM_TABLES

View file

@ -78,6 +78,9 @@
#define MBEDTLS_CERTS_C
#define MBEDTLS_PEM_PARSE_C
/* Save ROM by excluded SHA-2 variant that we don't need */
#define MBEDTLS_SHA256_NO_SHA224
/* Save RAM at the expense of ROM */
#define MBEDTLS_AES_ROM_TABLES

View file

@ -29,6 +29,7 @@
* Distinguishing features:
* - no RSA or classic DH, fully based on ECC
* - no X.509
* - no TLS, only DTLS
* - support for experimental EC J-PAKE key exchange
*
* See README.txt for usage instructions.
@ -48,6 +49,7 @@
#define MBEDTLS_SSL_MAX_FRAGMENT_LENGTH
#define MBEDTLS_SSL_PROTO_TLS1_2
#define MBEDTLS_SSL_PROTO_DTLS
#define MBEDTLS_SSL_PROTO_NO_TLS
#define MBEDTLS_SSL_DTLS_ANTI_REPLAY
#define MBEDTLS_SSL_DTLS_HELLO_VERIFY
#define MBEDTLS_SSL_EXPORT_KEYS
@ -86,6 +88,9 @@
#define MBEDTLS_ECP_MAX_BITS 256
#define MBEDTLS_MPI_MAX_SIZE 32 // 256 bits is 32 bytes
/* Save ROM by excluded SHA-2 variant that we don't need */
#define MBEDTLS_SHA256_NO_SHA224
/* Save ROM and a few bytes of RAM by specifying our own ciphersuite list */
#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8

37
dco.txt Normal file
View file

@ -0,0 +1,37 @@
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
1 Letterman Drive
Suite D4700
San Francisco, CA, 94129
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.

View file

@ -24,7 +24,7 @@
*/
/**
* @mainpage mbed TLS v2.16.3 source code documentation
* @mainpage mbed TLS v2.16.6 source code documentation
*
* This documentation describes the internal structure of mbed TLS. It was
* automatically generated from specially formatted comment blocks in

View file

@ -28,7 +28,7 @@ DOXYFILE_ENCODING = UTF-8
# identify the project. Note that if you do not use Doxywizard you need
# to put quotes around the project name if it contains spaces.
PROJECT_NAME = "mbed TLS v2.16.3"
PROJECT_NAME = "mbed TLS v2.16.6"
# The PROJECT_NUMBER tag can be used to enter a project or revision number.
# This could be handy for archiving the generated documentation or
@ -696,7 +696,9 @@ RECURSIVE = YES
# Note that relative paths are relative to the directory from which doxygen is
# run.
EXCLUDE =
EXCLUDE = ./../include/tinycrypt/ecc.h \
./../include/tinycrypt/ecc_dh.h \
./../include/tinycrypt/ecc_dsa.h
# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
# directories that are symbolic links (a Unix file system feature) are excluded
@ -1622,7 +1624,8 @@ PREDEFINED = WIN32 \
ENABLE_PLUGIN \
ENABLE_MANAGEMENT \
ENABLE_OCC \
HAVE_GETTIMEOFDAY
HAVE_GETTIMEOFDAY \
DOXYGEN_ONLY
# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
# this tag can be used to specify a list of macro names that should be expanded.

View file

@ -3,6 +3,7 @@ option(INSTALL_MBEDTLS_HEADERS "Install mbed TLS headers." ON)
if(INSTALL_MBEDTLS_HEADERS)
file(GLOB headers "mbedtls/*.h")
file(GLOB headers "tinycrypt/*.h")
install(FILES ${headers}
DESTINATION include/mbedtls

View file

@ -87,6 +87,9 @@ typedef struct mbedtls_aes_context
{
int nr; /*!< The number of rounds. */
uint32_t *rk; /*!< AES round keys. */
#if defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) && !defined(MBEDTLS_PADLOCK_C)
uint32_t buf[44]; /*!< Unaligned data buffer */
#else /* MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
uint32_t buf[68]; /*!< Unaligned data buffer. This buffer can
hold 32 extra Bytes, which can be used for
one of the following purposes:
@ -95,6 +98,7 @@ typedef struct mbedtls_aes_context
<li>Simplifying key expansion in the 256-bit
case by generating an extra round key.
</li></ul> */
#endif /* MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
}
mbedtls_aes_context;
@ -168,7 +172,8 @@ void mbedtls_aes_xts_free( mbedtls_aes_xts_context *ctx );
* <li>256 bits</li></ul>
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.
* \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH or
* #MBEDTLS_ERR_PLATFORM_FAULT_DETECTED on failure.
*/
int mbedtls_aes_setkey_enc( mbedtls_aes_context *ctx, const unsigned char *key,
unsigned int keybits );
@ -186,7 +191,8 @@ int mbedtls_aes_setkey_enc( mbedtls_aes_context *ctx, const unsigned char *key,
* <li>256 bits</li></ul>
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.
* \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH or
* #MBEDTLS_ERR_PLATFORM_FAULT_DETECTED on failure.
*/
int mbedtls_aes_setkey_dec( mbedtls_aes_context *ctx, const unsigned char *key,
unsigned int keybits );
@ -598,6 +604,7 @@ int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx,
* \param output The output (ciphertext) block.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_PLATFORM_FAULT_DETECTED in case of error.
*/
int mbedtls_internal_aes_encrypt( mbedtls_aes_context *ctx,
const unsigned char input[16],
@ -613,6 +620,7 @@ int mbedtls_internal_aes_encrypt( mbedtls_aes_context *ctx,
* \param output The output (plaintext) block.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_PLATFORM_FAULT_DETECTED in case of error.
*/
int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx,
const unsigned char input[16],

View file

@ -31,6 +31,7 @@
#endif
#include <stddef.h>
#include <stdint.h>
#if defined(MBEDTLS_BIGNUM_C)
#include "bignum.h"
@ -89,6 +90,18 @@
#define MBEDTLS_ASN1_CONSTRUCTED 0x20
#define MBEDTLS_ASN1_CONTEXT_SPECIFIC 0x80
/* Slightly smaller way to check if tag is a string tag
* compared to canonical implementation. */
#define MBEDTLS_ASN1_IS_STRING_TAG( tag ) \
( ( tag ) < 32u && ( \
( ( 1u << ( tag ) ) & ( ( 1u << MBEDTLS_ASN1_BMP_STRING ) | \
( 1u << MBEDTLS_ASN1_UTF8_STRING ) | \
( 1u << MBEDTLS_ASN1_T61_STRING ) | \
( 1u << MBEDTLS_ASN1_IA5_STRING ) | \
( 1u << MBEDTLS_ASN1_UNIVERSAL_STRING ) | \
( 1u << MBEDTLS_ASN1_PRINTABLE_STRING ) | \
( 1u << MBEDTLS_ASN1_BIT_STRING ) ) ) != 0 ) )
/*
* Bit masks for each of the components of an ASN.1 tag as specified in
* ITU X.690 (08/2015), section 8.1 "General rules for encoding",
@ -117,7 +130,11 @@
*/
#define MBEDTLS_OID_CMP(oid_str, oid_buf) \
( ( MBEDTLS_OID_SIZE(oid_str) != (oid_buf)->len ) || \
memcmp( (oid_str), (oid_buf)->p, (oid_buf)->len) != 0 )
mbedtls_platform_memcmp( (oid_str), (oid_buf)->p, (oid_buf)->len) != 0 )
#define MBEDTLS_OID_CMP_RAW(oid_str, oid_buf, oid_buf_len) \
( ( MBEDTLS_OID_SIZE(oid_str) != (oid_buf_len) ) || \
mbedtls_platform_memcmp( (oid_str), (oid_buf), (oid_buf_len) ) != 0 )
#ifdef __cplusplus
extern "C" {
@ -260,20 +277,97 @@ int mbedtls_asn1_get_bitstring_null( unsigned char **p, const unsigned char *end
size_t *len );
/**
* \brief Parses and splits an ASN.1 "SEQUENCE OF <tag>"
* Updated the pointer to immediately behind the full sequence tag.
* \brief Free a heap-allocated linked list presentation of
* an ASN.1 sequence, including the first element.
*
* \param p The position in the ASN.1 data
* \param end End of data
* \param cur First variable in the chain to fill
* \param tag Type of sequence
* \param seq The address of the first sequence component. This may
* be \c NULL, in which case this functions returns
* immediately.
*/
void mbedtls_asn1_sequence_free( mbedtls_asn1_sequence *seq );
/**
* \brief This function parses and splits an ASN.1 "SEQUENCE OF <tag>"
* and updates the source buffer pointer to immediately behind
* the full sequence.
*
* \param p The address of the pointer to the beginning of the
* ASN.1 SEQUENCE OF structure, including ASN.1 tag+length header.
* On success, `*p` is advanced to point to the first byte
* following the parsed ASN.1 sequence.
* \param end The end of the ASN.1 input buffer starting at \p p. This is
* used for bounds checking.
* \param cur The address at which to store the first entry in the parsed
* sequence. Further entries are heap-allocated and referenced
* from \p cur.
* \param tag The common tag of the entries in the ASN.1 sequence.
*
* \note Ownership for the heap-allocated elements \c cur->next,
* \c cur->next->next, ..., is passed to the caller. It
* is hence the caller's responsibility to free them when
* no longer needed, and mbedtls_asn1_sequence_free() can
* be used for that, passing \c cur->next as the \c seq
* argument (or \p cur if \p cur itself was heap-allocated
* by the caller).
*
* \return 0 if successful or a specific ASN.1 error code.
*/
int mbedtls_asn1_get_sequence_of( unsigned char **p,
const unsigned char *end,
mbedtls_asn1_sequence *cur,
int tag);
int tag );
/**
* \brief Traverse an ASN.1 SEQUENCE container and
* call a callback for each entry.
*
* \warning This function is still experimental and may change
* at any time.
*
* \param p The address of the pointer to the beginning of
* the ASN.1 SEQUENCE header. This is updated to
* point to the end of the ASN.1 SEQUENCE container
* on a successful invocation.
* \param end The end of the ASN.1 SEQUENCE container.
* \param tag_must_mask A mask to be applied to the ASN.1 tags found within
* the SEQUENCE before comparing to \p tag_must_value.
* \param tag_must_val The required value of each ASN.1 tag found in the
* SEQUENCE, after masking with \p tag_must_mask.
* Mismatching tags lead to an error.
* For example, a value of \c 0 for both \p tag_must_mask
* and \p tag_must_val means that every tag is allowed,
* while a value of \c 0xFF for \p tag_must_mask means
* that \p tag_must_val is the only allowed tag.
* \param tag_may_mask A mask to be applied to the ASN.1 tags found within
* the SEQUENCE before comparing to \p tag_may_value.
* \param tag_may_val The desired value of each ASN.1 tag found in the
* SEQUENCE, after masking with \p tag_may_mask.
* Mismatching tags will be silently ignored.
* For example, a value of \c 0 for \p tag_may_mask and
* \p tag_may_val means that any tag will be considered,
* while a value of \c 0xFF for \p tag_may_mask means
* that all tags with value different from \p tag_may_val
* will be ignored.
* \param cb The callback to trigger for each component
* in the ASN.1 SEQUENCE. If the callback returns
* a non-zero value, the function stops immediately,
* forwarding the callback's return value.
* \param ctx The context to be passed to the callback \p cb.
*
* \return \c 0 if successful the entire ASN.1 SEQUENCE
* was traversed without parsing or callback errors.
* \return A negative ASN.1 error code on a parsing failure.
* \return A non-zero error code forwarded from the callback
* \p cb in case the latter returns a non-zero value.
*/
int mbedtls_asn1_traverse_sequence_of(
unsigned char **p,
const unsigned char *end,
uint8_t tag_must_mask, uint8_t tag_must_val,
uint8_t tag_may_mask, uint8_t tag_may_val,
int (*cb)( void *ctx, int tag,
unsigned char* start, size_t len ),
void *ctx );
#if defined(MBEDTLS_BIGNUM_C)
/**

View file

@ -184,7 +184,7 @@ extern "C" {
*/
typedef struct mbedtls_mpi
{
int s; /*!< integer sign */
int s; /*!< Sign: -1 if the mpi is negative, 1 otherwise */
size_t n; /*!< total # of limbs */
mbedtls_mpi_uint *p; /*!< pointer to limbs */
}
@ -559,6 +559,24 @@ int mbedtls_mpi_cmp_abs( const mbedtls_mpi *X, const mbedtls_mpi *Y );
*/
int mbedtls_mpi_cmp_mpi( const mbedtls_mpi *X, const mbedtls_mpi *Y );
/**
* \brief Check if an MPI is less than the other in constant time.
*
* \param X The left-hand MPI. This must point to an initialized MPI
* with the same allocated length as Y.
* \param Y The right-hand MPI. This must point to an initialized MPI
* with the same allocated length as X.
* \param ret The result of the comparison:
* \c 1 if \p X is less than \p Y.
* \c 0 if \p X is greater than or equal to \p Y.
*
* \return 0 on success.
* \return MBEDTLS_ERR_MPI_BAD_INPUT_DATA if the allocated length of
* the two input MPIs is not the same.
*/
int mbedtls_mpi_lt_mpi_ct( const mbedtls_mpi *X, const mbedtls_mpi *Y,
unsigned *ret );
/**
* \brief Compare an MPI with an integer.
*

View file

@ -74,6 +74,10 @@
#error "MBEDTLS_CTR_DRBG_C defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_CTR_DRBG_C) && defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) && !defined(MBEDTLS_CTR_DRBG_USE_128_BIT_KEY)
#error "MBEDTLS_CTR_DRBG_C and MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH defined, but MBEDTLS_CTR_DRBG_USE_128_BIT_KEY is not defined"
#endif
#if defined(MBEDTLS_DHM_C) && !defined(MBEDTLS_BIGNUM_C)
#error "MBEDTLS_DHM_C defined, but not all prerequisites"
#endif
@ -87,6 +91,45 @@
#error "MBEDTLS_CMAC_C defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_SSL_CONF_SINGLE_EC) && \
( !defined(MBEDTLS_SSL_CONF_SINGLE_EC_TLS_ID) || \
( defined(MBEDTLS_USE_TINYCRYPT) && \
!defined(MBEDTLS_SSL_CONF_SINGLE_UECC_GRP_ID) ) || \
( defined(MBEDTLS_ECP_C) && \
!defined(MBEDTLS_SSL_CONF_SINGLE_EC_GRP_ID) ) )
#error "MBEDTLS_SSL_CONF_SINGLE_EC defined, but not all prerequesites"
#endif
#if defined(MBEDTLS_SSL_CONF_SINGLE_SIG_HASH) && \
( !defined(MBEDTLS_SSL_CONF_SINGLE_SIG_HASH_MD_ID) || \
!defined(MBEDTLS_SSL_CONF_SINGLE_SIG_HASH_TLS_ID) )
#error "MBEDTLS_SSL_CONF_SINGLE_SIG_HASH defined, but not all prerequesites"
#endif
#if defined(MBEDTLS_USE_TINYCRYPT) && defined(MBEDTLS_NO_64BIT_MULTIPLICATION)
#error "MBEDTLS_USE_TINYCRYPT defined, but it cannot be defined with MBEDTLS_NO_64BIT_MULTIPLICATION"
#endif
#if defined(MBEDTLS_USE_TINYCRYPT) && !defined(MBEDTLS_SHA256_C)
#error "MBEDTLS_USE_TINYCRYPT defined, but not MBEDTLS_SHA256_C"
#endif
#if defined(MBEDTLS_USE_TINYCRYPT) && \
!( defined(MBEDTLS_SSL_CONF_SINGLE_EC) && \
MBEDTLS_SSL_CONF_SINGLE_EC_TLS_ID == 23 && \
MBEDTLS_SSL_CONF_SINGLE_UECC_GRP_ID == MBEDTLS_UECC_DP_SECP256R1 )
#error "MBEDTLS_USE_TINYCRYPT requires the use of MBEDTLS_SSL_CONF_SINGLE_UECC_GRP_ID to hardcode the choice of Secp256r1"
#endif
#if defined(MBEDTLS_USE_TINYCRYPT) && defined(MBEDTLS_ECP_C)
#error "MBEDTLS_USE_TINYCRYPT and MBEDTLS_ECP_C cannot be used simultaneously"
#endif
#if defined(MBEDTLS_USE_TINYCRYPT) && \
!defined(MBEDTLS_SSL_CONF_RNG)
#error "MBEDTLS_USE_TINYCRYPT defined, but not all prerequesites"
#endif
#if defined(MBEDTLS_NIST_KW_C) && \
( !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CIPHER_C) )
#error "MBEDTLS_NIST_KW_C defined, but not all prerequisites"
@ -140,6 +183,21 @@
#error "MBEDTLS_ECP_C defined, but not all prerequisites"
#endif
#if ( defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) || \
defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) || \
defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || \
defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) || \
defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) || \
defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) || \
defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) || \
defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) || \
defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) || \
defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) || \
defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) ) && \
!defined(MBEDTLS_ECP_C)
#error "At least one ECP curve enabled, but not all prerequesites"
#endif
#if defined(MBEDTLS_PK_PARSE_C) && !defined(MBEDTLS_ASN1_PARSE_C)
#error "MBEDTLS_PK_PARSE_C defined, but not all prerequesites"
#endif
@ -222,12 +280,14 @@
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) && \
( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) )
( !( defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_USE_TINYCRYPT) ) || \
!defined(MBEDTLS_X509_CRT_PARSE_C) )
#error "MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) && \
( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) )
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) && \
( !( defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_USE_TINYCRYPT) ) || \
!defined(MBEDTLS_X509_CRT_PARSE_C) )
#error "MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED defined, but not all prerequisites"
#endif
@ -236,7 +296,7 @@
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) && \
!defined(MBEDTLS_ECDH_C)
!(defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_USE_TINYCRYPT) )
#error "MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED defined, but not all prerequisites"
#endif
@ -246,14 +306,17 @@
#error "MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_RSA_C) || \
!defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_PKCS1_V15) )
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
( !( defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_USE_TINYCRYPT) ) || \
!defined(MBEDTLS_RSA_C) || \
!defined(MBEDTLS_X509_CRT_PARSE_C) || \
!defined(MBEDTLS_PKCS1_V15) )
#error "MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) && \
( !defined(MBEDTLS_ECDH_C) || !defined(MBEDTLS_ECDSA_C) || \
( !( defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_USE_TINYCRYPT) ) || \
!( defined(MBEDTLS_ECDSA_C) || defined(MBEDTLS_USE_TINYCRYPT) ) || \
!defined(MBEDTLS_X509_CRT_PARSE_C) )
#error "MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED defined, but not all prerequisites"
#endif
@ -276,6 +339,14 @@
#error "MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) && \
!defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) && \
( !defined(MBEDTLS_SHA256_C) && \
!defined(MBEDTLS_SHA512_C) && \
!defined(MBEDTLS_SHA1_C) )
#error "MBEDTLS_SSL_KEEP_PEER_CERTIFICATE defined, but not all prerequesites"
#endif
#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) && \
( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_PLATFORM_MEMORY) )
#error "MBEDTLS_MEMORY_BUFFER_ALLOC_C defined, but not all prerequisites"
@ -301,8 +372,10 @@
#error "MBEDTLS_PEM_WRITE_C defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_PK_C) && \
( !defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_ECP_C) )
#if defined(MBEDTLS_PK_C) && \
( !defined(MBEDTLS_RSA_C) && \
!defined(MBEDTLS_ECP_C) && \
!defined(MBEDTLS_USE_TINYCRYPT) )
#error "MBEDTLS_PK_C defined, but not all prerequisites"
#endif
@ -546,6 +619,23 @@
#error "MBEDTLS_SSL_PROTO_TLS1_2 defined, but not all prerequisites"
#endif
#if (defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)) && \
!(defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) )
#error "One or more versions of the TLS protocol are enabled " \
"but no key exchange methods defined with MBEDTLS_KEY_EXCHANGE_xxxx"
#endif
#if defined(MBEDTLS_SSL_PROTO_DTLS) && \
!defined(MBEDTLS_SSL_PROTO_TLS1_1) && \
!defined(MBEDTLS_SSL_PROTO_TLS1_2)
@ -568,7 +658,18 @@
#if defined(MBEDTLS_SSL_TLS_C) && (!defined(MBEDTLS_SSL_PROTO_SSL3) && \
!defined(MBEDTLS_SSL_PROTO_TLS1) && !defined(MBEDTLS_SSL_PROTO_TLS1_1) && \
!defined(MBEDTLS_SSL_PROTO_TLS1_2))
#error "MBEDTLS_SSL_TLS_C defined, but no protocols are active"
#error "MBEDTLS_SSL_TLS_C defined, but no protocol version is active"
#endif
/* PROTO_TLS is not a documented option so far, but still check for conflicts
* involving it, in preparation for making it the documented option later */
#if defined(MBEDTLS_SSL_PROTO_TLS) && defined(MBEDTLS_SSL_PROTO_NO_TLS)
#error "MBEDTLS_SSL_PROTO_TLS and MBEDTLS_SSL_PROTO_NO_TLS both defined"
#endif
#if defined(MBEDTLS_SSL_TLS_C) && \
( defined(MBEDTLS_SSL_PROTO_NO_TLS) && !defined(MBEDTLS_SSL_PROTO_DTLS) )
#error "MBEDTLS_SSL_TLS_C defined, but neither TLS or DTLS is active"
#endif
#if defined(MBEDTLS_SSL_TLS_C) && (defined(MBEDTLS_SSL_PROTO_SSL3) && \
@ -601,6 +702,49 @@
#error "MBEDTLS_SSL_DTLS_ANTI_REPLAY defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_SSL_CONF_MIN_MINOR_VER) || \
defined(MBEDTLS_SSL_CONF_MAX_MINOR_VER) || \
defined(MBEDTLS_SSL_CONF_MIN_MAJOR_VER) || \
defined(MBEDTLS_SSL_CONF_MAX_MAJOR_VER)
#if !( defined(MBEDTLS_SSL_CONF_MIN_MINOR_VER) && \
defined(MBEDTLS_SSL_CONF_MAX_MINOR_VER) && \
defined(MBEDTLS_SSL_CONF_MIN_MAJOR_VER) && \
defined(MBEDTLS_SSL_CONF_MAX_MAJOR_VER) )
#error "MBEDTLS_SSL_CONF_MIN_MINOR_VER, MBEDTLS_SSL_CONF_MAX_MINOR_VER, MBEDTLS_SSL_CONF_MIN_MAJOR_VER, MBEDTLS_SSL_CONF_MAX_MAJOR_VER must be defined simultaneously"
#endif
#endif
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
( !defined(MBEDTLS_SSL_TLS_C) || !defined(MBEDTLS_SSL_PROTO_DTLS) )
#error "MBEDTLS_SSL_DTLS_CONNECTION_ID defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
defined(MBEDTLS_SSL_CID_IN_LEN_MAX) && \
MBEDTLS_SSL_CID_IN_LEN_MAX > 255
#error "MBEDTLS_SSL_CID_IN_LEN_MAX too large (max 255)"
#endif
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
defined(MBEDTLS_SSL_CID_OUT_LEN_MAX) && \
MBEDTLS_SSL_CID_OUT_LEN_MAX > 255
#error "MBEDTLS_SSL_CID_OUT_LEN_MAX too large (max 255)"
#endif
#if ( defined(MBEDTLS_SSL_CONF_CID_LEN) && \
!defined(MBEDTLS_SSL_CONF_IGNORE_UNEXPECTED_CID) ) || \
( !defined(MBEDTLS_SSL_CONF_CID_LEN) && \
defined(MBEDTLS_SSL_CONF_IGNORE_UNEXPECTED_CID) )
#error "MBEDTLS_SSL_CONF_CID_LEN and MBEDTLS_SSL_CONF_IGNORE_UNEXPECTED_CID must be defined simultaneously"
#endif
#if ( defined(MBEDTLS_SSL_CONF_HS_TIMEOUT_MIN) && \
!defined(MBEDTLS_SSL_CONF_HS_TIMEOUT_MAX) ) || \
( !defined(MBEDTLS_SSL_CONF_HS_TIMEOUT_MIN) && \
defined(MBEDTLS_SSL_CONF_HS_TIMEOUT_MAX) )
#error "MBEDTLS_SSL_CONF_HS_TIMEOUT_MIN and MBEDTLS_SSL_CONF_HS_TIMEOUT_MAX must be defined simultaneously"
#endif
#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) && \
( !defined(MBEDTLS_SSL_TLS_C) || !defined(MBEDTLS_SSL_PROTO_DTLS) )
#error "MBEDTLS_SSL_DTLS_BADMAC_LIMIT defined, but not all prerequisites"
@ -620,6 +764,32 @@
#error "MBEDTLS_SSL_EXTENDED_MASTER_SECRET defined, but not all prerequsites"
#endif
#if ( defined(MBEDTLS_SSL_CONF_EXTENDED_MASTER_SECRET) && \
!defined(MBEDTLS_SSL_CONF_ENFORCE_EXTENDED_MASTER_SECRET) ) || \
( !defined(MBEDTLS_SSL_CONF_EXTENDED_MASTER_SECRET) && \
defined(MBEDTLS_SSL_CONF_ENFORCE_EXTENDED_MASTER_SECRET) )
#error "MBEDTLS_SSL_CONF_EXTENDED_MASTER_SECRET and MBEDTLS_SSL_CONF_ENFORCE_EXTENDED_MASTER_SECRET must be defined together."
#endif
#if ( defined(MBEDTLS_SSL_CONF_SEND) && \
!( defined(MBEDTLS_SSL_CONF_RECV) && \
defined(MBEDTLS_SSL_CONF_RECV_TIMEOUT) ) ) || \
( defined(MBEDTLS_SSL_CONF_RECV) && \
!( defined(MBEDTLS_SSL_CONF_SEND) && \
defined(MBEDTLS_SSL_CONF_RECV_TIMEOUT) ) ) || \
( defined(MBEDTLS_SSL_CONF_RECV_TIMEOUT) && \
!( defined(MBEDTLS_SSL_CONF_SEND) && \
defined(MBEDTLS_SSL_CONF_RECV) ) )
#error "MBEDTLS_SSL_CONF_SEND/RECV/RECV_TIMEOUT must be defined simultaneously"
#endif
#if ( defined(MBEDTLS_SSL_CONF_GET_TIMER) && \
!defined(MBEDTLS_SSL_CONF_SET_TIMER) ) || \
( !defined(MBEDTLS_SSL_CONF_GET_TIMER) && \
defined(MBEDTLS_SSL_CONF_SET_TIMER) )
#error "MBEDTLS_SSL_CONF_GET_TIMER and MBEDTLS_SSL_CONF_SET_TIMER must be defined together."
#endif
#if defined(MBEDTLS_SSL_TICKET_C) && !defined(MBEDTLS_CIPHER_C)
#error "MBEDTLS_SSL_TICKET_C defined, but not all prerequisites"
#endif
@ -634,6 +804,16 @@
#error "MBEDTLS_SSL_SERVER_NAME_INDICATION defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_SSL_SESSION_TICKETS) && \
defined(MBEDTLS_SSL_NO_SESSION_RESUMPTION)
#error "MBEDTLS_SSL_SESSION_TICKETS cannot be defined with MBEDTLS_SSL_NO_SESSION_RESUMPTION"
#endif
#if !defined(MBEDTLS_SSL_NO_SESSION_CACHE) && \
defined(MBEDTLS_SSL_NO_SESSION_RESUMPTION)
#error "MBEDTLS_SSL_NO_SESSION_CACHE needs to be defined with MBEDTLS_SSL_NO_SESSION_RESUMPTION"
#endif
#if defined(MBEDTLS_THREADING_PTHREAD)
#if !defined(MBEDTLS_THREADING_C) || defined(MBEDTLS_THREADING_IMPL)
#error "MBEDTLS_THREADING_PTHREAD defined, but not all prerequisites"
@ -641,6 +821,104 @@
#define MBEDTLS_THREADING_IMPL
#endif
/* Ensure that precisely one hash is enabled. */
#if defined(MBEDTLS_MD_SINGLE_HASH)
#if defined(MBEDTLS_SHA256_C)
#define MBEDTLS_SHA256_ENABLED 1
#else
#define MBEDTLS_SHA256_ENABLED 0
#endif /* MBEDTLS_SHA256_C */
#if defined(MBEDTLS_SHA256_C) && !defined(MBEDTLS_SHA256_NO_SHA224)
#define MBEDTLS_SHA224_ENABLED 1
#else
#define MBEDTLS_SHA224_ENABLED 0
#endif /* MBEDTLS_SHA256_C && !MBEDTLS_SHA256_NO_SHA224 */
#if defined(MBEDTLS_SHA512_C)
#define MBEDTLS_SHA512_ENABLED 2
#else
#define MBEDTLS_SHA512_ENABLED 0
#endif /* MBEDTLS_SHA512_C */
#if defined(MBEDTLS_SHA1_C)
#define MBEDTLS_SHA1_ENABLED 1
#else
#define MBEDTLS_SHA1_ENABLED 0
#endif /* MBEDTLS_SHA1_C */
#if defined(MBEDTLS_MD2_C)
#define MBEDTLS_MD2_ENABLED 1
#else
#define MBEDTLS_MD2_ENABLED 0
#endif /* MBEDTLS_MD2_C */
#if defined(MBEDTLS_MD4_C)
#define MBEDTLS_MD4_ENABLED 1
#else
#define MBEDTLS_MD4_ENABLED 0
#endif /* MBEDTLS_MD4_C */
#if defined(MBEDTLS_MD5_C)
#define MBEDTLS_MD5_ENABLED 1
#else
#define MBEDTLS_MD5_ENABLED 0
#endif /* MBEDTLS_MD5_C */
#if defined(MBEDTLS_RIPEMD160_C)
#define MBEDTLS_RIPEMD160_ENABLED 1
#else
#define MBEDTLS_RIPEMD160_ENABLED 0
#endif /* MBEDTLS_RIPEMD160_C */
#define MBEDTLS_HASHES_ENABLED \
( MBEDTLS_MD2_ENABLED + \
MBEDTLS_MD4_ENABLED + \
MBEDTLS_MD5_ENABLED + \
MBEDTLS_RIPEMD160_ENABLED + \
MBEDTLS_SHA1_ENABLED + \
MBEDTLS_SHA256_ENABLED + \
MBEDTLS_SHA512_ENABLED )
#if MBEDTLS_HASHES_ENABLED != 1
#error "MBEDTLS_MD_SINGLE_HASH must be used with precisely one hash algorithm enabled."
#endif
#undef MBEDTLS_HASHES_ENABLED
#endif /* MBEDTLS_MD_SINGLE_HASH */
/*
* Note: the dependency on TinyCrypt is reflected in several ways in the code:
*
* 1. We only define the various MBEDTLS_PK_INFO_{TYPE}_{FIELD} macros for
* TYPE == ECKEY, resolving to the TinyCrypt version.
* 2. In pk_init() and pk_free() we assume that zeroization is a proper way
* to init/free the context, which is true of mbedtls_uecc_keypair, but
* might not always hold otherwise (think hardware-accelerated ECP_ALT).
* 3. We rely on the fact that MBEDTLS_ECP_RESTARTABLE is disabled - code
* paths (and pk_info fields) that are guarded by this are currently not
* handled by the internal abstraction layers enabling PK_SINGLE_TYPE.
*
* If this dependency is ever removed, the above points need to be addressed
* in the code.
*/
#if defined(MBEDTLS_PK_SINGLE_TYPE) && !defined(MBEDTLS_USE_TINYCRYPT)
#error "MBEDTLS_PK_SINGLE_TYPE can only be used with MBEDTLS_USE_TINYCRYPT"
#endif
/* Note: code paths that depend on MBEDTLS_PK_RSA_ALT_SUPPORT are not ported
* to the internal abstraction layers that enable PK_SINGLE_TYPE. */
#if defined(MBEDTLS_PK_SINGLE_TYPE) && defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
#error "MBEDTLS_PK_SINGLE_TYPE is not compatible with MBEDTLS_PK_RSA_ALT_SUPPORT"
#endif
/* This is to avoid a situation where RSA is available, but not through the PK
* layer, which might surprise user code. */
#if defined(MBEDTLS_PK_SINGLE_TYPE) && defined(MBEDTLS_RSA_C)
#error "MBEDTLS_PK_SINGLE_TYPE is not compatible with MBEDTLS_RSA_C"
#endif
#if defined(MBEDTLS_THREADING_ALT)
#if !defined(MBEDTLS_THREADING_C) || defined(MBEDTLS_THREADING_IMPL)
#error "MBEDTLS_THREADING_ALT defined, but not all prerequisites"
@ -657,9 +935,10 @@
#error "MBEDTLS_VERSION_FEATURES defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_X509_USE_C) && ( !defined(MBEDTLS_BIGNUM_C) || \
!defined(MBEDTLS_OID_C) || !defined(MBEDTLS_ASN1_PARSE_C) || \
!defined(MBEDTLS_PK_PARSE_C) )
#if defined(MBEDTLS_X509_USE_C) && \
( !defined(MBEDTLS_OID_C) || \
!defined(MBEDTLS_ASN1_PARSE_C) || \
!defined(MBEDTLS_PK_PARSE_C) )
#error "MBEDTLS_X509_USE_C defined, but not all prerequisites"
#endif
@ -669,6 +948,10 @@
#error "MBEDTLS_X509_CREATE_C defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_CERTS_C) && !defined(MBEDTLS_X509_USE_C)
#error "MBEDTLS_CERTS_C defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_X509_CRT_PARSE_C) && ( !defined(MBEDTLS_X509_USE_C) )
#error "MBEDTLS_X509_CRT_PARSE_C defined, but not all prerequisites"
#endif
@ -689,6 +972,11 @@
#error "MBEDTLS_X509_CSR_WRITE_C defined, but not all prerequisites"
#endif
#if defined(MBEDTLS_X509_CRT_REMOVE_TIME) && \
defined(MBEDTLS_HAVE_TIME_DATE)
#error "MBEDTLS_X509_CRT_REMOVE_TIME and MBEDTLS_HAVE_TIME_DATE cannot be defined simultaneously"
#endif
#if defined(MBEDTLS_HAVE_INT32) && defined(MBEDTLS_HAVE_INT64)
#error "MBEDTLS_HAVE_INT32 and MBEDTLS_HAVE_INT64 cannot be defined simultaneously"
#endif /* MBEDTLS_HAVE_INT32 && MBEDTLS_HAVE_INT64 */

View file

@ -283,17 +283,17 @@ typedef struct mbedtls_cipher_info_t
*/
typedef struct mbedtls_cipher_context_t
{
/** Operation that the key of the context has been
* initialized for.
*/
mbedtls_operation_t operation;
/** Information about the associated cipher. */
const mbedtls_cipher_info_t *cipher_info;
/** Key length to use. */
int key_bitlen;
/** Operation that the key of the context has been
* initialized for.
*/
mbedtls_operation_t operation;
#if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
/** Padding functions to use, if relevant for
* the specific cipher mode.
@ -302,16 +302,9 @@ typedef struct mbedtls_cipher_context_t
int (*get_padding)( unsigned char *input, size_t ilen, size_t *data_len );
#endif
/** Buffer for input that has not been processed yet. */
unsigned char unprocessed_data[MBEDTLS_MAX_BLOCK_LENGTH];
/** Number of Bytes that have not been processed yet. */
size_t unprocessed_len;
/** Current IV or NONCE_COUNTER for CTR-mode, data unit (or sector) number
* for XTS-mode. */
unsigned char iv[MBEDTLS_MAX_IV_LENGTH];
/** IV size in Bytes, for ciphers with variable-length IVs. */
size_t iv_size;
@ -322,6 +315,13 @@ typedef struct mbedtls_cipher_context_t
/** CMAC-specific context. */
mbedtls_cmac_context_t *cmac_ctx;
#endif
/** Buffer for input that has not been processed yet. */
unsigned char unprocessed_data[MBEDTLS_MAX_BLOCK_LENGTH];
/** Current IV or NONCE_COUNTER for CTR-mode, data unit (or sector) number
* for XTS-mode. */
unsigned char iv[MBEDTLS_MAX_IV_LENGTH];
} mbedtls_cipher_context_t;
/**

View file

@ -2231,7 +2231,7 @@
#define rsa_rsassa_pss_verify_ext mbedtls_rsa_rsassa_pss_verify_ext
#define rsa_self_test mbedtls_rsa_self_test
#define rsa_set_padding mbedtls_rsa_set_padding
#define safer_memcmp mbedtls_ssl_safer_memcmp
#define safer_memcmp mbedtls_platform_memcmp
#define set_alarm mbedtls_set_alarm
#define sha1 mbedtls_sha1
#define sha1_context mbedtls_sha1_context

View file

@ -596,6 +596,74 @@
*/
//#define MBEDTLS_AES_FEWER_TABLES
/**
* \def MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH
*
* Use only 128-bit keys in AES operations to save ROM.
*
* Uncommenting this macro removes support for AES operations that are using 192
* or 256-bit keys.
*
* Tradeoff: Uncommenting this macro reduces ROM footprint by ~240 bytes.
*
* If uncommented, uncomment also MBEDTLS_CTR_DRBG_USE_128_BIT_KEY
*
* Module: library/aes.c
*
* Requires: MBEDTLS_AES_C
*
*/
//#define MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH
/**
* \def MBEDTLS_AES_ONLY_ENCRYPT
*
* Use only AES encryption, decryption is not possible.
*
* Uncommenting this macro removes support for AES decryption.
*
* Tradeoff: Uncommenting this macro reduces the footprint. For
* example, when both MBEDTLS_AES_ROM_TABLES and
* MBEDTLS_AES_FEWER_TABLES are enabled, enabling this macro
* further reduces the ROM footprint by ~2.5kB.
*
* Module: library/aes.c
*
* Requires: MBEDTLS_AES_C
*
*/
//#define MBEDTLS_AES_ONLY_ENCRYPT
/**
* \def MBEDTLS_AES_SCA_COUNTERMEASURES
*
* Add countermeasures against possible side-channel-attack to AES calculation.
*
* Uncommenting this macro adds additional calculation rounds to AES
* calculation. Additional rounds are using random data for calculation. The
* additional rounds are added to:
* -initial key addition phase
* -before the first AES calculation round
* -after the last AES calculation round
*
* Tradeoff: Uncommenting this macro does not increase codesize.
* The performance loss is ~50% with 128 bit AES.
*
* This option is dependent of \c MBEDTLS_ENTROPY_HARDWARE_ALT.
*
*/
//#define MBEDTLS_AES_SCA_COUNTERMEASURES
/**
* \def MBEDTLS_FI_COUNTERMEASURES
*
* Add countermeasures against a possible FI attack.
*
* Uncommenting this macro increases code size and slows performance,
* it performs double calls and double result checks of some crypto functions
*/
//#define MBEDTLS_FI_COUNTERMEASURES
/**
* \def MBEDTLS_CAMELLIA_SMALL_MEMORY
*
@ -689,6 +757,13 @@
#define MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN
#define MBEDTLS_CIPHER_PADDING_ZEROS
/** \def MBEDTLS_CTR_DRBG_USE_128_BIT_KEY
*
* Uncomment this macro to use a 128-bit key in the CTR_DRBG module.
* By default, CTR_DRBG uses a 256-bit key.
*/
//#define MBEDTLS_CTR_DRBG_USE_128_BIT_KEY
/**
* \def MBEDTLS_ENABLE_WEAK_CIPHERSUITES
*
@ -1281,14 +1356,26 @@
*
* The default implementation is meant to be a reasonnable compromise between
* performance and size. This version optimizes more aggressively for size at
* the expense of performance. Eg on Cortex-M4 it reduces the size of
* mbedtls_sha256_process() from ~2KB to ~0.5KB for a performance hit of about
* 30%.
* the expense of performance.
*
* For example, on a Cortex-M0 core it reduces the size of the module by about
* 2KiB for a performance cost of about 45%; on a Cortex-M4 core the size
* benefit is about 1.5 KiB for a performance cost of of about 30%.
*
* Uncomment to enable the smaller implementation of SHA256.
*/
//#define MBEDTLS_SHA256_SMALLER
/**
* \def MBEDTLS_SHA256_NO_SHA224
*
* Disable the SHA-224 option of the SHA-256 module. Use this to save some
* code size on devices that don't use SHA-224.
*
* Uncomment to disable SHA-224
*/
//#define MBEDTLS_SHA256_NO_SHA224
/**
* \def MBEDTLS_SSL_ALL_ALERT_MESSAGES
*
@ -1303,6 +1390,47 @@
*/
#define MBEDTLS_SSL_ALL_ALERT_MESSAGES
/**
* \def MBEDTLS_SSL_RECORD_CHECKING
*
* Enable the API mbedtls_ssl_check_record() which allows to check the
* validity, freshness and authenticity of an incoming record without
* modifying the externally visible state of the SSL context.
*
* See mbedtls_ssl_check_record() for more information.
*
* Uncomment to enable support for record checking.
*/
#define MBEDTLS_SSL_RECORD_CHECKING
/**
* \def MBEDTLS_SSL_DTLS_CONNECTION_ID
*
* Enable support for the DTLS Connection ID extension
* (version draft-ietf-tls-dtls-connection-id-05,
* https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05)
* which allows to identify DTLS connections across changes
* in the underlying transport.
*
* Setting this option enables the SSL APIs mbedtls_ssl_set_cid(),
* mbedtls_ssl_get_peer_cid() and mbedtls_ssl_conf_cid().
* See the corresponding documentation for more information.
*
* \warning The Connection ID extension is still in draft state.
* We make no stability promises for the availability
* or the shape of the API controlled by this option.
*
* The maximum lengths of outgoing and incoming CIDs can be configured
* through the options
* - MBEDTLS_SSL_CID_OUT_LEN_MAX
* - MBEDTLS_SSL_CID_IN_LEN_MAX.
*
* Requires: MBEDTLS_SSL_PROTO_DTLS
*
* Uncomment to enable the Connection ID extension.
*/
//#define MBEDTLS_SSL_DTLS_CONNECTION_ID
/**
* \def MBEDTLS_SSL_ASYNC_PRIVATE
*
@ -1314,6 +1442,33 @@
*/
//#define MBEDTLS_SSL_ASYNC_PRIVATE
/**
* \def MBEDTLS_SSL_CONTEXT_SERIALIZATION
*
* Enable serialization of the TLS context structures, through use of the
* functions mbedtls_ssl_context_save() and mbedtls_ssl_context_load().
*
* This pair of functions allows one side of a connection to serialize the
* context associated with the connection, then free or re-use that context
* while the serialized state is persisted elsewhere, and finally deserialize
* that state to a live context for resuming read/write operations on the
* connection. From a protocol perspective, the state of the connection is
* unaffected, in particular this is entirely transparent to the peer.
*
* Note: this is distinct from TLS session resumption, which is part of the
* protocol and fully visible by the peer. TLS session resumption enables
* establishing new connections associated to a saved session with shorter,
* lighter handshakes, while context serialization is a local optimization in
* handling a single, potentially long-lived connection.
*
* Enabling these APIs makes some SSL structures larger, as 64 extra bytes are
* saved after the handshake to allow for more efficient serialization, so if
* you don't need this feature you'll save RAM by disabling it.
*
* Comment to disable the context serialization APIs.
*/
#define MBEDTLS_SSL_CONTEXT_SERIALIZATION
/**
* \def MBEDTLS_SSL_DEBUG_ALL
*
@ -1383,6 +1538,28 @@
*/
#define MBEDTLS_SSL_FALLBACK_SCSV
/**
* \def MBEDTLS_SSL_KEEP_PEER_CERTIFICATE
*
* This option controls the availability of the API mbedtls_ssl_get_peer_cert()
* giving access to the peer's certificate after completion of the handshake.
*
* Unless you need mbedtls_ssl_peer_cert() in your application, it is
* recommended to disable this option for reduced RAM usage.
*
* \note If this option is disabled, mbedtls_ssl_get_peer_cert() is still
* defined, but always returns \c NULL.
*
* \note This option has no influence on the protection against the
* triple handshake attack. Even if it is disabled, Mbed TLS will
* still ensure that certificates do not change during renegotiation,
* for exaple by keeping a hash of the peer's certificate.
*
* Comment this macro to disable storing the peer's certificate
* after the handshake.
*/
#define MBEDTLS_SSL_KEEP_PEER_CERTIFICATE
/**
* \def MBEDTLS_SSL_HW_RECORD_ACCEL
*
@ -1459,7 +1636,7 @@
/**
* \def MBEDTLS_SSL_PROTO_SSL3
*
* Enable support for SSL 3.0.
* Enable support for SSL 3.0 (if TLS is enabled).
*
* Requires: MBEDTLS_MD5_C
* MBEDTLS_SHA1_C
@ -1471,7 +1648,7 @@
/**
* \def MBEDTLS_SSL_PROTO_TLS1
*
* Enable support for TLS 1.0.
* Enable support for TLS 1.0 (if TLS is enabled).
*
* Requires: MBEDTLS_MD5_C
* MBEDTLS_SHA1_C
@ -1483,7 +1660,8 @@
/**
* \def MBEDTLS_SSL_PROTO_TLS1_1
*
* Enable support for TLS 1.1 (and DTLS 1.0 if DTLS is enabled).
* Enable support for TLS 1.1 (if TLS is enabled) and DTLS 1.0 (if DTLS is
* enabled).
*
* Requires: MBEDTLS_MD5_C
* MBEDTLS_SHA1_C
@ -1495,7 +1673,8 @@
/**
* \def MBEDTLS_SSL_PROTO_TLS1_2
*
* Enable support for TLS 1.2 (and DTLS 1.2 if DTLS is enabled).
* Enable support for TLS 1.2 (if TLS is enabled) and DTLS 1.2 (if DTLS is
* enabled).
*
* Requires: MBEDTLS_SHA1_C or MBEDTLS_SHA256_C or MBEDTLS_SHA512_C
* (Depends on ciphersuites)
@ -1509,8 +1688,10 @@
*
* Enable support for DTLS (all available versions).
*
* Enable this and MBEDTLS_SSL_PROTO_TLS1_1 to enable DTLS 1.0,
* and/or this and MBEDTLS_SSL_PROTO_TLS1_2 to enable DTLS 1.2.
* Enable this and MBEDTLS_SSL_PROTO_TLS1_2 to enable DTLS 1.2,
* and/or this and MBEDTLS_SSL_PROTO_TLS1_1 to enable DTLS 1.0.
*
* \see MBEDTLS_SSL_PROTO_NO_TLS
*
* Requires: MBEDTLS_SSL_PROTO_TLS1_1
* or MBEDTLS_SSL_PROTO_TLS1_2
@ -1519,6 +1700,25 @@
*/
#define MBEDTLS_SSL_PROTO_DTLS
/**
* \def MBEDTLS_SSL_PROTO_NO_TLS
*
* Disable support for SSL/TLS (all available versions) - this doesn't affect
* support for DTLS which is controlled by #MBEDTLS_SSL_PROTO_DTLS. This is
* useful to reduce code size in configurations where only DTLS is used.
*
* Disable this and enable MBEDTLS_SSL_PROTO_TLS1_2 to enable TLS 1.2;
* disable this and enable MBEDTLS_SSL_PROTO_TLS1_1 to enable TLS 1.1;
* disable this and enable MBEDTLS_SSL_PROTO_TLS1 to enable TLS 1.0;
* disable this and enable MBEDTLS_SSL_PROTO_SSL3 to enable SSL 3.0.
*
* Requirements: if this macro is disabled, at least one of the above
* TLS versions needs to be enabled.
*
* Uncomment this macro to disable support for TLS.
*/
//#define MBEDTLS_SSL_PROTO_NO_TLS
/**
* \def MBEDTLS_SSL_ALPN
*
@ -1598,10 +1798,63 @@
* tickets, including authenticated encryption and key management. Example
* callbacks are provided by MBEDTLS_SSL_TICKET_C.
*
* Comment this macro to disable support for SSL session tickets
* Requires: !MBEDTLS_SSL_NO_SESSION_RESUMPTION
*
* Comment this macro to disable support for SSL session tickets.
*/
#define MBEDTLS_SSL_SESSION_TICKETS
/**
* \def MBEDTLS_SSL_NO_SESSION_CACHE
*
* Disable support for cache based session resumption. This is useful to
* reduce code size in configurations where cache-based session resumption is
* not used.
*
* This option is only about the server-side support of the session caches.
* Client will only need !MBEDTLS_SSL_NO_SESSION_RESUMPTION to support
* cache based session resumption.
*
* Server-side, you also need to provide callbacks for storing and reading
* sessions from cache. Example callbacks are provided by MBEDTLS_SSL_CACHE_C.
*
* If MBEDTLS_SSL_NO_SESSION_RESUMPTION is defined, this needs to be defined
* as well.
*
* Uncomment this macro to disable support for SSL session cache.
*/
//#define MBEDTLS_SSL_NO_SESSION_CACHE
/**
* \def MBEDTLS_SSL_NO_SESSION_RESUMPTION
*
* Disable support for session resumption. This is useful to reduce code size
* in configurations where no form of session resumption is used.
*
* \note Session resumption is part of the TLS standard, disabling this
* option means that the full implementation of the standard is no longer
* used. This shouldn't cause any interoperability issues as the standard
* mandates that peers who want to resume a session need to be prepared to
* fall back to a full handshake.
*
* When this flag is enabled, following needs to be true:
* MBEDTLS_SSL_NO_SESSION_CACHE enabled
* MBEDTLS_SSL_SESSION_TICKETS disabled
*
* Client-side, this is enough to enable support for cache-based session
* resumption (as defined by the TLS standard); for ticket-based resumption
* you'll also need to enable MBEDTLS_SSL_SESSION_TICKETS.
*
* Server-side, this option is only useful in conjunction with at least
* one of !MBEDTLS_SSL_NO_SESSION_CACHE or MBEDTLS_SSL_SESSION_TICKETS.
* Each one of these additionally requires an implementation of the cache
* or tickets, examples of which are provided by MBEDTLS_SSL_CACHE_C
* and MBEDTLS_SSL_TICKET_C respectively.
*
* Uncomment this macro to disable support for SSL session resumption.
*/
//#define MBEDTLS_SSL_NO_SESSION_RESUMPTION
/**
* \def MBEDTLS_SSL_EXPORT_KEYS
*
@ -1691,6 +1944,54 @@
*/
#define MBEDTLS_VERSION_FEATURES
/**
* \def MBEDTLS_X509_ON_DEMAND_PARSING
*
* Save RAM by reducing mbedtls_x509_crt to a pointer
* to the raw CRT data and parsing CRTs on demand only.
*
* \warning This option changes the API by removing most of
* the structure fields of mbedtls_x509_crt.
*
* \warning This option and its corresponding X.509 API are currently
* under development and may change at any time.
*
* Regardless of whether this option is enabled or not, direct access of
* structure fields of `mbedtls_x509_crt` should be replaced by calls to
* one of the following functions:
* - mbedtls_x509_crt_get_frame(), to obtain a CRT frame giving
* access to several basic CRT fields (such as the CRT version),
* as well as pointers to the raw ASN.1 data of more complex fields
* (such as the issuer).
* - mbedtls_x509_crt_get_pk(), to obtain a public key context
* for the public key contained in the certificate.
* - mbedtls_x509_crt_get_issuer(), to obtain the issuer name.
* - mbedtls_x509_crt_get_subject(), to obtain the subject name.
* - mbedtls_x509_crt_get_subject_alt_names(), to obtain the
* alternative names from the subject alternative names extension.
* - mbedtls_x509_crt_get_ext_key_usage(), to obtain the state of
* the extended key usage extension.
*
* Uncomment this to enable on-demand CRT parsing to save RAM.
*/
//#define MBEDTLS_X509_ON_DEMAND_PARSING
/**
* \def MBEDTLS_X509_ALWAYS_FLUSH
*
* Save RAM by having Mbed TLS always flush caches for parsed X.509
* structures after use: This means, firstly, that caches of X.509
* structures used by an API call are flushed when the call returns,
* but it also encompasses immediate flushing of caches when Mbed TLS uses
* multiple structures in succession, thereby reducing the peak RAM usage.
* Setting this option leads to minimal RAM usage of the X.509 module at
* the cost of performance penalties when using X.509 structures multiple
* times (such as trusted CRTs on systems serving many connections).
*
* Uncomment this to always flush caches for unused X.509 structures.
*/
#define MBEDTLS_X509_ALWAYS_FLUSH
/**
* \def MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3
*
@ -1740,6 +2041,89 @@
*/
#define MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE
/**
* \def MBEDTLS_X509_REMOVE_INFO
*
* Enable mbedtls_x509_*_info() and related APIs.
*
* Comment to omit mbedtls_x509_*_info(), as well as mbedtls_debug_print_crt()
* and other functions/constants only used by these functions, thus reducing
* the code footprint by several KB.
*/
//#define MBEDTLS_X509_REMOVE_INFO
/**
* \def MBEDTLS_X509_CRT_REMOVE_TIME
*
* Don't store time validity fields in X.509 certificate structures.
*
* Uncomment this to save some code and RAM on constrained systems which
* don't have time and where there's no use of the time validity fields
* in a certificate.
*
* Requires: !MBEDTLS_HAVE_TIME_DATE
*/
//#define MBEDTLS_X509_CRT_REMOVE_TIME
/**
* \def MBEDTLS_X509_CRT_REMOVE_SUBJECT_ISSUER_ID
*
* Don't store subject and issuer ID in X.509 certificate structures.
*
* Uncomment this to save some code and RAM on constrained systems which
* don't need to inspect issuer and subject ID fields in certificates.
*/
//#define MBEDTLS_X509_CRT_REMOVE_SUBJECT_ISSUER_ID
/**
* \def MBEDTLS_X509_REMOVE_HOSTNAME_VERIFICATION
*
* Remove hostname verification from APIs related to X.509 certificate validation.
*
* \warning Uncommenting this affects parsing and verification of
* X.509 certificate by leaving Common Name and Subject Alternative Name fields out
* of parsing and verification.
*
* Affected API's:
* - mbedtls_ssl_set_hostname() not available.
* - mbedtls_x509_crt_get_subject_alt_names() not available.
* - mbedtls_x509_crt_parse_der(): Subject Alternative Name field
* is not parsed.
* - mbedtls_x509_crt_parse_der_nocopy(): Subject Alternative Name field
* is not parsed.
* - mbedtls_x509_crt_parse(): Subject Alternative Name field
* is not parsed.
* - mbedtls_x509_crt_parse_file(): Subject Alternative Name field
* is not parsed.
* - mbedtls_x509_crt_parse_path(): Subject Alternative Name field
* is not parsed.
* - mbedtls_x509_crt_info(): Subject Alternative Name field
* is not parsed.
* - mbedtls_x509_crt_verify(): param \c cn is omitted from the API.
* - mbedtls_x509_crt_verify_with_profile(): param \c cn is omitted from the API.
* - mbedtls_x509_crt_verify_restartable(): param \c cn is omitted from the API.
* -
*
* Affected structs
* - ::mbedtls_x509_crt_frame: subject_alt_raw is defined out.
* - ::mbedtls_x509_crt: subject_alt_names is defined out.
*
* Uncomment this to save some code and RAM on constrained systems which
* don't need hostname verification.
*/
//#define MBEDTLS_X509_REMOVE_HOSTNAME_VERIFICATION
/**
* \def MBEDTLS_X509_REMOVE_VERIFY_CALLBACK
*
* Remove support for X.509 certificate verification callbacks.
*
* Uncomment to save some bytes of code by removing support for X.509
* certificate verification callbacks in mbedtls_x509_crt_verify() and
* related verification API.
*/
//#define MBEDTLS_X509_REMOVE_VERIFY_CALLBACK
/**
* \def MBEDTLS_X509_RSASSA_PSS_SUPPORT
*
@ -2149,7 +2533,11 @@
*
* Enable the CTR_DRBG AES-based random generator.
* The CTR_DRBG generator uses AES-256 by default.
* To use AES-128 instead, enable MBEDTLS_CTR_DRBG_USE_128_BIT_KEY below.
* To use AES-128 instead, enable \c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY above.
*
* \note To achieve a 256-bit security strength with CTR_DRBG,
* you must use AES-256 *and* use sufficient entropy.
* See ctr_drbg.h for more details.
*
* Module: library/ctr_drbg.c
* Caller:
@ -2288,6 +2676,32 @@
*/
#define MBEDTLS_ECP_C
/**
* \def MBEDTLS_USE_TINYCRYPT
*
* Enable the TinyCrypt ECC library. This module provides alternative ECC
* handling functions replacing the native Mbed TLS ECP module.
*
* TinyCrypt is a project independent from Mbed TLS, licensed under 3-clause
* BSD, and can be found at https://github.com/intel/tinycrypt - this option
* only enables the ECC modules from TinyCrypt.
*
* Requires: MBEDTLS_SSL_CONF_RNG
* MBEDTLS_SSL_CONF_SINGLE_EC
* MBEDTLS_SSL_CONF_SINGLE_EC_TLS_ID == 23
* MBEDTLS_SSL_CONF_SINGLE_UECC_GRP_ID == MBEDTLS_UECC_DP_SECP256R1
* MBEDTLS_SHA256_C
*
* \see MBEDTLS_SSL_CONF_RNG
*
* \see MBEDTLS_SSL_CONF_SINGLE_EC
*
* Module: tinycrypt/ecc.c
* tinycrypt/ecc_dh.c
* tinycrypt/ecc_dsa.c
*/
//#define MBEDTLS_USE_TINYCRYPT
/**
* \def MBEDTLS_ENTROPY_C
*
@ -3041,7 +3455,6 @@
//#define MBEDTLS_CTR_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */
//#define MBEDTLS_CTR_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */
//#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */
//#define MBEDTLS_CTR_DRBG_USE_128_BIT_KEY /**< Use 128-bit key for CTR_DRBG - may reduce security (see ctr_drbg.h) */
/* HMAC_DRBG options */
//#define MBEDTLS_HMAC_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */
@ -3185,6 +3598,37 @@
*/
//#define MBEDTLS_SSL_IN_CONTENT_LEN 16384
/** \def MBEDTLS_SSL_CID_IN_LEN_MAX
*
* The maximum length of CIDs used for incoming DTLS messages.
*
*/
//#define MBEDTLS_SSL_CID_IN_LEN_MAX 32
/** \def MBEDTLS_SSL_CID_OUT_LEN_MAX
*
* The maximum length of CIDs used for outgoing DTLS messages.
*
*/
//#define MBEDTLS_SSL_CID_OUT_LEN_MAX 32
/** \def MBEDTLS_SSL_CID_PADDING_GRANULARITY
*
* This option controls the use of record plaintext padding
* when using the Connection ID extension in DTLS 1.2.
*
* The padding will always be chosen so that the length of the
* padded plaintext is a multiple of the value of this option.
*
* Note: A value of \c 1 means that no padding will be used
* for outgoing records.
*
* Note: On systems lacking division instructions,
* a power of two should be preferred.
*
*/
//#define MBEDTLS_SSL_CID_PADDING_GRANULARITY 16
/** \def MBEDTLS_SSL_OUT_CONTENT_LEN
*
* Maximum length (in bytes) of outgoing plaintext fragments.
@ -3320,6 +3764,184 @@
/* \} name SECTION: Customisation configuration options */
/**
* \name SECTION: Compile-time SSL configuration
*
* This section allows to fix parts of the SSL configuration
* at compile-time. If a field is fixed at compile-time, the
* corresponding SSL configuration API `mbedtls_ssl_conf_xxx()`
* is removed.
*
* This can be used on constrained systems to reduce code-size.
* \{
*/
//#define MBEDTLS_SSL_CONF_ALLOW_LEGACY_RENEGOTIATION MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION
//#define MBEDTLS_SSL_CONF_AUTHMODE MBEDTLS_SSL_VERIFY_REQUIRED
/* Timeout */
//#define MBEDTLS_SSL_CONF_READ_TIMEOUT 0
/* Endpoint (Client/Server) */
//#define MBEDTLS_SSL_CONF_ENDPOINT MBEDTLS_SSL_IS_CLIENT
//#define MBEDTLS_SSL_CONF_CERT_REQ_CA_LIST MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED
/* DTLS-specific settings */
//#define MBEDTLS_SSL_CONF_HS_TIMEOUT_MIN MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN
//#define MBEDTLS_SSL_CONF_HS_TIMEOUT_MAX MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX
//#define MBEDTLS_SSL_CONF_ANTI_REPLAY MBEDTLS_SSL_ANTI_REPLAY_ENABLED
//#define MBEDTLS_SSL_CONF_BADMAC_LIMIT 0
//#define MBEDTLS_SSL_CONF_CID_LEN 0
//#define MBEDTLS_SSL_CONF_IGNORE_UNEXPECTED_CID MBEDTLS_SSL_UNEXPECTED_CID_IGNORE
/* The timer callbacks to use by the SSL module.
* If defined,
* - MBEDTLS_SSL_CONF_SET_TIMER must evaluate to the name of an externally
* defined function with signature
* void f_set_timer( void* , uint32_t, uint32_t ),
* * MBEDTLS_SSL_CONF_SEND must evaluate to the name of an externally
* defined function with signature
* int f_get_timer( void* ).
*/
//#define MBEDTLS_SSL_CONF_GET_TIMER mbedtls_timing_get_delay
//#define MBEDTLS_SSL_CONF_SET_TIMER mbedtls_timing_set_delay
/* The send and receive callbacks to use by the SSL module.
* If defined,
* - MBEDTLS_SSL_CONF_RECV must evaluate to the name of an externally
* defined function with signature
* int f_recv( void*, unsigned char *, size_t ),
* * MBEDTLS_SSL_CONF_SEND must evaluate to the name of an externally
* defined function with signature
* int f_send( void*, const unsigned char *, size_t ),
* * MBEDTLS_SSL_CONF_RECV_TIMEOUT must evaluate to the name of an
* externally defined function with signature
* int f_recv_timeout( void*, const unsigned char *, size_t, uint32_t ).
*/
//#define MBEDTLS_SSL_CONF_RECV mbedtls_net_recv
//#define MBEDTLS_SSL_CONF_SEND mbedtls_net_send
//#define MBEDTLS_SSL_CONF_RECV_TIMEOUT mbedtls_net_recv_timeout
/* The PRNG to use by the SSL module. If defined, this must
* evaluate to the name of an externally defined function with signature
* int f_rng(void *, unsigned char *, size_t),
* which ignores its first parameter (the stack will always
* pass NULL to this function).
* NB: The reason not to drop the context parameter entirely
* is for compatibility with the Crypto and X.509 libraries
* which use RNG callbacks including context parameters.
*/
//#define MBEDTLS_SSL_CONF_RNG rng_wrap
/* TLS version */
//#define MBEDTLS_SSL_CONF_MIN_MINOR_VER MBEDTLS_SSL_MINOR_VERSION_3
//#define MBEDTLS_SSL_CONF_MAX_MINOR_VER MBEDTLS_SSL_MINOR_VERSION_3
//#define MBEDTLS_SSL_CONF_MIN_MAJOR_VER MBEDTLS_SSL_MAJOR_VERSION_3
//#define MBEDTLS_SSL_CONF_MAX_MAJOR_VER MBEDTLS_SSL_MAJOR_VERSION_3
/* ExtendedMasterSecret extension
* The following two options must be set/unset simultaneously. */
//#define MBEDTLS_SSL_CONF_EXTENDED_MASTER_SECRET MBEDTLS_SSL_EXTENDED_MS_ENABLED
//#define MBEDTLS_SSL_CONF_ENFORCE_EXTENDED_MASTER_SECRET MBEDTLS_SSL_EXTENDED_MS_ENFORCE_DISABLED
/* Set this to MBEDTLS_SUITE_{OFFICIAL_SUITE_NAME} to hardcode
* the choice of a fixed ciphersuite at compile-time.
*
* You need to make sure that the corresponding ciphersuite attributes
* are defined through macros in ssl_ciphersuites.h. See the definitions
* of MBEDTLS_SUITE_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8_XXX for an example.
*
* If this option is set, the API mbedtls_ssl_conf_ciphersuites() is removed.
*/
//#define MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE MBEDTLS_SUITE_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
/* Enable support of a single elliptic curve fixed
* at compile-time, at the benefit of code-size.
*
* On highly constrained systems with large control
* over the configuration of the connection endpoints,
* this option can be used to hardcode the choice of
* a single elliptic curve to be used for all elliptic
* curve operations during the handshake.
*
* If this is set, you must also define the following:
* - MBEDTLS_SSL_CONF_SINGLE_EC_GRP_ID (if MBEDTLS_ECP_C is set)
* This must resolve to the Mbed TLS group ID for the elliptic
* curve to use (e.g. MBEDTLS_ECP_DP_SECP256R1); see
* ::mbedtls_ecp_group_id in mbedtls/ecp.h for a complete list
* of curve identifiers.
* - MBEDTLS_SSL_CONF_SINGLE_UECC_GRP_ID (if MBEDTLS_USE_TINYCRYPT is set)
* This must resolve to MBEDTLS_UECC_DP_SECP256R1.
* - MBEDTLS_SSL_CONF_SINGLE_EC_TLS_ID
* This must resolve to the identifier for the elliptic curve
* to use according to the IANA NamedCurve registry:
* https://tools.ietf.org/html/rfc4492#section-5.1
*
* If defined, this option overwrites the effect of the
* runtime configuration API mbedtls_ssl_conf_curves().
*/
//#define MBEDTLS_SSL_CONF_SINGLE_EC
//#define MBEDTLS_SSL_CONF_SINGLE_EC_TLS_ID 23
//#define MBEDTLS_SSL_CONF_SINGLE_EC_GRP_ID MBEDTLS_ECP_DP_SECP256R1
//#define MBEDTLS_SSL_CONF_SINGLE_UECC_GRP_ID MBEDTLS_UECC_DP_SECP256R1
/* Enable support a single signature hash algorithm
* at compile-time, at the benefit of code-size.
*
* On highly constrained systems with large control
* over the configuration of the connection endpoints,
* this option can be used to hardcode the choice of
* hash algorithm to be used for signatures in the
* ServerKeyExchange and CertificateVerify messages.
*
* If this is set, you must also define the following:
* - MBEDTLS_SSL_CONF_SINGLE_SIG_HASH_MD_ID
* This must resolve to the Mbed TLS hash ID for the hash
* algorithm to use (e.g. MBEDTLS_MD_SHA256). See
* ::mbedtls_md_type_t in mbedtls/md.h for a complete
* list of supported hash algorithm identifiers.
* - MBEDTLS_SSL_CONF_SINGLE_SIG_HASH_TLS_ID
* This must resolve to the TLS identifier for the hash
* algorithm to use. See
* https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
* for a list of the supported identifiers.
*
* If defined, this option overwrites the effect of the
* runtime configuration API mbedtls_ssl_conf_sig_hashes().
*/
//#define MBEDTLS_SSL_CONF_SINGLE_SIG_HASH
//#define MBEDTLS_SSL_CONF_SINGLE_SIG_HASH_MD_ID
//#define MBEDTLS_SSL_CONF_SINGLE_SIG_HASH_TLS_ID
/* Set this to MBEDTLS_MD_INFO_{DIGEST} support of a single message
* digest at compile-time, at the benefit of code-size.
*
* On highly constrained systems with large control over the configuration of
* the connection endpoints, this option can be used to hardcode support for
* a single hash algorithm.
*
* You need to make sure that the corresponding digest algorithm attributes
* are defined through macros in md.c. See the definitions
* MBEDTLS_MD_INFO_SHA256_XXX for example.
*
*/
//#define MBEDTLS_MD_SINGLE_HASH MBEDTLS_MD_INFO_SHA256
/* Enable support for a single PK type in the PK layer.
*
* This is mainly intented to reduce code size on highly constrained system
* with large control over the set of algorithms they need to support. It will
* also reduce dynamic memory allocation.
*
* Currently this is only supported with EC keys in conjunction with the
* MBEDTLS_USE_TINYCRYPT option. Set this to MBEDTLS_PK_INFO_ECKEY to enable.
*/
//#define MBEDTLS_PK_SINGLE_TYPE MBEDTLS_PK_INFO_ECKEY
/* \} SECTION: Compile-time SSL configuration */
/* Target and application specific configurations
*
* Allow user to override any previous default.

View file

@ -1,7 +1,8 @@
/**
* \file ctr_drbg.h
*
* \brief This file contains CTR_DRBG definitions and functions.
* \brief This file contains definitions and functions for the
* CTR_DRBG pseudorandom generator.
*
* CTR_DRBG is a standardized way of building a PRNG from a block-cipher
* in counter mode operation, as defined in <em>NIST SP 800-90A:
@ -9,13 +10,35 @@
* Bit Generators</em>.
*
* The Mbed TLS implementation of CTR_DRBG uses AES-256 (default) or AES-128
* as the underlying block cipher.
* (if \c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY is enabled at compile time)
* as the underlying block cipher, with a derivation function.
* The initial seeding grabs #MBEDTLS_CTR_DRBG_ENTROPY_LEN bytes of entropy.
* See the documentation of mbedtls_ctr_drbg_seed() for more details.
*
* \warning Using 128-bit keys for CTR_DRBG limits the security of generated
* keys and operations that use random values generated to 128-bit security.
* Based on NIST SP 800-90A §10.2.1 table 3 and NIST SP 800-57 part 1 table 2,
* here are the security strengths achieved in typical configuration:
* - 256 bits under the default configuration of the library, with AES-256
* and with #MBEDTLS_CTR_DRBG_ENTROPY_LEN set to 48 or more.
* - 256 bits if AES-256 is used, #MBEDTLS_CTR_DRBG_ENTROPY_LEN is set
* to 32 or more, and the DRBG is initialized with an explicit
* nonce in the \c custom parameter to mbedtls_ctr_drbg_seed().
* - 128 bits if AES-256 is used but #MBEDTLS_CTR_DRBG_ENTROPY_LEN is
* between 24 and 47 and the DRBG is not initialized with an explicit
* nonce (see mbedtls_ctr_drbg_seed()).
* - 128 bits if AES-128 is used (\c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY enabled)
* and #MBEDTLS_CTR_DRBG_ENTROPY_LEN is set to 24 or more (which is
* always the case unless it is explicitly set to a different value
* in config.h).
*
* Note that the value of #MBEDTLS_CTR_DRBG_ENTROPY_LEN defaults to:
* - \c 48 if the module \c MBEDTLS_SHA512_C is enabled and the symbol
* \c MBEDTLS_ENTROPY_FORCE_SHA256 is disabled at compile time.
* This is the default configuration of the library.
* - \c 32 if the module \c MBEDTLS_SHA512_C is disabled at compile time.
* - \c 32 if \c MBEDTLS_ENTROPY_FORCE_SHA256 is enabled at compile time.
*/
/*
* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
* Copyright (C) 2006-2019, Arm Limited (or its affiliates), All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -56,9 +79,19 @@
#define MBEDTLS_CTR_DRBG_BLOCKSIZE 16 /**< The block size used by the cipher. */
#if defined(MBEDTLS_CTR_DRBG_USE_128_BIT_KEY)
#define MBEDTLS_CTR_DRBG_KEYSIZE 16 /**< The key size used by the cipher (compile-time choice: 128 bits). */
#define MBEDTLS_CTR_DRBG_KEYSIZE 16
/**< The key size in bytes used by the cipher.
*
* Compile-time choice: 16 bytes (128 bits)
* because #MBEDTLS_CTR_DRBG_USE_128_BIT_KEY is enabled.
*/
#else
#define MBEDTLS_CTR_DRBG_KEYSIZE 32 /**< The key size used by the cipher (compile-time choice: 256 bits). */
#define MBEDTLS_CTR_DRBG_KEYSIZE 32
/**< The key size in bytes used by the cipher.
*
* Compile-time choice: 32 bytes (256 bits)
* because \c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY is disabled.
*/
#endif
#define MBEDTLS_CTR_DRBG_KEYBITS ( MBEDTLS_CTR_DRBG_KEYSIZE * 8 ) /**< The key size for the DRBG operation, in bits. */
@ -73,21 +106,31 @@
* \{
*/
/** \def MBEDTLS_CTR_DRBG_ENTROPY_LEN
*
* \brief The amount of entropy used per seed by default, in bytes.
*/
#if !defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN)
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256)
/** This is 48 bytes because the entropy module uses SHA-512
* (\c MBEDTLS_ENTROPY_FORCE_SHA256 is disabled).
*/
#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 48
/**< The amount of entropy used per seed by default:
* <ul><li>48 with SHA-512.</li>
* <li>32 with SHA-256.</li></ul>
#else /* defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256) */
/** This is 32 bytes because the entropy module uses SHA-256
* (the SHA512 module is disabled or
* \c MBEDTLS_ENTROPY_FORCE_SHA256 is enabled).
*/
#else
#if !defined(MBEDTLS_CTR_DRBG_USE_128_BIT_KEY)
/** \warning To achieve a 256-bit security strength, you must pass a nonce
* to mbedtls_ctr_drbg_seed().
*/
#endif /* !defined(MBEDTLS_CTR_DRBG_USE_128_BIT_KEY) */
#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 32
/**< Amount of entropy used per seed by default:
* <ul><li>48 with SHA-512.</li>
* <li>32 with SHA-256.</li></ul>
*/
#endif
#endif
#endif /* defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256) */
#endif /* !defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN) */
#if !defined(MBEDTLS_CTR_DRBG_RESEED_INTERVAL)
#define MBEDTLS_CTR_DRBG_RESEED_INTERVAL 10000
@ -106,7 +149,7 @@
#if !defined(MBEDTLS_CTR_DRBG_MAX_SEED_INPUT)
#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT 384
/**< The maximum size of seed or reseed buffer. */
/**< The maximum size of seed or reseed buffer in bytes. */
#endif
/* \} name SECTION: Module settings */
@ -164,17 +207,68 @@ void mbedtls_ctr_drbg_init( mbedtls_ctr_drbg_context *ctx );
* \brief This function seeds and sets up the CTR_DRBG
* entropy source for future reseeds.
*
* \note Personalization data can be provided in addition to the more generic
* entropy source, to make this instantiation as unique as possible.
* A typical choice for the \p f_entropy and \p p_entropy parameters is
* to use the entropy module:
* - \p f_entropy is mbedtls_entropy_func();
* - \p p_entropy is an instance of ::mbedtls_entropy_context initialized
* with mbedtls_entropy_init() (which registers the platform's default
* entropy sources).
*
* The entropy length is #MBEDTLS_CTR_DRBG_ENTROPY_LEN by default.
* You can override it by calling mbedtls_ctr_drbg_set_entropy_len().
*
* You can provide a personalization string in addition to the
* entropy source, to make this instantiation as unique as possible.
*
* \note The _seed_material_ value passed to the derivation
* function in the CTR_DRBG Instantiate Process
* described in NIST SP 800-90A §10.2.1.3.2
* is the concatenation of the string obtained from
* calling \p f_entropy and the \p custom string.
* The origin of the nonce depends on the value of
* the entropy length relative to the security strength.
* - If the entropy length is at least 1.5 times the
* security strength then the nonce is taken from the
* string obtained with \p f_entropy.
* - If the entropy length is less than the security
* strength, then the nonce is taken from \p custom.
* In this case, for compliance with SP 800-90A,
* you must pass a unique value of \p custom at
* each invocation. See SP 800-90A §8.6.7 for more
* details.
*/
#if MBEDTLS_CTR_DRBG_ENTROPY_LEN < MBEDTLS_CTR_DRBG_KEYSIZE * 3 / 2
/** \warning When #MBEDTLS_CTR_DRBG_ENTROPY_LEN is less than
* #MBEDTLS_CTR_DRBG_KEYSIZE * 3 / 2, to achieve the
* maximum security strength permitted by CTR_DRBG,
* you must pass a value of \p custom that is a nonce:
* this value must never be repeated in subsequent
* runs of the same application or on a different
* device.
*/
#endif
/**
* \param ctx The CTR_DRBG context to seed.
* It must have been initialized with
* mbedtls_ctr_drbg_init().
* After a successful call to mbedtls_ctr_drbg_seed(),
* you may not call mbedtls_ctr_drbg_seed() again on
* the same context unless you call
* mbedtls_ctr_drbg_free() and mbedtls_ctr_drbg_init()
* again first.
* \param f_entropy The entropy callback, taking as arguments the
* \p p_entropy context, the buffer to fill, and the
length of the buffer.
* \param p_entropy The entropy context.
* \param custom Personalization data, that is device-specific
identifiers. Can be NULL.
* \param len The length of the personalization data.
* length of the buffer.
* \p f_entropy is always called with a buffer size
* equal to the entropy length.
* \param p_entropy The entropy context to pass to \p f_entropy.
* \param custom The personalization string.
* This can be \c NULL, in which case the personalization
* string is empty regardless of the value of \p len.
* \param len The length of the personalization string.
* This must be at most
* #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT
* - #MBEDTLS_CTR_DRBG_ENTROPY_LEN.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure.
@ -197,7 +291,8 @@ void mbedtls_ctr_drbg_free( mbedtls_ctr_drbg_context *ctx );
* The default value is off.
*
* \note If enabled, entropy is gathered at the beginning of
* every call to mbedtls_ctr_drbg_random_with_add().
* every call to mbedtls_ctr_drbg_random_with_add()
* or mbedtls_ctr_drbg_random().
* Only use this if your entropy source has sufficient
* throughput.
*
@ -209,18 +304,37 @@ void mbedtls_ctr_drbg_set_prediction_resistance( mbedtls_ctr_drbg_context *ctx,
/**
* \brief This function sets the amount of entropy grabbed on each
* seed or reseed. The default value is
* #MBEDTLS_CTR_DRBG_ENTROPY_LEN.
* seed or reseed.
*
* The default value is #MBEDTLS_CTR_DRBG_ENTROPY_LEN.
*
* \note The security strength of CTR_DRBG is bounded by the
* entropy length. Thus:
* - When using AES-256
* (\c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY is disabled,
* which is the default),
* \p len must be at least 32 (in bytes)
* to achieve a 256-bit strength.
* - When using AES-128
* (\c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY is enabled)
* \p len must be at least 16 (in bytes)
* to achieve a 128-bit strength.
*
* \param ctx The CTR_DRBG context.
* \param len The amount of entropy to grab.
* \param len The amount of entropy to grab, in bytes.
* This must be at most #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT.
*/
void mbedtls_ctr_drbg_set_entropy_len( mbedtls_ctr_drbg_context *ctx,
size_t len );
/**
* \brief This function sets the reseed interval.
* The default value is #MBEDTLS_CTR_DRBG_RESEED_INTERVAL.
*
* The reseed interval is the number of calls to mbedtls_ctr_drbg_random()
* or mbedtls_ctr_drbg_random_with_add() after which the entropy function
* is called again.
*
* The default value is #MBEDTLS_CTR_DRBG_RESEED_INTERVAL.
*
* \param ctx The CTR_DRBG context.
* \param interval The reseed interval.
@ -233,8 +347,12 @@ void mbedtls_ctr_drbg_set_reseed_interval( mbedtls_ctr_drbg_context *ctx,
* extracts data from the entropy source.
*
* \param ctx The CTR_DRBG context.
* \param additional Additional data to add to the state. Can be NULL.
* \param additional Additional data to add to the state. Can be \c NULL.
* \param len The length of the additional data.
* This must be less than
* #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT - \c entropy_len
* where \c entropy_len is the entropy length
* configured for the context.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure.
@ -246,7 +364,8 @@ int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx,
* \brief This function updates the state of the CTR_DRBG context.
*
* \param ctx The CTR_DRBG context.
* \param additional The data to update the state with.
* \param additional The data to update the state with. This must not be
* \c NULL unless \p add_len is \c 0.
* \param add_len Length of \p additional in bytes. This must be at
* most #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT.
*
@ -264,14 +383,23 @@ int mbedtls_ctr_drbg_update_ret( mbedtls_ctr_drbg_context *ctx,
* \brief This function updates a CTR_DRBG instance with additional
* data and uses it to generate random data.
*
* \note The function automatically reseeds if the reseed counter is exceeded.
* This function automatically reseeds if the reseed counter is exceeded
* or prediction resistance is enabled.
*
* \param p_rng The CTR_DRBG context. This must be a pointer to a
* #mbedtls_ctr_drbg_context structure.
* \param output The buffer to fill.
* \param output_len The length of the buffer.
* \param additional Additional data to update. Can be NULL.
* \param add_len The length of the additional data.
* \param output_len The length of the buffer in bytes.
* \param additional Additional data to update. Can be \c NULL, in which
* case the additional data is empty regardless of
* the value of \p add_len.
* \param add_len The length of the additional data
* if \p additional is not \c NULL.
* This must be less than #MBEDTLS_CTR_DRBG_MAX_INPUT
* and less than
* #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT - \c entropy_len
* where \c entropy_len is the entropy length
* configured for the context.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or
@ -284,12 +412,14 @@ int mbedtls_ctr_drbg_random_with_add( void *p_rng,
/**
* \brief This function uses CTR_DRBG to generate random data.
*
* \note The function automatically reseeds if the reseed counter is exceeded.
* This function automatically reseeds if the reseed counter is exceeded
* or prediction resistance is enabled.
*
*
* \param p_rng The CTR_DRBG context. This must be a pointer to a
* #mbedtls_ctr_drbg_context structure.
* \param output The buffer to fill.
* \param output_len The length of the buffer.
* \param output_len The length of the buffer in bytes.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or
@ -336,7 +466,7 @@ MBEDTLS_DEPRECATED void mbedtls_ctr_drbg_update(
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error.
* \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on
* \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on reseed
* failure.
*/
int mbedtls_ctr_drbg_write_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path );
@ -350,8 +480,10 @@ int mbedtls_ctr_drbg_write_seed_file( mbedtls_ctr_drbg_context *ctx, const char
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error.
* \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or
* #MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG on failure.
* \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on
* reseed failure.
* \return #MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG if the existing
* seed file is too large.
*/
int mbedtls_ctr_drbg_update_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path );
#endif /* MBEDTLS_FS_IO */

View file

@ -36,6 +36,10 @@
#include "ecp.h"
#endif
#if defined(MBEDTLS_ECDH_C)
#include "ecdh.h"
#endif
#if defined(MBEDTLS_DEBUG_C)
#define MBEDTLS_DEBUG_STRIP_PARENS( ... ) __VA_ARGS__
@ -61,9 +65,13 @@
#endif
#if defined(MBEDTLS_X509_CRT_PARSE_C)
#if !defined(MBEDTLS_X509_REMOVE_INFO)
#define MBEDTLS_SSL_DEBUG_CRT( level, text, crt ) \
mbedtls_debug_print_crt( ssl, level, __FILE__, __LINE__, text, crt )
#endif
#else
#define MBEDTLS_SSL_DEBUG_CRT( level, text, crt ) do { } while( 0 )
#endif /* !MBEDTLS_X509_REMOVE_INFO */
#endif /* MBEDTLS_X509_CRT_PARSE_C */
#if defined(MBEDTLS_ECDH_C)
#define MBEDTLS_SSL_DEBUG_ECDH( level, ecdh, attr ) \
@ -206,7 +214,7 @@ void mbedtls_debug_print_ecp( const mbedtls_ssl_context *ssl, int level,
const char *text, const mbedtls_ecp_point *X );
#endif
#if defined(MBEDTLS_X509_CRT_PARSE_C)
#if defined(MBEDTLS_X509_CRT_PARSE_C) && !defined(MBEDTLS_X509_REMOVE_INFO)
/**
* \brief Print a X.509 certificate structure to the debug output. This
* function is always used through the MBEDTLS_SSL_DEBUG_CRT() macro,
@ -262,4 +270,3 @@ void mbedtls_debug_printf_ecdh( const mbedtls_ssl_context *ssl, int level,
#endif
#endif /* debug.h */

View file

@ -75,7 +75,7 @@ typedef enum {
*/
typedef struct mbedtls_ecjpake_context
{
const mbedtls_md_info_t *md_info; /**< Hash to use */
mbedtls_md_handle_t md_info; /**< Hash to use */
mbedtls_ecp_group grp; /**< Elliptic curve */
mbedtls_ecjpake_role role; /**< Are we client or server? */
int point_format; /**< Format for point export */

View file

@ -83,8 +83,8 @@
#define MBEDTLS_ENTROPY_MAX_SEED_SIZE 1024 /**< Maximum size of seed we read from seed file */
#define MBEDTLS_ENTROPY_SOURCE_MANUAL MBEDTLS_ENTROPY_MAX_SOURCES
#define MBEDTLS_ENTROPY_SOURCE_STRONG 1 /**< Entropy source is strong */
#define MBEDTLS_ENTROPY_SOURCE_WEAK 0 /**< Entropy source is weak */
#define MBEDTLS_ENTROPY_SOURCE_STRONG 0x7F /**< Entropy source is strong */
#define MBEDTLS_ENTROPY_SOURCE_WEAK 0x0 /**< Entropy source is weak */
#ifdef __cplusplus
extern "C" {

View file

@ -86,7 +86,7 @@
* CHACHA20 3 0x0051-0x0055
* POLY1305 3 0x0057-0x005B
* CHACHAPOLY 2 0x0054-0x0056
* PLATFORM 1 0x0070-0x0072
* PLATFORM 4 0x0070-0x0072 0x0071-0x0071 0x0076-0x0076
*
* High-level module nr (3 bits - 0x0...-0x7...)
* Name ID Nr of Errors
@ -100,8 +100,9 @@
* ECP 4 10 (Started from top)
* MD 5 5
* HKDF 5 1 (Started from top)
* CIPHER 6 8
* SSL 6 23 (Started from top)
* SSL 5 1 (Started from 0x5F00)
* CIPHER 6 8 (Started from 0x6080)
* SSL 6 24 (Started from top, plus 0x6000)
* SSL 7 32
*
* Module dependent error code (5 bits 0x.00.-0x.F8.)

View file

@ -70,7 +70,7 @@ extern "C" {
* \return An MBEDTLS_ERR_MD_* error for errors returned from the underlying
* MD layer.
*/
int mbedtls_hkdf( const mbedtls_md_info_t *md, const unsigned char *salt,
int mbedtls_hkdf( mbedtls_md_handle_t md, const unsigned char *salt,
size_t salt_len, const unsigned char *ikm, size_t ikm_len,
const unsigned char *info, size_t info_len,
unsigned char *okm, size_t okm_len );
@ -99,7 +99,7 @@ int mbedtls_hkdf( const mbedtls_md_info_t *md, const unsigned char *salt,
* \return An MBEDTLS_ERR_MD_* error for errors returned from the underlying
* MD layer.
*/
int mbedtls_hkdf_extract( const mbedtls_md_info_t *md,
int mbedtls_hkdf_extract( mbedtls_md_handle_t md,
const unsigned char *salt, size_t salt_len,
const unsigned char *ikm, size_t ikm_len,
unsigned char *prk );
@ -130,7 +130,7 @@ int mbedtls_hkdf_extract( const mbedtls_md_info_t *md,
* \return An MBEDTLS_ERR_MD_* error for errors returned from the underlying
* MD layer.
*/
int mbedtls_hkdf_expand( const mbedtls_md_info_t *md, const unsigned char *prk,
int mbedtls_hkdf_expand( mbedtls_md_handle_t md, const unsigned char *prk,
size_t prk_len, const unsigned char *info,
size_t info_len, unsigned char *okm, size_t okm_len );

View file

@ -1,10 +1,14 @@
/**
* \file hmac_drbg.h
*
* \brief HMAC_DRBG (NIST SP 800-90A)
* \brief The HMAC_DRBG pseudorandom generator.
*
* This module implements the HMAC_DRBG pseudorandom generator described
* in <em>NIST SP 800-90A: Recommendation for Random Number Generation Using
* Deterministic Random Bit Generators</em>.
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* Copyright (C) 2006-2019, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -70,8 +74,8 @@
/* \} name SECTION: Module settings */
#define MBEDTLS_HMAC_DRBG_PR_OFF 0 /**< No prediction resistance */
#define MBEDTLS_HMAC_DRBG_PR_ON 1 /**< Prediction resistance enabled */
#define MBEDTLS_HMAC_DRBG_PR_OFF 0x55555555 /**< No prediction resistance */
#define MBEDTLS_HMAC_DRBG_PR_ON 0x2AAAAAAA /**< Prediction resistance enabled */
#ifdef __cplusplus
extern "C" {
@ -104,41 +108,75 @@ typedef struct mbedtls_hmac_drbg_context
} mbedtls_hmac_drbg_context;
/**
* \brief HMAC_DRBG context initialization
* Makes the context ready for mbedtls_hmac_drbg_seed(),
* mbedtls_hmac_drbg_seed_buf() or
* mbedtls_hmac_drbg_free().
* \brief HMAC_DRBG context initialization.
*
* \param ctx HMAC_DRBG context to be initialized
* This function makes the context ready for mbedtls_hmac_drbg_seed(),
* mbedtls_hmac_drbg_seed_buf() or mbedtls_hmac_drbg_free().
*
* \param ctx HMAC_DRBG context to be initialized.
*/
void mbedtls_hmac_drbg_init( mbedtls_hmac_drbg_context *ctx );
/**
* \brief HMAC_DRBG initial seeding
* Seed and setup entropy source for future reseeds.
* \brief HMAC_DRBG initial seeding.
*
* \param ctx HMAC_DRBG context to be seeded
* \param md_info MD algorithm to use for HMAC_DRBG
* \param f_entropy Entropy callback (p_entropy, buffer to fill, buffer
* length)
* \param p_entropy Entropy context
* \param custom Personalization data (Device specific identifiers)
* (Can be NULL)
* \param len Length of personalization data
* Set the initial seed and set up the entropy source for future reseeds.
*
* \note The "security strength" as defined by NIST is set to:
* 128 bits if md_alg is SHA-1,
* 192 bits if md_alg is SHA-224,
* 256 bits if md_alg is SHA-256 or higher.
* A typical choice for the \p f_entropy and \p p_entropy parameters is
* to use the entropy module:
* - \p f_entropy is mbedtls_entropy_func();
* - \p p_entropy is an instance of ::mbedtls_entropy_context initialized
* with mbedtls_entropy_init() (which registers the platform's default
* entropy sources).
*
* You can provide a personalization string in addition to the
* entropy source, to make this instantiation as unique as possible.
*
* \note By default, the security strength as defined by NIST is:
* - 128 bits if \p md_info is SHA-1;
* - 192 bits if \p md_info is SHA-224;
* - 256 bits if \p md_info is SHA-256, SHA-384 or SHA-512.
* Note that SHA-256 is just as efficient as SHA-224.
* The security strength can be reduced if a smaller
* entropy length is set with
* mbedtls_hmac_drbg_set_entropy_len().
*
* \return 0 if successful, or
* MBEDTLS_ERR_MD_BAD_INPUT_DATA, or
* MBEDTLS_ERR_MD_ALLOC_FAILED, or
* MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED.
* \note The default entropy length is the security strength
* (converted from bits to bytes). You can override
* it by calling mbedtls_hmac_drbg_set_entropy_len().
*
* \note During the initial seeding, this function calls
* the entropy source to obtain a nonce
* whose length is half the entropy length.
*
* \param ctx HMAC_DRBG context to be seeded.
* \param md_info MD algorithm to use for HMAC_DRBG.
* \param f_entropy The entropy callback, taking as arguments the
* \p p_entropy context, the buffer to fill, and the
* length of the buffer.
* \p f_entropy is always called with a length that is
* less than or equal to the entropy length.
* \param p_entropy The entropy context to pass to \p f_entropy.
* \param custom The personalization string.
* This can be \c NULL, in which case the personalization
* string is empty regardless of the value of \p len.
* \param len The length of the personalization string.
* This must be at most #MBEDTLS_HMAC_DRBG_MAX_INPUT
* and also at most
* #MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT - \p entropy_len * 3 / 2
* where \p entropy_len is the entropy length
* described above.
*
* \return \c 0 if successful.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info is
* invalid.
* \return #MBEDTLS_ERR_MD_ALLOC_FAILED if there was not enough
* memory to allocate context data.
* \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED
* if the call to \p f_entropy failed.
*/
int mbedtls_hmac_drbg_seed( mbedtls_hmac_drbg_context *ctx,
const mbedtls_md_info_t * md_info,
mbedtls_md_handle_t md_info,
int (*f_entropy)(void *, unsigned char *, size_t),
void *p_entropy,
const unsigned char *custom,
@ -146,98 +184,134 @@ int mbedtls_hmac_drbg_seed( mbedtls_hmac_drbg_context *ctx,
/**
* \brief Initilisation of simpified HMAC_DRBG (never reseeds).
* (For use with deterministic ECDSA.)
*
* \param ctx HMAC_DRBG context to be initialised
* \param md_info MD algorithm to use for HMAC_DRBG
* \param data Concatenation of entropy string and additional data
* \param data_len Length of data in bytes
* This function is meant for use in algorithms that need a pseudorandom
* input such as deterministic ECDSA.
*
* \return 0 if successful, or
* MBEDTLS_ERR_MD_BAD_INPUT_DATA, or
* MBEDTLS_ERR_MD_ALLOC_FAILED.
* \param ctx HMAC_DRBG context to be initialised.
* \param md_info MD algorithm to use for HMAC_DRBG.
* \param data Concatenation of the initial entropy string and
* the additional data.
* \param data_len Length of \p data in bytes.
*
* \return \c 0 if successful. or
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info is
* invalid.
* \return #MBEDTLS_ERR_MD_ALLOC_FAILED if there was not enough
* memory to allocate context data.
*/
int mbedtls_hmac_drbg_seed_buf( mbedtls_hmac_drbg_context *ctx,
const mbedtls_md_info_t * md_info,
mbedtls_md_handle_t md_info,
const unsigned char *data, size_t data_len );
/**
* \brief Enable / disable prediction resistance (Default: Off)
* \brief This function turns prediction resistance on or off.
* The default value is off.
*
* Note: If enabled, entropy is used for ctx->entropy_len before each call!
* Only use this if you have ample supply of good entropy!
* \note If enabled, entropy is gathered at the beginning of
* every call to mbedtls_hmac_drbg_random_with_add()
* or mbedtls_hmac_drbg_random().
* Only use this if your entropy source has sufficient
* throughput.
*
* \param ctx HMAC_DRBG context
* \param resistance MBEDTLS_HMAC_DRBG_PR_ON or MBEDTLS_HMAC_DRBG_PR_OFF
* \param ctx The HMAC_DRBG context.
* \param resistance #MBEDTLS_HMAC_DRBG_PR_ON or #MBEDTLS_HMAC_DRBG_PR_OFF.
*/
void mbedtls_hmac_drbg_set_prediction_resistance( mbedtls_hmac_drbg_context *ctx,
int resistance );
/**
* \brief Set the amount of entropy grabbed on each reseed
* (Default: given by the security strength, which
* depends on the hash used, see \c mbedtls_hmac_drbg_init() )
* \brief This function sets the amount of entropy grabbed on each
* seed or reseed.
*
* \param ctx HMAC_DRBG context
* \param len Amount of entropy to grab, in bytes
* See the documentation of mbedtls_hmac_drbg_seed() for the default value.
*
* \param ctx The HMAC_DRBG context.
* \param len The amount of entropy to grab, in bytes.
*/
void mbedtls_hmac_drbg_set_entropy_len( mbedtls_hmac_drbg_context *ctx,
size_t len );
/**
* \brief Set the reseed interval
* (Default: MBEDTLS_HMAC_DRBG_RESEED_INTERVAL)
* \brief Set the reseed interval.
*
* \param ctx HMAC_DRBG context
* \param interval Reseed interval
* The reseed interval is the number of calls to mbedtls_hmac_drbg_random()
* or mbedtls_hmac_drbg_random_with_add() after which the entropy function
* is called again.
*
* The default value is #MBEDTLS_HMAC_DRBG_RESEED_INTERVAL.
*
* \param ctx The HMAC_DRBG context.
* \param interval The reseed interval.
*/
void mbedtls_hmac_drbg_set_reseed_interval( mbedtls_hmac_drbg_context *ctx,
int interval );
/**
* \brief HMAC_DRBG update state
* \brief This function updates the state of the HMAC_DRBG context.
*
* \param ctx HMAC_DRBG context
* \param additional Additional data to update state with, or NULL
* \param add_len Length of additional data, or 0
* \param ctx The HMAC_DRBG context.
* \param additional The data to update the state with.
* If this is \c NULL, there is no additional data.
* \param add_len Length of \p additional in bytes.
* Unused if \p additional is \c NULL.
*
* \return \c 0 on success, or an error from the underlying
* hash calculation.
*
* \note Additional data is optional, pass NULL and 0 as second
* third argument if no additional data is being used.
* hash calculation or
* MBEDTLS_ERR_PLATFORM_FAULT_DETECTED.
*/
int mbedtls_hmac_drbg_update_ret( mbedtls_hmac_drbg_context *ctx,
const unsigned char *additional, size_t add_len );
/**
* \brief HMAC_DRBG reseeding (extracts data from entropy source)
* \brief This function reseeds the HMAC_DRBG context, that is
* extracts data from the entropy source.
*
* \param ctx HMAC_DRBG context
* \param additional Additional data to add to state (Can be NULL)
* \param len Length of additional data
* \param ctx The HMAC_DRBG context.
* \param additional Additional data to add to the state.
* If this is \c NULL, there is no additional data
* and \p len should be \c 0.
* \param len The length of the additional data.
* This must be at most #MBEDTLS_HMAC_DRBG_MAX_INPUT
* and also at most
* #MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT - \p entropy_len
* where \p entropy_len is the entropy length
* (see mbedtls_hmac_drbg_set_entropy_len()).
*
* \return 0 if successful, or
* MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED
* \return \c 0 if successful.
* \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED
* if a call to the entropy function failed.
*/
int mbedtls_hmac_drbg_reseed( mbedtls_hmac_drbg_context *ctx,
const unsigned char *additional, size_t len );
/**
* \brief HMAC_DRBG generate random with additional update input
* \brief This function updates an HMAC_DRBG instance with additional
* data and uses it to generate random data.
*
* Note: Automatically reseeds if reseed_counter is reached or PR is enabled.
* This function automatically reseeds if the reseed counter is exceeded
* or prediction resistance is enabled.
*
* \param p_rng HMAC_DRBG context
* \param output Buffer to fill
* \param output_len Length of the buffer
* \param additional Additional data to update with (can be NULL)
* \param add_len Length of additional data (can be 0)
* \param p_rng The HMAC_DRBG context. This must be a pointer to a
* #mbedtls_hmac_drbg_context structure.
* \param output The buffer to fill.
* \param output_len The length of the buffer in bytes.
* This must be at most #MBEDTLS_HMAC_DRBG_MAX_REQUEST.
* \param additional Additional data to update with.
* If this is \c NULL, there is no additional data
* and \p add_len should be \c 0.
* \param add_len The length of the additional data.
* This must be at most #MBEDTLS_HMAC_DRBG_MAX_INPUT.
*
* \return 0 if successful, or
* MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED, or
* MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG, or
* MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG.
* \return \c 0 if successful.
* \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED
* if a call to the entropy source failed.
* \return #MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG if
* \p output_len > #MBEDTLS_HMAC_DRBG_MAX_REQUEST.
* \return #MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG if
* \p add_len > #MBEDTLS_HMAC_DRBG_MAX_INPUT.
* \return #MBEDTLS_ERR_PLATFORM_FAULT_DETECTED if
* a logical fault is detected.
*/
int mbedtls_hmac_drbg_random_with_add( void *p_rng,
unsigned char *output, size_t output_len,
@ -245,24 +319,31 @@ int mbedtls_hmac_drbg_random_with_add( void *p_rng,
size_t add_len );
/**
* \brief HMAC_DRBG generate random
* \brief This function uses HMAC_DRBG to generate random data.
*
* Note: Automatically reseeds if reseed_counter is reached or PR is enabled.
* This function automatically reseeds if the reseed counter is exceeded
* or prediction resistance is enabled.
*
* \param p_rng HMAC_DRBG context
* \param output Buffer to fill
* \param out_len Length of the buffer
* \param p_rng The HMAC_DRBG context. This must be a pointer to a
* #mbedtls_hmac_drbg_context structure.
* \param output The buffer to fill.
* \param out_len The length of the buffer in bytes.
* This must be at most #MBEDTLS_HMAC_DRBG_MAX_REQUEST.
*
* \return 0 if successful, or
* MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED, or
* MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG
* \return \c 0 if successful.
* \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED
* if a call to the entropy source failed.
* \return #MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG if
* \p out_len > #MBEDTLS_HMAC_DRBG_MAX_REQUEST.
* \return #MBEDTLS_ERR_PLATFORM_FAULT_DETECTED if
* a logical fault is detected.
*/
int mbedtls_hmac_drbg_random( void *p_rng, unsigned char *output, size_t out_len );
/**
* \brief Free an HMAC_DRBG context
*
* \param ctx HMAC_DRBG context to free.
* \param ctx The HMAC_DRBG context to free.
*/
void mbedtls_hmac_drbg_free( mbedtls_hmac_drbg_context *ctx );
@ -273,17 +354,16 @@ void mbedtls_hmac_drbg_free( mbedtls_hmac_drbg_context *ctx );
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief HMAC_DRBG update state
* \brief This function updates the state of the HMAC_DRBG context.
*
* \deprecated Superseded by mbedtls_hmac_drbg_update_ret()
* in 2.16.0.
*
* \param ctx HMAC_DRBG context
* \param additional Additional data to update state with, or NULL
* \param add_len Length of additional data, or 0
*
* \note Additional data is optional, pass NULL and 0 as second
* third argument if no additional data is being used.
* \param ctx The HMAC_DRBG context.
* \param additional The data to update the state with.
* If this is \c NULL, there is no additional data.
* \param add_len Length of \p additional in bytes.
* Unused if \p additional is \c NULL.
*/
MBEDTLS_DEPRECATED void mbedtls_hmac_drbg_update(
mbedtls_hmac_drbg_context *ctx,
@ -293,26 +373,31 @@ MBEDTLS_DEPRECATED void mbedtls_hmac_drbg_update(
#if defined(MBEDTLS_FS_IO)
/**
* \brief Write a seed file
* \brief This function writes a seed file.
*
* \param ctx HMAC_DRBG context
* \param path Name of the file
* \param ctx The HMAC_DRBG context.
* \param path The name of the file.
*
* \return 0 if successful, 1 on file error, or
* MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED
* \return \c 0 on success.
* \return #MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR on file error.
* \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED on reseed
* failure.
*/
int mbedtls_hmac_drbg_write_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path );
/**
* \brief Read and update a seed file. Seed is added to this
* instance
* \brief This function reads and updates a seed file. The seed
* is added to this instance.
*
* \param ctx HMAC_DRBG context
* \param path Name of the file
* \param ctx The HMAC_DRBG context.
* \param path The name of the file.
*
* \return 0 if successful, 1 on file error,
* MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED or
* MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG
* \return \c 0 on success.
* \return #MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR on file error.
* \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED on
* reseed failure.
* \return #MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG if the existing
* seed file is too large.
*/
int mbedtls_hmac_drbg_update_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path );
#endif /* MBEDTLS_FS_IO */
@ -320,9 +405,10 @@ int mbedtls_hmac_drbg_update_seed_file( mbedtls_hmac_drbg_context *ctx, const ch
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine
* \brief The HMAC_DRBG Checkup routine.
*
* \return 0 if successful, or 1 if the test failed
* \return \c 0 if successful.
* \return \c 1 if the test failed.
*/
int mbedtls_hmac_drbg_self_test( int verbose );
#endif

View file

@ -35,6 +35,11 @@
#include MBEDTLS_CONFIG_FILE
#endif
#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
!defined(inline) && !defined(__cplusplus)
#define inline __inline
#endif
#define MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE -0x5080 /**< The selected feature is not available. */
#define MBEDTLS_ERR_MD_BAD_INPUT_DATA -0x5100 /**< Bad input parameters to function. */
#define MBEDTLS_ERR_MD_ALLOC_FAILED -0x5180 /**< Failed to allocate memory. */
@ -74,26 +79,78 @@ typedef enum {
#define MBEDTLS_MD_MAX_SIZE 32 /* longest known is SHA256 or less */
#endif
#if defined(MBEDTLS_SHA512_C)
#define MBEDTLS_MD_MAX_BLOCK_SIZE 128
#else
#define MBEDTLS_MD_MAX_BLOCK_SIZE 64
#endif
#if !defined(MBEDTLS_MD_SINGLE_HASH)
#define MBEDTLS_MD_INLINABLE_API
/**
* Opaque struct defined in md_internal.h.
* Opaque struct defined in md.c.
*/
typedef struct mbedtls_md_info_t mbedtls_md_info_t;
typedef struct mbedtls_md_info_t const * mbedtls_md_handle_t;
#define MBEDTLS_MD_INVALID_HANDLE ( (mbedtls_md_handle_t) NULL )
#else /* !MBEDTLS_MD_SINGLE_HASH */
#define MBEDTLS_MD_INLINABLE_API MBEDTLS_ALWAYS_INLINE static inline
typedef int mbedtls_md_handle_t;
#define MBEDTLS_MD_INVALID_HANDLE ( (mbedtls_md_handle_t) 0 )
#define MBEDTLS_MD_UNIQUE_VALID_HANDLE ( (mbedtls_md_handle_t) 1 )
#endif /* !MBEDTLS_MD_SINGLE_HASH */
#include "md_internal.h"
/**
* The generic message-digest context.
*/
typedef struct mbedtls_md_context_t
{
#if !defined(MBEDTLS_MD_SINGLE_HASH)
/** Information about the associated message digest. */
const mbedtls_md_info_t *md_info;
mbedtls_md_handle_t md_info;
#endif
#if !defined(MBEDTLS_MD_SINGLE_HASH)
/** The digest-specific context. */
void *md_ctx;
/** The HMAC part of the context. */
void *hmac_ctx;
#else
unsigned char md_ctx[ sizeof( MBEDTLS_MD_INFO_CTX_TYPE(
MBEDTLS_MD_SINGLE_HASH ) ) ];
unsigned char hmac_ctx[ 2 * MBEDTLS_MD_INFO_BLOCKSIZE(
MBEDTLS_MD_SINGLE_HASH ) ];
#endif /* MBEDTLS_MD_SINGLE_HASH */
} mbedtls_md_context_t;
#if !defined(MBEDTLS_MD_SINGLE_HASH)
static inline mbedtls_md_handle_t mbedtls_md_get_handle(
struct mbedtls_md_context_t const *ctx )
{
return( ctx->md_info );
}
#else /* !MBEDTLS_MD_SINGLE_HASH */
static inline mbedtls_md_handle_t mbedtls_md_get_handle(
struct mbedtls_md_context_t const *ctx )
{
((void) ctx);
return( MBEDTLS_MD_UNIQUE_VALID_HANDLE );
}
#endif /* !MBEDTLS_MD_SINGLE_HASH */
/**
* \brief This function returns the list of digests supported by the
* generic digest module.
@ -114,7 +171,7 @@ const int *mbedtls_md_list( void );
* \return The message-digest information associated with \p md_name.
* \return NULL if the associated message-digest information is not found.
*/
const mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name );
mbedtls_md_handle_t mbedtls_md_info_from_string( const char *md_name );
/**
* \brief This function returns the message-digest information
@ -125,7 +182,7 @@ const mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name );
* \return The message-digest information associated with \p md_type.
* \return NULL if the associated message-digest information is not found.
*/
const mbedtls_md_info_t *mbedtls_md_info_from_type( mbedtls_md_type_t md_type );
mbedtls_md_handle_t mbedtls_md_info_from_type( mbedtls_md_type_t md_type );
/**
* \brief This function initializes a message-digest context without
@ -176,7 +233,7 @@ void mbedtls_md_free( mbedtls_md_context_t *ctx );
* failure.
* \return #MBEDTLS_ERR_MD_ALLOC_FAILED on memory-allocation failure.
*/
int mbedtls_md_init_ctx( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info ) MBEDTLS_DEPRECATED;
int mbedtls_md_init_ctx( mbedtls_md_context_t *ctx, mbedtls_md_handle_t md_info ) MBEDTLS_DEPRECATED;
#undef MBEDTLS_DEPRECATED
#endif /* MBEDTLS_DEPRECATED_REMOVED */
@ -199,7 +256,9 @@ int mbedtls_md_init_ctx( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_
* failure.
* \return #MBEDTLS_ERR_MD_ALLOC_FAILED on memory-allocation failure.
*/
int mbedtls_md_setup( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info, int hmac );
MBEDTLS_MD_INLINABLE_API int mbedtls_md_setup( mbedtls_md_context_t *ctx,
mbedtls_md_handle_t md_info,
int hmac );
/**
* \brief This function clones the state of an message-digest
@ -232,7 +291,7 @@ int mbedtls_md_clone( mbedtls_md_context_t *dst,
*
* \return The size of the message-digest output in Bytes.
*/
unsigned char mbedtls_md_get_size( const mbedtls_md_info_t *md_info );
unsigned char mbedtls_md_get_size( mbedtls_md_handle_t md_info );
/**
* \brief This function extracts the message-digest type from the
@ -243,7 +302,7 @@ unsigned char mbedtls_md_get_size( const mbedtls_md_info_t *md_info );
*
* \return The type of the message digest.
*/
mbedtls_md_type_t mbedtls_md_get_type( const mbedtls_md_info_t *md_info );
mbedtls_md_type_t mbedtls_md_get_type( mbedtls_md_handle_t md_info );
/**
* \brief This function extracts the message-digest name from the
@ -254,7 +313,7 @@ mbedtls_md_type_t mbedtls_md_get_type( const mbedtls_md_info_t *md_info );
*
* \return The name of the message digest.
*/
const char *mbedtls_md_get_name( const mbedtls_md_info_t *md_info );
const char *mbedtls_md_get_name( mbedtls_md_handle_t md_info );
/**
* \brief This function starts a message-digest computation.
@ -269,7 +328,7 @@ const char *mbedtls_md_get_name( const mbedtls_md_info_t *md_info );
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md_starts( mbedtls_md_context_t *ctx );
MBEDTLS_MD_INLINABLE_API int mbedtls_md_starts( mbedtls_md_context_t *ctx );
/**
* \brief This function feeds an input buffer into an ongoing
@ -287,7 +346,9 @@ int mbedtls_md_starts( mbedtls_md_context_t *ctx );
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen );
MBEDTLS_MD_INLINABLE_API int mbedtls_md_update( mbedtls_md_context_t *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief This function finishes the digest operation,
@ -307,7 +368,8 @@ int mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, si
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output );
MBEDTLS_MD_INLINABLE_API int mbedtls_md_finish( mbedtls_md_context_t *ctx,
unsigned char *output );
/**
* \brief This function calculates the message-digest of a buffer,
@ -327,8 +389,11 @@ int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output );
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, size_t ilen,
unsigned char *output );
MBEDTLS_MD_INLINABLE_API int mbedtls_md(
mbedtls_md_handle_t md_info,
const unsigned char *input,
size_t ilen,
unsigned char *output );
#if defined(MBEDTLS_FS_IO)
/**
@ -348,7 +413,7 @@ int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, si
* the file pointed by \p path.
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info was NULL.
*/
int mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path,
int mbedtls_md_file( mbedtls_md_handle_t md_info, const char *path,
unsigned char *output );
#endif /* MBEDTLS_FS_IO */
@ -454,12 +519,167 @@ int mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx );
* \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
* failure.
*/
int mbedtls_md_hmac( const mbedtls_md_info_t *md_info, const unsigned char *key, size_t keylen,
int mbedtls_md_hmac( mbedtls_md_handle_t md_info, const unsigned char *key, size_t keylen,
const unsigned char *input, size_t ilen,
unsigned char *output );
/* Internal use */
int mbedtls_md_process( mbedtls_md_context_t *ctx, const unsigned char *data );
MBEDTLS_MD_INLINABLE_API int mbedtls_md_process( mbedtls_md_context_t *ctx,
const unsigned char *data );
/*
* Internal wrapper functions for those MD API functions which should be
* inlined in some but not all configurations. The actual MD API will be
* implemented either here or in md.c, and forward to the wrappers.
*/
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_setup_internal(
mbedtls_md_context_t *ctx, mbedtls_md_handle_t md_info, int hmac )
{
if( md_info == MBEDTLS_MD_INVALID_HANDLE || ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
#if !defined(MBEDTLS_MD_SINGLE_HASH)
ctx->md_ctx = mbedtls_md_info_ctx_alloc( md_info );
if( ctx->md_ctx == NULL )
return( MBEDTLS_ERR_MD_ALLOC_FAILED );
if( hmac != 0 )
{
ctx->hmac_ctx = mbedtls_calloc( 2,
mbedtls_md_info_block_size( md_info ) );
if( ctx->hmac_ctx == NULL )
{
mbedtls_md_info_ctx_free( md_info, ctx->md_ctx);
return( MBEDTLS_ERR_MD_ALLOC_FAILED );
}
}
ctx->md_info = md_info;
#else
((void) hmac);
#endif /* MBEDTLS_MD_SINGLE_HASH */
return( 0 );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_starts_internal(
mbedtls_md_context_t *ctx )
{
mbedtls_md_handle_t md_info;
if( ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
md_info = mbedtls_md_get_handle( ctx );
if( md_info == MBEDTLS_MD_INVALID_HANDLE )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return( mbedtls_md_info_starts( md_info, ctx->md_ctx ) );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_update_internal(
mbedtls_md_context_t *ctx,
const unsigned char *input,
size_t ilen )
{
mbedtls_md_handle_t md_info;
if( ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
md_info = mbedtls_md_get_handle( ctx );
if( md_info == MBEDTLS_MD_INVALID_HANDLE )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return( mbedtls_md_info_update( md_info, ctx->md_ctx,
input, ilen ) );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_finish_internal(
mbedtls_md_context_t *ctx, unsigned char *output )
{
mbedtls_md_handle_t md_info;
if( ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
md_info = mbedtls_md_get_handle( ctx );
if( md_info == MBEDTLS_MD_INVALID_HANDLE )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return( mbedtls_md_info_finish( md_info, ctx->md_ctx,
output ) );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_internal(
mbedtls_md_handle_t md_info,
const unsigned char *input,
size_t ilen,
unsigned char *output )
{
if( md_info == MBEDTLS_MD_INVALID_HANDLE )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return( mbedtls_md_info_digest( md_info, input,
ilen, output) );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_process_internal(
mbedtls_md_context_t *ctx, const unsigned char *data )
{
mbedtls_md_handle_t md_info;
if( ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
md_info = mbedtls_md_get_handle( ctx );
if( md_info == MBEDTLS_MD_INVALID_HANDLE )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return( mbedtls_md_info_process( md_info, ctx->md_ctx, data ) );
}
#if defined(MBEDTLS_MD_SINGLE_HASH)
MBEDTLS_MD_INLINABLE_API int mbedtls_md_setup(
mbedtls_md_context_t *ctx, mbedtls_md_handle_t md_info, int hmac )
{
return( mbedtls_md_setup_internal( ctx, md_info, hmac ) );
}
MBEDTLS_MD_INLINABLE_API int mbedtls_md_starts(
mbedtls_md_context_t *ctx )
{
return( mbedtls_md_starts_internal( ctx ) );
}
MBEDTLS_MD_INLINABLE_API int mbedtls_md_update(
mbedtls_md_context_t *ctx,
const unsigned char *input,
size_t ilen )
{
return( mbedtls_md_update_internal( ctx, input, ilen ) );
}
MBEDTLS_MD_INLINABLE_API int mbedtls_md_finish(
mbedtls_md_context_t *ctx, unsigned char *output )
{
return( mbedtls_md_finish_internal( ctx, output ) );
}
MBEDTLS_MD_INLINABLE_API int mbedtls_md(
mbedtls_md_handle_t md_info,
const unsigned char *input,
size_t ilen,
unsigned char *output )
{
return( mbedtls_md_internal( md_info, input, ilen, output ) );
}
MBEDTLS_MD_INLINABLE_API int mbedtls_md_process(
mbedtls_md_context_t *ctx, const unsigned char *data )
{
return( mbedtls_md_process_internal( ctx, data ) );
}
#endif /* MBEDTLS_MD_SINGLE_HASH */
#ifdef __cplusplus
}

View file

@ -1,14 +1,12 @@
/**
/**
* \file md_internal.h
*
* \brief Message digest wrappers.
*
* \warning This in an internal header. Do not include directly.
* \brief This file contains the generic message-digest wrapper.
*
* \author Adriaan de Jong <dejong@fox-it.com>
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -23,27 +21,157 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_MD_WRAP_H
#define MBEDTLS_MD_WRAP_H
#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#ifndef MBEDTLS_MD_INTERNAL_H
#define MBEDTLS_MD_INTERNAL_H
#if defined(MBEDTLS_MD2_C)
#include "mbedtls/md2.h"
#endif
#include "md.h"
#if defined(MBEDTLS_MD4_C)
#include "mbedtls/md4.h"
#endif
#if defined(MBEDTLS_MD5_C)
#include "mbedtls/md5.h"
#endif
#if defined(MBEDTLS_RIPEMD160_C)
#include "mbedtls/ripemd160.h"
#endif
#if defined(MBEDTLS_SHA1_C)
#include "mbedtls/sha1.h"
#endif
#if defined(MBEDTLS_SHA256_C)
#include "mbedtls/sha256.h"
#endif
#if defined(MBEDTLS_SHA512_C)
#include "mbedtls/sha512.h"
#endif
#include "mbedtls/platform_util.h"
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdlib.h>
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif
#ifdef __cplusplus
extern "C" {
#endif
#define MBEDTLS_MD_WRAPPER MBEDTLS_ALWAYS_INLINE static inline
/*
* Message-digest information macro definition
*/
/* Dummy definition to keep check-names.sh happy - don't uncomment */
//#define MBEDTLS_MD_INFO_SHA256
/* SHA-256 */
static inline void mbedtls_md_sha256_init_free_dummy( void* ctx )
{
/* Zero-initialization can be skipped. */
((void) ctx);
}
#define MBEDTLS_MD_INFO_SHA256_TYPE MBEDTLS_MD_SHA256
#define MBEDTLS_MD_INFO_SHA256_CTX_TYPE mbedtls_sha256_context
#if defined(MBEDTLS_MD_SINGLE_HASH) && !defined(MBEDTLS_SHA256_ALT)
/* mbedtls_md_sha256_init() only zeroizes, which is redundant
* because mbedtls_md_context is zeroized in mbedtls_md_init(),
* and the mbedtls_sha256_context is embedded in mbedtls_md_context_t. */
#define MBEDTLS_MD_INFO_SHA256_INIT_FUNC mbedtls_md_sha256_init_free_dummy
#else
#define MBEDTLS_MD_INFO_SHA256_INIT_FUNC mbedtls_sha256_init
#endif /* MBEDTLS_MD_SINGLE_HASH && !MBEDTLS_SHA256_ALT */
#define MBEDTLS_MD_INFO_SHA256_NAME "SHA256"
#define MBEDTLS_MD_INFO_SHA256_SIZE 32
#define MBEDTLS_MD_INFO_SHA256_BLOCKSIZE 64
#define MBEDTLS_MD_INFO_SHA256_STARTS_FUNC mbedtls_sha256_starts_wrap
#define MBEDTLS_MD_INFO_SHA256_UPDATE_FUNC mbedtls_sha224_update_wrap
#define MBEDTLS_MD_INFO_SHA256_FINISH_FUNC mbedtls_sha224_finish_wrap
#define MBEDTLS_MD_INFO_SHA256_DIGEST_FUNC mbedtls_sha256_wrap
#define MBEDTLS_MD_INFO_SHA256_ALLOC_FUNC mbedtls_sha224_ctx_alloc
#if defined(MBEDTLS_MD_SINGLE_HASH) && !defined(MBEDTLS_SHA256_ALT)
/* mbedtls_md_sha256_free() only zeroizes, which is redundant
* because mbedtls_md_context is zeroized in mbedtls_md_init(),
* and the mbedtls_sha256_context is embedded in mbedtls_md_context_t. */
#define MBEDTLS_MD_INFO_SHA256_FREE_FUNC mbedtls_md_sha256_init_free_dummy
#else
#define MBEDTLS_MD_INFO_SHA256_FREE_FUNC mbedtls_sha224_ctx_free
#endif /* MBEDTLS_MD_SINGLE_HASH && !MBEDTLS_SHA256_ALT */
#define MBEDTLS_MD_INFO_SHA256_CLONE_FUNC mbedtls_sha224_clone_wrap
#define MBEDTLS_MD_INFO_SHA256_PROCESS_FUNC mbedtls_sha224_process_wrap
/*
* Helper macros to extract fields from ciphersuites.
*/
#define MBEDTLS_MD_INFO_CTX_TYPE_T( MD ) MD ## _CTX_TYPE
#define MBEDTLS_MD_INFO_INIT_FUNC_T( MD ) MD ## _INIT_FUNC
#define MBEDTLS_MD_INFO_TYPE_T( MD ) MD ## _TYPE
#define MBEDTLS_MD_INFO_NAME_T( MD ) MD ## _NAME
#define MBEDTLS_MD_INFO_SIZE_T( MD ) MD ## _SIZE
#define MBEDTLS_MD_INFO_BLOCKSIZE_T( MD ) MD ## _BLOCKSIZE
#define MBEDTLS_MD_INFO_STARTS_FUNC_T( MD ) MD ## _STARTS_FUNC
#define MBEDTLS_MD_INFO_UPDATE_FUNC_T( MD ) MD ## _UPDATE_FUNC
#define MBEDTLS_MD_INFO_FINISH_FUNC_T( MD ) MD ## _FINISH_FUNC
#define MBEDTLS_MD_INFO_DIGEST_FUNC_T( MD ) MD ## _DIGEST_FUNC
#define MBEDTLS_MD_INFO_ALLOC_FUNC_T( MD ) MD ## _ALLOC_FUNC
#define MBEDTLS_MD_INFO_FREE_FUNC_T( MD ) MD ## _FREE_FUNC
#define MBEDTLS_MD_INFO_CLONE_FUNC_T( MD ) MD ## _CLONE_FUNC
#define MBEDTLS_MD_INFO_PROCESS_FUNC_T( MD ) MD ## _PROCESS_FUNC
/* Wrapper around MBEDTLS_MD_INFO_{FIELD}_T() which makes sure that
* the argument is macro-expanded before concatenated with the
* field name. This allows to call these macros as
* MBEDTLS_MD_INFO_{FIELD}( MBEDTLS_MD_SINGLE_HASH ).
* where MBEDTLS_MD_SINGLE_HASH expands to MBEDTLS_MD_INFO_{DIGEST}. */
#define MBEDTLS_MD_INFO_CTX_TYPE( MD ) MBEDTLS_MD_INFO_CTX_TYPE_T( MD )
#define MBEDTLS_MD_INFO_INIT_FUNC( MD ) MBEDTLS_MD_INFO_INIT_FUNC_T( MD )
#define MBEDTLS_MD_INFO_TYPE( MD ) MBEDTLS_MD_INFO_TYPE_T( MD )
#define MBEDTLS_MD_INFO_NAME( MD ) MBEDTLS_MD_INFO_NAME_T( MD )
#define MBEDTLS_MD_INFO_SIZE( MD ) MBEDTLS_MD_INFO_SIZE_T( MD )
#define MBEDTLS_MD_INFO_BLOCKSIZE( MD ) MBEDTLS_MD_INFO_BLOCKSIZE_T( MD )
#define MBEDTLS_MD_INFO_STARTS_FUNC( MD ) MBEDTLS_MD_INFO_STARTS_FUNC_T( MD )
#define MBEDTLS_MD_INFO_UPDATE_FUNC( MD ) MBEDTLS_MD_INFO_UPDATE_FUNC_T( MD )
#define MBEDTLS_MD_INFO_FINISH_FUNC( MD ) MBEDTLS_MD_INFO_FINISH_FUNC_T( MD )
#define MBEDTLS_MD_INFO_DIGEST_FUNC( MD ) MBEDTLS_MD_INFO_DIGEST_FUNC_T( MD )
#define MBEDTLS_MD_INFO_ALLOC_FUNC( MD ) MBEDTLS_MD_INFO_ALLOC_FUNC_T( MD )
#define MBEDTLS_MD_INFO_FREE_FUNC( MD ) MBEDTLS_MD_INFO_FREE_FUNC_T( MD )
#define MBEDTLS_MD_INFO_CLONE_FUNC( MD ) MBEDTLS_MD_INFO_CLONE_FUNC_T( MD )
#define MBEDTLS_MD_INFO_PROCESS_FUNC( MD ) MBEDTLS_MD_INFO_PROCESS_FUNC_T( MD )
/**
* Message digest information.
* Allows message digest functions to be called in a generic way.
*/
typedef int mbedtls_md_starts_func_t( void *ctx );
typedef int mbedtls_md_update_func_t( void *ctx,
const unsigned char *input,
size_t ilen );
typedef int mbedtls_md_finish_func_t( void *ctx, unsigned char *output );
typedef int mbedtls_md_digest_func_t( const unsigned char *input,
size_t ilen,
unsigned char *output );
typedef void* mbedtls_md_ctx_alloc_func_t( void );
typedef void mbedtls_md_ctx_free_func_t( void *ctx );
typedef void mbedtls_md_clone_func_t( void *st, const void *src );
typedef int mbedtls_md_process_func_t( void *ctx,
const unsigned char *input );
#if !defined(MBEDTLS_MD_SINGLE_HASH)
struct mbedtls_md_info_t
{
/** Digest identifier */
@ -59,57 +187,672 @@ struct mbedtls_md_info_t
int block_size;
/** Digest initialisation function */
int (*starts_func)( void *ctx );
mbedtls_md_starts_func_t *starts_func;
/** Digest update function */
int (*update_func)( void *ctx, const unsigned char *input, size_t ilen );
mbedtls_md_update_func_t *update_func;
/** Digest finalisation function */
int (*finish_func)( void *ctx, unsigned char *output );
mbedtls_md_finish_func_t *finish_func;
/** Generic digest function */
int (*digest_func)( const unsigned char *input, size_t ilen,
unsigned char *output );
mbedtls_md_digest_func_t *digest_func;
/** Allocate a new context */
void * (*ctx_alloc_func)( void );
mbedtls_md_ctx_alloc_func_t *ctx_alloc_func;
/** Free the given context */
void (*ctx_free_func)( void *ctx );
mbedtls_md_ctx_free_func_t *ctx_free_func;
/** Clone state from a context */
void (*clone_func)( void *dst, const void *src );
mbedtls_md_clone_func_t *clone_func;
/** Internal use only */
int (*process_func)( void *ctx, const unsigned char *input );
mbedtls_md_process_func_t *process_func;
};
/**
* \brief This macro builds an instance of ::mbedtls_md_info_t
* from an \c MBEDTLS_MD_INFO_XXX identifier.
*/
#define MBEDTLS_MD_INFO( MD ) \
{ MBEDTLS_MD_INFO_TYPE( MD ), \
MBEDTLS_MD_INFO_NAME( MD ), \
MBEDTLS_MD_INFO_SIZE( MD ), \
MBEDTLS_MD_INFO_BLOCKSIZE( MD ), \
MBEDTLS_MD_INFO_STARTS_FUNC( MD ), \
MBEDTLS_MD_INFO_UPDATE_FUNC( MD ), \
MBEDTLS_MD_INFO_FINISH_FUNC( MD ), \
MBEDTLS_MD_INFO_DIGEST_FUNC( MD ), \
MBEDTLS_MD_INFO_ALLOC_FUNC( MD ), \
MBEDTLS_MD_INFO_FREE_FUNC( MD ), \
MBEDTLS_MD_INFO_CLONE_FUNC( MD ), \
MBEDTLS_MD_INFO_PROCESS_FUNC( MD ) }
#endif /* !MBEDTLS_MD_SINGLE_HASH */
/*
*
* Definitions of MD information structures for various digests.
*
*/
/*
* MD-2
*/
#if defined(MBEDTLS_MD2_C)
extern const mbedtls_md_info_t mbedtls_md2_info;
#endif
MBEDTLS_MD_WRAPPER int mbedtls_md2_starts_wrap( void *ctx )
{
return( mbedtls_md2_starts_ret( (mbedtls_md2_context *) ctx ) );
}
MBEDTLS_MD_WRAPPER int mbedtls_md2_update_wrap( void *ctx, const unsigned char *input,
size_t ilen )
{
return( mbedtls_md2_update_ret( (mbedtls_md2_context *) ctx, input, ilen ) );
}
MBEDTLS_MD_WRAPPER int mbedtls_md2_finish_wrap( void *ctx, unsigned char *output )
{
return( mbedtls_md2_finish_ret( (mbedtls_md2_context *) ctx, output ) );
}
MBEDTLS_MD_WRAPPER void* mbedtls_md2_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_md2_context ) );
if( ctx != NULL )
mbedtls_md2_init( (mbedtls_md2_context *) ctx );
return( ctx );
}
MBEDTLS_MD_WRAPPER void mbedtls_md2_ctx_free( void *ctx )
{
mbedtls_md2_free( (mbedtls_md2_context *) ctx );
mbedtls_free( ctx );
}
MBEDTLS_MD_WRAPPER void mbedtls_md2_clone_wrap( void *dst, const void *src )
{
mbedtls_md2_clone( (mbedtls_md2_context *) dst,
(const mbedtls_md2_context *) src );
}
MBEDTLS_MD_WRAPPER int mbedtls_md2_process_wrap( void *ctx, const unsigned char *data )
{
((void) data);
return( mbedtls_internal_md2_process( (mbedtls_md2_context *) ctx ) );
}
#endif /* MBEDTLS_MD2_C */
/*
* MD-4
*/
#if defined(MBEDTLS_MD4_C)
extern const mbedtls_md_info_t mbedtls_md4_info;
#endif
MBEDTLS_MD_WRAPPER int mbedtls_md4_starts_wrap( void *ctx )
{
return( mbedtls_md4_starts_ret( (mbedtls_md4_context *) ctx ) );
}
MBEDTLS_MD_WRAPPER int mbedtls_md4_update_wrap( void *ctx, const unsigned char *input,
size_t ilen )
{
return( mbedtls_md4_update_ret( (mbedtls_md4_context *) ctx, input, ilen ) );
}
MBEDTLS_MD_WRAPPER int mbedtls_md4_finish_wrap( void *ctx, unsigned char *output )
{
return( mbedtls_md4_finish_ret( (mbedtls_md4_context *) ctx, output ) );
}
MBEDTLS_MD_WRAPPER void* mbedtls_md4_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_md4_context ) );
if( ctx != NULL )
mbedtls_md4_init( (mbedtls_md4_context *) ctx );
return( ctx );
}
MBEDTLS_MD_WRAPPER void mbedtls_md4_ctx_free( void *ctx )
{
mbedtls_md4_free( (mbedtls_md4_context *) ctx );
mbedtls_free( ctx );
}
MBEDTLS_MD_WRAPPER void mbedtls_md4_clone_wrap( void *dst, const void *src )
{
mbedtls_md4_clone( (mbedtls_md4_context *) dst,
(const mbedtls_md4_context *) src );
}
MBEDTLS_MD_WRAPPER int mbedtls_md4_process_wrap( void *ctx, const unsigned char *data )
{
return( mbedtls_internal_md4_process( (mbedtls_md4_context *) ctx, data ) );
}
#endif /* MBEDTLS_MD4_C */
/*
* MD-5
*/
#if defined(MBEDTLS_MD5_C)
extern const mbedtls_md_info_t mbedtls_md5_info;
#endif
MBEDTLS_MD_WRAPPER int mbedtls_md5_starts_wrap( void *ctx )
{
return( mbedtls_md5_starts_ret( (mbedtls_md5_context *) ctx ) );
}
MBEDTLS_MD_WRAPPER int mbedtls_md5_update_wrap( void *ctx, const unsigned char *input,
size_t ilen )
{
return( mbedtls_md5_update_ret( (mbedtls_md5_context *) ctx, input, ilen ) );
}
MBEDTLS_MD_WRAPPER int mbedtls_md5_finish_wrap( void *ctx, unsigned char *output )
{
return( mbedtls_md5_finish_ret( (mbedtls_md5_context *) ctx, output ) );
}
MBEDTLS_MD_WRAPPER void* mbedtls_md5_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_md5_context ) );
if( ctx != NULL )
mbedtls_md5_init( (mbedtls_md5_context *) ctx );
return( ctx );
}
MBEDTLS_MD_WRAPPER void mbedtls_md5_ctx_free( void *ctx )
{
mbedtls_md5_free( (mbedtls_md5_context *) ctx );
mbedtls_free( ctx );
}
MBEDTLS_MD_WRAPPER void mbedtls_md5_clone_wrap( void *dst, const void *src )
{
mbedtls_md5_clone( (mbedtls_md5_context *) dst,
(const mbedtls_md5_context *) src );
}
MBEDTLS_MD_WRAPPER int mbedtls_md5_process_wrap( void *ctx, const unsigned char *data )
{
return( mbedtls_internal_md5_process( (mbedtls_md5_context *) ctx, data ) );
}
#endif /* MBEDTLS_MD5_C */
/*
* RIPEMD-160
*/
#if defined(MBEDTLS_RIPEMD160_C)
extern const mbedtls_md_info_t mbedtls_ripemd160_info;
#endif
MBEDTLS_MD_WRAPPER int mbedtls_ripemd160_starts_wrap( void *ctx )
{
return( mbedtls_ripemd160_starts_ret( (mbedtls_ripemd160_context *) ctx ) );
}
MBEDTLS_MD_WRAPPER int mbedtls_ripemd160_update_wrap( void *ctx, const unsigned char *input,
size_t ilen )
{
return( mbedtls_ripemd160_update_ret( (mbedtls_ripemd160_context *) ctx,
input, ilen ) );
}
MBEDTLS_MD_WRAPPER int mbedtls_ripemd160_finish_wrap( void *ctx, unsigned char *output )
{
return( mbedtls_ripemd160_finish_ret( (mbedtls_ripemd160_context *) ctx,
output ) );
}
MBEDTLS_MD_WRAPPER void* mbedtls_ripemd160_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_ripemd160_context ) );
if( ctx != NULL )
mbedtls_ripemd160_init( (mbedtls_ripemd160_context *) ctx );
return( ctx );
}
MBEDTLS_MD_WRAPPER void mbedtls_ripemd160_ctx_free( void *ctx )
{
mbedtls_ripemd160_free( (mbedtls_ripemd160_context *) ctx );
mbedtls_free( ctx );
}
MBEDTLS_MD_WRAPPER void mbedtls_ripemd160_clone_wrap( void *dst, const void *src )
{
mbedtls_ripemd160_clone( (mbedtls_ripemd160_context *) dst,
(const mbedtls_ripemd160_context *) src );
}
MBEDTLS_MD_WRAPPER int mbedtls_ripemd160_process_wrap( void *ctx, const unsigned char *data )
{
return( mbedtls_internal_ripemd160_process(
(mbedtls_ripemd160_context *) ctx, data ) );
}
#endif /* MBEDTLS_RIPEMD160_C */
/*
* SHA-1
*/
#if defined(MBEDTLS_SHA1_C)
extern const mbedtls_md_info_t mbedtls_sha1_info;
#endif
MBEDTLS_MD_WRAPPER int mbedtls_sha1_starts_wrap( void *ctx )
{
return( mbedtls_sha1_starts_ret( (mbedtls_sha1_context *) ctx ) );
}
MBEDTLS_MD_WRAPPER int mbedtls_sha1_update_wrap( void *ctx, const unsigned char *input,
size_t ilen )
{
return( mbedtls_sha1_update_ret( (mbedtls_sha1_context *) ctx,
input, ilen ) );
}
MBEDTLS_MD_WRAPPER int mbedtls_sha1_finish_wrap( void *ctx, unsigned char *output )
{
return( mbedtls_sha1_finish_ret( (mbedtls_sha1_context *) ctx, output ) );
}
MBEDTLS_MD_WRAPPER void* mbedtls_sha1_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_sha1_context ) );
if( ctx != NULL )
mbedtls_sha1_init( (mbedtls_sha1_context *) ctx );
return( ctx );
}
MBEDTLS_MD_WRAPPER void mbedtls_sha1_clone_wrap( void *dst, const void *src )
{
mbedtls_sha1_clone( (mbedtls_sha1_context *) dst,
(const mbedtls_sha1_context *) src );
}
MBEDTLS_MD_WRAPPER void mbedtls_sha1_ctx_free( void *ctx )
{
mbedtls_sha1_free( (mbedtls_sha1_context *) ctx );
mbedtls_free( ctx );
}
MBEDTLS_MD_WRAPPER int mbedtls_sha1_process_wrap( void *ctx, const unsigned char *data )
{
return( mbedtls_internal_sha1_process( (mbedtls_sha1_context *) ctx,
data ) );
}
#endif /* MBEDTLS_SHA1_C */
/*
* SHA-224 and SHA-256
*/
#if defined(MBEDTLS_SHA256_C)
extern const mbedtls_md_info_t mbedtls_sha224_info;
extern const mbedtls_md_info_t mbedtls_sha256_info;
#endif
#if !defined(MBEDTLS_SHA256_NO_SHA224)
MBEDTLS_MD_WRAPPER int mbedtls_sha224_starts_wrap( void *ctx )
{
return( mbedtls_sha256_starts_ret( (mbedtls_sha256_context *) ctx, 1 ) );
}
#endif /* !MBEDTLS_SHA256_NO_SHA224 */
MBEDTLS_MD_WRAPPER int mbedtls_sha224_update_wrap( void *ctx, const unsigned char *input,
size_t ilen )
{
return( mbedtls_sha256_update_ret( (mbedtls_sha256_context *) ctx,
input, ilen ) );
}
MBEDTLS_MD_WRAPPER int mbedtls_sha224_finish_wrap( void *ctx, unsigned char *output )
{
return( mbedtls_sha256_finish_ret( (mbedtls_sha256_context *) ctx,
output ) );
}
#if !defined(MBEDTLS_SHA256_NO_SHA224)
MBEDTLS_MD_WRAPPER int mbedtls_sha224_wrap( const unsigned char *input, size_t ilen,
unsigned char *output )
{
return( mbedtls_sha256_ret( input, ilen, output, 1 ) );
}
#endif /* !MBEDTLS_SHA256_NO_SHA224 */
MBEDTLS_MD_WRAPPER void* mbedtls_sha224_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_sha256_context ) );
if( ctx != NULL )
mbedtls_sha256_init( (mbedtls_sha256_context *) ctx );
return( ctx );
}
MBEDTLS_MD_WRAPPER void mbedtls_sha224_ctx_free( void *ctx )
{
mbedtls_sha256_free( (mbedtls_sha256_context *) ctx );
mbedtls_free( ctx );
}
MBEDTLS_MD_WRAPPER void mbedtls_sha224_clone_wrap( void *dst, const void *src )
{
mbedtls_sha256_clone( (mbedtls_sha256_context *) dst,
(const mbedtls_sha256_context *) src );
}
MBEDTLS_MD_WRAPPER int mbedtls_sha224_process_wrap( void *ctx, const unsigned char *data )
{
return( mbedtls_internal_sha256_process( (mbedtls_sha256_context *) ctx,
data ) );
}
MBEDTLS_MD_WRAPPER int mbedtls_sha256_starts_wrap( void *ctx )
{
return( mbedtls_sha256_starts_ret( (mbedtls_sha256_context *) ctx, 0 ) );
}
MBEDTLS_MD_WRAPPER int mbedtls_sha256_wrap( const unsigned char *input, size_t ilen,
unsigned char *output )
{
return( mbedtls_sha256_ret( input, ilen, output, 0 ) );
}
#endif /* MBEDTLS_SHA256_C */
/*
* SHA-384 and SHA-512
*/
#if defined(MBEDTLS_SHA512_C)
extern const mbedtls_md_info_t mbedtls_sha384_info;
extern const mbedtls_md_info_t mbedtls_sha512_info;
#endif
MBEDTLS_MD_WRAPPER int mbedtls_sha384_starts_wrap( void *ctx )
{
return( mbedtls_sha512_starts_ret( (mbedtls_sha512_context *) ctx, 1 ) );
}
MBEDTLS_MD_WRAPPER int mbedtls_sha384_update_wrap( void *ctx, const unsigned char *input,
size_t ilen )
{
return( mbedtls_sha512_update_ret( (mbedtls_sha512_context *) ctx,
input, ilen ) );
}
MBEDTLS_MD_WRAPPER int mbedtls_sha384_finish_wrap( void *ctx, unsigned char *output )
{
return( mbedtls_sha512_finish_ret( (mbedtls_sha512_context *) ctx,
output ) );
}
MBEDTLS_MD_WRAPPER int mbedtls_sha384_wrap( const unsigned char *input, size_t ilen,
unsigned char *output )
{
return( mbedtls_sha512_ret( input, ilen, output, 1 ) );
}
MBEDTLS_MD_WRAPPER void* mbedtls_sha384_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_sha512_context ) );
if( ctx != NULL )
mbedtls_sha512_init( (mbedtls_sha512_context *) ctx );
return( ctx );
}
MBEDTLS_MD_WRAPPER void mbedtls_sha384_ctx_free( void *ctx )
{
mbedtls_sha512_free( (mbedtls_sha512_context *) ctx );
mbedtls_free( ctx );
}
MBEDTLS_MD_WRAPPER void mbedtls_sha384_clone_wrap( void *dst, const void *src )
{
mbedtls_sha512_clone( (mbedtls_sha512_context *) dst,
(const mbedtls_sha512_context *) src );
}
MBEDTLS_MD_WRAPPER int mbedtls_sha384_process_wrap( void *ctx, const unsigned char *data )
{
return( mbedtls_internal_sha512_process( (mbedtls_sha512_context *) ctx,
data ) );
}
MBEDTLS_MD_WRAPPER int mbedtls_sha512_starts_wrap( void *ctx )
{
return( mbedtls_sha512_starts_ret( (mbedtls_sha512_context *) ctx, 0 ) );
}
MBEDTLS_MD_WRAPPER int mbedtls_sha512_wrap( const unsigned char *input, size_t ilen,
unsigned char *output )
{
return( mbedtls_sha512_ret( input, ilen, output, 0 ) );
}
#endif /* MBEDTLS_SHA512_C */
/*
* Getter functions for MD info structure.
*/
#if !defined(MBEDTLS_MD_SINGLE_HASH)
MBEDTLS_ALWAYS_INLINE static inline mbedtls_md_type_t mbedtls_md_info_type(
mbedtls_md_handle_t info )
{
return( info->type );
}
MBEDTLS_ALWAYS_INLINE static inline const char * mbedtls_md_info_name(
mbedtls_md_handle_t info )
{
return( info->name );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_info_size(
mbedtls_md_handle_t info )
{
return( info->size );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_info_block_size(
mbedtls_md_handle_t info )
{
return( info->block_size );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_info_starts(
mbedtls_md_handle_t info,
void *ctx )
{
return( info->starts_func( ctx ) );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_info_update(
mbedtls_md_handle_t info,
void *ctx,
const unsigned char *input,
size_t ilen )
{
return( info->update_func( ctx, input, ilen ) );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_info_finish(
mbedtls_md_handle_t info,
void *ctx,
unsigned char *output )
{
return( info->finish_func( ctx, output ) );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_info_digest(
mbedtls_md_handle_t info,
const unsigned char *input,
size_t ilen,
unsigned char *output )
{
return( info->digest_func( input, ilen, output ) );
}
MBEDTLS_ALWAYS_INLINE static inline void* mbedtls_md_info_ctx_alloc(
mbedtls_md_handle_t info )
{
return( info->ctx_alloc_func() );
}
MBEDTLS_ALWAYS_INLINE static inline void mbedtls_md_info_ctx_free(
mbedtls_md_handle_t info,
void *ctx )
{
info->ctx_free_func( ctx );
}
MBEDTLS_ALWAYS_INLINE static inline void mbedtls_md_info_clone(
mbedtls_md_handle_t info,
void *dst,
const void *src )
{
info->clone_func( dst, src );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_info_process(
mbedtls_md_handle_t info,
void *ctx,
const unsigned char *input )
{
return( info->process_func( ctx, input ) );
}
#else /* !MBEDTLS_MD_SINGLE_HASH */
MBEDTLS_ALWAYS_INLINE static inline mbedtls_md_type_t mbedtls_md_info_type(
mbedtls_md_handle_t info )
{
((void) info);
return( MBEDTLS_MD_INFO_TYPE( MBEDTLS_MD_SINGLE_HASH ) );
}
MBEDTLS_ALWAYS_INLINE static inline const char * mbedtls_md_info_name(
mbedtls_md_handle_t info )
{
((void) info);
return( MBEDTLS_MD_INFO_NAME( MBEDTLS_MD_SINGLE_HASH ) );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_info_size(
mbedtls_md_handle_t info )
{
((void) info);
return( MBEDTLS_MD_INFO_SIZE( MBEDTLS_MD_SINGLE_HASH ) );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_info_block_size(
mbedtls_md_handle_t info )
{
((void) info);
return( MBEDTLS_MD_INFO_BLOCKSIZE( MBEDTLS_MD_SINGLE_HASH ) );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_info_starts(
mbedtls_md_handle_t info,
void *ctx )
{
((void) info);
return( MBEDTLS_MD_INFO_STARTS_FUNC( MBEDTLS_MD_SINGLE_HASH )( ctx ) );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_info_update(
mbedtls_md_handle_t info,
void *ctx,
const unsigned char *input,
size_t ilen )
{
((void) info);
return( MBEDTLS_MD_INFO_UPDATE_FUNC( MBEDTLS_MD_SINGLE_HASH )
( ctx, input, ilen ) );
}
MBEDTLS_ALWAYS_INLINE static inline void mbedtls_md_info_init(
mbedtls_md_handle_t info,
void *ctx )
{
((void) info);
MBEDTLS_MD_INFO_INIT_FUNC( MBEDTLS_MD_SINGLE_HASH )( ctx );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_info_finish(
mbedtls_md_handle_t info,
void *ctx,
unsigned char *output )
{
((void) info);
return( MBEDTLS_MD_INFO_FINISH_FUNC( MBEDTLS_MD_SINGLE_HASH )
( ctx, output ) );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_info_digest(
mbedtls_md_handle_t info,
const unsigned char *input,
size_t ilen,
unsigned char *output )
{
((void) info);
return( MBEDTLS_MD_INFO_DIGEST_FUNC( MBEDTLS_MD_SINGLE_HASH )
( input, ilen, output ) );
}
MBEDTLS_ALWAYS_INLINE static inline void* mbedtls_md_info_ctx_alloc(
mbedtls_md_handle_t info )
{
((void) info);
return( MBEDTLS_MD_INFO_ALLOC_FUNC( MBEDTLS_MD_SINGLE_HASH )() );
}
MBEDTLS_ALWAYS_INLINE static inline void mbedtls_md_info_ctx_free(
mbedtls_md_handle_t info,
void *ctx )
{
((void) info);
MBEDTLS_MD_INFO_FREE_FUNC( MBEDTLS_MD_SINGLE_HASH )( ctx );
}
MBEDTLS_ALWAYS_INLINE static inline void mbedtls_md_info_clone(
mbedtls_md_handle_t info,
void *dst,
const void *src )
{
((void) info);
MBEDTLS_MD_INFO_CLONE_FUNC( MBEDTLS_MD_SINGLE_HASH )( dst, src );
}
MBEDTLS_ALWAYS_INLINE static inline int mbedtls_md_info_process(
mbedtls_md_handle_t info,
void *ctx,
const unsigned char *input )
{
((void) info);
return( MBEDTLS_MD_INFO_PROCESS_FUNC( MBEDTLS_MD_SINGLE_HASH )
( ctx, input ) );
}
#endif /* MBEDTLS_MD_SINGLE_HASH */
#ifdef __cplusplus
}
#endif
#endif /* MBEDTLS_MD_WRAP_H */
#endif /* MBEDTLS_MD_INTERNAL_H */

View file

@ -133,6 +133,7 @@ void mbedtls_nist_kw_free( mbedtls_nist_kw_context *ctx );
*
* \return \c 0 on success.
* \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for invalid input length.
* \return \c MBEDTLS_ERR_PLATFORM_ALLOC_FAILED in case of a memory allocation failure.
* \return cipher-specific error code on failure of the underlying cipher.
*/
int mbedtls_nist_kw_wrap( mbedtls_nist_kw_context *ctx, mbedtls_nist_kw_mode_t mode,

View file

@ -407,8 +407,10 @@ typedef struct mbedtls_oid_descriptor_t
{
const char *asn1; /*!< OID ASN.1 representation */
size_t asn1_len; /*!< length of asn1 */
#if !defined(MBEDTLS_X509_REMOVE_INFO)
const char *name; /*!< official name (e.g. from RFC) */
const char *description; /*!< human friendly description */
#endif
} mbedtls_oid_descriptor_t;
/**
@ -469,6 +471,18 @@ int mbedtls_oid_get_pk_alg( const mbedtls_asn1_buf *oid, mbedtls_pk_type_t *pk_a
int mbedtls_oid_get_oid_by_pk_alg( mbedtls_pk_type_t pk_alg,
const char **oid, size_t *olen );
#if defined(MBEDTLS_USE_TINYCRYPT)
typedef enum
{
MBEDTLS_UECC_DP_NONE = 0, /*!< Curve not defined. */
MBEDTLS_UECC_DP_SECP256R1, /*!< Domain parameters for the 256-bit curve defined by FIPS 186-4 and SEC1. */
} mbedtls_uecc_group_id;
int mbedtls_oid_get_ec_grp( const mbedtls_asn1_buf *oid, mbedtls_uecc_group_id *grp_id );
int mbedtls_oid_get_oid_by_ec_grp( mbedtls_uecc_group_id grp_id,
const char **oid, size_t *olen);
#else
#if defined(MBEDTLS_ECP_C)
/**
* \brief Translate NamedCurve OID into an EC group identifier
@ -492,6 +506,7 @@ int mbedtls_oid_get_ec_grp( const mbedtls_asn1_buf *oid, mbedtls_ecp_group_id *g
int mbedtls_oid_get_oid_by_ec_grp( mbedtls_ecp_group_id grp_id,
const char **oid, size_t *olen );
#endif /* MBEDTLS_ECP_C */
#endif
#if defined(MBEDTLS_MD_C)
/**
@ -550,6 +565,7 @@ int mbedtls_oid_get_md_alg( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_a
int mbedtls_oid_get_md_hmac( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_hmac );
#endif /* MBEDTLS_MD_C */
#if !defined(MBEDTLS_X509_REMOVE_INFO)
/**
* \brief Translate Extended Key Usage OID into description
*
@ -559,6 +575,7 @@ int mbedtls_oid_get_md_hmac( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_
* \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
*/
int mbedtls_oid_get_extended_key_usage( const mbedtls_asn1_buf *oid, const char **desc );
#endif
/**
* \brief Translate md_type into hash algorithm OID

View file

@ -45,6 +45,14 @@
#include "ecdsa.h"
#endif
#if defined(MBEDTLS_USE_TINYCRYPT)
#include "tinycrypt/ecc.h"
#endif
#if defined(MBEDTLS_PK_SINGLE_TYPE)
#include "pk_internal.h"
#endif
#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
!defined(inline) && !defined(__cplusplus)
#define inline __inline
@ -122,15 +130,39 @@ typedef struct mbedtls_pk_debug_item
/**
* \brief Public key information and operations
*/
#if defined(MBEDTLS_PK_SINGLE_TYPE)
typedef enum {
MBEDTLS_PK_INVALID_HANDLE,
MBEDTLS_PK_UNIQUE_VALID_HANDLE,
} mbedtls_pk_handle_t;
#else /* MBEDTLS_PK_SINGLE_TYPE */
typedef struct mbedtls_pk_info_t mbedtls_pk_info_t;
typedef const mbedtls_pk_info_t *mbedtls_pk_handle_t;
#define MBEDTLS_PK_INVALID_HANDLE ( (mbedtls_pk_handle_t) NULL )
#endif /* MBEDTLS_PK_SINGLE_TYPE */
#if defined(MBEDTLS_USE_TINYCRYPT)
typedef struct
{
uint8_t private_key[NUM_ECC_BYTES];
uint8_t public_key[2*NUM_ECC_BYTES];
} mbedtls_uecc_keypair;
#endif
/**
* \brief Public key container
*/
typedef struct mbedtls_pk_context
{
const mbedtls_pk_info_t * pk_info; /**< Public key information */
#if defined(MBEDTLS_PK_SINGLE_TYPE)
/* This is an array to make access to it more uniform with the case where
* it's a pointer to void - either way it needs casting before use. */
unsigned char pk_ctx[sizeof(
MBEDTLS_PK_INFO_CONTEXT( MBEDTLS_PK_SINGLE_TYPE ) )];
#else
mbedtls_pk_handle_t pk_info; /**< Public key information */
void * pk_ctx; /**< Underlying public key context */
#endif
} mbedtls_pk_context;
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
@ -139,7 +171,7 @@ typedef struct mbedtls_pk_context
*/
typedef struct
{
const mbedtls_pk_info_t * pk_info; /**< Public key information */
mbedtls_pk_handle_t pk_info; /**< Public key information */
void * rs_ctx; /**< Underlying restart context */
} mbedtls_pk_restart_ctx;
#else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
@ -160,6 +192,20 @@ static inline mbedtls_rsa_context *mbedtls_pk_rsa( const mbedtls_pk_context pk )
}
#endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_USE_TINYCRYPT)
#if !defined(MBEDTLS_PK_SINGLE_TYPE)
static inline mbedtls_uecc_keypair *mbedtls_pk_uecc( const mbedtls_pk_context pk )
{
return( (mbedtls_uecc_keypair *) (pk).pk_ctx );
}
#else
/* Go with a macro in order to avoid making a copy of the struct (the argument
* is not a pointer so it's passed by value) and then returning an address
* inside that copy, which would be undefined behaviour. */
#define mbedtls_pk_uecc( pk ) ( (mbedtls_uecc_keypair *) (pk).pk_ctx )
#endif
#endif /* MBEDTLS_USE_TINYCRYPT */
#if defined(MBEDTLS_ECP_C)
/**
* Quick access to an EC context inside a PK context.
@ -194,7 +240,7 @@ typedef size_t (*mbedtls_pk_rsa_alt_key_len_func)( void *ctx );
*
* \return The PK info associated with the type or NULL if not found.
*/
const mbedtls_pk_info_t *mbedtls_pk_info_from_type( mbedtls_pk_type_t pk_type );
mbedtls_pk_handle_t mbedtls_pk_info_from_type( mbedtls_pk_type_t pk_type );
/**
* \brief Initialize a #mbedtls_pk_context (as NONE).
@ -245,7 +291,7 @@ void mbedtls_pk_restart_free( mbedtls_pk_restart_ctx *ctx );
* \note For contexts holding an RSA-alt key, use
* \c mbedtls_pk_setup_rsa_alt() instead.
*/
int mbedtls_pk_setup( mbedtls_pk_context *ctx, const mbedtls_pk_info_t *info );
int mbedtls_pk_setup( mbedtls_pk_context *ctx, mbedtls_pk_handle_t info );
#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
/**

View file

@ -33,6 +33,90 @@
#include "pk.h"
/*
* PK information macro definitions
*/
/*
* Each PK type that can be used with MBEDTLS_PK_SINGLE_TYPE needs to have
* the following MBEDTLS_PK_INFO_{FIELD} definitions, plus a dummy one for the
* base name. For now, only ECKEY with MBEDTLS_USE_TINYCRYPT is defined.
*
* For optional functions that are omitted, we need both the _FUNC field
* defined to NULL, and an extra macro _OMIT defined to 1.
*/
#if defined(MBEDTLS_USE_TINYCRYPT)
/* Dummy definition to keep check-names.sh happy - don't uncomment */
//#define MBEDTLS_PK_INFO_ECKEY
#define MBEDTLS_PK_INFO_ECKEY_CONTEXT mbedtls_uecc_keypair
#define MBEDTLS_PK_INFO_ECKEY_TYPE MBEDTLS_PK_ECKEY
#define MBEDTLS_PK_INFO_ECKEY_NAME "EC"
#define MBEDTLS_PK_INFO_ECKEY_GET_BITLEN uecc_eckey_get_bitlen
#define MBEDTLS_PK_INFO_ECKEY_CAN_DO uecc_eckey_can_do
#define MBEDTLS_PK_INFO_ECKEY_VERIFY_FUNC uecc_eckey_verify_wrap
#define MBEDTLS_PK_INFO_ECKEY_SIGN_FUNC uecc_eckey_sign_wrap
#define MBEDTLS_PK_INFO_ECKEY_DECRYPT_FUNC NULL
#define MBEDTLS_PK_INFO_ECKEY_DECRYPT_OMIT 1
#define MBEDTLS_PK_INFO_ECKEY_ENCRYPT_FUNC NULL
#define MBEDTLS_PK_INFO_ECKEY_ENCRYPT_OMIT 1
#define MBEDTLS_PK_INFO_ECKEY_CHECK_PAIR_FUNC uecc_eckey_check_pair
#define MBEDTLS_PK_INFO_ECKEY_CTX_ALLOC_FUNC uecc_eckey_alloc_wrap
#define MBEDTLS_PK_INFO_ECKEY_CTX_FREE_FUNC uecc_eckey_free_wrap
#define MBEDTLS_PK_INFO_ECKEY_DEBUG_FUNC NULL
#define MBEDTLS_PK_INFO_ECKEY_DEBUG_OMIT 1
#endif /* MBEDTLS_USE_TINYCRYPT */
/*
* Helper macros to extract fields from PK types
*/
#define MBEDTLS_PK_INFO_CONTEXT_T( PK ) PK ## _CONTEXT
#define MBEDTLS_PK_INFO_TYPE_T( PK ) PK ## _TYPE
#define MBEDTLS_PK_INFO_NAME_T( PK ) PK ## _NAME
#define MBEDTLS_PK_INFO_GET_BITLEN_T( PK ) PK ## _GET_BITLEN
#define MBEDTLS_PK_INFO_CAN_DO_T( PK ) PK ## _CAN_DO
#define MBEDTLS_PK_INFO_VERIFY_FUNC_T( PK ) PK ## _VERIFY_FUNC
#define MBEDTLS_PK_INFO_VERIFY_OMIT_T( PK ) PK ## _VERIFY_OMIT
#define MBEDTLS_PK_INFO_SIGN_FUNC_T( PK ) PK ## _SIGN_FUNC
#define MBEDTLS_PK_INFO_SIGN_OMIT_T( PK ) PK ## _SIGN_OMIT
#define MBEDTLS_PK_INFO_DECRYPT_FUNC_T( PK ) PK ## _DECRYPT_FUNC
#define MBEDTLS_PK_INFO_DECRYPT_OMIT_T( PK ) PK ## _DECRYPT_OMIT
#define MBEDTLS_PK_INFO_ENCRYPT_FUNC_T( PK ) PK ## _ENCRYPT_FUNC
#define MBEDTLS_PK_INFO_ENCRYPT_OMIT_T( PK ) PK ## _ENCRYPT_OMIT
#define MBEDTLS_PK_INFO_CHECK_PAIR_FUNC_T( PK ) PK ## _CHECK_PAIR_FUNC
#define MBEDTLS_PK_INFO_CHECK_PAIR_OMIT_T( PK ) PK ## _CHECK_PAIR_OMIT
#define MBEDTLS_PK_INFO_CTX_ALLOC_FUNC_T( PK ) PK ## _CTX_ALLOC_FUNC
#define MBEDTLS_PK_INFO_CTX_FREE_FUNC_T( PK ) PK ## _CTX_FREE_FUNC
#define MBEDTLS_PK_INFO_DEBUG_FUNC_T( PK ) PK ## _DEBUG_FUNC
#define MBEDTLS_PK_INFO_DEBUG_OMIT_T( PK ) PK ## _DEBUG_OMIT
/* Wrappers around MBEDTLS_PK_INFO_{FIELD}_T() which makes sure that
* the argument is macro-expanded before concatenated with the
* field name. This allows to call these macros as
* MBEDTLS_PK_INFO_{FIELD}( MBEDTLS_PK_SINGLE_TYPE ).
* where MBEDTLS_PK_SINGLE_TYPE expands to MBEDTLS_PK_INFO_{TYPE}. */
#define MBEDTLS_PK_INFO_CONTEXT( PK ) MBEDTLS_PK_INFO_CONTEXT_T( PK )
#define MBEDTLS_PK_INFO_TYPE( PK ) MBEDTLS_PK_INFO_TYPE_T( PK )
#define MBEDTLS_PK_INFO_NAME( PK ) MBEDTLS_PK_INFO_NAME_T( PK )
#define MBEDTLS_PK_INFO_GET_BITLEN( PK ) MBEDTLS_PK_INFO_GET_BITLEN_T( PK )
#define MBEDTLS_PK_INFO_CAN_DO( PK ) MBEDTLS_PK_INFO_CAN_DO_T( PK )
#define MBEDTLS_PK_INFO_VERIFY_FUNC( PK ) MBEDTLS_PK_INFO_VERIFY_FUNC_T( PK )
#define MBEDTLS_PK_INFO_VERIFY_OMIT( PK ) MBEDTLS_PK_INFO_VERIFY_OMIT_T( PK )
#define MBEDTLS_PK_INFO_SIGN_FUNC( PK ) MBEDTLS_PK_INFO_SIGN_FUNC_T( PK )
#define MBEDTLS_PK_INFO_SIGN_OMIT( PK ) MBEDTLS_PK_INFO_SIGN_OMIT_T( PK )
#define MBEDTLS_PK_INFO_DECRYPT_FUNC( PK ) MBEDTLS_PK_INFO_DECRYPT_FUNC_T( PK )
#define MBEDTLS_PK_INFO_DECRYPT_OMIT( PK ) MBEDTLS_PK_INFO_DECRYPT_OMIT_T( PK )
#define MBEDTLS_PK_INFO_ENCRYPT_FUNC( PK ) MBEDTLS_PK_INFO_ENCRYPT_FUNC_T( PK )
#define MBEDTLS_PK_INFO_ENCRYPT_OMIT( PK ) MBEDTLS_PK_INFO_ENCRYPT_OMIT_T( PK )
#define MBEDTLS_PK_INFO_CHECK_PAIR_FUNC( PK ) MBEDTLS_PK_INFO_CHECK_PAIR_FUNC_T( PK )
#define MBEDTLS_PK_INFO_CHECK_PAIR_OMIT( PK ) MBEDTLS_PK_INFO_CHECK_PAIR_OMIT_T( PK )
#define MBEDTLS_PK_INFO_CTX_ALLOC_FUNC( PK ) MBEDTLS_PK_INFO_CTX_ALLOC_FUNC_T( PK )
#define MBEDTLS_PK_INFO_CTX_FREE_FUNC( PK ) MBEDTLS_PK_INFO_CTX_FREE_FUNC_T( PK )
#define MBEDTLS_PK_INFO_DEBUG_FUNC( PK ) MBEDTLS_PK_INFO_DEBUG_FUNC_T( PK )
#define MBEDTLS_PK_INFO_DEBUG_OMIT( PK ) MBEDTLS_PK_INFO_DEBUG_OMIT_T( PK )
#if !defined(MBEDTLS_PK_SINGLE_TYPE)
struct mbedtls_pk_info_t
{
/** Public key type */
@ -41,18 +125,19 @@ struct mbedtls_pk_info_t
/** Type name */
const char *name;
/** Get key size in bits */
/** Get key size in bits (must be valid)*/
size_t (*get_bitlen)( const void * );
/** Tell if the context implements this type (e.g. ECKEY can do ECDSA) */
/** Tell if the context implements this type (e.g. ECKEY can do ECDSA)
* (must be valid) */
int (*can_do)( mbedtls_pk_type_t type );
/** Verify signature */
/** Verify signature (may be NULL) */
int (*verify_func)( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len );
/** Make signature */
/** Make signature (may be NULL)*/
int (*sign_func)( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t *sig_len,
@ -60,13 +145,13 @@ struct mbedtls_pk_info_t
void *p_rng );
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
/** Verify signature (restartable) */
/** Verify signature (restartable) (may be NULL) */
int (*verify_rs_func)( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
const unsigned char *sig, size_t sig_len,
void *rs_ctx );
/** Make signature (restartable) */
/** Make signature (restartable) (may be NULL) */
int (*sign_rs_func)( void *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hash_len,
unsigned char *sig, size_t *sig_len,
@ -74,39 +159,94 @@ struct mbedtls_pk_info_t
void *p_rng, void *rs_ctx );
#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
/** Decrypt message */
/** Decrypt message (may be NULL) */
int (*decrypt_func)( void *ctx, const unsigned char *input, size_t ilen,
unsigned char *output, size_t *olen, size_t osize,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
/** Encrypt message */
/** Encrypt message (may be NULL ) */
int (*encrypt_func)( void *ctx, const unsigned char *input, size_t ilen,
unsigned char *output, size_t *olen, size_t osize,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
/** Check public-private key pair */
/** Check public-private key pair (may be NULL) */
int (*check_pair_func)( const void *pub, const void *prv );
/** Allocate a new context */
/** Allocate a new context (must be valid) */
void * (*ctx_alloc_func)( void );
/** Free the given context */
/** Free the given context (must be valid) */
void (*ctx_free_func)( void *ctx );
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
/** Allocate the restart context */
/** Allocate the restart context (may be NULL)*/
void * (*rs_alloc_func)( void );
/** Free the restart context */
/** Free the restart context (may be NULL) */
void (*rs_free_func)( void *rs_ctx );
#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
/** Interface with the debug module */
/** Interface with the debug module (may be NULL) */
void (*debug_func)( const void *ctx, mbedtls_pk_debug_item *items );
};
/**
* \brief This macro builds an instance of ::mbedtls_pk_info_t
* from an \c MBEDTLS_PK_INFO_{TYPE} identifier.
*/
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
#define MBEDTLS_PK_INFO( PK ) \
{ \
MBEDTLS_PK_INFO_TYPE( PK ), \
MBEDTLS_PK_INFO_NAME( PK ), \
MBEDTLS_PK_INFO_GET_BITLEN( PK ), \
MBEDTLS_PK_INFO_CAN_DO( PK ), \
MBEDTLS_PK_INFO_VERIFY_FUNC( PK ), \
MBEDTLS_PK_INFO_SIGN_FUNC( PK ), \
NULL, \
NULL, \
MBEDTLS_PK_INFO_DECRYPT_FUNC( PK ), \
MBEDTLS_PK_INFO_ENCRYPT_FUNC( PK ), \
MBEDTLS_PK_INFO_CHECK_PAIR_FUNC( PK ), \
MBEDTLS_PK_INFO_CTX_ALLOC_FUNC( PK ), \
MBEDTLS_PK_INFO_CTX_FREE_FUNC( PK ), \
NULL, \
NULL, \
MBEDTLS_PK_INFO_DEBUG_FUNC( PK ), \
}
#else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
#define MBEDTLS_PK_INFO( PK ) \
{ \
MBEDTLS_PK_INFO_TYPE( PK ), \
MBEDTLS_PK_INFO_NAME( PK ), \
MBEDTLS_PK_INFO_GET_BITLEN( PK ), \
MBEDTLS_PK_INFO_CAN_DO( PK ), \
MBEDTLS_PK_INFO_VERIFY_FUNC( PK ), \
MBEDTLS_PK_INFO_SIGN_FUNC( PK ), \
MBEDTLS_PK_INFO_DECRYPT_FUNC( PK ), \
MBEDTLS_PK_INFO_ENCRYPT_FUNC( PK ), \
MBEDTLS_PK_INFO_CHECK_PAIR_FUNC( PK ), \
MBEDTLS_PK_INFO_CTX_ALLOC_FUNC( PK ), \
MBEDTLS_PK_INFO_CTX_FREE_FUNC( PK ), \
MBEDTLS_PK_INFO_DEBUG_FUNC( PK ), \
}
#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
#endif /* MBEDTLS_PK_SINGLE_TYPE */
/*
* Macros to access pk_info
*/
#if defined(MBEDTLS_PK_SINGLE_TYPE)
#define MBEDTLS_PK_CTX_INFO( ctx ) MBEDTLS_PK_UNIQUE_VALID_HANDLE
#else
#define MBEDTLS_PK_CTX_INFO( ctx ) ( (ctx)->pk_info )
#endif
#define MBEDTLS_PK_CTX_IS_VALID( ctx ) \
( MBEDTLS_PK_CTX_INFO( (ctx) ) != MBEDTLS_PK_INVALID_HANDLE )
#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
/* Container for RSA-alt */
typedef struct
@ -118,6 +258,7 @@ typedef struct
} mbedtls_rsa_alt_context;
#endif
#if !defined(MBEDTLS_PK_SINGLE_TYPE)
#if defined(MBEDTLS_RSA_C)
extern const mbedtls_pk_info_t mbedtls_rsa_info;
#endif
@ -131,8 +272,13 @@ extern const mbedtls_pk_info_t mbedtls_eckeydh_info;
extern const mbedtls_pk_info_t mbedtls_ecdsa_info;
#endif
#if defined(MBEDTLS_USE_TINYCRYPT)
extern const mbedtls_pk_info_t mbedtls_uecc_eckey_info;
#endif
#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
extern const mbedtls_pk_info_t mbedtls_rsa_alt_info;
#endif
#endif /* MBEDTLS_PK_SINGLE_TYPE */
#endif /* MBEDTLS_PK_WRAP_H */

View file

@ -39,13 +39,17 @@
#include MBEDTLS_CONFIG_FILE
#endif
#define MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED -0x0070 /**< Hardware accelerator failed */
#define MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED -0x0072 /**< The requested feature is not supported by the platform */
#define MBEDTLS_ERR_PLATFORM_FAULT_DETECTED -0x0071 /**< A hardware fault was detected in a critical path. As a security precaution this should be treated as a potential physical attack */
#define MBEDTLS_ERR_PLATFORM_ALLOC_FAILED -0x0076 /**< Memory allocation failed */
#if defined(MBEDTLS_PLATFORM_C)
#if defined(MBEDTLS_HAVE_TIME)
#include "platform_time.h"
#endif
#define MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED -0x0070 /**< Hardware accelerator failed */
#define MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED -0x0072 /**< The requested feature is not supported by the platform */
#ifdef __cplusplus
extern "C" {
#endif
@ -364,4 +368,6 @@ void mbedtls_platform_teardown( mbedtls_platform_context *ctx );
}
#endif
#endif /* MBEDTLS_PLATFORM_C */
#endif /* platform.h */

View file

@ -30,7 +30,7 @@
#else
#include MBEDTLS_CONFIG_FILE
#endif
#include <stdint.h>
#include <stddef.h>
#if defined(MBEDTLS_HAVE_TIME_DATE)
#include "platform_time.h"
@ -113,6 +113,12 @@ void mbedtls_param_failed( const char *failure_condition,
#endif /* MBEDTLS_CHECK_PARAMS */
#if defined(__GNUC__) || defined(__arm__)
#define MBEDTLS_ALWAYS_INLINE __attribute__((always_inline))
#else
#define MBEDTLS_ALWAYS_INLINE
#endif
/* Internal helper macros for deprecating API constants. */
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
@ -158,6 +164,110 @@ MBEDTLS_DEPRECATED typedef int mbedtls_deprecated_numeric_constant_t;
*/
void mbedtls_platform_zeroize( void *buf, size_t len );
/**
* \brief Secure memset
*
* This is a constant-time version of memset(). If
* MBEDTLS_ENTROPY_HARDWARE_ALT is defined, the buffer is
* initialised with random data and the order is also
* randomised using the hardware RNG in order to further harden
* against side-channel attacks.
*
* \param ptr Buffer to be set.
* \param value Value to be used when setting the buffer.
* \param num The length of the buffer in bytes.
*
* \return The value of \p ptr.
*/
void *mbedtls_platform_memset( void *ptr, int value, size_t num );
/**
* \brief Secure memcpy
*
* This is a constant-time version of memcpy(). If
* MBEDTLS_ENTROPY_HARDWARE_ALT is defined, the buffer is
* initialised with random data and the order is also
* randomised using the hardware RNG in order to further harden
* against side-channel attacks.
*
* \param dst Destination buffer where the data is being copied to.
* \param src Source buffer where the data is being copied from.
* \param num The length of the buffers in bytes.
*
* \return The value of \p dst.
*/
void *mbedtls_platform_memcpy( void *dst, const void *src, size_t num );
/**
* \brief Secure memmove
*
* This is a constant-time version of memmove(). It is based on
* the double use of the mbedtls_platform_memcpy() function secured
* against side-channel attacks.
*
* \param dst Destination buffer where the data is being moved to.
* \param src Source buffer where the data is being moved from.
* \param num The length of the buffers in bytes.
*
* \return 0 if the operation was successful
* \return #MBEDTLS_ERR_PLATFORM_ALLOC_FAILED if a memory allocation failed
*/
int mbedtls_platform_memmove( void *dst, const void *src, size_t num );
/**
* \brief Secure memcmp
*
* This is a constant-time version of memcmp(). If
* MBEDTLS_ENTROPY_HARDWARE_ALT is defined, the order is also
* randomised using the hardware RNG in order to further harden
* against side-channel attacks.
*
* \param buf1 First buffer to compare.
* \param buf2 Second buffer to compare against.
* \param num The length of the buffers in bytes.
*
* \return 0 if the buffers were equal or an unspecified non-zero value
* otherwise.
*/
int mbedtls_platform_memcmp( const void *buf1, const void *buf2, size_t num );
/**
* \brief RNG-function for getting a random in given range.
*
* This function is meant to provide a global RNG to be used
* throughout Mbed TLS for hardening the library. It is used
* for generating a random delay, random data or random offset
* for utility functions. It is not meant to be a
* cryptographically secure RNG, but provide an RNG for utility
* functions.
*
* \note Currently the function is dependent of hardware providing an
* rng with MBEDTLS_ENTROPY_HARDWARE_ALT. By default, 0 is
* returned.
*
* \note If the given range is [0, 0), 0 is returned.
*
* \param num Max-value for the generated random number, exclusive.
* The generated number will be on range [0, num).
*
* \return The generated random number.
*/
uint32_t mbedtls_platform_random_in_range( size_t num );
/**
* \brief Random delay function.
*
* Function implements a random delay by incrementing a local
* variable randomized number of times (busy-looping).
*
* Duration of the delay is random as number of variable increments
* is randomized.
*
* \note Currently the function is dependent of hardware providing an
* rng with MBEDTLS_ENTROPY_HARDWARE_ALT.
*/
void mbedtls_platform_random_delay( void );
#if defined(MBEDTLS_HAVE_TIME_DATE)
/**
* \brief Platform-specific implementation of gmtime_r()
@ -189,6 +299,82 @@ struct tm *mbedtls_platform_gmtime_r( const mbedtls_time_t *tt,
struct tm *tm_buf );
#endif /* MBEDTLS_HAVE_TIME_DATE */
/**
* \brief Convert a 32-bit number to the big endian format and write it to
* the given buffer.
*
* \param buf Address where the converted number is written.
* \param num A number that needs to be converted to the big endian format.
*
* \return Address to the end of buffer where the converted number is
* written.
*/
unsigned char* mbedtls_platform_put_uint32_be( unsigned char *buf,
size_t num );
/**
* \brief Convert a 24-bit number to the big endian format and write it to
* the given buffer.
*
* \param buf Address where the converted number is written.
* \param num A number that needs to be converted to the big endian format.
*
* \return Address to the end of buffer where the converted number is
* written.
*/
unsigned char* mbedtls_platform_put_uint24_be( unsigned char *buf,
size_t num );
/**
* \brief Convert a 16-bit number to the big endian format and write it to
* the given buffer.
*
*
* \param buf Address where the converted number is written.
* \param num A number that needs to be converted to the big endian format.
*
* \return Address to the end of buffer where the converted number is
* written.
*/
unsigned char* mbedtls_platform_put_uint16_be( unsigned char *buf,
size_t num );
/**
* \brief Convert a 32-bit number from the big endian format.
*
* The function reads a 32-bit number from the given buffer in the
* big endian format and returns it to the caller.
*
* \param buf Buffer where the 32-bit number locates.
*
* \return Converted number.
*/
size_t mbedtls_platform_get_uint32_be( const unsigned char *buf );
/**
* \brief Convert a 24-bit number from the big endian format.
*
* The function reads a 14-bit number from the given buffer in the
* big endian format and returns it to the caller.
*
* \param buf Buffer where the 24-bit number locates.
*
* \return Converted number.
*/
size_t mbedtls_platform_get_uint24_be( const unsigned char *buf );
/**
* \brief Convert a 16-bit number from the big endian format.
*
* The function reads a 16-bit number from the given buffer in the
* big endian format and returns it to the caller.
*
* \param buf Buffer where the 16-bit number locates.
*
* \return Converted number.
*/
size_t mbedtls_platform_get_uint16_be( const unsigned char *buf );
#ifdef __cplusplus
}
#endif

View file

@ -60,8 +60,10 @@ typedef struct mbedtls_sha256_context
uint32_t total[2]; /*!< The number of Bytes processed. */
uint32_t state[8]; /*!< The intermediate digest state. */
unsigned char buffer[64]; /*!< The data block being processed. */
#if !defined(MBEDTLS_SHA256_NO_SHA224)
int is224; /*!< Determines which function to use:
0: Use SHA-256, or 1: Use SHA-224. */
#endif
}
mbedtls_sha256_context;
@ -101,6 +103,7 @@ void mbedtls_sha256_clone( mbedtls_sha256_context *dst,
* \param ctx The context to use. This must be initialized.
* \param is224 This determines which function to use. This must be
* either \c 0 for SHA-256, or \c 1 for SHA-224.
* If #MBEDTLS_SHA256_NO_SHA224 is defined, this must be \c 0.
*
* \return \c 0 on success.
* \return A negative error code on failure.
@ -169,6 +172,7 @@ int mbedtls_internal_sha256_process( mbedtls_sha256_context *ctx,
* \param ctx The context to use. This must be initialized.
* \param is224 Determines which function to use. This must be
* either \c 0 for SHA-256, or \c 1 for SHA-224.
* If #MBEDTLS_SHA256_NO_SHA224 is defined, this must be \c 0.
*/
MBEDTLS_DEPRECATED void mbedtls_sha256_starts( mbedtls_sha256_context *ctx,
int is224 );
@ -237,6 +241,7 @@ MBEDTLS_DEPRECATED void mbedtls_sha256_process( mbedtls_sha256_context *ctx,
* be a writable buffer of length \c 32 Bytes.
* \param is224 Determines which function to use. This must be
* either \c 0 for SHA-256, or \c 1 for SHA-224.
* If #MBEDTLS_SHA256_NO_SHA224 is defined, this must be \c 0.
*/
int mbedtls_sha256_ret( const unsigned char *input,
size_t ilen,
@ -269,6 +274,7 @@ int mbedtls_sha256_ret( const unsigned char *input,
* a writable buffer of length \c 32 Bytes.
* \param is224 Determines which function to use. This must be either
* \c 0 for SHA-256, or \c 1 for SHA-224.
* If #MBEDTLS_SHA256_NO_SHA224 is defined, this must be \c 0.
*/
MBEDTLS_DEPRECATED void mbedtls_sha256( const unsigned char *input,
size_t ilen,

File diff suppressed because it is too large Load diff

View file

@ -70,7 +70,8 @@ struct mbedtls_ssl_cache_entry
mbedtls_time_t timestamp; /*!< entry timestamp */
#endif
mbedtls_ssl_session session; /*!< entry session */
#if defined(MBEDTLS_X509_CRT_PARSE_C)
#if defined(MBEDTLS_X509_CRT_PARSE_C) && \
defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
mbedtls_x509_buf peer_cert; /*!< entry peer_cert */
#endif
mbedtls_ssl_cache_entry *next; /*!< chain pointer */

View file

@ -33,6 +33,8 @@
#include "pk.h"
#include "cipher.h"
#include "md.h"
#include "ssl.h"
#include <string.h>
#ifdef __cplusplus
extern "C" {
@ -304,79 +306,6 @@ typedef enum {
MBEDTLS_KEY_EXCHANGE_ECJPAKE,
} mbedtls_key_exchange_type_t;
/* Key exchanges using a certificate */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
#define MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED
#endif
/* Key exchanges allowing client certificate requests */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
#define MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED
#endif
/* Key exchanges involving server signature in ServerKeyExchange */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
#define MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED
#endif
/* Key exchanges using ECDH */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
#define MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED
#endif
/* Key exchanges that don't involve ephemeral keys */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED)
#define MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED
#endif
/* Key exchanges that involve ephemeral keys */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
#define MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED
#endif
/* Key exchanges using a PSK */
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
#define MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
#endif
/* Key exchanges using DHE */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
#define MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED
#endif
/* Key exchanges using ECDHE */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
#define MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED
#endif
typedef struct mbedtls_ssl_ciphersuite_t mbedtls_ssl_ciphersuite_t;
#define MBEDTLS_CIPHERSUITE_WEAK 0x01 /**< Weak ciphersuite flag */
@ -384,6 +313,61 @@ typedef struct mbedtls_ssl_ciphersuite_t mbedtls_ssl_ciphersuite_t;
eg for CCM_8 */
#define MBEDTLS_CIPHERSUITE_NODTLS 0x04 /**< Can't be used with DTLS */
/*
* Ciphersuite macro definitions
*
* This is highly incomplete and only contains those ciphersuites for
* which we need to be able to build the library with support for that
* ciphersuite only (currently MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8
* as an example).
*/
#define MBEDTLS_SUITE_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8_ID MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
#define MBEDTLS_SUITE_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8_NAME "TLS-ECDHE-ECDSA-WITH-AES-128-CCM-8"
#define MBEDTLS_SUITE_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8_CIPHER MBEDTLS_CIPHER_AES_128_CCM
#define MBEDTLS_SUITE_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8_MAC MBEDTLS_MD_SHA256
#define MBEDTLS_SUITE_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8_KEY_EXCHANGE MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA
#define MBEDTLS_SUITE_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8_MIN_MAJOR_VER MBEDTLS_SSL_MAJOR_VERSION_3
#define MBEDTLS_SUITE_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8_MIN_MINOR_VER MBEDTLS_SSL_MINOR_VERSION_3
#define MBEDTLS_SUITE_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8_MAX_MAJOR_VER MBEDTLS_SSL_MAJOR_VERSION_3
#define MBEDTLS_SUITE_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8_MAX_MINOR_VER MBEDTLS_SSL_MINOR_VERSION_3
#define MBEDTLS_SUITE_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8_FLAGS MBEDTLS_CIPHERSUITE_SHORT_TAG
/* This is just to make check-names.sh happy -- don't uncomment. */
//#define MBEDTLS_SUITE_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
/*
* Helper macros to extract fields from ciphersuites.
*/
#define MBEDTLS_SSL_SUITE_ID_T( SUITE ) SUITE ## _ID
#define MBEDTLS_SSL_SUITE_NAME_T( SUITE ) SUITE ## _NAME
#define MBEDTLS_SSL_SUITE_CIPHER_T( SUITE ) SUITE ## _CIPHER
#define MBEDTLS_SSL_SUITE_MAC_T( SUITE ) SUITE ## _MAC
#define MBEDTLS_SSL_SUITE_KEY_EXCHANGE_T( SUITE ) SUITE ## _KEY_EXCHANGE
#define MBEDTLS_SSL_SUITE_MIN_MAJOR_VER_T( SUITE ) SUITE ## _MIN_MAJOR_VER
#define MBEDTLS_SSL_SUITE_MIN_MINOR_VER_T( SUITE ) SUITE ## _MIN_MINOR_VER
#define MBEDTLS_SSL_SUITE_MAX_MAJOR_VER_T( SUITE ) SUITE ## _MAX_MAJOR_VER
#define MBEDTLS_SSL_SUITE_MAX_MINOR_VER_T( SUITE ) SUITE ## _MAX_MINOR_VER
#define MBEDTLS_SSL_SUITE_FLAGS_T( SUITE ) SUITE ## _FLAGS
/* Wrapper around MBEDTLS_SSL_SUITE_XXX_T() which makes sure that
* the argument is macro-expanded before concatenated with the
* field name. This allows to call these macros as
* MBEDTLS_SSL_SUITE_XXX( MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE ),
* where MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE expands to MBEDTLS_SSL_SUITE_XXX. */
#define MBEDTLS_SSL_SUITE_ID( SUITE ) MBEDTLS_SSL_SUITE_ID_T( SUITE )
#define MBEDTLS_SSL_SUITE_NAME( SUITE ) MBEDTLS_SSL_SUITE_NAME_T( SUITE )
#define MBEDTLS_SSL_SUITE_CIPHER( SUITE ) MBEDTLS_SSL_SUITE_CIPHER_T( SUITE )
#define MBEDTLS_SSL_SUITE_MAC( SUITE ) MBEDTLS_SSL_SUITE_MAC_T( SUITE )
#define MBEDTLS_SSL_SUITE_KEY_EXCHANGE( SUITE ) MBEDTLS_SSL_SUITE_KEY_EXCHANGE_T( SUITE )
#define MBEDTLS_SSL_SUITE_MIN_MAJOR_VER( SUITE ) MBEDTLS_SSL_SUITE_MIN_MAJOR_VER_T( SUITE )
#define MBEDTLS_SSL_SUITE_MIN_MINOR_VER( SUITE ) MBEDTLS_SSL_SUITE_MIN_MINOR_VER_T( SUITE )
#define MBEDTLS_SSL_SUITE_MAX_MAJOR_VER( SUITE ) MBEDTLS_SSL_SUITE_MAX_MAJOR_VER_T( SUITE )
#define MBEDTLS_SSL_SUITE_MAX_MINOR_VER( SUITE ) MBEDTLS_SSL_SUITE_MAX_MINOR_VER_T( SUITE )
#define MBEDTLS_SSL_SUITE_FLAGS( SUITE ) MBEDTLS_SSL_SUITE_FLAGS_T( SUITE )
#if !defined(MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE)
/**
* \brief This structure is used for storing ciphersuite information
*/
@ -404,23 +388,386 @@ struct mbedtls_ssl_ciphersuite_t
unsigned char flags;
};
typedef mbedtls_ssl_ciphersuite_t const * mbedtls_ssl_ciphersuite_handle_t;
#define MBEDTLS_SSL_CIPHERSUITE_INVALID_HANDLE ( (mbedtls_ssl_ciphersuite_handle_t) NULL )
/**
* \brief This macro builds an instance of ::mbedtls_ssl_ciphersuite_t
* from an \c MBEDTLS_SUITE_XXX identifier.
*/
#define MBEDTLS_SSL_SUITE_INFO( SUITE ) \
{ MBEDTLS_SSL_SUITE_ID( SUITE ), \
MBEDTLS_SSL_SUITE_NAME( SUITE ), \
MBEDTLS_SSL_SUITE_CIPHER( SUITE ), \
MBEDTLS_SSL_SUITE_MAC( SUITE ), \
MBEDTLS_SSL_SUITE_KEY_EXCHANGE( SUITE ), \
MBEDTLS_SSL_SUITE_MIN_MAJOR_VER( SUITE ), \
MBEDTLS_SSL_SUITE_MIN_MINOR_VER( SUITE ), \
MBEDTLS_SSL_SUITE_MAX_MAJOR_VER( SUITE ), \
MBEDTLS_SSL_SUITE_MAX_MINOR_VER( SUITE ), \
MBEDTLS_SSL_SUITE_FLAGS( SUITE ) }
#else /* !MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE */
typedef unsigned char mbedtls_ssl_ciphersuite_handle_t;
#define MBEDTLS_SSL_CIPHERSUITE_INVALID_HANDLE ( (mbedtls_ssl_ciphersuite_handle_t) 0 )
#define MBEDTLS_SSL_CIPHERSUITE_UNIQUE_VALID_HANDLE ( (mbedtls_ssl_ciphersuite_handle_t) 1 )
#endif /* MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE */
#if !defined(MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE)
static inline int mbedtls_ssl_session_get_ciphersuite(
mbedtls_ssl_session const * session )
{
return( session->ciphersuite );
}
#else /* !MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE */
static inline int mbedtls_ssl_session_get_ciphersuite(
mbedtls_ssl_session const * session )
{
((void) session);
return( MBEDTLS_SSL_SUITE_ID( MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE ) );
}
#endif /* MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE */
/*
* Getter functions for the extraction of ciphersuite attributes
* from a ciphersuite handle.
*
* Warning: These functions have the validity of the handle as a precondition!
* Their behaviour is undefined when MBEDTLS_SSL_CIPHERSUITE_INVALID_HANDLE
* is passed.
*/
#if !defined(MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE)
/*
* Implementation of getter functions when the ciphersuite handle
* is a pointer to the ciphersuite information structure.
*
* The precondition that the handle is valid means that
* we don't need to check that info != NULL.
*/
static inline int mbedtls_ssl_suite_get_id(
mbedtls_ssl_ciphersuite_handle_t const info )
{
return( info->id );
}
static inline const char* mbedtls_ssl_suite_get_name(
mbedtls_ssl_ciphersuite_handle_t const info )
{
return( info->name );
}
static inline mbedtls_cipher_type_t mbedtls_ssl_suite_get_cipher(
mbedtls_ssl_ciphersuite_handle_t const info )
{
return( info->cipher );
}
static inline mbedtls_md_type_t mbedtls_ssl_suite_get_mac(
mbedtls_ssl_ciphersuite_handle_t const info )
{
return( info->mac );
}
static inline mbedtls_key_exchange_type_t mbedtls_ssl_suite_get_key_exchange(
mbedtls_ssl_ciphersuite_handle_t const info )
{
return( info->key_exchange );
}
static inline int mbedtls_ssl_suite_get_min_major_ver(
mbedtls_ssl_ciphersuite_handle_t const info )
{
return( info->min_major_ver );
}
static inline int mbedtls_ssl_suite_get_min_minor_ver(
mbedtls_ssl_ciphersuite_handle_t const info )
{
return( info->min_minor_ver );
}
static inline int mbedtls_ssl_suite_get_max_major_ver(
mbedtls_ssl_ciphersuite_handle_t const info )
{
return( info->max_major_ver );
}
static inline int mbedtls_ssl_suite_get_max_minor_ver(
mbedtls_ssl_ciphersuite_handle_t const info )
{
return( info->max_minor_ver );
}
static inline unsigned char mbedtls_ssl_suite_get_flags(
mbedtls_ssl_ciphersuite_handle_t const info )
{
return( info->flags );
}
#else /* !MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE */
/*
* Implementations of getter functions in the case of only a single possible
* ciphersuite. In this case, the handle is logically a boolean (either the
* invalid handle or the unique valid handle representing the single enabled
* ciphersuite), and the precondition that the handle is valid means that we
* can statically return the hardcoded attribute of the enabled ciphersuite.
*/
static inline int mbedtls_ssl_suite_get_id(
mbedtls_ssl_ciphersuite_handle_t const info )
{
((void) info);
return( MBEDTLS_SSL_SUITE_ID( MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE ) );
}
static inline const char* mbedtls_ssl_suite_get_name(
mbedtls_ssl_ciphersuite_handle_t const info )
{
((void) info);
return( MBEDTLS_SSL_SUITE_NAME( MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE ) );
}
static inline mbedtls_cipher_type_t mbedtls_ssl_suite_get_cipher(
mbedtls_ssl_ciphersuite_handle_t const info )
{
((void) info);
return( MBEDTLS_SSL_SUITE_CIPHER( MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE ) );
}
static inline mbedtls_md_type_t mbedtls_ssl_suite_get_mac(
mbedtls_ssl_ciphersuite_handle_t const info )
{
((void) info);
return( MBEDTLS_SSL_SUITE_MAC( MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE ) );
}
static inline mbedtls_key_exchange_type_t mbedtls_ssl_suite_get_key_exchange(
mbedtls_ssl_ciphersuite_handle_t const info )
{
((void) info);
return( MBEDTLS_SSL_SUITE_KEY_EXCHANGE( MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE ) );
}
static inline int mbedtls_ssl_suite_get_min_major_ver(
mbedtls_ssl_ciphersuite_handle_t const info )
{
((void) info);
return( MBEDTLS_SSL_SUITE_MIN_MAJOR_VER( MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE ) );
}
static inline int mbedtls_ssl_suite_get_min_minor_ver(
mbedtls_ssl_ciphersuite_handle_t const info )
{
((void) info);
return( MBEDTLS_SSL_SUITE_MIN_MINOR_VER( MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE ) );
}
static inline int mbedtls_ssl_suite_get_max_major_ver(
mbedtls_ssl_ciphersuite_handle_t const info )
{
((void) info);
return( MBEDTLS_SSL_SUITE_MAX_MAJOR_VER( MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE ) );
}
static inline int mbedtls_ssl_suite_get_max_minor_ver(
mbedtls_ssl_ciphersuite_handle_t const info )
{
((void) info);
return( MBEDTLS_SSL_SUITE_MAX_MINOR_VER( MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE ) );
}
static inline unsigned char mbedtls_ssl_suite_get_flags(
mbedtls_ssl_ciphersuite_handle_t const info )
{
((void) info);
return( MBEDTLS_SSL_SUITE_FLAGS( MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE ) );
}
#endif /* MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE */
const int *mbedtls_ssl_list_ciphersuites( void );
const mbedtls_ssl_ciphersuite_t *mbedtls_ssl_ciphersuite_from_string( const char *ciphersuite_name );
const mbedtls_ssl_ciphersuite_t *mbedtls_ssl_ciphersuite_from_id( int ciphersuite_id );
/*
* Various small helper functions for ciphersuites.
*
* Like the getter functions, they assume that the provided ciphersuite
* handle is valid, and hence can be optimized in case there's only one
* ciphersuite enabled.
*
* To avoid code-duplication between inline and non-inline implementations
* of this, we define internal static inline versions of all functions first,
* and define wrappers around these either here or in ssl_ciphersuites.c,
* depending on whether MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE is defined.
*/
#if defined(MBEDTLS_PK_C)
mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_pk_alg( const mbedtls_ssl_ciphersuite_t *info );
mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_alg( const mbedtls_ssl_ciphersuite_t *info );
#endif
int mbedtls_ssl_ciphersuite_uses_ec( const mbedtls_ssl_ciphersuite_t *info );
int mbedtls_ssl_ciphersuite_uses_psk( const mbedtls_ssl_ciphersuite_t *info );
#if defined(MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED)
static inline int mbedtls_ssl_ciphersuite_has_pfs( const mbedtls_ssl_ciphersuite_t *info )
static inline mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_pk_alg_internal(
mbedtls_ssl_ciphersuite_handle_t info )
{
switch( info->key_exchange )
switch( mbedtls_ssl_suite_get_key_exchange( info ) )
{
case MBEDTLS_KEY_EXCHANGE_RSA:
case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
return( MBEDTLS_PK_RSA );
case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
return( MBEDTLS_PK_ECDSA );
case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
return( MBEDTLS_PK_ECKEY );
default:
return( MBEDTLS_PK_NONE );
}
}
static inline mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_alg_internal(
mbedtls_ssl_ciphersuite_handle_t info )
{
switch( mbedtls_ssl_suite_get_key_exchange( info ) )
{
case MBEDTLS_KEY_EXCHANGE_RSA:
case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
return( MBEDTLS_PK_RSA );
case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
return( MBEDTLS_PK_ECDSA );
default:
return( MBEDTLS_PK_NONE );
}
}
#endif /* MBEDTLS_PK_C */
#if defined(MBEDTLS_USE_TINYCRYPT) || \
defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static inline int mbedtls_ssl_ciphersuite_uses_ec_internal(
mbedtls_ssl_ciphersuite_handle_t info )
{
switch( mbedtls_ssl_suite_get_key_exchange( info ) )
{
case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
return( 1 );
default:
return( 0 );
}
}
#endif /* MBEDTLS_USE_TINYCRYPT ||
MBEDTLS_ECDH_C ||
MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
static inline int mbedtls_ssl_ciphersuite_uses_psk_internal(
mbedtls_ssl_ciphersuite_handle_t info )
{
switch( mbedtls_ssl_suite_get_key_exchange( info ) )
{
case MBEDTLS_KEY_EXCHANGE_PSK:
case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
return( 1 );
default:
return( 0 );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
/*
* Wrappers around internal helper functions to be used by the rest of
* the library, either defined static inline here or in ssl_ciphersuites.c.
*/
#if !defined(MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE)
mbedtls_ssl_ciphersuite_handle_t mbedtls_ssl_ciphersuite_from_string(
const char *ciphersuite_name );
mbedtls_ssl_ciphersuite_handle_t mbedtls_ssl_ciphersuite_from_id(
int ciphersuite_id );
#if defined(MBEDTLS_PK_C)
mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_pk_alg(
mbedtls_ssl_ciphersuite_handle_t info );
mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_alg(
mbedtls_ssl_ciphersuite_handle_t info );
#endif /* MBEDTLS_PK_C */
#if defined(MBEDTLS_USE_TINYCRYPT) || \
defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
int mbedtls_ssl_ciphersuite_uses_ec( mbedtls_ssl_ciphersuite_handle_t info );
#endif /* MBEDTLS_USE_TINYCRYPT ||
MBEDTLS_ECDH_C ||
MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
int mbedtls_ssl_ciphersuite_uses_psk( mbedtls_ssl_ciphersuite_handle_t info );
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#else /* !MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE */
#if defined(MBEDTLS_PK_C)
static inline mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_pk_alg(
mbedtls_ssl_ciphersuite_handle_t info )
{
return( mbedtls_ssl_get_ciphersuite_sig_pk_alg_internal( info ) );
}
static inline mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_alg(
mbedtls_ssl_ciphersuite_handle_t info )
{
return( mbedtls_ssl_get_ciphersuite_sig_alg_internal( info ) );
}
#endif /* MBEDTLS_PK_C */
#if defined(MBEDTLS_USE_TINYCRYPT) || \
defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static inline int mbedtls_ssl_ciphersuite_uses_ec(
mbedtls_ssl_ciphersuite_handle_t info )
{
return( mbedtls_ssl_ciphersuite_uses_ec_internal( info ) );
}
#endif /* MBEDTLS_USE_TINYCRYPT ||
MBEDTLS_ECDH_C ||
MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
static inline int mbedtls_ssl_ciphersuite_uses_psk(
mbedtls_ssl_ciphersuite_handle_t info )
{
return( mbedtls_ssl_ciphersuite_uses_psk_internal( info ) );
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
static inline mbedtls_ssl_ciphersuite_handle_t mbedtls_ssl_ciphersuite_from_id(
int ciphersuite )
{
static const int single_suite_id =
MBEDTLS_SSL_SUITE_ID( MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE );
if( ciphersuite == single_suite_id )
return( MBEDTLS_SSL_CIPHERSUITE_UNIQUE_VALID_HANDLE );
return( MBEDTLS_SSL_CIPHERSUITE_INVALID_HANDLE );
}
static inline mbedtls_ssl_ciphersuite_handle_t mbedtls_ssl_ciphersuite_from_string(
const char *ciphersuite_name )
{
static const char * const single_suite_name =
MBEDTLS_SSL_SUITE_NAME( MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE );
if( strcmp( ciphersuite_name, single_suite_name ) == 0 )
return( MBEDTLS_SSL_CIPHERSUITE_UNIQUE_VALID_HANDLE );
return( MBEDTLS_SSL_CIPHERSUITE_INVALID_HANDLE );
}
#endif /* MBEDTLS_SSL_CONF_SINGLE_CIPHERSUITE */
static inline int mbedtls_ssl_ciphersuite_has_pfs(
mbedtls_ssl_ciphersuite_handle_t info )
{
switch( mbedtls_ssl_suite_get_key_exchange( info ) )
{
case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
@ -434,12 +781,11 @@ static inline int mbedtls_ssl_ciphersuite_has_pfs( const mbedtls_ssl_ciphersuite
return( 0 );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED)
static inline int mbedtls_ssl_ciphersuite_no_pfs( const mbedtls_ssl_ciphersuite_t *info )
static inline int mbedtls_ssl_ciphersuite_no_pfs(
mbedtls_ssl_ciphersuite_handle_t info )
{
switch( info->key_exchange )
switch( mbedtls_ssl_suite_get_key_exchange( info ) )
{
case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
@ -452,12 +798,12 @@ static inline int mbedtls_ssl_ciphersuite_no_pfs( const mbedtls_ssl_ciphersuite_
return( 0 );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED)
static inline int mbedtls_ssl_ciphersuite_uses_ecdh( const mbedtls_ssl_ciphersuite_t *info )
static inline int mbedtls_ssl_ciphersuite_uses_ecdh(
mbedtls_ssl_ciphersuite_handle_t info )
{
switch( info->key_exchange )
switch( mbedtls_ssl_suite_get_key_exchange( info ) )
{
case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
@ -467,11 +813,11 @@ static inline int mbedtls_ssl_ciphersuite_uses_ecdh( const mbedtls_ssl_ciphersui
return( 0 );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED */
static inline int mbedtls_ssl_ciphersuite_cert_req_allowed( const mbedtls_ssl_ciphersuite_t *info )
static inline int mbedtls_ssl_ciphersuite_cert_req_allowed(
mbedtls_ssl_ciphersuite_handle_t info )
{
switch( info->key_exchange )
switch( mbedtls_ssl_suite_get_key_exchange( info ) )
{
case MBEDTLS_KEY_EXCHANGE_RSA:
case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
@ -486,10 +832,29 @@ static inline int mbedtls_ssl_ciphersuite_cert_req_allowed( const mbedtls_ssl_ci
}
}
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED)
static inline int mbedtls_ssl_ciphersuite_uses_dhe( const mbedtls_ssl_ciphersuite_t *info )
static inline int mbedtls_ssl_ciphersuite_uses_srv_cert(
mbedtls_ssl_ciphersuite_handle_t info )
{
switch( info->key_exchange )
switch( mbedtls_ssl_suite_get_key_exchange( info ) )
{
case MBEDTLS_KEY_EXCHANGE_RSA:
case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
return( 1 );
default:
return( 0 );
}
}
static inline int mbedtls_ssl_ciphersuite_uses_dhe(
mbedtls_ssl_ciphersuite_handle_t info )
{
switch( mbedtls_ssl_suite_get_key_exchange( info ) )
{
case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
@ -499,12 +864,11 @@ static inline int mbedtls_ssl_ciphersuite_uses_dhe( const mbedtls_ssl_ciphersuit
return( 0 );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED) */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED)
static inline int mbedtls_ssl_ciphersuite_uses_ecdhe( const mbedtls_ssl_ciphersuite_t *info )
static inline int mbedtls_ssl_ciphersuite_uses_ecdhe(
mbedtls_ssl_ciphersuite_handle_t info )
{
switch( info->key_exchange )
switch( mbedtls_ssl_suite_get_key_exchange( info ) )
{
case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
@ -515,12 +879,11 @@ static inline int mbedtls_ssl_ciphersuite_uses_ecdhe( const mbedtls_ssl_ciphersu
return( 0 );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED) */
#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
static inline int mbedtls_ssl_ciphersuite_uses_server_signature( const mbedtls_ssl_ciphersuite_t *info )
static inline int mbedtls_ssl_ciphersuite_uses_server_signature(
mbedtls_ssl_ciphersuite_handle_t info )
{
switch( info->key_exchange )
switch( mbedtls_ssl_suite_get_key_exchange( info ) )
{
case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
@ -531,7 +894,6 @@ static inline int mbedtls_ssl_ciphersuite_uses_server_signature( const mbedtls_s
return( 0 );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
#ifdef __cplusplus
}

File diff suppressed because it is too large Load diff

View file

@ -63,15 +63,15 @@ mbedtls_ssl_ticket_key;
*/
typedef struct mbedtls_ssl_ticket_context
{
mbedtls_ssl_ticket_key keys[2]; /*!< ticket protection keys */
unsigned char active; /*!< index of the currently active key */
uint32_t ticket_lifetime; /*!< lifetime of tickets in seconds */
/** Callback for getting (pseudo-)random numbers */
int (*f_rng)(void *, unsigned char *, size_t);
void *p_rng; /*!< context for the RNG function */
mbedtls_ssl_ticket_key keys[2]; /*!< ticket protection keys */
#if defined(MBEDTLS_THREADING_C)
mbedtls_threading_mutex_t mutex;
#endif

View file

@ -40,16 +40,16 @@
*/
#define MBEDTLS_VERSION_MAJOR 2
#define MBEDTLS_VERSION_MINOR 16
#define MBEDTLS_VERSION_PATCH 3
#define MBEDTLS_VERSION_PATCH 6
/**
* The single version number has the following structure:
* MMNNPP00
* Major version | Minor version | Patch version
*/
#define MBEDTLS_VERSION_NUMBER 0x02100300
#define MBEDTLS_VERSION_STRING "2.16.3"
#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.16.3"
#define MBEDTLS_VERSION_NUMBER 0x02100600
#define MBEDTLS_VERSION_STRING "2.16.6"
#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.16.6"
#if defined(MBEDTLS_VERSION_C)

View file

@ -85,6 +85,8 @@
* \{
*/
/* Reminder: update x509_crt_verify_strings[] in library/x509_crt.c */
/* Reminder: update X509_BADCERT_FI_EXTRA in library/x509_crt.c if using more
* that 24 bits */
#define MBEDTLS_X509_BADCERT_EXPIRED 0x01 /**< The certificate validity has expired. */
#define MBEDTLS_X509_BADCERT_REVOKED 0x02 /**< The certificate has been revoked (is on a CRL). */
#define MBEDTLS_X509_BADCERT_CN_MISMATCH 0x04 /**< The certificate Common Name (CN) does not match with the expected CN. */
@ -183,6 +185,15 @@ extern "C" {
* \{
*/
/**
* Basic length-value buffer structure
*/
typedef struct mbedtls_x509_buf_raw
{
unsigned char *p; /*!< The address of the first byte in the buffer. */
size_t len; /*!< The number of Bytes in the buffer. */
} mbedtls_x509_buf_raw;
/**
* Type-length-value structure that allows for ASN1 using DER.
*/
@ -241,6 +252,7 @@ int mbedtls_x509_dn_gets( char *buf, size_t size, const mbedtls_x509_name *dn );
*/
int mbedtls_x509_serial_gets( char *buf, size_t size, const mbedtls_x509_buf *serial );
#if defined(MBEDTLS_HAVE_TIME_DATE)
/**
* \brief Check a given mbedtls_x509_time against the system time
* and tell if it's in the past.
@ -268,6 +280,44 @@ int mbedtls_x509_time_is_past( const mbedtls_x509_time *to );
* 0 otherwise.
*/
int mbedtls_x509_time_is_future( const mbedtls_x509_time *from );
#endif /* MBEDTLS_HAVE_TIME_DATE */
/**
* \brief Free a dynamic linked list presentation of an X.509 name
* as returned e.g. by mbedtls_x509_crt_get_subject().
*
* \param name The address of the first name component. This may
* be \c NULL, in which case this functions returns
* immediately.
*/
void mbedtls_x509_name_free( mbedtls_x509_name *name );
/**
* \brief Free a dynamic linked list presentation of an X.509 sequence
* as returned e.g. by mbedtls_x509_crt_get_subject_alt_name().
*
* \param seq The address of the first sequence component. This may
* be \c NULL, in which case this functions returns
* immediately.
*/
static inline void mbedtls_x509_sequence_free( mbedtls_x509_sequence *seq )
{
mbedtls_asn1_sequence_free( (mbedtls_asn1_sequence*) seq );
}
#if !defined(MBEDTLS_HAVE_TIME_DATE)
static inline int mbedtls_x509_time_is_past( const mbedtls_x509_time *to )
{
((void) to);
return( 0 );
}
static inline int mbedtls_x509_time_is_future( const mbedtls_x509_time *from )
{
((void) from);
return( 0 );
}
#endif /* !MBEDTLS_HAVE_TIME_DATE */
#if defined(MBEDTLS_SELF_TEST)
@ -280,47 +330,6 @@ int mbedtls_x509_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
/*
* Internal module functions. You probably do not want to use these unless you
* know you do.
*/
int mbedtls_x509_get_name( unsigned char **p, const unsigned char *end,
mbedtls_x509_name *cur );
int mbedtls_x509_get_alg_null( unsigned char **p, const unsigned char *end,
mbedtls_x509_buf *alg );
int mbedtls_x509_get_alg( unsigned char **p, const unsigned char *end,
mbedtls_x509_buf *alg, mbedtls_x509_buf *params );
#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
int mbedtls_x509_get_rsassa_pss_params( const mbedtls_x509_buf *params,
mbedtls_md_type_t *md_alg, mbedtls_md_type_t *mgf_md,
int *salt_len );
#endif
int mbedtls_x509_get_sig( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *sig );
int mbedtls_x509_get_sig_alg( const mbedtls_x509_buf *sig_oid, const mbedtls_x509_buf *sig_params,
mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg,
void **sig_opts );
int mbedtls_x509_get_time( unsigned char **p, const unsigned char *end,
mbedtls_x509_time *t );
int mbedtls_x509_get_serial( unsigned char **p, const unsigned char *end,
mbedtls_x509_buf *serial );
int mbedtls_x509_get_ext( unsigned char **p, const unsigned char *end,
mbedtls_x509_buf *ext, int tag );
int mbedtls_x509_sig_alg_gets( char *buf, size_t size, const mbedtls_x509_buf *sig_oid,
mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg,
const void *sig_opts );
int mbedtls_x509_key_size_helper( char *buf, size_t buf_size, const char *name );
int mbedtls_x509_string_to_names( mbedtls_asn1_named_data **head, const char *name );
int mbedtls_x509_set_extension( mbedtls_asn1_named_data **head, const char *oid, size_t oid_len,
int critical, const unsigned char *val,
size_t val_len );
int mbedtls_x509_write_extensions( unsigned char **p, unsigned char *start,
mbedtls_asn1_named_data *first );
int mbedtls_x509_write_names( unsigned char **p, unsigned char *start,
mbedtls_asn1_named_data *first );
int mbedtls_x509_write_sig( unsigned char **p, unsigned char *start,
const char *oid, size_t oid_len,
unsigned char *sig, size_t size );
#define MBEDTLS_X509_SAFE_SNPRINTF \
do { \
if( ret < 0 || (size_t) ret >= n ) \
@ -330,6 +339,18 @@ int mbedtls_x509_write_sig( unsigned char **p, unsigned char *start,
p += (size_t) ret; \
} while( 0 )
#define MBEDTLS_X509_SAFE_SNPRINTF_WITH_CLEANUP \
do { \
if( ret < 0 || (size_t) ret >= n ) \
{ \
ret = MBEDTLS_ERR_X509_BUFFER_TOO_SMALL; \
goto cleanup; \
} \
\
n -= (size_t) ret; \
p += (size_t) ret; \
} while( 0 )
#ifdef __cplusplus
}
#endif

View file

@ -69,13 +69,21 @@ mbedtls_x509_crl_entry;
*/
typedef struct mbedtls_x509_crl
{
mbedtls_md_type_t sig_md; /**< Internal representation of the MD algorithm of the signature algorithm, e.g. MBEDTLS_MD_SHA256 */
mbedtls_pk_type_t sig_pk; /**< Internal representation of the Public Key algorithm of the signature algorithm, e.g. MBEDTLS_PK_RSA */
int version; /**< CRL version (1=v1, 2=v2) */
void *sig_opts; /**< Signature options to be passed to mbedtls_pk_verify_ext(), e.g. for RSASSA-PSS */
struct mbedtls_x509_crl *next;
mbedtls_x509_buf_raw issuer_raw; /**< The raw issuer data (DER). */
mbedtls_x509_buf raw; /**< The raw certificate data (DER). */
mbedtls_x509_buf tbs; /**< The raw certificate body (DER). The part that is To Be Signed. */
int version; /**< CRL version (1=v1, 2=v2) */
mbedtls_x509_buf sig_oid; /**< CRL signature type identifier */
mbedtls_x509_buf issuer_raw; /**< The raw issuer data (DER). */
mbedtls_x509_buf sig_oid; /**< CRL signature type identifier */
mbedtls_x509_name issuer; /**< The parsed issuer data (named information object). */
@ -88,11 +96,6 @@ typedef struct mbedtls_x509_crl
mbedtls_x509_buf sig_oid2;
mbedtls_x509_buf sig;
mbedtls_md_type_t sig_md; /**< Internal representation of the MD algorithm of the signature algorithm, e.g. MBEDTLS_MD_SHA256 */
mbedtls_pk_type_t sig_pk; /**< Internal representation of the Public Key algorithm of the signature algorithm, e.g. MBEDTLS_PK_RSA */
void *sig_opts; /**< Signature options to be passed to mbedtls_pk_verify_ext(), e.g. for RSASSA-PSS */
struct mbedtls_x509_crl *next;
}
mbedtls_x509_crl;
@ -136,6 +139,7 @@ int mbedtls_x509_crl_parse( mbedtls_x509_crl *chain, const unsigned char *buf, s
int mbedtls_x509_crl_parse_file( mbedtls_x509_crl *chain, const char *path );
#endif /* MBEDTLS_FS_IO */
#if !defined(MBEDTLS_X509_REMOVE_INFO)
/**
* \brief Returns an informational string about the CRL.
*
@ -149,6 +153,7 @@ int mbedtls_x509_crl_parse_file( mbedtls_x509_crl *chain, const char *path );
*/
int mbedtls_x509_crl_info( char *buf, size_t size, const char *prefix,
const mbedtls_x509_crl *crl );
#endif /* !MBEDTLS_X509_REMOVE_INFO */
/**
* \brief Initialize a CRL (chain)

View file

@ -47,12 +47,90 @@ extern "C" {
* \{
*/
typedef struct mbedtls_x509_crt_cache
{
#if !defined(MBEDTLS_X509_ALWAYS_FLUSH) || \
defined(MBEDTLS_THREADING_C)
uint32_t frame_readers;
uint32_t pk_readers;
#endif /* !MBEDTLS_X509_ALWAYS_FLUSH || MBEDTLS_THREADING_C */
#if defined(MBEDTLS_THREADING_C)
mbedtls_threading_mutex_t frame_mutex;
mbedtls_threading_mutex_t pk_mutex;
#endif
mbedtls_x509_buf_raw pk_raw;
struct mbedtls_x509_crt_frame *frame;
struct mbedtls_pk_context *pk;
} mbedtls_x509_crt_cache;
typedef struct mbedtls_x509_crt_frame
{
/* Keep these 8-bit fields at the front of the structure to allow them to
* be fetched in a single instruction on Thumb2; putting them at the back
* requires an intermediate address calculation. */
uint8_t version; /**< The X.509 version. (1=v1, 2=v2, 3=v3) */
uint8_t ca_istrue; /**< Optional Basic Constraint extension value:
* 1 if this certificate belongs to a CA, 0 otherwise. */
uint8_t max_pathlen; /**< Optional Basic Constraint extension value:
* The maximum path length to the root certificate.
* Path length is 1 higher than RFC 5280 'meaning', so 1+ */
uint8_t ns_cert_type; /**< Optional Netscape certificate type extension value:
* See the values in x509.h */
mbedtls_md_type_t sig_md; /**< The hash algorithm used to hash CRT before signing. */
mbedtls_pk_type_t sig_pk; /**< The signature algorithm used to sign the CRT hash. */
uint16_t key_usage; /**< Optional key usage extension value: See the values in x509.h */
uint32_t ext_types; /**< Bitfield indicating which extensions are present.
* See the values in x509.h. */
#if !defined(MBEDTLS_X509_CRT_REMOVE_TIME)
mbedtls_x509_time valid_from; /**< The start time of certificate validity. */
mbedtls_x509_time valid_to; /**< The end time of certificate validity. */
#endif /* !MBEDTLS_X509_CRT_REMOVE_TIME */
mbedtls_x509_buf_raw raw; /**< The raw certificate data in DER. */
mbedtls_x509_buf_raw tbs; /**< The part of the CRT that is [T]o [B]e [S]igned. */
mbedtls_x509_buf_raw serial; /**< The unique ID for certificate issued by a specific CA. */
mbedtls_x509_buf_raw pubkey_raw; /**< The raw public key data (DER). */
#if !defined(MBEDTLS_X509_CRT_REMOVE_SUBJECT_ISSUER_ID)
mbedtls_x509_buf_raw issuer_id; /**< Optional X.509 v2/v3 issuer unique identifier. */
mbedtls_x509_buf_raw subject_id; /**< Optional X.509 v2/v3 subject unique identifier. */
#endif /* !MBEDTLS_X509_CRT_REMOVE_SUBJECT_ISSUER_ID */
mbedtls_x509_buf_raw issuer_raw; /**< The raw issuer data (DER). Used for quick comparison. */
mbedtls_x509_buf_raw subject_raw; /**< The raw subject data (DER). Used for quick comparison. */
mbedtls_x509_buf_raw sig; /**< Signature: hash of the tbs part signed with the private key. */
mbedtls_x509_buf_raw sig_alg; /**< The signature algorithm used for \p sig. */
mbedtls_x509_buf_raw v3_ext; /**< The raw data for the extension list in the certificate.
* Might be useful for manual inspection of extensions that
* Mbed TLS doesn't yet support. */
#if !defined(MBEDTLS_X509_REMOVE_HOSTNAME_VERIFICATION)
mbedtls_x509_buf_raw subject_alt_raw; /**< The raw data for the SubjectAlternativeNames extension. */
#endif /* !MBEDTLS_X509_REMOVE_HOSTNAME_VERIFICATION */
mbedtls_x509_buf_raw ext_key_usage_raw; /**< The raw data for the ExtendedKeyUsage extension. */
} mbedtls_x509_crt_frame;
/**
* Container for an X.509 certificate. The certificate may be chained.
*/
typedef struct mbedtls_x509_crt
{
mbedtls_x509_buf raw; /**< The raw certificate data (DER). */
int own_buffer; /**< Indicates if \c raw is owned
* by the structure or not. */
mbedtls_x509_buf raw; /**< The raw certificate data (DER). */
mbedtls_x509_crt_cache *cache; /**< Internal parsing cache. */
struct mbedtls_x509_crt *next; /**< Next certificate in the CA-chain. */
/* Legacy fields */
#if !defined(MBEDTLS_X509_ON_DEMAND_PARSING)
mbedtls_x509_buf tbs; /**< The raw certificate body (DER). The part that is To Be Signed. */
int version; /**< The X.509 version. (1=v1, 2=v2, 3=v3) */
@ -65,15 +143,22 @@ typedef struct mbedtls_x509_crt
mbedtls_x509_name issuer; /**< The parsed issuer data (named information object). */
mbedtls_x509_name subject; /**< The parsed subject data (named information object). */
#if !defined(MBEDTLS_X509_CRT_REMOVE_TIME)
mbedtls_x509_time valid_from; /**< Start time of certificate validity. */
mbedtls_x509_time valid_to; /**< End time of certificate validity. */
#endif /* !MBEDTLS_X509_CRT_REMOVE_TIME */
mbedtls_x509_buf pk_raw;
mbedtls_pk_context pk; /**< Container for the public key context. */
#if !defined(MBEDTLS_X509_CRT_REMOVE_SUBJECT_ISSUER_ID)
mbedtls_x509_buf issuer_id; /**< Optional X.509 v2/v3 issuer unique identifier. */
mbedtls_x509_buf subject_id; /**< Optional X.509 v2/v3 subject unique identifier. */
#endif /* !MBEDTLS_X509_CRT_REMOVE_SUBJECT_ISSUER_ID */
mbedtls_x509_buf v3_ext; /**< Optional X.509 v3 extensions. */
#if !defined(MBEDTLS_X509_REMOVE_HOSTNAME_VERIFICATION)
mbedtls_x509_sequence subject_alt_names; /**< Optional list of Subject Alternative Names (Only dNSName supported). */
#endif /* !MBEDTLS_X509_REMOVE_HOSTNAME_VERIFICATION */
int ext_types; /**< Bit string containing detected and parsed extensions */
int ca_istrue; /**< Optional Basic Constraint extension value: 1 if this certificate belongs to a CA, 0 otherwise. */
@ -81,7 +166,7 @@ typedef struct mbedtls_x509_crt
unsigned int key_usage; /**< Optional key usage extension value: See the values in x509.h */
mbedtls_x509_sequence ext_key_usage; /**< Optional list of extended key usage OIDs. */
mbedtls_x509_sequence ext_key_usage; /**< Optional list of extended key usage OIDs. */
unsigned char ns_cert_type; /**< Optional Netscape certificate type extension value: See the values in x509.h */
@ -89,8 +174,7 @@ typedef struct mbedtls_x509_crt
mbedtls_md_type_t sig_md; /**< Internal representation of the MD algorithm of the signature algorithm, e.g. MBEDTLS_MD_SHA256 */
mbedtls_pk_type_t sig_pk; /**< Internal representation of the Public Key algorithm of the signature algorithm, e.g. MBEDTLS_PK_RSA */
void *sig_opts; /**< Signature options to be passed to mbedtls_pk_verify_ext(), e.g. for RSASSA-PSS */
struct mbedtls_x509_crt *next; /**< Next certificate in the CA-chain. */
#endif /* !MBEDTLS_X509_ON_DEMAND_PARSING */
}
mbedtls_x509_crt;
@ -125,6 +209,7 @@ mbedtls_x509_crt_profile;
#define MBEDTLS_X509_MAX_FILE_PATH_LEN 512
#endif
#if defined(MBEDTLS_X509_CRT_WRITE_C)
/**
* Container for writing a certificate (CRT)
*/
@ -142,6 +227,9 @@ typedef struct mbedtls_x509write_cert
mbedtls_asn1_named_data *extensions;
}
mbedtls_x509write_cert;
#endif /* MBEDTLS_X509_CRT_WRITE_C */
#if !defined(MBEDTLS_X509_REMOVE_VERIFY_CALLBACK)
/**
* Item in a verification chain: cert and flags for it
@ -165,6 +253,16 @@ typedef struct
unsigned len;
} mbedtls_x509_crt_verify_chain;
#else /* !MBEDTLS_X509_REMOVE_VERIFY_CALLBACK */
typedef struct
{
unsigned len;
uint32_t flags;
} mbedtls_x509_crt_verify_chain;
#endif /* !MBEDTLS_X509_REMOVE_VERIFY_CALLBACK */
#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
/**
@ -177,8 +275,14 @@ typedef struct
/* for find_parent_in() */
mbedtls_x509_crt *parent; /* non-null iff parent_in in progress */
/* current child CRT */
mbedtls_x509_crt *cur_crt;
#if defined(MBEDTLS_HAVE_TIME_DATE)
mbedtls_x509_crt *fallback_parent;
int fallback_signature_is_good;
#endif /* MBEDTLS_HAVE_TIME_DATE */
/* for find_parent() */
int parent_is_trusted; /* -1 if find_parent is not in progress */
@ -220,16 +324,58 @@ extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb;
/**
* \brief Parse a single DER formatted certificate and add it
* to the chained list.
* to the end of the provided chained list.
*
* \param chain points to the start of the chain
* \param buf buffer holding the certificate DER data
* \param buflen size of the buffer
* \param chain The pointer to the start of the CRT chain to attach to.
* When parsing the first CRT in a chain, this should point
* to an instance of ::mbedtls_x509_crt initialized through
* mbedtls_x509_crt_init().
* \param buf The buffer holding the DER encoded certificate.
* \param buflen The size in Bytes of \p buf.
*
* \return 0 if successful, or a specific X509 or PEM error code
* \note This function makes an internal copy of the CRT buffer
* \p buf. In particular, \p buf may be destroyed or reused
* after this call returns. To avoid duplicating the CRT
* buffer (at the cost of stricter lifetime constraints),
* use mbedtls_x509_crt_parse_der_nocopy() instead.
*
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *buf,
size_t buflen );
int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain,
const unsigned char *buf,
size_t buflen );
/**
* \brief Parse a single DER formatted certificate and add it
* to the end of the provided chained list. This is a
* variant of mbedtls_x509_crt_parse_der() which takes
* temporary ownership of the CRT buffer until the CRT
* is destroyed.
*
* \param chain The pointer to the start of the CRT chain to attach to.
* When parsing the first CRT in a chain, this should point
* to an instance of ::mbedtls_x509_crt initialized through
* mbedtls_x509_crt_init().
* \param buf The address of the readable buffer holding the DER encoded
* certificate to use. On success, this buffer must be
* retained and not be changed for the liftetime of the
* CRT chain \p chain, that is, until \p chain is destroyed
* through a call to mbedtls_x509_crt_free().
* \param buflen The size in Bytes of \p buf.
*
* \note This call is functionally equivalent to
* mbedtls_x509_crt_parse_der(), but it avoids creating a
* copy of the input buffer at the cost of stronger lifetime
* constraints. This is useful in constrained environments
* where duplication of the CRT cannot be tolerated.
*
* \return \c 0 if successful.
* \return A negative error code on failure.
*/
int mbedtls_x509_crt_parse_der_nocopy( mbedtls_x509_crt *chain,
const unsigned char *buf,
size_t buflen );
/**
* \brief Parse one DER-encoded or one or more concatenated PEM-encoded
@ -295,6 +441,7 @@ int mbedtls_x509_crt_parse_file( mbedtls_x509_crt *chain, const char *path );
int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path );
#endif /* MBEDTLS_FS_IO */
#if !defined(MBEDTLS_X509_REMOVE_INFO)
/**
* \brief Returns an informational string about the
* certificate.
@ -324,6 +471,7 @@ int mbedtls_x509_crt_info( char *buf, size_t size, const char *prefix,
*/
int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
uint32_t flags );
#endif /* !MBEDTLS_X509_REMOVE_INFO */
/**
* \brief Verify the certificate signature
@ -384,11 +532,17 @@ int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
* verification process.
*/
int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const char *cn, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy );
mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
#if !defined(MBEDTLS_X509_REMOVE_HOSTNAME_VERIFICATION) || defined(DOXYGEN_ONLY)
const char *cn,
#endif /* !MBEDTLS_X509_REMOVE_HOSTNAME_VERIFICATION || DOXYGEN_ONLY */
uint32_t *flags
#if !defined(MBEDTLS_X509_REMOVE_VERIFY_CALLBACK) || defined(DOXYGEN_ONLY)
, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy
#endif /* !MBEDTLS_X509_REMOVE_VERIFY_CALLBACK || DOXYGEN_ONLY */
);
/**
* \brief Verify the certificate signature according to profile
@ -421,9 +575,15 @@ int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
const char *cn, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy );
#if !defined(MBEDTLS_X509_REMOVE_HOSTNAME_VERIFICATION) || defined(DOXYGEN_ONLY)
const char *cn,
#endif /* !MBEDTLS_X509_REMOVE_HOSTNAME_VERIFICATION || DOXYGEN_ONLY */
uint32_t *flags
#if !defined(MBEDTLS_X509_REMOVE_VERIFY_CALLBACK) || defined(DOXYGEN_ONLY)
, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy
#endif /* !MBEDTLS_X509_REMOVE_VERIFY_CALLBACK || DOXYGEN_ONLY */
);
/**
* \brief Restartable version of \c mbedtls_crt_verify_with_profile()
@ -451,9 +611,14 @@ int mbedtls_x509_crt_verify_restartable( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
const char *cn, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy,
#if !defined(MBEDTLS_X509_REMOVE_HOSTNAME_VERIFICATION) || defined(DOXYGEN_ONLY)
const char *cn,
#endif /* !MBEDTLS_X509_REMOVE_HOSTNAME_VERIFICATION || DOXYGEN_ONLY */
uint32_t *flags,
#if !defined(MBEDTLS_X509_REMOVE_VERIFY_CALLBACK) || defined(DOXYGEN_ONLY)
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy,
#endif /* !MBEDTLS_X509_REMOVE_VERIFY_CALLBACK || DOXYGEN_ONLY */
mbedtls_x509_crt_restart_ctx *rs_ctx );
#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
@ -539,6 +704,252 @@ void mbedtls_x509_crt_restart_init( mbedtls_x509_crt_restart_ctx *ctx );
*/
void mbedtls_x509_crt_restart_free( mbedtls_x509_crt_restart_ctx *ctx );
#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
/**
* \brief Request CRT frame giving access to basic CRT fields
* and raw ASN.1 data of complex fields.
*
* \param crt The CRT to use. This must be initialized and set up.
* \param dst The address of the destination frame structure.
* This need not be initialized.
*
* \note ::mbedtls_x509_crt_frame does not contain pointers to
* dynamically allocated memory, and hence need not be freed.
* Users may e.g. allocate an instance of
* ::mbedtls_x509_crt_frame on the stack and call this function
* on it, in which case no allocation/freeing has to be done.
*
* \note You may also use mbedtls_x509_crt_frame_acquire() and
* mbedtls_x509_crt_frame_release() for copy-less variants
* of this function.
*
* \return \c 0 on success. In this case, \p dst is updated
* to hold the frame for the given CRT.
* \return A negative error code on failure.
*/
int mbedtls_x509_crt_get_frame( mbedtls_x509_crt const *crt,
mbedtls_x509_crt_frame *dst );
/**
* \brief Set up a PK context with the public key in a certificate.
*
* \param crt The certificate to use. This must be initialized and set up.
* \param pk The address of the destination PK context to fill.
* This must be initialized via mbedtls_pk_init().
*
* \note You may also use mbedtls_x509_crt_pk_acquire() and
* mbedtls_x509_crt_pk_release() for copy-less variants
* of this function.
*
* \return \c 0 on success. In this case, the user takes ownership
* of the destination PK context, and is responsible for
* calling mbedtls_pk_free() on it once it's no longer needed.
* \return A negative error code on failure.
*/
int mbedtls_x509_crt_get_pk( mbedtls_x509_crt const *crt,
mbedtls_pk_context *pk );
/**
* \brief Request the subject name of a CRT, presented
* as a dynamically allocated linked list.
*
* \param crt The CRT to use. This must be initialized and set up.
* \param subject The address at which to store the address of the
* first entry of the generated linked list holding
* the subject name.
*
* \note Depending on your use case, consider using the raw ASN.1
* describing the subject name instead of the heap-allocated
* linked list generated by this call. The pointers to the
* raw ASN.1 data are part of the CRT frame that can be queried
* via mbedtls_x509_crt_get_frame(), and they can be traversed
* via mbedtls_asn1_traverse_sequence_of().
*
* \return \c 0 on success. In this case, the user takes ownership
* of the name context, and is responsible for freeing it
* through a call to mbedtls_x509_name_free() once it's no
* longer needed.
* \return A negative error code on failure.
*/
int mbedtls_x509_crt_get_subject( mbedtls_x509_crt const *crt,
mbedtls_x509_name **subject );
/**
* \brief Request the subject name of a CRT, presented
* as a dynamically allocated linked list.
*
* \param crt The CRT to use. This must be initialized and set up.
* \param issuer The address at which to store the address of the
* first entry of the generated linked list holding
* the subject name.
*
* \note Depending on your use case, consider using the raw ASN.1
* describing the issuer name instead of the heap-allocated
* linked list generated by this call. The pointers to the
* raw ASN.1 data are part of the CRT frame that can be queried
* via mbedtls_x509_crt_get_frame(), and they can be traversed
* via mbedtls_asn1_traverse_sequence_of().
*
* \return \c 0 on success. In this case, the user takes ownership
* of the name context, and is responsible for freeing it
* through a call to mbedtls_x509_name_free() once it's no
* longer needed.
* \return A negative error code on failure.
*/
int mbedtls_x509_crt_get_issuer( mbedtls_x509_crt const *crt,
mbedtls_x509_name **issuer );
#if !defined(MBEDTLS_X509_REMOVE_HOSTNAME_VERIFICATION)
/**
* \brief Request the subject alternative name of a CRT, presented
* as a dynamically allocated linked list.
*
* \param crt The CRT to use. This must be initialized and set up.
* \param subj_alt The address at which to store the address of the
* first component of the subject alternative names list.
*
* \note Depending in your use case, consider using the raw ASN.1
* describing the subject alternative names extension
* instead of the heap-allocated linked list generated by this
* call. The pointers to the raw ASN.1 data are part of the CRT
* frame that can be queried via mbedtls_x509_crt_get_frame(),
* and mbedtls_asn1_traverse_sequence_of() can be used to
* traverse the list of subject alternative names.
*
* \return \c 0 on success. In this case, the user takes ownership
* of the name context, and is responsible for freeing it
* through a call to mbedtls_x509_sequence_free() once it's
* no longer needed.
* \return A negative error code on failure.
*/
int mbedtls_x509_crt_get_subject_alt_names( mbedtls_x509_crt const *crt,
mbedtls_x509_sequence **subj_alt );
#endif /* !MBEDTLS_X509_REMOVE_HOSTNAME_VERIFICATION */
/**
* \brief Request the ExtendedKeyUsage extension of a CRT,
* presented as a dynamically allocated linked list.
*
* \param crt The CRT to use. This must be initialized and set up.
* \param ext_key_usage The address at which to store the address of the
* first entry of the ExtendedKeyUsage extension.
*
* \note Depending in your use case, consider using the raw ASN.1
* describing the extended key usage extension instead of
* the heap-allocated linked list generated by this call.
* The pointers to the raw ASN.1 data are part of the CRT
* frame that can be queried via mbedtls_x509_crt_get_frame(),
* and mbedtls_asn1_traverse_sequence_of() can be used to
* traverse the entries in the extended key usage extension.
*
* \return \c 0 on success. In this case, the user takes ownership
* of the name context, and is responsible for freeing it
* through a call to mbedtls_x509_sequence_free() once it's
* no longer needed.
* \return A negative error code on failure.
*/
int mbedtls_x509_crt_get_ext_key_usage( mbedtls_x509_crt const *crt,
mbedtls_x509_sequence **ext_key_usage );
/**
* \brief Flush internal X.509 CRT parsing cache, if present.
*
* \param crt The CRT structure whose cache to flush.
*
* \note Calling this function frequently reduces RAM usage
* at the cost of performance.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_x509_crt_flush_cache( mbedtls_x509_crt const *crt );
/**
* \brief Request temporary read-access to a certificate frame
* for a given certificate.
*
* Once no longer needed, the frame must be released
* through a call to mbedtls_x509_crt_frame_release().
*
* This is a copy-less version of mbedtls_x509_crt_get_frame().
* See there for more information.
*
* \param crt The certificate to use. This must be initialized and set up.
* \param dst The address at which to store the address of a readable
* certificate frame for the input certificate \p crt which the
* caller can use until calling mbedtls_x509_crt_frame_release().
*
* \note The certificate frame `**frame_ptr` returned by this function
* is owned by the X.509 module and must not be freed or modified
* by the caller. The X.509 module guarantees its validity as long
* as \p crt is valid and mbedtls_x509_crt_frame_release() hasn't
* been issued.
*
* \note In a single-threaded application using
* MBEDTLS_X509_ALWAYS_FLUSH, nested calls to this function
* are not allowed and will fail gracefully with
* MBEDTLS_ERR_X509_FATAL_ERROR.
*
* \return \c 0 on success. In this case, `*frame_ptr` is updated
* to hold the address of a frame for the given CRT.
* \return A negative error code on failure.
*/
int mbedtls_x509_crt_frame_acquire( mbedtls_x509_crt const *crt,
mbedtls_x509_crt_frame const **dst );
/**
* \brief Release access to a certificate frame acquired
* through a prior call to mbedtls_x509_crt_frame_acquire().
*
* \param crt The certificate for which a certificate frame has
* previously been acquired.
*/
int mbedtls_x509_crt_frame_release( mbedtls_x509_crt const *crt );
/**
* \brief Request temporary access to a public key context
* for a given certificate.
*
* Once no longer needed, the frame must be released
* through a call to mbedtls_x509_crt_pk_release().
*
* This is a copy-less version of mbedtls_x509_crt_get_pk().
* See there for more information.
*
* \param crt The certificate to use. This must be initialized and set up.
* \param dst The address at which to store the address of a public key
* context for the public key in the input certificate \p crt.
*
* \warning The public key context `**pk_ptr` returned by this function
* is owned by the X.509 module and must be used by the caller
* in a thread-safe way. In particular, the caller must only
* use the context with functions which are `const` on the input
* context, or those which are known to be thread-safe. The latter
* for example includes mbedtls_pk_verify() for ECC or RSA public
* key contexts.
*
* \note In a single-threaded application using
* MBEDTLS_X509_ALWAYS_FLUSH, nested calls to this function
* are not allowed and will fail gracefully with
* MBEDTLS_ERR_X509_FATAL_ERROR.
*
* \return \c 0 on success. In this case, `*pk_ptr` is updated
* to hold the address of a public key context for the given
* certificate.
* \return A negative error code on failure.
*/
int mbedtls_x509_crt_pk_acquire( mbedtls_x509_crt const *crt,
mbedtls_pk_context **dst );
/**
* \brief Release access to a public key context acquired
* through a prior call to mbedtls_x509_crt_frame_acquire().
*
* \param crt The certificate for which a certificate frame has
* previously been acquired.
*/
int mbedtls_x509_crt_pk_release( mbedtls_x509_crt const *crt );
#endif /* MBEDTLS_X509_CRT_PARSE_C */
/* \} name */

View file

@ -123,6 +123,7 @@ int mbedtls_x509_csr_parse( mbedtls_x509_csr *csr, const unsigned char *buf, siz
int mbedtls_x509_csr_parse_file( mbedtls_x509_csr *csr, const char *path );
#endif /* MBEDTLS_FS_IO */
#if !defined(MBEDTLS_X509_REMOVE_INFO)
/**
* \brief Returns an informational string about the
* CSR.
@ -137,6 +138,7 @@ int mbedtls_x509_csr_parse_file( mbedtls_x509_csr *csr, const char *path );
*/
int mbedtls_x509_csr_info( char *buf, size_t size, const char *prefix,
const mbedtls_x509_csr *csr );
#endif /* !MBEDTLS_X509_REMOVE_INFO */
/**
* \brief Initialize a CSR

View file

@ -0,0 +1,124 @@
/**
* \file x509_internal.h
*
* \brief Internal X.509 functions
*/
/*
* Copyright (C) 2006-2019, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of Mbed TLS (https://tls.mbed.org)
*
*/
#ifndef MBEDTLS_X509_INTERNAL_H
#define MBEDTLS_X509_INTERNAL_H
#if defined(MBEDTLS_X509_USE_C)
#include "x509.h"
#include "threading.h"
/* Internal structure used for caching parsed data from an X.509 CRT. */
struct mbedtls_x509_crt;
struct mbedtls_pk_context;
struct mbedtls_x509_crt_frame;
#define MBEDTLS_X509_CACHE_PK_READERS_MAX ((uint32_t) -1)
#define MBEDTLS_X509_CACHE_FRAME_READERS_MAX ((uint32_t) -1)
/* Internal X.509 CRT cache handling functions. */
#if defined(MBEDTLS_X509_CRT_PARSE_C)
static int mbedtls_x509_crt_flush_cache_frame( struct mbedtls_x509_crt const *crt );
static int mbedtls_x509_crt_flush_cache_pk( struct mbedtls_x509_crt const *crt );
static int mbedtls_x509_crt_cache_provide_frame( struct mbedtls_x509_crt const *crt );
static int mbedtls_x509_crt_cache_provide_pk( struct mbedtls_x509_crt const *crt );
#endif /* MBEDTLS_X509_CRT_PARSE_C */
/* Uncategorized internal X.509 functions */
static int mbedtls_x509_get_name( unsigned char *p, size_t len,
mbedtls_x509_name *cur );
#if defined(MBEDTLS_X509_CRL_PARSE_C) || defined(MBEDTLS_X509_CSR_PARSE_C) || \
( !defined(MBEDTLS_X509_ON_DEMAND_PARSING) && defined(MBEDTLS_X509_CRT_PARSE_C) )
static int mbedtls_x509_get_alg( unsigned char **p, const unsigned char *end,
mbedtls_x509_buf *alg, mbedtls_x509_buf *params );
#endif /* defined(MBEDTLS_X509_CRL_PARSE_C) || defined(MBEDTLS_X509_CSR_PARSE_C) ||
( !defined(MBEDTLS_X509_ON_DEMAND_PARSING) && defined(MBEDTLS_X509_CRT_PARSE_C) ) */
#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
static int mbedtls_x509_get_alg_null( unsigned char **p, const unsigned char *end,
mbedtls_x509_buf *alg );
static int mbedtls_x509_get_rsassa_pss_params( const mbedtls_x509_buf *params,
mbedtls_md_type_t *md_alg, mbedtls_md_type_t *mgf_md,
int *salt_len );
#endif
static int mbedtls_x509_get_sig( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *sig );
static int mbedtls_x509_get_sig_alg_raw( unsigned char **p, unsigned char const *end,
mbedtls_md_type_t *md_alg,
mbedtls_pk_type_t *pk_alg,
void **sig_opts );
static int mbedtls_x509_get_sig_alg( const mbedtls_x509_buf *sig_oid, const mbedtls_x509_buf *sig_params,
mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg,
void **sig_opts );
#if ( !defined(MBEDTLS_X509_CRT_REMOVE_TIME) && defined(MBEDTLS_X509_CRT_PARSE_C) ) || \
defined(MBEDTLS_X509_CRL_PARSE_C)
static int mbedtls_x509_get_time( unsigned char **p, const unsigned char *end,
mbedtls_x509_time *t );
#endif /* ( !defined(MBEDTLS_X509_CRT_REMOVE_TIME) && defined(MBEDTLS_X509_CRT_PARSE_C) ) ||
defined(MBEDTLS_X509_CRL_PARSE_C) */
static int mbedtls_x509_get_serial( unsigned char **p, const unsigned char *end,
mbedtls_x509_buf *serial );
static int mbedtls_x509_name_cmp_raw( mbedtls_x509_buf_raw const *a,
mbedtls_x509_buf_raw const *b,
int (*check)( void *ctx,
mbedtls_x509_buf *oid,
mbedtls_x509_buf *val,
int next_merged ),
void *check_ctx );
static int mbedtls_x509_memcasecmp( const void *s1, const void *s2,
size_t len1, size_t len2 );
#if defined(MBEDTLS_X509_CRL_PARSE_C)
static int mbedtls_x509_get_ext( unsigned char **p, const unsigned char *end,
mbedtls_x509_buf *ext, int tag );
#endif /* defined(MBEDTLS_X509_CRL_PARSE_C) */
#if !defined(MBEDTLS_X509_REMOVE_INFO)
static int mbedtls_x509_sig_alg_gets( char *buf, size_t size,
mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg,
const void *sig_opts );
#endif
#if !defined(MBEDTLS_X509_REMOVE_INFO)
static int mbedtls_x509_key_size_helper( char *buf, size_t buf_size, const char *name );
#endif /* !defined(MBEDTLS_X509_REMOVE_INFO) */
#if defined(MBEDTLS_X509_CREATE_C)
static int mbedtls_x509_string_to_names( mbedtls_asn1_named_data **head, const char *name );
static int mbedtls_x509_set_extension( mbedtls_asn1_named_data **head, const char *oid, size_t oid_len,
int critical, const unsigned char *val,
size_t val_len );
static int mbedtls_x509_write_extensions( unsigned char **p, unsigned char *start,
mbedtls_asn1_named_data *first );
int mbedtls_x509_write_names( unsigned char **p, unsigned char *start,
mbedtls_asn1_named_data *first );
static int mbedtls_x509_write_sig( unsigned char **p, unsigned char *start,
const char *oid, size_t oid_len,
unsigned char *sig, size_t size );
#endif /* MBEDTLS_X509_CREATE_C */
#endif /* MBEDTLS_X509_USE_C */
#endif /* MBEDTLS_X509_INTERNAL_H */

479
include/tinycrypt/ecc.h Normal file
View file

@ -0,0 +1,479 @@
/* ecc.h - TinyCrypt interface to common ECC functions */
/*
* Copyright (c) 2019, Arm Limited (or its affiliates), All Rights Reserved.
* SPDX-License-Identifier: BSD-3-Clause
*/
/* Copyright (c) 2014, Kenneth MacKay
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Copyright (C) 2017 by Intel Corporation, All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* @brief -- Interface to common ECC functions.
*
* Overview: This software is an implementation of common functions
* necessary to elliptic curve cryptography. This implementation uses
* curve NIST p-256.
*
* Security: The curve NIST p-256 provides approximately 128 bits of security.
*
*/
#ifndef __TC_UECC_H__
#define __TC_UECC_H__
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Return values for functions, chosen with large Hamming distances between
* them (especially to SUCESS) to mitigate the impact of fault injection
* attacks flipping a low number of bits. */
#define UECC_SUCCESS 0
#define UECC_FAILURE 0x75555555
#define UECC_FAULT_DETECTED 0x7aaaaaaa
/* Word size (4 bytes considering 32-bits architectures) */
#define uECC_WORD_SIZE 4
/* setting max number of calls to prng: */
#ifndef uECC_RNG_MAX_TRIES
#define uECC_RNG_MAX_TRIES 64
#endif
/* defining data types to store word and bit counts: */
typedef int8_t wordcount_t;
typedef int16_t bitcount_t;
/* defining data type for comparison result: */
typedef int8_t cmpresult_t;
/* defining data type to store ECC coordinate/point in 32bits words: */
typedef unsigned int uECC_word_t;
/* defining data type to store an ECC coordinate/point in 64bits words: */
typedef uint64_t uECC_dword_t;
/* defining masks useful for ecc computations: */
#define HIGH_BIT_SET 0x80000000
#define uECC_WORD_BITS 32
#define uECC_WORD_BITS_SHIFT 5
#define uECC_WORD_BITS_MASK 0x01F
/* Number of words of 32 bits to represent an element of the the curve p-256: */
#define NUM_ECC_WORDS 8
/* Number of bytes to represent an element of the the curve p-256: */
#define NUM_ECC_BYTES (uECC_WORD_SIZE*NUM_ECC_WORDS)
#define NUM_ECC_BITS 256
/*
* @brief computes doubling of point ion jacobian coordinates, in place.
* @param X1 IN/OUT -- x coordinate
* @param Y1 IN/OUT -- y coordinate
* @param Z1 IN/OUT -- z coordinate
* @param curve IN -- elliptic curve
*/
void double_jacobian_default(uECC_word_t * X1, uECC_word_t * Y1,
uECC_word_t * Z1);
/*
* @brief Computes result = product % curve_p
* from http://www.nsa.gov/ia/_files/nist-routines.pdf
* @param result OUT -- product % curve_p
* @param product IN -- value to be reduced mod curve_p
*/
void vli_mmod_fast_secp256r1(unsigned int *result, unsigned int *product);
/* Bytes to words ordering: */
#define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##d##c##b##a, 0x##h##g##f##e
#define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a
#define BITS_TO_WORDS(num_bits) \
((num_bits + ((uECC_WORD_SIZE * 8) - 1)) / (uECC_WORD_SIZE * 8))
#define BITS_TO_BYTES(num_bits) ((num_bits + 7) / 8)
extern const uECC_word_t curve_p[NUM_ECC_WORDS];
extern const uECC_word_t curve_n[NUM_ECC_WORDS];
extern const uECC_word_t curve_G[2 * NUM_ECC_WORDS];
extern const uECC_word_t curve_b[NUM_ECC_WORDS];
/*
* @brief Generates a random integer in the range 0 < random < top.
* Both random and top have num_words words.
* @param random OUT -- random integer in the range 0 < random < top
* @param top IN -- upper limit
* @param num_words IN -- number of words
* @return UECC_SUCCESS in case of success
* @return UECC_FAILURE upon failure
*/
int uECC_generate_random_int(uECC_word_t *random, const uECC_word_t *top,
wordcount_t num_words);
/* uECC_RNG_Function type
* The RNG function should fill 'size' random bytes into 'dest'. It should
* return 'size' if 'dest' was filled with random data of 'size' length, or 0
* if the random data could not be generated. The filled-in values should be
* either truly random, or from a cryptographically-secure PRNG.
*
* A correctly functioning RNG function must be set (using uECC_set_rng())
* before calling uECC_make_key() or uECC_sign().
*
* Setting a correctly functioning RNG function improves the resistance to
* side-channel attacks for uECC_shared_secret().
*
* A correct RNG function is set by default. If you are building on another
* POSIX-compliant system that supports /dev/random or /dev/urandom, you can
* define uECC_POSIX to use the predefined RNG.
*/
typedef int(*uECC_RNG_Function)(uint8_t *dest, unsigned int size);
/*
* @brief Set the function that will be used to generate random bytes. The RNG
* function should return 'size' if the random data of length 'size' was
* generated, or 0 if the random data could not be generated.
*
* @note On platforms where there is no predefined RNG function, this must be
* called before uECC_make_key() or uECC_sign() are used.
*
* @param rng_function IN -- function that will be used to generate random bytes
*/
void uECC_set_rng(uECC_RNG_Function rng_function);
/*
* @brief provides current uECC_RNG_Function.
* @return Returns the function that will be used to generate random bytes.
*/
uECC_RNG_Function uECC_get_rng(void);
/*
* @brief computes the size of a private key for the curve in bytes.
* @param curve IN -- elliptic curve
* @return size of a private key for the curve in bytes.
*/
int uECC_curve_private_key_size(void);
/*
* @brief computes the size of a public key for the curve in bytes.
* @param curve IN -- elliptic curve
* @return the size of a public key for the curve in bytes.
*/
int uECC_curve_public_key_size(void);
/*
* @brief Compute the corresponding public key for a private key.
* @param private_key IN -- The private key to compute the public key for
* @param public_key OUT -- Will be filled in with the corresponding public key
* @param curve
* @return UECC_SUCCESS or UECC_FAILURE or UECC_FAULT_DETECTED
*/
int uECC_compute_public_key(const uint8_t *private_key,
uint8_t *public_key);
/*
* @brief Compute public-key.
* @return corresponding public-key.
* @param result OUT -- public-key
* @param private_key IN -- private-key
* @param curve IN -- elliptic curve
* @return UECC_SUCCESS or UECC_FAILURE or UECC_FAULT_DETECTED
*/
uECC_word_t EccPoint_compute_public_key(uECC_word_t *result,
uECC_word_t *private_key);
/*
* @brief Point multiplication algorithm using Montgomery's ladder with co-Z
* coordinates. See http://eprint.iacr.org/2011/338.pdf.
* Uses scalar regularization and coordinate randomization (if a global RNG
* function is set) in order to protect against some side channel attacks.
* @note Result may overlap point.
* @param result OUT -- returns scalar*point
* @param point IN -- elliptic curve point
* @param scalar IN -- scalar
* @return UECC_SUCCESS or UECC_FAILURE or UECC_FAULT_DETECTED
*/
int EccPoint_mult_safer(uECC_word_t * result, const uECC_word_t * point,
const uECC_word_t * scalar);
/*
* @brief Constant-time comparison to zero - secure way to compare long integers
* @param vli IN -- very long integer
* @param num_words IN -- number of words in the vli
* @return 1 if vli == 0, 0 otherwise.
*/
uECC_word_t uECC_vli_isZero(const uECC_word_t *vli);
/*
* @brief Check if 'point' is the point at infinity
* @param point IN -- elliptic curve point
* @return if 'point' is the point at infinity, 0 otherwise.
*/
uECC_word_t EccPoint_isZero(const uECC_word_t *point);
/*
* @brief computes the sign of left - right, in constant time.
* @param left IN -- left term to be compared
* @param right IN -- right term to be compared
* @param num_words IN -- number of words
* @return the sign of left - right
*/
cmpresult_t uECC_vli_cmp(const uECC_word_t *left, const uECC_word_t *right);
/*
* @brief computes sign of left - right, not in constant time.
* @note should not be used if inputs are part of a secret
* @param left IN -- left term to be compared
* @param right IN -- right term to be compared
* @param num_words IN -- number of words
* @return the sign of left - right
*/
cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t *left, const uECC_word_t *right);
/*
* @brief Computes result = (left - right) % mod.
* @note Assumes that (left < mod) and (right < mod), and that result does not
* overlap mod.
* @param result OUT -- (left - right) % mod
* @param left IN -- leftright term in modular subtraction
* @param right IN -- right term in modular subtraction
* @param mod IN -- mod
* @param num_words IN -- number of words
*/
void uECC_vli_modSub(uECC_word_t *result, const uECC_word_t *left,
const uECC_word_t *right, const uECC_word_t *mod);
/*
* @brief Computes P' = (x1', y1', Z3), P + Q = (x3, y3, Z3) or
* P => P', Q => P + Q
* @note assumes Input P = (x1, y1, Z), Q = (x2, y2, Z)
* @param X1 IN -- x coordinate of P
* @param Y1 IN -- y coordinate of P
* @param X2 IN -- x coordinate of Q
* @param Y2 IN -- y coordinate of Q
* @param curve IN -- elliptic curve
*/
void XYcZ_add(uECC_word_t * X1, uECC_word_t * Y1, uECC_word_t * X2,
uECC_word_t * Y2);
/*
* @brief Computes (x1 * z^2, y1 * z^3)
* @param X1 IN -- previous x1 coordinate
* @param Y1 IN -- previous y1 coordinate
* @param Z IN -- z value
* @param curve IN -- elliptic curve
*/
void apply_z(uECC_word_t * X1, uECC_word_t * Y1, const uECC_word_t * const Z);
/*
* @brief Check if bit is set.
* @return Returns nonzero if bit 'bit' of vli is set.
* @warning It is assumed that the value provided in 'bit' is within the
* boundaries of the word-array 'vli'.
* @note The bit ordering layout assumed for vli is: {31, 30, ..., 0},
* {63, 62, ..., 32}, {95, 94, ..., 64}, {127, 126,..., 96} for a vli consisting
* of 4 uECC_word_t elements.
*/
uECC_word_t uECC_vli_testBit(const uECC_word_t *vli, bitcount_t bit);
/*
* @brief Computes result = product % mod, where product is 2N words long.
* @param result OUT -- product % mod
* @param mod IN -- module
* @param num_words IN -- number of words
* @warning Currently only designed to work for curve_p or curve_n.
*/
void uECC_vli_mmod(uECC_word_t *result, uECC_word_t *product,
const uECC_word_t *mod);
/*
* @brief Computes modular product (using curve->mmod_fast)
* @param result OUT -- (left * right) mod % curve_p
* @param left IN -- left term in product
* @param right IN -- right term in product
* @param curve IN -- elliptic curve
*/
void uECC_vli_modMult_fast(uECC_word_t *result, const uECC_word_t *left,
const uECC_word_t *right);
/*
* @brief Computes result = left - right.
* @note Can modify in place.
* @param result OUT -- left - right
* @param left IN -- left term in subtraction
* @param right IN -- right term in subtraction
* @param num_words IN -- number of words
* @return borrow
*/
uECC_word_t uECC_vli_sub(uECC_word_t *result, const uECC_word_t *left,
const uECC_word_t *right);
/*
* @brief Constant-time comparison function(secure way to compare long ints)
* @param left IN -- left term in comparison
* @param right IN -- right term in comparison
* @param num_words IN -- number of words
* @return Returns 0 if left == right, non-zero otherwise.
*/
uECC_word_t uECC_vli_equal(const uECC_word_t *left, const uECC_word_t *right);
/*
* @brief Computes (left * right) % mod
* @param result OUT -- (left * right) % mod
* @param left IN -- left term in product
* @param right IN -- right term in product
* @param mod IN -- mod
* @param num_words IN -- number of words
*/
void uECC_vli_modMult(uECC_word_t *result, const uECC_word_t *left,
const uECC_word_t *right, const uECC_word_t *mod);
/*
* @brief Computes (1 / input) % mod
* @note All VLIs are the same size.
* @note See "Euclid's GCD to Montgomery Multiplication to the Great Divide"
* @param result OUT -- (1 / input) % mod
* @param input IN -- value to be modular inverted
* @param mod IN -- mod
* @param num_words -- number of words
*/
void uECC_vli_modInv(uECC_word_t *result, const uECC_word_t *input,
const uECC_word_t *mod);
/*
* @brief Sets dest = src.
* @param dest OUT -- destination buffer
* @param src IN -- origin buffer
* @param num_words IN -- number of words
*/
void uECC_vli_set(uECC_word_t *dest, const uECC_word_t *src);
/*
* @brief Computes (left + right) % mod.
* @note Assumes that (left < mod) and right < mod), and that result does not
* overlap mod.
* @param result OUT -- (left + right) % mod.
* @param left IN -- left term in addition
* @param right IN -- right term in addition
* @param mod IN -- mod
* @param num_words IN -- number of words
*/
void uECC_vli_modAdd(uECC_word_t *result, const uECC_word_t *left,
const uECC_word_t *right, const uECC_word_t *mod);
/*
* @brief Counts the number of bits required to represent vli.
* @param vli IN -- very long integer
* @param max_words IN -- number of words
* @return number of bits in given vli
*/
bitcount_t uECC_vli_numBits(const uECC_word_t *vli);
/*
* @brief Erases (set to 0) vli
* @param vli IN -- very long integer
* @param num_words IN -- number of words
*/
void uECC_vli_clear(uECC_word_t *vli);
/*
* @brief check if it is a valid point in the curve
* @param point IN -- point to be checked
* @param curve IN -- elliptic curve
* @return 0 if point is valid
* @exception returns -1 if it is a point at infinity
* @exception returns -2 if x or y is smaller than p,
* @exception returns -3 if y^2 != x^3 + ax + b.
*/
int uECC_valid_point(const uECC_word_t *point);
/*
* @brief Check if a public key is valid.
* @param public_key IN -- The public key to be checked.
* @return returns 0 if the public key is valid
* @exception returns -1 if it is a point at infinity
* @exception returns -2 if x or y is smaller than p,
* @exception returns -3 if y^2 != x^3 + ax + b.
* @exception returns -4 if public key is the group generator.
*
* @note Note that you are not required to check for a valid public key before
* using any other uECC functions. However, you may wish to avoid spending CPU
* time computing a shared secret or verifying a signature using an invalid
* public key.
*/
int uECC_valid_public_key(const uint8_t *public_key);
/*
* @brief Converts an integer in uECC native format to big-endian bytes.
* @param bytes OUT -- bytes representation
* @param num_bytes IN -- number of bytes
* @param native IN -- uECC native representation
*/
void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
const unsigned int *native);
/*
* @brief Converts big-endian bytes to an integer in uECC native format.
* @param native OUT -- uECC native representation
* @param bytes IN -- bytes representation
* @param num_bytes IN -- number of bytes
*/
void uECC_vli_bytesToNative(unsigned int *native, const uint8_t *bytes,
int num_bytes);
#ifdef __cplusplus
}
#endif
#endif /* __TC_UECC_H__ */

134
include/tinycrypt/ecc_dh.h Normal file
View file

@ -0,0 +1,134 @@
/* ecc_dh.h - TinyCrypt interface to EC-DH implementation */
/*
* Copyright (c) 2019, Arm Limited (or its affiliates), All Rights Reserved.
* SPDX-License-Identifier: BSD-3-Clause
*/
/*
* Copyright (c) 2014, Kenneth MacKay
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* Copyright (C) 2017 by Intel Corporation, All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* @brief -- Interface to EC-DH implementation.
*
* Overview: This software is an implementation of EC-DH. This implementation
* uses curve NIST p-256.
*
* Security: The curve NIST p-256 provides approximately 128 bits of security.
*/
#ifndef __TC_ECC_DH_H__
#define __TC_ECC_DH_H__
#include <tinycrypt/ecc.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Create a public/private key pair.
* @return UECC_SUCCESS or UECC_FAILURE or UECC_FAULT_DETECTED
*
* @param p_public_key OUT -- Will be filled in with the public key. Must be at
* least 2 * the curve size (in bytes) long. For curve secp256r1, p_public_key
* must be 64 bytes long.
* @param p_private_key OUT -- Will be filled in with the private key. Must be as
* long as the curve order (for secp256r1, p_private_key must be 32 bytes long).
*
* @note side-channel countermeasure: algorithm strengthened against timing
* attack.
* @warning A cryptographically-secure PRNG function must be set (using
* uECC_set_rng()) before calling uECC_make_key().
*/
int uECC_make_key(uint8_t *p_public_key, uint8_t *p_private_key);
#ifdef ENABLE_TESTS
/**
* @brief Create a public/private key pair given a specific d.
*
* @note THIS FUNCTION SHOULD BE CALLED ONLY FOR TEST PURPOSES. Refer to
* uECC_make_key() function for real applications.
*/
int uECC_make_key_with_d(uint8_t *p_public_key, uint8_t *p_private_key,
unsigned int *d);
#endif
/**
* @brief Compute a shared secret given your secret key and someone else's
* public key.
* @return UECC_SUCCESS or UECC_FAILURE or UECC_FAULT_DETECTED
*
* @param p_secret OUT -- Will be filled in with the shared secret value. Must be
* the same size as the curve size (for curve secp256r1, secret must be 32 bytes
* long.
* @param p_public_key IN -- The public key of the remote party.
* @param p_private_key IN -- Your private key.
*
* @warning It is recommended to use the output of uECC_shared_secret() as the
* input of a recommended Key Derivation Function (see NIST SP 800-108) in
* order to produce a cryptographically secure symmetric key.
*/
int uECC_shared_secret(const uint8_t *p_public_key, const uint8_t *p_private_key,
uint8_t *p_secret);
#ifdef __cplusplus
}
#endif
#endif /* __TC_ECC_DH_H__ */

142
include/tinycrypt/ecc_dsa.h Normal file
View file

@ -0,0 +1,142 @@
/* ecc_dh.h - TinyCrypt interface to EC-DSA implementation */
/*
* Copyright (c) 2019, Arm Limited (or its affiliates), All Rights Reserved.
* SPDX-License-Identifier: BSD-3-Clause
*/
/*
* Copyright (c) 2014, Kenneth MacKay
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Copyright (C) 2017 by Intel Corporation, All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* @brief -- Interface to EC-DSA implementation.
*
* Overview: This software is an implementation of EC-DSA. This implementation
* uses curve NIST p-256.
*
* Security: The curve NIST p-256 provides approximately 128 bits of security.
*
* Usage: - To sign: Compute a hash of the data you wish to sign (SHA-2 is
* recommended) and pass it in to ecdsa_sign function along with your
* private key and a random number. You must use a new non-predictable
* random number to generate each new signature.
* - To verify a signature: Compute the hash of the signed data using
* the same hash as the signer and pass it to this function along with
* the signer's public key and the signature values (r and s).
*/
#ifndef __TC_ECC_DSA_H__
#define __TC_ECC_DSA_H__
#include <tinycrypt/ecc.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Generate an ECDSA signature for a given hash value.
* @return UECC_SUCCESS or UECC_FAILURE or UECC_FAULT_DETECTED
*
* @param p_private_key IN -- Your private key.
* @param p_message_hash IN -- The hash of the message to sign.
* @param p_hash_size IN -- The size of p_message_hash in bytes.
* @param p_signature OUT -- Will be filled in with the signature value. Must be
* at least 2 * curve size long (for secp256r1, signature must be 64 bytes long).
*
* @warning A cryptographically-secure PRNG function must be set (using
* uECC_set_rng()) before calling uECC_sign().
* @note Usage: Compute a hash of the data you wish to sign (SHA-2 is
* recommended) and pass it in to this function along with your private key.
* @note side-channel countermeasure: algorithm strengthened against timing
* attack.
*/
int uECC_sign(const uint8_t *p_private_key, const uint8_t *p_message_hash,
unsigned p_hash_size, uint8_t *p_signature);
#ifdef ENABLE_TESTS
/*
* THIS FUNCTION SHOULD BE CALLED FOR TEST PURPOSES ONLY.
* Refer to uECC_sign() function for real applications.
*/
int uECC_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash,
unsigned int hash_size, uECC_word_t *k, uint8_t *signature)
#endif
/**
* @brief Verify an ECDSA signature.
* @return returns UECC_SUCCESS if the signature is valid
* returns UECC_FAILURE if the signature is invalid.
*
* @param p_public_key IN -- The signer's public key.
* @param p_message_hash IN -- The hash of the signed data.
* @param p_hash_size IN -- The size of p_message_hash in bytes.
* @param p_signature IN -- The signature values.
*
* @note Usage: Compute the hash of the signed data using the same hash as the
* signer and pass it to this function along with the signer's public key and
* the signature values (hash_size and signature).
*/
int uECC_verify(const uint8_t *p_public_key, const uint8_t *p_message_hash,
unsigned int p_hash_size, const uint8_t *p_signature);
#ifdef __cplusplus
}
#endif
#endif /* __TC_ECC_DSA_H__ */

View file

@ -1,4 +1,5 @@
option(USE_STATIC_MBEDTLS_LIBRARY "Build mbed TLS static library." ON)
option(USE_TINYCRYPT "Include TinyCrypt." ON)
option(USE_SHARED_MBEDTLS_LIBRARY "Build mbed TLS shared library." OFF)
option(LINK_WITH_PTHREAD "Explicitly link mbed TLS library to pthread." OFF)
@ -38,14 +39,12 @@ set(src_crypto
md2.c
md4.c
md5.c
md_wrap.c
memory_buffer_alloc.c
nist_kw.c
oid.c
padlock.c
pem.c
pk.c
pk_wrap.c
pkcs12.c
pkcs5.c
pkparse.c
@ -70,12 +69,6 @@ set(src_x509
certs.c
pkcs11.c
x509.c
x509_create.c
x509_crl.c
x509_crt.c
x509_csr.c
x509write_crt.c
x509write_csr.c
)
set(src_tls
@ -131,6 +124,10 @@ if(LINK_WITH_PTHREAD)
set(libs ${libs} pthread)
endif()
if(USE_TINYCRYPT)
set(libs ${libs} tinycrypt)
endif()
if (NOT USE_STATIC_MBEDTLS_LIBRARY AND NOT USE_SHARED_MBEDTLS_LIBRARY)
message(FATAL_ERROR "Need to choose static or shared mbedtls build!")
endif(NOT USE_STATIC_MBEDTLS_LIBRARY AND NOT USE_SHARED_MBEDTLS_LIBRARY)
@ -165,15 +162,15 @@ endif(USE_STATIC_MBEDTLS_LIBRARY)
if(USE_SHARED_MBEDTLS_LIBRARY)
add_library(mbedcrypto SHARED ${src_crypto})
set_target_properties(mbedcrypto PROPERTIES VERSION 2.16.3 SOVERSION 3)
set_target_properties(mbedcrypto PROPERTIES VERSION 2.16.6 SOVERSION 3)
target_link_libraries(mbedcrypto ${libs})
add_library(mbedx509 SHARED ${src_x509})
set_target_properties(mbedx509 PROPERTIES VERSION 2.16.3 SOVERSION 0)
set_target_properties(mbedx509 PROPERTIES VERSION 2.16.6 SOVERSION 0)
target_link_libraries(mbedx509 ${libs} mbedcrypto)
add_library(mbedtls SHARED ${src_tls})
set_target_properties(mbedtls PROPERTIES VERSION 2.16.3 SOVERSION 12)
set_target_properties(mbedtls PROPERTIES VERSION 2.16.6 SOVERSION 12)
target_link_libraries(mbedtls ${libs} mbedx509)
install(TARGETS mbedtls mbedx509 mbedcrypto

View file

@ -5,7 +5,20 @@ CFLAGS ?= -O2
WARNING_CFLAGS ?= -Wall -W -Wdeclaration-after-statement
LDFLAGS ?=
LOCAL_CFLAGS = $(WARNING_CFLAGS) -I../include -D_FILE_OFFSET_BITS=64
# Check test environment. If ../library is available then Mbed TLS is used.
# Otherwise Mbed OS environment is used.
DIR_FOR_MBED_TLS_ENV=../library
ifneq "$(wildcard $(DIR_FOR_MBED_TLS_ENV) )" ""
# Set include dirs for Mbed TLS test environment
INCLUDE_DIRS=-I../include
else
# Set include dirs for Mbed OS test environment
INCLUDE_DIRS=-I../inc
CFLAGS += "-DMBEDTLS_CONFIG_FILE=\"mbedtls/test_config.h\""
endif
LOCAL_CFLAGS = $(WARNING_CFLAGS) $(INCLUDE_DIRS) -D_FILE_OFFSET_BITS=64
LOCAL_LDFLAGS =
ifdef DEBUG
@ -63,6 +76,8 @@ DLEXT = dylib
endif
endif
VPATH = ../tinycrypt
OBJS_CRYPTO= aes.o aesni.o arc4.o \
aria.o asn1parse.o asn1write.o \
base64.o bignum.o blowfish.o \
@ -75,10 +90,10 @@ OBJS_CRYPTO= aes.o aesni.o arc4.o \
error.o gcm.o havege.o \
hkdf.o \
hmac_drbg.o md.o md2.o \
md4.o md5.o md_wrap.o \
md4.o md5.o \
memory_buffer_alloc.o nist_kw.o \
oid.o padlock.o pem.o \
pk.o pk_wrap.o pkcs12.o \
pk.o pkcs12.o \
pkcs5.o pkparse.o pkwrite.o \
platform.o platform_util.o poly1305.o \
ripemd160.o rsa_internal.o rsa.o \
@ -86,9 +101,7 @@ OBJS_CRYPTO= aes.o aesni.o arc4.o \
threading.o timing.o version.o \
version_features.o xtea.o
OBJS_X509= certs.o pkcs11.o x509.o \
x509_create.o x509_crl.o x509_crt.o \
x509_csr.o x509write_crt.o x509write_csr.o
OBJS_X509= certs.o pkcs11.o x509.o
OBJS_TLS= debug.o net_sockets.o \
ssl_cache.o ssl_ciphersuites.o \
@ -96,6 +109,17 @@ OBJS_TLS= debug.o net_sockets.o \
ssl_srv.o ssl_ticket.o \
ssl_tls.o
# Default to always build TinyCrypt
ifndef TINYCRYPT_BUILD
TINYCRYPT_BUILD=1
endif
ifeq ($(TINYCRYPT_BUILD),1)
# Add TinyCrypt to the targets and Makefile path
VPATH = ../tinycrypt
OBJS_CRYPTO += ecc.o ecc_dh.o ecc_dsa.o
endif
.SILENT:
.PHONY: all static shared clean
@ -197,7 +221,7 @@ libmbedcrypto.dll: $(OBJS_CRYPTO)
clean:
ifndef WINDOWS
rm -f *.o libmbed*
rm -f *.o *.su libmbed*
else
del /Q /F *.o libmbed*
del /Q /F *.o *.su libmbed*
endif

File diff suppressed because it is too large Load diff

View file

@ -39,6 +39,7 @@
#endif
#include "mbedtls/aesni.h"
#include "mbedtls/platform_util.h"
#include <string.h>
@ -261,7 +262,7 @@ void mbedtls_aesni_inverse_key( unsigned char *invkey,
unsigned char *ik = invkey;
const unsigned char *fk = fwdkey + 16 * nr;
memcpy( ik, fk, 16 );
mbedtls_platform_memcpy( ik, fk, 16 );
for( fk -= 16, ik += 16; fk > fwdkey; fk -= 16, ik += 16 )
asm( "movdqu (%0), %%xmm0 \n\t"
@ -271,7 +272,7 @@ void mbedtls_aesni_inverse_key( unsigned char *invkey,
: "r" (fk), "r" (ik)
: "memory", "xmm0" );
memcpy( ik, fk, 16 );
mbedtls_platform_memcpy( ik, fk, 16 );
}
/*
@ -327,6 +328,7 @@ static void aesni_setkey_enc_128( unsigned char *rk,
/*
* Key expansion, 192-bit case
*/
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
static void aesni_setkey_enc_192( unsigned char *rk,
const unsigned char *key )
{
@ -380,10 +382,12 @@ static void aesni_setkey_enc_192( unsigned char *rk,
: "r" (rk), "r" (key)
: "memory", "cc", "0" );
}
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
/*
* Key expansion, 256-bit case
*/
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
static void aesni_setkey_enc_256( unsigned char *rk,
const unsigned char *key )
{
@ -446,6 +450,7 @@ static void aesni_setkey_enc_256( unsigned char *rk,
: "r" (rk), "r" (key)
: "memory", "cc", "0" );
}
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
/*
* Key expansion, wrapper
@ -457,8 +462,10 @@ int mbedtls_aesni_setkey_enc( unsigned char *rk,
switch( bits )
{
case 128: aesni_setkey_enc_128( rk, key ); break;
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
case 192: aesni_setkey_enc_192( rk, key ); break;
case 256: aesni_setkey_enc_256( rk, key ); break;
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
default : return( MBEDTLS_ERR_AES_INVALID_KEY_LENGTH );
}

View file

@ -50,7 +50,7 @@
void mbedtls_arc4_init( mbedtls_arc4_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_arc4_context ) );
mbedtls_platform_memset( ctx, 0, sizeof( mbedtls_arc4_context ) );
}
void mbedtls_arc4_free( mbedtls_arc4_context *ctx )

View file

@ -467,7 +467,7 @@ int mbedtls_aria_setkey_enc( mbedtls_aria_context *ctx,
GET_UINT32_LE( w[0][2], key, 8 );
GET_UINT32_LE( w[0][3], key, 12 );
memset( w[1], 0, 16 );
mbedtls_platform_memset( w[1], 0, 16 );
if( keybits >= 192 )
{
GET_UINT32_LE( w[1][0], key, 16 ); // 192 bit key
@ -600,7 +600,7 @@ int mbedtls_aria_crypt_ecb( mbedtls_aria_context *ctx,
void mbedtls_aria_init( mbedtls_aria_context *ctx )
{
ARIA_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_aria_context ) );
mbedtls_platform_memset( ctx, 0, sizeof( mbedtls_aria_context ) );
}
/* Clear context */
@ -640,13 +640,13 @@ int mbedtls_aria_crypt_cbc( mbedtls_aria_context *ctx,
{
while( length > 0 )
{
memcpy( temp, input, MBEDTLS_ARIA_BLOCKSIZE );
mbedtls_platform_memcpy( temp, input, MBEDTLS_ARIA_BLOCKSIZE );
mbedtls_aria_crypt_ecb( ctx, input, output );
for( i = 0; i < MBEDTLS_ARIA_BLOCKSIZE; i++ )
output[i] = (unsigned char)( output[i] ^ iv[i] );
memcpy( iv, temp, MBEDTLS_ARIA_BLOCKSIZE );
mbedtls_platform_memcpy( iv, temp, MBEDTLS_ARIA_BLOCKSIZE );
input += MBEDTLS_ARIA_BLOCKSIZE;
output += MBEDTLS_ARIA_BLOCKSIZE;
@ -661,7 +661,7 @@ int mbedtls_aria_crypt_cbc( mbedtls_aria_context *ctx,
output[i] = (unsigned char)( input[i] ^ iv[i] );
mbedtls_aria_crypt_ecb( ctx, output, output );
memcpy( iv, output, MBEDTLS_ARIA_BLOCKSIZE );
mbedtls_platform_memcpy( iv, output, MBEDTLS_ARIA_BLOCKSIZE );
input += MBEDTLS_ARIA_BLOCKSIZE;
output += MBEDTLS_ARIA_BLOCKSIZE;

View file

@ -229,6 +229,103 @@ int mbedtls_asn1_get_bitstring_null( unsigned char **p, const unsigned char *end
return( 0 );
}
void mbedtls_asn1_sequence_free( mbedtls_asn1_sequence *seq )
{
while( seq != NULL )
{
mbedtls_asn1_sequence *next = seq->next;
mbedtls_platform_zeroize( seq, sizeof( *seq ) );
mbedtls_free( seq );
seq = next;
}
}
/*
* Traverse an ASN.1 "SEQUENCE OF <tag>"
* and call a callback for each entry found.
*/
int mbedtls_asn1_traverse_sequence_of(
unsigned char **p,
const unsigned char *end,
uint8_t tag_must_mask, uint8_t tag_must_val,
uint8_t tag_may_mask, uint8_t tag_may_val,
int (*cb)( void *ctx, int tag,
unsigned char *start, size_t len ),
void *ctx )
{
int ret;
size_t len;
/* Get main sequence tag */
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
return( ret );
}
if( *p + len != end )
return( MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
while( *p < end )
{
unsigned char const tag = *(*p)++;
if( ( tag & tag_must_mask ) != tag_must_val )
return( MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
if( ( ret = mbedtls_asn1_get_len( p, end, &len ) ) != 0 )
return( ret );
if( ( tag & tag_may_mask ) == tag_may_val )
{
if( cb != NULL )
{
ret = cb( ctx, tag, *p, len );
if( ret != 0 )
return( ret );
}
}
*p += len;
}
return( 0 );
}
typedef struct
{
int tag;
mbedtls_asn1_sequence *cur;
} asn1_get_sequence_of_cb_ctx_t;
static int asn1_get_sequence_of_cb( void *ctx,
int tag,
unsigned char *start,
size_t len )
{
asn1_get_sequence_of_cb_ctx_t *cb_ctx =
(asn1_get_sequence_of_cb_ctx_t *) ctx;
mbedtls_asn1_sequence *cur =
cb_ctx->cur;
if( cur->buf.p != NULL )
{
cur->next =
mbedtls_calloc( 1, sizeof( mbedtls_asn1_sequence ) );
if( cur->next == NULL )
return( MBEDTLS_ERR_ASN1_ALLOC_FAILED );
cur = cur->next;
}
cur->buf.p = start;
cur->buf.len = len;
cur->buf.tag = tag;
cb_ctx->cur = cur;
return( 0 );
}
/*
@ -239,49 +336,11 @@ int mbedtls_asn1_get_sequence_of( unsigned char **p,
mbedtls_asn1_sequence *cur,
int tag)
{
int ret;
size_t len;
mbedtls_asn1_buf *buf;
/* Get main sequence tag */
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( ret );
if( *p + len != end )
return( MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
while( *p < end )
{
buf = &(cur->buf);
buf->tag = **p;
if( ( ret = mbedtls_asn1_get_tag( p, end, &buf->len, tag ) ) != 0 )
return( ret );
buf->p = *p;
*p += buf->len;
/* Allocate and assign next pointer */
if( *p < end )
{
cur->next = (mbedtls_asn1_sequence*)mbedtls_calloc( 1,
sizeof( mbedtls_asn1_sequence ) );
if( cur->next == NULL )
return( MBEDTLS_ERR_ASN1_ALLOC_FAILED );
cur = cur->next;
}
}
/* Set final sequence entry's next pointer to NULL */
cur->next = NULL;
if( *p != end )
return( MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
asn1_get_sequence_of_cb_ctx_t cb_ctx = { tag, cur };
mbedtls_platform_memset( cur, 0, sizeof( mbedtls_asn1_sequence ) );
return( mbedtls_asn1_traverse_sequence_of(
p, end, 0xFF, tag, 0, 0,
asn1_get_sequence_of_cb, &cb_ctx ) );
}
int mbedtls_asn1_get_alg( unsigned char **p,
@ -295,15 +354,12 @@ int mbedtls_asn1_get_alg( unsigned char **p,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( ret );
if( ( end - *p ) < 1 )
return( MBEDTLS_ERR_ASN1_OUT_OF_DATA );
alg->tag = **p;
end = *p + len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &alg->len, MBEDTLS_ASN1_OID ) ) != 0 )
return( ret );
alg->tag = MBEDTLS_ASN1_OID;
alg->p = *p;
*p += alg->len;
@ -375,7 +431,7 @@ mbedtls_asn1_named_data *mbedtls_asn1_find_named_data( mbedtls_asn1_named_data *
while( list != NULL )
{
if( list->oid.len == len &&
memcmp( list->oid.p, oid, len ) == 0 )
mbedtls_platform_memcmp( list->oid.p, oid, len ) == 0 )
{
break;
}

View file

@ -28,6 +28,7 @@
#if defined(MBEDTLS_ASN1_WRITE_C)
#include "mbedtls/asn1write.h"
#include "mbedtls/platform_util.h"
#include <string.h>
@ -123,7 +124,7 @@ int mbedtls_asn1_write_raw_buffer( unsigned char **p, unsigned char *start,
len = size;
(*p) -= len;
memcpy( *p, buf, len );
mbedtls_platform_memcpy( *p, buf, len );
return( (int) len );
}
@ -311,7 +312,7 @@ int mbedtls_asn1_write_bitstring( unsigned char **p, unsigned char *start,
byte_len--;
*--( *p ) = buf[byte_len] & ~( ( 0x1 << unused_bits ) - 1 );
( *p ) -= byte_len;
memcpy( *p, buf, byte_len );
mbedtls_platform_memcpy( *p, buf, byte_len );
}
/* Write unused bits */
@ -347,7 +348,7 @@ static mbedtls_asn1_named_data *asn1_find_named_data(
while( list != NULL )
{
if( list->oid.len == len &&
memcmp( list->oid.p, oid, len ) == 0 )
mbedtls_platform_memcmp( list->oid.p, oid, len ) == 0 )
{
break;
}
@ -383,7 +384,7 @@ mbedtls_asn1_named_data *mbedtls_asn1_store_named_data(
return( NULL );
}
memcpy( cur->oid.p, oid, oid_len );
mbedtls_platform_memcpy( cur->oid.p, oid, oid_len );
cur->val.len = val_len;
cur->val.p = mbedtls_calloc( 1, val_len );
@ -414,7 +415,7 @@ mbedtls_asn1_named_data *mbedtls_asn1_store_named_data(
}
if( val != NULL )
memcpy( cur->val.p, val, val_len );
mbedtls_platform_memcpy( cur->val.p, val, val_len );
return( cur );
}

View file

@ -260,7 +260,7 @@ int mbedtls_base64_self_test( int verbose )
src = base64_test_dec;
if( mbedtls_base64_encode( buffer, sizeof( buffer ), &len, src, 64 ) != 0 ||
memcmp( base64_test_enc, buffer, 88 ) != 0 )
memcmp( base64_test_enc, buffer, 88 ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
@ -274,7 +274,7 @@ int mbedtls_base64_self_test( int verbose )
src = base64_test_enc;
if( mbedtls_base64_decode( buffer, sizeof( buffer ), &len, src, 88 ) != 0 ||
memcmp( base64_test_dec, buffer, 64 ) != 0 )
memcmp( base64_test_dec, buffer, 64 ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );

View file

@ -127,12 +127,12 @@ int mbedtls_mpi_grow( mbedtls_mpi *X, size_t nblimbs )
if( X->n < nblimbs )
{
if( ( p = (mbedtls_mpi_uint*)mbedtls_calloc( nblimbs, ciL ) ) == NULL )
if( ( p = (mbedtls_mpi_uint *)mbedtls_calloc( nblimbs, ciL ) ) == NULL )
return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
if( X->p != NULL )
{
memcpy( p, X->p, X->n * ciL );
mbedtls_platform_memcpy( p, X->p, X->n * ciL );
mbedtls_mpi_zeroize( X->p, X->n );
mbedtls_free( X->p );
}
@ -157,9 +157,10 @@ int mbedtls_mpi_shrink( mbedtls_mpi *X, size_t nblimbs )
if( nblimbs > MBEDTLS_MPI_MAX_LIMBS )
return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
/* Actually resize up in this case */
/* Actually resize up if there are currently fewer than nblimbs limbs. */
if( X->n <= nblimbs )
return( mbedtls_mpi_grow( X, nblimbs ) );
/* After this point, then X->n > nblimbs and in particular X->n > 0. */
for( i = X->n - 1; i > 0; i-- )
if( X->p[i] != 0 )
@ -169,12 +170,12 @@ int mbedtls_mpi_shrink( mbedtls_mpi *X, size_t nblimbs )
if( i < nblimbs )
i = nblimbs;
if( ( p = (mbedtls_mpi_uint*)mbedtls_calloc( i, ciL ) ) == NULL )
if( ( p = (mbedtls_mpi_uint *)mbedtls_calloc( i, ciL ) ) == NULL )
return( MBEDTLS_ERR_MPI_ALLOC_FAILED );
if( X->p != NULL )
{
memcpy( p, X->p, i * ciL );
mbedtls_platform_memcpy( p, X->p, i * ciL );
mbedtls_mpi_zeroize( X->p, X->n );
mbedtls_free( X->p );
}
@ -198,7 +199,7 @@ int mbedtls_mpi_copy( mbedtls_mpi *X, const mbedtls_mpi *Y )
if( X == Y )
return( 0 );
if( Y->p == NULL )
if( Y->n == 0 )
{
mbedtls_mpi_free( X );
return( 0 );
@ -217,10 +218,10 @@ int mbedtls_mpi_copy( mbedtls_mpi *X, const mbedtls_mpi *Y )
}
else
{
memset( X->p + i, 0, ( X->n - i ) * ciL );
mbedtls_platform_memset( X->p + i, 0, ( X->n - i ) * ciL );
}
memcpy( X->p, Y->p, i * ciL );
mbedtls_platform_memcpy( X->p, Y->p, i * ciL );
cleanup:
@ -236,9 +237,9 @@ void mbedtls_mpi_swap( mbedtls_mpi *X, mbedtls_mpi *Y )
MPI_VALIDATE( X != NULL );
MPI_VALIDATE( Y != NULL );
memcpy( &T, X, sizeof( mbedtls_mpi ) );
memcpy( X, Y, sizeof( mbedtls_mpi ) );
memcpy( Y, &T, sizeof( mbedtls_mpi ) );
mbedtls_platform_memcpy( &T, X, sizeof( mbedtls_mpi ) );
mbedtls_platform_memcpy( X, Y, sizeof( mbedtls_mpi ) );
mbedtls_platform_memcpy( Y, &T, sizeof( mbedtls_mpi ) );
}
/*
@ -318,7 +319,7 @@ int mbedtls_mpi_lset( mbedtls_mpi *X, mbedtls_mpi_sint z )
MPI_VALIDATE_RET( X != NULL );
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, 1 ) );
memset( X->p, 0, X->n * ciL );
mbedtls_platform_memset( X->p, 0, X->n * ciL );
X->p[0] = ( z < 0 ) ? -z : z;
X->s = ( z < 0 ) ? -1 : 1;
@ -557,7 +558,7 @@ static int mpi_write_hlp( mbedtls_mpi *X, int radix,
length++;
} while( mbedtls_mpi_cmp_int( X, 0 ) != 0 );
memmove( *p, p_end, length );
MBEDTLS_MPI_CHK( mbedtls_platform_memmove( *p, p_end, length ) );
*p += length;
cleanup:
@ -673,7 +674,7 @@ int mbedtls_mpi_read_file( mbedtls_mpi *X, int radix, FILE *fin )
if( radix < 2 || radix > 16 )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
memset( s, 0, sizeof( s ) );
mbedtls_platform_memset( s, 0, sizeof( s ) );
if( fgets( s, sizeof( s ) - 1, fin ) == NULL )
return( MBEDTLS_ERR_MPI_FILE_IO_ERROR );
@ -709,7 +710,7 @@ int mbedtls_mpi_write_file( const char *p, const mbedtls_mpi *X, int radix, FILE
if( radix < 2 || radix > 16 )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
memset( s, 0, sizeof( s ) );
mbedtls_platform_memset( s, 0, sizeof( s ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_write_string( X, radix, s, sizeof( s ) - 2, &n ) );
@ -848,12 +849,12 @@ int mbedtls_mpi_read_binary( mbedtls_mpi *X, const unsigned char *buf, size_t bu
}
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );
/* Avoid calling `memcpy` with NULL source argument,
/* Avoid calling `mbedtls_platform_memcpy` with NULL source argument,
* even if buflen is 0. */
if( buf != NULL )
{
Xp = (unsigned char*) X->p;
memcpy( Xp + overhead, buf, buflen );
mbedtls_platform_memcpy( Xp + overhead, buf, buflen );
mpi_bigendian_to_host( X->p, limbs );
}
@ -888,7 +889,7 @@ int mbedtls_mpi_write_binary( const mbedtls_mpi *X,
* number. */
bytes_to_copy = stored_bytes;
p = buf + buflen - stored_bytes;
memset( buf, 0, buflen - stored_bytes );
mbedtls_platform_memset( buf, 0, buflen - stored_bytes );
}
else
{
@ -1071,6 +1072,107 @@ int mbedtls_mpi_cmp_mpi( const mbedtls_mpi *X, const mbedtls_mpi *Y )
return( 0 );
}
/** Decide if an integer is less than the other, without branches.
*
* \param x First integer.
* \param y Second integer.
*
* \return 1 if \p x is less than \p y, 0 otherwise
*/
static unsigned ct_lt_mpi_uint( const mbedtls_mpi_uint x,
const mbedtls_mpi_uint y )
{
mbedtls_mpi_uint ret;
mbedtls_mpi_uint cond;
/*
* Check if the most significant bits (MSB) of the operands are different.
*/
cond = ( x ^ y );
/*
* If the MSB are the same then the difference x-y will be negative (and
* have its MSB set to 1 during conversion to unsigned) if and only if x<y.
*/
ret = ( x - y ) & ~cond;
/*
* If the MSB are different, then the operand with the MSB of 1 is the
* bigger. (That is if y has MSB of 1, then x<y is true and it is false if
* the MSB of y is 0.)
*/
ret |= y & cond;
ret = ret >> ( biL - 1 );
return (unsigned) ret;
}
/*
* Compare signed values in constant time
*/
int mbedtls_mpi_lt_mpi_ct( const mbedtls_mpi *X, const mbedtls_mpi *Y,
unsigned *ret )
{
size_t i;
/* The value of any of these variables is either 0 or 1 at all times. */
unsigned cond, done, X_is_negative, Y_is_negative;
MPI_VALIDATE_RET( X != NULL );
MPI_VALIDATE_RET( Y != NULL );
MPI_VALIDATE_RET( ret != NULL );
if( X->n != Y->n )
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
/*
* Set sign_N to 1 if N >= 0, 0 if N < 0.
* We know that N->s == 1 if N >= 0 and N->s == -1 if N < 0.
*/
X_is_negative = ( X->s & 2 ) >> 1;
Y_is_negative = ( Y->s & 2 ) >> 1;
/*
* If the signs are different, then the positive operand is the bigger.
* That is if X is negative (X_is_negative == 1), then X < Y is true and it
* is false if X is positive (X_is_negative == 0).
*/
cond = ( X_is_negative ^ Y_is_negative );
*ret = cond & X_is_negative;
/*
* This is a constant-time function. We might have the result, but we still
* need to go through the loop. Record if we have the result already.
*/
done = cond;
for( i = X->n; i > 0; i-- )
{
/*
* If Y->p[i - 1] < X->p[i - 1] then X < Y is true if and only if both
* X and Y are negative.
*
* Again even if we can make a decision, we just mark the result and
* the fact that we are done and continue looping.
*/
cond = ct_lt_mpi_uint( Y->p[i - 1], X->p[i - 1] );
*ret |= cond & ( 1 - done ) & X_is_negative;
done |= cond;
/*
* If X->p[i - 1] < Y->p[i - 1] then X < Y is true if and only if both
* X and Y are positive.
*
* Again even if we can make a decision, we just mark the result and
* the fact that we are done and continue looping.
*/
cond = ct_lt_mpi_uint( X->p[i - 1], Y->p[i - 1] );
*ret |= cond & ( 1 - done ) & ( 1 - X_is_negative );
done |= cond;
}
return( 0 );
}
/*
* Compare signed values
*/
@ -1797,7 +1899,7 @@ static int mpi_montmul( mbedtls_mpi *A, const mbedtls_mpi *B, const mbedtls_mpi
if( T->n < N->n + 1 || T->p == NULL )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
memset( T->p, 0, T->n * ciL );
mbedtls_platform_memset( T->p, 0, T->n * ciL );
d = T->p;
n = N->n;
@ -1817,7 +1919,7 @@ static int mpi_montmul( mbedtls_mpi *A, const mbedtls_mpi *B, const mbedtls_mpi
*d++ = u0; d[n + 1] = 0;
}
memcpy( A->p, d, ( n + 1 ) * ciL );
mbedtls_platform_memcpy( A->p, d, ( n + 1 ) * ciL );
if( mbedtls_mpi_cmp_abs( A, N ) >= 0 )
mpi_sub_hlp( n, N->p, A->p );
@ -1875,7 +1977,7 @@ int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A,
mpi_montg_init( &mm, N );
mbedtls_mpi_init( &RR ); mbedtls_mpi_init( &T );
mbedtls_mpi_init( &Apos );
memset( W, 0, sizeof( W ) );
mbedtls_platform_memset( W, 0, sizeof( W ) );
i = mbedtls_mpi_bitlen( E );
@ -1913,10 +2015,10 @@ int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A,
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &RR, &RR, N ) );
if( _RR != NULL )
memcpy( _RR, &RR, sizeof( mbedtls_mpi ) );
mbedtls_platform_memcpy( _RR, &RR, sizeof( mbedtls_mpi ) );
}
else
memcpy( &RR, _RR, sizeof( mbedtls_mpi ) );
mbedtls_platform_memcpy( &RR, _RR, sizeof( mbedtls_mpi ) );
/*
* W[1] = A * R^2 * R^-1 mod N = A * R mod N

View file

@ -160,7 +160,7 @@ static void blowfish_dec( mbedtls_blowfish_context *ctx, uint32_t *xl, uint32_t
void mbedtls_blowfish_init( mbedtls_blowfish_context *ctx )
{
BLOWFISH_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_blowfish_context ) );
mbedtls_platform_memset( ctx, 0, sizeof( mbedtls_blowfish_context ) );
}
void mbedtls_blowfish_free( mbedtls_blowfish_context *ctx )
@ -293,13 +293,13 @@ int mbedtls_blowfish_crypt_cbc( mbedtls_blowfish_context *ctx,
{
while( length > 0 )
{
memcpy( temp, input, MBEDTLS_BLOWFISH_BLOCKSIZE );
mbedtls_platform_memcpy( temp, input, MBEDTLS_BLOWFISH_BLOCKSIZE );
mbedtls_blowfish_crypt_ecb( ctx, mode, input, output );
for( i = 0; i < MBEDTLS_BLOWFISH_BLOCKSIZE;i++ )
output[i] = (unsigned char)( output[i] ^ iv[i] );
memcpy( iv, temp, MBEDTLS_BLOWFISH_BLOCKSIZE );
mbedtls_platform_memcpy( iv, temp, MBEDTLS_BLOWFISH_BLOCKSIZE );
input += MBEDTLS_BLOWFISH_BLOCKSIZE;
output += MBEDTLS_BLOWFISH_BLOCKSIZE;
@ -314,7 +314,7 @@ int mbedtls_blowfish_crypt_cbc( mbedtls_blowfish_context *ctx,
output[i] = (unsigned char)( input[i] ^ iv[i] );
mbedtls_blowfish_crypt_ecb( ctx, mode, output, output );
memcpy( iv, output, MBEDTLS_BLOWFISH_BLOCKSIZE );
mbedtls_platform_memcpy( iv, output, MBEDTLS_BLOWFISH_BLOCKSIZE );
input += MBEDTLS_BLOWFISH_BLOCKSIZE;
output += MBEDTLS_BLOWFISH_BLOCKSIZE;

View file

@ -328,7 +328,7 @@ static void camellia_feistel( const uint32_t x[2], const uint32_t k[2],
void mbedtls_camellia_init( mbedtls_camellia_context *ctx )
{
CAMELLIA_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_camellia_context ) );
mbedtls_platform_memset( ctx, 0, sizeof( mbedtls_camellia_context ) );
}
void mbedtls_camellia_free( mbedtls_camellia_context *ctx )
@ -359,8 +359,8 @@ int mbedtls_camellia_setkey_enc( mbedtls_camellia_context *ctx,
RK = ctx->rk;
memset( t, 0, 64 );
memset( RK, 0, sizeof(ctx->rk) );
mbedtls_platform_memset( t, 0, 64 );
mbedtls_platform_memset( RK, 0, sizeof(ctx->rk) );
switch( keybits )
{
@ -390,7 +390,7 @@ int mbedtls_camellia_setkey_enc( mbedtls_camellia_context *ctx,
* Key storage in KC
* Order: KL, KR, KA, KB
*/
memset( KC, 0, sizeof(KC) );
mbedtls_platform_memset( KC, 0, sizeof(KC) );
/* Store KL, KR */
for( i = 0; i < 8; i++ )
@ -593,13 +593,13 @@ int mbedtls_camellia_crypt_cbc( mbedtls_camellia_context *ctx,
{
while( length > 0 )
{
memcpy( temp, input, 16 );
mbedtls_platform_memcpy( temp, input, 16 );
mbedtls_camellia_crypt_ecb( ctx, mode, input, output );
for( i = 0; i < 16; i++ )
output[i] = (unsigned char)( output[i] ^ iv[i] );
memcpy( iv, temp, 16 );
mbedtls_platform_memcpy( iv, temp, 16 );
input += 16;
output += 16;
@ -614,7 +614,7 @@ int mbedtls_camellia_crypt_cbc( mbedtls_camellia_context *ctx,
output[i] = (unsigned char)( input[i] ^ iv[i] );
mbedtls_camellia_crypt_ecb( ctx, mode, output, output );
memcpy( iv, output, 16 );
mbedtls_platform_memcpy( iv, output, 16 );
input += 16;
output += 16;

View file

@ -37,6 +37,7 @@
#if defined(MBEDTLS_CCM_C)
#include "mbedtls/ccm.h"
#include "mbedtls/platform.h"
#include "mbedtls/platform_util.h"
#include <string.h>
@ -74,7 +75,7 @@ int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx,
const unsigned char *key,
unsigned int keybits )
{
int ret;
int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
const mbedtls_cipher_info_t *cipher_info;
CCM_VALIDATE_RET( ctx != NULL );
@ -98,7 +99,7 @@ int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx,
return( ret );
}
return( 0 );
return( ret );
}
/*
@ -155,7 +156,7 @@ static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len )
{
int ret;
int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
unsigned char i;
unsigned char q;
size_t len_left, olen;
@ -201,7 +202,7 @@ static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,
b[0] |= ( ( tag_len - 2 ) / 2 ) << 3;
b[0] |= q - 1;
memcpy( b + 1, iv, iv_len );
mbedtls_platform_memcpy( b + 1, iv, iv_len );
for( i = 0, len_left = length; i < q; i++, len_left >>= 8 )
b[15-i] = (unsigned char)( len_left & 0xFF );
@ -224,12 +225,12 @@ static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,
len_left = add_len;
src = add;
memset( b, 0, 16 );
mbedtls_platform_memset( b, 0, 16 );
b[0] = (unsigned char)( ( add_len >> 8 ) & 0xFF );
b[1] = (unsigned char)( ( add_len ) & 0xFF );
use_len = len_left < 16 - 2 ? len_left : 16 - 2;
memcpy( b + 2, src, use_len );
mbedtls_platform_memcpy( b + 2, src, use_len );
len_left -= use_len;
src += use_len;
@ -239,8 +240,8 @@ static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,
{
use_len = len_left > 16 ? 16 : len_left;
memset( b, 0, 16 );
memcpy( b, src, use_len );
mbedtls_platform_memset( b, 0, 16 );
mbedtls_platform_memcpy( b, src, use_len );
UPDATE_CBC_MAC;
len_left -= use_len;
@ -259,8 +260,8 @@ static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,
* 2 .. 0 q - 1
*/
ctr[0] = q - 1;
memcpy( ctr + 1, iv, iv_len );
memset( ctr + 1 + iv_len, 0, q );
mbedtls_platform_memcpy( ctr + 1, iv, iv_len );
mbedtls_platform_memset( ctr + 1 + iv_len, 0, q );
ctr[15] = 1;
/*
@ -279,8 +280,8 @@ static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,
if( mode == CCM_ENCRYPT )
{
memset( b, 0, 16 );
memcpy( b, src, use_len );
mbedtls_platform_memset( b, 0, 16 );
mbedtls_platform_memcpy( b, src, use_len );
UPDATE_CBC_MAC;
}
@ -288,8 +289,8 @@ static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,
if( mode == CCM_DECRYPT )
{
memset( b, 0, 16 );
memcpy( b, dst, use_len );
mbedtls_platform_memset( b, 0, 16 );
mbedtls_platform_memcpy( b, dst, use_len );
UPDATE_CBC_MAC;
}
@ -313,9 +314,9 @@ static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,
ctr[15-i] = 0;
CTR_CRYPT( y, y, 16 );
memcpy( tag, y, tag_len );
mbedtls_platform_memcpy( tag, y, tag_len );
return( 0 );
return( ret );
}
/*
@ -365,7 +366,7 @@ int mbedtls_ccm_star_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *input, unsigned char *output,
const unsigned char *tag, size_t tag_len )
{
int ret;
int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
unsigned char check_tag[16];
unsigned char i;
int diff;
@ -394,7 +395,7 @@ int mbedtls_ccm_star_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
return( MBEDTLS_ERR_CCM_AUTH_FAILED );
}
return( 0 );
return( ret );
}
int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
@ -505,7 +506,7 @@ int mbedtls_ccm_self_test( int verbose )
ciphertext + msg_len[i], tag_len[i] );
if( ret != 0 ||
memcmp( ciphertext, res[i], msg_len[i] + tag_len[i] ) != 0 )
memcmp( ciphertext, res[i], msg_len[i] + tag_len[i] ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
@ -520,7 +521,7 @@ int mbedtls_ccm_self_test( int verbose )
ciphertext + msg_len[i], tag_len[i] );
if( ret != 0 ||
memcmp( plaintext, msg, msg_len[i] ) != 0 )
memcmp( plaintext, msg, msg_len[i] ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );

View file

@ -42,6 +42,101 @@
*
*/
/* Use CRTs with Secp256r1-only if Secp384r1 is disabled.
* Otherwise, fall back to previous test CRTs using both
* Secp256r1 and Secp384r1. */
#if !defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
/* This is taken from tests/data_files/test-ca3.crt.pem */
/* BEGIN FILE string macro TEST_CA_CRT_EC_PEM tests/data_files/test-ca3.crt.pem */
#define TEST_CA_CRT_EC_PEM \
"-----BEGIN CERTIFICATE-----\r\n" \
"MIIBuTCCAV2gAwIBAgIBATAMBggqhkjOPQQDAgUAMDsxGjAYBgNVBAMMEVRlc3Qg\r\n" \
"Q0EgU2VjcDI1NnIxMRAwDgYDVQQKDAdNYmVkVExTMQswCQYDVQQGEwJVSzAeFw0w\r\n" \
"MTAxMDEwMDAwMDBaFw0zMDEyMzEyMzU5NTlaMDsxGjAYBgNVBAMMEVRlc3QgQ0Eg\r\n" \
"U2VjcDI1NnIxMRAwDgYDVQQKDAdNYmVkVExTMQswCQYDVQQGEwJVSzBZMBMGByqG\r\n" \
"SM49AgEGCCqGSM49AwEHA0IABLZIHgilzw/iCx1r09kyZsZfarzztX4y1km0S5Mx\r\n" \
"rsFB67NjUhXE6/YY3W38oxeY4eIvEb516BOR/g3e3OL7Q8WjUDBOMAwGA1UdEwQF\r\n" \
"MAMBAf8wHQYDVR0OBBYEFEpepGEzSxZIDDF4IjXW+85Q5yASMB8GA1UdIwQYMBaA\r\n" \
"FEpepGEzSxZIDDF4IjXW+85Q5yASMAwGCCqGSM49BAMCBQADSAAwRQIhAKejV1jK\r\n" \
"vPH1vIsZAr6/VmSvjXkxmT2rpzEP9iJvJAteAiBhCPtV7LdSF1ZUqphAK3DYh2m7\r\n" \
"l1eSxSKXB29adbF96g==\r\n" \
"-----END CERTIFICATE-----\r\n"
/* END FILE */
/* This is generated from tests/data_files/test-ca3.crt.der using `xxd -i`. */
/* BEGIN FILE binary macro TEST_CA_CRT_EC_DER tests/data_files/test-ca3.crt.der */
#define TEST_CA_CRT_EC_DER { \
0x30, 0x82, 0x01, 0xb9, 0x30, 0x82, 0x01, 0x5d, 0xa0, 0x03, 0x02, 0x01, \
0x02, 0x02, 0x01, 0x01, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, \
0x3d, 0x04, 0x03, 0x02, 0x05, 0x00, 0x30, 0x3b, 0x31, 0x1a, 0x30, 0x18, \
0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x11, 0x54, 0x65, 0x73, 0x74, 0x20, \
0x43, 0x41, 0x20, 0x53, 0x65, 0x63, 0x70, 0x32, 0x35, 0x36, 0x72, 0x31, \
0x31, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x07, 0x4d, \
0x62, 0x65, 0x64, 0x54, 0x4c, 0x53, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, \
0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x4b, 0x30, 0x1e, 0x17, 0x0d, 0x30, \
0x31, 0x30, 0x31, 0x30, 0x31, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x5a, \
0x17, 0x0d, 0x33, 0x30, 0x31, 0x32, 0x33, 0x31, 0x32, 0x33, 0x35, 0x39, \
0x35, 0x39, 0x5a, 0x30, 0x3b, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, \
0x04, 0x03, 0x0c, 0x11, 0x54, 0x65, 0x73, 0x74, 0x20, 0x43, 0x41, 0x20, \
0x53, 0x65, 0x63, 0x70, 0x32, 0x35, 0x36, 0x72, 0x31, 0x31, 0x10, 0x30, \
0x0e, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x07, 0x4d, 0x62, 0x65, 0x64, \
0x54, 0x4c, 0x53, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, \
0x13, 0x02, 0x55, 0x4b, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, \
0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, \
0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xb6, 0x48, 0x1e, 0x08, 0xa5, \
0xcf, 0x0f, 0xe2, 0x0b, 0x1d, 0x6b, 0xd3, 0xd9, 0x32, 0x66, 0xc6, 0x5f, \
0x6a, 0xbc, 0xf3, 0xb5, 0x7e, 0x32, 0xd6, 0x49, 0xb4, 0x4b, 0x93, 0x31, \
0xae, 0xc1, 0x41, 0xeb, 0xb3, 0x63, 0x52, 0x15, 0xc4, 0xeb, 0xf6, 0x18, \
0xdd, 0x6d, 0xfc, 0xa3, 0x17, 0x98, 0xe1, 0xe2, 0x2f, 0x11, 0xbe, 0x75, \
0xe8, 0x13, 0x91, 0xfe, 0x0d, 0xde, 0xdc, 0xe2, 0xfb, 0x43, 0xc5, 0xa3, \
0x50, 0x30, 0x4e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x05, \
0x30, 0x03, 0x01, 0x01, 0xff, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, \
0x04, 0x16, 0x04, 0x14, 0x4a, 0x5e, 0xa4, 0x61, 0x33, 0x4b, 0x16, 0x48, \
0x0c, 0x31, 0x78, 0x22, 0x35, 0xd6, 0xfb, 0xce, 0x50, 0xe7, 0x20, 0x12, \
0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, \
0x14, 0x4a, 0x5e, 0xa4, 0x61, 0x33, 0x4b, 0x16, 0x48, 0x0c, 0x31, 0x78, \
0x22, 0x35, 0xd6, 0xfb, 0xce, 0x50, 0xe7, 0x20, 0x12, 0x30, 0x0c, 0x06, \
0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x05, 0x00, 0x03, \
0x48, 0x00, 0x30, 0x45, 0x02, 0x21, 0x00, 0xa7, 0xa3, 0x57, 0x58, 0xca, \
0xbc, 0xf1, 0xf5, 0xbc, 0x8b, 0x19, 0x02, 0xbe, 0xbf, 0x56, 0x64, 0xaf, \
0x8d, 0x79, 0x31, 0x99, 0x3d, 0xab, 0xa7, 0x31, 0x0f, 0xf6, 0x22, 0x6f, \
0x24, 0x0b, 0x5e, 0x02, 0x20, 0x61, 0x08, 0xfb, 0x55, 0xec, 0xb7, 0x52, \
0x17, 0x56, 0x54, 0xaa, 0x98, 0x40, 0x2b, 0x70, 0xd8, 0x87, 0x69, 0xbb, \
0x97, 0x57, 0x92, 0xc5, 0x22, 0x97, 0x07, 0x6f, 0x5a, 0x75, 0xb1, 0x7d, \
0xea \
}
/* END FILE */
/* This is taken from tests/data_files/test-ca3.key.pem */
/* BEGIN FILE string macro TEST_CA_KEY_EC_PEM tests/data_files/test-ca3.key.pem */
#define TEST_CA_KEY_EC_PEM \
"-----BEGIN EC PRIVATE KEY-----\r\n" \
"MHcCAQEEIDlfIVA04pd23r9UJhLf0kt6SkROecrhPbNWtawigBCkoAoGCCqGSM49\r\n" \
"AwEHoUQDQgAEtkgeCKXPD+ILHWvT2TJmxl9qvPO1fjLWSbRLkzGuwUHrs2NSFcTr\r\n" \
"9hjdbfyjF5jh4i8RvnXoE5H+Dd7c4vtDxQ==\r\n" \
"-----END EC PRIVATE KEY-----\r\n"
/* END FILE */
/* This is generated from tests/data_files/test-ca3.key.der using `xxd -i`. */
/* BEGIN FILE binary macro TEST_CA_KEY_EC_DER tests/data_files/test-ca3.key.der */
#define TEST_CA_KEY_EC_DER { \
0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20, 0x39, 0x5f, 0x21, 0x50, 0x34, \
0xe2, 0x97, 0x76, 0xde, 0xbf, 0x54, 0x26, 0x12, 0xdf, 0xd2, 0x4b, 0x7a, \
0x4a, 0x44, 0x4e, 0x79, 0xca, 0xe1, 0x3d, 0xb3, 0x56, 0xb5, 0xac, 0x22, \
0x80, 0x10, 0xa4, 0xa0, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, \
0x03, 0x01, 0x07, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0xb6, 0x48, 0x1e, \
0x08, 0xa5, 0xcf, 0x0f, 0xe2, 0x0b, 0x1d, 0x6b, 0xd3, 0xd9, 0x32, 0x66, \
0xc6, 0x5f, 0x6a, 0xbc, 0xf3, 0xb5, 0x7e, 0x32, 0xd6, 0x49, 0xb4, 0x4b, \
0x93, 0x31, 0xae, 0xc1, 0x41, 0xeb, 0xb3, 0x63, 0x52, 0x15, 0xc4, 0xeb, \
0xf6, 0x18, 0xdd, 0x6d, 0xfc, 0xa3, 0x17, 0x98, 0xe1, 0xe2, 0x2f, 0x11, \
0xbe, 0x75, 0xe8, 0x13, 0x91, 0xfe, 0x0d, 0xde, 0xdc, 0xe2, 0xfb, 0x43, \
0xc5 \
}
/* END FILE */
#else /* !MBEDTLS_ECP_DP_SECP384R1_ENABLED */
/* This is taken from tests/data_files/test-ca2.crt */
/* BEGIN FILE string macro TEST_CA_CRT_EC_PEM tests/data_files/test-ca2.crt */
#define TEST_CA_CRT_EC_PEM \
@ -146,6 +241,10 @@
}
/* END FILE */
#endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */
#define TEST_CA_PWD_EC_PEM "PolarSSLTest"
/* This is taken from tests/data_files/test-ca-sha256.crt. */
/* BEGIN FILE string macro TEST_CA_CRT_RSA_SHA256_PEM tests/data_files/test-ca-sha256.crt */
#define TEST_CA_CRT_RSA_SHA256_PEM \
@ -505,6 +604,100 @@
* - multiple EC curve types
*/
/* Use CRTs with Secp256r1-only if Secp384r1 is disabled.
* Otherwise, fall back to previous test CRTs using both
* Secp256r1 and Secp384r1. */
#if !defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
/* This is taken from tests/data_files/server11.crt.pem. */
/* BEGIN FILE string macro TEST_SRV_CRT_EC_PEM tests/data_files/server11.crt.pem */
#define TEST_SRV_CRT_EC_PEM \
"-----BEGIN CERTIFICATE-----\r\n" \
"MIIBrzCCAVKgAwIBAgIBATAMBggqhkjOPQQDAgUAMDsxGjAYBgNVBAMMEVRlc3Qg\r\n" \
"Q0EgU2VjcDI1NnIxMRAwDgYDVQQKDAdNYmVkVExTMQswCQYDVQQGEwJVSzAeFw0w\r\n" \
"MTAxMDEwMDAwMDBaFw0zMDEyMzEyMzU5NTlaMDMxEjAQBgNVBAMMCWxvY2FsaG9z\r\n" \
"dDEQMA4GA1UECgwHTWJlZFRMUzELMAkGA1UEBhMCVUswWTATBgcqhkjOPQIBBggq\r\n" \
"hkjOPQMBBwNCAATH4k2I+9HG/2AM4cN0pPkfO62ddKWwtDsdFezZoKxwXYm0ClZe\r\n" \
"zZYmfpl8x5Q7+V2oGg3TXoC8TOmXjAtabfDNo00wSzAJBgNVHRMEAjAAMB0GA1Ud\r\n" \
"DgQWBBQjXj0e2wlEVpSCbySpu2oDJgn7sjAfBgNVHSMEGDAWgBRKXqRhM0sWSAwx\r\n" \
"eCI11vvOUOcgEjAMBggqhkjOPQQDAgUAA0kAMEYCIQCN7/F5DbM4Ug5NcKHeKFbb\r\n" \
"3EHpsBjg0//gXa9mJ7Q4jAIhAIzio6vwCYnzrslzsTbPpmtU+6Op6SlzdGO/iR77\r\n" \
"bcfp\r\n" \
"-----END CERTIFICATE-----\r\n"
/* END FILE */
/* This is generated from tests/data_files/server11.crt.der using `xxd -i`. */
/* BEGIN FILE binary macro TEST_SRV_CRT_EC_DER tests/data_files/server11.crt.der */
#define TEST_SRV_CRT_EC_DER { \
0x30, 0x82, 0x01, 0xaf, 0x30, 0x82, 0x01, 0x52, 0xa0, 0x03, 0x02, 0x01, \
0x02, 0x02, 0x01, 0x01, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, \
0x3d, 0x04, 0x03, 0x02, 0x05, 0x00, 0x30, 0x3b, 0x31, 0x1a, 0x30, 0x18, \
0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x11, 0x54, 0x65, 0x73, 0x74, 0x20, \
0x43, 0x41, 0x20, 0x53, 0x65, 0x63, 0x70, 0x32, 0x35, 0x36, 0x72, 0x31, \
0x31, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x07, 0x4d, \
0x62, 0x65, 0x64, 0x54, 0x4c, 0x53, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, \
0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x4b, 0x30, 0x1e, 0x17, 0x0d, 0x30, \
0x31, 0x30, 0x31, 0x30, 0x31, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x5a, \
0x17, 0x0d, 0x33, 0x30, 0x31, 0x32, 0x33, 0x31, 0x32, 0x33, 0x35, 0x39, \
0x35, 0x39, 0x5a, 0x30, 0x33, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, \
0x04, 0x03, 0x0c, 0x09, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73, \
0x74, 0x31, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x07, \
0x4d, 0x62, 0x65, 0x64, 0x54, 0x4c, 0x53, 0x31, 0x0b, 0x30, 0x09, 0x06, \
0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x4b, 0x30, 0x59, 0x30, 0x13, \
0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, \
0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xc7, \
0xe2, 0x4d, 0x88, 0xfb, 0xd1, 0xc6, 0xff, 0x60, 0x0c, 0xe1, 0xc3, 0x74, \
0xa4, 0xf9, 0x1f, 0x3b, 0xad, 0x9d, 0x74, 0xa5, 0xb0, 0xb4, 0x3b, 0x1d, \
0x15, 0xec, 0xd9, 0xa0, 0xac, 0x70, 0x5d, 0x89, 0xb4, 0x0a, 0x56, 0x5e, \
0xcd, 0x96, 0x26, 0x7e, 0x99, 0x7c, 0xc7, 0x94, 0x3b, 0xf9, 0x5d, 0xa8, \
0x1a, 0x0d, 0xd3, 0x5e, 0x80, 0xbc, 0x4c, 0xe9, 0x97, 0x8c, 0x0b, 0x5a, \
0x6d, 0xf0, 0xcd, 0xa3, 0x4d, 0x30, 0x4b, 0x30, 0x09, 0x06, 0x03, 0x55, \
0x1d, 0x13, 0x04, 0x02, 0x30, 0x00, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, \
0x0e, 0x04, 0x16, 0x04, 0x14, 0x23, 0x5e, 0x3d, 0x1e, 0xdb, 0x09, 0x44, \
0x56, 0x94, 0x82, 0x6f, 0x24, 0xa9, 0xbb, 0x6a, 0x03, 0x26, 0x09, 0xfb, \
0xb2, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, \
0x80, 0x14, 0x4a, 0x5e, 0xa4, 0x61, 0x33, 0x4b, 0x16, 0x48, 0x0c, 0x31, \
0x78, 0x22, 0x35, 0xd6, 0xfb, 0xce, 0x50, 0xe7, 0x20, 0x12, 0x30, 0x0c, \
0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x05, 0x00, \
0x03, 0x49, 0x00, 0x30, 0x46, 0x02, 0x21, 0x00, 0x8d, 0xef, 0xf1, 0x79, \
0x0d, 0xb3, 0x38, 0x52, 0x0e, 0x4d, 0x70, 0xa1, 0xde, 0x28, 0x56, 0xdb, \
0xdc, 0x41, 0xe9, 0xb0, 0x18, 0xe0, 0xd3, 0xff, 0xe0, 0x5d, 0xaf, 0x66, \
0x27, 0xb4, 0x38, 0x8c, 0x02, 0x21, 0x00, 0x8c, 0xe2, 0xa3, 0xab, 0xf0, \
0x09, 0x89, 0xf3, 0xae, 0xc9, 0x73, 0xb1, 0x36, 0xcf, 0xa6, 0x6b, 0x54, \
0xfb, 0xa3, 0xa9, 0xe9, 0x29, 0x73, 0x74, 0x63, 0xbf, 0x89, 0x1e, 0xfb, \
0x6d, 0xc7, 0xe9 \
}
/* END FILE */
/* This is taken from tests/data_files/server11.key.pem. */
/* BEGIN FILE string macro TEST_SRV_KEY_EC_PEM tests/data_files/server11.key.pem */
#define TEST_SRV_KEY_EC_PEM \
"-----BEGIN EC PRIVATE KEY-----\r\n" \
"MHcCAQEEIGEWs7/9cQHgEI5v2qeQRGLoFhjrNK4lul6tmcqDACKuoAoGCCqGSM49\r\n" \
"AwEHoUQDQgAEx+JNiPvRxv9gDOHDdKT5HzutnXSlsLQ7HRXs2aCscF2JtApWXs2W\r\n" \
"Jn6ZfMeUO/ldqBoN016AvEzpl4wLWm3wzQ==\r\n" \
"-----END EC PRIVATE KEY-----\r\n"
/* END FILE */
/* This is generated from tests/data_files/server11.key.der using `xxd -i`. */
/* BEGIN FILE binary macro TEST_SRV_KEY_EC_DER tests/data_files/server11.key.der */
#define TEST_SRV_KEY_EC_DER { \
0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20, 0x61, 0x16, 0xb3, 0xbf, 0xfd, \
0x71, 0x01, 0xe0, 0x10, 0x8e, 0x6f, 0xda, 0xa7, 0x90, 0x44, 0x62, 0xe8, \
0x16, 0x18, 0xeb, 0x34, 0xae, 0x25, 0xba, 0x5e, 0xad, 0x99, 0xca, 0x83, \
0x00, 0x22, 0xae, 0xa0, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, \
0x03, 0x01, 0x07, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0xc7, 0xe2, 0x4d, \
0x88, 0xfb, 0xd1, 0xc6, 0xff, 0x60, 0x0c, 0xe1, 0xc3, 0x74, 0xa4, 0xf9, \
0x1f, 0x3b, 0xad, 0x9d, 0x74, 0xa5, 0xb0, 0xb4, 0x3b, 0x1d, 0x15, 0xec, \
0xd9, 0xa0, 0xac, 0x70, 0x5d, 0x89, 0xb4, 0x0a, 0x56, 0x5e, 0xcd, 0x96, \
0x26, 0x7e, 0x99, 0x7c, 0xc7, 0x94, 0x3b, 0xf9, 0x5d, 0xa8, 0x1a, 0x0d, \
0xd3, 0x5e, 0x80, 0xbc, 0x4c, 0xe9, 0x97, 0x8c, 0x0b, 0x5a, 0x6d, 0xf0, \
0xcd \
}
/* END FILE */
#else /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */
/* This is taken from tests/data_files/server5.crt. */
/* BEGIN FILE string macro TEST_SRV_CRT_EC_PEM tests/data_files/server5.crt */
#define TEST_SRV_CRT_EC_PEM \
@ -603,6 +796,8 @@
}
/* END FILE */
#endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */
/* This is taken from tests/data_files/server2-sha256.crt. */
/* BEGIN FILE string macro TEST_SRV_CRT_RSA_SHA256_PEM tests/data_files/server2-sha256.crt */
#define TEST_SRV_CRT_RSA_SHA256_PEM \
@ -954,6 +1149,101 @@
* - multiple EC curve types
*/
/* Use CRTs with Secp256r1-only if Secp384r1 is disabled.
* Otherwise, fall back to previous test CRTs using both
* Secp256r1 and Secp384r1. */
#if !defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
/* This is taken from tests/data_files/cli3.crt. */
/* BEGIN FILE string macro TEST_CLI_CRT_EC_PEM tests/data_files/cli3.crt.pem */
#define TEST_CLI_CRT_EC_PEM \
"-----BEGIN CERTIFICATE-----\r\n" \
"MIIBuTCCAVygAwIBAgIBATAMBggqhkjOPQQDAgUAMDsxGjAYBgNVBAMMEVRlc3Qg\r\n" \
"Q0EgU2VjcDI1NnIxMRAwDgYDVQQKDAdNYmVkVExTMQswCQYDVQQGEwJVSzAeFw0w\r\n" \
"MTAxMDEwMDAwMDBaFw0zMDEyMzEyMzU5NTlaMD0xHDAaBgNVBAMME1Rlc3QgQ1JU\r\n" \
"MiBTZWNwMjU2cjExEDAOBgNVBAoMB01iZWRUTFMxCzAJBgNVBAYTAlVLMFkwEwYH\r\n" \
"KoZIzj0CAQYIKoZIzj0DAQcDQgAEEm+TJ4LBB85IBjWNcNIodr2L06CZqLbVClmH\r\n" \
"uxPqiZafsAZDl0lqgL6cCigF/ML2EqFyKW+Oext3uAmNkemj6aNNMEswCQYDVR0T\r\n" \
"BAIwADAdBgNVHQ4EFgQUF9Yq9UkoSClnXwrdghuhrokH/hIwHwYDVR0jBBgwFoAU\r\n" \
"Sl6kYTNLFkgMMXgiNdb7zlDnIBIwDAYIKoZIzj0EAwIFAANJADBGAiEAg3UsTyLd\r\n" \
"vCPRG13gbf1R8gb85g4K1VbZ+CKl58HW2VgCIQDXk/8WFrt7vA+m3L1xJxj8iln9\r\n" \
"wMR16i9Fqykw7cqsRw==\r\n" \
"-----END CERTIFICATE-----\r\n"
/* END FILE */
/* This is generated from tests/data_files/cli3.crt.der using `xxd -i`. */
/* BEGIN FILE binary macro TEST_CLI_CRT_EC_DER tests/data_files/cli3.crt.der */
#define TEST_CLI_CRT_EC_DER { \
0x30, 0x82, 0x01, 0xb9, 0x30, 0x82, 0x01, 0x5c, 0xa0, 0x03, 0x02, 0x01, \
0x02, 0x02, 0x01, 0x01, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, \
0x3d, 0x04, 0x03, 0x02, 0x05, 0x00, 0x30, 0x3b, 0x31, 0x1a, 0x30, 0x18, \
0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x11, 0x54, 0x65, 0x73, 0x74, 0x20, \
0x43, 0x41, 0x20, 0x53, 0x65, 0x63, 0x70, 0x32, 0x35, 0x36, 0x72, 0x31, \
0x31, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x07, 0x4d, \
0x62, 0x65, 0x64, 0x54, 0x4c, 0x53, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, \
0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x4b, 0x30, 0x1e, 0x17, 0x0d, 0x30, \
0x31, 0x30, 0x31, 0x30, 0x31, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x5a, \
0x17, 0x0d, 0x33, 0x30, 0x31, 0x32, 0x33, 0x31, 0x32, 0x33, 0x35, 0x39, \
0x35, 0x39, 0x5a, 0x30, 0x3d, 0x31, 0x1c, 0x30, 0x1a, 0x06, 0x03, 0x55, \
0x04, 0x03, 0x0c, 0x13, 0x54, 0x65, 0x73, 0x74, 0x20, 0x43, 0x52, 0x54, \
0x32, 0x20, 0x53, 0x65, 0x63, 0x70, 0x32, 0x35, 0x36, 0x72, 0x31, 0x31, \
0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x07, 0x4d, 0x62, \
0x65, 0x64, 0x54, 0x4c, 0x53, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, \
0x04, 0x06, 0x13, 0x02, 0x55, 0x4b, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, \
0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, \
0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x12, 0x6f, 0x93, \
0x27, 0x82, 0xc1, 0x07, 0xce, 0x48, 0x06, 0x35, 0x8d, 0x70, 0xd2, 0x28, \
0x76, 0xbd, 0x8b, 0xd3, 0xa0, 0x99, 0xa8, 0xb6, 0xd5, 0x0a, 0x59, 0x87, \
0xbb, 0x13, 0xea, 0x89, 0x96, 0x9f, 0xb0, 0x06, 0x43, 0x97, 0x49, 0x6a, \
0x80, 0xbe, 0x9c, 0x0a, 0x28, 0x05, 0xfc, 0xc2, 0xf6, 0x12, 0xa1, 0x72, \
0x29, 0x6f, 0x8e, 0x7b, 0x1b, 0x77, 0xb8, 0x09, 0x8d, 0x91, 0xe9, 0xa3, \
0xe9, 0xa3, 0x4d, 0x30, 0x4b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, \
0x04, 0x02, 0x30, 0x00, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, \
0x16, 0x04, 0x14, 0x17, 0xd6, 0x2a, 0xf5, 0x49, 0x28, 0x48, 0x29, 0x67, \
0x5f, 0x0a, 0xdd, 0x82, 0x1b, 0xa1, 0xae, 0x89, 0x07, 0xfe, 0x12, 0x30, \
0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, \
0x4a, 0x5e, 0xa4, 0x61, 0x33, 0x4b, 0x16, 0x48, 0x0c, 0x31, 0x78, 0x22, \
0x35, 0xd6, 0xfb, 0xce, 0x50, 0xe7, 0x20, 0x12, 0x30, 0x0c, 0x06, 0x08, \
0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x05, 0x00, 0x03, 0x49, \
0x00, 0x30, 0x46, 0x02, 0x21, 0x00, 0x83, 0x75, 0x2c, 0x4f, 0x22, 0xdd, \
0xbc, 0x23, 0xd1, 0x1b, 0x5d, 0xe0, 0x6d, 0xfd, 0x51, 0xf2, 0x06, 0xfc, \
0xe6, 0x0e, 0x0a, 0xd5, 0x56, 0xd9, 0xf8, 0x22, 0xa5, 0xe7, 0xc1, 0xd6, \
0xd9, 0x58, 0x02, 0x21, 0x00, 0xd7, 0x93, 0xff, 0x16, 0x16, 0xbb, 0x7b, \
0xbc, 0x0f, 0xa6, 0xdc, 0xbd, 0x71, 0x27, 0x18, 0xfc, 0x8a, 0x59, 0xfd, \
0xc0, 0xc4, 0x75, 0xea, 0x2f, 0x45, 0xab, 0x29, 0x30, 0xed, 0xca, 0xac, \
0x47 \
}
/* END FILE */
/* This is taken from tests/data_files/cli3.key.pem. */
/* BEGIN FILE string macro TEST_CLI_KEY_EC_PEM tests/data_files/cli3.key.pem */
#define TEST_CLI_KEY_EC_PEM \
"-----BEGIN EC PRIVATE KEY-----\r\n" \
"MHcCAQEEIGFE8JJMBKeo1BnPGgzGae1stIrWdEaUvjo9xO8OTC5QoAoGCCqGSM49\r\n" \
"AwEHoUQDQgAEEm+TJ4LBB85IBjWNcNIodr2L06CZqLbVClmHuxPqiZafsAZDl0lq\r\n" \
"gL6cCigF/ML2EqFyKW+Oext3uAmNkemj6Q==\r\n" \
"-----END EC PRIVATE KEY-----\r\n"
/* END FILE */
/* This is generated from tests/data_files/cli3.key.der using `xxd -i`. */
/* BEGIN FILE binary macro TEST_CLI_KEY_EC_DER tests/data_files/cli3.key.der */
#define TEST_CLI_KEY_EC_DER { \
0x30, 0x77, 0x02, 0x01, 0x01, 0x04, 0x20, 0x61, 0x44, 0xf0, 0x92, 0x4c, \
0x04, 0xa7, 0xa8, 0xd4, 0x19, 0xcf, 0x1a, 0x0c, 0xc6, 0x69, 0xed, 0x6c, \
0xb4, 0x8a, 0xd6, 0x74, 0x46, 0x94, 0xbe, 0x3a, 0x3d, 0xc4, 0xef, 0x0e, \
0x4c, 0x2e, 0x50, 0xa0, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, \
0x03, 0x01, 0x07, 0xa1, 0x44, 0x03, 0x42, 0x00, 0x04, 0x12, 0x6f, 0x93, \
0x27, 0x82, 0xc1, 0x07, 0xce, 0x48, 0x06, 0x35, 0x8d, 0x70, 0xd2, 0x28, \
0x76, 0xbd, 0x8b, 0xd3, 0xa0, 0x99, 0xa8, 0xb6, 0xd5, 0x0a, 0x59, 0x87, \
0xbb, 0x13, 0xea, 0x89, 0x96, 0x9f, 0xb0, 0x06, 0x43, 0x97, 0x49, 0x6a, \
0x80, 0xbe, 0x9c, 0x0a, 0x28, 0x05, 0xfc, 0xc2, 0xf6, 0x12, 0xa1, 0x72, \
0x29, 0x6f, 0x8e, 0x7b, 0x1b, 0x77, 0xb8, 0x09, 0x8d, 0x91, 0xe9, 0xa3, \
0xe9 \
}
/* END FILE */
#else /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */
/* This is taken from tests/data_files/cli2.crt. */
/* BEGIN FILE string macro TEST_CLI_CRT_EC_PEM tests/data_files/cli2.crt */
#define TEST_CLI_CRT_EC_PEM \
@ -1046,6 +1336,8 @@
}
/* END FILE */
#endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */
/* This is taken from tests/data_files/cli-rsa-sha256.crt. */
/* BEGIN FILE string macro TEST_CLI_CRT_RSA_PEM tests/data_files/cli-rsa-sha256.crt */
#define TEST_CLI_CRT_RSA_PEM \
@ -1683,9 +1975,9 @@ const char * mbedtls_test_cas[] = {
#if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_SHA256_C)
mbedtls_test_ca_crt_rsa_sha256,
#endif
#if defined(MBEDTLS_ECDSA_C)
#if defined(MBEDTLS_ECDSA_C) || defined(MBEDTLS_USE_TINYCRYPT)
mbedtls_test_ca_crt_ec,
#endif
#endif /* MBEDTLS_ECDSA_C || MBEDTLS_USE_TINYCRYPT */
NULL
};
const size_t mbedtls_test_cas_len[] = {
@ -1695,9 +1987,9 @@ const size_t mbedtls_test_cas_len[] = {
#if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_SHA256_C)
sizeof( mbedtls_test_ca_crt_rsa_sha256 ),
#endif
#if defined(MBEDTLS_ECDSA_C)
#if defined(MBEDTLS_ECDSA_C) || defined(MBEDTLS_USE_TINYCRYPT)
sizeof( mbedtls_test_ca_crt_ec ),
#endif
#endif /* MBEDTLS_ECDSA_C || MBEDTLS_USE_TINYCRYPT */
0
};
@ -1711,9 +2003,9 @@ const unsigned char * mbedtls_test_cas_der[] = {
mbedtls_test_ca_crt_rsa_sha1_der,
#endif /* MBEDTLS_SHA1_C */
#endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_ECDSA_C)
#if defined(MBEDTLS_ECDSA_C) || defined(MBEDTLS_USE_TINYCRYPT)
mbedtls_test_ca_crt_ec_der,
#endif /* MBEDTLS_ECDSA_C */
#endif /* MBEDTLS_ECDSA_C || MBEDTLS_USE_TINYCRYPT */
NULL
};
@ -1726,9 +2018,9 @@ const size_t mbedtls_test_cas_der_len[] = {
sizeof( mbedtls_test_ca_crt_rsa_sha1_der ),
#endif /* MBEDTLS_SHA1_C */
#endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_ECDSA_C)
#if defined(MBEDTLS_ECDSA_C) || defined(MBEDTLS_USE_TINYCRYPT)
sizeof( mbedtls_test_ca_crt_ec_der ),
#endif /* MBEDTLS_ECDSA_C */
#endif /* MBEDTLS_ECDSA_C || MBEDTLS_USE_TINYCRYPT */
0
};
@ -1743,9 +2035,9 @@ const char mbedtls_test_cas_pem[] =
TEST_CA_CRT_RSA_SHA1_PEM
#endif /* MBEDTLS_SHA1_C */
#endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_ECDSA_C)
#if defined(MBEDTLS_ECDSA_C) || defined(MBEDTLS_USE_TINYCRYPT)
TEST_CA_CRT_EC_PEM
#endif /* MBEDTLS_ECDSA_C */
#endif /* MBEDTLS_ECDSA_C || MBEDTLS_USE_TINYCRYPT */
"";
const size_t mbedtls_test_cas_pem_len = sizeof( mbedtls_test_cas_pem );
#endif /* MBEDTLS_PEM_PARSE_C */

View file

@ -148,7 +148,7 @@ static void chacha20_block( const uint32_t initial_state[16],
uint32_t working_state[16];
size_t i;
memcpy( working_state,
mbedtls_platform_memcpy( working_state,
initial_state,
CHACHA20_BLOCK_SIZE_BYTES );

View file

@ -68,7 +68,7 @@ static int chachapoly_pad_aad( mbedtls_chachapoly_context *ctx )
if( partial_block_len == 0U )
return( 0 );
memset( zeroes, 0, sizeof( zeroes ) );
mbedtls_platform_memset( zeroes, 0, sizeof( zeroes ) );
return( mbedtls_poly1305_update( &ctx->poly1305_ctx,
zeroes,
@ -88,7 +88,7 @@ static int chachapoly_pad_ciphertext( mbedtls_chachapoly_context *ctx )
if( partial_block_len == 0U )
return( 0 );
memset( zeroes, 0, sizeof( zeroes ) );
mbedtls_platform_memset( zeroes, 0, sizeof( zeroes ) );
return( mbedtls_poly1305_update( &ctx->poly1305_ctx,
zeroes,
16U - partial_block_len ) );
@ -150,7 +150,7 @@ int mbedtls_chachapoly_starts( mbedtls_chachapoly_context *ctx,
* Only the first 256-bits (32 bytes) of the key is used for Poly1305.
* The other 256 bits are discarded.
*/
memset( poly1305_key, 0, sizeof( poly1305_key ) );
mbedtls_platform_memset( poly1305_key, 0, sizeof( poly1305_key ) );
ret = mbedtls_chacha20_update( &ctx->chacha20_ctx, sizeof( poly1305_key ),
poly1305_key, poly1305_key );
if( ret != 0 )

View file

@ -185,7 +185,7 @@ int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_in
if( cipher_info == NULL )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
memset( ctx, 0, sizeof( mbedtls_cipher_context_t ) );
mbedtls_platform_memset( ctx, 0, sizeof( mbedtls_cipher_context_t ) );
if( NULL == ( ctx->cipher_ctx = cipher_info->base->ctx_alloc_func() ) )
return( MBEDTLS_ERR_CIPHER_ALLOC_FAILED );
@ -286,7 +286,7 @@ int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx,
if ( actual_iv_size != 0 )
{
memcpy( ctx->iv, iv, actual_iv_size );
mbedtls_platform_memcpy( ctx->iv, iv, actual_iv_size );
ctx->iv_size = actual_iv_size;
}
@ -331,13 +331,13 @@ int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx,
? MBEDTLS_CHACHAPOLY_ENCRYPT
: MBEDTLS_CHACHAPOLY_DECRYPT;
result = mbedtls_chachapoly_starts( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
result = mbedtls_chachapoly_starts( (mbedtls_chachapoly_context *) ctx->cipher_ctx,
ctx->iv,
mode );
if ( result != 0 )
return( result );
return( mbedtls_chachapoly_update_aad( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
return( mbedtls_chachapoly_update_aad( (mbedtls_chachapoly_context *) ctx->cipher_ctx,
ad, ad_len ) );
}
#endif
@ -361,6 +361,10 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i
*olen = 0;
block_size = mbedtls_cipher_get_block_size( ctx );
if ( 0 == block_size )
{
return( MBEDTLS_ERR_CIPHER_INVALID_CONTEXT );
}
if( ctx->cipher_info->mode == MBEDTLS_MODE_ECB )
{
@ -391,16 +395,11 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i
if ( ctx->cipher_info->type == MBEDTLS_CIPHER_CHACHA20_POLY1305 )
{
*olen = ilen;
return( mbedtls_chachapoly_update( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
return( mbedtls_chachapoly_update( (mbedtls_chachapoly_context *) ctx->cipher_ctx,
ilen, input, output ) );
}
#endif
if ( 0 == block_size )
{
return( MBEDTLS_ERR_CIPHER_INVALID_CONTEXT );
}
if( input == output &&
( ctx->unprocessed_len != 0 || ilen % block_size ) )
{
@ -422,7 +421,7 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i
( ctx->operation == MBEDTLS_ENCRYPT &&
ilen < block_size - ctx->unprocessed_len ) )
{
memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ), input,
mbedtls_platform_memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ), input,
ilen );
ctx->unprocessed_len += ilen;
@ -436,7 +435,7 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i
{
copy_len = block_size - ctx->unprocessed_len;
memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ), input,
mbedtls_platform_memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ), input,
copy_len );
if( 0 != ( ret = ctx->cipher_info->base->cbc_func( ctx->cipher_ctx,
@ -459,11 +458,6 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i
*/
if( 0 != ilen )
{
if( 0 == block_size )
{
return( MBEDTLS_ERR_CIPHER_INVALID_CONTEXT );
}
/* Encryption: only cache partial blocks
* Decryption w/ padding: always keep at least one whole block
* Decryption w/o padding: only cache partial blocks
@ -476,7 +470,7 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i
copy_len = block_size;
}
memcpy( ctx->unprocessed_data, &( input[ilen - copy_len] ),
mbedtls_platform_memcpy( ctx->unprocessed_data, &( input[ilen - copy_len] ),
copy_len );
ctx->unprocessed_len += copy_len;
@ -924,7 +918,7 @@ int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx,
if ( tag_len != 16U )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
return( mbedtls_chachapoly_finish( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
return( mbedtls_chachapoly_finish( (mbedtls_chachapoly_context *) ctx->cipher_ctx,
tag ) );
}
#endif
@ -975,7 +969,7 @@ int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx,
if ( tag_len != sizeof( check_tag ) )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
ret = mbedtls_chachapoly_finish( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
ret = mbedtls_chachapoly_finish( (mbedtls_chachapoly_context *) ctx->cipher_ctx,
check_tag );
if ( ret != 0 )
{

View file

@ -264,6 +264,7 @@ static const mbedtls_cipher_info_t aes_128_ecb_info = {
&aes_info
};
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
static const mbedtls_cipher_info_t aes_192_ecb_info = {
MBEDTLS_CIPHER_AES_192_ECB,
MBEDTLS_MODE_ECB,
@ -285,6 +286,7 @@ static const mbedtls_cipher_info_t aes_256_ecb_info = {
16,
&aes_info
};
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static const mbedtls_cipher_info_t aes_128_cbc_info = {
@ -298,6 +300,7 @@ static const mbedtls_cipher_info_t aes_128_cbc_info = {
&aes_info
};
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
static const mbedtls_cipher_info_t aes_192_cbc_info = {
MBEDTLS_CIPHER_AES_192_CBC,
MBEDTLS_MODE_CBC,
@ -319,6 +322,7 @@ static const mbedtls_cipher_info_t aes_256_cbc_info = {
16,
&aes_info
};
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
@ -333,6 +337,7 @@ static const mbedtls_cipher_info_t aes_128_cfb128_info = {
&aes_info
};
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
static const mbedtls_cipher_info_t aes_192_cfb128_info = {
MBEDTLS_CIPHER_AES_192_CFB128,
MBEDTLS_MODE_CFB,
@ -354,6 +359,7 @@ static const mbedtls_cipher_info_t aes_256_cfb128_info = {
16,
&aes_info
};
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_OFB)
@ -368,6 +374,7 @@ static const mbedtls_cipher_info_t aes_128_ofb_info = {
&aes_info
};
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
static const mbedtls_cipher_info_t aes_192_ofb_info = {
MBEDTLS_CIPHER_AES_192_OFB,
MBEDTLS_MODE_OFB,
@ -389,6 +396,7 @@ static const mbedtls_cipher_info_t aes_256_ofb_info = {
16,
&aes_info
};
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#endif /* MBEDTLS_CIPHER_MODE_OFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
@ -403,6 +411,7 @@ static const mbedtls_cipher_info_t aes_128_ctr_info = {
&aes_info
};
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
static const mbedtls_cipher_info_t aes_192_ctr_info = {
MBEDTLS_CIPHER_AES_192_CTR,
MBEDTLS_MODE_CTR,
@ -424,6 +433,7 @@ static const mbedtls_cipher_info_t aes_256_ctr_info = {
16,
&aes_info
};
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#endif /* MBEDTLS_CIPHER_MODE_CTR */
#if defined(MBEDTLS_CIPHER_MODE_XTS)
@ -500,6 +510,7 @@ static const mbedtls_cipher_info_t aes_128_xts_info = {
&xts_aes_info
};
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
static const mbedtls_cipher_info_t aes_256_xts_info = {
MBEDTLS_CIPHER_AES_256_XTS,
MBEDTLS_MODE_XTS,
@ -510,6 +521,7 @@ static const mbedtls_cipher_info_t aes_256_xts_info = {
16,
&xts_aes_info
};
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#endif /* MBEDTLS_CIPHER_MODE_XTS */
#if defined(MBEDTLS_GCM_C)
@ -558,6 +570,7 @@ static const mbedtls_cipher_info_t aes_128_gcm_info = {
&gcm_aes_info
};
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
static const mbedtls_cipher_info_t aes_192_gcm_info = {
MBEDTLS_CIPHER_AES_192_GCM,
MBEDTLS_MODE_GCM,
@ -579,6 +592,7 @@ static const mbedtls_cipher_info_t aes_256_gcm_info = {
16,
&gcm_aes_info
};
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#endif /* MBEDTLS_GCM_C */
#if defined(MBEDTLS_CCM_C)
@ -627,6 +641,7 @@ static const mbedtls_cipher_info_t aes_128_ccm_info = {
&ccm_aes_info
};
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
static const mbedtls_cipher_info_t aes_192_ccm_info = {
MBEDTLS_CIPHER_AES_192_CCM,
MBEDTLS_MODE_CCM,
@ -648,6 +663,7 @@ static const mbedtls_cipher_info_t aes_256_ccm_info = {
16,
&ccm_aes_info
};
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#endif /* MBEDTLS_CCM_C */
#endif /* MBEDTLS_AES_C */
@ -1987,7 +2003,7 @@ static int chachapoly_setkey_wrap( void *ctx,
if( key_bitlen != 256U )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
if ( 0 != mbedtls_chachapoly_setkey( (mbedtls_chachapoly_context*)ctx, key ) )
if ( 0 != mbedtls_chachapoly_setkey( (mbedtls_chachapoly_context *)ctx, key ) )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
return( 0 );
@ -2123,42 +2139,65 @@ const mbedtls_cipher_definition_t mbedtls_cipher_definitions[] =
{
#if defined(MBEDTLS_AES_C)
{ MBEDTLS_CIPHER_AES_128_ECB, &aes_128_ecb_info },
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
{ MBEDTLS_CIPHER_AES_192_ECB, &aes_192_ecb_info },
{ MBEDTLS_CIPHER_AES_256_ECB, &aes_256_ecb_info },
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#if defined(MBEDTLS_CIPHER_MODE_CBC)
{ MBEDTLS_CIPHER_AES_128_CBC, &aes_128_cbc_info },
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
{ MBEDTLS_CIPHER_AES_192_CBC, &aes_192_cbc_info },
{ MBEDTLS_CIPHER_AES_256_CBC, &aes_256_cbc_info },
#endif
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
{ MBEDTLS_CIPHER_AES_128_CFB128, &aes_128_cfb128_info },
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
{ MBEDTLS_CIPHER_AES_192_CFB128, &aes_192_cfb128_info },
{ MBEDTLS_CIPHER_AES_256_CFB128, &aes_256_cfb128_info },
#endif
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_OFB)
{ MBEDTLS_CIPHER_AES_128_OFB, &aes_128_ofb_info },
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
{ MBEDTLS_CIPHER_AES_192_OFB, &aes_192_ofb_info },
{ MBEDTLS_CIPHER_AES_256_OFB, &aes_256_ofb_info },
#endif
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#endif /* MBEDTLS_CIPHER_MODE_OFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
{ MBEDTLS_CIPHER_AES_128_CTR, &aes_128_ctr_info },
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
{ MBEDTLS_CIPHER_AES_192_CTR, &aes_192_ctr_info },
{ MBEDTLS_CIPHER_AES_256_CTR, &aes_256_ctr_info },
#endif
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#endif /* MBEDTLS_CIPHER_MODE_CTR */
#if defined(MBEDTLS_CIPHER_MODE_XTS)
{ MBEDTLS_CIPHER_AES_128_XTS, &aes_128_xts_info },
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
{ MBEDTLS_CIPHER_AES_256_XTS, &aes_256_xts_info },
#endif
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#endif /* MBEDTLS_CIPHER_MODE_XTS */
#if defined(MBEDTLS_GCM_C)
{ MBEDTLS_CIPHER_AES_128_GCM, &aes_128_gcm_info },
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
{ MBEDTLS_CIPHER_AES_192_GCM, &aes_192_gcm_info },
{ MBEDTLS_CIPHER_AES_256_GCM, &aes_256_gcm_info },
#endif
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#endif /* MBEDTLS_GCM_C */
#if defined(MBEDTLS_CCM_C)
{ MBEDTLS_CIPHER_AES_128_CCM, &aes_128_ccm_info },
#if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
{ MBEDTLS_CIPHER_AES_192_CCM, &aes_192_ccm_info },
{ MBEDTLS_CIPHER_AES_256_CCM, &aes_256_ccm_info },
#endif
#endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
#endif /* MBEDTLS_CCM_C */
#endif /* MBEDTLS_AES_C */
#if defined(MBEDTLS_ARC4_C)

View file

@ -260,7 +260,7 @@ int mbedtls_cipher_cmac_update( mbedtls_cipher_context_t *ctx,
if( cmac_ctx->unprocessed_len > 0 &&
ilen > block_size - cmac_ctx->unprocessed_len )
{
memcpy( &cmac_ctx->unprocessed_block[cmac_ctx->unprocessed_len],
mbedtls_platform_memcpy( &cmac_ctx->unprocessed_block[cmac_ctx->unprocessed_len],
input,
block_size - cmac_ctx->unprocessed_len );
@ -297,7 +297,7 @@ int mbedtls_cipher_cmac_update( mbedtls_cipher_context_t *ctx,
/* If there is data left over that wasn't aligned to a block */
if( ilen > 0 )
{
memcpy( &cmac_ctx->unprocessed_block[cmac_ctx->unprocessed_len],
mbedtls_platform_memcpy( &cmac_ctx->unprocessed_block[cmac_ctx->unprocessed_len],
input,
ilen );
cmac_ctx->unprocessed_len += ilen;
@ -352,7 +352,7 @@ int mbedtls_cipher_cmac_finish( mbedtls_cipher_context_t *ctx,
goto exit;
}
memcpy( output, state, block_size );
mbedtls_platform_memcpy( output, state, block_size );
exit:
/* Wipe the generated keys on the stack, and any other transients to avoid
@ -446,11 +446,11 @@ int mbedtls_aes_cmac_prf_128( const unsigned char *key, size_t key_length,
if( key_length == MBEDTLS_AES_BLOCK_SIZE )
{
/* Use key as is */
memcpy( int_key, key, MBEDTLS_AES_BLOCK_SIZE );
mbedtls_platform_memcpy( int_key, key, MBEDTLS_AES_BLOCK_SIZE );
}
else
{
memset( zero_key, 0, MBEDTLS_AES_BLOCK_SIZE );
mbedtls_platform_memset( zero_key, 0, MBEDTLS_AES_BLOCK_SIZE );
ret = mbedtls_cipher_cmac( cipher_info, zero_key, 128, key,
key_length, int_key );
@ -902,7 +902,7 @@ static int test_aes128_cmac_prf( int verbose )
mbedtls_printf( " AES CMAC 128 PRF #%u: ", i );
ret = mbedtls_aes_cmac_prf_128( PRFK, PRFKlen[i], PRFM, 20, output );
if( ret != 0 ||
memcmp( output, PRFT[i], MBEDTLS_AES_BLOCK_SIZE ) != 0 )
memcmp( output, PRFT[i], MBEDTLS_AES_BLOCK_SIZE ) != 0 )
{
if( verbose != 0 )

View file

@ -55,75 +55,13 @@
*/
void mbedtls_ctr_drbg_init( mbedtls_ctr_drbg_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_ctr_drbg_context ) );
mbedtls_platform_memset( ctx, 0, sizeof( mbedtls_ctr_drbg_context ) );
#if defined(MBEDTLS_THREADING_C)
mbedtls_mutex_init( &ctx->mutex );
#endif
}
/*
* Non-public function wrapped by mbedtls_ctr_drbg_seed(). Necessary to allow
* NIST tests to succeed (which require known length fixed entropy)
*/
/* CTR_DRBG_Instantiate with derivation function (SP 800-90A &sect;10.2.1.3.2)
* mbedtls_ctr_drbg_seed_entropy_len(ctx, f_entropy, p_entropy,
* custom, len, entropy_len)
* implements
* CTR_DRBG_Instantiate(entropy_input, nonce, personalization_string,
* security_strength) -> initial_working_state
* with inputs
* custom[:len] = nonce || personalization_string
* where entropy_input comes from f_entropy for entropy_len bytes
* and with outputs
* ctx = initial_working_state
*/
int mbedtls_ctr_drbg_seed_entropy_len(
mbedtls_ctr_drbg_context *ctx,
int (*f_entropy)(void *, unsigned char *, size_t),
void *p_entropy,
const unsigned char *custom,
size_t len,
size_t entropy_len )
{
int ret;
unsigned char key[MBEDTLS_CTR_DRBG_KEYSIZE];
memset( key, 0, MBEDTLS_CTR_DRBG_KEYSIZE );
mbedtls_aes_init( &ctx->aes_ctx );
ctx->f_entropy = f_entropy;
ctx->p_entropy = p_entropy;
ctx->entropy_len = entropy_len;
ctx->reseed_interval = MBEDTLS_CTR_DRBG_RESEED_INTERVAL;
/*
* Initialize with an empty key
*/
if( ( ret = mbedtls_aes_setkey_enc( &ctx->aes_ctx, key, MBEDTLS_CTR_DRBG_KEYBITS ) ) != 0 )
{
return( ret );
}
if( ( ret = mbedtls_ctr_drbg_reseed( ctx, custom, len ) ) != 0 )
{
return( ret );
}
return( 0 );
}
int mbedtls_ctr_drbg_seed( mbedtls_ctr_drbg_context *ctx,
int (*f_entropy)(void *, unsigned char *, size_t),
void *p_entropy,
const unsigned char *custom,
size_t len )
{
return( mbedtls_ctr_drbg_seed_entropy_len( ctx, f_entropy, p_entropy, custom, len,
MBEDTLS_CTR_DRBG_ENTROPY_LEN ) );
}
void mbedtls_ctr_drbg_free( mbedtls_ctr_drbg_context *ctx )
{
if( ctx == NULL )
@ -168,7 +106,7 @@ static int block_cipher_df( unsigned char *output,
if( data_len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT )
return( MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG );
memset( buf, 0, MBEDTLS_CTR_DRBG_MAX_SEED_INPUT + MBEDTLS_CTR_DRBG_BLOCKSIZE + 16 );
mbedtls_platform_memset( buf, 0, MBEDTLS_CTR_DRBG_MAX_SEED_INPUT + MBEDTLS_CTR_DRBG_BLOCKSIZE + 16 );
mbedtls_aes_init( &aes_ctx );
/*
@ -185,7 +123,7 @@ static int block_cipher_df( unsigned char *output,
*p++ = ( data_len ) & 0xff;
p += 3;
*p++ = MBEDTLS_CTR_DRBG_SEEDLEN;
memcpy( p, data, data_len );
mbedtls_platform_memcpy( p, data, data_len );
p[data_len] = 0x80;
buf_len = MBEDTLS_CTR_DRBG_BLOCKSIZE + 8 + data_len + 1;
@ -204,7 +142,7 @@ static int block_cipher_df( unsigned char *output,
for( j = 0; j < MBEDTLS_CTR_DRBG_SEEDLEN; j += MBEDTLS_CTR_DRBG_BLOCKSIZE )
{
p = buf;
memset( chain, 0, MBEDTLS_CTR_DRBG_BLOCKSIZE );
mbedtls_platform_memset( chain, 0, MBEDTLS_CTR_DRBG_BLOCKSIZE );
use_len = buf_len;
while( use_len > 0 )
@ -221,7 +159,7 @@ static int block_cipher_df( unsigned char *output,
}
}
memcpy( tmp + j, chain, MBEDTLS_CTR_DRBG_BLOCKSIZE );
mbedtls_platform_memcpy( tmp + j, chain, MBEDTLS_CTR_DRBG_BLOCKSIZE );
/*
* Update IV
@ -245,7 +183,7 @@ static int block_cipher_df( unsigned char *output,
{
goto exit;
}
memcpy( p, iv, MBEDTLS_CTR_DRBG_BLOCKSIZE );
mbedtls_platform_memcpy( p, iv, MBEDTLS_CTR_DRBG_BLOCKSIZE );
p += MBEDTLS_CTR_DRBG_BLOCKSIZE;
}
exit:
@ -284,7 +222,7 @@ static int ctr_drbg_update_internal( mbedtls_ctr_drbg_context *ctx,
int i, j;
int ret = 0;
memset( tmp, 0, MBEDTLS_CTR_DRBG_SEEDLEN );
mbedtls_platform_memset( tmp, 0, MBEDTLS_CTR_DRBG_SEEDLEN );
for( j = 0; j < MBEDTLS_CTR_DRBG_SEEDLEN; j += MBEDTLS_CTR_DRBG_BLOCKSIZE )
{
@ -312,7 +250,7 @@ static int ctr_drbg_update_internal( mbedtls_ctr_drbg_context *ctx,
*/
if( ( ret = mbedtls_aes_setkey_enc( &ctx->aes_ctx, tmp, MBEDTLS_CTR_DRBG_KEYBITS ) ) != 0 )
goto exit;
memcpy( ctx->counter, tmp + MBEDTLS_CTR_DRBG_KEYSIZE, MBEDTLS_CTR_DRBG_BLOCKSIZE );
mbedtls_platform_memcpy( ctx->counter, tmp + MBEDTLS_CTR_DRBG_KEYSIZE, MBEDTLS_CTR_DRBG_BLOCKSIZE );
exit:
mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
@ -387,7 +325,7 @@ int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx,
len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT - ctx->entropy_len )
return( MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG );
memset( seed, 0, MBEDTLS_CTR_DRBG_MAX_SEED_INPUT );
mbedtls_platform_memset( seed, 0, MBEDTLS_CTR_DRBG_MAX_SEED_INPUT );
/*
* Gather entropy_len bytes of entropy to seed state
@ -405,7 +343,7 @@ int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx,
*/
if( additional && len )
{
memcpy( seed + seedlen, additional, len );
mbedtls_platform_memcpy( seed + seedlen, additional, len );
seedlen += len;
}
@ -427,6 +365,63 @@ exit:
return( ret );
}
/* CTR_DRBG_Instantiate with derivation function (SP 800-90A &sect;10.2.1.3.2)
* mbedtls_ctr_drbg_seed(ctx, f_entropy, p_entropy, custom, len)
* implements
* CTR_DRBG_Instantiate(entropy_input, nonce, personalization_string,
* security_strength) -> initial_working_state
* with inputs
* custom[:len] = nonce || personalization_string
* where entropy_input comes from f_entropy for ctx->entropy_len bytes
* and with outputs
* ctx = initial_working_state
*/
int mbedtls_ctr_drbg_seed( mbedtls_ctr_drbg_context *ctx,
int (*f_entropy)(void *, unsigned char *, size_t),
void *p_entropy,
const unsigned char *custom,
size_t len )
{
int ret;
unsigned char key[MBEDTLS_CTR_DRBG_KEYSIZE];
memset( key, 0, MBEDTLS_CTR_DRBG_KEYSIZE );
mbedtls_aes_init( &ctx->aes_ctx );
ctx->f_entropy = f_entropy;
ctx->p_entropy = p_entropy;
if( ctx->entropy_len == 0 )
ctx->entropy_len = MBEDTLS_CTR_DRBG_ENTROPY_LEN;
ctx->reseed_interval = MBEDTLS_CTR_DRBG_RESEED_INTERVAL;
/*
* Initialize with an empty key
*/
if( ( ret = mbedtls_aes_setkey_enc( &ctx->aes_ctx, key, MBEDTLS_CTR_DRBG_KEYBITS ) ) != 0 )
{
return( ret );
}
if( ( ret = mbedtls_ctr_drbg_reseed( ctx, custom, len ) ) != 0 )
{
return( ret );
}
return( 0 );
}
/* Backward compatibility wrapper */
int mbedtls_ctr_drbg_seed_entropy_len(
mbedtls_ctr_drbg_context *ctx,
int (*f_entropy)(void *, unsigned char *, size_t), void *p_entropy,
const unsigned char *custom, size_t len,
size_t entropy_len )
{
mbedtls_ctr_drbg_set_entropy_len( ctx, entropy_len );
return( mbedtls_ctr_drbg_seed( ctx, f_entropy, p_entropy, custom, len ) );
}
/* CTR_DRBG_Generate with derivation function (SP 800-90A &sect;10.2.1.5.2)
* mbedtls_ctr_drbg_random_with_add(ctx, output, output_len, additional, add_len)
* implements
@ -464,7 +459,7 @@ int mbedtls_ctr_drbg_random_with_add( void *p_rng,
if( add_len > MBEDTLS_CTR_DRBG_MAX_INPUT )
return( MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG );
memset( add_input, 0, MBEDTLS_CTR_DRBG_SEEDLEN );
mbedtls_platform_memset( add_input, 0, MBEDTLS_CTR_DRBG_SEEDLEN );
if( ctx->reseed_counter > ctx->reseed_interval ||
ctx->prediction_resistance )
@ -504,7 +499,7 @@ int mbedtls_ctr_drbg_random_with_add( void *p_rng,
/*
* Copy random block to destination
*/
memcpy( p, tmp, use_len );
mbedtls_platform_memcpy( p, tmp, use_len );
p += use_len;
output_len -= use_len;
}
@ -517,7 +512,7 @@ int mbedtls_ctr_drbg_random_with_add( void *p_rng,
exit:
mbedtls_platform_zeroize( add_input, sizeof( add_input ) );
mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
return( 0 );
return( ret );
}
int mbedtls_ctr_drbg_random( void *p_rng, unsigned char *output, size_t output_len )
@ -678,8 +673,11 @@ int mbedtls_ctr_drbg_self_test( int verbose )
mbedtls_printf( " CTR_DRBG (PR = TRUE) : " );
test_offset = 0;
CHK( mbedtls_ctr_drbg_seed_entropy_len( &ctx, ctr_drbg_self_test_entropy,
(void *) entropy_source_pr, nonce_pers_pr, 16, 32 ) );
mbedtls_ctr_drbg_set_entropy_len( &ctx, 32 );
CHK( mbedtls_ctr_drbg_seed( &ctx,
ctr_drbg_self_test_entropy,
(void *) entropy_source_pr,
nonce_pers_pr, 16 ) );
mbedtls_ctr_drbg_set_prediction_resistance( &ctx, MBEDTLS_CTR_DRBG_PR_ON );
CHK( mbedtls_ctr_drbg_random( &ctx, buf, MBEDTLS_CTR_DRBG_BLOCKSIZE ) );
CHK( mbedtls_ctr_drbg_random( &ctx, buf, MBEDTLS_CTR_DRBG_BLOCKSIZE ) );
@ -699,8 +697,11 @@ int mbedtls_ctr_drbg_self_test( int verbose )
mbedtls_ctr_drbg_init( &ctx );
test_offset = 0;
CHK( mbedtls_ctr_drbg_seed_entropy_len( &ctx, ctr_drbg_self_test_entropy,
(void *) entropy_source_nopr, nonce_pers_nopr, 16, 32 ) );
mbedtls_ctr_drbg_set_entropy_len( &ctx, 32 );
CHK( mbedtls_ctr_drbg_seed( &ctx,
ctr_drbg_self_test_entropy,
(void *) entropy_source_nopr,
nonce_pers_nopr, 16 ) );
CHK( mbedtls_ctr_drbg_random( &ctx, buf, 16 ) );
CHK( mbedtls_ctr_drbg_reseed( &ctx, NULL, 0 ) );
CHK( mbedtls_ctr_drbg_random( &ctx, buf, 16 ) );

View file

@ -42,6 +42,7 @@
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "mbedtls/platform_util.h"
#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
!defined(inline) && !defined(__cplusplus)
@ -71,7 +72,7 @@ static inline void debug_send_line( const mbedtls_ssl_context *ssl, int level,
*/
#if defined(MBEDTLS_THREADING_C)
char idstr[20 + DEBUG_BUF_SIZE]; /* 0x + 16 nibbles + ': ' */
mbedtls_snprintf( idstr, sizeof( idstr ), "%p: %s", (void*)ssl, str );
mbedtls_snprintf( idstr, sizeof( idstr ), "%p: %s", (void *)ssl, str );
ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, idstr );
#else
ssl->conf->f_dbg( ssl->conf->p_dbg, level, file, line, str );
@ -170,7 +171,7 @@ void mbedtls_debug_print_buf( const mbedtls_ssl_context *ssl, int level,
debug_send_line( ssl, level, file, line, str );
idx = 0;
memset( txt, 0, sizeof( txt ) );
mbedtls_platform_memset( txt, 0, sizeof( txt ) );
for( i = 0; i < len; i++ )
{
if( i >= 4096 )
@ -184,7 +185,7 @@ void mbedtls_debug_print_buf( const mbedtls_ssl_context *ssl, int level,
debug_send_line( ssl, level, file, line, str );
idx = 0;
memset( txt, 0, sizeof( txt ) );
mbedtls_platform_memset( txt, 0, sizeof( txt ) );
}
idx += mbedtls_snprintf( str + idx, sizeof( str ) - idx, "%04x: ",
@ -300,7 +301,7 @@ void mbedtls_debug_print_mpi( const mbedtls_ssl_context *ssl, int level,
}
#endif /* MBEDTLS_BIGNUM_C */
#if defined(MBEDTLS_X509_CRT_PARSE_C)
#if defined(MBEDTLS_X509_CRT_PARSE_C) && !defined(MBEDTLS_X509_REMOVE_INFO)
static void debug_print_pk( const mbedtls_ssl_context *ssl, int level,
const char *file, int line,
const char *text, const mbedtls_pk_context *pk )
@ -309,7 +310,7 @@ static void debug_print_pk( const mbedtls_ssl_context *ssl, int level,
mbedtls_pk_debug_item items[MBEDTLS_PK_DEBUG_MAX_ITEMS];
char name[16];
memset( items, 0, sizeof( items ) );
mbedtls_platform_memset( items, 0, sizeof( items ) );
if( mbedtls_pk_debug( pk, items ) != 0 )
{
@ -354,7 +355,7 @@ static void debug_print_line_by_line( const mbedtls_ssl_context *ssl, int level,
if( len > DEBUG_BUF_SIZE - 1 )
len = DEBUG_BUF_SIZE - 1;
memcpy( str, start, len );
mbedtls_platform_memcpy( str, start, len );
str[len] = '\0';
debug_send_line( ssl, level, file, line, str );
@ -382,6 +383,8 @@ void mbedtls_debug_print_crt( const mbedtls_ssl_context *ssl, int level,
while( crt != NULL )
{
int ret;
mbedtls_pk_context *pk;
char buf[1024];
mbedtls_snprintf( str, sizeof( str ), "%s #%d:\n", text, ++i );
@ -390,12 +393,22 @@ void mbedtls_debug_print_crt( const mbedtls_ssl_context *ssl, int level,
mbedtls_x509_crt_info( buf, sizeof( buf ) - 1, "", crt );
debug_print_line_by_line( ssl, level, file, line, buf );
debug_print_pk( ssl, level, file, line, "crt->", &crt->pk );
ret = mbedtls_x509_crt_pk_acquire( crt, &pk );
if( ret != 0 )
{
mbedtls_snprintf( str, sizeof( str ),
"mbedtls_x509_crt_pk_acquire() failed with -%#04x\n",
-ret );
debug_send_line( ssl, level, file, line, str );
return;
}
debug_print_pk( ssl, level, file, line, "crt->", pk );
mbedtls_x509_crt_pk_release( crt );
crt = crt->next;
}
}
#endif /* MBEDTLS_X509_CRT_PARSE_C */
#endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_X509_REMOVE_INFO&& MBEDTLS_X509_REMOVE_INFO !MBEDTLS_X509_REMOVE_INFO */
#if defined(MBEDTLS_ECDH_C)
static void mbedtls_debug_printf_ecdh_internal( const mbedtls_ssl_context *ssl,

View file

@ -311,7 +311,7 @@ static const uint32_t RHs[16] =
void mbedtls_des_init( mbedtls_des_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_des_context ) );
mbedtls_platform_memset( ctx, 0, sizeof( mbedtls_des_context ) );
}
void mbedtls_des_free( mbedtls_des_context *ctx )
@ -324,7 +324,7 @@ void mbedtls_des_free( mbedtls_des_context *ctx )
void mbedtls_des3_init( mbedtls_des3_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_des3_context ) );
mbedtls_platform_memset( ctx, 0, sizeof( mbedtls_des3_context ) );
}
void mbedtls_des3_free( mbedtls_des3_context *ctx )
@ -417,7 +417,7 @@ int mbedtls_des_key_check_weak( const unsigned char key[MBEDTLS_DES_KEY_SIZE] )
int i;
for( i = 0; i < WEAK_KEY_COUNT; i++ )
if( memcmp( weak_key_table[i], key, MBEDTLS_DES_KEY_SIZE) == 0 )
if( mbedtls_platform_memcmp( weak_key_table[i], key, MBEDTLS_DES_KEY_SIZE) == 0 )
return( 1 );
return( 0 );
@ -684,7 +684,7 @@ int mbedtls_des_crypt_cbc( mbedtls_des_context *ctx,
output[i] = (unsigned char)( input[i] ^ iv[i] );
mbedtls_des_crypt_ecb( ctx, output, output );
memcpy( iv, output, 8 );
mbedtls_platform_memcpy( iv, output, 8 );
input += 8;
output += 8;
@ -695,13 +695,13 @@ int mbedtls_des_crypt_cbc( mbedtls_des_context *ctx,
{
while( length > 0 )
{
memcpy( temp, input, 8 );
mbedtls_platform_memcpy( temp, input, 8 );
mbedtls_des_crypt_ecb( ctx, input, output );
for( i = 0; i < 8; i++ )
output[i] = (unsigned char)( output[i] ^ iv[i] );
memcpy( iv, temp, 8 );
mbedtls_platform_memcpy( iv, temp, 8 );
input += 8;
output += 8;
@ -783,7 +783,7 @@ int mbedtls_des3_crypt_cbc( mbedtls_des3_context *ctx,
output[i] = (unsigned char)( input[i] ^ iv[i] );
mbedtls_des3_crypt_ecb( ctx, output, output );
memcpy( iv, output, 8 );
mbedtls_platform_memcpy( iv, output, 8 );
input += 8;
output += 8;
@ -794,13 +794,13 @@ int mbedtls_des3_crypt_cbc( mbedtls_des3_context *ctx,
{
while( length > 0 )
{
memcpy( temp, input, 8 );
mbedtls_platform_memcpy( temp, input, 8 );
mbedtls_des3_crypt_ecb( ctx, input, output );
for( i = 0; i < 8; i++ )
output[i] = (unsigned char)( output[i] ^ iv[i] );
memcpy( iv, temp, 8 );
mbedtls_platform_memcpy( iv, temp, 8 );
input += 8;
output += 8;
@ -939,7 +939,7 @@ int mbedtls_des_self_test( int verbose )
if( ( v == MBEDTLS_DES_DECRYPT &&
memcmp( buf, des3_test_ecb_dec[u], 8 ) != 0 ) ||
( v != MBEDTLS_DES_DECRYPT &&
memcmp( buf, des3_test_ecb_enc[u], 8 ) != 0 ) )
memcmp( buf, des3_test_ecb_enc[u], 8 ) != 0 ) )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
@ -1035,7 +1035,7 @@ int mbedtls_des_self_test( int verbose )
if( ( v == MBEDTLS_DES_DECRYPT &&
memcmp( buf, des3_test_cbc_dec[u], 8 ) != 0 ) ||
( v != MBEDTLS_DES_DECRYPT &&
memcmp( buf, des3_test_cbc_enc[u], 8 ) != 0 ) )
memcmp( buf, des3_test_cbc_enc[u], 8 ) != 0 ) )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );

View file

@ -127,7 +127,7 @@ cleanup:
void mbedtls_dhm_init( mbedtls_dhm_context *ctx )
{
DHM_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_dhm_context ) );
mbedtls_platform_memset( ctx, 0, sizeof( mbedtls_dhm_context ) );
}
/*

View file

@ -179,7 +179,7 @@ void mbedtls_ecdh_init( mbedtls_ecdh_context *ctx )
mbedtls_ecp_point_init( &ctx->Vf );
mbedtls_mpi_init( &ctx->_d );
#else
memset( ctx, 0, sizeof( mbedtls_ecdh_context ) );
mbedtls_platform_memset( ctx, 0, sizeof( mbedtls_ecdh_context ) );
ctx->var = MBEDTLS_ECDH_VARIANT_NONE;
#endif

View file

@ -297,7 +297,7 @@ static int ecdsa_sign_restartable( mbedtls_ecp_group *grp,
*p_sign_tries = 0;
do
{
if( *p_sign_tries++ > 10 )
if( (*p_sign_tries)++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
@ -310,7 +310,7 @@ static int ecdsa_sign_restartable( mbedtls_ecp_group *grp,
*p_key_tries = 0;
do
{
if( *p_key_tries++ > 10 )
if( (*p_key_tries)++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
@ -363,6 +363,7 @@ modn:
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pk, pk, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pk, pk, &grp->N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, pk, &grp->N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) );
@ -420,11 +421,14 @@ static int ecdsa_sign_det_restartable( mbedtls_ecp_group *grp,
mbedtls_hmac_drbg_context *p_rng = &rng_ctx;
unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES];
size_t grp_len = ( grp->nbits + 7 ) / 8;
const mbedtls_md_info_t *md_info;
mbedtls_md_handle_t md_info;
mbedtls_mpi h;
if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL )
if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) ==
MBEDTLS_MD_INVALID_HANDLE )
{
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
}
mbedtls_mpi_init( &h );
mbedtls_hmac_drbg_init( &rng_ctx );
@ -719,7 +723,7 @@ static int ecdsa_signature_to_asn1( const mbedtls_mpi *r, const mbedtls_mpi *s,
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &p, buf,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) );
memcpy( sig, p, len );
mbedtls_platform_memcpy( sig, p, len );
*slen = len;
return( 0 );

View file

@ -63,7 +63,7 @@ void mbedtls_ecjpake_init( mbedtls_ecjpake_context *ctx )
{
ECJPAKE_VALIDATE( ctx != NULL );
ctx->md_info = NULL;
ctx->md_info = MBEDTLS_MD_INVALID_HANDLE;
mbedtls_ecp_group_init( &ctx->grp );
ctx->point_format = MBEDTLS_ECP_PF_UNCOMPRESSED;
@ -86,7 +86,7 @@ void mbedtls_ecjpake_free( mbedtls_ecjpake_context *ctx )
if( ctx == NULL )
return;
ctx->md_info = NULL;
ctx->md_info = MBEDTLS_MD_INVALID_HANDLE;
mbedtls_ecp_group_free( &ctx->grp );
mbedtls_ecp_point_free( &ctx->Xm1 );
@ -119,8 +119,11 @@ int mbedtls_ecjpake_setup( mbedtls_ecjpake_context *ctx,
ctx->role = role;
if( ( ctx->md_info = mbedtls_md_info_from_type( hash ) ) == NULL )
if( ( ctx->md_info = mbedtls_md_info_from_type( hash ) ) ==
MBEDTLS_MD_INVALID_HANDLE )
{
return( MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE );
}
MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &ctx->grp, curve ) );
@ -140,7 +143,7 @@ int mbedtls_ecjpake_check( const mbedtls_ecjpake_context *ctx )
{
ECJPAKE_VALIDATE_RET( ctx != NULL );
if( ctx->md_info == NULL ||
if( ctx->md_info == MBEDTLS_MD_INVALID_HANDLE ||
ctx->grp.id == MBEDTLS_ECP_DP_NONE ||
ctx->s.p == NULL )
{
@ -190,7 +193,7 @@ static int ecjpake_write_len_point( unsigned char **p,
/*
* Compute hash for ZKP (7.4.2.2.2.1)
*/
static int ecjpake_hash( const mbedtls_md_info_t *md_info,
static int ecjpake_hash( mbedtls_md_handle_t md_info,
const mbedtls_ecp_group *grp,
const int pf,
const mbedtls_ecp_point *G,
@ -222,7 +225,7 @@ static int ecjpake_hash( const mbedtls_md_info_t *md_info,
if( end < p || (size_t)( end - p ) < id_len )
return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
memcpy( p, id, id_len );
mbedtls_platform_memcpy( p, id, id_len );
p += id_len;
/* Compute hash */
@ -240,7 +243,7 @@ cleanup:
/*
* Parse a ECShnorrZKP (7.4.2.2.2) and verify it (7.4.2.3.3)
*/
static int ecjpake_zkp_read( const mbedtls_md_info_t *md_info,
static int ecjpake_zkp_read( mbedtls_md_handle_t md_info,
const mbedtls_ecp_group *grp,
const int pf,
const mbedtls_ecp_point *G,
@ -312,7 +315,7 @@ cleanup:
/*
* Generate ZKP (7.4.2.3.2) and write it as ECSchnorrZKP (7.4.2.2.2)
*/
static int ecjpake_zkp_write( const mbedtls_md_info_t *md_info,
static int ecjpake_zkp_write( mbedtls_md_handle_t md_info,
const mbedtls_ecp_group *grp,
const int pf,
const mbedtls_ecp_point *G,
@ -373,7 +376,7 @@ cleanup:
* Parse a ECJPAKEKeyKP (7.4.2.2.1) and check proof
* Output: verified public key X
*/
static int ecjpake_kkp_read( const mbedtls_md_info_t *md_info,
static int ecjpake_kkp_read( mbedtls_md_handle_t md_info,
const mbedtls_ecp_group *grp,
const int pf,
const mbedtls_ecp_point *G,
@ -410,7 +413,7 @@ cleanup:
* Generate an ECJPAKEKeyKP
* Output: the serialized structure, plus private/public key pair
*/
static int ecjpake_kkp_write( const mbedtls_md_info_t *md_info,
static int ecjpake_kkp_write( mbedtls_md_handle_t md_info,
const mbedtls_ecp_group *grp,
const int pf,
const mbedtls_ecp_point *G,
@ -447,7 +450,7 @@ cleanup:
* Read a ECJPAKEKeyKPPairList (7.4.2.3) and check proofs
* Ouputs: verified peer public keys Xa, Xb
*/
static int ecjpake_kkpp_read( const mbedtls_md_info_t *md_info,
static int ecjpake_kkpp_read( mbedtls_md_handle_t md_info,
const mbedtls_ecp_group *grp,
const int pf,
const mbedtls_ecp_point *G,
@ -480,7 +483,7 @@ cleanup:
* Generate a ECJPAKEKeyKPPairList
* Outputs: the serialized structure, plus two private/public key pairs
*/
static int ecjpake_kkpp_write( const mbedtls_md_info_t *md_info,
static int ecjpake_kkpp_write( mbedtls_md_handle_t md_info,
const mbedtls_ecp_group *grp,
const int pf,
const mbedtls_ecp_point *G,

View file

@ -1553,7 +1553,7 @@ static void ecp_comb_recode_core( unsigned char x[], size_t d,
size_t i, j;
unsigned char c, cc, adjust;
memset( x, 0, d+1 );
mbedtls_platform_memset( x, 0, d+1 );
/* First get the classical comb values (except for x_d = 0) */
for( i = 0; i < d; i++ )
@ -1938,6 +1938,20 @@ static int ecp_mul_comb_after_precomp( const mbedtls_ecp_group *grp,
final_norm:
#endif
/*
* Knowledge of the jacobian coordinates may leak the last few bits of the
* scalar [1], and since our MPI implementation isn't constant-flow,
* inversion (used for coordinate normalization) may leak the full value
* of its input via side-channels [2].
*
* [1] https://eprint.iacr.org/2003/191
* [2] https://eprint.iacr.org/2020/055
*
* Avoid the leak by randomizing coordinates before we normalize them.
*/
if( f_rng != 0 )
MBEDTLS_MPI_CHK( ecp_randomize_jac( grp, RR, f_rng, p_rng ) );
MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_INV );
MBEDTLS_MPI_CHK( ecp_normalize_jac( grp, RR ) );
@ -2308,6 +2322,20 @@ static int ecp_mul_mxz( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->Z, &RP.Z, b ) );
}
/*
* Knowledge of the projective coordinates may leak the last few bits of the
* scalar [1], and since our MPI implementation isn't constant-flow,
* inversion (used for coordinate normalization) may leak the full value
* of its input via side-channels [2].
*
* [1] https://eprint.iacr.org/2003/191
* [2] https://eprint.iacr.org/2020/055
*
* Avoid the leak by randomizing coordinates before we normalize them.
*/
if( f_rng != NULL )
MBEDTLS_MPI_CHK( ecp_randomize_mxz( grp, R, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( ecp_normalize_mxz( grp, R ) );
cleanup:
@ -2724,6 +2752,7 @@ int mbedtls_ecp_gen_privkey( const mbedtls_ecp_group *grp,
{
/* SEC1 3.2.1: Generate d such that 1 <= n < N */
int count = 0;
unsigned cmp = 0;
/*
* Match the procedure given in RFC 6979 (deterministic ECDSA):
@ -2748,9 +2777,14 @@ int mbedtls_ecp_gen_privkey( const mbedtls_ecp_group *grp,
*/
if( ++count > 30 )
return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
ret = mbedtls_mpi_lt_mpi_ct( d, &grp->N, &cmp );
if( ret != 0 )
{
goto cleanup;
}
}
while( mbedtls_mpi_cmp_int( d, 1 ) < 0 ||
mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 );
while( mbedtls_mpi_cmp_int( d, 1 ) < 0 || cmp != 1 );
}
#endif /* ECP_SHORTWEIERSTRASS */

View file

@ -1001,7 +1001,7 @@ static inline void sub32( uint32_t *dst, uint32_t src, signed char *carry )
C.s = 1; \
C.n = (b) / 8 / sizeof( mbedtls_mpi_uint) + 1; \
C.p = Cp; \
memset( Cp, 0, C.n * sizeof( mbedtls_mpi_uint ) ); \
mbedtls_platform_memset( Cp, 0, C.n * sizeof( mbedtls_mpi_uint ) ); \
\
MBEDTLS_MPI_CHK( mbedtls_mpi_grow( N, (b) * 2 / 8 / \
sizeof( mbedtls_mpi_uint ) ) ); \
@ -1202,7 +1202,7 @@ static int ecp_mod_p521( mbedtls_mpi *N )
if( M.n > P521_WIDTH + 1 )
M.n = P521_WIDTH + 1;
M.p = Mp;
memcpy( Mp, N->p + P521_WIDTH - 1, M.n * sizeof( mbedtls_mpi_uint ) );
mbedtls_platform_memcpy( Mp, N->p + P521_WIDTH - 1, M.n * sizeof( mbedtls_mpi_uint ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &M, 521 % ( 8 * sizeof( mbedtls_mpi_uint ) ) ) );
/* N = A0 */
@ -1248,8 +1248,8 @@ static int ecp_mod_p255( mbedtls_mpi *N )
if( M.n > P255_WIDTH + 1 )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
M.p = Mp;
memset( Mp, 0, sizeof Mp );
memcpy( Mp, N->p + P255_WIDTH - 1, M.n * sizeof( mbedtls_mpi_uint ) );
mbedtls_platform_memset( Mp, 0, sizeof Mp );
mbedtls_platform_memcpy( Mp, N->p + P255_WIDTH - 1, M.n * sizeof( mbedtls_mpi_uint ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &M, 255 % ( 8 * sizeof( mbedtls_mpi_uint ) ) ) );
M.n++; /* Make room for multiplication by 19 */
@ -1306,8 +1306,8 @@ static int ecp_mod_p448( mbedtls_mpi *N )
/* Shouldn't be called with N larger than 2^896! */
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
M.p = Mp;
memset( Mp, 0, sizeof( Mp ) );
memcpy( Mp, N->p + P448_WIDTH, M.n * sizeof( mbedtls_mpi_uint ) );
mbedtls_platform_memset( Mp, 0, sizeof( Mp ) );
mbedtls_platform_memcpy( Mp, N->p + P448_WIDTH, M.n * sizeof( mbedtls_mpi_uint ) );
/* N = A0 */
for( i = P448_WIDTH; i < N->n; i++ )
@ -1319,7 +1319,7 @@ static int ecp_mod_p448( mbedtls_mpi *N )
/* Q = B1, N += B1 */
Q = M;
Q.p = Qp;
memcpy( Qp, Mp, sizeof( Qp ) );
mbedtls_platform_memcpy( Qp, Mp, sizeof( Qp ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &Q, 224 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( N, N, &Q ) );
@ -1374,8 +1374,8 @@ static inline int ecp_mod_koblitz( mbedtls_mpi *N, mbedtls_mpi_uint *Rp, size_t
M.n = N->n - ( p_limbs - adjust );
if( M.n > p_limbs + adjust )
M.n = p_limbs + adjust;
memset( Mp, 0, sizeof Mp );
memcpy( Mp, N->p + p_limbs - adjust, M.n * sizeof( mbedtls_mpi_uint ) );
mbedtls_platform_memset( Mp, 0, sizeof Mp );
mbedtls_platform_memcpy( Mp, N->p + p_limbs - adjust, M.n * sizeof( mbedtls_mpi_uint ) );
if( shift != 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &M, shift ) );
M.n += R.n; /* Make room for multiplication by R */
@ -1396,8 +1396,8 @@ static inline int ecp_mod_koblitz( mbedtls_mpi *N, mbedtls_mpi_uint *Rp, size_t
M.n = N->n - ( p_limbs - adjust );
if( M.n > p_limbs + adjust )
M.n = p_limbs + adjust;
memset( Mp, 0, sizeof Mp );
memcpy( Mp, N->p + p_limbs - adjust, M.n * sizeof( mbedtls_mpi_uint ) );
mbedtls_platform_memset( Mp, 0, sizeof Mp );
mbedtls_platform_memcpy( Mp, N->p + p_limbs - adjust, M.n * sizeof( mbedtls_mpi_uint ) );
if( shift != 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &M, shift ) );
M.n += R.n; /* Make room for multiplication by R */

View file

@ -43,9 +43,7 @@
#include <stdio.h>
#endif
#if defined(MBEDTLS_ENTROPY_NV_SEED)
#include "mbedtls/platform.h"
#endif
#if defined(MBEDTLS_SELF_TEST)
#if defined(MBEDTLS_PLATFORM_C)
@ -144,7 +142,11 @@ int mbedtls_entropy_add_source( mbedtls_entropy_context *ctx,
mbedtls_entropy_f_source_ptr f_source, void *p_source,
size_t threshold, int strong )
{
int idx, ret = 0;
int idx, ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
volatile mbedtls_entropy_f_source_ptr f_source_dup = f_source;
volatile void *p_source_dup = p_source;
volatile size_t threshold_dup = threshold;
volatile int strong_dup = strong;
#if defined(MBEDTLS_THREADING_C)
if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
@ -164,6 +166,7 @@ int mbedtls_entropy_add_source( mbedtls_entropy_context *ctx,
ctx->source[idx].strong = strong;
ctx->source_count++;
ret = 0;
exit:
#if defined(MBEDTLS_THREADING_C)
@ -171,6 +174,11 @@ exit:
return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
#endif
if( f_source_dup != f_source || p_source_dup != p_source ||
threshold_dup != threshold || strong_dup != strong )
{
ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
}
return( ret );
}
@ -184,8 +192,9 @@ static int entropy_update( mbedtls_entropy_context *ctx, unsigned char source_id
unsigned char tmp[MBEDTLS_ENTROPY_BLOCK_SIZE];
size_t use_len = len;
const unsigned char *p = data;
int ret = 0;
int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
volatile const unsigned char *data_dup = data;
volatile size_t len_dup = len;
if( use_len > MBEDTLS_ENTROPY_BLOCK_SIZE )
{
#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
@ -230,13 +239,17 @@ static int entropy_update( mbedtls_entropy_context *ctx, unsigned char source_id
cleanup:
mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
if( len_dup != len || data_dup != data )
{
ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
}
return( ret );
}
int mbedtls_entropy_update_manual( mbedtls_entropy_context *ctx,
const unsigned char *data, size_t len )
{
int ret;
int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
#if defined(MBEDTLS_THREADING_C)
if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
@ -258,7 +271,9 @@ int mbedtls_entropy_update_manual( mbedtls_entropy_context *ctx,
*/
static int entropy_gather_internal( mbedtls_entropy_context *ctx )
{
int ret, i, have_one_strong = 0;
int i;
volatile int ret = MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE;
volatile int have_one_strong_fi = MBEDTLS_ENTROPY_SOURCE_WEAK;
unsigned char buf[MBEDTLS_ENTROPY_MAX_GATHER];
size_t olen;
@ -270,8 +285,16 @@ static int entropy_gather_internal( mbedtls_entropy_context *ctx )
*/
for( i = 0; i < ctx->source_count; i++ )
{
if( ctx->source[i].strong == MBEDTLS_ENTROPY_SOURCE_STRONG )
have_one_strong = 1;
volatile int strong_fi = ctx->source[i].strong;
if( strong_fi == MBEDTLS_ENTROPY_SOURCE_STRONG )
{
mbedtls_platform_random_delay();
if( strong_fi == MBEDTLS_ENTROPY_SOURCE_STRONG )
have_one_strong_fi = MBEDTLS_ENTROPY_SOURCE_STRONG;
else
return( MBEDTLS_ERR_PLATFORM_FAULT_DETECTED );
}
olen = 0;
if( ( ret = ctx->source[i].f_source( ctx->source[i].p_source,
@ -292,13 +315,24 @@ static int entropy_gather_internal( mbedtls_entropy_context *ctx )
}
}
if( have_one_strong == 0 )
ret = MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE;
cleanup:
mbedtls_platform_zeroize( buf, sizeof( buf ) );
return( ret );
if( have_one_strong_fi == MBEDTLS_ENTROPY_SOURCE_STRONG )
{
mbedtls_platform_random_delay();
if( have_one_strong_fi == MBEDTLS_ENTROPY_SOURCE_STRONG )
{
return( ret );
}
else
{
return( MBEDTLS_ERR_PLATFORM_FAULT_DETECTED );
}
}
return( MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE );
}
/*
@ -306,7 +340,7 @@ cleanup:
*/
int mbedtls_entropy_gather( mbedtls_entropy_context *ctx )
{
int ret;
int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
#if defined(MBEDTLS_THREADING_C)
if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
@ -325,9 +359,13 @@ int mbedtls_entropy_gather( mbedtls_entropy_context *ctx )
int mbedtls_entropy_func( void *data, unsigned char *output, size_t len )
{
int ret, count = 0, i, done;
int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
int count = 0, i, done;
mbedtls_entropy_context *ctx = (mbedtls_entropy_context *) data;
unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];
volatile void *data_dup = data;
volatile unsigned char *output_dup = output;
volatile size_t len_dup = len;
if( len > MBEDTLS_ENTROPY_BLOCK_SIZE )
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
@ -424,7 +462,7 @@ int mbedtls_entropy_func( void *data, unsigned char *output, size_t len )
for( i = 0; i < ctx->source_count; i++ )
ctx->source[i].size = 0;
memcpy( output, buf, len );
mbedtls_platform_memcpy( output, buf, len );
ret = 0;
@ -435,7 +473,10 @@ exit:
if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
#endif
if( data_dup != data || len_dup != len || output_dup != output )
{
ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
}
return( ret );
}
@ -453,7 +494,7 @@ int mbedtls_entropy_update_nv_seed( mbedtls_entropy_context *ctx )
return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR );
/* Manually update the remaining stream with a separator value to diverge */
memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
mbedtls_platform_memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
ret = mbedtls_entropy_update_manual( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE );
return( ret );
@ -531,7 +572,7 @@ static int entropy_dummy_source( void *data, unsigned char *output,
{
((void) data);
memset( output, 0x2a, len );
mbedtls_platform_memset( output, 0x2a, len );
*olen = len;
return( 0 );
@ -602,8 +643,8 @@ int mbedtls_entropy_source_self_test( int verbose )
if( verbose != 0 )
mbedtls_printf( " ENTROPY_BIAS test: " );
memset( buf0, 0x00, sizeof( buf0 ) );
memset( buf1, 0x00, sizeof( buf1 ) );
mbedtls_platform_memset( buf0, 0x00, sizeof( buf0 ) );
mbedtls_platform_memset( buf1, 0x00, sizeof( buf1 ) );
if( ( ret = mbedtls_entropy_source_self_test_gather( buf0, sizeof( buf0 ) ) ) != 0 )
goto cleanup;

View file

@ -31,11 +31,13 @@
#endif
#include <string.h>
#include "mbedtls/platform_util.h"
#if defined(MBEDTLS_ENTROPY_C)
#include "mbedtls/entropy.h"
#include "mbedtls/entropy_poll.h"
#include "mbedtls/platform_util.h"
#if defined(MBEDTLS_TIMING_C)
#include "mbedtls/timing.h"
@ -106,7 +108,7 @@ static int getrandom_wrapper( void *buf, size_t buflen, unsigned int flags )
/* MemSan cannot understand that the syscall writes to the buffer */
#if defined(__has_feature)
#if __has_feature(memory_sanitizer)
memset( buf, 0, buflen );
mbedtls_platform_memset( buf, 0, buflen );
#endif
#endif
return( syscall( SYS_getrandom, buf, buflen, flags ) );
@ -187,7 +189,7 @@ int mbedtls_hardclock_poll( void *data,
if( len < sizeof(unsigned long) )
return( 0 );
memcpy( output, &timer, sizeof(unsigned long) );
mbedtls_platform_memcpy( output, &timer, sizeof(unsigned long) );
*olen = sizeof(unsigned long);
return( 0 );
@ -218,7 +220,7 @@ int mbedtls_nv_seed_poll( void *data,
size_t use_len = MBEDTLS_ENTROPY_BLOCK_SIZE;
((void) data);
memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
mbedtls_platform_memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
if( mbedtls_nv_seed_read( buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) < 0 )
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
@ -226,7 +228,7 @@ int mbedtls_nv_seed_poll( void *data,
if( len < use_len )
use_len = len;
memcpy( output, buf, use_len );
mbedtls_platform_memcpy( output, buf, use_len );
*olen = use_len;
return( 0 );

View file

@ -28,6 +28,7 @@
#if defined(MBEDTLS_ERROR_C) || defined(MBEDTLS_ERROR_STRERROR_DUMMY)
#include "mbedtls/error.h"
#include <string.h>
#include "mbedtls/platform_util.h"
#endif
#if defined(MBEDTLS_PLATFORM_C)
@ -218,14 +219,14 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
if( buflen == 0 )
return;
memset( buf, 0x00, buflen );
mbedtls_platform_memset( buf, 0x00, buflen );
if( ret < 0 )
ret = -ret;
if( ret & 0xFF80 )
if( ret & 0xFFFF80 )
{
use_ret = ret & 0xFF80;
use_ret = ret & 0xFFFF80;
// High level error codes
//
@ -523,6 +524,10 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
mbedtls_snprintf( buf, buflen, "SSL - The asynchronous operation is not completed yet" );
if( use_ret == -(MBEDTLS_ERR_SSL_EARLY_MESSAGE) )
mbedtls_snprintf( buf, buflen, "SSL - Internal-only message signaling that a message arrived early" );
if( use_ret == -(MBEDTLS_ERR_SSL_UNEXPECTED_CID) )
mbedtls_snprintf( buf, buflen, "SSL - An encrypted DTLS-frame with an unexpected CID was received" );
if( use_ret == -(MBEDTLS_ERR_SSL_VERSION_MISMATCH) )
mbedtls_snprintf( buf, buflen, "SSL - An operation failed due to an unexpected version or configuration" );
if( use_ret == -(MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) )
mbedtls_snprintf( buf, buflen, "SSL - A cryptographic operation is in progress. Try again later" );
#endif /* MBEDTLS_SSL_TLS_C */
@ -575,7 +580,7 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", use_ret );
}
use_ret = ret & ~0xFF80;
use_ret = ret & ~0xFFFF80;
if( use_ret == 0 )
return;
@ -836,6 +841,10 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
mbedtls_snprintf( buf, buflen, "PLATFORM - Hardware accelerator failed" );
if( use_ret == -(MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED) )
mbedtls_snprintf( buf, buflen, "PLATFORM - The requested feature is not supported by the platform" );
if( use_ret == -(MBEDTLS_ERR_PLATFORM_FAULT_DETECTED) )
mbedtls_snprintf( buf, buflen, "PLATFORM - A hardware fault was detected in a critical path. As a security precaution this should be treated as a potential physical attack" );
if( use_ret == -(MBEDTLS_ERR_PLATFORM_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "PLATFORM - Memory allocation failed" );
#endif /* MBEDTLS_PLATFORM_C */
#if defined(MBEDTLS_POLY1305_C)

View file

@ -92,7 +92,7 @@
void mbedtls_gcm_init( mbedtls_gcm_context *ctx )
{
GCM_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_gcm_context ) );
mbedtls_platform_memset( ctx, 0, sizeof( mbedtls_gcm_context ) );
}
/*
@ -111,7 +111,7 @@ static int gcm_gen_table( mbedtls_gcm_context *ctx )
unsigned char h[16];
size_t olen = 0;
memset( h, 0, 16 );
mbedtls_platform_memset( h, 0, 16 );
if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, h, 16, h, &olen ) ) != 0 )
return( ret );
@ -298,8 +298,8 @@ int mbedtls_gcm_starts( mbedtls_gcm_context *ctx,
return( MBEDTLS_ERR_GCM_BAD_INPUT );
}
memset( ctx->y, 0x00, sizeof(ctx->y) );
memset( ctx->buf, 0x00, sizeof(ctx->buf) );
mbedtls_platform_memset( ctx->y, 0x00, sizeof(ctx->y) );
mbedtls_platform_memset( ctx->buf, 0x00, sizeof(ctx->buf) );
ctx->mode = mode;
ctx->len = 0;
@ -307,12 +307,12 @@ int mbedtls_gcm_starts( mbedtls_gcm_context *ctx,
if( iv_len == 12 )
{
memcpy( ctx->y, iv, iv_len );
mbedtls_platform_memcpy( ctx->y, iv, iv_len );
ctx->y[15] = 1;
}
else
{
memset( work_buf, 0x00, 16 );
mbedtls_platform_memset( work_buf, 0x00, 16 );
PUT_UINT32_BE( iv_len * 8, work_buf, 12 );
p = iv;
@ -440,11 +440,11 @@ int mbedtls_gcm_finish( mbedtls_gcm_context *ctx,
if( tag_len > 16 || tag_len < 4 )
return( MBEDTLS_ERR_GCM_BAD_INPUT );
memcpy( tag, ctx->base_ectr, tag_len );
mbedtls_platform_memcpy( tag, ctx->base_ectr, tag_len );
if( orig_len || orig_add_len )
{
memset( work_buf, 0x00, 16 );
mbedtls_platform_memset( work_buf, 0x00, 16 );
PUT_UINT32_BE( ( orig_add_len >> 32 ), work_buf, 0 );
PUT_UINT32_BE( ( orig_add_len ), work_buf, 4 );
@ -797,6 +797,14 @@ int mbedtls_gcm_self_test( int verbose )
mbedtls_printf( " AES-GCM-%3d #%d (%s): ",
key_len, i, "enc" );
#if defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH)
if( key_len > 128 )
{
mbedtls_printf( "skipped\n" );
continue;
}
#endif /* MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */
ret = mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]],
key_len );
/*
@ -823,7 +831,7 @@ int mbedtls_gcm_self_test( int verbose )
goto exit;
if ( memcmp( buf, ct[j * 6 + i], pt_len[i] ) != 0 ||
memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )
memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )
{
ret = 1;
goto exit;
@ -855,7 +863,7 @@ int mbedtls_gcm_self_test( int verbose )
goto exit;
if( memcmp( buf, pt[pt_index[i]], pt_len[i] ) != 0 ||
memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )
memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )
{
ret = 1;
goto exit;
@ -907,7 +915,7 @@ int mbedtls_gcm_self_test( int verbose )
goto exit;
if( memcmp( buf, ct[j * 6 + i], pt_len[i] ) != 0 ||
memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )
memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )
{
ret = 1;
goto exit;
@ -960,7 +968,7 @@ int mbedtls_gcm_self_test( int verbose )
goto exit;
if( memcmp( buf, pt[pt_index[i]], pt_len[i] ) != 0 ||
memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )
memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )
{
ret = 1;
goto exit;

View file

@ -184,7 +184,7 @@ static void havege_fill( mbedtls_havege_state *hs )
(void)PTX;
memset( RES, 0, sizeof( RES ) );
mbedtls_platform_memset( RES, 0, sizeof( RES ) );
while( n < MBEDTLS_HAVEGE_COLLECT_SIZE * 4 )
{
@ -206,7 +206,7 @@ static void havege_fill( mbedtls_havege_state *hs )
*/
void mbedtls_havege_init( mbedtls_havege_state *hs )
{
memset( hs, 0, sizeof( mbedtls_havege_state ) );
mbedtls_platform_memset( hs, 0, sizeof( mbedtls_havege_state ) );
havege_fill( hs );
}
@ -241,7 +241,7 @@ int mbedtls_havege_random( void *p_rng, unsigned char *buf, size_t len )
val = hs->pool[hs->offset[0]++];
val ^= hs->pool[hs->offset[1]++];
memcpy( p, &val, use_len );
mbedtls_platform_memcpy( p, &val, use_len );
len -= use_len;
p += use_len;

View file

@ -30,7 +30,7 @@
#include "mbedtls/hkdf.h"
#include "mbedtls/platform_util.h"
int mbedtls_hkdf( const mbedtls_md_info_t *md, const unsigned char *salt,
int mbedtls_hkdf( mbedtls_md_handle_t md, const unsigned char *salt,
size_t salt_len, const unsigned char *ikm, size_t ikm_len,
const unsigned char *info, size_t info_len,
unsigned char *okm, size_t okm_len )
@ -51,7 +51,7 @@ int mbedtls_hkdf( const mbedtls_md_info_t *md, const unsigned char *salt,
return( ret );
}
int mbedtls_hkdf_extract( const mbedtls_md_info_t *md,
int mbedtls_hkdf_extract( mbedtls_md_handle_t md,
const unsigned char *salt, size_t salt_len,
const unsigned char *ikm, size_t ikm_len,
unsigned char *prk )
@ -81,7 +81,7 @@ int mbedtls_hkdf_extract( const mbedtls_md_info_t *md,
return( mbedtls_md_hmac( md, salt, salt_len, ikm, ikm_len, prk ) );
}
int mbedtls_hkdf_expand( const mbedtls_md_info_t *md, const unsigned char *prk,
int mbedtls_hkdf_expand( mbedtls_md_handle_t md, const unsigned char *prk,
size_t prk_len, const unsigned char *info,
size_t info_len, unsigned char *okm, size_t okm_len )
{
@ -177,7 +177,7 @@ int mbedtls_hkdf_expand( const mbedtls_md_info_t *md, const unsigned char *prk,
}
num_to_copy = i != n ? hash_len : okm_len - where;
memcpy( okm + where, t, num_to_copy );
mbedtls_platform_memcpy( okm + where, t, num_to_copy );
where += hash_len;
t_len = hash_len;
}

View file

@ -34,6 +34,7 @@
#if defined(MBEDTLS_HMAC_DRBG_C)
#include "mbedtls/hmac_drbg.h"
#include "mbedtls/platform.h"
#include "mbedtls/platform_util.h"
#include <string.h>
@ -51,6 +52,9 @@
#endif /* MBEDTLS_SELF_TEST */
#endif /* MBEDTLS_PLATFORM_C */
#define HMAC_NONCE_YES 0x4AAAAAAA
#define HMAC_NONCE_NO 0x75555555
/*
* HMAC_DRBG context initialization
*/
@ -70,45 +74,85 @@ int mbedtls_hmac_drbg_update_ret( mbedtls_hmac_drbg_context *ctx,
const unsigned char *additional,
size_t add_len )
{
size_t md_len = mbedtls_md_get_size( ctx->md_ctx.md_info );
size_t md_len = mbedtls_md_get_size(
mbedtls_md_get_handle( &ctx->md_ctx ) );
unsigned char rounds = ( additional != NULL && add_len != 0 ) ? 2 : 1;
unsigned char sep[1];
volatile unsigned int flow_counter = 0;
unsigned char K[MBEDTLS_MD_MAX_SIZE];
int ret;
int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
volatile const unsigned char *additional_dup = additional;
volatile size_t add_len_dup = add_len;
for( sep[0] = 0; sep[0] < rounds; sep[0]++ )
{
/* Step 1 or 4 */
flow_counter++;
if( ( ret = mbedtls_md_hmac_reset( &ctx->md_ctx ) ) != 0 )
goto exit;
flow_counter++;
if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx,
ctx->V, md_len ) ) != 0 )
goto exit;
flow_counter++;
if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx,
sep, 1 ) ) != 0 )
goto exit;
if( rounds == 2 )
{
flow_counter++;
if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx,
additional, add_len ) ) != 0 )
goto exit;
}
flow_counter++;
if( ( ret = mbedtls_md_hmac_finish( &ctx->md_ctx, K ) ) != 0 )
goto exit;
/* Step 2 or 5 */
flow_counter++;
if( ( ret = mbedtls_md_hmac_starts( &ctx->md_ctx, K, md_len ) ) != 0 )
goto exit;
flow_counter++;
if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx,
ctx->V, md_len ) ) != 0 )
goto exit;
flow_counter++;
if( ( ret = mbedtls_md_hmac_finish( &ctx->md_ctx, ctx->V ) ) != 0 )
goto exit;
flow_counter++;
}
exit:
mbedtls_platform_zeroize( K, sizeof( K ) );
return( ret );
/* Check for possible attack.
* Counters needs to have correct values when returning success
*/
if ( ret != 0 )
return( ret ); // error case, return immediately
if ( ( ( flow_counter == 8 ) && ( sep[0] == 1 ) ) ||
( ( flow_counter == 18 ) && ( sep[0] == 2 ) ) )
{
flow_counter = flow_counter - sep[0];
// Double check flow_counter
if ( ( flow_counter == 7 ) || ( flow_counter == 16 ) )
{
if( additional_dup == additional && add_len_dup == add_len )
{
return ret; // success, return 0 from ret
}
}
}
return( MBEDTLS_ERR_PLATFORM_FAULT_DETECTED );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
@ -124,10 +168,12 @@ void mbedtls_hmac_drbg_update( mbedtls_hmac_drbg_context *ctx,
* Simplified HMAC_DRBG initialisation (for use with deterministic ECDSA)
*/
int mbedtls_hmac_drbg_seed_buf( mbedtls_hmac_drbg_context *ctx,
const mbedtls_md_info_t * md_info,
const unsigned char *data, size_t data_len )
mbedtls_md_handle_t md_info,
const unsigned char *data, size_t data_len )
{
int ret;
int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
volatile const unsigned char *data_dup = data;
volatile size_t data_len_dup = data_len;
if( ( ret = mbedtls_md_setup( &ctx->md_ctx, md_info, 1 ) ) != 0 )
return( ret );
@ -144,8 +190,11 @@ int mbedtls_hmac_drbg_seed_buf( mbedtls_hmac_drbg_context *ctx,
if( ( ret = mbedtls_hmac_drbg_update_ret( ctx, data, data_len ) ) != 0 )
return( ret );
return( 0 );
if( data_dup != data || data_len_dup != data_len )
{
ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
}
return( ret );
}
/*
@ -159,22 +208,22 @@ static int hmac_drbg_reseed_core( mbedtls_hmac_drbg_context *ctx,
{
unsigned char seed[MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT];
size_t seedlen = 0;
int ret;
size_t total_entropy_len;
int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
volatile const unsigned char *additional_dup = additional;
volatile size_t len_dup = len;
int reseed_counter_backup = -1;
if( use_nonce == HMAC_NONCE_NO )
total_entropy_len = ctx->entropy_len;
else
total_entropy_len = ctx->entropy_len * 3 / 2;
/* III. Check input length */
if( len > MBEDTLS_HMAC_DRBG_MAX_INPUT ||
total_entropy_len + len > MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT )
{
size_t total_entropy_len;
if( use_nonce == 0 )
total_entropy_len = ctx->entropy_len;
else
total_entropy_len = ctx->entropy_len * 3 / 2;
/* III. Check input length */
if( len > MBEDTLS_HMAC_DRBG_MAX_INPUT ||
total_entropy_len + len > MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT )
{
return( MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG );
}
return( MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG );
}
memset( seed, 0, MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT );
@ -189,7 +238,7 @@ static int hmac_drbg_reseed_core( mbedtls_hmac_drbg_context *ctx,
/* For initial seeding, allow adding of nonce generated
* from the entropy source. See Sect 8.6.7 in SP800-90A. */
if( use_nonce )
if( use_nonce == HMAC_NONCE_YES )
{
/* Note: We don't merge the two calls to f_entropy() in order
* to avoid requesting too much entropy from f_entropy()
@ -212,7 +261,7 @@ static int hmac_drbg_reseed_core( mbedtls_hmac_drbg_context *ctx,
/* 1. Concatenate entropy and additional data if any */
if( additional != NULL && len != 0 )
{
memcpy( seed + seedlen, additional, len );
mbedtls_platform_memcpy( seed + seedlen, additional, len );
seedlen += len;
}
@ -221,12 +270,36 @@ static int hmac_drbg_reseed_core( mbedtls_hmac_drbg_context *ctx,
goto exit;
/* 3. Reset reseed_counter */
reseed_counter_backup = ctx->reseed_counter;
ctx->reseed_counter = 1;
exit:
/* 4. Done */
mbedtls_platform_zeroize( seed, seedlen );
return( ret );
if( additional_dup != additional || len_dup != len )
{
/* Rollback the reseed_counter in case of FI */
if( reseed_counter_backup != -1 )
ctx->reseed_counter = reseed_counter_backup;
return MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
}
if ( ret != 0 )
return ret;
if ( ret == 0 && ctx->reseed_counter == 1 )
{
/* All ok, return 0 from ret */
return ret;
}
/* Rollback the reseed_counter in case of FI */
if( reseed_counter_backup != -1 )
ctx->reseed_counter = reseed_counter_backup;
return( MBEDTLS_ERR_PLATFORM_FAULT_DETECTED );
}
/*
@ -235,7 +308,7 @@ exit:
int mbedtls_hmac_drbg_reseed( mbedtls_hmac_drbg_context *ctx,
const unsigned char *additional, size_t len )
{
return( hmac_drbg_reseed_core( ctx, additional, len, 0 ) );
return( hmac_drbg_reseed_core( ctx, additional, len, HMAC_NONCE_NO ) );
}
/*
@ -245,13 +318,18 @@ int mbedtls_hmac_drbg_reseed( mbedtls_hmac_drbg_context *ctx,
* from the entropy source as suggested in 8.6.7.
*/
int mbedtls_hmac_drbg_seed( mbedtls_hmac_drbg_context *ctx,
const mbedtls_md_info_t * md_info,
mbedtls_md_handle_t md_info,
int (*f_entropy)(void *, unsigned char *, size_t),
void *p_entropy,
const unsigned char *custom,
size_t len )
{
int ret;
int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
int (* volatile f_entropy_dup)(void *, unsigned char *, size_t) = f_entropy;
volatile void *p_entropy_dup = p_entropy;
volatile const unsigned char *custom_dup = custom;
volatile size_t len_dup = len;
size_t md_size;
if( ( ret = mbedtls_md_setup( &ctx->md_ctx, md_info, 1 ) ) != 0 )
@ -273,24 +351,31 @@ int mbedtls_hmac_drbg_seed( mbedtls_hmac_drbg_context *ctx,
ctx->reseed_interval = MBEDTLS_HMAC_DRBG_RESEED_INTERVAL;
/*
* See SP800-57 5.6.1 (p. 65-66) for the security strength provided by
* each hash function, then according to SP800-90A rev1 10.1 table 2,
* min_entropy_len (in bits) is security_strength.
*
* (This also matches the sizes used in the NIST test vectors.)
*/
ctx->entropy_len = md_size <= 20 ? 16 : /* 160-bits hash -> 128 bits */
md_size <= 28 ? 24 : /* 224-bits hash -> 192 bits */
32; /* better (256+) -> 256 bits */
if( ctx->entropy_len == 0 )
{
/*
* See SP800-57 5.6.1 (p. 65-66) for the security strength provided by
* each hash function, then according to SP800-90A rev1 10.1 table 2,
* min_entropy_len (in bits) is security_strength.
*
* (This also matches the sizes used in the NIST test vectors.)
*/
ctx->entropy_len = md_size <= 20 ? 16 : /* 160-bits hash -> 128 bits */
md_size <= 28 ? 24 : /* 224-bits hash -> 192 bits */
32; /* better (256+) -> 256 bits */
}
if( ( ret = hmac_drbg_reseed_core( ctx, custom, len,
1 /* add nonce */ ) ) != 0 )
if( ( ret = hmac_drbg_reseed_core( ctx, custom, len, HMAC_NONCE_YES ) ) != 0 )
{
return( ret );
}
return( 0 );
if( f_entropy != f_entropy_dup || p_entropy != p_entropy_dup ||
custom_dup != custom || len_dup != len )
{
ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
}
return( ret );
}
/*
@ -303,7 +388,7 @@ void mbedtls_hmac_drbg_set_prediction_resistance( mbedtls_hmac_drbg_context *ctx
}
/*
* Set entropy length grabbed for reseeds
* Set entropy length grabbed for seeding
*/
void mbedtls_hmac_drbg_set_entropy_len( mbedtls_hmac_drbg_context *ctx, size_t len )
{
@ -326,9 +411,12 @@ int mbedtls_hmac_drbg_random_with_add( void *p_rng,
unsigned char *output, size_t out_len,
const unsigned char *additional, size_t add_len )
{
int ret;
int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
volatile unsigned char *output_fi = output;
volatile size_t out_len_fi = out_len;
mbedtls_hmac_drbg_context *ctx = (mbedtls_hmac_drbg_context *) p_rng;
size_t md_len = mbedtls_md_get_size( ctx->md_ctx.md_info );
size_t md_len = mbedtls_md_get_size(
mbedtls_md_get_handle( &ctx->md_ctx ) );
size_t left = out_len;
unsigned char *out = output;
@ -372,7 +460,7 @@ int mbedtls_hmac_drbg_random_with_add( void *p_rng,
if( ( ret = mbedtls_md_hmac_finish( &ctx->md_ctx, ctx->V ) ) != 0 )
goto exit;
memcpy( out, ctx->V, use_len );
mbedtls_platform_memcpy( out, ctx->V, use_len );
out += use_len;
left -= use_len;
}
@ -387,7 +475,21 @@ int mbedtls_hmac_drbg_random_with_add( void *p_rng,
exit:
/* 8. Done */
return( ret );
if ( ret != 0 )
return ret;
/*
* Check doubled variables and illegal conditions in case of possible
* attack.
*/
if ( ( out_len_fi == out_len ) && ( output_fi == output) &&
( left == 0 ) )
{
return ret; // Success, return 0
}
return( MBEDTLS_ERR_PLATFORM_FAULT_DETECTED );
}
/*
@ -395,7 +497,7 @@ exit:
*/
int mbedtls_hmac_drbg_random( void *p_rng, unsigned char *output, size_t out_len )
{
int ret;
int ret = MBEDTLS_ERR_PLATFORM_FAULT_DETECTED;
mbedtls_hmac_drbg_context *ctx = (mbedtls_hmac_drbg_context *) p_rng;
#if defined(MBEDTLS_THREADING_C)
@ -563,7 +665,7 @@ int mbedtls_hmac_drbg_self_test( int verbose )
{
mbedtls_hmac_drbg_context ctx;
unsigned char buf[OUTPUT_LEN];
const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 );
mbedtls_md_handle_t md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 );
mbedtls_hmac_drbg_init( &ctx );

View file

@ -32,7 +32,7 @@
#if defined(MBEDTLS_MD_C)
#include "mbedtls/md.h"
#include "mbedtls/md_internal.h"
#include "mbedtls/platform.h"
#include "mbedtls/platform_util.h"
#if defined(MBEDTLS_PLATFORM_C)
@ -49,6 +49,177 @@
#include <stdio.h>
#endif
#if !defined(MBEDTLS_MD_SINGLE_HASH)
/*
*
* Definitions of MD information structures for various digests.
*
*/
/*
* MD-2
*/
#if defined(MBEDTLS_MD2_C)
static const mbedtls_md_info_t mbedtls_md2_info = {
MBEDTLS_MD_MD2,
"MD2",
16,
16,
mbedtls_md2_starts_wrap,
mbedtls_md2_update_wrap,
mbedtls_md2_finish_wrap,
mbedtls_md2_ret,
mbedtls_md2_ctx_alloc,
mbedtls_md2_ctx_free,
mbedtls_md2_clone_wrap,
mbedtls_md2_process_wrap,
};
#endif /* MBEDTLS_MD2_C */
/*
* MD-4
*/
#if defined(MBEDTLS_MD4_C)
static const mbedtls_md_info_t mbedtls_md4_info = {
MBEDTLS_MD_MD4,
"MD4",
16,
64,
mbedtls_md4_starts_wrap,
mbedtls_md4_update_wrap,
mbedtls_md4_finish_wrap,
mbedtls_md4_ret,
mbedtls_md4_ctx_alloc,
mbedtls_md4_ctx_free,
mbedtls_md4_clone_wrap,
mbedtls_md4_process_wrap,
};
#endif /* MBEDTLS_MD4_C */
/*
* MD-5
*/
#if defined(MBEDTLS_MD5_C)
static const mbedtls_md_info_t mbedtls_md5_info = {
MBEDTLS_MD_MD5,
"MD5",
16,
64,
mbedtls_md5_starts_wrap,
mbedtls_md5_update_wrap,
mbedtls_md5_finish_wrap,
mbedtls_md5_ret,
mbedtls_md5_ctx_alloc,
mbedtls_md5_ctx_free,
mbedtls_md5_clone_wrap,
mbedtls_md5_process_wrap,
};
#endif /* MBEDTLS_MD5_C */
/*
* RIPEMD-160
*/
#if defined(MBEDTLS_RIPEMD160_C)
static const mbedtls_md_info_t mbedtls_ripemd160_info = {
MBEDTLS_MD_RIPEMD160,
"RIPEMD160",
20,
64,
mbedtls_ripemd160_starts_wrap,
mbedtls_ripemd160_update_wrap,
mbedtls_ripemd160_finish_wrap,
mbedtls_ripemd160_ret,
mbedtls_ripemd160_ctx_alloc,
mbedtls_ripemd160_ctx_free,
mbedtls_ripemd160_clone_wrap,
mbedtls_ripemd160_process_wrap,
};
#endif /* MBEDTLS_RIPEMD160_C */
/*
* SHA-1
*/
#if defined(MBEDTLS_SHA1_C)
static const mbedtls_md_info_t mbedtls_sha1_info = {
MBEDTLS_MD_SHA1,
"SHA1",
20,
64,
mbedtls_sha1_starts_wrap,
mbedtls_sha1_update_wrap,
mbedtls_sha1_finish_wrap,
mbedtls_sha1_ret,
mbedtls_sha1_ctx_alloc,
mbedtls_sha1_ctx_free,
mbedtls_sha1_clone_wrap,
mbedtls_sha1_process_wrap,
};
#endif /* MBEDTLS_SHA1_C */
/*
* SHA-224 and SHA-256
*/
#if defined(MBEDTLS_SHA256_C)
#if !defined(MBEDTLS_SHA256_NO_SHA224)
static const mbedtls_md_info_t mbedtls_sha224_info = {
MBEDTLS_MD_SHA224,
"SHA224",
28,
64,
mbedtls_sha224_starts_wrap,
mbedtls_sha224_update_wrap,
mbedtls_sha224_finish_wrap,
mbedtls_sha224_wrap,
mbedtls_sha224_ctx_alloc,
mbedtls_sha224_ctx_free,
mbedtls_sha224_clone_wrap,
mbedtls_sha224_process_wrap,
};
#endif /* !MBEDTLS_SHA256_NO_SHA224 */
static const mbedtls_md_info_t mbedtls_sha256_info =
MBEDTLS_MD_INFO( MBEDTLS_MD_INFO_SHA256 );
#endif /* MBEDTLS_SHA256_C */
/*
* SHA-384 and SHA-512
*/
#if defined(MBEDTLS_SHA512_C)
static const mbedtls_md_info_t mbedtls_sha384_info = {
MBEDTLS_MD_SHA384,
"SHA384",
48,
128,
mbedtls_sha384_starts_wrap,
mbedtls_sha384_update_wrap,
mbedtls_sha384_finish_wrap,
mbedtls_sha384_wrap,
mbedtls_sha384_ctx_alloc,
mbedtls_sha384_ctx_free,
mbedtls_sha384_clone_wrap,
mbedtls_sha384_process_wrap,
};
static const mbedtls_md_info_t mbedtls_sha512_info = {
MBEDTLS_MD_SHA512,
"SHA512",
64,
128,
mbedtls_sha512_starts_wrap,
mbedtls_sha384_update_wrap,
mbedtls_sha384_finish_wrap,
mbedtls_sha512_wrap,
mbedtls_sha384_ctx_alloc,
mbedtls_sha384_ctx_free,
mbedtls_sha384_clone_wrap,
mbedtls_sha384_process_wrap,
};
#endif /* MBEDTLS_SHA512_C */
/*
* Reminder: update profiles in x509_crt.c when adding a new hash!
*/
@ -61,8 +232,10 @@ static const int supported_digests[] = {
#if defined(MBEDTLS_SHA256_C)
MBEDTLS_MD_SHA256,
#if !defined(MBEDTLS_SHA256_NO_SHA224)
MBEDTLS_MD_SHA224,
#endif
#endif /* MBEDTLS_SHA256_C */
#if defined(MBEDTLS_SHA1_C)
MBEDTLS_MD_SHA1,
@ -92,7 +265,7 @@ const int *mbedtls_md_list( void )
return( supported_digests );
}
const mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name )
mbedtls_md_handle_t mbedtls_md_info_from_string( const char *md_name )
{
if( NULL == md_name )
return( NULL );
@ -119,11 +292,13 @@ const mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name )
return mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 );
#endif
#if defined(MBEDTLS_SHA256_C)
#if !defined(MBEDTLS_SHA256_NO_SHA224)
if( !strcmp( "SHA224", md_name ) )
return mbedtls_md_info_from_type( MBEDTLS_MD_SHA224 );
#endif
if( !strcmp( "SHA256", md_name ) )
return mbedtls_md_info_from_type( MBEDTLS_MD_SHA256 );
#endif
#endif /* MBEDTLS_SHA256_C */
#if defined(MBEDTLS_SHA512_C)
if( !strcmp( "SHA384", md_name ) )
return mbedtls_md_info_from_type( MBEDTLS_MD_SHA384 );
@ -133,7 +308,7 @@ const mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name )
return( NULL );
}
const mbedtls_md_info_t *mbedtls_md_info_from_type( mbedtls_md_type_t md_type )
mbedtls_md_handle_t mbedtls_md_info_from_type( mbedtls_md_type_t md_type )
{
switch( md_type )
{
@ -158,11 +333,13 @@ const mbedtls_md_info_t *mbedtls_md_info_from_type( mbedtls_md_type_t md_type )
return( &mbedtls_sha1_info );
#endif
#if defined(MBEDTLS_SHA256_C)
#if !defined(MBEDTLS_SHA256_NO_SHA224)
case MBEDTLS_MD_SHA224:
return( &mbedtls_sha224_info );
#endif
case MBEDTLS_MD_SHA256:
return( &mbedtls_sha256_info );
#endif
#endif /* MBEDTLS_SHA256_C */
#if defined(MBEDTLS_SHA512_C)
case MBEDTLS_MD_SHA384:
return( &mbedtls_sha384_info );
@ -174,25 +351,69 @@ const mbedtls_md_info_t *mbedtls_md_info_from_type( mbedtls_md_type_t md_type )
}
}
#else /* MBEDTLS_MD_SINGLE_HASH */
const int *mbedtls_md_list( void )
{
static int single_hash[2] =
{ MBEDTLS_MD_INFO_TYPE( MBEDTLS_MD_SINGLE_HASH ),
MBEDTLS_MD_INVALID_HANDLE };
return( single_hash );
}
mbedtls_md_handle_t mbedtls_md_info_from_string( const char *md_name )
{
static const char * const hash_name =
MBEDTLS_MD_INFO_NAME( MBEDTLS_MD_SINGLE_HASH );
if( md_name != NULL && strcmp( hash_name, md_name ) == 0 )
return( MBEDTLS_MD_UNIQUE_VALID_HANDLE );
return( MBEDTLS_MD_INVALID_HANDLE );
}
mbedtls_md_handle_t mbedtls_md_info_from_type( mbedtls_md_type_t md_type )
{
static const mbedtls_md_type_t hash_type =
MBEDTLS_MD_INFO_TYPE( MBEDTLS_MD_SINGLE_HASH );
if( hash_type == md_type )
return( MBEDTLS_MD_UNIQUE_VALID_HANDLE );
return( MBEDTLS_MD_INVALID_HANDLE );
}
#endif /* MBEDTLS_MD_SINGLE_HASH */
void mbedtls_md_init( mbedtls_md_context_t *ctx )
{
memset( ctx, 0, sizeof( mbedtls_md_context_t ) );
#if defined(MBEDTLS_MD_SINGLE_HASH)
mbedtls_md_info_init( mbedtls_md_get_handle( ctx ),
ctx->md_ctx );
#endif
}
void mbedtls_md_free( mbedtls_md_context_t *ctx )
{
if( ctx == NULL || ctx->md_info == NULL )
if( ctx == NULL || mbedtls_md_get_handle( ctx ) == MBEDTLS_MD_INVALID_HANDLE )
return;
#if !defined(MBEDTLS_MD_SINGLE_HASH)
if( ctx->md_ctx != NULL )
ctx->md_info->ctx_free_func( ctx->md_ctx );
{
mbedtls_md_info_ctx_free( mbedtls_md_get_handle( ctx ), ctx->md_ctx );
}
if( ctx->hmac_ctx != NULL )
{
mbedtls_platform_zeroize( ctx->hmac_ctx,
2 * ctx->md_info->block_size );
2 * mbedtls_md_info_block_size( mbedtls_md_get_handle( ctx ) ) );
mbedtls_free( ctx->hmac_ctx );
}
#endif /* MBEDTLS_MD_SINGLE_HASH */
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md_context_t ) );
}
@ -200,83 +421,57 @@ void mbedtls_md_free( mbedtls_md_context_t *ctx )
int mbedtls_md_clone( mbedtls_md_context_t *dst,
const mbedtls_md_context_t *src )
{
if( dst == NULL || dst->md_info == NULL ||
src == NULL || src->md_info == NULL ||
dst->md_info != src->md_info )
if( dst == NULL || mbedtls_md_get_handle( dst ) == MBEDTLS_MD_INVALID_HANDLE ||
src == NULL || mbedtls_md_get_handle( src ) == MBEDTLS_MD_INVALID_HANDLE ||
mbedtls_md_get_handle( dst ) != mbedtls_md_get_handle( src ) )
{
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
}
dst->md_info->clone_func( dst->md_ctx, src->md_ctx );
mbedtls_md_info_clone( mbedtls_md_get_handle( dst ),
dst->md_ctx, src->md_ctx );
return( 0 );
}
#if ! defined(MBEDTLS_DEPRECATED_REMOVED)
int mbedtls_md_init_ctx( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info )
int mbedtls_md_init_ctx( mbedtls_md_context_t *ctx, mbedtls_md_handle_t md_info )
{
return mbedtls_md_setup( ctx, md_info, 1 );
}
#endif
int mbedtls_md_setup( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info, int hmac )
#if !defined(MBEDTLS_MD_SINGLE_HASH)
int mbedtls_md_setup( mbedtls_md_context_t *ctx, mbedtls_md_handle_t md_info, int hmac )
{
if( md_info == NULL || ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
if( ( ctx->md_ctx = md_info->ctx_alloc_func() ) == NULL )
return( MBEDTLS_ERR_MD_ALLOC_FAILED );
if( hmac != 0 )
{
ctx->hmac_ctx = mbedtls_calloc( 2, md_info->block_size );
if( ctx->hmac_ctx == NULL )
{
md_info->ctx_free_func( ctx->md_ctx );
return( MBEDTLS_ERR_MD_ALLOC_FAILED );
}
}
ctx->md_info = md_info;
return( 0 );
return( mbedtls_md_setup_internal( ctx, md_info, hmac ) );
}
int mbedtls_md_starts( mbedtls_md_context_t *ctx )
{
if( ctx == NULL || ctx->md_info == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return( ctx->md_info->starts_func( ctx->md_ctx ) );
return( mbedtls_md_starts_internal( ctx ) );
}
int mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen )
int mbedtls_md_update( mbedtls_md_context_t *ctx,
const unsigned char *input,
size_t ilen )
{
if( ctx == NULL || ctx->md_info == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return( ctx->md_info->update_func( ctx->md_ctx, input, ilen ) );
return( mbedtls_md_update_internal( ctx, input, ilen ) );
}
int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output )
{
if( ctx == NULL || ctx->md_info == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return( ctx->md_info->finish_func( ctx->md_ctx, output ) );
return( mbedtls_md_finish_internal( ctx, output ) );
}
int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, size_t ilen,
int mbedtls_md( mbedtls_md_handle_t md_info, const unsigned char *input, size_t ilen,
unsigned char *output )
{
if( md_info == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return( md_info->digest_func( input, ilen, output ) );
return( mbedtls_md_internal( md_info, input, ilen, output ) );
}
#endif /* !MBEDTLS_MD_SINGLE_HASH */
#if defined(MBEDTLS_FS_IO)
int mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path, unsigned char *output )
int mbedtls_md_file( mbedtls_md_handle_t md_info, const char *path, unsigned char *output )
{
int ret;
FILE *f;
@ -284,7 +479,7 @@ int mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path, unsigne
mbedtls_md_context_t ctx;
unsigned char buf[1024];
if( md_info == NULL )
if( md_info == MBEDTLS_MD_INVALID_HANDLE )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
if( ( f = fopen( path, "rb" ) ) == NULL )
@ -295,17 +490,27 @@ int mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path, unsigne
if( ( ret = mbedtls_md_setup( &ctx, md_info, 0 ) ) != 0 )
goto cleanup;
if( ( ret = md_info->starts_func( ctx.md_ctx ) ) != 0 )
ret = mbedtls_md_info_starts( md_info, ctx.md_ctx );
if( ret != 0 )
goto cleanup;
while( ( n = fread( buf, 1, sizeof( buf ), f ) ) > 0 )
if( ( ret = md_info->update_func( ctx.md_ctx, buf, n ) ) != 0 )
{
ret = mbedtls_md_info_update( md_info, ctx.md_ctx,
buf, n );
if( ret != 0 )
goto cleanup;
}
if( ferror( f ) != 0 )
{
ret = MBEDTLS_ERR_MD_FILE_IO_ERROR;
}
else
ret = md_info->finish_func( ctx.md_ctx, output );
{
ret = mbedtls_md_info_finish( md_info, ctx.md_ctx,
output );
}
cleanup:
mbedtls_platform_zeroize( buf, sizeof( buf ) );
@ -321,29 +526,46 @@ int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key,
int ret;
unsigned char sum[MBEDTLS_MD_MAX_SIZE];
unsigned char *ipad, *opad;
size_t i;
size_t i = 0;
if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )
mbedtls_md_handle_t md_info;
if( ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
if( keylen > (size_t) ctx->md_info->block_size )
#if !defined(MBEDTLS_MD_SINGLE_HASH)
if( ctx->hmac_ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
#endif /* !MBEDTLS_MD_SINGLE_HASH */
md_info = mbedtls_md_get_handle( ctx );
if( md_info == MBEDTLS_MD_INVALID_HANDLE )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
if( keylen > (size_t) mbedtls_md_info_block_size( md_info ) )
{
if( ( ret = ctx->md_info->starts_func( ctx->md_ctx ) ) != 0 )
goto cleanup;
if( ( ret = ctx->md_info->update_func( ctx->md_ctx, key, keylen ) ) != 0 )
goto cleanup;
if( ( ret = ctx->md_info->finish_func( ctx->md_ctx, sum ) ) != 0 )
if( ( ret = mbedtls_md_info_starts( md_info, ctx->md_ctx ) ) != 0 )
goto cleanup;
keylen = ctx->md_info->size;
if( ( ret = mbedtls_md_info_update( md_info, ctx->md_ctx,
key, keylen ) ) != 0 )
{
goto cleanup;
}
if( ( ret = mbedtls_md_info_finish( md_info, ctx->md_ctx, sum ) ) != 0 )
goto cleanup;
keylen = mbedtls_md_info_size( md_info );
key = sum;
}
ipad = (unsigned char *) ctx->hmac_ctx;
opad = (unsigned char *) ctx->hmac_ctx + ctx->md_info->block_size;
opad = (unsigned char *) ctx->hmac_ctx +
mbedtls_md_info_block_size( md_info );
memset( ipad, 0x36, ctx->md_info->block_size );
memset( opad, 0x5C, ctx->md_info->block_size );
mbedtls_platform_memset( ipad, 0x36, mbedtls_md_info_block_size( md_info ) );
mbedtls_platform_memset( opad, 0x5C, mbedtls_md_info_block_size( md_info ) );
for( i = 0; i < keylen; i++ )
{
@ -351,24 +573,52 @@ int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key,
opad[i] = (unsigned char)( opad[i] ^ key[i] );
}
if( ( ret = ctx->md_info->starts_func( ctx->md_ctx ) ) != 0 )
if( ( ret = mbedtls_md_info_starts( md_info, ctx->md_ctx ) ) != 0 )
goto cleanup;
if( ( ret = ctx->md_info->update_func( ctx->md_ctx, ipad,
ctx->md_info->block_size ) ) != 0 )
i++; // Use i as flow control
if( ( ret = mbedtls_md_info_update( md_info, ctx->md_ctx, ipad,
mbedtls_md_info_block_size( md_info ) ) ) != 0 )
{
goto cleanup;
}
i++; // Use i as flow control now
cleanup:
mbedtls_platform_zeroize( sum, sizeof( sum ) );
return( ret );
if ( ret != 0 )
return ret;
/* Check possible fault injection */
if ( ( i - 2 ) == keylen )
return ret; // success, return 0 from ret
return( MBEDTLS_ERR_PLATFORM_FAULT_DETECTED );
}
int mbedtls_md_hmac_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen )
int mbedtls_md_hmac_update( mbedtls_md_context_t *ctx,
const unsigned char *input, size_t ilen )
{
if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )
mbedtls_md_handle_t md_info;
if( ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return( ctx->md_info->update_func( ctx->md_ctx, input, ilen ) );
#if !defined(MBEDTLS_MD_SINGLE_HASH)
if( ctx->hmac_ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
#endif /* !MBEDTLS_MD_SINGLE_HASH */
md_info = mbedtls_md_get_handle( ctx );
if( md_info == MBEDTLS_MD_INVALID_HANDLE )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return( mbedtls_md_info_update( md_info,
ctx->md_ctx, input,
ilen ) );
}
int mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output )
@ -377,22 +627,45 @@ int mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output )
unsigned char tmp[MBEDTLS_MD_MAX_SIZE];
unsigned char *opad;
if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )
mbedtls_md_handle_t md_info;
if( ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
opad = (unsigned char *) ctx->hmac_ctx + ctx->md_info->block_size;
#if !defined(MBEDTLS_MD_SINGLE_HASH)
if( ctx->hmac_ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
#endif /* !MBEDTLS_MD_SINGLE_HASH */
if( ( ret = ctx->md_info->finish_func( ctx->md_ctx, tmp ) ) != 0 )
md_info = mbedtls_md_get_handle( ctx );
if( md_info == MBEDTLS_MD_INVALID_HANDLE )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
opad = (unsigned char *) ctx->hmac_ctx +
mbedtls_md_info_block_size( md_info );
if( ( ret = mbedtls_md_info_finish( md_info, ctx->md_ctx, tmp ) ) != 0 )
return( ret );
if( ( ret = ctx->md_info->starts_func( ctx->md_ctx ) ) != 0 )
if( ( ret = mbedtls_md_info_starts( md_info, ctx->md_ctx ) ) != 0 )
return( ret );
if( ( ret = ctx->md_info->update_func( ctx->md_ctx, opad,
ctx->md_info->block_size ) ) != 0 )
if( ( ret = mbedtls_md_info_update( md_info, ctx->md_ctx, opad,
mbedtls_md_info_block_size( md_info ) ) ) != 0 )
{
return( ret );
if( ( ret = ctx->md_info->update_func( ctx->md_ctx, tmp,
ctx->md_info->size ) ) != 0 )
}
if( ( ret = mbedtls_md_info_update( md_info, ctx->md_ctx, tmp,
mbedtls_md_info_size( md_info ) ) ) != 0 )
{
return( ret );
return( ctx->md_info->finish_func( ctx->md_ctx, output ) );
}
if( ( ret = mbedtls_md_info_finish( md_info, ctx->md_ctx, output ) ) != 0 )
return( ret );
return( ret );
}
int mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx )
@ -400,18 +673,33 @@ int mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx )
int ret;
unsigned char *ipad;
if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )
mbedtls_md_handle_t md_info;
if( ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
#if !defined(MBEDTLS_MD_SINGLE_HASH)
if( ctx->hmac_ctx == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
#endif /* !MBEDTLS_MD_SINGLE_HASH */
md_info = mbedtls_md_get_handle( ctx );
if( md_info == MBEDTLS_MD_INVALID_HANDLE )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
ipad = (unsigned char *) ctx->hmac_ctx;
if( ( ret = ctx->md_info->starts_func( ctx->md_ctx ) ) != 0 )
ret = mbedtls_md_info_starts( md_info, ctx->md_ctx );
if( ret != 0 )
return( ret );
return( ctx->md_info->update_func( ctx->md_ctx, ipad,
ctx->md_info->block_size ) );
ret = mbedtls_md_info_update( md_info,
ctx->md_ctx, ipad,
mbedtls_md_info_block_size( md_info ) );
return( ret );
}
int mbedtls_md_hmac( const mbedtls_md_info_t *md_info,
int mbedtls_md_hmac( mbedtls_md_handle_t md_info,
const unsigned char *key, size_t keylen,
const unsigned char *input, size_t ilen,
unsigned char *output )
@ -419,7 +707,7 @@ int mbedtls_md_hmac( const mbedtls_md_info_t *md_info,
mbedtls_md_context_t ctx;
int ret;
if( md_info == NULL )
if( md_info == MBEDTLS_MD_INVALID_HANDLE )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
mbedtls_md_init( &ctx );
@ -440,36 +728,35 @@ cleanup:
return( ret );
}
#if !defined(MBEDTLS_MD_SINGLE_HASH)
int mbedtls_md_process( mbedtls_md_context_t *ctx, const unsigned char *data )
{
if( ctx == NULL || ctx->md_info == NULL )
return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
return( ctx->md_info->process_func( ctx->md_ctx, data ) );
return( mbedtls_md_process_internal( ctx, data ) );
}
#endif /* !MBEDTLS_MD_SINGLE_HASH */
unsigned char mbedtls_md_get_size( const mbedtls_md_info_t *md_info )
unsigned char mbedtls_md_get_size( mbedtls_md_handle_t md_info )
{
if( md_info == NULL )
if( md_info == MBEDTLS_MD_INVALID_HANDLE )
return( 0 );
return md_info->size;
return mbedtls_md_info_size( md_info );
}
mbedtls_md_type_t mbedtls_md_get_type( const mbedtls_md_info_t *md_info )
mbedtls_md_type_t mbedtls_md_get_type( mbedtls_md_handle_t md_info )
{
if( md_info == NULL )
if( md_info == MBEDTLS_MD_INVALID_HANDLE )
return( MBEDTLS_MD_NONE );
return md_info->type;
return mbedtls_md_info_type( md_info );
}
const char *mbedtls_md_get_name( const mbedtls_md_info_t *md_info )
const char *mbedtls_md_get_name( mbedtls_md_handle_t md_info )
{
if( md_info == NULL )
if( md_info == MBEDTLS_MD_INVALID_HANDLE )
return( NULL );
return md_info->name;
return mbedtls_md_info_name( md_info );
}
#endif /* MBEDTLS_MD_C */

View file

@ -81,7 +81,7 @@ static const unsigned char PI_SUBST[256] =
void mbedtls_md2_init( mbedtls_md2_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_md2_context ) );
mbedtls_platform_memset( ctx, 0, sizeof( mbedtls_md2_context ) );
}
void mbedtls_md2_free( mbedtls_md2_context *ctx )
@ -103,9 +103,9 @@ void mbedtls_md2_clone( mbedtls_md2_context *dst,
*/
int mbedtls_md2_starts_ret( mbedtls_md2_context *ctx )
{
memset( ctx->cksum, 0, 16 );
memset( ctx->state, 0, 46 );
memset( ctx->buffer, 0, 16 );
mbedtls_platform_memset( ctx->cksum, 0, 16 );
mbedtls_platform_memset( ctx->state, 0, 46 );
mbedtls_platform_memset( ctx->buffer, 0, 16 );
ctx->left = 0;
return( 0 );
@ -180,7 +180,7 @@ int mbedtls_md2_update_ret( mbedtls_md2_context *ctx,
else
fill = ilen;
memcpy( ctx->buffer + ctx->left, input, fill );
mbedtls_platform_memcpy( ctx->buffer + ctx->left, input, fill );
ctx->left += fill;
input += fill;
@ -224,11 +224,11 @@ int mbedtls_md2_finish_ret( mbedtls_md2_context *ctx,
if( ( ret = mbedtls_internal_md2_process( ctx ) ) != 0 )
return( ret );
memcpy( ctx->buffer, ctx->cksum, 16 );
mbedtls_platform_memcpy( ctx->buffer, ctx->cksum, 16 );
if( ( ret = mbedtls_internal_md2_process( ctx ) ) != 0 )
return( ret );
memcpy( output, ctx->state, 16 );
mbedtls_platform_memcpy( output, ctx->state, 16 );
return( 0 );
}

View file

@ -74,7 +74,7 @@
void mbedtls_md4_init( mbedtls_md4_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_md4_context ) );
mbedtls_platform_memset( ctx, 0, sizeof( mbedtls_md4_context ) );
}
void mbedtls_md4_free( mbedtls_md4_context *ctx )
@ -271,7 +271,7 @@ int mbedtls_md4_update_ret( mbedtls_md4_context *ctx,
if( left && ilen >= fill )
{
memcpy( (void *) (ctx->buffer + left),
mbedtls_platform_memcpy( (void *) (ctx->buffer + left),
(void *) input, fill );
if( ( ret = mbedtls_internal_md4_process( ctx, ctx->buffer ) ) != 0 )
@ -293,7 +293,7 @@ int mbedtls_md4_update_ret( mbedtls_md4_context *ctx,
if( ilen > 0 )
{
memcpy( (void *) (ctx->buffer + left),
mbedtls_platform_memcpy( (void *) (ctx->buffer + left),
(void *) input, ilen );
}

View file

@ -73,7 +73,7 @@
void mbedtls_md5_init( mbedtls_md5_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_md5_context ) );
mbedtls_platform_memset( ctx, 0, sizeof( mbedtls_md5_context ) );
}
void mbedtls_md5_free( mbedtls_md5_context *ctx )
@ -277,7 +277,7 @@ int mbedtls_md5_update_ret( mbedtls_md5_context *ctx,
if( left && ilen >= fill )
{
memcpy( (void *) (ctx->buffer + left), input, fill );
mbedtls_platform_memcpy( (void *) (ctx->buffer + left), input, fill );
if( ( ret = mbedtls_internal_md5_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
@ -297,7 +297,7 @@ int mbedtls_md5_update_ret( mbedtls_md5_context *ctx,
if( ilen > 0 )
{
memcpy( (void *) (ctx->buffer + left), input, ilen );
mbedtls_platform_memcpy( (void *) (ctx->buffer + left), input, ilen );
}
return( 0 );
@ -332,17 +332,17 @@ int mbedtls_md5_finish_ret( mbedtls_md5_context *ctx,
if( used <= 56 )
{
/* Enough room for padding + length in current block */
memset( ctx->buffer + used, 0, 56 - used );
mbedtls_platform_memset( ctx->buffer + used, 0, 56 - used );
}
else
{
/* We'll need an extra block */
memset( ctx->buffer + used, 0, 64 - used );
mbedtls_platform_memset( ctx->buffer + used, 0, 64 - used );
if( ( ret = mbedtls_internal_md5_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
memset( ctx->buffer, 0, 56 );
mbedtls_platform_memset( ctx->buffer, 0, 56 );
}
/*

View file

@ -1,586 +0,0 @@
/**
* \file md_wrap.c
*
* \brief Generic message digest wrapper for mbed TLS
*
* \author Adriaan de Jong <dejong@fox-it.com>
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_MD_C)
#include "mbedtls/md_internal.h"
#if defined(MBEDTLS_MD2_C)
#include "mbedtls/md2.h"
#endif
#if defined(MBEDTLS_MD4_C)
#include "mbedtls/md4.h"
#endif
#if defined(MBEDTLS_MD5_C)
#include "mbedtls/md5.h"
#endif
#if defined(MBEDTLS_RIPEMD160_C)
#include "mbedtls/ripemd160.h"
#endif
#if defined(MBEDTLS_SHA1_C)
#include "mbedtls/sha1.h"
#endif
#if defined(MBEDTLS_SHA256_C)
#include "mbedtls/sha256.h"
#endif
#if defined(MBEDTLS_SHA512_C)
#include "mbedtls/sha512.h"
#endif
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdlib.h>
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif
#if defined(MBEDTLS_MD2_C)
static int md2_starts_wrap( void *ctx )
{
return( mbedtls_md2_starts_ret( (mbedtls_md2_context *) ctx ) );
}
static int md2_update_wrap( void *ctx, const unsigned char *input,
size_t ilen )
{
return( mbedtls_md2_update_ret( (mbedtls_md2_context *) ctx, input, ilen ) );
}
static int md2_finish_wrap( void *ctx, unsigned char *output )
{
return( mbedtls_md2_finish_ret( (mbedtls_md2_context *) ctx, output ) );
}
static void *md2_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_md2_context ) );
if( ctx != NULL )
mbedtls_md2_init( (mbedtls_md2_context *) ctx );
return( ctx );
}
static void md2_ctx_free( void *ctx )
{
mbedtls_md2_free( (mbedtls_md2_context *) ctx );
mbedtls_free( ctx );
}
static void md2_clone_wrap( void *dst, const void *src )
{
mbedtls_md2_clone( (mbedtls_md2_context *) dst,
(const mbedtls_md2_context *) src );
}
static int md2_process_wrap( void *ctx, const unsigned char *data )
{
((void) data);
return( mbedtls_internal_md2_process( (mbedtls_md2_context *) ctx ) );
}
const mbedtls_md_info_t mbedtls_md2_info = {
MBEDTLS_MD_MD2,
"MD2",
16,
16,
md2_starts_wrap,
md2_update_wrap,
md2_finish_wrap,
mbedtls_md2_ret,
md2_ctx_alloc,
md2_ctx_free,
md2_clone_wrap,
md2_process_wrap,
};
#endif /* MBEDTLS_MD2_C */
#if defined(MBEDTLS_MD4_C)
static int md4_starts_wrap( void *ctx )
{
return( mbedtls_md4_starts_ret( (mbedtls_md4_context *) ctx ) );
}
static int md4_update_wrap( void *ctx, const unsigned char *input,
size_t ilen )
{
return( mbedtls_md4_update_ret( (mbedtls_md4_context *) ctx, input, ilen ) );
}
static int md4_finish_wrap( void *ctx, unsigned char *output )
{
return( mbedtls_md4_finish_ret( (mbedtls_md4_context *) ctx, output ) );
}
static void *md4_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_md4_context ) );
if( ctx != NULL )
mbedtls_md4_init( (mbedtls_md4_context *) ctx );
return( ctx );
}
static void md4_ctx_free( void *ctx )
{
mbedtls_md4_free( (mbedtls_md4_context *) ctx );
mbedtls_free( ctx );
}
static void md4_clone_wrap( void *dst, const void *src )
{
mbedtls_md4_clone( (mbedtls_md4_context *) dst,
(const mbedtls_md4_context *) src );
}
static int md4_process_wrap( void *ctx, const unsigned char *data )
{
return( mbedtls_internal_md4_process( (mbedtls_md4_context *) ctx, data ) );
}
const mbedtls_md_info_t mbedtls_md4_info = {
MBEDTLS_MD_MD4,
"MD4",
16,
64,
md4_starts_wrap,
md4_update_wrap,
md4_finish_wrap,
mbedtls_md4_ret,
md4_ctx_alloc,
md4_ctx_free,
md4_clone_wrap,
md4_process_wrap,
};
#endif /* MBEDTLS_MD4_C */
#if defined(MBEDTLS_MD5_C)
static int md5_starts_wrap( void *ctx )
{
return( mbedtls_md5_starts_ret( (mbedtls_md5_context *) ctx ) );
}
static int md5_update_wrap( void *ctx, const unsigned char *input,
size_t ilen )
{
return( mbedtls_md5_update_ret( (mbedtls_md5_context *) ctx, input, ilen ) );
}
static int md5_finish_wrap( void *ctx, unsigned char *output )
{
return( mbedtls_md5_finish_ret( (mbedtls_md5_context *) ctx, output ) );
}
static void *md5_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_md5_context ) );
if( ctx != NULL )
mbedtls_md5_init( (mbedtls_md5_context *) ctx );
return( ctx );
}
static void md5_ctx_free( void *ctx )
{
mbedtls_md5_free( (mbedtls_md5_context *) ctx );
mbedtls_free( ctx );
}
static void md5_clone_wrap( void *dst, const void *src )
{
mbedtls_md5_clone( (mbedtls_md5_context *) dst,
(const mbedtls_md5_context *) src );
}
static int md5_process_wrap( void *ctx, const unsigned char *data )
{
return( mbedtls_internal_md5_process( (mbedtls_md5_context *) ctx, data ) );
}
const mbedtls_md_info_t mbedtls_md5_info = {
MBEDTLS_MD_MD5,
"MD5",
16,
64,
md5_starts_wrap,
md5_update_wrap,
md5_finish_wrap,
mbedtls_md5_ret,
md5_ctx_alloc,
md5_ctx_free,
md5_clone_wrap,
md5_process_wrap,
};
#endif /* MBEDTLS_MD5_C */
#if defined(MBEDTLS_RIPEMD160_C)
static int ripemd160_starts_wrap( void *ctx )
{
return( mbedtls_ripemd160_starts_ret( (mbedtls_ripemd160_context *) ctx ) );
}
static int ripemd160_update_wrap( void *ctx, const unsigned char *input,
size_t ilen )
{
return( mbedtls_ripemd160_update_ret( (mbedtls_ripemd160_context *) ctx,
input, ilen ) );
}
static int ripemd160_finish_wrap( void *ctx, unsigned char *output )
{
return( mbedtls_ripemd160_finish_ret( (mbedtls_ripemd160_context *) ctx,
output ) );
}
static void *ripemd160_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_ripemd160_context ) );
if( ctx != NULL )
mbedtls_ripemd160_init( (mbedtls_ripemd160_context *) ctx );
return( ctx );
}
static void ripemd160_ctx_free( void *ctx )
{
mbedtls_ripemd160_free( (mbedtls_ripemd160_context *) ctx );
mbedtls_free( ctx );
}
static void ripemd160_clone_wrap( void *dst, const void *src )
{
mbedtls_ripemd160_clone( (mbedtls_ripemd160_context *) dst,
(const mbedtls_ripemd160_context *) src );
}
static int ripemd160_process_wrap( void *ctx, const unsigned char *data )
{
return( mbedtls_internal_ripemd160_process(
(mbedtls_ripemd160_context *) ctx, data ) );
}
const mbedtls_md_info_t mbedtls_ripemd160_info = {
MBEDTLS_MD_RIPEMD160,
"RIPEMD160",
20,
64,
ripemd160_starts_wrap,
ripemd160_update_wrap,
ripemd160_finish_wrap,
mbedtls_ripemd160_ret,
ripemd160_ctx_alloc,
ripemd160_ctx_free,
ripemd160_clone_wrap,
ripemd160_process_wrap,
};
#endif /* MBEDTLS_RIPEMD160_C */
#if defined(MBEDTLS_SHA1_C)
static int sha1_starts_wrap( void *ctx )
{
return( mbedtls_sha1_starts_ret( (mbedtls_sha1_context *) ctx ) );
}
static int sha1_update_wrap( void *ctx, const unsigned char *input,
size_t ilen )
{
return( mbedtls_sha1_update_ret( (mbedtls_sha1_context *) ctx,
input, ilen ) );
}
static int sha1_finish_wrap( void *ctx, unsigned char *output )
{
return( mbedtls_sha1_finish_ret( (mbedtls_sha1_context *) ctx, output ) );
}
static void *sha1_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_sha1_context ) );
if( ctx != NULL )
mbedtls_sha1_init( (mbedtls_sha1_context *) ctx );
return( ctx );
}
static void sha1_clone_wrap( void *dst, const void *src )
{
mbedtls_sha1_clone( (mbedtls_sha1_context *) dst,
(const mbedtls_sha1_context *) src );
}
static void sha1_ctx_free( void *ctx )
{
mbedtls_sha1_free( (mbedtls_sha1_context *) ctx );
mbedtls_free( ctx );
}
static int sha1_process_wrap( void *ctx, const unsigned char *data )
{
return( mbedtls_internal_sha1_process( (mbedtls_sha1_context *) ctx,
data ) );
}
const mbedtls_md_info_t mbedtls_sha1_info = {
MBEDTLS_MD_SHA1,
"SHA1",
20,
64,
sha1_starts_wrap,
sha1_update_wrap,
sha1_finish_wrap,
mbedtls_sha1_ret,
sha1_ctx_alloc,
sha1_ctx_free,
sha1_clone_wrap,
sha1_process_wrap,
};
#endif /* MBEDTLS_SHA1_C */
/*
* Wrappers for generic message digests
*/
#if defined(MBEDTLS_SHA256_C)
static int sha224_starts_wrap( void *ctx )
{
return( mbedtls_sha256_starts_ret( (mbedtls_sha256_context *) ctx, 1 ) );
}
static int sha224_update_wrap( void *ctx, const unsigned char *input,
size_t ilen )
{
return( mbedtls_sha256_update_ret( (mbedtls_sha256_context *) ctx,
input, ilen ) );
}
static int sha224_finish_wrap( void *ctx, unsigned char *output )
{
return( mbedtls_sha256_finish_ret( (mbedtls_sha256_context *) ctx,
output ) );
}
static int sha224_wrap( const unsigned char *input, size_t ilen,
unsigned char *output )
{
return( mbedtls_sha256_ret( input, ilen, output, 1 ) );
}
static void *sha224_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_sha256_context ) );
if( ctx != NULL )
mbedtls_sha256_init( (mbedtls_sha256_context *) ctx );
return( ctx );
}
static void sha224_ctx_free( void *ctx )
{
mbedtls_sha256_free( (mbedtls_sha256_context *) ctx );
mbedtls_free( ctx );
}
static void sha224_clone_wrap( void *dst, const void *src )
{
mbedtls_sha256_clone( (mbedtls_sha256_context *) dst,
(const mbedtls_sha256_context *) src );
}
static int sha224_process_wrap( void *ctx, const unsigned char *data )
{
return( mbedtls_internal_sha256_process( (mbedtls_sha256_context *) ctx,
data ) );
}
const mbedtls_md_info_t mbedtls_sha224_info = {
MBEDTLS_MD_SHA224,
"SHA224",
28,
64,
sha224_starts_wrap,
sha224_update_wrap,
sha224_finish_wrap,
sha224_wrap,
sha224_ctx_alloc,
sha224_ctx_free,
sha224_clone_wrap,
sha224_process_wrap,
};
static int sha256_starts_wrap( void *ctx )
{
return( mbedtls_sha256_starts_ret( (mbedtls_sha256_context *) ctx, 0 ) );
}
static int sha256_wrap( const unsigned char *input, size_t ilen,
unsigned char *output )
{
return( mbedtls_sha256_ret( input, ilen, output, 0 ) );
}
const mbedtls_md_info_t mbedtls_sha256_info = {
MBEDTLS_MD_SHA256,
"SHA256",
32,
64,
sha256_starts_wrap,
sha224_update_wrap,
sha224_finish_wrap,
sha256_wrap,
sha224_ctx_alloc,
sha224_ctx_free,
sha224_clone_wrap,
sha224_process_wrap,
};
#endif /* MBEDTLS_SHA256_C */
#if defined(MBEDTLS_SHA512_C)
static int sha384_starts_wrap( void *ctx )
{
return( mbedtls_sha512_starts_ret( (mbedtls_sha512_context *) ctx, 1 ) );
}
static int sha384_update_wrap( void *ctx, const unsigned char *input,
size_t ilen )
{
return( mbedtls_sha512_update_ret( (mbedtls_sha512_context *) ctx,
input, ilen ) );
}
static int sha384_finish_wrap( void *ctx, unsigned char *output )
{
return( mbedtls_sha512_finish_ret( (mbedtls_sha512_context *) ctx,
output ) );
}
static int sha384_wrap( const unsigned char *input, size_t ilen,
unsigned char *output )
{
return( mbedtls_sha512_ret( input, ilen, output, 1 ) );
}
static void *sha384_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_sha512_context ) );
if( ctx != NULL )
mbedtls_sha512_init( (mbedtls_sha512_context *) ctx );
return( ctx );
}
static void sha384_ctx_free( void *ctx )
{
mbedtls_sha512_free( (mbedtls_sha512_context *) ctx );
mbedtls_free( ctx );
}
static void sha384_clone_wrap( void *dst, const void *src )
{
mbedtls_sha512_clone( (mbedtls_sha512_context *) dst,
(const mbedtls_sha512_context *) src );
}
static int sha384_process_wrap( void *ctx, const unsigned char *data )
{
return( mbedtls_internal_sha512_process( (mbedtls_sha512_context *) ctx,
data ) );
}
const mbedtls_md_info_t mbedtls_sha384_info = {
MBEDTLS_MD_SHA384,
"SHA384",
48,
128,
sha384_starts_wrap,
sha384_update_wrap,
sha384_finish_wrap,
sha384_wrap,
sha384_ctx_alloc,
sha384_ctx_free,
sha384_clone_wrap,
sha384_process_wrap,
};
static int sha512_starts_wrap( void *ctx )
{
return( mbedtls_sha512_starts_ret( (mbedtls_sha512_context *) ctx, 0 ) );
}
static int sha512_wrap( const unsigned char *input, size_t ilen,
unsigned char *output )
{
return( mbedtls_sha512_ret( input, ilen, output, 0 ) );
}
const mbedtls_md_info_t mbedtls_sha512_info = {
MBEDTLS_MD_SHA512,
"SHA512",
64,
128,
sha512_starts_wrap,
sha384_update_wrap,
sha384_finish_wrap,
sha512_wrap,
sha384_ctx_alloc,
sha384_ctx_free,
sha384_clone_wrap,
sha384_process_wrap,
};
#endif /* MBEDTLS_SHA512_C */
#endif /* MBEDTLS_MD_C */

View file

@ -315,7 +315,7 @@ static void *buffer_alloc_calloc( size_t n, size_t size )
mbedtls_exit( 1 );
ret = (unsigned char *) cur + sizeof( memory_header );
memset( ret, 0, original_len );
mbedtls_platform_memset( ret, 0, original_len );
return( ret );
}
@ -373,7 +373,7 @@ static void *buffer_alloc_calloc( size_t n, size_t size )
mbedtls_exit( 1 );
ret = (unsigned char *) cur + sizeof( memory_header );
memset( ret, 0, original_len );
mbedtls_platform_memset( ret, 0, original_len );
return( ret );
}
@ -438,7 +438,7 @@ static void buffer_alloc_free( void *ptr )
if( hdr->next != NULL )
hdr->next->prev = hdr;
memset( old, 0, sizeof(memory_header) );
mbedtls_platform_memset( old, 0, sizeof(memory_header) );
}
// Regroup with block after
@ -477,7 +477,7 @@ static void buffer_alloc_free( void *ptr )
if( hdr->next != NULL )
hdr->next->prev = hdr;
memset( old, 0, sizeof(memory_header) );
mbedtls_platform_memset( old, 0, sizeof(memory_header) );
}
// Prepend to free_list if we have not merged
@ -572,7 +572,7 @@ static void buffer_alloc_free_mutexed( void *ptr )
void mbedtls_memory_buffer_alloc_init( unsigned char *buf, size_t len )
{
memset( &heap, 0, sizeof( buffer_alloc_ctx ) );
mbedtls_platform_memset( &heap, 0, sizeof( buffer_alloc_ctx ) );
#if defined(MBEDTLS_THREADING_C)
mbedtls_mutex_init( &heap.mutex );
@ -593,7 +593,7 @@ void mbedtls_memory_buffer_alloc_init( unsigned char *buf, size_t len )
- (size_t)buf % MBEDTLS_MEMORY_ALIGN_MULTIPLE;
}
memset( buf, 0, len );
mbedtls_platform_memset( buf, 0, len );
heap.buf = buf;
heap.len = len;

Some files were not shown because too many files have changed in this diff Show more