Commit Graph

3420 Commits

Author SHA1 Message Date
k-stachowiak
202b1df5ba Fix handling of md failure
The failure of mbedtls_md was not checked in one place. This could have led
to an incorrect computation if a hardware accelerator failed. In most cases
this would have led to the key exchange failing, so the impact would have been
a hard-to-diagnose error reported in the wrong place. If the two sides of the
key exchange failed in the same way with an output from mbedtls_md that was
independent of the input, this could have led to an apparently successful key
exchange with a predictable key, thus a glitching md accelerator could have
caused a security vulnerability.
2019-07-08 15:26:09 +02:00
Gilles Peskine
d1800a76a9 Prevent building the HAVEGE module on platforms where it doesn't work
If int is not capable of storing as many values as unsigned, the code
may generate a trap value. If signed int and unsigned int aren't
32-bit types, the code may calculate meaningless values.
2019-07-05 11:33:10 +02:00
Gilles Peskine
8850e2e367 Fix misuse of signed ints in the HAVEGE module
The elements of the HAVEGE state are manipulated with bitwise
operations, with the expectations that the elements are 32-bit
unsigned integers (or larger). But they are declared as int, and so
the code has undefined behavior. Clang with Asan correctly points out
some shifts that reach the sign bit.

Use unsigned int internally. This is technically an aliasing violation
since we're accessing an array of `int` via a pointer to `unsigned
int`, but since we don't access the array directly inside the same
function, it's very unlikely to be compiled in an unintended manner.
2019-07-05 11:31:50 +02:00
Jaeden Amero
1e61b0fb3f Merge remote-tracking branch 'restricted/pr/581' into mbedtls-2.7-restricted
* restricted/pr/581:
  Remove unnecessary empty line
  Add a test for signing content with a long ECDSA key
  Add documentation notes about the required size of the signature buffers
  Add missing MBEDTLS_ECP_C dependencies in check_config.h
  Change size of preallocated buffer for pk_sign() calls
2019-06-24 11:40:49 +01:00
Jaeden Amero
0b2035794f Merge remote-tracking branch 'origin/pr/2713' into mbedtls-2.7
* origin/pr/2713:
  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()
2019-06-21 15:58:02 +01:00
Jaeden Amero
0cf1776a2d Merge remote-tracking branch 'origin/pr/2451' into mbedtls-2.7
* origin/pr/2451:
  Fix #2370, minor typos and spelling mistakes
2019-06-21 15:55:21 +01:00
Jaeden Amero
ba59f6b38e ssl_tls: Enable Suite B with subset of ECP curves
Make sure the code compiles even if some curves are not defined.

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

Fixes #2640
2019-06-20 16:28:10 +01:00
Jaeden Amero
1529ede823 net_sockets: Fix typo in net_would_block()
Fixes #528
2019-06-20 16:28:10 +01:00
Jaeden Amero
35a7e4675f Merge remote-tracking branch 'origin/pr/2688' into mbedtls-2.7
* origin/pr/2688:
  Update library version to 2.7.11
2019-06-18 14:22:59 +01:00
k-stachowiak
dff85e7e8a Remove unnecessary empty line 2019-06-13 11:54:49 +02:00
Jaeden Amero
6794f68d29 Update library version to 2.7.11 2019-06-11 17:31:57 +01:00
k-stachowiak
b50c39ca4a Change size of preallocated buffer for pk_sign() calls 2019-06-06 13:06:46 +02:00
Hanno Becker
c24e019513 Improve documentation of mbedtls_x509_get_ext()
- Explain the use of explicit ASN.1 tagging for the extensions structuree
- Remove misleading comment which suggests that mbedtls_x509_get_ext()
  also parsed the header of the first extension, which is not the case.
2019-06-04 14:03:27 +01:00
Hanno Becker
19557c2078 Always return a high-level error code from X.509 module
Some functions within the X.509 module return an ASN.1 low level
error code where instead this error code should be wrapped by a
high-level X.509 error code as in the bulk of the module.

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

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

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

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

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

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

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

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

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

This commit fixes this.

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

The following X.509 parsing tests need to be adapted:
- "TBSCertificate, issuer two inner set datas"
  This test exercises the X.509 CRT parser with a Subject name
  which has two empty `AttributeTypeAndValue` structures.
  This is supposed to fail with `MBEDTLS_ERR_ASN1_OUT_OF_DATA`
  because the parser should attempt to parse the first structure
  and fail because of a lack of data. Previously, it failed to
  obey the (0-length) bounds of the first AttributeTypeAndValue
  structure and would try to interpret the beginning of the second
  AttributeTypeAndValue structure as the first field of the first
  AttributeTypeAndValue structure, returning an UNEXPECTED_TAG error.
- "TBSCertificate, issuer, no full following string"
  This test exercises the parser's behaviour on an AttributeTypeAndValue
  structure which contains more data than expected; it should therefore
  fail with MBEDTLS_ERR_ASN1_LENGTH_MISMATCH. Because of the missing bounds
  check, it previously failed with UNEXPECTED_TAG because it interpreted
  the remaining byte in the first AttributeTypeAndValue structure as the
  first byte in the second AttributeTypeAndValue structure.
- "SubjectAltName repeated"
  This test should exercise two SubjectAltNames extensions in succession,
  but a wrong length values makes the second SubjectAltNames extension appear
  outside of the Extensions structure. With the new bounds in place, this
  therefore fails with a LENGTH_MISMATCH error. This commit adapts the test
  data to put the 2nd SubjectAltNames extension inside the Extensions
  structure, too.
2019-06-04 14:03:27 +01:00
Jaeden Amero
99b679f364 Merge remote-tracking branch 'origin/pr/2504' into mbedtls-2.7
* origin/pr/2504:
  Fix ChangeLog entry ordering
  Fix typo
  Add non-regression test for buffer overflow
  Improve documentation of mbedtls_mpi_write_string()
  Adapt ChangeLog
  Fix 1-byte buffer overflow in mbedtls_mpi_write_string()
2019-04-05 14:09:25 +01:00
Jaeden Amero
415255f4a0 Merge remote-tracking branch 'origin/pr/2513' into mbedtls-2.7
* origin/pr/2513:
  x509.c: Fix potential memory leak in X.509 self test
2019-04-05 13:48:19 +01:00
Jaeden Amero
a5f5ad3cf4 Merge remote-tracking branch 'restricted/pr/554' into mbedtls-2.7
* restricted/pr/554:
  Fix too small buffer in a test
  Add changelog entry for mbedtls_ecdh_get_params robustness
  Fix ecdh_get_params with mismatching group
  Add test case for ecdh_get_params with mismatching group
  Add test case for ecdh_calc_secret
2019-03-27 14:53:29 +00:00
Jaeden Amero
1beeeff394 Merge remote-tracking branch 'origin/pr/2527' into mbedtls-2.7
* origin/pr/2527:
  Update library version to 2.7.10
2019-03-26 14:53:56 +00:00
Jaeden Amero
b4686b4f32 Update library version to 2.7.10 2019-03-19 16:18:43 +00:00
Junhwan Park
e5d016356a x509.c: Fix potential memory leak in X.509 self test
Found and fixed by Junhwan Park in #2106.

Signed-off-by: Junhwan Park <semoking@naver.com>
2019-03-11 15:17:27 +02:00
Janos Follath
216e7385ef Fix typo 2019-03-06 14:00:44 +00:00
Hanno Becker
a277d4cc82 Improve documentation of mbedtls_mpi_write_string() 2019-03-06 14:00:33 +00:00
Hanno Becker
eff335d575 Fix 1-byte buffer overflow in mbedtls_mpi_write_string()
This can only occur for negative numbers. Fixes #2404.
2019-03-06 13:56:31 +00:00
Jaeden Amero
3a70ab9319 Merge remote-tracking branch 'origin/pr/2390' into mbedtls-2.7
* origin/pr/2390:
  Correct length check for DTLS records from old epochs.
2019-03-05 16:38:00 +00:00
Jaeden Amero
f921e8fa9f Merge remote-tracking branch 'origin/pr/2387' into mbedtls-2.7
* origin/pr/2387:
  Update change log
  all.sh: Test MBEDTLS_MPI_WINDOW_SIZE=1
  Fix DEADCODE in mbedtls_mpi_exp_mod()
2019-03-05 16:34:12 +00:00
Jaeden Amero
a47f32b9b9 Merge remote-tracking branch 'origin/pr/1976' into mbedtls-2.7
* origin/pr/1976:
  Move ChangeLog entry from Bugfix to Changes section
  Adapt ChangeLog
  Return from debugging functions if SSL context is unset
2019-03-05 16:28:59 +00:00
Jaeden Amero
6ee6f181ff Merge remote-tracking branch 'origin/pr/2435' into mbedtls-2.7
* origin/pr/2435:
  Use certificates from data_files and refer them
  Specify server certificate to use in SHA-1 test
  refactor CA and SRV certificates into separate blocks
  refactor SHA-1 certificate defintions and assignment
  refactor server SHA-1 certificate definition into a new block
  define TEST_SRV_CRT_RSA_SOME in similar logic to TEST_CA_CRT_RSA_SOME
  server SHA-256 certificate now follows the same logic as CA SHA-256 certificate
  add entry to ChangeLog
2019-03-05 16:25:53 +00:00
Simon Butcher
fb85576f05 Merge remote-tracking branch 'restricted/pr/529' into mbedtls-2.7
* restricted/pr/529:
  Fix order of sections in the ChangeLog
  Fix failure in SSLv3 per-version suites test
  Adjust DES exclude lists in test scripts
  Clarify 3DES changes in ChangeLog
  Fix documentation for 3DES removal
  Exclude 3DES tests in test scripts
  Fix wording of ChangeLog and 3DES_REMOVE docs
  Reduce priority of 3DES ciphersuites
2019-03-03 10:08:12 +00:00
Gilles Peskine
f58078c7c5 Fix ecdh_get_params with mismatching group
If mbedtls_ecdh_get_params is called with keys belonging to
different groups, make it return an error the second time, rather than
silently interpret the first key as being on the second curve.

This makes the non-regression test added by the previous commit pass.
2019-02-21 18:17:05 +01:00
Antonin Décimo
8fd9156a4a Fix #2370, minor typos and spelling mistakes 2019-02-18 15:57:54 +00:00
Ron Eldor
de0c841b94 Use certificates from data_files and refer them
Use the server certificate from `data_files` folder, for formality,
and refer to the source, for easier reproduction.
2019-02-13 16:00:07 +02:00
Andres Amaya Garcia
21ade06ef8 Reduce priority of 3DES ciphersuites 2019-02-13 09:52:46 +00:00
ILUXONCHIK
be3d1ee4ac refactor CA and SRV certificates into separate blocks 2019-02-12 15:38:22 +02:00
ILUXONCHIK
231385568e refactor SHA-1 certificate defintions and assignment
As per refactoring suggestion that I made in #1520.
2019-02-12 15:38:12 +02:00
ILUXONCHIK
62f9aec184 refactor server SHA-1 certificate definition into a new block 2019-02-12 15:38:03 +02:00
ILUXONCHIK
e3be6723b0 define TEST_SRV_CRT_RSA_SOME in similar logic to TEST_CA_CRT_RSA_SOME 2019-02-12 15:37:48 +02:00
ILUXONCHIK
4d8325eceb server SHA-256 certificate now follows the same logic as CA SHA-256 certificate 2019-02-12 15:37:39 +02:00
Andres Amaya Garcia
04ee5e0bbd Fix ASN1 bitstring writing
Refactor the function mbedtls_asn1_write_bitstring() that removes
trailing 0s at the end of DER encoded bitstrings. The function is
implemented according to Hanno Becker's suggestions.

This commit also changes the functions x509write_crt_set_ns_cert_type
and crt_set_key_usage to call the new function as the use named
bitstrings instead of the regular bitstrings.
2019-02-11 21:10:48 +00:00
Peter Kolbus
f5d153daf0 Fix DEADCODE in mbedtls_mpi_exp_mod()
In mbedtls_mpi_exp_mod(), the limit check on wsize is never true when
MBEDTLS_MPI_WINDOW_SIZE is at least 6. Wrap in a preprocessor guard
to remove the dead code and resolve a Coverity finding from the
DEADCODE checker.

Change-Id: Ice7739031a9e8249283a04de11150565b613ae89
2019-02-05 16:42:27 +01:00
Jens Wiklander
b2aa938ed6 fix memory leak in mpi_miller_rabin()
Fixes memory leak in mpi_miller_rabin() that occurs when the function has
failed to obtain a usable random 'A' 30 turns in a row.

Signed-off-by: Jens Wiklander <jens.wiklander@linaro.org>
2019-01-31 19:10:01 +02:00
Jaeden Amero
bdc807dbe8 Merge remote-tracking branch 'origin/pr/2343' into mbedtls-2.7 2019-01-30 15:45:15 +00:00
Jaeden Amero
9033e541a6 Merge remote-tracking branch 'origin/pr/2234' into mbedtls-2.7 2019-01-30 15:29:00 +00:00
Hanno Becker
a34cc6b1c6 Correct length check for DTLS records from old epochs.
DTLS records from previous epochs were incorrectly checked against the
current epoch transform's minimal content length, leading to the
rejection of entire datagrams. This commit fixed that and adapts two
test cases accordingly.

Internal reference: IOTSSL-1417
2019-01-30 15:07:09 +01:00
Simon Butcher
d09324ac58 Merge remote-tracking branch 'public/pr/2264' into mbedtls-2.7 2019-01-23 10:58:08 +01:00
Simon Butcher
c5b6c2f877 Merge remote-tracking branch 'public/pr/2296' into mbedtls-2.7 2019-01-23 09:51:48 +01:00
Janos Follath
4bf65fb71f Add clarifying comment about the backport 2019-01-21 10:56:23 +00:00
Janos Follath
7b774483bf Correct deterministic ECDSA behavior
We were still reusing the internal HMAC-DRBG of the deterministic ECDSA
for blinding. This meant that with cryptographically low likelyhood the
result was not the same signature as the one the deterministic ECDSA
algorithm has to produce (however it is still a valid ECDSA signature).

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

This workaround can't be implemented in the restartable case without
penalising the case where external RNG is available or completely
defeating the purpose of the restartable feature, therefore in this case
the small chance of incorrect behavior remains.
2019-01-16 17:25:13 +00:00
Janos Follath
2934c32da2 Add a safer deterministic ECDSA function
`mbedtls_ecdsa_sign_det` reuses the internal HMAC-DRBG instance to
implement blinding. The advantage of this is that the algorithm is
deterministic too, not just the resulting signature. The drawback is
that the blinding is always the same for the same key and message.
This diminishes the efficiency of blinding and leaks information about
the private key.

A function that takes external randomness fixes this weakness.
2019-01-16 16:00:27 +00:00
Manuel Pégourié-Gonnard
c80555d835 Add public function generating private keys
We need to separate the uses of the RNG for blinding and for key
generation for the sake of an upcoming security fix in deterministic
ECDSA.
2019-01-16 15:47:26 +00:00
Gilles Peskine
4e7b323fd8 Use CMAKE_BUILD_TYPE to do Asan builds
Use `cmake -D CMAKE_BUILD_TYPE=Asan` rather than manually setting
`-fsanitize=address`. This lets cmake determine the necessary compiler
and linker flags.

With UNSAFE_BUILD on, force -Wno-error. This is necessary to build
with MBEDTLS_TEST_NULL_ENTROPY.
2019-01-10 18:28:17 +01:00
Simon Butcher
b22a808cc6 Update the version of the library to 2.7.9 2018-12-21 10:52:37 +00:00
Ron Eldor
c7aac417f2 Return error code of underlying function.
Return the error code if failed, instead of returning value `1`.
If not failed, return the call of the underlying function,
in `mbedtls_ecdsa_genkey()`.
2018-12-17 10:22:19 +02:00
Jaeden Amero
b85e35d8d2 Merge remote-tracking branch 'upstream-public/pr/2102' into mbedtls-2.7 2018-12-07 16:15:46 +00:00
Jaeden Amero
93bfd1da0c Merge remote-tracking branch 'upstream-public/pr/2132' into mbedtls-2.7 2018-12-06 16:06:21 +00:00
Jaeden Amero
5e264e37d8 Merge remote-tracking branch 'upstream-public/pr/2129' into mbedtls-2.7 2018-12-06 16:02:43 +00:00
Jaeden Amero
a7d16ba3a1 Merge remote-tracking branch 'upstream-public/pr/2150' into mbedtls-2.7 2018-12-06 16:02:06 +00:00
Simon Butcher
41349fd2bc Fix CSR parsing header call
Change the secondary X509 CSR parsing call for the alternative MS header to only
occur if the first call fails due to the header being unfound, instead of any
call.
2018-12-05 23:23:39 +00:00
Simon Butcher
c47614ab42 Add support for alternative CSR headers
Add support for RFC7468, and the alternative Microsoft footer/headers for CSR's
that contain the text 'BEGIN NEW CERTIFICATE REQUEST' instead of
'BEGIN CERTIFICATE REQUEST'.
2018-12-05 23:17:52 +00:00
Simon Butcher
4a908ca6bb Update library version number to 2.7.8 2018-12-01 23:12:40 +00:00
Simon Butcher
4303f7619e Merge remote-tracking branch 'restricted/pr/513' into mbedtls-2.7-restricted 2018-11-29 17:27:35 +00:00
Simon Butcher
e34a4f5825 Merge remote-tracking branch 'restricted/pr/536' into mbedtls-2.7-restricted 2018-11-29 17:26:43 +00:00
Simon Butcher
a0d3e1d570 Merge remote-tracking branch 'restricted/pr/518' into mbedtls-2.7-restricted 2018-11-29 17:26:25 +00:00
Ron Eldor
e6cbfc3622 Refactor mpi_write_hlp to not be recursive
Refactor `mpi_write_hlp()` to not be recursive, to fix stack overflows.
Iterate over the `mbedtls_mpi` division of the radix requested,
until it is zero. Each iteration, put the residue in the next LSB
of the output buffer. Fixes #2190
2018-11-27 10:44:03 +02:00
Gilles Peskine
220cc17165 mbedtls_mpi_write_binary: don't leak the exact size of the number
In mbedtls_mpi_write_binary, avoid leaking the size of the number
through timing or branches, if possible. More precisely, if the number
fits in the output buffer based on its allocated size, the new code's
trace doesn't depend on the value of the number.
2018-11-26 12:45:35 +01:00
Simon Butcher
20f30d97a8 Update library version number to 2.7.7 2018-11-19 18:32:22 +00:00
Simon Butcher
58012321b8 Merge remote-tracking branch 'restricted/pr/521' into mbedtls-2.7-restricted-proposed 2018-11-07 13:36:00 +00:00
Simon Butcher
02d3b1cfbb Merge remote-tracking branch 'restricted/pr/523' into mbedtls-2.7-restricted-proposed 2018-11-07 13:35:07 +00:00
Simon Butcher
9136dab9c3 Merge remote-tracking branch 'public/pr/2138' into mbedtls-2.7-restricted-proposed 2018-11-07 13:34:42 +00:00
Simon Butcher
c37966239c Merge remote-tracking branch 'public/pr/2080' into mbedtls-2.7-restricted-proposed 2018-11-07 13:34:27 +00:00
Simon Butcher
ce8c509b3e Merge remote-tracking branch 'public/pr/2135' into mbedtls-2.7-restricted-proposed 2018-11-07 13:33:09 +00:00
Hanno Becker
18a4cbfac3 Don't perform binary comparison of CRL issuer and CA subject
Previously, when checking whether a CRT was revoked through
one of the configured CRLs, the library would only consider
those CRLs whose `issuer` field binary-matches the `subject`
field of the CA that has issued the CRT in question. If those
fields were not binary equivalent, the corresponding CRL was
discarded.

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

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

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

Fixes #1784.
2018-11-06 13:18:40 +00:00
Hanno Becker
52da7ee9e0 Move static x509_name_cmp() in library/x509_crt.c
A subsequent change will need this function earlier
within the file.
2018-11-06 13:18:23 +00:00
Hanno Becker
beedec8735 Add missing bracket
Wasn't spotted earlier because it's guarded by `! HAVE_GETRANDOM`.
2018-11-05 12:17:15 +00:00
Simon Butcher
7b28abc8ae Merge remote-tracking branch 'public/pr/2045' into mbedtls-2.7-proposed 2018-11-04 18:53:52 +00:00
Simon Butcher
5a15fa3cdc Merge remote-tracking branch 'public/pr/2096' into mbedtls-2.7-proposed 2018-11-04 18:48:46 +00:00
Hanno Becker
6b89197f26 Entropy: Fall through to /dev/random if getrandom() syscall unknown
This commit fixes issue #1212 related to platform-specific entropy
polling in an syscall-emulated environment.

Previously, the implementation of the entropy gathering function
`mbedtls_platform_entropy_poll()` for linux machines used the
following logic to determine how to obtain entropy from the kernel:

1. If the getrandom() system call identifier SYS_getrandom is present and
   the kernel version is 3.17 or higher, use syscall( SYS_getrandom, ... )
2. Otherwise, fall back to reading from /dev/random.

There are two issues with this:

1. Portability:
   When cross-compiling the code for a different
   architecture and running it through system call
   emulation in qemu, qemu reports the host kernel
   version through uname but, as of v.2.5.0,
   doesn't support emulating the getrandom() syscall.
   This leads to `mbedtls_platform_entropy_poll()`
   failing even though reading from /dev/random would
   have worked.

2. Style:
   Extracting the linux kernel version from
   the output of `uname` is slightly tedious.

This commit fixes both by implementing the suggestion in #1212:
- It removes the kernel-version detection through uname().
- Instead, it checks whether `syscall( SYS_getrandom, ... )`
  fails with errno set to ENOSYS indicating an unknown system call.
  If so, it falls through to trying to read from /dev/random.

Fixes #1212.
2018-10-30 09:31:15 +00:00
Simon Butcher
e2a6f01f3f Merge remote-tracking branch 'public/pr/1763' into mbedtls-2.7-proposed 2018-10-28 18:13:46 +00:00
Hanno Becker
52adf349fa Indentation fix 2018-10-26 10:08:29 +01:00
Hanno Becker
fa95a6ad22 Fix unsafe bounds checks in ssl_load_session()
Fixes #659 reported by Guido Vranken.
2018-10-26 10:08:28 +01:00
Hanno Becker
e67f7a7683 Use brackets around shift operations
Use `( x >> y ) & z` instead of `x >> y & z`. Both are equivalent
by operator precedence, but the former is more readable and the
commonly used idiom in the library.
2018-10-26 10:08:27 +01:00
Simon Butcher
e5eb2581f8 Make inclusion of stdio.h conditional in x509_crt.c
stdio.h was being included both conditionally if MBEDTLS_FS_IO was
defined, and also unconditionally, which made at least one of them
redundant.

This change removes the unconditional inclusion of stdio.h and makes it
conditional on MBEDTLS_PLATFORM_C.
2018-10-25 18:23:07 +01:00
Hanno Becker
5cc4f76f5f Reinitialize PK ctx in mbedtls_pk_parse_key before reuse are free
Context: This commit makes a change to mbedtls_pk_parse_key() which
is responsible for parsing of private keys. The function doesn't know
the key format in advance (PEM vs. DER, encrypted vs. unencrypted) and
tries them one by one, resetting the PK context in between.

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

Change: The commit adds calls to mbedtls_pk_init() after those calls
to mbedtls_pk_free() within mbedtls_pk_parse_key() after which the
PK context might still be used.
2018-10-25 15:24:21 +01:00
Brian J Murray
e02c9050cf typo fix 2018-10-23 07:40:13 -07:00
Darryl Green
94759f6593 Mark internal function as static 2018-10-19 09:21:15 +01:00
Darryl Green
56d7cc472f Fix bias in random number generation in Miller-Rabin test
When a random number is generated for the Miller-Rabin primality test,
if the bit length of the random number is larger than the number being
tested, the random number is shifted right to have the same bit length.
This introduces bias, as the random number is now guaranteed to be
larger than 2^(bit length-1).

Changing this to instead zero all bits higher than the tested numbers
bit length will remove this bias and keep the random number being
uniformly generated.
2018-10-19 09:21:15 +01:00
Hanno Becker
ca31b47188 Fail when encountering invalid CBC padding in EtM records
This commit changes the behavior of the record decryption routine
`ssl_decrypt_buf()` in the following situation:
1. A CBC ciphersuite with Encrypt-then-MAC is used.
2. A record with valid MAC but invalid CBC padding is received.
In this situation, the previous code would not raise and error but
instead forward the decrypted packet, including the wrong padding,
to the user.

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

While erroneous, the previous behavior does not constitute a
security flaw since it can only happen for properly authenticated
records, that is, if the peer makes a mistake while preparing the
padded plaintext.
2018-10-17 14:54:16 +01:00
Hanno Becker
a4d116e20f Duplicate mbedtls_asn1_find_named_data in asn1write.c to avoid dep.
This commit duplicates the public function mbedtls_asn1_find_named_data()
defined in library/asn1parse.c within library/asn1write.c in order to
avoid a dependency of the ASN.1 writing module on the ASN.1 parsing module.

The duplication is unproblematic from a semantic and an efficiency
perspective becasue it is just a short list traversal that doesn't
actually do any ASN.1 parsing.
2018-10-16 13:54:01 +01:00
Hanno Becker
5ed0355bc8 Guard mbedtls_pkcs5_pbes2() by MBEDTLS_ASN1_PARSE_C
Previously, mbedtls_pkcs5_pbes2() was unconditionally declared
in `pkcs5.h` but defined as a stub returning
`MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE` in case
MBEDTLS_ASN1_PARSE_C was not defined.

In line with the previous commits, this commit removes declaration
and definition from both `pkcs5.h` and `pkcs5.c` in case
MBEDTLS_ASN1_PARSE_C is not defined.
2018-10-16 13:53:58 +01:00
Hanno Becker
d30cd34dc2 Make PBE-related parts of PKCS12 depend on MBEDTLS_ASN1_PARSE_C 2018-10-16 13:53:50 +01:00
Hanno Becker
d82e0c0235 Add missing zeroization of reassembled handshake messages
This commit ensures that buffers holding fragmented or
handshake messages get zeroized before they are freed
when the respective handshake message is no longer needed.
Previously, the handshake message content would leak on
the heap.
2018-10-16 09:14:03 +01:00
Gilles Peskine
84a21d5a54 Fix undefined behavior in unsigned-to-signed conversion
The code assumed that `int x = - (unsigned) u` with 0 <= u < INT_MAX
sets `x` to the negative of u, but actually this calculates
(UINT_MAX - u) and then converts this value to int, which overflows.
Cast to int before applying the unary minus operator to guarantee the
desired behavior.
2018-10-12 19:19:12 +02:00
Gilles Peskine
66a28e991d Fix likely-harmless undefined behavior surrounding volatile
The code was making two unsequenced reads from volatile locations.
This is undefined behavior. It was probably harmless because we didn't
care in what order the reads happened and the reads were from ordinary
memory, but UB is UB and IAR8 complained.
2018-10-12 19:15:34 +02:00
Janos Follath
72d555dd7c Bignum: Fix prime validation vulnerability
The input distribution to primality testing functions is completely
different when used for generating primes and when for validating
primes. The constants used in the library are geared towards the prime
generation use case and are weak when used for validation. (Maliciously
constructed composite numbers can pass the test with high probability)

The mbedtls_mpi_is_prime() function is in the public API and although it
is not documented, it is reasonable to assume that the primary use case
is validating primes. The RSA module too uses it for validating key
material.
2018-10-11 15:38:46 +01:00
Hanno Becker
643f311921 Omit runtime configuration of calloc/free if macro config enabled
This commit removes the definition of the API function

`mbedtls_platform_set_calloc_free()`

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

`MBEDTLS_PLATFORM_CALLOC_MACRO`
`MBEDTLS_PLATFORM_FREE_MACRO`

for compile time configuration of calloc/free are set.

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

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

The conversion is safe because `len` is representable by 16-bits,
hence smaller than the maximum integer.
2018-10-10 15:50:05 +01:00
Hanno Becker
63c706f429 Fix bounds check in ssl_parse_server_psk_hint()
In the previous bounds check `(*p) > end - len`, the computation
of `end - len` might underflow if `end` is within the first 64KB
of the address space (note that the length `len` is controlled by
the peer). In this case, the bounds check will be bypassed, leading
to `*p` exceed the message bounds by up to 64KB when leaving
`ssl_parse_server_psk_hint()`. In a pure PSK-based handshake,
this doesn't seem to have any consequences, as `*p*` is not accessed
afterwards. In a PSK-(EC)DHE handshake, however, `*p` is read from
in `ssl_parse_server_ecdh_params()` and `ssl_parse_server_dh_params()`
which might lead to an application crash of information leakage.
2018-10-08 13:53:51 +01:00
Janos Follath
b39740e934 Bignum: Remove dead code
Both variables affected by the code are overwritten before their next
read.
2018-10-08 12:06:45 +01:00
Gilles Peskine
23d7ceaca9 PKCS#1 v1.5 decoding: fix empty payload case 2018-10-08 11:49:15 +02:00
Gilles Peskine
0b330f764f Remove a remaining sensitive memory access in PKCS#1 v1.5 decryption 2018-10-08 11:49:15 +02:00
Gilles Peskine
03fb3e36e4 mbedtls_rsa_rsaes_pkcs1_v15_decrypt: remove the variable p
Get rid of the variable p. This makes it more apparent where the code
accesses the buffer at an offset whose value is sensitive.

No intended behavior change in this commit.
2018-10-08 11:49:15 +02:00
Gilles Peskine
087544bc98 Minor optimization in the PKCS#1v1.5 unpadding step
Rather than doing the quadratic-time constant-memory-trace on the
whole working buffer, do it on the section of the buffer where the
data to copy has to lie, which can be significantly smaller if the
output buffer is significantly smaller than the working buffer, e.g.
for TLS RSA ciphersuites (48 bytes vs MBEDTLS_MPI_MAX_SIZE).
2018-10-08 11:49:15 +02:00
Gilles Peskine
cf1253e8f0 Use branch-free size comparison for the padding size
In mbedtls_rsa_rsaes_pkcs1_v15_decrypt, use size_greater_than (which
is based on bitwise operations) instead of the < operator to compare
sizes when the values being compared must not leak. Some compilers
compile < to a branch at least under some circumstances (observed with
gcc 5.4 for arm-gnueabi -O9 on a toy program).
2018-10-08 11:49:15 +02:00
Gilles Peskine
a04f8bbd0d Bleichenbacher fix: don't leak the plaintext length (step 2)
Replace memmove(to, to + offset, length) by a functionally equivalent
function that strives to make the same memory access patterns
regardless of the value of length. This fixes an information leak
through timing (especially timing of memory accesses via cache probes)
that leads to a Bleichenbacher-style attack on PKCS#1 v1.5 decryption
using the plaintext length as the observable.
2018-10-08 11:49:15 +02:00
Gilles Peskine
f9dd29e3a8 Bleichenbacher fix: don't leak the plaintext length (step 1)
mbedtls_rsa_rsaes_pkcs1_v15_decrypt takes care not to reveal whether
the padding is valid or not, even through timing or memory access
patterns. This is a defense against an attack published by
Bleichenbacher. The attacker can also obtain the same information by
observing the length of the plaintext. The current implementation
leaks the length of the plaintext through timing and memory access
patterns.

This commit is a first step towards fixing this leak. It reduces the
leak to a single memmove call inside the working buffer.
2018-10-08 11:49:15 +02:00
Gilles Peskine
b473916dcf Evolve choose_int_from_mask to if_int
Make the function more robust by taking an arbitrary zero/nonzero
argument instead of insisting on zero/all-bits-one. Update and fix its
documentation.
2018-10-08 11:49:15 +02:00
Gilles Peskine
dabe87cd71 Fix a timing-based Bleichenbacher attack on PKCS#1v1.5 decryption
mbedtls_rsa_rsaes_pkcs1_v15_decrypt took care of calculating the
padding length without leaking the amount of padding or the validity
of the padding. However it then skipped the copying of the data if the
padding was invalid, which could allow an adversary to find out
whether the padding was valid through precise timing measurements,
especially if for a local attacker who could observe memory access via
cache timings.

Avoid this leak by always copying from the decryption buffer to the
output buffer, even when the padding is invalid. With invalid padding,
copy the same amount of data as what is expected on valid padding: the
minimum valid padding size if this fits in the output buffer,
otherwise the output buffer size. To avoid leaking payload data from
an unsuccessful decryption, zero the decryption buffer before copying
if the padding was invalid.
2018-10-08 11:49:15 +02:00
Gilles Peskine
cd500f3832 Minor readability improvement
Polish the beginning of mbedtls_rsa_rsaes_pkcs1_v15_decrypt a little,
to prepare for some behavior changes.
2018-10-08 11:49:15 +02:00
irwir
88eeb4f3f7 Implicit _endthread call: comment changed 2018-10-01 14:33:34 +01:00
irwir
5afc7ba8bf Added spaces after type casts
`(void) TimerContext;` seems more consistent with the current style than ((void) TimerContext);
No objections to changing this if necessary.
2018-10-01 14:33:25 +01:00
irwir
8efb3cc0d1 Replace Windows API threading with CRT functions 2018-10-01 14:33:16 +01:00
Simon Butcher
651902d062 Merge remote-tracking branch 'public/pr/1972' into mbedtls-2.7 2018-09-26 22:35:51 +01:00
Gilles Peskine
aadc818126 HMAC_DRBG: report all errors from HMAC functions
Make sure that any error from mbedtls_md_hmac_xxx is propagated.
2018-09-13 22:20:58 +02:00
Gilles Peskine
4d23757fad HMAC_DRBG: deprecate mbedtls_hmac_drbg_update because it ignores errors
Deprecate mbedtls_hmac_drbg_update (which returns void) in favor of a
new function mbedtls_hmac_drbg_update_ret which reports error. The old
function is not officially marked as deprecated in this branch because
this is a stable maintenance branch.
2018-09-13 22:19:57 +02:00
Gilles Peskine
9ce2972399 CTR_DRBG: add mbedtls_ctr_drbg_update_ret
Deprecate mbedtls_ctr_drbg_update (which returns void) in favor of a
new function mbedtls_ctr_drbg_update_ret which reports error. The old
function is not officially marked as deprecated in this branch because
this is a stable maintenance branch.
2018-09-13 22:19:31 +02:00
Gilles Peskine
1da7776bd7 HMAC_DRBG: clean stack buffers
Wipe stack buffers that may contain sensitive data (data that
contributes to the DRBG state.
2018-09-13 22:11:17 +02:00
Gilles Peskine
d324c5954a CTR_DRBG: clean stack buffers
Wipe stack buffers that may contain sensitive data (data that
contributes to the DRBG state.
2018-09-13 22:10:46 +02:00
Gilles Peskine
98add4fd5a Fix pk_write with an EC key to write a constant-length private value
When writing a private EC key, use a constant size for the private
value, as specified in RFC 5915. Previously, the value was written
as an ASN.1 INTEGER, which caused the size of the key to leak
about 1 bit of information on average, and could cause the value to be
1 byte too large for the output buffer.
2018-09-04 11:22:08 +02:00
Simon Butcher
34997fd291 Update library version number to 2.7.6 2018-08-31 16:07:23 +01:00
Simon Butcher
9877efb401 Merge remote-tracking branch 'restricted/pr/437' into mbedtls-2.7-restricted 2018-08-28 15:34:28 +01:00
Simon Butcher
242169bdc3 Merge remote-tracking branch 'restricted/pr/498' into mbedtls-2.7-restricted 2018-08-28 15:29:55 +01:00
Simon Butcher
6910201cd1 Merge remote-tracking branch 'restricted/pr/493' into mbedtls-2.7-restricted 2018-08-28 15:23:39 +01:00
Simon Butcher
4102b3d377 Merge remote-tracking branch 'public/pr/1888' into mbedtls-2.7 2018-08-28 12:25:12 +01:00
Simon Butcher
cc4f58d08c Merge remote-tracking branch 'public/pr/1956' into mbedtls-2.7 2018-08-28 12:16:11 +01:00
Simon Butcher
f7be6b029e Merge remote-tracking branch 'public/pr/1960' into mbedtls-2.7 2018-08-28 11:51:56 +01:00
Hanno Becker
99f3916e31 Return from debugging functions if SSL context is unset
The debugging functions
- mbedtls_debug_print_ret,
- mbedtls_debug_print_buf,
- mbedtls_debug_print_mpi, and
- mbedtls_debug_print_crt
return immediately if the SSL configuration bound to the
passed SSL context is NULL, has no debugging functions
configured, or if the debug threshold is below the debugging
level.
However, they do not check whether the provided SSL context
is not NULL before accessing the SSL configuration bound to it,
therefore leading to a segmentation fault if it is.
In contrast, the debugging function
- mbedtls_debug_print_msg
does check for ssl != NULL before accessing ssl->conf.

This commit unifies the checks by always returning immediately
if ssl == NULL.
2018-08-23 14:57:39 +01:00
Hanno Becker
6c794faa46 Fix bug in SSL ticket implementation removing keys of age < 1s
Fixes #1968.
2018-08-22 14:58:31 +01:00
Hanno Becker
12f7ede56e Compute record expansion in steps to ease readability 2018-08-17 15:30:03 +01:00
Hanno Becker
dbd3e88479 Fix mbedtls_ssl_get_record_expansion() for CBC modes
`mbedtls_ssl_get_record_expansion()` is supposed to return the maximum
difference between the size of a protected record and the size of the
encapsulated plaintext.

Previously, it did not correctly estimate the maximum record expansion
in case of CBC ciphersuites in (D)TLS versions 1.1 and higher, in which
case the ciphertext is prefixed by an explicit IV.

This commit fixes this bug. Fixes #1914.
2018-08-17 10:12:21 +01:00
Hanno Becker
78d5d8225e Fix overly strict bounds check in ssl_parse_certificate_request() 2018-08-16 15:53:02 +01:00
Hanno Becker
cd6a64a516 Reset session_in/out pointers in ssl_session_reset_int()
Fixes #1941.
2018-08-14 15:48:36 +01:00
Jaeden Amero
9eb78b4dab Merge remote-tracking branch 'upstream-public/pr/1900' into mbedtls-2.7
Add a Changelog entry
2018-08-10 11:26:15 +01:00
Jaeden Amero
f37a99e3fc Merge remote-tracking branch 'upstream-public/pr/1814' into mbedtls-2.7 2018-08-10 11:01:29 +01:00
Jaeden Amero
3b69174852 Merge remote-tracking branch 'upstream-public/pr/1886' into mbedtls-2.7 2018-08-10 10:50:34 +01:00
k-stachowiak
2c161144e2 Revert change of a return variable name 2018-07-31 17:02:56 +02:00
Ron Eldor
15b0a39322 enforce input and output of ccm selftest on stack
In `mbedtls_ccm_self_test()`, enforce input and output
buffers sent to the ccm API to be contigous and aligned,
by copying the test vectors to buffers on the stack.
2018-07-30 11:43:08 +03:00
Philippe Antoine
84cc74e82b Fix undefined shifts
- in x509_profile_check_pk_alg
- in x509_profile_check_md_alg
- in x509_profile_check_key

and in ssl_cli.c : unsigned char gets promoted to signed integer
2018-07-26 22:49:42 +01:00
Angus Gratton
cb7a5b0b0c Fix memory leak in ecp_mul_comb() if ecp_precompute_comb() fails
In ecp_mul_comb(), if (!p_eq_g && grp->T == NULL) and then ecp_precompute_comb() fails (which can
happen due to OOM), then the new array of points T will be leaked (as it's newly allocated, but
hasn't been asigned to grp->T yet).

Symptom was a memory leak in ECDHE key exchange under low memory conditions.
2018-07-26 11:08:06 +03:00
Jaeden Amero
8385110ae8 Update version to 2.7.5 2018-07-25 15:43:21 +01:00
Simon Butcher
7daacda940 Merge remote-tracking branch 'restricted/pr/494' into mbedtls-2.7 2018-07-24 23:40:53 +01:00
Simon Butcher
d5a3ed36b8 Merge remote-tracking branch 'public/pr/1863' into mbedtls-2.7 2018-07-24 12:57:15 +01:00
k-stachowiak
f4a668870f Fix code formatting 2018-07-24 12:54:39 +02:00
Simon Butcher
b65d6ce83f Merge remote-tracking branch 'public/pr/1870' into mbedtls-2.7 2018-07-24 10:30:11 +01:00
Dawid Drozd
2ba7d8ed2d Remove unnecessary mark as unused #1098 (backport) 2018-07-20 14:08:02 +02:00
Simon Butcher
bc5ec41c01 Merge remote-tracking branch 'public/pr/1847' into mbedtls-2.7 2018-07-19 19:48:25 +01:00
Angus Gratton
8946b0dd30 Check for invalid short Alert messages
(Short Change Cipher Spec & Handshake messages are already checked for.)
2018-07-16 20:12:56 +01:00
Angus Gratton
b91cb6e1e6 TLSv1.2: Treat zero-length fragments as invalid, unless they are application data
TLS v1.2 explicitly disallows other kinds of zero length fragments (earlier standards
don't mention zero-length fragments at all).
2018-07-16 20:12:55 +01:00
Angus Gratton
1ba8e911ec CBC mode: Allow zero-length message fragments (100% padding)
Fixes https://github.com/ARMmbed/mbedtls/issues/1632
2018-07-16 20:12:47 +01:00
k-stachowiak
6978949cd0 Prevent buffer overread by one byte 2018-07-16 12:30:39 +02:00