Explorar o código

【更新】mbedtls 版本 2.7.10 ,支持部分硬件加解密接口

tangyuxin %!s(int64=6) %!d(string=hai) anos
pai
achega
19d475c515
Modificáronse 100 ficheiros con 8047 adicións e 2561 borrados
  1. 1 1
      SConscript
  2. 3 0
      mbedtls/.gitignore
  3. 1003 0
      mbedtls/ChangeLog
  4. 109 70
      mbedtls/README.md
  5. 5 0
      mbedtls/include/CMakeLists.txt
  6. 220 146
      mbedtls/include/mbedtls/aes.h
  7. 8 1
      mbedtls/include/mbedtls/aesni.h
  8. 37 1
      mbedtls/include/mbedtls/arc4.h
  9. 18 2
      mbedtls/include/mbedtls/asn1.h
  10. 22 12
      mbedtls/include/mbedtls/asn1write.h
  11. 8 1
      mbedtls/include/mbedtls/base64.h
  12. 8 3
      mbedtls/include/mbedtls/bignum.h
  13. 3 1
      mbedtls/include/mbedtls/blowfish.h
  14. 32 18
      mbedtls/include/mbedtls/bn_mul.h
  15. 3 1
      mbedtls/include/mbedtls/camellia.h
  16. 100 59
      mbedtls/include/mbedtls/ccm.h
  17. 8 1
      mbedtls/include/mbedtls/certs.h
  18. 10 1
      mbedtls/include/mbedtls/check_config.h
  19. 302 259
      mbedtls/include/mbedtls/cipher.h
  20. 2 1
      mbedtls/include/mbedtls/cipher_internal.h
  21. 117 73
      mbedtls/include/mbedtls/cmac.h
  22. 8 1
      mbedtls/include/mbedtls/compat-1.3.h
  23. 216 26
      mbedtls/include/mbedtls/config.h
  24. 180 115
      mbedtls/include/mbedtls/ctr_drbg.h
  25. 2 1
      mbedtls/include/mbedtls/debug.h
  26. 51 0
      mbedtls/include/mbedtls/des.h
  27. 935 179
      mbedtls/include/mbedtls/dhm.h
  28. 157 88
      mbedtls/include/mbedtls/ecdh.h
  29. 180 112
      mbedtls/include/mbedtls/ecdsa.h
  30. 24 2
      mbedtls/include/mbedtls/ecjpake.h
  31. 10 2
      mbedtls/include/mbedtls/ecp.h
  32. 9 2
      mbedtls/include/mbedtls/ecp_internal.h
  33. 3 1
      mbedtls/include/mbedtls/entropy.h
  34. 2 1
      mbedtls/include/mbedtls/entropy_poll.h
  35. 31 15
      mbedtls/include/mbedtls/error.h
  36. 161 86
      mbedtls/include/mbedtls/gcm.h
  37. 8 1
      mbedtls/include/mbedtls/havege.h
  38. 30 3
      mbedtls/include/mbedtls/hmac_drbg.h
  39. 235 136
      mbedtls/include/mbedtls/md.h
  40. 182 9
      mbedtls/include/mbedtls/md2.h
  41. 187 9
      mbedtls/include/mbedtls/md4.h
  42. 186 8
      mbedtls/include/mbedtls/md5.h
  43. 8 7
      mbedtls/include/mbedtls/md_internal.h
  44. 2 1
      mbedtls/include/mbedtls/memory_buffer_alloc.h
  45. 10 4
      mbedtls/include/mbedtls/net.h
  46. 5 3
      mbedtls/include/mbedtls/net_sockets.h
  47. 20 1
      mbedtls/include/mbedtls/oid.h
  48. 8 1
      mbedtls/include/mbedtls/padlock.h
  49. 8 1
      mbedtls/include/mbedtls/pem.h
  50. 9 7
      mbedtls/include/mbedtls/pk.h
  51. 3 2
      mbedtls/include/mbedtls/pk_internal.h
  52. 2 1
      mbedtls/include/mbedtls/pkcs11.h
  53. 12 1
      mbedtls/include/mbedtls/pkcs12.h
  54. 12 1
      mbedtls/include/mbedtls/pkcs5.h
  55. 58 53
      mbedtls/include/mbedtls/platform.h
  56. 2 1
      mbedtls/include/mbedtls/platform_time.h
  57. 113 12
      mbedtls/include/mbedtls/ripemd160.h
  58. 603 218
      mbedtls/include/mbedtls/rsa.h
  59. 226 0
      mbedtls/include/mbedtls/rsa_internal.h
  60. 217 31
      mbedtls/include/mbedtls/sha1.h
  61. 176 39
      mbedtls/include/mbedtls/sha256.h
  62. 180 41
      mbedtls/include/mbedtls/sha512.h
  63. 104 34
      mbedtls/include/mbedtls/ssl.h
  64. 8 1
      mbedtls/include/mbedtls/ssl_cache.h
  65. 9 2
      mbedtls/include/mbedtls/ssl_ciphersuites.h
  66. 8 1
      mbedtls/include/mbedtls/ssl_cookie.h
  67. 65 11
      mbedtls/include/mbedtls/ssl_internal.h
  68. 8 1
      mbedtls/include/mbedtls/ssl_ticket.h
  69. 6 1
      mbedtls/include/mbedtls/threading.h
  70. 25 5
      mbedtls/include/mbedtls/timing.h
  71. 7 6
      mbedtls/include/mbedtls/version.h
  72. 2 1
      mbedtls/include/mbedtls/x509.h
  73. 2 1
      mbedtls/include/mbedtls/x509_crl.h
  74. 46 22
      mbedtls/include/mbedtls/x509_crt.h
  75. 10 1
      mbedtls/include/mbedtls/x509_csr.h
  76. 3 1
      mbedtls/include/mbedtls/xtea.h
  77. 10 3
      mbedtls/library/CMakeLists.txt
  78. 20 17
      mbedtls/library/Makefile
  79. 130 108
      mbedtls/library/aes.c
  80. 45 14
      mbedtls/library/asn1write.c
  81. 106 54
      mbedtls/library/bignum.c
  82. 27 12
      mbedtls/library/ccm.c
  83. 26 14
      mbedtls/library/cipher.c
  84. 3 3
      mbedtls/library/cipher_wrap.c
  85. 10 2
      mbedtls/library/cmac.c
  86. 107 41
      mbedtls/library/ctr_drbg.c
  87. 1 1
      mbedtls/library/debug.c
  88. 49 13
      mbedtls/library/dhm.c
  89. 4 0
      mbedtls/library/ecdh.c
  90. 20 2
      mbedtls/library/ecdsa.c
  91. 4 1
      mbedtls/library/ecjpake.c
  92. 8 5
      mbedtls/library/ecp.c
  93. 103 33
      mbedtls/library/entropy.c
  94. 9 48
      mbedtls/library/entropy_poll.c
  95. 124 11
      mbedtls/library/error.c
  96. 102 98
      mbedtls/library/gcm.c
  97. 79 27
      mbedtls/library/hmac_drbg.c
  98. 58 51
      mbedtls/library/md.c
  99. 99 20
      mbedtls/library/md2.c
  100. 110 22
      mbedtls/library/md4.c

+ 1 - 1
SConscript

@@ -121,7 +121,7 @@ if len(ROOT_CA_FILE) > 0:
             with open(ROOT_CA_FILE[i], 'r') as ca:
             with open(ROOT_CA_FILE[i], 'r') as ca:
                 # Pre-read, check first line
                 # Pre-read, check first line
                 if not ca.readline().startswith("-----BEGIN CERTIFICATE"):
                 if not ca.readline().startswith("-----BEGIN CERTIFICATE"):
-                    print "[mbedtls] Warning: ", ROOT_CA_FILE[i], "is not CA file! Skipped!"
+                    print("[mbedtls] Warning: ", ROOT_CA_FILE[i], "is not CA file! Skipped!")
                     continue
                     continue
                 ca.seek(0)
                 ca.seek(0)
                 for line in ca.readlines():
                 for line in ca.readlines():

+ 3 - 0
mbedtls/.gitignore

@@ -21,5 +21,8 @@ massif-*
 *.ilk
 *.ilk
 *.lib
 *.lib
 
 
+# Python build artifacts:
+*.pyc
+
 # CMake generates *.dir/ folders for in-tree builds (used by MSVC projects), ignore all of those:
 # CMake generates *.dir/ folders for in-tree builds (used by MSVC projects), ignore all of those:
 *.dir/
 *.dir/

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 1003 - 0
mbedtls/ChangeLog


+ 109 - 70
mbedtls/README.md

@@ -1,62 +1,33 @@
-README for mbed TLS
+README for Mbed TLS
 ===================
 ===================
 
 
 Configuration
 Configuration
 -------------
 -------------
 
 
-mbed TLS should build out of the box on most systems. Some platform specific options are available in the fully documented configuration file `include/mbedtls/config.h`, which is also the place where features can be selected. This file can be edited manually, or in a more programmatic way using the Perl script `scripts/config.pl` (use `--help` for usage instructions).
+Mbed TLS should build out of the box on most systems. Some platform specific options are available in the fully documented configuration file `include/mbedtls/config.h`, which is also the place where features can be selected. This file can be edited manually, or in a more programmatic way using the Perl script `scripts/config.pl` (use `--help` for usage instructions).
 
 
 Compiler options can be set using conventional environment variables such as `CC` and `CFLAGS` when using the Make and CMake build system (see below).
 Compiler options can be set using conventional environment variables such as `CC` and `CFLAGS` when using the Make and CMake build system (see below).
 
 
 Compiling
 Compiling
 ---------
 ---------
 
 
-There are currently four active build systems used within mbed TLS releases:
+There are currently three active build systems used within Mbed TLS releases:
 
 
--   yotta
--   Make
+-   GNU Make
 -   CMake
 -   CMake
--   Microsoft Visual Studio (Visual Studio 6 and Visual Studio 2010)
+-   Microsoft Visual Studio (Microsoft Visual Studio 2010 or later)
 
 
-The main systems used for development are CMake and Make. Those systems are always complete and up-to-date. The others should reflect all changes present in the CMake and Make build system, although features may not be ported there automatically.
-
-Yotta, as a build system, is slightly different from the other build systems:
-
--   it provides a minimalistic configuration file by default
--   depending on the yotta target, features of mbed OS may be used in examples and tests
+The main systems used for development are CMake and GNU Make. Those systems are always complete and up-to-date. The others should reflect all changes present in the CMake and Make build system, although features may not be ported there automatically.
 
 
 The Make and CMake build systems create three libraries: libmbedcrypto, libmbedx509, and libmbedtls. Note that libmbedtls depends on libmbedx509 and libmbedcrypto, and libmbedx509 depends on libmbedcrypto. As a result, some linkers will expect flags to be in a specific order, for example the GNU linker wants `-lmbedtls -lmbedx509 -lmbedcrypto`. Also, when loading shared libraries using dlopen(), you'll need to load libmbedcrypto first, then libmbedx509, before you can load libmbedtls.
 The Make and CMake build systems create three libraries: libmbedcrypto, libmbedx509, and libmbedtls. Note that libmbedtls depends on libmbedx509 and libmbedcrypto, and libmbedx509 depends on libmbedcrypto. As a result, some linkers will expect flags to be in a specific order, for example the GNU linker wants `-lmbedtls -lmbedx509 -lmbedcrypto`. Also, when loading shared libraries using dlopen(), you'll need to load libmbedcrypto first, then libmbedx509, before you can load libmbedtls.
 
 
-### Yotta
-
-[yotta](http://yottabuild.org) is a package manager and build system developed by mbed, and is the build system of mbed OS 16.03. To install it on your platform, please follow the yotta [installation instructions](http://docs.yottabuild.org/#installing).
-
-Once yotta is installed, you can use it to download the latest version of mbed TLS from the yotta registry with:
-
-    yotta install mbedtls
-
-and build it with:
-
-    yotta build
-
-If, on the other hand, you already have a copy of mbed TLS from a source other than the yotta registry, for example from cloning our GitHub repository, or from downloading a tarball of the standalone edition, then you'll first need to generate the yotta module by running:
-
-    yotta/create-module.sh
-
-This should be executed from the root mbed TLS project directory. This will create the yotta module in the `yotta/module` directory within it. You can then change to that directory and build as usual:
-
-    cd yotta/module
-    yotta build
-
-In any case, you'll probably want to set the yotta target before building unless it has already been set globally. For more information on using yotta, please consult the [yotta documentation](http://docs.yottabuild.org/).
-
-For more details on the yotta/mbed OS edition of mbed TLS, including example programs, please consult the [Readme at the root of the yotta module](https://github.com/ARMmbed/mbedtls/blob/development/yotta/data/README.md).
-
 ### Make
 ### Make
 
 
-We intentionally only use the minimum of `Make` functionality, as a lot of `Make` features are not supported on all different implementations of Make or on different platforms. As such, the Makefiles sometimes require some manual changes or export statements in order to work for your platform.
+We require GNU Make. To build the library and the sample programs, GNU Make and a C compiler are sufficient. Some of the more advanced build targets require some Unix/Linux tools.
 
 
-In order to build from the source code using Make, just enter at the command line:
+We intentionally only use a minimum of functionality in the makefiles in order to keep them as simple and independent of different toolchains as possible, to allow users to more easily move between different platforms. Users who need more features are recommended to use CMake.
+
+In order to build from the source code using GNU Make, just enter at the command line:
 
 
     make
     make
 
 
@@ -64,7 +35,7 @@ In order to run the tests, enter:
 
 
     make check
     make check
 
 
-The tests need Perl to be built and run. If you don't have Perl installed, you can skip building the tests with:
+The tests need Python to be built and Perl to be run. If you don't have one of them installed, you can skip building the tests with:
 
 
     make no_test
     make no_test
 
 
@@ -74,26 +45,29 @@ You'll still be able to run a much smaller set of tests with:
 
 
 In order to build for a Windows platform, you should use `WINDOWS_BUILD=1` if the target is Windows but the build environment is Unix-like (for instance when cross-compiling, or compiling from an MSYS shell), and `WINDOWS=1` if the build environment is a Windows shell (for instance using mingw32-make) (in that case some targets will not be available).
 In order to build for a Windows platform, you should use `WINDOWS_BUILD=1` if the target is Windows but the build environment is Unix-like (for instance when cross-compiling, or compiling from an MSYS shell), and `WINDOWS=1` if the build environment is a Windows shell (for instance using mingw32-make) (in that case some targets will not be available).
 
 
-Setting the variable `SHARED` in your environment will build shared libraries in addition to the static libraries. Setting `DEBUG` gives you a debug build. You can override `CFLAGS` and `LDFLAGS` by setting them in your environment or on the make command line; if you do so, essential parts such as `-I` will still be preserved. Warning options may be overridden separately using `WARNING_CFLAGS`.
+Setting the variable `SHARED` in your environment will build shared libraries in addition to the static libraries. Setting `DEBUG` gives you a debug build. You can override `CFLAGS` and `LDFLAGS` by setting them in your environment or on the make command line; compiler warning options may be overridden separately using `WARNING_CFLAGS`. Some directory-specific options (for example, `-I` directives) are still preserved.
+
+Please note that setting `CFLAGS` overrides its default value of `-O2` and setting `WARNING_CFLAGS` overrides its default value (starting with `-Wall -W`), so if you just want to add some warning options to the default ones, you can do so by setting `CFLAGS=-O2 -Werror` for example. Setting `WARNING_CFLAGS` is useful when you want to get rid of its default content (for example because your compiler doesn't accept `-Wall` as an option). Directory-specific options cannot be overridden from the command line.
 
 
-Depending on your platform, you might run into some issues. Please check the Makefiles in `library/`, `programs/` and `tests/` for options to manually add or remove for specific platforms. You can also check [the mbed TLS Knowledge Base](https://tls.mbed.org/kb) for articles on your platform or issue.
+Depending on your platform, you might run into some issues. Please check the Makefiles in `library/`, `programs/` and `tests/` for options to manually add or remove for specific platforms. You can also check [the Mbed TLS Knowledge Base](https://tls.mbed.org/kb) for articles on your platform or issue.
 
 
-In case you find that you need to do something else as well, please let us know what, so we can add it to the [mbed TLS knowledge base](https://tls.mbed.org/kb).
+In case you find that you need to do something else as well, please let us know what, so we can add it to the [Mbed TLS Knowledge Base](https://tls.mbed.org/kb).
 
 
 ### CMake
 ### CMake
 
 
-In order to build the source using CMake, just enter at the command line:
+In order to build the source using CMake in a separate directory (recommended), just enter at the command line:
 
 
-    cmake .
+    mkdir /path/to/build_dir && cd /path/to/build_dir
+    cmake /path/to/mbedtls_source
     make
     make
 
 
 In order to run the tests, enter:
 In order to run the tests, enter:
 
 
     make test
     make test
 
 
-The test suites need Perl to be built. If you don't have Perl installed, you'll want to disable the test suites with:
+The test suites need Python to be built and Perl to be executed. If you don't have one of these installed, you'll want to disable the test suites with:
 
 
-    cmake -DENABLE_TESTING=Off .
+    cmake -DENABLE_TESTING=Off /path/to/mbedtls_source
 
 
 If you disabled the test suites, but kept the programs enabled, you can still run a much smaller set of tests with:
 If you disabled the test suites, but kept the programs enabled, you can still run a much smaller set of tests with:
 
 
@@ -101,47 +75,75 @@ If you disabled the test suites, but kept the programs enabled, you can still ru
 
 
 To configure CMake for building shared libraries, use:
 To configure CMake for building shared libraries, use:
 
 
-    cmake -DUSE_SHARED_MBEDTLS_LIBRARY=On .
+    cmake -DUSE_SHARED_MBEDTLS_LIBRARY=On /path/to/mbedtls_source
 
 
 There are many different build modes available within the CMake buildsystem. Most of them are available for gcc and clang, though some are compiler-specific:
 There are many different build modes available within the CMake buildsystem. Most of them are available for gcc and clang, though some are compiler-specific:
 
 
--   Release. This generates the default code without any unnecessary information in the binary files.
--   Debug. This generates debug information and disables optimization of the code.
--   Coverage. This generates code coverage information in addition to debug information.
--   ASan. This instruments the code with AddressSanitizer to check for memory errors. (This includes LeakSanitizer, with recent version of gcc and clang.) (With recent version of clang, this mode also instruments the code with UndefinedSanitizer to check for undefined behaviour.)
--   ASanDbg. Same as ASan but slower, with debug information and better stack traces.
--   MemSan. This instruments the code with MemorySanitizer to check for uninitialised memory reads. Experimental, needs recent clang on Linux/x86\_64.
--   MemSanDbg. Same as MemSan but slower, with debug information, better stack traces and origin tracking.
--   Check. This activates the compiler warnings that depend on optimization and treats all warnings as errors.
+-   `Release`. This generates the default code without any unnecessary information in the binary files.
+-   `Debug`. This generates debug information and disables optimization of the code.
+-   `Coverage`. This generates code coverage information in addition to debug information.
+-   `ASan`. This instruments the code with AddressSanitizer to check for memory errors. (This includes LeakSanitizer, with recent version of gcc and clang.) (With recent version of clang, this mode also instruments the code with UndefinedSanitizer to check for undefined behaviour.)
+-   `ASanDbg`. Same as ASan but slower, with debug information and better stack traces.
+-   `MemSan`. This instruments the code with MemorySanitizer to check for uninitialised memory reads. Experimental, needs recent clang on Linux/x86\_64.
+-   `MemSanDbg`. Same as MemSan but slower, with debug information, better stack traces and origin tracking.
+-   `Check`. This activates the compiler warnings that depend on optimization and treats all warnings as errors.
 
 
 Switching build modes in CMake is simple. For debug mode, enter at the command line:
 Switching build modes in CMake is simple. For debug mode, enter at the command line:
 
 
-    cmake -D CMAKE_BUILD_TYPE=Debug .
+    cmake -D CMAKE_BUILD_TYPE=Debug /path/to/mbedtls_source
 
 
 To list other available CMake options, use:
 To list other available CMake options, use:
 
 
     cmake -LH
     cmake -LH
 
 
-Note that, with CMake, if you want to change the compiler or its options after you already ran CMake, you need to clear its cache first, e.g. (using GNU find):
+Note that, with CMake, you can't adjust the compiler or its flags after the
+initial invocation of cmake. This means that `CC=your_cc make` and `make
+CC=your_cc` will *not* work (similarly with `CFLAGS` and other variables).
+These variables need to be adjusted when invoking cmake for the first time,
+for example:
+
+    CC=your_cc cmake /path/to/mbedtls_source
+
+If you already invoked cmake and want to change those settings, you need to
+remove the build directory and create it again.
+
+Note that it is possible to build in-place; this will however overwrite the
+provided Makefiles (see `scripts/tmp_ignore_makefiles.sh` if you want to
+prevent `git status` from showing them as modified). In order to do so, from
+the Mbed TLS source directory, use:
+
+    cmake .
+    make
+
+If you want to change `CC` or `CFLAGS` afterwards, you will need to remove the
+CMake cache. This can be done with the following command using GNU find:
 
 
     find . -iname '*cmake*' -not -name CMakeLists.txt -exec rm -rf {} +
     find . -iname '*cmake*' -not -name CMakeLists.txt -exec rm -rf {} +
-    CC=gcc CFLAGS='-fstack-protector-strong -Wa,--noexecstack' cmake .
+
+You can now make the desired change:
+
+    CC=your_cc cmake .
+    make
+
+Regarding variables, also note that if you set CFLAGS when invoking cmake,
+your value of CFLAGS doesn't override the content provided by cmake (depending
+on the build mode as seen above), it's merely prepended to it.
 
 
 ### Microsoft Visual Studio
 ### Microsoft Visual Studio
 
 
 The build files for Microsoft Visual Studio are generated for Visual Studio 2010.
 The build files for Microsoft Visual Studio are generated for Visual Studio 2010.
 
 
-The solution file `mbedTLS.sln` contains all the basic projects needed to build the library and all the programs. The files in tests are not generated and compiled, as these need a perl environment as well. However, the selftest program in `programs/test/` is still available.
+The solution file `mbedTLS.sln` contains all the basic projects needed to build the library and all the programs. The files in tests are not generated and compiled, as these need Python and perl environments as well. However, the selftest program in `programs/test/` is still available.
 
 
 Example programs
 Example programs
 ----------------
 ----------------
 
 
-We've included example programs for a lot of different features and uses in `programs/`. Most programs only focus on a single feature or usage scenario, so keep that in mind when copying parts of the code.
+We've included example programs for a lot of different features and uses in [`programs/`](programs/README.md). Most programs only focus on a single feature or usage scenario, so keep that in mind when copying parts of the code.
 
 
 Tests
 Tests
 -----
 -----
 
 
-mbed TLS includes an elaborate test suite in `tests/` that initially requires Perl to generate the tests files (e.g. `test\_suite\_mpi.c`). These files are generated from a `function file` (e.g. `suites/test\_suite\_mpi.function`) and a `data file` (e.g. `suites/test\_suite\_mpi.data`). The `function file` contains the test functions. The `data file` contains the test cases, specified as parameters that will be passed to the test function.
+Mbed TLS includes an elaborate test suite in `tests/` that initially requires Python to generate the tests files (e.g. `test\_suite\_mpi.c`). These files are generated from a `function file` (e.g. `suites/test\_suite\_mpi.function`) and a `data file` (e.g. `suites/test\_suite\_mpi.data`). The `function file` contains the test functions. The `data file` contains the test cases, specified as parameters that will be passed to the test function.
 
 
 For machines with a Unix shell and OpenSSL (and optionally GnuTLS) installed, additional test scripts are available:
 For machines with a Unix shell and OpenSSL (and optionally GnuTLS) installed, additional test scripts are available:
 
 
@@ -156,14 +158,51 @@ Configurations
 
 
 We provide some non-standard configurations focused on specific use cases in the `configs/` directory. You can read more about those in `configs/README.txt`
 We provide some non-standard configurations focused on specific use cases in the `configs/` directory. You can read more about those in `configs/README.txt`
 
 
-Porting mbed TLS
+Using Mbed Crypto as a submodule
+--------------------------------
+
+As an experimental feature, you can use Mbed Crypto as the source of the cryptography implementation, with Mbed TLS providing the X.509 and TLS parts of the library. Mbed Crypto is currently provided for evaluation only and should not be used in production. At this point, you should only use this option if you want to try out the experimental PSA Crypto API.
+
+To enable the use of Mbed Crypto as a submodule:
+
+1. Check out the `crypto` submodule and update it.
+
+        git submodule init crypto
+        git submodule update crypto
+
+2. (Optional) TO enable the PSA Crypto API, set the build configuration option `MBEDTLS_PSA_CRYPTO_C`. You can either edit `include/mbedtls/config.h` directly or use the configuration script:
+
+        scripts/config.pl set MBEDTLS_PSA_CRYPTO_C
+
+3. Activate the build option `USE_CRYPTO_SUBMODULE`. With GNU make, set `USE_CRYPTO_SUBMODULE=1` on each make invocation:
+
+        make USE_CRYPTO_SUBMODULE=1
+        make USE_CRYPTO_SUBMODULE=1 test
+        tests/ssl-opt.sh -f Default
+
+   Note that you need to pass `USE_CRYPTO_SUBMODULE=1` even to `make clean`. For example, if you change `config.h`, run this before rebuilding:
+
+        make USE_CRYPTO_SUBMODULE=1 clean
+
+   With CMake, create a build directory (recommended) and pass `-DUSE_CRYPTO_SUBMODULE=1` to `cmake`:
+
+        mkdir build
+        cd build
+        cmake -DUSE_CRYPTO_SUBMODULE=1 ..
+        make
+        make test
+        tests/ssl-opt.sh -f Default
+
+Note that this does not enable the PSA-specific tests and utility programs. To use these programs, use Mbed Crypto as a standalone project.
+
+Porting Mbed TLS
 ----------------
 ----------------
 
 
-mbed TLS can be ported to many different architectures, OS's and platforms. Before starting a port, you may find the following knowledge base articles useful:
+Mbed TLS can be ported to many different architectures, OS's and platforms. Before starting a port, you may find the following Knowledge Base articles useful:
 
 
--   [Porting mbed TLS to a new environment or OS](https://tls.mbed.org/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS)
--   [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)
+-   [Porting Mbed TLS to a new environment or OS](https://tls.mbed.org/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS)
+-   [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)
 
 
 Contributing
 Contributing
 ------------
 ------------
@@ -174,12 +213,12 @@ We gratefully accept bug reports and contributions from the community. There are
 -   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.
 -   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.
 -   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 Contributor’s Licence 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.
+To accept the Contributor’s 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
 ### 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.
-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.
+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.
 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 :)
 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 :)
 
 

+ 5 - 0
mbedtls/include/CMakeLists.txt

@@ -9,3 +9,8 @@ if(INSTALL_MBEDTLS_HEADERS)
         PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ)
         PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ)
 
 
 endif(INSTALL_MBEDTLS_HEADERS)
 endif(INSTALL_MBEDTLS_HEADERS)
+
+# Make config.h available in an out-of-source build. ssl-opt.sh requires it.
+if (NOT ${CMAKE_CURRENT_BINARY_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR})
+    link_to_source(mbedtls)
+endif()

+ 220 - 146
mbedtls/include/mbedtls/aes.h

@@ -1,9 +1,18 @@
 /**
 /**
  * \file aes.h
  * \file aes.h
  *
  *
- * \brief AES block cipher
- *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * \brief   The Advanced Encryption Standard (AES) specifies a FIPS-approved
+ *          cryptographic algorithm that can be used to protect electronic
+ *          data.
+ *
+ *          The AES algorithm is a symmetric block cipher that can
+ *          encrypt and decrypt information. For more information, see
+ *          <em>FIPS Publication 197: Advanced Encryption Standard</em> and
+ *          <em>ISO/IEC 18033-2:2006: Information technology -- Security
+ *          techniques -- Encryption algorithms -- Part 2: Asymmetric
+ *          ciphers</em>.
+ */
+/*  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved.
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,8 +27,9 @@
  *  See the License for the specific language governing permissions and
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *  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_AES_H
 #ifndef MBEDTLS_AES_H
 #define MBEDTLS_AES_H
 #define MBEDTLS_AES_H
 
 
@@ -33,12 +43,17 @@
 #include <stdint.h>
 #include <stdint.h>
 
 
 /* padlock.c and aesni.c rely on these values! */
 /* padlock.c and aesni.c rely on these values! */
-#define MBEDTLS_AES_ENCRYPT     1
-#define MBEDTLS_AES_DECRYPT     0
+#define MBEDTLS_AES_ENCRYPT     1 /**< AES encryption. */
+#define MBEDTLS_AES_DECRYPT     0 /**< AES decryption. */
 
 
+/* Error codes in range 0x0020-0x0022 */
 #define MBEDTLS_ERR_AES_INVALID_KEY_LENGTH                -0x0020  /**< Invalid key length. */
 #define MBEDTLS_ERR_AES_INVALID_KEY_LENGTH                -0x0020  /**< Invalid key length. */
 #define MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH              -0x0022  /**< Invalid data input length. */
 #define MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH              -0x0022  /**< Invalid data input length. */
 
 
+/* Error codes in range 0x0023-0x0025 */
+#define MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE               -0x0023  /**< Feature not available. For example, an unsupported AES key size. */
+#define MBEDTLS_ERR_AES_HW_ACCEL_FAILED                   -0x0025  /**< AES hardware accelerator failed. */
+
 #if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
 #if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
     !defined(inline) && !defined(__cplusplus)
     !defined(inline) && !defined(__cplusplus)
 #define inline __inline
 #define inline __inline
@@ -53,68 +68,90 @@ extern "C" {
 #endif
 #endif
 
 
 /**
 /**
- * \brief          AES context structure
- *
- * \note           buf is able to hold 32 extra bytes, which can be used:
- *                 - for alignment purposes if VIA padlock is used, and/or
- *                 - to simplify key expansion in the 256-bit case by
- *                 generating an extra round key
+ * \brief The AES context-type definition.
  */
  */
 typedef struct
 typedef struct
 {
 {
-    int nr;                     /*!<  number of rounds  */
-    uint32_t *rk;               /*!<  AES round keys    */
-    uint32_t buf[68];           /*!<  unaligned data    */
+    int nr;                     /*!< The number of rounds. */
+    uint32_t *rk;               /*!< AES round keys. */
+    uint32_t buf[68];           /*!< Unaligned data buffer. This buffer can
+                                     hold 32 extra Bytes, which can be used for
+                                     one of the following purposes:
+                                     <ul><li>Alignment if VIA padlock is
+                                             used.</li>
+                                     <li>Simplifying key expansion in the 256-bit
+                                         case by generating an extra round key.
+                                         </li></ul> */
 }
 }
 mbedtls_aes_context;
 mbedtls_aes_context;
 
 
 /**
 /**
- * \brief          Initialize AES context
+ * \brief          This function initializes the specified AES context.
  *
  *
- * \param ctx      AES context to be initialized
+ *                 It must be the first API called before using
+ *                 the context.
+ *
+ * \param ctx      The AES context to initialize.
  */
  */
 void mbedtls_aes_init( mbedtls_aes_context *ctx );
 void mbedtls_aes_init( mbedtls_aes_context *ctx );
 
 
 /**
 /**
- * \brief          Clear AES context
+ * \brief          This function releases and clears the specified AES context.
  *
  *
- * \param ctx      AES context to be cleared
+ * \param ctx      The AES context to clear.
  */
  */
 void mbedtls_aes_free( mbedtls_aes_context *ctx );
 void mbedtls_aes_free( mbedtls_aes_context *ctx );
 
 
 /**
 /**
- * \brief          AES key schedule (encryption)
+ * \brief          This function sets the encryption key.
  *
  *
- * \param ctx      AES context to be initialized
- * \param key      encryption key
- * \param keybits  must be 128, 192 or 256
+ * \param ctx      The AES context to which the key should be bound.
+ * \param key      The encryption key.
+ * \param keybits  The size of data passed in bits. Valid options are:
+ *                 <ul><li>128 bits</li>
+ *                 <li>192 bits</li>
+ *                 <li>256 bits</li></ul>
  *
  *
- * \return         0 if successful, or MBEDTLS_ERR_AES_INVALID_KEY_LENGTH
+ * \return         \c 0 on success or #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH
+ *                 on failure.
  */
  */
 int mbedtls_aes_setkey_enc( mbedtls_aes_context *ctx, const unsigned char *key,
 int mbedtls_aes_setkey_enc( mbedtls_aes_context *ctx, const unsigned char *key,
                     unsigned int keybits );
                     unsigned int keybits );
 
 
 /**
 /**
- * \brief          AES key schedule (decryption)
+ * \brief          This function sets the decryption key.
  *
  *
- * \param ctx      AES context to be initialized
- * \param key      decryption key
- * \param keybits  must be 128, 192 or 256
+ * \param ctx      The AES context to which the key should be bound.
+ * \param key      The decryption key.
+ * \param keybits  The size of data passed. Valid options are:
+ *                 <ul><li>128 bits</li>
+ *                 <li>192 bits</li>
+ *                 <li>256 bits</li></ul>
  *
  *
- * \return         0 if successful, or MBEDTLS_ERR_AES_INVALID_KEY_LENGTH
+ * \return         \c 0 on success, or #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.
  */
  */
 int mbedtls_aes_setkey_dec( mbedtls_aes_context *ctx, const unsigned char *key,
 int mbedtls_aes_setkey_dec( mbedtls_aes_context *ctx, const unsigned char *key,
                     unsigned int keybits );
                     unsigned int keybits );
 
 
 /**
 /**
- * \brief          AES-ECB block encryption/decryption
- *
- * \param ctx      AES context
- * \param mode     MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT
- * \param input    16-byte input block
- * \param output   16-byte output block
- *
- * \return         0 if successful
+ * \brief          This function performs an AES single-block encryption or
+ *                 decryption operation.
+ *
+ *                 It performs the operation defined in the \p mode parameter
+ *                 (encrypt or decrypt), on the input data buffer defined in
+ *                 the \p input parameter.
+ *
+ *                 mbedtls_aes_init(), and either mbedtls_aes_setkey_enc() or
+ *                 mbedtls_aes_setkey_dec() must be called before the first
+ *                 call to this API with the same context.
+ *
+ * \param ctx      The AES context to use for encryption or decryption.
+ * \param mode     The AES operation: #MBEDTLS_AES_ENCRYPT or
+ *                 #MBEDTLS_AES_DECRYPT.
+ * \param input    The 16-Byte buffer holding the input data.
+ * \param output   The 16-Byte buffer holding the output data.
+
+ * \return         \c 0 on success.
  */
  */
 int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx,
 int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx,
                     int mode,
                     int mode,
@@ -123,26 +160,40 @@ int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx,
 
 
 #if defined(MBEDTLS_CIPHER_MODE_CBC)
 #if defined(MBEDTLS_CIPHER_MODE_CBC)
 /**
 /**
- * \brief          AES-CBC buffer encryption/decryption
- *                 Length should be a multiple of the block
- *                 size (16 bytes)
- *
- * \note           Upon exit, the content of the IV is updated so that you can
- *                 call the function same function again on the following
- *                 block(s) of data and get the same result as if it was
- *                 encrypted in one call. This allows a "streaming" usage.
- *                 If on the other hand you need to retain the contents of the
- *                 IV, you should either save it manually or use the cipher
- *                 module instead.
- *
- * \param ctx      AES context
- * \param mode     MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT
- * \param length   length of the input data
- * \param iv       initialization vector (updated after use)
- * \param input    buffer holding the input data
- * \param output   buffer holding the output data
- *
- * \return         0 if successful, or MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH
+ * \brief  This function performs an AES-CBC encryption or decryption operation
+ *         on full blocks.
+ *
+ *         It performs the operation defined in the \p mode
+ *         parameter (encrypt/decrypt), on the input data buffer defined in
+ *         the \p input parameter.
+ *
+ *         It can be called as many times as needed, until all the input
+ *         data is processed. mbedtls_aes_init(), and either
+ *         mbedtls_aes_setkey_enc() or mbedtls_aes_setkey_dec() must be called
+ *         before the first call to this API with the same context.
+ *
+ * \note   This function operates on aligned blocks, that is, the input size
+ *         must be a multiple of the AES block size of 16 Bytes.
+ *
+ * \note   Upon exit, the content of the IV is updated so that you can
+ *         call the same function again on the next
+ *         block(s) of data and get the same result as if it was
+ *         encrypted in one call. This allows a "streaming" usage.
+ *         If you need to retain the contents of the IV, you should
+ *         either save it manually or use the cipher module instead.
+ *
+ *
+ * \param ctx      The AES context to use for encryption or decryption.
+ * \param mode     The AES operation: #MBEDTLS_AES_ENCRYPT or
+ *                 #MBEDTLS_AES_DECRYPT.
+ * \param length   The length of the input data in Bytes. This must be a
+ *                 multiple of the block size (16 Bytes).
+ * \param iv       Initialization vector (updated after use).
+ * \param input    The buffer holding the input data.
+ * \param output   The buffer holding the output data.
+ *
+ * \return         \c 0 on success, or #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH
+ *                 on failure.
  */
  */
 int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx,
 int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx,
                     int mode,
                     int mode,
@@ -154,29 +205,38 @@ int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx,
 
 
 #if defined(MBEDTLS_CIPHER_MODE_CFB)
 #if defined(MBEDTLS_CIPHER_MODE_CFB)
 /**
 /**
- * \brief          AES-CFB128 buffer encryption/decryption.
- *
- * Note: Due to the nature of CFB you should use the same key schedule for
- * both encryption and decryption. So a context initialized with
- * mbedtls_aes_setkey_enc() for both MBEDTLS_AES_ENCRYPT and MBEDTLS_AES_DECRYPT.
- *
- * \note           Upon exit, the content of the IV is updated so that you can
- *                 call the function same function again on the following
- *                 block(s) of data and get the same result as if it was
- *                 encrypted in one call. This allows a "streaming" usage.
- *                 If on the other hand you need to retain the contents of the
- *                 IV, you should either save it manually or use the cipher
- *                 module instead.
- *
- * \param ctx      AES context
- * \param mode     MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT
- * \param length   length of the input data
- * \param iv_off   offset in IV (updated after use)
- * \param iv       initialization vector (updated after use)
- * \param input    buffer holding the input data
- * \param output   buffer holding the output data
- *
- * \return         0 if successful
+ * \brief This function performs an AES-CFB128 encryption or decryption
+ *        operation.
+ *
+ *        It performs the operation defined in the \p mode
+ *        parameter (encrypt or decrypt), on the input data buffer
+ *        defined in the \p input parameter.
+ *
+ *        For CFB, you must set up the context with mbedtls_aes_setkey_enc(),
+ *        regardless of whether you are performing an encryption or decryption
+ *        operation, that is, regardless of the \p mode parameter. This is
+ *        because CFB mode uses the same key schedule for encryption and
+ *        decryption.
+ *
+ * \note  Upon exit, the content of the IV is updated so that you can
+ *        call the same function again on the next
+ *        block(s) of data and get the same result as if it was
+ *        encrypted in one call. This allows a "streaming" usage.
+ *        If you need to retain the contents of the
+ *        IV, you must either save it manually or use the cipher
+ *        module instead.
+ *
+ *
+ * \param ctx      The AES context to use for encryption or decryption.
+ * \param mode     The AES operation: #MBEDTLS_AES_ENCRYPT or
+ *                 #MBEDTLS_AES_DECRYPT.
+ * \param length   The length of the input data.
+ * \param iv_off   The offset in IV (updated after use).
+ * \param iv       The initialization vector (updated after use).
+ * \param input    The buffer holding the input data.
+ * \param output   The buffer holding the output data.
+ *
+ * \return         \c 0 on success.
  */
  */
 int mbedtls_aes_crypt_cfb128( mbedtls_aes_context *ctx,
 int mbedtls_aes_crypt_cfb128( mbedtls_aes_context *ctx,
                        int mode,
                        int mode,
@@ -187,28 +247,36 @@ int mbedtls_aes_crypt_cfb128( mbedtls_aes_context *ctx,
                        unsigned char *output );
                        unsigned char *output );
 
 
 /**
 /**
- * \brief          AES-CFB8 buffer encryption/decryption.
- *
- * Note: Due to the nature of CFB you should use the same key schedule for
- * both encryption and decryption. So a context initialized with
- * mbedtls_aes_setkey_enc() for both MBEDTLS_AES_ENCRYPT and MBEDTLS_AES_DECRYPT.
- *
- * \note           Upon exit, the content of the IV is updated so that you can
- *                 call the function same function again on the following
- *                 block(s) of data and get the same result as if it was
- *                 encrypted in one call. This allows a "streaming" usage.
- *                 If on the other hand you need to retain the contents of the
- *                 IV, you should either save it manually or use the cipher
- *                 module instead.
- *
- * \param ctx      AES context
- * \param mode     MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT
- * \param length   length of the input data
- * \param iv       initialization vector (updated after use)
- * \param input    buffer holding the input data
- * \param output   buffer holding the output data
- *
- * \return         0 if successful
+ * \brief This function performs an AES-CFB8 encryption or decryption
+ *        operation.
+ *
+ *        It performs the operation defined in the \p mode
+ *        parameter (encrypt/decrypt), on the input data buffer defined
+ *        in the \p input parameter.
+ *
+ *        Due to the nature of CFB, you must use the same key schedule for
+ *        both encryption and decryption operations. Therefore, you must
+ *        use the context initialized with mbedtls_aes_setkey_enc() for
+ *        both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT.
+ *
+ * \note  Upon exit, the content of the IV is updated so that you can
+ *        call the same function again on the next
+ *        block(s) of data and get the same result as if it was
+ *        encrypted in one call. This allows a "streaming" usage.
+ *        If you need to retain the contents of the
+ *        IV, you should either save it manually or use the cipher
+ *        module instead.
+ *
+ *
+ * \param ctx      The AES context to use for encryption or decryption.
+ * \param mode     The AES operation: #MBEDTLS_AES_ENCRYPT or
+ *                 #MBEDTLS_AES_DECRYPT
+ * \param length   The length of the input data.
+ * \param iv       The initialization vector (updated after use).
+ * \param input    The buffer holding the input data.
+ * \param output   The buffer holding the output data.
+ *
+ * \return         \c 0 on success.
  */
  */
 int mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx,
 int mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx,
                     int mode,
                     int mode,
@@ -220,26 +288,32 @@ int mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx,
 
 
 #if defined(MBEDTLS_CIPHER_MODE_CTR)
 #if defined(MBEDTLS_CIPHER_MODE_CTR)
 /**
 /**
- * \brief               AES-CTR buffer encryption/decryption
- *
- * Warning: You have to keep the maximum use of your counter in mind!
- *
- * Note: Due to the nature of CTR you should use the same key schedule for
- * both encryption and decryption. So a context initialized with
- * mbedtls_aes_setkey_enc() for both MBEDTLS_AES_ENCRYPT and MBEDTLS_AES_DECRYPT.
- *
- * \param ctx           AES context
- * \param length        The length of the data
- * \param nc_off        The offset in the current stream_block (for resuming
- *                      within current cipher stream). The offset pointer to
- *                      should be 0 at the start of a stream.
- * \param nonce_counter The 128-bit nonce and counter.
- * \param stream_block  The saved stream-block for resuming. Is overwritten
- *                      by the function.
- * \param input         The input data stream
- * \param output        The output data stream
- *
- * \return         0 if successful
+ * \brief      This function performs an AES-CTR encryption or decryption
+ *             operation.
+ *
+ *             This function performs the operation defined in the \p mode
+ *             parameter (encrypt/decrypt), on the input data buffer
+ *             defined in the \p input parameter.
+ *
+ *             Due to the nature of CTR, you must use the same key schedule
+ *             for both encryption and decryption operations. Therefore, you
+ *             must use the context initialized with mbedtls_aes_setkey_enc()
+ *             for both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT.
+ *
+ * \warning    You must keep the maximum use of your counter in mind.
+ *
+ * \param ctx              The AES context to use for encryption or decryption.
+ * \param length           The length of the input data.
+ * \param nc_off           The offset in the current \p stream_block, for
+ *                         resuming within the current cipher stream. The
+ *                         offset pointer should be 0 at the start of a stream.
+ * \param nonce_counter    The 128-bit nonce and counter.
+ * \param stream_block     The saved stream block for resuming. This is
+ *                         overwritten by the function.
+ * \param input            The buffer holding the input data.
+ * \param output           The buffer holding the output data.
+ *
+ * \return     \c 0 on success.
  */
  */
 int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx,
 int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx,
                        size_t length,
                        size_t length,
@@ -251,30 +325,30 @@ int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx,
 #endif /* MBEDTLS_CIPHER_MODE_CTR */
 #endif /* MBEDTLS_CIPHER_MODE_CTR */
 
 
 /**
 /**
- * \brief           Internal AES block encryption function
- *                  (Only exposed to allow overriding it,
- *                  see MBEDTLS_AES_ENCRYPT_ALT)
+ * \brief           Internal AES block encryption function. This is only
+ *                  exposed to allow overriding it using
+ *                  \c MBEDTLS_AES_ENCRYPT_ALT.
  *
  *
- * \param ctx       AES context
- * \param input     Plaintext block
- * \param output    Output (ciphertext) block
+ * \param ctx       The AES context to use for encryption.
+ * \param input     The plaintext block.
+ * \param output    The output (ciphertext) block.
  *
  *
- * \return          0 if successful
+ * \return          \c 0 on success.
  */
  */
 int mbedtls_internal_aes_encrypt( mbedtls_aes_context *ctx,
 int mbedtls_internal_aes_encrypt( mbedtls_aes_context *ctx,
                                   const unsigned char input[16],
                                   const unsigned char input[16],
                                   unsigned char output[16] );
                                   unsigned char output[16] );
 
 
 /**
 /**
- * \brief           Internal AES block decryption function
- *                  (Only exposed to allow overriding it,
- *                  see MBEDTLS_AES_DECRYPT_ALT)
+ * \brief           Internal AES block decryption function. This is only
+ *                  exposed to allow overriding it using see
+ *                  \c MBEDTLS_AES_DECRYPT_ALT.
  *
  *
- * \param ctx       AES context
- * \param input     Ciphertext block
- * \param output    Output (plaintext) block
+ * \param ctx       The AES context to use for decryption.
+ * \param input     The ciphertext block.
+ * \param output    The output (plaintext) block.
  *
  *
- * \return          0 if successful
+ * \return          \c 0 on success.
  */
  */
 int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx,
 int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx,
                                   const unsigned char input[16],
                                   const unsigned char input[16],
@@ -290,11 +364,11 @@ int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx,
  * \brief           Deprecated internal AES block encryption function
  * \brief           Deprecated internal AES block encryption function
  *                  without return value.
  *                  without return value.
  *
  *
- * \deprecated      Superseded by mbedtls_aes_encrypt_ext() in 2.5.0
+ * \deprecated      Superseded by mbedtls_aes_encrypt_ext() in 2.5.0.
  *
  *
- * \param ctx       AES context
- * \param input     Plaintext block
- * \param output    Output (ciphertext) block
+ * \param ctx       The AES context to use for encryption.
+ * \param input     Plaintext block.
+ * \param output    Output (ciphertext) block.
  */
  */
 MBEDTLS_DEPRECATED void mbedtls_aes_encrypt( mbedtls_aes_context *ctx,
 MBEDTLS_DEPRECATED void mbedtls_aes_encrypt( mbedtls_aes_context *ctx,
                                              const unsigned char input[16],
                                              const unsigned char input[16],
@@ -304,11 +378,11 @@ MBEDTLS_DEPRECATED void mbedtls_aes_encrypt( mbedtls_aes_context *ctx,
  * \brief           Deprecated internal AES block decryption function
  * \brief           Deprecated internal AES block decryption function
  *                  without return value.
  *                  without return value.
  *
  *
- * \deprecated      Superseded by mbedtls_aes_decrypt_ext() in 2.5.0
+ * \deprecated      Superseded by mbedtls_aes_decrypt_ext() in 2.5.0.
  *
  *
- * \param ctx       AES context
- * \param input     Ciphertext block
- * \param output    Output (plaintext) block
+ * \param ctx       The AES context to use for decryption.
+ * \param input     Ciphertext block.
+ * \param output    Output (plaintext) block.
  */
  */
 MBEDTLS_DEPRECATED void mbedtls_aes_decrypt( mbedtls_aes_context *ctx,
 MBEDTLS_DEPRECATED void mbedtls_aes_decrypt( mbedtls_aes_context *ctx,
                                              const unsigned char input[16],
                                              const unsigned char input[16],
@@ -330,9 +404,9 @@ extern "C" {
 #endif
 #endif
 
 
 /**
 /**
- * \brief          Checkup routine
+ * \brief          Checkup routine.
  *
  *
- * \return         0 if successful, or 1 if the test failed
+ * \return         \c 0 on success, or \c 1 on failure.
  */
  */
 int mbedtls_aes_self_test( int verbose );
 int mbedtls_aes_self_test( int verbose );
 
 

+ 8 - 1
mbedtls/include/mbedtls/aesni.h

@@ -2,7 +2,8 @@
  * \file aesni.h
  * \file aesni.h
  *
  *
  * \brief AES-NI for hardware AES acceleration on some Intel processors
  * \brief AES-NI for hardware AES acceleration on some Intel processors
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -23,6 +24,12 @@
 #ifndef MBEDTLS_AESNI_H
 #ifndef MBEDTLS_AESNI_H
 #define MBEDTLS_AESNI_H
 #define MBEDTLS_AESNI_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include "aes.h"
 #include "aes.h"
 
 
 #define MBEDTLS_AESNI_AES      0x02000000u
 #define MBEDTLS_AESNI_AES      0x02000000u

+ 37 - 1
mbedtls/include/mbedtls/arc4.h

@@ -3,6 +3,10 @@
  *
  *
  * \brief The ARCFOUR stream cipher
  * \brief The ARCFOUR stream cipher
  *
  *
+ * \warning   ARC4 is considered a weak cipher and its use constitutes a
+ *            security risk. We recommend considering stronger ciphers instead.
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -19,6 +23,7 @@
  *  limitations under the License.
  *  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_ARC4_H
 #ifndef MBEDTLS_ARC4_H
 #define MBEDTLS_ARC4_H
 #define MBEDTLS_ARC4_H
@@ -31,6 +36,8 @@
 
 
 #include <stddef.h>
 #include <stddef.h>
 
 
+#define MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED                  -0x0019  /**< ARC4 hardware accelerator failed. */
+
 #if !defined(MBEDTLS_ARC4_ALT)
 #if !defined(MBEDTLS_ARC4_ALT)
 // Regular implementation
 // Regular implementation
 //
 //
@@ -40,7 +47,11 @@ extern "C" {
 #endif
 #endif
 
 
 /**
 /**
- * \brief          ARC4 context structure
+ * \brief     ARC4 context structure
+ *
+ * \warning   ARC4 is considered a weak cipher and its use constitutes a
+ *            security risk. We recommend considering stronger ciphers instead.
+ *
  */
  */
 typedef struct
 typedef struct
 {
 {
@@ -54,6 +65,11 @@ mbedtls_arc4_context;
  * \brief          Initialize ARC4 context
  * \brief          Initialize ARC4 context
  *
  *
  * \param ctx      ARC4 context to be initialized
  * \param ctx      ARC4 context to be initialized
+ *
+ * \warning        ARC4 is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
+ *
  */
  */
 void mbedtls_arc4_init( mbedtls_arc4_context *ctx );
 void mbedtls_arc4_init( mbedtls_arc4_context *ctx );
 
 
@@ -61,6 +77,11 @@ void mbedtls_arc4_init( mbedtls_arc4_context *ctx );
  * \brief          Clear ARC4 context
  * \brief          Clear ARC4 context
  *
  *
  * \param ctx      ARC4 context to be cleared
  * \param ctx      ARC4 context to be cleared
+ *
+ * \warning        ARC4 is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
+ *
  */
  */
 void mbedtls_arc4_free( mbedtls_arc4_context *ctx );
 void mbedtls_arc4_free( mbedtls_arc4_context *ctx );
 
 
@@ -70,6 +91,11 @@ void mbedtls_arc4_free( mbedtls_arc4_context *ctx );
  * \param ctx      ARC4 context to be setup
  * \param ctx      ARC4 context to be setup
  * \param key      the secret key
  * \param key      the secret key
  * \param keylen   length of the key, in bytes
  * \param keylen   length of the key, in bytes
+ *
+ * \warning        ARC4 is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
+ *
  */
  */
 void mbedtls_arc4_setup( mbedtls_arc4_context *ctx, const unsigned char *key,
 void mbedtls_arc4_setup( mbedtls_arc4_context *ctx, const unsigned char *key,
                  unsigned int keylen );
                  unsigned int keylen );
@@ -83,6 +109,11 @@ void mbedtls_arc4_setup( mbedtls_arc4_context *ctx, const unsigned char *key,
  * \param output   buffer for the output data
  * \param output   buffer for the output data
  *
  *
  * \return         0 if successful
  * \return         0 if successful
+ *
+ * \warning        ARC4 is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
+ *
  */
  */
 int mbedtls_arc4_crypt( mbedtls_arc4_context *ctx, size_t length, const unsigned char *input,
 int mbedtls_arc4_crypt( mbedtls_arc4_context *ctx, size_t length, const unsigned char *input,
                 unsigned char *output );
                 unsigned char *output );
@@ -103,6 +134,11 @@ extern "C" {
  * \brief          Checkup routine
  * \brief          Checkup routine
  *
  *
  * \return         0 if successful, or 1 if the test failed
  * \return         0 if successful, or 1 if the test failed
+ *
+ * \warning        ARC4 is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
+ *
  */
  */
 int mbedtls_arc4_self_test( int verbose );
 int mbedtls_arc4_self_test( int verbose );
 
 

+ 18 - 2
mbedtls/include/mbedtls/asn1.h

@@ -2,7 +2,8 @@
  * \file asn1.h
  * \file asn1.h
  *
  *
  * \brief Generic ASN.1 parsing
  * \brief Generic ASN.1 parsing
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -59,7 +60,7 @@
 
 
 /**
 /**
  * \name DER constants
  * \name DER constants
- * These constants comply with DER encoded the ANS1 type tags.
+ * These constants comply with the DER encoded ASN.1 type tags.
  * DER encoding uses hexadecimal representation.
  * DER encoding uses hexadecimal representation.
  * An example DER sequence is:\n
  * An example DER sequence is:\n
  * - 0x02 -- tag indicating INTEGER
  * - 0x02 -- tag indicating INTEGER
@@ -87,6 +88,21 @@
 #define MBEDTLS_ASN1_PRIMITIVE               0x00
 #define MBEDTLS_ASN1_PRIMITIVE               0x00
 #define MBEDTLS_ASN1_CONSTRUCTED             0x20
 #define MBEDTLS_ASN1_CONSTRUCTED             0x20
 #define MBEDTLS_ASN1_CONTEXT_SPECIFIC        0x80
 #define MBEDTLS_ASN1_CONTEXT_SPECIFIC        0x80
+
+/*
+ * 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",
+ * paragraph 8.1.2.2:
+ *
+ * Bit  8     7   6   5          1
+ *     +-------+-----+------------+
+ *     | Class | P/C | Tag number |
+ *     +-------+-----+------------+
+ */
+#define MBEDTLS_ASN1_TAG_CLASS_MASK          0xC0
+#define MBEDTLS_ASN1_TAG_PC_MASK             0x20
+#define MBEDTLS_ASN1_TAG_VALUE_MASK          0x1F
+
 /* \} name */
 /* \} name */
 /* \} addtogroup asn1_module */
 /* \} addtogroup asn1_module */
 
 

+ 22 - 12
mbedtls/include/mbedtls/asn1write.h

@@ -2,7 +2,8 @@
  * \file asn1write.h
  * \file asn1write.h
  *
  *
  * \brief ASN.1 buffer writing functionality
  * \brief ASN.1 buffer writing functionality
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -23,6 +24,12 @@
 #ifndef MBEDTLS_ASN1_WRITE_H
 #ifndef MBEDTLS_ASN1_WRITE_H
 #define MBEDTLS_ASN1_WRITE_H
 #define MBEDTLS_ASN1_WRITE_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include "asn1.h"
 #include "asn1.h"
 
 
 #define MBEDTLS_ASN1_CHK_ADD(g, f) do { if( ( ret = f ) < 0 ) return( ret ); else   \
 #define MBEDTLS_ASN1_CHK_ADD(g, f) do { if( ( ret = f ) < 0 ) return( ret ); else   \
@@ -182,24 +189,27 @@ int mbedtls_asn1_write_ia5_string( unsigned char **p, unsigned char *start,
                            const char *text, size_t text_len );
                            const char *text, size_t text_len );
 
 
 /**
 /**
- * \brief           Write a bitstring tag (MBEDTLS_ASN1_BIT_STRING) and
- *                  value in ASN.1 format
- *                  Note: function works backwards in data buffer
+ * \brief           Write a bitstring tag (#MBEDTLS_ASN1_BIT_STRING) and
+ *                  value in ASN.1 format.
  *
  *
- * \param p         reference to current position pointer
- * \param start     start of the buffer (for bounds-checking)
- * \param buf       the bitstring
- * \param bits      the total number of bits in the bitstring
+ * \note            This function works backwards in data buffer.
  *
  *
- * \return          the length written or a negative error code
+ * \param p         The reference to the current position pointer.
+ * \param start     The start of the buffer, for bounds-checking.
+ * \param buf       The bitstring to write.
+ * \param bits      The total number of bits in the bitstring.
+ *
+ * \return          The number of bytes written to \p p on success.
+ * \return          A negative error code on failure.
  */
  */
 int mbedtls_asn1_write_bitstring( unsigned char **p, unsigned char *start,
 int mbedtls_asn1_write_bitstring( unsigned char **p, unsigned char *start,
                           const unsigned char *buf, size_t bits );
                           const unsigned char *buf, size_t bits );
 
 
 /**
 /**
- * \brief           Write an octet string tag (MBEDTLS_ASN1_OCTET_STRING) and
- *                  value in ASN.1 format
- *                  Note: function works backwards in data buffer
+ * \brief           Write an octet string tag (#MBEDTLS_ASN1_OCTET_STRING)
+ *                  and value in ASN.1 format.
+ *
+ * \note            This function works backwards in data buffer.
  *
  *
  * \param p         reference to current position pointer
  * \param p         reference to current position pointer
  * \param start     start of the buffer (for bounds-checking)
  * \param start     start of the buffer (for bounds-checking)

+ 8 - 1
mbedtls/include/mbedtls/base64.h

@@ -2,7 +2,8 @@
  * \file base64.h
  * \file base64.h
  *
  *
  * \brief RFC 1521 base64 encoding/decoding
  * \brief RFC 1521 base64 encoding/decoding
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -23,6 +24,12 @@
 #ifndef MBEDTLS_BASE64_H
 #ifndef MBEDTLS_BASE64_H
 #define MBEDTLS_BASE64_H
 #define MBEDTLS_BASE64_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include <stddef.h>
 #include <stddef.h>
 
 
 #define MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL               -0x002A  /**< Output buffer too small. */
 #define MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL               -0x002A  /**< Output buffer too small. */

+ 8 - 3
mbedtls/include/mbedtls/bignum.h

@@ -1,8 +1,9 @@
 /**
 /**
  * \file bignum.h
  * \file bignum.h
  *
  *
- * \brief  Multi-precision integer library
- *
+ * \brief Multi-precision integer library
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -70,7 +71,7 @@
  * Maximum size of MPIs allowed in bits and bytes for user-MPIs.
  * Maximum size of MPIs allowed in bits and bytes for user-MPIs.
  * ( Default: 512 bytes => 4096 bits, Maximum tested: 2048 bytes => 16384 bits )
  * ( Default: 512 bytes => 4096 bits, Maximum tested: 2048 bytes => 16384 bits )
  *
  *
- * Note: Calculations can results temporarily in larger MPIs. So the number
+ * Note: Calculations can temporarily result in larger MPIs. So the number
  * of limbs required (MBEDTLS_MPI_MAX_LIMBS) is higher.
  * of limbs required (MBEDTLS_MPI_MAX_LIMBS) is higher.
  */
  */
 #define MBEDTLS_MPI_MAX_SIZE                              1024     /**< Maximum number of bytes for usable MPIs. */
 #define MBEDTLS_MPI_MAX_SIZE                              1024     /**< Maximum number of bytes for usable MPIs. */
@@ -683,6 +684,10 @@ int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi
  *
  *
  * \return         0 if successful,
  * \return         0 if successful,
  *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed
  *                 MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed
+ *
+ * \note           The bytes obtained from the PRNG are interpreted
+ *                 as a big-endian representation of an MPI; this can
+ *                 be relevant in applications like deterministic ECDSA.
  */
  */
 int mbedtls_mpi_fill_random( mbedtls_mpi *X, size_t size,
 int mbedtls_mpi_fill_random( mbedtls_mpi *X, size_t size,
                      int (*f_rng)(void *, unsigned char *, size_t),
                      int (*f_rng)(void *, unsigned char *, size_t),

+ 3 - 1
mbedtls/include/mbedtls/blowfish.h

@@ -2,7 +2,8 @@
  * \file blowfish.h
  * \file blowfish.h
  *
  *
  * \brief Blowfish block cipher
  * \brief Blowfish block cipher
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -40,6 +41,7 @@
 #define MBEDTLS_BLOWFISH_BLOCKSIZE   8          /* Blowfish uses 64 bit blocks */
 #define MBEDTLS_BLOWFISH_BLOCKSIZE   8          /* Blowfish uses 64 bit blocks */
 
 
 #define MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH                -0x0016  /**< Invalid key length. */
 #define MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH                -0x0016  /**< Invalid key length. */
+#define MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED                   -0x0017  /**< Blowfish hardware accelerator failed. */
 #define MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH              -0x0018  /**< Invalid data input length. */
 #define MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH              -0x0018  /**< Invalid data input length. */
 
 
 #if !defined(MBEDTLS_BLOWFISH_ALT)
 #if !defined(MBEDTLS_BLOWFISH_ALT)

+ 32 - 18
mbedtls/include/mbedtls/bn_mul.h

@@ -1,8 +1,9 @@
 /**
 /**
  * \file bn_mul.h
  * \file bn_mul.h
  *
  *
- * \brief  Multi-precision integer library
- *
+ * \brief Multi-precision integer library
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -37,6 +38,12 @@
 #ifndef MBEDTLS_BN_MUL_H
 #ifndef MBEDTLS_BN_MUL_H
 #define MBEDTLS_BN_MUL_H
 #define MBEDTLS_BN_MUL_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include "bignum.h"
 #include "bignum.h"
 
 
 #if defined(MBEDTLS_HAVE_ASM)
 #if defined(MBEDTLS_HAVE_ASM)
@@ -48,7 +55,14 @@
 /* armcc5 --gnu defines __GNUC__ but doesn't support GNU's extended asm */
 /* armcc5 --gnu defines __GNUC__ but doesn't support GNU's extended asm */
 #if defined(__GNUC__) && \
 #if defined(__GNUC__) && \
     ( !defined(__ARMCC_VERSION) || __ARMCC_VERSION >= 6000000 )
     ( !defined(__ARMCC_VERSION) || __ARMCC_VERSION >= 6000000 )
-#if defined(__i386__)
+
+/*
+ * Disable use of the i386 assembly code below if option -O0, to disable all
+ * compiler optimisations, is passed, detected with __OPTIMIZE__
+ * This is done as the number of registers used in the assembly code doesn't
+ * work with the -O0 option.
+ */
+#if defined(__i386__) && defined(__OPTIMIZE__)
 
 
 #define MULADDC_INIT                        \
 #define MULADDC_INIT                        \
     asm(                                    \
     asm(                                    \
@@ -141,7 +155,7 @@
         "movl   %%esi, %3       \n\t"   \
         "movl   %%esi, %3       \n\t"   \
         : "=m" (t), "=m" (c), "=m" (d), "=m" (s)        \
         : "=m" (t), "=m" (c), "=m" (d), "=m" (s)        \
         : "m" (t), "m" (s), "m" (d), "m" (c), "m" (b)   \
         : "m" (t), "m" (s), "m" (d), "m" (c), "m" (b)   \
-        : "eax", "ecx", "edx", "esi", "edi"             \
+        : "eax", "ebx", "ecx", "edx", "esi", "edi"      \
     );
     );
 
 
 #else
 #else
@@ -153,7 +167,7 @@
         "movl   %%esi, %3       \n\t"   \
         "movl   %%esi, %3       \n\t"   \
         : "=m" (t), "=m" (c), "=m" (d), "=m" (s)        \
         : "=m" (t), "=m" (c), "=m" (d), "=m" (s)        \
         : "m" (t), "m" (s), "m" (d), "m" (c), "m" (b)   \
         : "m" (t), "m" (s), "m" (d), "m" (c), "m" (b)   \
-        : "eax", "ecx", "edx", "esi", "edi"             \
+        : "eax", "ebx", "ecx", "edx", "esi", "edi"      \
     );
     );
 #endif /* SSE2 */
 #endif /* SSE2 */
 #endif /* i386 */
 #endif /* i386 */
@@ -162,19 +176,19 @@
 
 
 #define MULADDC_INIT                        \
 #define MULADDC_INIT                        \
     asm(                                    \
     asm(                                    \
-        "xorq   %%r8, %%r8          \n\t"
+        "xorq   %%r8, %%r8\n"
 
 
 #define MULADDC_CORE                        \
 #define MULADDC_CORE                        \
-        "movq   (%%rsi), %%rax      \n\t"   \
-        "mulq   %%rbx               \n\t"   \
-        "addq   $8,      %%rsi      \n\t"   \
-        "addq   %%rcx,   %%rax      \n\t"   \
-        "movq   %%r8,    %%rcx      \n\t"   \
-        "adcq   $0,      %%rdx      \n\t"   \
-        "nop                        \n\t"   \
-        "addq   %%rax,   (%%rdi)    \n\t"   \
-        "adcq   %%rdx,   %%rcx      \n\t"   \
-        "addq   $8,      %%rdi      \n\t"
+        "movq   (%%rsi), %%rax\n"           \
+        "mulq   %%rbx\n"                    \
+        "addq   $8, %%rsi\n"                \
+        "addq   %%rcx, %%rax\n"             \
+        "movq   %%r8, %%rcx\n"              \
+        "adcq   $0, %%rdx\n"                \
+        "nop    \n"                         \
+        "addq   %%rax, (%%rdi)\n"           \
+        "adcq   %%rdx, %%rcx\n"             \
+        "addq   $8, %%rdi\n"
 
 
 #define MULADDC_STOP                        \
 #define MULADDC_STOP                        \
         : "+c" (c), "+D" (d), "+S" (s)      \
         : "+c" (c), "+D" (d), "+S" (s)      \
@@ -520,7 +534,7 @@
         "swi   r3,   %2         \n\t"   \
         "swi   r3,   %2         \n\t"   \
         : "=m" (c), "=m" (d), "=m" (s)              \
         : "=m" (c), "=m" (d), "=m" (s)              \
         : "m" (s), "m" (d), "m" (c), "m" (b)        \
         : "m" (s), "m" (d), "m" (c), "m" (b)        \
-        : "r3", "r4"  "r5", "r6", "r7", "r8",       \
+        : "r3", "r4", "r5", "r6", "r7", "r8",       \
           "r9", "r10", "r11", "r12", "r13"          \
           "r9", "r10", "r11", "r12", "r13"          \
     );
     );
 
 
@@ -726,7 +740,7 @@
         "sw     $10, %2         \n\t"   \
         "sw     $10, %2         \n\t"   \
         : "=m" (c), "=m" (d), "=m" (s)                      \
         : "=m" (c), "=m" (d), "=m" (s)                      \
         : "m" (s), "m" (d), "m" (c), "m" (b)                \
         : "m" (s), "m" (d), "m" (c), "m" (b)                \
-        : "$9", "$10", "$11", "$12", "$13", "$14", "$15"    \
+        : "$9", "$10", "$11", "$12", "$13", "$14", "$15", "lo", "hi" \
     );
     );
 
 
 #endif /* MIPS */
 #endif /* MIPS */

+ 3 - 1
mbedtls/include/mbedtls/camellia.h

@@ -2,7 +2,8 @@
  * \file camellia.h
  * \file camellia.h
  *
  *
  * \brief Camellia block cipher
  * \brief Camellia block cipher
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -37,6 +38,7 @@
 
 
 #define MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH           -0x0024  /**< Invalid key length. */
 #define MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH           -0x0024  /**< Invalid key length. */
 #define MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH         -0x0026  /**< Invalid data input length. */
 #define MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH         -0x0026  /**< Invalid data input length. */
+#define MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED              -0x0027  /**< Camellia hardware accelerator failed. */
 
 
 #if !defined(MBEDTLS_CAMELLIA_ALT)
 #if !defined(MBEDTLS_CAMELLIA_ALT)
 // Regular implementation
 // Regular implementation

+ 100 - 59
mbedtls/include/mbedtls/ccm.h

@@ -1,9 +1,19 @@
 /**
 /**
  * \file ccm.h
  * \file ccm.h
  *
  *
- * \brief Counter with CBC-MAC (CCM) for 128-bit block ciphers
+ * \brief CCM combines Counter mode encryption with CBC-MAC authentication
+ *        for 128-bit block ciphers.
  *
  *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * Input to CCM includes the following elements:
+ * <ul><li>Payload - data that is both authenticated and encrypted.</li>
+ * <li>Associated data (Adata) - data that is authenticated but not
+ * encrypted, For example, a header.</li>
+ * <li>Nonce - A unique value that is assigned to the payload and the
+ * associated data.</li></ul>
+ *
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,46 +28,60 @@
  *  See the License for the specific language governing permissions and
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *  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_CCM_H
 #ifndef MBEDTLS_CCM_H
 #define MBEDTLS_CCM_H
 #define MBEDTLS_CCM_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include "cipher.h"
 #include "cipher.h"
 
 
-#define MBEDTLS_ERR_CCM_BAD_INPUT      -0x000D /**< Bad input parameters to function. */
-#define MBEDTLS_ERR_CCM_AUTH_FAILED    -0x000F /**< Authenticated decryption failed. */
+#define MBEDTLS_ERR_CCM_BAD_INPUT       -0x000D /**< Bad input parameters to the function. */
+#define MBEDTLS_ERR_CCM_AUTH_FAILED     -0x000F /**< Authenticated decryption failed. */
+#define MBEDTLS_ERR_CCM_HW_ACCEL_FAILED -0x0011 /**< CCM hardware accelerator failed. */
+
+#if !defined(MBEDTLS_CCM_ALT)
+// Regular implementation
+//
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
 extern "C" {
 extern "C" {
 #endif
 #endif
 
 
 /**
 /**
- * \brief          CCM context structure
+ * \brief    The CCM context-type definition. The CCM context is passed
+ *           to the APIs called.
  */
  */
 typedef struct {
 typedef struct {
-    mbedtls_cipher_context_t cipher_ctx;    /*!< cipher context used */
+    mbedtls_cipher_context_t cipher_ctx;    /*!< The cipher context used. */
 }
 }
 mbedtls_ccm_context;
 mbedtls_ccm_context;
 
 
 /**
 /**
- * \brief           Initialize CCM context (just makes references valid)
- *                  Makes the context ready for mbedtls_ccm_setkey() or
- *                  mbedtls_ccm_free().
+ * \brief           This function initializes the specified CCM context,
+ *                  to make references valid, and prepare the context
+ *                  for mbedtls_ccm_setkey() or mbedtls_ccm_free().
  *
  *
- * \param ctx       CCM context to initialize
+ * \param ctx       The CCM context to initialize.
  */
  */
 void mbedtls_ccm_init( mbedtls_ccm_context *ctx );
 void mbedtls_ccm_init( mbedtls_ccm_context *ctx );
 
 
 /**
 /**
- * \brief           CCM initialization (encryption and decryption)
+ * \brief           This function initializes the CCM context set in the
+ *                  \p ctx parameter and sets the encryption key.
  *
  *
- * \param ctx       CCM context to be initialized
- * \param cipher    cipher to use (a 128-bit block cipher)
- * \param key       encryption key
- * \param keybits   key size in bits (must be acceptable by the cipher)
+ * \param ctx       The CCM context to initialize.
+ * \param cipher    The 128-bit block cipher to use.
+ * \param key       The encryption key.
+ * \param keybits   The key size in bits. This must be acceptable by the cipher.
  *
  *
- * \return          0 if successful, or a cipher specific error code
+ * \return          \c 0 on success, or a cipher-specific error code.
  */
  */
 int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx,
 int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx,
                         mbedtls_cipher_id_t cipher,
                         mbedtls_cipher_id_t cipher,
@@ -65,36 +89,37 @@ int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx,
                         unsigned int keybits );
                         unsigned int keybits );
 
 
 /**
 /**
- * \brief           Free a CCM context and underlying cipher sub-context
+ * \brief   This function releases and clears the specified CCM context
+ *          and underlying cipher sub-context.
  *
  *
- * \param ctx       CCM context to free
+ * \param ctx       The CCM context to clear.
  */
  */
 void mbedtls_ccm_free( mbedtls_ccm_context *ctx );
 void mbedtls_ccm_free( mbedtls_ccm_context *ctx );
 
 
 /**
 /**
- * \brief           CCM buffer encryption
- *
- * \param ctx       CCM context
- * \param length    length of the input data in bytes
- * \param iv        nonce (initialization vector)
- * \param iv_len    length of IV in bytes
- *                  must be 2, 3, 4, 5, 6, 7 or 8
- * \param add       additional data
- * \param add_len   length of additional data in bytes
- *                  must be less than 2^16 - 2^8
- * \param input     buffer holding the input data
- * \param output    buffer for holding the output data
- *                  must be at least 'length' bytes wide
- * \param tag       buffer for holding the tag
- * \param tag_len   length of the tag to generate in bytes
- *                  must be 4, 6, 8, 10, 14 or 16
- *
- * \note            The tag is written to a separate buffer. To get the tag
- *                  concatenated with the output as in the CCM spec, use
- *                  tag = output + length and make sure the output buffer is
- *                  at least length + tag_len wide.
- *
- * \return          0 if successful
+ * \brief           This function encrypts a buffer using CCM.
+ *
+ * \param ctx       The CCM context to use for encryption.
+ * \param length    The length of the input data in Bytes.
+ * \param iv        Initialization vector (nonce).
+ * \param iv_len    The length of the IV in Bytes: 7, 8, 9, 10, 11, 12, or 13.
+ * \param add       The additional data field.
+ * \param add_len   The length of additional data in Bytes.
+ *                  Must be less than 2^16 - 2^8.
+ * \param input     The buffer holding the input data.
+ * \param output    The buffer holding the output data.
+ *                  Must be at least \p length Bytes wide.
+ * \param tag       The buffer holding the tag.
+ * \param tag_len   The length of the tag to generate in Bytes:
+ *                  4, 6, 8, 10, 12, 14 or 16.
+ *
+ * \note            The tag is written to a separate buffer. To concatenate
+ *                  the \p tag with the \p output, as done in <em>RFC-3610:
+ *                  Counter with CBC-MAC (CCM)</em>, use
+ *                  \p tag = \p output + \p length, and make sure that the
+ *                  output buffer is at least \p length + \p tag_len wide.
+ *
+ * \return          \c 0 on success.
  */
  */
 int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
 int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
                          const unsigned char *iv, size_t iv_len,
                          const unsigned char *iv, size_t iv_len,
@@ -103,21 +128,25 @@ int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
                          unsigned char *tag, size_t tag_len );
                          unsigned char *tag, size_t tag_len );
 
 
 /**
 /**
- * \brief           CCM buffer authenticated decryption
- *
- * \param ctx       CCM context
- * \param length    length of the input data
- * \param iv        initialization vector
- * \param iv_len    length of IV
- * \param add       additional data
- * \param add_len   length of additional data
- * \param input     buffer holding the input data
- * \param output    buffer for holding the output data
- * \param tag       buffer holding the tag
- * \param tag_len   length of the tag
- *
- * \return         0 if successful and authenticated,
- *                 MBEDTLS_ERR_CCM_AUTH_FAILED if tag does not match
+ * \brief           This function performs a CCM authenticated decryption of a
+ *                  buffer.
+ *
+ * \param ctx       The CCM context to use for decryption.
+ * \param length    The length of the input data in Bytes.
+ * \param iv        Initialization vector.
+ * \param iv_len    The length of the IV in Bytes: 7, 8, 9, 10, 11, 12, or 13.
+ * \param add       The additional data field.
+ * \param add_len   The length of additional data in Bytes.
+ *                  Must be less than 2^16 - 2^8.
+ * \param input     The buffer holding the input data.
+ * \param output    The buffer holding the output data.
+ *                  Must be at least \p length Bytes wide.
+ * \param tag       The buffer holding the tag.
+ * \param tag_len   The length of the tag in Bytes.
+ *                  4, 6, 8, 10, 12, 14 or 16.
+ *
+ * \return          0 if successful and authenticated, or
+ *                  #MBEDTLS_ERR_CCM_AUTH_FAILED if the tag does not match.
  */
  */
 int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
 int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
                       const unsigned char *iv, size_t iv_len,
                       const unsigned char *iv, size_t iv_len,
@@ -125,11 +154,23 @@ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
                       const unsigned char *input, unsigned char *output,
                       const unsigned char *input, unsigned char *output,
                       const unsigned char *tag, size_t tag_len );
                       const unsigned char *tag, size_t tag_len );
 
 
+#ifdef __cplusplus
+}
+#endif
+
+#else  /* MBEDTLS_CCM_ALT */
+#include "ccm_alt.h"
+#endif /* MBEDTLS_CCM_ALT */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
 #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
 /**
 /**
- * \brief          Checkup routine
+ * \brief          The CCM checkup routine.
  *
  *
- * \return         0 if successful, or 1 if the test failed
+ * \return         \c 0 on success, or \c 1 on failure.
  */
  */
 int mbedtls_ccm_self_test( int verbose );
 int mbedtls_ccm_self_test( int verbose );
 #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
 #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */

+ 8 - 1
mbedtls/include/mbedtls/certs.h

@@ -2,7 +2,8 @@
  * \file certs.h
  * \file certs.h
  *
  *
  * \brief Sample certificates and DHM parameters for testing
  * \brief Sample certificates and DHM parameters for testing
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -23,6 +24,12 @@
 #ifndef MBEDTLS_CERTS_H
 #ifndef MBEDTLS_CERTS_H
 #define MBEDTLS_CERTS_H
 #define MBEDTLS_CERTS_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include <stddef.h>
 #include <stddef.h>
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus

+ 10 - 1
mbedtls/include/mbedtls/check_config.h

@@ -2,7 +2,8 @@
  * \file check_config.h
  * \file check_config.h
  *
  *
  * \brief Consistency checks for configuration options
  * \brief Consistency checks for configuration options
- *
+ */
+/*
  *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -77,6 +78,10 @@
 #error "MBEDTLS_DHM_C defined, but not all prerequisites"
 #error "MBEDTLS_DHM_C defined, but not all prerequisites"
 #endif
 #endif
 
 
+#if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT) && !defined(MBEDTLS_SSL_TRUNCATED_HMAC)
+#error "MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT defined, but not all prerequisites"
+#endif
+
 #if defined(MBEDTLS_CMAC_C) && \
 #if defined(MBEDTLS_CMAC_C) && \
     !defined(MBEDTLS_AES_C) && !defined(MBEDTLS_DES_C)
     !defined(MBEDTLS_AES_C) && !defined(MBEDTLS_DES_C)
 #error "MBEDTLS_CMAC_C defined, but not all prerequisites"
 #error "MBEDTLS_CMAC_C defined, but not all prerequisites"
@@ -117,6 +122,10 @@
 #error "MBEDTLS_ECP_C defined, but not all prerequisites"
 #error "MBEDTLS_ECP_C defined, but not all prerequisites"
 #endif
 #endif
 
 
+#if defined(MBEDTLS_PK_PARSE_C) && !defined(MBEDTLS_ASN1_PARSE_C)
+#error "MBEDTLS_PK_PARSE_C defined, but not all prerequesites"
+#endif
+
 #if defined(MBEDTLS_ENTROPY_C) && (!defined(MBEDTLS_SHA512_C) &&      \
 #if defined(MBEDTLS_ENTROPY_C) && (!defined(MBEDTLS_SHA512_C) &&      \
                                     !defined(MBEDTLS_SHA256_C))
                                     !defined(MBEDTLS_SHA256_C))
 #error "MBEDTLS_ENTROPY_C defined, but not all prerequisites"
 #error "MBEDTLS_ENTROPY_C defined, but not all prerequisites"

+ 302 - 259
mbedtls/include/mbedtls/cipher.h

@@ -1,11 +1,12 @@
 /**
 /**
  * \file cipher.h
  * \file cipher.h
  *
  *
- * \brief Generic cipher wrapper.
+ * \brief The generic cipher wrapper.
  *
  *
  * \author Adriaan de Jong <dejong@fox-it.com>
  * \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
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -20,7 +21,7 @@
  *  See the License for the specific language governing permissions and
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *  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_CIPHER_H
 #ifndef MBEDTLS_CIPHER_H
@@ -42,7 +43,7 @@
 #define MBEDTLS_CIPHER_MODE_WITH_PADDING
 #define MBEDTLS_CIPHER_MODE_WITH_PADDING
 #endif
 #endif
 
 
-#if defined(MBEDTLS_ARC4_C)
+#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
 #define MBEDTLS_CIPHER_MODE_STREAM
 #define MBEDTLS_CIPHER_MODE_STREAM
 #endif
 #endif
 
 
@@ -51,21 +52,29 @@
 #define inline __inline
 #define inline __inline
 #endif
 #endif
 
 
-#define MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE            -0x6080  /**< The selected feature is not available. */
-#define MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA                 -0x6100  /**< Bad input parameters to function. */
-#define MBEDTLS_ERR_CIPHER_ALLOC_FAILED                   -0x6180  /**< Failed to allocate memory. */
-#define MBEDTLS_ERR_CIPHER_INVALID_PADDING                -0x6200  /**< Input data contains invalid padding and is rejected. */
-#define MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED            -0x6280  /**< Decryption of block requires a full block. */
-#define MBEDTLS_ERR_CIPHER_AUTH_FAILED                    -0x6300  /**< Authentication failed (for AEAD modes). */
-#define MBEDTLS_ERR_CIPHER_INVALID_CONTEXT              -0x6380  /**< The context is invalid, eg because it was free()ed. */
+#define MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE  -0x6080  /**< The selected feature is not available. */
+#define MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA       -0x6100  /**< Bad input parameters. */
+#define MBEDTLS_ERR_CIPHER_ALLOC_FAILED         -0x6180  /**< Failed to allocate memory. */
+#define MBEDTLS_ERR_CIPHER_INVALID_PADDING      -0x6200  /**< Input data contains invalid padding and is rejected. */
+#define MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED  -0x6280  /**< Decryption of block requires a full block. */
+#define MBEDTLS_ERR_CIPHER_AUTH_FAILED          -0x6300  /**< Authentication failed (for AEAD modes). */
+#define MBEDTLS_ERR_CIPHER_INVALID_CONTEXT      -0x6380  /**< The context is invalid. For example, because it was freed. */
+#define MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED      -0x6400  /**< Cipher hardware accelerator failed. */
 
 
-#define MBEDTLS_CIPHER_VARIABLE_IV_LEN     0x01    /**< Cipher accepts IVs of variable length */
-#define MBEDTLS_CIPHER_VARIABLE_KEY_LEN    0x02    /**< Cipher accepts keys of variable length */
+#define MBEDTLS_CIPHER_VARIABLE_IV_LEN     0x01    /**< Cipher accepts IVs of variable length. */
+#define MBEDTLS_CIPHER_VARIABLE_KEY_LEN    0x02    /**< Cipher accepts keys of variable length. */
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
 extern "C" {
 extern "C" {
 #endif
 #endif
 
 
+/**
+ * \brief     An enumeration of supported ciphers.
+ *
+ * \warning   ARC4 and DES are considered weak ciphers and their use
+ *            constitutes a security risk. We recommend considering stronger
+ *            ciphers instead.
+ */
 typedef enum {
 typedef enum {
     MBEDTLS_CIPHER_ID_NONE = 0,
     MBEDTLS_CIPHER_ID_NONE = 0,
     MBEDTLS_CIPHER_ID_NULL,
     MBEDTLS_CIPHER_ID_NULL,
@@ -77,6 +86,13 @@ typedef enum {
     MBEDTLS_CIPHER_ID_ARC4,
     MBEDTLS_CIPHER_ID_ARC4,
 } mbedtls_cipher_id_t;
 } mbedtls_cipher_id_t;
 
 
+/**
+ * \brief     An enumeration of supported (cipher, mode) pairs.
+ *
+ * \warning   ARC4 and DES are considered weak ciphers and their use
+ *            constitutes a security risk. We recommend considering stronger
+ *            ciphers instead.
+ */
 typedef enum {
 typedef enum {
     MBEDTLS_CIPHER_NONE = 0,
     MBEDTLS_CIPHER_NONE = 0,
     MBEDTLS_CIPHER_NULL,
     MBEDTLS_CIPHER_NULL,
@@ -129,6 +145,7 @@ typedef enum {
     MBEDTLS_CIPHER_CAMELLIA_256_CCM,
     MBEDTLS_CIPHER_CAMELLIA_256_CCM,
 } mbedtls_cipher_type_t;
 } mbedtls_cipher_type_t;
 
 
+/** Supported cipher modes. */
 typedef enum {
 typedef enum {
     MBEDTLS_MODE_NONE = 0,
     MBEDTLS_MODE_NONE = 0,
     MBEDTLS_MODE_ECB,
     MBEDTLS_MODE_ECB,
@@ -141,14 +158,16 @@ typedef enum {
     MBEDTLS_MODE_CCM,
     MBEDTLS_MODE_CCM,
 } mbedtls_cipher_mode_t;
 } mbedtls_cipher_mode_t;
 
 
+/** Supported cipher padding types. */
 typedef enum {
 typedef enum {
-    MBEDTLS_PADDING_PKCS7 = 0,     /**< PKCS7 padding (default)        */
-    MBEDTLS_PADDING_ONE_AND_ZEROS, /**< ISO/IEC 7816-4 padding         */
-    MBEDTLS_PADDING_ZEROS_AND_LEN, /**< ANSI X.923 padding             */
-    MBEDTLS_PADDING_ZEROS,         /**< zero padding (not reversible!) */
-    MBEDTLS_PADDING_NONE,          /**< never pad (full blocks only)   */
+    MBEDTLS_PADDING_PKCS7 = 0,     /**< PKCS7 padding (default).        */
+    MBEDTLS_PADDING_ONE_AND_ZEROS, /**< ISO/IEC 7816-4 padding.         */
+    MBEDTLS_PADDING_ZEROS_AND_LEN, /**< ANSI X.923 padding.             */
+    MBEDTLS_PADDING_ZEROS,         /**< zero padding (not reversible). */
+    MBEDTLS_PADDING_NONE,          /**< never pad (full blocks only).   */
 } mbedtls_cipher_padding_t;
 } mbedtls_cipher_padding_t;
 
 
+/** Type of operation. */
 typedef enum {
 typedef enum {
     MBEDTLS_OPERATION_NONE = -1,
     MBEDTLS_OPERATION_NONE = -1,
     MBEDTLS_DECRYPT = 0,
     MBEDTLS_DECRYPT = 0,
@@ -156,19 +175,19 @@ typedef enum {
 } mbedtls_operation_t;
 } mbedtls_operation_t;
 
 
 enum {
 enum {
-    /** Undefined key length */
+    /** Undefined key length. */
     MBEDTLS_KEY_LENGTH_NONE = 0,
     MBEDTLS_KEY_LENGTH_NONE = 0,
-    /** Key length, in bits (including parity), for DES keys */
+    /** Key length, in bits (including parity), for DES keys. */
     MBEDTLS_KEY_LENGTH_DES  = 64,
     MBEDTLS_KEY_LENGTH_DES  = 64,
-    /** Key length, in bits (including parity), for DES in two key EDE */
+    /** Key length in bits, including parity, for DES in two-key EDE. */
     MBEDTLS_KEY_LENGTH_DES_EDE = 128,
     MBEDTLS_KEY_LENGTH_DES_EDE = 128,
-    /** Key length, in bits (including parity), for DES in three-key EDE */
+    /** Key length in bits, including parity, for DES in three-key EDE. */
     MBEDTLS_KEY_LENGTH_DES_EDE3 = 192,
     MBEDTLS_KEY_LENGTH_DES_EDE3 = 192,
 };
 };
 
 
-/** Maximum length of any IV, in bytes */
+/** Maximum length of any IV, in Bytes. */
 #define MBEDTLS_MAX_IV_LENGTH      16
 #define MBEDTLS_MAX_IV_LENGTH      16
-/** Maximum block size of any cipher, in bytes */
+/** Maximum block size of any cipher, in Bytes. */
 #define MBEDTLS_MAX_BLOCK_LENGTH   16
 #define MBEDTLS_MAX_BLOCK_LENGTH   16
 
 
 /**
 /**
@@ -182,33 +201,40 @@ typedef struct mbedtls_cipher_base_t mbedtls_cipher_base_t;
 typedef struct mbedtls_cmac_context_t mbedtls_cmac_context_t;
 typedef struct mbedtls_cmac_context_t mbedtls_cmac_context_t;
 
 
 /**
 /**
- * Cipher information. Allows cipher functions to be called in a generic way.
+ * Cipher information. Allows calling cipher functions
+ * in a generic way.
  */
  */
 typedef struct {
 typedef struct {
-    /** Full cipher identifier (e.g. MBEDTLS_CIPHER_AES_256_CBC) */
+    /** Full cipher identifier. For example,
+     * MBEDTLS_CIPHER_AES_256_CBC.
+     */
     mbedtls_cipher_type_t type;
     mbedtls_cipher_type_t type;
 
 
-    /** Cipher mode (e.g. MBEDTLS_MODE_CBC) */
+    /** The cipher mode. For example, MBEDTLS_MODE_CBC. */
     mbedtls_cipher_mode_t mode;
     mbedtls_cipher_mode_t mode;
 
 
-    /** Cipher key length, in bits (default length for variable sized ciphers)
-     *  (Includes parity bits for ciphers like DES) */
+    /** The cipher key length, in bits. This is the
+     * default length for variable sized ciphers.
+     * Includes parity bits for ciphers like DES.
+     */
     unsigned int key_bitlen;
     unsigned int key_bitlen;
 
 
-    /** Name of the cipher */
+    /** Name of the cipher. */
     const char * name;
     const char * name;
 
 
-    /** IV/NONCE size, in bytes.
-     *  For cipher that accept many sizes: recommended size */
+    /** IV or nonce size, in Bytes.
+     * For ciphers that accept variable IV sizes,
+     * this is the recommended size.
+     */
     unsigned int iv_size;
     unsigned int iv_size;
 
 
-    /** Flags for variable IV size, variable key size, etc. */
+    /** Flags to set. For example, if the cipher supports variable IV sizes or variable key sizes. */
     int flags;
     int flags;
 
 
-    /** block size, in bytes */
+    /** The block size, in Bytes. */
     unsigned int block_size;
     unsigned int block_size;
 
 
-    /** Base cipher information and functions */
+    /** Struct for base cipher information and functions. */
     const mbedtls_cipher_base_t *base;
     const mbedtls_cipher_base_t *base;
 
 
 } mbedtls_cipher_info_t;
 } mbedtls_cipher_info_t;
@@ -217,125 +243,133 @@ typedef struct {
  * Generic cipher context.
  * Generic cipher context.
  */
  */
 typedef struct {
 typedef struct {
-    /** Information about the associated cipher */
+    /** Information about the associated cipher. */
     const mbedtls_cipher_info_t *cipher_info;
     const mbedtls_cipher_info_t *cipher_info;
 
 
-    /** Key length to use */
+    /** Key length to use. */
     int key_bitlen;
     int key_bitlen;
 
 
-    /** Operation that the context's key has been initialised for */
+    /** Operation that the key of the context has been
+     * initialized for.
+     */
     mbedtls_operation_t operation;
     mbedtls_operation_t operation;
 
 
 #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
 #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
-    /** Padding functions to use, if relevant for cipher mode */
+    /** Padding functions to use, if relevant for
+     * the specific cipher mode.
+     */
     void (*add_padding)( unsigned char *output, size_t olen, size_t data_len );
     void (*add_padding)( unsigned char *output, size_t olen, size_t data_len );
     int (*get_padding)( unsigned char *input, size_t ilen, size_t *data_len );
     int (*get_padding)( unsigned char *input, size_t ilen, size_t *data_len );
 #endif
 #endif
 
 
-    /** Buffer for data that hasn't been encrypted yet */
+    /** Buffer for input that has not been processed yet. */
     unsigned char unprocessed_data[MBEDTLS_MAX_BLOCK_LENGTH];
     unsigned char unprocessed_data[MBEDTLS_MAX_BLOCK_LENGTH];
 
 
-    /** Number of bytes that still need processing */
+    /** Number of Bytes that have not been processed yet. */
     size_t unprocessed_len;
     size_t unprocessed_len;
 
 
-    /** Current IV or NONCE_COUNTER for CTR-mode */
+    /** Current IV or NONCE_COUNTER for CTR-mode. */
     unsigned char iv[MBEDTLS_MAX_IV_LENGTH];
     unsigned char iv[MBEDTLS_MAX_IV_LENGTH];
 
 
-    /** IV size in bytes (for ciphers with variable-length IVs) */
+    /** IV size in Bytes, for ciphers with variable-length IVs. */
     size_t iv_size;
     size_t iv_size;
 
 
-    /** Cipher-specific context */
+    /** The cipher-specific context. */
     void *cipher_ctx;
     void *cipher_ctx;
 
 
 #if defined(MBEDTLS_CMAC_C)
 #if defined(MBEDTLS_CMAC_C)
-    /** CMAC Specific context */
+    /** CMAC-specific context. */
     mbedtls_cmac_context_t *cmac_ctx;
     mbedtls_cmac_context_t *cmac_ctx;
 #endif
 #endif
 } mbedtls_cipher_context_t;
 } mbedtls_cipher_context_t;
 
 
 /**
 /**
- * \brief Returns the list of ciphers supported by the generic cipher module.
+ * \brief This function retrieves the list of ciphers supported by the generic
+ * cipher module.
  *
  *
- * \return              a statically allocated array of ciphers, the last entry
- *                      is 0.
+ * \return      A statically-allocated array of ciphers. The last entry
+ *              is zero.
  */
  */
 const int *mbedtls_cipher_list( void );
 const int *mbedtls_cipher_list( void );
 
 
 /**
 /**
- * \brief               Returns the cipher information structure associated
- *                      with the given cipher name.
+ * \brief               This function retrieves the cipher-information
+ *                      structure associated with the given cipher name.
  *
  *
  * \param cipher_name   Name of the cipher to search for.
  * \param cipher_name   Name of the cipher to search for.
  *
  *
- * \return              the cipher information structure associated with the
- *                      given cipher_name, or NULL if not found.
+ * \return              The cipher information structure associated with the
+ *                      given \p cipher_name, or NULL if not found.
  */
  */
 const mbedtls_cipher_info_t *mbedtls_cipher_info_from_string( const char *cipher_name );
 const mbedtls_cipher_info_t *mbedtls_cipher_info_from_string( const char *cipher_name );
 
 
 /**
 /**
- * \brief               Returns the cipher information structure associated
- *                      with the given cipher type.
+ * \brief               This function retrieves the cipher-information
+ *                      structure associated with the given cipher type.
  *
  *
  * \param cipher_type   Type of the cipher to search for.
  * \param cipher_type   Type of the cipher to search for.
  *
  *
- * \return              the cipher information structure associated with the
- *                      given cipher_type, or NULL if not found.
+ * \return              The cipher information structure associated with the
+ *                      given \p cipher_type, or NULL if not found.
  */
  */
 const mbedtls_cipher_info_t *mbedtls_cipher_info_from_type( const mbedtls_cipher_type_t cipher_type );
 const mbedtls_cipher_info_t *mbedtls_cipher_info_from_type( const mbedtls_cipher_type_t cipher_type );
 
 
 /**
 /**
- * \brief               Returns the cipher information structure associated
- *                      with the given cipher id, key size and mode.
+ * \brief               This function retrieves the cipher-information
+ *                      structure associated with the given cipher ID,
+ *                      key size and mode.
  *
  *
- * \param cipher_id     Id of the cipher to search for
- *                      (e.g. MBEDTLS_CIPHER_ID_AES)
- * \param key_bitlen    Length of the key in bits
- * \param mode          Cipher mode (e.g. MBEDTLS_MODE_CBC)
+ * \param cipher_id     The ID of the cipher to search for. For example,
+ *                      #MBEDTLS_CIPHER_ID_AES.
+ * \param key_bitlen    The length of the key in bits.
+ * \param mode          The cipher mode. For example, #MBEDTLS_MODE_CBC.
  *
  *
- * \return              the cipher information structure associated with the
- *                      given cipher_type, or NULL if not found.
+ * \return              The cipher information structure associated with the
+ *                      given \p cipher_id, or NULL if not found.
  */
  */
 const mbedtls_cipher_info_t *mbedtls_cipher_info_from_values( const mbedtls_cipher_id_t cipher_id,
 const mbedtls_cipher_info_t *mbedtls_cipher_info_from_values( const mbedtls_cipher_id_t cipher_id,
                                               int key_bitlen,
                                               int key_bitlen,
                                               const mbedtls_cipher_mode_t mode );
                                               const mbedtls_cipher_mode_t mode );
 
 
 /**
 /**
- * \brief               Initialize a cipher_context (as NONE)
+ * \brief               This function initializes a \p cipher_context as NONE.
  */
  */
 void mbedtls_cipher_init( mbedtls_cipher_context_t *ctx );
 void mbedtls_cipher_init( mbedtls_cipher_context_t *ctx );
 
 
 /**
 /**
- * \brief               Free and clear the cipher-specific context of ctx.
- *                      Freeing ctx itself remains the responsibility of the
- *                      caller.
+ * \brief               This function frees and clears the cipher-specific
+ *                      context of \p ctx. Freeing \p ctx itself remains the
+ *                      responsibility of the caller.
  */
  */
 void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx );
 void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx );
 
 
+
 /**
 /**
- * \brief               Initialises and fills the cipher context structure with
- *                      the appropriate values.
- *
- * \note                Currently also clears structure. In future versions you
- *                      will be required to call mbedtls_cipher_init() on the structure
- *                      first.
+ * \brief               This function initializes and fills the cipher-context
+ *                      structure with the appropriate values. It also clears
+ *                      the structure.
  *
  *
- * \param ctx           context to initialise. May not be NULL.
- * \param cipher_info   cipher to use.
+ * \param ctx           The context to initialize. May not be NULL.
+ * \param cipher_info   The cipher to use.
  *
  *
- * \return              0 on success,
- *                      MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on parameter failure,
- *                      MBEDTLS_ERR_CIPHER_ALLOC_FAILED if allocation of the
+ * \return              \c 0 on success,
+ *                      #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on parameter failure,
+ *                      #MBEDTLS_ERR_CIPHER_ALLOC_FAILED if allocation of the
  *                      cipher-specific context failed.
  *                      cipher-specific context failed.
+ *
+ * \internal Currently, the function also clears the structure.
+ * In future versions, the caller will be required to call
+ * mbedtls_cipher_init() on the structure first.
  */
  */
 int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_info_t *cipher_info );
 int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx, const mbedtls_cipher_info_t *cipher_info );
 
 
 /**
 /**
- * \brief               Returns the block size of the given cipher.
+ * \brief        This function returns the block size of the given cipher.
  *
  *
- * \param ctx           cipher's context. Must have been initialised.
+ * \param ctx    The context of the cipher. Must be initialized.
  *
  *
- * \return              size of the cipher's blocks, or 0 if ctx has not been
- *                      initialised.
+ * \return       The size of the blocks of the cipher, or zero if \p ctx
+ *               has not been initialized.
  */
  */
 static inline unsigned int mbedtls_cipher_get_block_size( const mbedtls_cipher_context_t *ctx )
 static inline unsigned int mbedtls_cipher_get_block_size( const mbedtls_cipher_context_t *ctx )
 {
 {
@@ -346,13 +380,13 @@ static inline unsigned int mbedtls_cipher_get_block_size( const mbedtls_cipher_c
 }
 }
 
 
 /**
 /**
- * \brief               Returns the mode of operation for the cipher.
- *                      (e.g. MBEDTLS_MODE_CBC)
+ * \brief        This function returns the mode of operation for
+ *               the cipher. For example, MBEDTLS_MODE_CBC.
  *
  *
- * \param ctx           cipher's context. Must have been initialised.
+ * \param ctx    The context of the cipher. Must be initialized.
  *
  *
- * \return              mode of operation, or MBEDTLS_MODE_NONE if ctx
- *                      has not been initialised.
+ * \return       The mode of operation, or #MBEDTLS_MODE_NONE if
+ *               \p ctx has not been initialized.
  */
  */
 static inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode( const mbedtls_cipher_context_t *ctx )
 static inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode( const mbedtls_cipher_context_t *ctx )
 {
 {
@@ -363,13 +397,14 @@ static inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode( const mbedtl
 }
 }
 
 
 /**
 /**
- * \brief               Returns the size of the cipher's IV/NONCE in bytes.
+ * \brief       This function returns the size of the IV or nonce
+ *              of the cipher, in Bytes.
  *
  *
- * \param ctx           cipher's context. Must have been initialised.
+ * \param ctx   The context of the cipher. Must be initialized.
  *
  *
- * \return              If IV has not been set yet: (recommended) IV size
- *                      (0 for ciphers not using IV/NONCE).
- *                      If IV has already been set: actual size.
+ * \return      <ul><li>If no IV has been set: the recommended IV size.
+ *              0 for ciphers not using IV or nonce.</li>
+ *              <li>If IV has already been set: the actual size.</li></ul>
  */
  */
 static inline int mbedtls_cipher_get_iv_size( const mbedtls_cipher_context_t *ctx )
 static inline int mbedtls_cipher_get_iv_size( const mbedtls_cipher_context_t *ctx )
 {
 {
@@ -383,12 +418,12 @@ static inline int mbedtls_cipher_get_iv_size( const mbedtls_cipher_context_t *ct
 }
 }
 
 
 /**
 /**
- * \brief               Returns the type of the given cipher.
+ * \brief               This function returns the type of the given cipher.
  *
  *
- * \param ctx           cipher's context. Must have been initialised.
+ * \param ctx           The context of the cipher. Must be initialized.
  *
  *
- * \return              type of the cipher, or MBEDTLS_CIPHER_NONE if ctx has
- *                      not been initialised.
+ * \return              The type of the cipher, or #MBEDTLS_CIPHER_NONE if
+ *                      \p ctx has not been initialized.
  */
  */
 static inline mbedtls_cipher_type_t mbedtls_cipher_get_type( const mbedtls_cipher_context_t *ctx )
 static inline mbedtls_cipher_type_t mbedtls_cipher_get_type( const mbedtls_cipher_context_t *ctx )
 {
 {
@@ -399,11 +434,13 @@ static inline mbedtls_cipher_type_t mbedtls_cipher_get_type( const mbedtls_ciphe
 }
 }
 
 
 /**
 /**
- * \brief               Returns the name of the given cipher, as a string.
+ * \brief               This function returns the name of the given cipher
+ *                      as a string.
  *
  *
- * \param ctx           cipher's context. Must have been initialised.
+ * \param ctx           The context of the cipher. Must be initialized.
  *
  *
- * \return              name of the cipher, or NULL if ctx was not initialised.
+ * \return              The name of the cipher, or NULL if \p ctx has not
+ *                      been not initialized.
  */
  */
 static inline const char *mbedtls_cipher_get_name( const mbedtls_cipher_context_t *ctx )
 static inline const char *mbedtls_cipher_get_name( const mbedtls_cipher_context_t *ctx )
 {
 {
@@ -414,13 +451,13 @@ static inline const char *mbedtls_cipher_get_name( const mbedtls_cipher_context_
 }
 }
 
 
 /**
 /**
- * \brief               Returns the key length of the cipher.
+ * \brief               This function returns the key length of the cipher.
  *
  *
- * \param ctx           cipher's context. Must have been initialised.
+ * \param ctx           The context of the cipher. Must be initialized.
  *
  *
- * \return              cipher's key length, in bits, or
- *                      MBEDTLS_KEY_LENGTH_NONE if ctx has not been
- *                      initialised.
+ * \return              The key length of the cipher in bits, or
+ *                      #MBEDTLS_KEY_LENGTH_NONE if ctx \p has not been
+ *                      initialized.
  */
  */
 static inline int mbedtls_cipher_get_key_bitlen( const mbedtls_cipher_context_t *ctx )
 static inline int mbedtls_cipher_get_key_bitlen( const mbedtls_cipher_context_t *ctx )
 {
 {
@@ -431,13 +468,13 @@ static inline int mbedtls_cipher_get_key_bitlen( const mbedtls_cipher_context_t
 }
 }
 
 
 /**
 /**
- * \brief               Returns the operation of the given cipher.
+ * \brief          This function returns the operation of the given cipher.
  *
  *
- * \param ctx           cipher's context. Must have been initialised.
+ * \param ctx      The context of the cipher. Must be initialized.
  *
  *
- * \return              operation (MBEDTLS_ENCRYPT or MBEDTLS_DECRYPT),
- *                      or MBEDTLS_OPERATION_NONE if ctx has not been
- *                      initialised.
+ * \return         The type of operation: #MBEDTLS_ENCRYPT or
+ *                 #MBEDTLS_DECRYPT, or #MBEDTLS_OPERATION_NONE if \p ctx
+ *                 has not been initialized.
  */
  */
 static inline mbedtls_operation_t mbedtls_cipher_get_operation( const mbedtls_cipher_context_t *ctx )
 static inline mbedtls_operation_t mbedtls_cipher_get_operation( const mbedtls_cipher_context_t *ctx )
 {
 {
@@ -448,18 +485,18 @@ static inline mbedtls_operation_t mbedtls_cipher_get_operation( const mbedtls_ci
 }
 }
 
 
 /**
 /**
- * \brief               Set the key to use with the given context.
+ * \brief               This function sets the key to use with the given context.
  *
  *
- * \param ctx           generic cipher context. May not be NULL. Must have been
- *                      initialised using cipher_context_from_type or
- *                      cipher_context_from_string.
+ * \param ctx           The generic cipher context. May not be NULL. Must have
+ *                      been initialized using mbedtls_cipher_info_from_type()
+ *                      or mbedtls_cipher_info_from_string().
  * \param key           The key to use.
  * \param key           The key to use.
- * \param key_bitlen    key length to use, in bits.
- * \param operation     Operation that the key will be used for, either
- *                      MBEDTLS_ENCRYPT or MBEDTLS_DECRYPT.
+ * \param key_bitlen    The key length to use, in bits.
+ * \param operation     The operation that the key will be used for:
+ *                      #MBEDTLS_ENCRYPT or #MBEDTLS_DECRYPT.
  *
  *
- * \returns             0 on success, MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if
- *                      parameter verification fails or a cipher specific
+ * \returns             \c 0 on success, #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if
+ *                      parameter verification fails, or a cipher-specific
  *                      error code.
  *                      error code.
  */
  */
 int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *key,
 int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *key,
@@ -467,170 +504,176 @@ int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx, const unsigned char *k
 
 
 #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
 #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
 /**
 /**
- * \brief               Set padding mode, for cipher modes that use padding.
- *                      (Default: PKCS7 padding.)
+ * \brief               This function sets the padding mode, for cipher modes
+ *                      that use padding.
+ *
+ *                      The default passing mode is PKCS7 padding.
  *
  *
- * \param ctx           generic cipher context
- * \param mode          padding mode
+ * \param ctx           The generic cipher context.
+ * \param mode          The padding mode.
  *
  *
- * \returns             0 on success, MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE
- *                      if selected padding mode is not supported, or
- *                      MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if the cipher mode
+ * \returns             \c 0 on success, #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE
+ *                      if the selected padding mode is not supported, or
+ *                      #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if the cipher mode
  *                      does not support padding.
  *                      does not support padding.
  */
  */
 int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, mbedtls_cipher_padding_t mode );
 int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx, mbedtls_cipher_padding_t mode );
 #endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */
 #endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */
 
 
 /**
 /**
- * \brief               Set the initialization vector (IV) or nonce
+ * \brief           This function sets the initialization vector (IV)
+ *                  or nonce.
  *
  *
- * \param ctx           generic cipher context
- * \param iv            IV to use (or NONCE_COUNTER for CTR-mode ciphers)
- * \param iv_len        IV length for ciphers with variable-size IV;
- *                      discarded by ciphers with fixed-size IV.
+ * \param ctx       The generic cipher context.
+ * \param iv        The IV to use, or NONCE_COUNTER for CTR-mode ciphers.
+ * \param iv_len    The IV length for ciphers with variable-size IV.
+ *                  This parameter is discarded by ciphers with fixed-size IV.
  *
  *
- * \returns             0 on success, or MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA
+ * \returns         \c 0 on success, or #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA
  *
  *
- * \note                Some ciphers don't use IVs nor NONCE. For these
- *                      ciphers, this function has no effect.
+ * \note            Some ciphers do not use IVs nor nonce. For these
+ *                  ciphers, this function has no effect.
  */
  */
 int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx,
 int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx,
                    const unsigned char *iv, size_t iv_len );
                    const unsigned char *iv, size_t iv_len );
 
 
 /**
 /**
- * \brief               Finish preparation of the given context
+ * \brief         This function resets the cipher state.
  *
  *
- * \param ctx           generic cipher context
+ * \param ctx     The generic cipher context.
  *
  *
- * \returns             0 on success, MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA
- *                      if parameter verification fails.
+ * \returns       \c 0 on success, #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA
+ *                if parameter verification fails.
  */
  */
 int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx );
 int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx );
 
 
 #if defined(MBEDTLS_GCM_C)
 #if defined(MBEDTLS_GCM_C)
 /**
 /**
- * \brief               Add additional data (for AEAD ciphers).
- *                      Currently only supported with GCM.
- *                      Must be called exactly once, after mbedtls_cipher_reset().
+ * \brief               This function adds additional data for AEAD ciphers.
+ *                      Only supported with GCM. Must be called
+ *                      exactly once, after mbedtls_cipher_reset().
  *
  *
- * \param ctx           generic cipher context
- * \param ad            Additional data to use.
- * \param ad_len        Length of ad.
+ * \param ctx           The generic cipher context.
+ * \param ad            The additional data to use.
+ * \param ad_len        the Length of \p ad.
  *
  *
- * \return              0 on success, or a specific error code.
+ * \return              \c 0 on success, or a specific error code on failure.
  */
  */
 int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx,
 int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx,
                       const unsigned char *ad, size_t ad_len );
                       const unsigned char *ad, size_t ad_len );
 #endif /* MBEDTLS_GCM_C */
 #endif /* MBEDTLS_GCM_C */
 
 
 /**
 /**
- * \brief               Generic cipher update function. Encrypts/decrypts
- *                      using the given cipher context. Writes as many block
- *                      size'd blocks of data as possible to output. Any data
- *                      that cannot be written immediately will either be added
- *                      to the next block, or flushed when cipher_final is
- *                      called.
- *                      Exception: for MBEDTLS_MODE_ECB, expects single block
- *                                 in size (e.g. 16 bytes for AES)
- *
- * \param ctx           generic cipher context
- * \param input         buffer holding the input data
- * \param ilen          length of the input data
- * \param output        buffer for the output data. Should be able to hold at
- *                      least ilen + block_size. Cannot be the same buffer as
- *                      input!
- * \param olen          length of the output data, will be filled with the
- *                      actual number of bytes written.
- *
- * \returns             0 on success, MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if
+ * \brief               The generic cipher update function. It encrypts or
+ *                      decrypts using the given cipher context. Writes as
+ *                      many block-sized blocks of data as possible to output.
+ *                      Any data that cannot be written immediately is either
+ *                      added to the next block, or flushed when
+ *                      mbedtls_cipher_finish() is called.
+ *                      Exception: For MBEDTLS_MODE_ECB, expects a single block
+ *                      in size. For example, 16 Bytes for AES.
+ *
+ * \param ctx           The generic cipher context.
+ * \param input         The buffer holding the input data.
+ * \param ilen          The length of the input data.
+ * \param output        The buffer for the output data. Must be able to hold at
+ *                      least \p ilen + block_size. Must not be the same buffer
+ *                      as input.
+ * \param olen          The length of the output data, to be updated with the
+ *                      actual number of Bytes written.
+ *
+ * \returns             \c 0 on success, #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if
  *                      parameter verification fails,
  *                      parameter verification fails,
- *                      MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE on an
- *                      unsupported mode for a cipher or a cipher specific
+ *                      #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE on an
+ *                      unsupported mode for a cipher, or a cipher-specific
  *                      error code.
  *                      error code.
  *
  *
  * \note                If the underlying cipher is GCM, all calls to this
  * \note                If the underlying cipher is GCM, all calls to this
- *                      function, except the last one before mbedtls_cipher_finish(),
- *                      must have ilen a multiple of the block size.
+ *                      function, except the last one before
+ *                      mbedtls_cipher_finish(). Must have \p ilen as a
+ *                      multiple of the block_size.
  */
  */
 int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *input,
 int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *input,
                    size_t ilen, unsigned char *output, size_t *olen );
                    size_t ilen, unsigned char *output, size_t *olen );
 
 
 /**
 /**
- * \brief               Generic cipher finalisation function. If data still
- *                      needs to be flushed from an incomplete block, data
- *                      contained within it will be padded with the size of
- *                      the last block, and written to the output buffer.
+ * \brief               The generic cipher finalization function. If data still
+ *                      needs to be flushed from an incomplete block, the data
+ *                      contained in it is padded to the size of
+ *                      the last block, and written to the \p output buffer.
  *
  *
- * \param ctx           Generic cipher context
- * \param output        buffer to write data to. Needs block_size available.
- * \param olen          length of the data written to the output buffer.
+ * \param ctx           The generic cipher context.
+ * \param output        The buffer to write data to. Needs block_size available.
+ * \param olen          The length of the data written to the \p output buffer.
  *
  *
- * \returns             0 on success, MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if
+ * \returns             \c 0 on success, #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if
  *                      parameter verification fails,
  *                      parameter verification fails,
- *                      MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED if decryption
+ *                      #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED if decryption
  *                      expected a full block but was not provided one,
  *                      expected a full block but was not provided one,
- *                      MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding
- *                      while decrypting or a cipher specific error code.
+ *                      #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding
+ *                      while decrypting, or a cipher-specific error code
+ *                      on failure for any other reason.
  */
  */
 int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx,
 int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx,
                    unsigned char *output, size_t *olen );
                    unsigned char *output, size_t *olen );
 
 
 #if defined(MBEDTLS_GCM_C)
 #if defined(MBEDTLS_GCM_C)
 /**
 /**
- * \brief               Write tag for AEAD ciphers.
- *                      Currently only supported with GCM.
+ * \brief               This function writes a tag for AEAD ciphers.
+ *                      Only supported with GCM.
  *                      Must be called after mbedtls_cipher_finish().
  *                      Must be called after mbedtls_cipher_finish().
  *
  *
- * \param ctx           Generic cipher context
- * \param tag           buffer to write the tag
- * \param tag_len       Length of the tag to write
+ * \param ctx           The generic cipher context.
+ * \param tag           The buffer to write the tag to.
+ * \param tag_len       The length of the tag to write.
  *
  *
- * \return              0 on success, or a specific error code.
+ * \return              \c 0 on success, or a specific error code on failure.
  */
  */
 int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx,
 int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx,
                       unsigned char *tag, size_t tag_len );
                       unsigned char *tag, size_t tag_len );
 
 
 /**
 /**
- * \brief               Check tag for AEAD ciphers.
- *                      Currently only supported with GCM.
+ * \brief               This function checks the tag for AEAD ciphers.
+ *                      Only supported with GCM.
  *                      Must be called after mbedtls_cipher_finish().
  *                      Must be called after mbedtls_cipher_finish().
  *
  *
- * \param ctx           Generic cipher context
- * \param tag           Buffer holding the tag
- * \param tag_len       Length of the tag to check
+ * \param ctx           The generic cipher context.
+ * \param tag           The buffer holding the tag.
+ * \param tag_len       The length of the tag to check.
  *
  *
- * \return              0 on success, or a specific error code.
+ * \return              \c 0 on success, or a specific error code on failure.
  */
  */
 int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx,
 int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx,
                       const unsigned char *tag, size_t tag_len );
                       const unsigned char *tag, size_t tag_len );
 #endif /* MBEDTLS_GCM_C */
 #endif /* MBEDTLS_GCM_C */
 
 
 /**
 /**
- * \brief               Generic all-in-one encryption/decryption
- *                      (for all ciphers except AEAD constructs).
- *
- * \param ctx           generic cipher context
- * \param iv            IV to use (or NONCE_COUNTER for CTR-mode ciphers)
- * \param iv_len        IV length for ciphers with variable-size IV;
- *                      discarded by ciphers with fixed-size IV.
- * \param input         buffer holding the input data
- * \param ilen          length of the input data
- * \param output        buffer for the output data. Should be able to hold at
- *                      least ilen + block_size. Cannot be the same buffer as
- *                      input!
- * \param olen          length of the output data, will be filled with the
- *                      actual number of bytes written.
- *
- * \note                Some ciphers don't use IVs nor NONCE. For these
- *                      ciphers, use iv = NULL and iv_len = 0.
- *
- * \returns             0 on success, or
- *                      MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, or
- *                      MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED if decryption
+ * \brief               The generic all-in-one encryption/decryption function,
+ *                      for all ciphers except AEAD constructs.
+ *
+ * \param ctx           The generic cipher context.
+ * \param iv            The IV to use, or NONCE_COUNTER for CTR-mode ciphers.
+ * \param iv_len        The IV length for ciphers with variable-size IV.
+ *                      This parameter is discarded by ciphers with fixed-size
+ *                      IV.
+ * \param input         The buffer holding the input data.
+ * \param ilen          The length of the input data.
+ * \param output        The buffer for the output data. Must be able to hold at
+ *                      least \p ilen + block_size. Must not be the same buffer
+ *                      as input.
+ * \param olen          The length of the output data, to be updated with the
+ *                      actual number of Bytes written.
+ *
+ * \note                Some ciphers do not use IVs nor nonce. For these
+ *                      ciphers, use \p iv = NULL and \p iv_len = 0.
+ *
+ * \returns             \c 0 on success, or
+ *                      #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, or
+ *                      #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED if decryption
  *                      expected a full block but was not provided one, or
  *                      expected a full block but was not provided one, or
- *                      MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding
- *                      while decrypting, or
- *                      a cipher specific error code.
+ *                      #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding
+ *                      while decrypting, or a cipher-specific error code on
+ *                      failure for any other reason.
  */
  */
 int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx,
 int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx,
                   const unsigned char *iv, size_t iv_len,
                   const unsigned char *iv, size_t iv_len,
@@ -639,26 +682,26 @@ int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx,
 
 
 #if defined(MBEDTLS_CIPHER_MODE_AEAD)
 #if defined(MBEDTLS_CIPHER_MODE_AEAD)
 /**
 /**
- * \brief               Generic autenticated encryption (AEAD ciphers).
- *
- * \param ctx           generic cipher context
- * \param iv            IV to use (or NONCE_COUNTER for CTR-mode ciphers)
- * \param iv_len        IV length for ciphers with variable-size IV;
- *                      discarded by ciphers with fixed-size IV.
- * \param ad            Additional data to authenticate.
- * \param ad_len        Length of ad.
- * \param input         buffer holding the input data
- * \param ilen          length of the input data
- * \param output        buffer for the output data.
- *                      Should be able to hold at least ilen.
- * \param olen          length of the output data, will be filled with the
- *                      actual number of bytes written.
- * \param tag           buffer for the authentication tag
- * \param tag_len       desired tag length
- *
- * \returns             0 on success, or
- *                      MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, or
- *                      a cipher specific error code.
+ * \brief               The generic autenticated encryption (AEAD) function.
+ *
+ * \param ctx           The generic cipher context.
+ * \param iv            The IV to use, or NONCE_COUNTER for CTR-mode ciphers.
+ * \param iv_len        The IV length for ciphers with variable-size IV.
+ *                      This parameter is discarded by ciphers with fixed-size IV.
+ * \param ad            The additional data to authenticate.
+ * \param ad_len        The length of \p ad.
+ * \param input         The buffer holding the input data.
+ * \param ilen          The length of the input data.
+ * \param output        The buffer for the output data.
+ *                      Must be able to hold at least \p ilen.
+ * \param olen          The length of the output data, to be updated with the
+ *                      actual number of Bytes written.
+ * \param tag           The buffer for the authentication tag.
+ * \param tag_len       The desired length of the authentication tag.
+ *
+ * \returns             \c 0 on success, or
+ *                      #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, or
+ *                      a cipher-specific error code.
  */
  */
 int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx,
 int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx,
                          const unsigned char *iv, size_t iv_len,
                          const unsigned char *iv, size_t iv_len,
@@ -668,31 +711,31 @@ int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx,
                          unsigned char *tag, size_t tag_len );
                          unsigned char *tag, size_t tag_len );
 
 
 /**
 /**
- * \brief               Generic autenticated decryption (AEAD ciphers).
- *
- * \param ctx           generic cipher context
- * \param iv            IV to use (or NONCE_COUNTER for CTR-mode ciphers)
- * \param iv_len        IV length for ciphers with variable-size IV;
- *                      discarded by ciphers with fixed-size IV.
- * \param ad            Additional data to be authenticated.
- * \param ad_len        Length of ad.
- * \param input         buffer holding the input data
- * \param ilen          length of the input data
- * \param output        buffer for the output data.
- *                      Should be able to hold at least ilen.
- * \param olen          length of the output data, will be filled with the
- *                      actual number of bytes written.
- * \param tag           buffer holding the authentication tag
- * \param tag_len       length of the authentication tag
- *
- * \returns             0 on success, or
- *                      MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, or
- *                      MBEDTLS_ERR_CIPHER_AUTH_FAILED if data isn't authentic,
- *                      or a cipher specific error code.
+ * \brief               The generic autenticated decryption (AEAD) function.
+ *
+ * \param ctx           The generic cipher context.
+ * \param iv            The IV to use, or NONCE_COUNTER for CTR-mode ciphers.
+ * \param iv_len        The IV length for ciphers with variable-size IV.
+ *                      This parameter is discarded by ciphers with fixed-size IV.
+ * \param ad            The additional data to be authenticated.
+ * \param ad_len        The length of \p ad.
+ * \param input         The buffer holding the input data.
+ * \param ilen          The length of the input data.
+ * \param output        The buffer for the output data.
+ *                      Must be able to hold at least \p ilen.
+ * \param olen          The length of the output data, to be updated with the
+ *                      actual number of Bytes written.
+ * \param tag           The buffer holding the authentication tag.
+ * \param tag_len       The length of the authentication tag.
+ *
+ * \returns             \c 0 on success, or
+ *                      #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, or
+ *                      #MBEDTLS_ERR_CIPHER_AUTH_FAILED if data is not authentic,
+ *                      or a cipher-specific error code on failure for any other reason.
  *
  *
  * \note                If the data is not authentic, then the output buffer
  * \note                If the data is not authentic, then the output buffer
- *                      is zeroed out to prevent the unauthentic plaintext to
- *                      be used by mistake, making this interface safer.
+ *                      is zeroed out to prevent the unauthentic plaintext being
+ *                      used, making this interface safer.
  */
  */
 int mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx,
 int mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx,
                          const unsigned char *iv, size_t iv_len,
                          const unsigned char *iv, size_t iv_len,

+ 2 - 1
mbedtls/include/mbedtls/cipher_internal.h

@@ -4,7 +4,8 @@
  * \brief Cipher wrappers.
  * \brief Cipher wrappers.
  *
  *
  * \author Adriaan de Jong <dejong@fox-it.com>
  * \author Adriaan de Jong <dejong@fox-it.com>
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *

+ 117 - 73
mbedtls/include/mbedtls/cmac.h

@@ -1,10 +1,11 @@
 /**
 /**
  * \file cmac.h
  * \file cmac.h
  *
  *
- * \brief Cipher-based Message Authentication Code (CMAC) Mode for
- *        Authentication
- *
- *  Copyright (C) 2015-2016, ARM Limited, All Rights Reserved
+ * \brief The Cipher-based Message Authentication Code (CMAC) Mode for
+ *        Authentication.
+ */
+/*
+ *  Copyright (C) 2015-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -19,117 +20,143 @@
  *  See the License for the specific language governing permissions and
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *  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_CMAC_H
 #ifndef MBEDTLS_CMAC_H
 #define MBEDTLS_CMAC_H
 #define MBEDTLS_CMAC_H
 
 
-#include "mbedtls/cipher.h"
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
+#include "cipher.h"
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
 extern "C" {
 extern "C" {
 #endif
 #endif
 
 
+#define MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED -0x007A  /**< CMAC hardware accelerator failed. */
+
 #define MBEDTLS_AES_BLOCK_SIZE          16
 #define MBEDTLS_AES_BLOCK_SIZE          16
 #define MBEDTLS_DES3_BLOCK_SIZE         8
 #define MBEDTLS_DES3_BLOCK_SIZE         8
 
 
 #if defined(MBEDTLS_AES_C)
 #if defined(MBEDTLS_AES_C)
-#define MBEDTLS_CIPHER_BLKSIZE_MAX      16  /* longest used by CMAC is AES */
+#define MBEDTLS_CIPHER_BLKSIZE_MAX      16  /* The longest block used by CMAC is that of AES. */
 #else
 #else
-#define MBEDTLS_CIPHER_BLKSIZE_MAX      8   /* longest used by CMAC is 3DES */
+#define MBEDTLS_CIPHER_BLKSIZE_MAX      8   /* The longest block used by CMAC is that of 3DES. */
 #endif
 #endif
 
 
+#if !defined(MBEDTLS_CMAC_ALT)
+
 /**
 /**
- * CMAC context structure - Contains internal state information only
+ * The CMAC context structure.
  */
  */
 struct mbedtls_cmac_context_t
 struct mbedtls_cmac_context_t
 {
 {
-    /** Internal state of the CMAC algorithm  */
+    /** The internal state of the CMAC algorithm.  */
     unsigned char       state[MBEDTLS_CIPHER_BLKSIZE_MAX];
     unsigned char       state[MBEDTLS_CIPHER_BLKSIZE_MAX];
 
 
     /** Unprocessed data - either data that was not block aligned and is still
     /** Unprocessed data - either data that was not block aligned and is still
-     *  pending to be processed, or the final block */
+     *  pending processing, or the final block. */
     unsigned char       unprocessed_block[MBEDTLS_CIPHER_BLKSIZE_MAX];
     unsigned char       unprocessed_block[MBEDTLS_CIPHER_BLKSIZE_MAX];
 
 
-    /** Length of data pending to be processed */
+    /** The length of data pending processing. */
     size_t              unprocessed_len;
     size_t              unprocessed_len;
 };
 };
 
 
 /**
 /**
- * \brief               Set the CMAC key and prepare to authenticate the input
- *                      data.
- *                      Should be called with an initialized cipher context.
- *
- * \param ctx           Cipher context. This should be a cipher context,
- *                      initialized to be one of the following types:
- *                      MBEDTLS_CIPHER_AES_128_ECB, MBEDTLS_CIPHER_AES_192_ECB,
- *                      MBEDTLS_CIPHER_AES_256_ECB or
- *                      MBEDTLS_CIPHER_DES_EDE3_ECB.
- * \param key           CMAC key
- * \param keybits       length of the CMAC key in bits
- *                      (must be acceptable by the cipher)
- *
- * \return              0 if successful, or a cipher specific error code
+ * \brief               This function sets the CMAC key, and prepares to authenticate
+ *                      the input data.
+ *                      Must be called with an initialized cipher context.
+ *
+ * \param ctx           The cipher context used for the CMAC operation, initialized
+ *                      as one of the following types:<ul>
+ *                      <li>MBEDTLS_CIPHER_AES_128_ECB</li>
+ *                      <li>MBEDTLS_CIPHER_AES_192_ECB</li>
+ *                      <li>MBEDTLS_CIPHER_AES_256_ECB</li>
+ *                      <li>MBEDTLS_CIPHER_DES_EDE3_ECB</li></ul>
+ * \param key           The CMAC key.
+ * \param keybits       The length of the CMAC key in bits.
+ *                      Must be supported by the cipher.
+ *
+ * \return              \c 0 on success, or a cipher-specific error code.
  */
  */
 int mbedtls_cipher_cmac_starts( mbedtls_cipher_context_t *ctx,
 int mbedtls_cipher_cmac_starts( mbedtls_cipher_context_t *ctx,
                                 const unsigned char *key, size_t keybits );
                                 const unsigned char *key, size_t keybits );
 
 
 /**
 /**
- * \brief               Generic CMAC process buffer.
- *                      Called between mbedtls_cipher_cmac_starts() or
- *                      mbedtls_cipher_cmac_reset() and
- *                      mbedtls_cipher_cmac_finish().
- *                      May be called repeatedly.
- *
- * \param ctx           CMAC context
- * \param input         buffer holding the  data
- * \param ilen          length of the input data
- *
- * \returns             0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                      verification fails.
+ * \brief               This function feeds an input buffer into an ongoing CMAC
+ *                      computation.
+ *
+ *                      It is called between mbedtls_cipher_cmac_starts() or
+ *                      mbedtls_cipher_cmac_reset(), and mbedtls_cipher_cmac_finish().
+ *                      Can be called repeatedly.
+ *
+ * \param ctx           The cipher context used for the CMAC operation.
+ * \param input         The buffer holding the input data.
+ * \param ilen          The length of the input data.
+ *
+ * \returns             \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA
+ *                      if parameter verification fails.
  */
  */
 int mbedtls_cipher_cmac_update( mbedtls_cipher_context_t *ctx,
 int mbedtls_cipher_cmac_update( mbedtls_cipher_context_t *ctx,
                                 const unsigned char *input, size_t ilen );
                                 const unsigned char *input, size_t ilen );
 
 
 /**
 /**
- * \brief               Output CMAC.
- *                      Called after mbedtls_cipher_cmac_update().
- *                      Usually followed by mbedtls_cipher_cmac_reset(), then
- *                      mbedtls_cipher_cmac_starts(), or mbedtls_cipher_free().
+ * \brief               This function finishes the CMAC operation, and writes
+ *                      the result to the output buffer.
  *
  *
- * \param ctx           CMAC context
- * \param output        Generic CMAC checksum result
+ *                      It is called after mbedtls_cipher_cmac_update().
+ *                      It can be followed by mbedtls_cipher_cmac_reset() and
+ *                      mbedtls_cipher_cmac_update(), or mbedtls_cipher_free().
  *
  *
- * \returns             0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                      verification fails.
+ * \param ctx           The cipher context used for the CMAC operation.
+ * \param output        The output buffer for the CMAC checksum result.
+ *
+ * \returns             \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA
+ *                      if parameter verification fails.
  */
  */
 int mbedtls_cipher_cmac_finish( mbedtls_cipher_context_t *ctx,
 int mbedtls_cipher_cmac_finish( mbedtls_cipher_context_t *ctx,
                                 unsigned char *output );
                                 unsigned char *output );
 
 
 /**
 /**
- * \brief               Prepare to authenticate a new message with the same key.
- *                      Called after mbedtls_cipher_cmac_finish() and before
- *                      mbedtls_cipher_cmac_update().
+ * \brief               This function prepares the authentication of another
+ *                      message with the same key as the previous CMAC
+ *                      operation.
+ *
+ *                      It is called after mbedtls_cipher_cmac_finish()
+ *                      and before mbedtls_cipher_cmac_update().
  *
  *
- * \param ctx           CMAC context to be reset
+ * \param ctx           The cipher context used for the CMAC operation.
  *
  *
- * \returns             0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                      verification fails.
+ * \returns             \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA
+ *                      if parameter verification fails.
  */
  */
 int mbedtls_cipher_cmac_reset( mbedtls_cipher_context_t *ctx );
 int mbedtls_cipher_cmac_reset( mbedtls_cipher_context_t *ctx );
 
 
 /**
 /**
- * \brief               Output = Generic_CMAC( cmac key, input buffer )
+ * \brief               This function calculates the full generic CMAC
+ *                      on the input buffer with the provided key.
+ *
+ *                      The function allocates the context, performs the
+ *                      calculation, and frees the context.
  *
  *
- * \param cipher_info   message digest info
- * \param key           CMAC key
- * \param keylen        length of the CMAC key in bits
- * \param input         buffer holding the  data
- * \param ilen          length of the input data
- * \param output        Generic CMAC-result
+ *                      The CMAC result is calculated as
+ *                      output = generic CMAC(cmac key, input buffer).
  *
  *
- * \returns             0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                      verification fails.
+ *
+ * \param cipher_info   The cipher information.
+ * \param key           The CMAC key.
+ * \param keylen        The length of the CMAC key in bits.
+ * \param input         The buffer holding the input data.
+ * \param ilen          The length of the input data.
+ * \param output        The buffer for the generic CMAC result.
+ *
+ * \returns             \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA
+ *                      if parameter verification fails.
  */
  */
 int mbedtls_cipher_cmac( const mbedtls_cipher_info_t *cipher_info,
 int mbedtls_cipher_cmac( const mbedtls_cipher_info_t *cipher_info,
                          const unsigned char *key, size_t keylen,
                          const unsigned char *key, size_t keylen,
@@ -138,27 +165,44 @@ int mbedtls_cipher_cmac( const mbedtls_cipher_info_t *cipher_info,
 
 
 #if defined(MBEDTLS_AES_C)
 #if defined(MBEDTLS_AES_C)
 /**
 /**
- * \brief           AES-CMAC-128-PRF
- *                  Implementation of (AES-CMAC-PRF-128), as defined in RFC 4615
- *
- * \param key       PRF key
- * \param key_len   PRF key length in bytes
- * \param input     buffer holding the input data
- * \param in_len    length of the input data in bytes
- * \param output    buffer holding the generated pseudorandom output (16 bytes)
- *
- * \return          0 if successful
+ * \brief           This function implements the AES-CMAC-PRF-128 pseudorandom
+ *                  function, as defined in
+ *                  <em>RFC-4615: The Advanced Encryption Standard-Cipher-based
+ *                  Message Authentication Code-Pseudo-Random Function-128
+ *                  (AES-CMAC-PRF-128) Algorithm for the Internet Key
+ *                  Exchange Protocol (IKE).</em>
+ *
+ * \param key       The key to use.
+ * \param key_len   The key length in Bytes.
+ * \param input     The buffer holding the input data.
+ * \param in_len    The length of the input data in Bytes.
+ * \param output    The buffer holding the generated 16 Bytes of
+ *                  pseudorandom output.
+ *
+ * \return          \c 0 on success.
  */
  */
 int mbedtls_aes_cmac_prf_128( const unsigned char *key, size_t key_len,
 int mbedtls_aes_cmac_prf_128( const unsigned char *key, size_t key_len,
                               const unsigned char *input, size_t in_len,
                               const unsigned char *input, size_t in_len,
                               unsigned char output[16] );
                               unsigned char output[16] );
 #endif /* MBEDTLS_AES_C */
 #endif /* MBEDTLS_AES_C */
 
 
+#ifdef __cplusplus
+}
+#endif
+
+#else  /* !MBEDTLS_CMAC_ALT */
+#include "cmac_alt.h"
+#endif /* !MBEDTLS_CMAC_ALT */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 #if defined(MBEDTLS_SELF_TEST) && ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_DES_C) )
 #if defined(MBEDTLS_SELF_TEST) && ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_DES_C) )
 /**
 /**
- * \brief          Checkup routine
+ * \brief          The CMAC checkup routine.
  *
  *
- * \return         0 if successful, or 1 if the test failed
+ * \return         \c 0 on success, or \c 1 on failure.
  */
  */
 int mbedtls_cmac_self_test( int verbose );
 int mbedtls_cmac_self_test( int verbose );
 #endif /* MBEDTLS_SELF_TEST && ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */
 #endif /* MBEDTLS_SELF_TEST && ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */

+ 8 - 1
mbedtls/include/mbedtls/compat-1.3.h

@@ -5,7 +5,8 @@
  *  for the PolarSSL naming conventions.
  *  for the PolarSSL naming conventions.
  *
  *
  * \deprecated Use the new names directly instead
  * \deprecated Use the new names directly instead
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -24,6 +25,12 @@
  *  This file is part of mbed TLS (https://tls.mbed.org)
  *  This file is part of mbed TLS (https://tls.mbed.org)
  */
  */
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #if ! defined(MBEDTLS_DEPRECATED_REMOVED)
 #if ! defined(MBEDTLS_DEPRECATED_REMOVED)
 
 
 #if defined(MBEDTLS_DEPRECATED_WARNING)
 #if defined(MBEDTLS_DEPRECATED_WARNING)

+ 216 - 26
mbedtls/include/mbedtls/config.h

@@ -1,13 +1,14 @@
 /**
 /**
- * \file config.h
+ * \file tls_config.h
  *
  *
  * \brief Configuration options (set of defines)
  * \brief Configuration options (set of defines)
  *
  *
  *  This set of compile-time options may be used to enable
  *  This set of compile-time options may be used to enable
  *  or disable features selectively, and reduce the global
  *  or disable features selectively, and reduce the global
  *  memory footprint.
  *  memory footprint.
- *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ */
+/*
+ *  Copyright (C) 2006-2019, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -28,6 +29,9 @@
 #ifndef MBEDTLS_CONFIG_H
 #ifndef MBEDTLS_CONFIG_H
 #define MBEDTLS_CONFIG_H
 #define MBEDTLS_CONFIG_H
 
 
+/* the memory allocation method configurations */
+#include <rtthread.h>
+
 #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
 #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
 #define _CRT_SECURE_NO_DEPRECATE 1
 #define _CRT_SECURE_NO_DEPRECATE 1
 #endif
 #endif
@@ -117,7 +121,7 @@
  *
  *
  * Comment if your system does not have a correct clock.
  * Comment if your system does not have a correct clock.
  */
  */
-#define MBEDTLS_HAVE_TIME_DATE
+// #define MBEDTLS_HAVE_TIME_DATE
 
 
 /**
 /**
  * \def MBEDTLS_PLATFORM_MEMORY
  * \def MBEDTLS_PLATFORM_MEMORY
@@ -241,7 +245,7 @@
  * You will need to provide a header "timing_alt.h" and an implementation at
  * You will need to provide a header "timing_alt.h" and an implementation at
  * compile time.
  * compile time.
  */
  */
-//#define MBEDTLS_TIMING_ALT
+#define MBEDTLS_TIMING_ALT
 
 
 /**
 /**
  * \def MBEDTLS_AES_ALT
  * \def MBEDTLS_AES_ALT
@@ -261,20 +265,49 @@
  *
  *
  * Uncomment a macro to enable alternate implementation of the corresponding
  * Uncomment a macro to enable alternate implementation of the corresponding
  * module.
  * module.
+ *
+ * \warning   MD2, MD4, MD5, ARC4, DES and SHA-1 are considered weak and their
+ *            use constitutes a security risk. If possible, we recommend
+ *            avoiding dependencies on them, and considering stronger message
+ *            digests and ciphers instead.
+ *
  */
  */
-//#define MBEDTLS_AES_ALT
-//#define MBEDTLS_ARC4_ALT
+#if defined(RT_HWCRYPTO_USING_AES)
+#define MBEDTLS_AES_ALT
+#endif
+#if defined(RT_HWCRYPTO_USING_RC4)
+#define MBEDTLS_ARC4_ALT
+#endif
+#if defined(RT_HWCRYPTO_USING_DES) || defined(RT_HWCRYPTO_USING_3DES)
+#define MBEDTLS_DES_ALT
+#endif
+#if defined(RT_HWCRYPTO_USING_GCM)
+#define MBEDTLS_GCM_ALT
+#endif
+#ifdef RT_HWCRYPTO_USING_MD5
+#define MBEDTLS_MD5_ALT
+#endif
+#if defined(RT_HWCRYPTO_USING_BIGNUM)
+#define MBEDTLS_RSA_ALT
+#endif
+#if defined(RT_HWCRYPTO_USING_SHA1)
+#define MBEDTLS_SHA1_ALT
+#endif
+#if defined(RT_HWCRYPTO_USING_SHA2_256) || defined(RT_HWCRYPTO_USING_SHA2_224)
+#define MBEDTLS_SHA256_ALT
+#endif
+#if defined(RT_HWCRYPTO_USING_SHA2_512) || defined(RT_HWCRYPTO_USING_SHA2_384)
+#define MBEDTLS_SHA512_ALT
+#endif
+//#define MBEDTLS_DHM_ALT
+//#define MBEDTLS_ECJPAKE_ALT
 //#define MBEDTLS_BLOWFISH_ALT
 //#define MBEDTLS_BLOWFISH_ALT
 //#define MBEDTLS_CAMELLIA_ALT
 //#define MBEDTLS_CAMELLIA_ALT
-//#define MBEDTLS_DES_ALT
-//#define MBEDTLS_XTEA_ALT
-//#define MBEDTLS_MD2_ALT
-//#define MBEDTLS_MD4_ALT
-//#define MBEDTLS_MD5_ALT
+//#define MBEDTLS_CCM_ALT
+//#define MBEDTLS_CMAC_ALT
 //#define MBEDTLS_RIPEMD160_ALT
 //#define MBEDTLS_RIPEMD160_ALT
-//#define MBEDTLS_SHA1_ALT
-//#define MBEDTLS_SHA256_ALT
-//#define MBEDTLS_SHA512_ALT
+//#define MBEDTLS_XTEA_ALT
+
 /*
 /*
  * When replacing the elliptic curve module, pleace consider, that it is
  * When replacing the elliptic curve module, pleace consider, that it is
  * implemented with two .c files:
  * implemented with two .c files:
@@ -314,6 +347,12 @@
  *
  *
  * Uncomment a macro to enable alternate implementation of the corresponding
  * Uncomment a macro to enable alternate implementation of the corresponding
  * function.
  * function.
+ *
+ * \warning   MD2, MD4, MD5, DES and SHA-1 are considered weak and their use
+ *            constitutes a security risk. If possible, we recommend avoiding
+ *            dependencies on them, and considering stronger message digests
+ *            and ciphers instead.
+ *
  */
  */
 //#define MBEDTLS_MD2_PROCESS_ALT
 //#define MBEDTLS_MD2_PROCESS_ALT
 //#define MBEDTLS_MD4_PROCESS_ALT
 //#define MBEDTLS_MD4_PROCESS_ALT
@@ -329,6 +368,11 @@
 //#define MBEDTLS_AES_SETKEY_DEC_ALT
 //#define MBEDTLS_AES_SETKEY_DEC_ALT
 //#define MBEDTLS_AES_ENCRYPT_ALT
 //#define MBEDTLS_AES_ENCRYPT_ALT
 //#define MBEDTLS_AES_DECRYPT_ALT
 //#define MBEDTLS_AES_DECRYPT_ALT
+//#define MBEDTLS_ECDH_GEN_PUBLIC_ALT
+//#define MBEDTLS_ECDH_COMPUTE_SHARED_ALT
+//#define MBEDTLS_ECDSA_VERIFY_ALT
+//#define MBEDTLS_ECDSA_SIGN_ALT
+//#define MBEDTLS_ECDSA_GENKEY_ALT
 
 
 /**
 /**
  * \def MBEDTLS_ECP_INTERNAL_ALT
  * \def MBEDTLS_ECP_INTERNAL_ALT
@@ -411,7 +455,7 @@
  *
  *
  * Uncomment to use your own hardware entropy collector.
  * Uncomment to use your own hardware entropy collector.
  */
  */
-//#define MBEDTLS_ENTROPY_HARDWARE_ALT
+#define MBEDTLS_ENTROPY_HARDWARE_ALT
 
 
 /**
 /**
  * \def MBEDTLS_AES_ROM_TABLES
  * \def MBEDTLS_AES_ROM_TABLES
@@ -513,6 +557,9 @@
  *      MBEDTLS_TLS_DHE_RSA_WITH_DES_CBC_SHA
  *      MBEDTLS_TLS_DHE_RSA_WITH_DES_CBC_SHA
  *
  *
  * Uncomment this macro to enable weak ciphersuites
  * Uncomment this macro to enable weak ciphersuites
+ *
+ * \warning   DES is considered a weak cipher and its use constitutes a
+ *            security risk. We recommend considering stronger ciphers instead.
  */
  */
 //#define MBEDTLS_ENABLE_WEAK_CIPHERSUITES
 //#define MBEDTLS_ENABLE_WEAK_CIPHERSUITES
 
 
@@ -529,6 +576,26 @@
  */
  */
 #define MBEDTLS_REMOVE_ARC4_CIPHERSUITES
 #define MBEDTLS_REMOVE_ARC4_CIPHERSUITES
 
 
+/**
+ * \def MBEDTLS_REMOVE_3DES_CIPHERSUITES
+ *
+ * Remove 3DES ciphersuites by default in SSL / TLS.
+ * This flag removes the ciphersuites based on 3DES from the default list as
+ * returned by mbedtls_ssl_list_ciphersuites(). However, it is still possible
+ * to enable (some of) them with mbedtls_ssl_conf_ciphersuites() by including
+ * them explicitly.
+ *
+ * A man-in-the-browser attacker can recover authentication tokens sent through
+ * a TLS connection using a 3DES based cipher suite (see "On the Practical
+ * (In-)Security of 64-bit Block Ciphers" by Karthikeyan Bhargavan and Gaëtan
+ * Leurent, see https://sweet32.info/SWEET32_CCS16.pdf). If this attack falls
+ * in your threat model or you are unsure, then you should keep this option
+ * enabled to remove 3DES based cipher suites.
+ *
+ * Comment this macro to keep 3DES in the default ciphersuite list.
+ */
+#define MBEDTLS_REMOVE_3DES_CIPHERSUITES
+
 /**
 /**
  * \def MBEDTLS_ECP_DP_SECP192R1_ENABLED
  * \def MBEDTLS_ECP_DP_SECP192R1_ENABLED
  *
  *
@@ -618,6 +685,13 @@
  *      MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256
  *      MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256
  *      MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA
  *      MBEDTLS_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA
  *      MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA
  *      MBEDTLS_TLS_DHE_PSK_WITH_RC4_128_SHA
+ *
+ * \warning    Using DHE constitutes a security risk as it
+ *             is not possible to validate custom DH parameters.
+ *             If possible, it is recommended users should consider
+ *             preferring other methods of key exchange.
+ *             See dhm.h for more details.
+ *
  */
  */
 #define MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED
 #define MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED
 
 
@@ -717,6 +791,13 @@
  *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
  *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
  *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
  *      MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
  *      MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
  *      MBEDTLS_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
+ *
+ * \warning    Using DHE constitutes a security risk as it
+ *             is not possible to validate custom DH parameters.
+ *             If possible, it is recommended users should consider
+ *             preferring other methods of key exchange.
+ *             See dhm.h for more details.
+ *
  */
  */
 #define MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
 #define MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
 
 
@@ -903,7 +984,7 @@
  *
  *
  * Uncomment this macro to disable the built-in platform entropy functions.
  * Uncomment this macro to disable the built-in platform entropy functions.
  */
  */
-//#define MBEDTLS_NO_PLATFORM_ENTROPY
+#define MBEDTLS_NO_PLATFORM_ENTROPY
 
 
 /**
 /**
  * \def MBEDTLS_ENTROPY_FORCE_SHA256
  * \def MBEDTLS_ENTROPY_FORCE_SHA256
@@ -1008,7 +1089,8 @@
 /**
 /**
  * \def MBEDTLS_RSA_NO_CRT
  * \def MBEDTLS_RSA_NO_CRT
  *
  *
- * Do not use the Chinese Remainder Theorem for the RSA private operation.
+ * Do not use the Chinese Remainder Theorem
+ * for the RSA private operation.
  *
  *
  * Uncomment this macro to disable the use of CRT in RSA.
  * Uncomment this macro to disable the use of CRT in RSA.
  *
  *
@@ -1146,7 +1228,7 @@
 /**
 /**
  * \def MBEDTLS_SSL_RENEGOTIATION
  * \def MBEDTLS_SSL_RENEGOTIATION
  *
  *
- * Disable support for TLS renegotiation.
+ * Enable support for TLS renegotiation.
  *
  *
  * The two main uses of renegotiation are (1) refresh keys on long-lived
  * The two main uses of renegotiation are (1) refresh keys on long-lived
  * connections and (2) client authentication after the initial handshake.
  * connections and (2) client authentication after the initial handshake.
@@ -1155,6 +1237,13 @@
  * misuse/misunderstand.
  * misuse/misunderstand.
  *
  *
  * Comment this to disable support for renegotiation.
  * Comment this to disable support for renegotiation.
+ *
+ * \note   Even if this option is disabled, both client and server are aware
+ *         of the Renegotiation Indication Extension (RFC 5746) used to
+ *         prevent the SSL renegotiation attack (see RFC 5746 Sect. 1).
+ *         (See \c mbedtls_ssl_conf_legacy_renegotiation for the
+ *          configuration of this extension).
+ *
  */
  */
 #define MBEDTLS_SSL_RENEGOTIATION
 #define MBEDTLS_SSL_RENEGOTIATION
 
 
@@ -1363,6 +1452,30 @@
  */
  */
 #define MBEDTLS_SSL_TRUNCATED_HMAC
 #define MBEDTLS_SSL_TRUNCATED_HMAC
 
 
+/**
+ * \def MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT
+ *
+ * Fallback to old (pre-2.7), non-conforming implementation of the truncated
+ * HMAC extension which also truncates the HMAC key. Note that this option is
+ * only meant for a transitory upgrade period and is likely to be removed in
+ * a future version of the library.
+ *
+ * \warning The old implementation is non-compliant and has a security weakness
+ *          (2^80 brute force attack on the HMAC key used for a single,
+ *          uninterrupted connection). This should only be enabled temporarily
+ *          when (1) the use of truncated HMAC is essential in order to save
+ *          bandwidth, and (2) the peer is an Mbed TLS stack that doesn't use
+ *          the fixed implementation yet (pre-2.7).
+ *
+ * \deprecated This option is deprecated and will likely be removed in a
+ *             future version of Mbed TLS.
+ *
+ * Uncomment to fallback to old, non-compliant truncated HMAC implementation.
+ *
+ * Requires: MBEDTLS_SSL_TRUNCATED_HMAC
+ */
+//#define MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT
+
 /**
 /**
  * \def MBEDTLS_THREADING_ALT
  * \def MBEDTLS_THREADING_ALT
  *
  *
@@ -1596,6 +1709,11 @@
  *      MBEDTLS_TLS_RSA_WITH_RC4_128_MD5
  *      MBEDTLS_TLS_RSA_WITH_RC4_128_MD5
  *      MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA
  *      MBEDTLS_TLS_RSA_PSK_WITH_RC4_128_SHA
  *      MBEDTLS_TLS_PSK_WITH_RC4_128_SHA
  *      MBEDTLS_TLS_PSK_WITH_RC4_128_SHA
+ *
+ * \warning   ARC4 is considered a weak cipher and its use constitutes a
+ *            security risk. If possible, we recommend avoidng dependencies on
+ *            it, and considering stronger ciphers instead.
+ *
  */
  */
 #define MBEDTLS_ARC4_C
 #define MBEDTLS_ARC4_C
 
 
@@ -1649,6 +1767,7 @@
  *          library/ecp.c
  *          library/ecp.c
  *          library/ecdsa.c
  *          library/ecdsa.c
  *          library/rsa.c
  *          library/rsa.c
+ *          library/rsa_internal.c
  *          library/ssl_tls.c
  *          library/ssl_tls.c
  *
  *
  * This module is required for RSA, DHM and ECC (ECDH, ECDSA) support.
  * This module is required for RSA, DHM and ECC (ECDH, ECDSA) support.
@@ -1796,7 +1915,10 @@
  *
  *
  * This module provides debugging functions.
  * This module provides debugging functions.
  */
  */
+ 
+#ifdef PKG_USING_MBEDTLS_DEBUG
 #define MBEDTLS_DEBUG_C
 #define MBEDTLS_DEBUG_C
+#endif
 
 
 /**
 /**
  * \def MBEDTLS_DES_C
  * \def MBEDTLS_DES_C
@@ -1821,6 +1943,9 @@
  *      MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA
  *      MBEDTLS_TLS_PSK_WITH_3DES_EDE_CBC_SHA
  *
  *
  * PEM_PARSE uses DES/3DES for decrypting encrypted keys.
  * PEM_PARSE uses DES/3DES for decrypting encrypted keys.
+ *
+ * \warning   DES is considered a weak cipher and its use constitutes a
+ *            security risk. We recommend considering stronger ciphers instead.
  */
  */
 #define MBEDTLS_DES_C
 #define MBEDTLS_DES_C
 
 
@@ -1835,6 +1960,13 @@
  *
  *
  * This module is used by the following key exchanges:
  * This module is used by the following key exchanges:
  *      DHE-RSA, DHE-PSK
  *      DHE-RSA, DHE-PSK
+ *
+ * \warning    Using DHE constitutes a security risk as it
+ *             is not possible to validate custom DH parameters.
+ *             If possible, it is recommended users should consider
+ *             preferring other methods of key exchange.
+ *             See dhm.h for more details.
+ *
  */
  */
 #define MBEDTLS_DHM_C
 #define MBEDTLS_DHM_C
 
 
@@ -2000,6 +2132,11 @@
  * Caller:
  * Caller:
  *
  *
  * Uncomment to enable support for (rare) MD2-signed X.509 certs.
  * Uncomment to enable support for (rare) MD2-signed X.509 certs.
+ *
+ * \warning   MD2 is considered a weak message digest and its use constitutes a
+ *            security risk. If possible, we recommend avoiding dependencies on
+ *            it, and considering stronger message digests instead.
+ *
  */
  */
 //#define MBEDTLS_MD2_C
 //#define MBEDTLS_MD2_C
 
 
@@ -2012,6 +2149,11 @@
  * Caller:
  * Caller:
  *
  *
  * Uncomment to enable support for (rare) MD4-signed X.509 certs.
  * Uncomment to enable support for (rare) MD4-signed X.509 certs.
+ *
+ * \warning   MD4 is considered a weak message digest and its use constitutes a
+ *            security risk. If possible, we recommend avoiding dependencies on
+ *            it, and considering stronger message digests instead.
+ *
  */
  */
 //#define MBEDTLS_MD4_C
 //#define MBEDTLS_MD4_C
 
 
@@ -2025,8 +2167,15 @@
  *          library/pem.c
  *          library/pem.c
  *          library/ssl_tls.c
  *          library/ssl_tls.c
  *
  *
- * This module is required for SSL/TLS and X.509.
- * PEM_PARSE uses MD5 for decrypting encrypted keys.
+ * This module is required for SSL/TLS up to version 1.1, and for TLS 1.2
+ * depending on the handshake parameters. Further, it is used for checking
+ * MD5-signed certificates, and for PBKDF1 when decrypting PEM-encoded
+ * encrypted keys.
+ *
+ * \warning   MD5 is considered a weak message digest and its use constitutes a
+ *            security risk. If possible, we recommend avoiding dependencies on
+ *            it, and considering stronger message digests instead.
+ *
  */
  */
 #define MBEDTLS_MD5_C
 #define MBEDTLS_MD5_C
 
 
@@ -2063,7 +2212,7 @@
  *
  *
  * This module provides networking routines.
  * This module provides networking routines.
  */
  */
-#define MBEDTLS_NET_C
+//#define MBEDTLS_NET_C
 
 
 /**
 /**
  * \def MBEDTLS_OID_C
  * \def MBEDTLS_OID_C
@@ -2262,6 +2411,7 @@
  * Enable the RSA public-key cryptosystem.
  * Enable the RSA public-key cryptosystem.
  *
  *
  * Module:  library/rsa.c
  * Module:  library/rsa.c
+ *          library/rsa_internal.c
  * Caller:  library/ssl_cli.c
  * Caller:  library/ssl_cli.c
  *          library/ssl_srv.c
  *          library/ssl_srv.c
  *          library/ssl_tls.c
  *          library/ssl_tls.c
@@ -2288,6 +2438,11 @@
  *
  *
  * This module is required for SSL/TLS up to version 1.1, for TLS 1.2
  * This module is required for SSL/TLS up to version 1.1, for TLS 1.2
  * depending on the handshake parameters, and for SHA1-signed certificates.
  * depending on the handshake parameters, and for SHA1-signed certificates.
+ *
+ * \warning   SHA-1 is considered a weak message digest and its use constitutes
+ *            a security risk. If possible, we recommend avoiding dependencies
+ *            on it, and considering stronger message digests instead.
+ *
  */
  */
 #define MBEDTLS_SHA1_C
 #define MBEDTLS_SHA1_C
 
 
@@ -2586,7 +2741,7 @@
 
 
 /* MPI / BIGNUM options */
 /* MPI / BIGNUM options */
 //#define MBEDTLS_MPI_WINDOW_SIZE            6 /**< Maximum windows size used. */
 //#define MBEDTLS_MPI_WINDOW_SIZE            6 /**< Maximum windows size used. */
-//#define MBEDTLS_MPI_MAX_SIZE            1024 /**< Maximum number of bytes for usable MPIs. */
+//#define MBEDTLS_MPI_MAX_SIZE               256 /**< Maximum number of bytes for usable MPIs. */
 
 
 /* CTR_DRBG options */
 /* CTR_DRBG options */
 //#define MBEDTLS_CTR_DRBG_ENTROPY_LEN               48 /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with SHA-256) */
 //#define MBEDTLS_CTR_DRBG_ENTROPY_LEN               48 /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with SHA-256) */
@@ -2666,7 +2821,7 @@
  *
  *
  * The value below is only an example, not the default.
  * The value below is only an example, not the default.
  */
  */
-//#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
+#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256
 
 
 /* X509 options */
 /* X509 options */
 //#define MBEDTLS_X509_MAX_INTERMEDIATE_CA   8   /**< Maximum number of intermediate CAs in a verification chain. */
 //#define MBEDTLS_X509_MAX_INTERMEDIATE_CA   8   /**< Maximum number of intermediate CAs in a verification chain. */
@@ -2676,8 +2831,13 @@
  * Allow SHA-1 in the default TLS configuration for certificate signing.
  * Allow SHA-1 in the default TLS configuration for certificate signing.
  * Without this build-time option, SHA-1 support must be activated explicitly
  * Without this build-time option, SHA-1 support must be activated explicitly
  * through mbedtls_ssl_conf_cert_profile. Turning on this option is not
  * through mbedtls_ssl_conf_cert_profile. Turning on this option is not
- * recommended because of it is possible to generte SHA-1 collisions, however
+ * recommended because of it is possible to generate SHA-1 collisions, however
  * this may be safe for legacy infrastructure where additional controls apply.
  * this may be safe for legacy infrastructure where additional controls apply.
+ *
+ * \warning   SHA-1 is considered a weak message digest and its use constitutes
+ *            a security risk. If possible, we recommend avoiding dependencies
+ *            on it, and considering stronger message digests instead.
+ *
  */
  */
 // #define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES
 // #define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES
 
 
@@ -2688,7 +2848,13 @@
  * The use of SHA-1 in TLS <= 1.1 and in HMAC-SHA-1 is always allowed by
  * The use of SHA-1 in TLS <= 1.1 and in HMAC-SHA-1 is always allowed by
  * default. At the time of writing, there is no practical attack on the use
  * default. At the time of writing, there is no practical attack on the use
  * of SHA-1 in handshake signatures, hence this option is turned on by default
  * of SHA-1 in handshake signatures, hence this option is turned on by default
- * for compatibility with existing peers.
+ * to preserve compatibility with existing peers, but the general
+ * warning applies nonetheless:
+ *
+ * \warning   SHA-1 is considered a weak message digest and its use constitutes
+ *            a security risk. If possible, we recommend avoiding dependencies
+ *            on it, and considering stronger message digests instead.
+ *
  */
  */
 #define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE
 #define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE
 
 
@@ -2714,6 +2880,30 @@
 #include MBEDTLS_USER_CONFIG_FILE
 #include MBEDTLS_USER_CONFIG_FILE
 #endif
 #endif
 
 
+/*
+ * !!!!! The following two macros are added to the porting code !!!!!
+ * !!!!! The following two macros are added to the porting code !!!!!
+ * !!!!! The following two macros are added to the porting code !!!!!
+ * 
+ * Upgraded version handles the following two macro definitions
+ * 
+ * These two macros are defined in the ctr_drbg.c file
+ *
+ * #if !defined(MBEDTLS_CTR_DRBG_BLOCKSIZE)
+ * #define MBEDTLS_CTR_DRBG_BLOCKSIZE          16
+ * #endif
+ * #if !defined(MBEDTLS_CTR_DRBG_KEYSIZE)
+ * #define MBEDTLS_CTR_DRBG_KEYSIZE            32
+ * #endif 
+ * 
+*/
+
 #include "check_config.h"
 #include "check_config.h"
 
 
+#define tls_malloc  rt_malloc
+#define tls_free    rt_free
+#define tls_realloc rt_realloc
+#define tls_calloc  rt_calloc
+#define tls_strdup  rt_strdup
+
 #endif /* MBEDTLS_CONFIG_H */
 #endif /* MBEDTLS_CONFIG_H */

+ 180 - 115
mbedtls/include/mbedtls/ctr_drbg.h

@@ -1,9 +1,13 @@
 /**
 /**
  * \file ctr_drbg.h
  * \file ctr_drbg.h
  *
  *
- * \brief CTR_DRBG based on AES-256 (NIST SP 800-90)
+ * \brief    CTR_DRBG is based on AES-256, as defined 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-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,90 +22,118 @@
  *  See the License for the specific language governing permissions and
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *  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_CTR_DRBG_H
 #ifndef MBEDTLS_CTR_DRBG_H
 #define MBEDTLS_CTR_DRBG_H
 #define MBEDTLS_CTR_DRBG_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include "aes.h"
 #include "aes.h"
 
 
 #if defined(MBEDTLS_THREADING_C)
 #if defined(MBEDTLS_THREADING_C)
-#include "mbedtls/threading.h"
+#include "threading.h"
 #endif
 #endif
 
 
 #define MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED        -0x0034  /**< The entropy source failed. */
 #define MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED        -0x0034  /**< The entropy source failed. */
-#define MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG              -0x0036  /**< Too many random requested in single call. */
-#define MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG                -0x0038  /**< Input too large (Entropy + additional). */
-#define MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR                -0x003A  /**< Read/write error in file. */
+#define MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG              -0x0036  /**< The requested random buffer length is too big. */
+#define MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG                -0x0038  /**< The input (entropy + additional data) is too large. */
+#define MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR                -0x003A  /**< Read or write error in file. */
 
 
-#define MBEDTLS_CTR_DRBG_BLOCKSIZE          16      /**< Block size used by the cipher                  */
-#define MBEDTLS_CTR_DRBG_KEYSIZE            32      /**< Key size used by the cipher                    */
-#define MBEDTLS_CTR_DRBG_KEYBITS            ( MBEDTLS_CTR_DRBG_KEYSIZE * 8 )
-#define MBEDTLS_CTR_DRBG_SEEDLEN            ( MBEDTLS_CTR_DRBG_KEYSIZE + MBEDTLS_CTR_DRBG_BLOCKSIZE )
-                                            /**< The seed length (counter + AES key)            */
+#if !defined(MBEDTLS_CTR_DRBG_BLOCKSIZE)
+#define MBEDTLS_CTR_DRBG_BLOCKSIZE          16 /**< The block size used by the cipher. */
+#endif
+#if !defined(MBEDTLS_CTR_DRBG_KEYSIZE)
+#define MBEDTLS_CTR_DRBG_KEYSIZE            32 /**< The key size used by the cipher. */
+#endif
+#define MBEDTLS_CTR_DRBG_KEYBITS            ( MBEDTLS_CTR_DRBG_KEYSIZE * 8 ) /**< The key size for the DRBG operation, in bits. */
+#define MBEDTLS_CTR_DRBG_SEEDLEN            ( MBEDTLS_CTR_DRBG_KEYSIZE + MBEDTLS_CTR_DRBG_BLOCKSIZE ) /**< The seed length, calculated as (counter + AES key). */
 
 
 /**
 /**
  * \name SECTION: Module settings
  * \name SECTION: Module settings
  *
  *
  * The configuration options you can set for this module are in this section.
  * The configuration options you can set for this module are in this section.
- * Either change them in config.h or define them on the compiler command line.
+ * Either change them in config.h or define them using the compiler command
+ * line.
  * \{
  * \{
  */
  */
 
 
 #if !defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN)
 #if !defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN)
 #if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256)
 #if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256)
-#define MBEDTLS_CTR_DRBG_ENTROPY_LEN        48      /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with SHA-256) */
+#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
 #else
-#define MBEDTLS_CTR_DRBG_ENTROPY_LEN        32      /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with SHA-256) */
+#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
 #endif
 
 
 #if !defined(MBEDTLS_CTR_DRBG_RESEED_INTERVAL)
 #if !defined(MBEDTLS_CTR_DRBG_RESEED_INTERVAL)
-#define MBEDTLS_CTR_DRBG_RESEED_INTERVAL    10000   /**< Interval before reseed is performed by default */
+#define MBEDTLS_CTR_DRBG_RESEED_INTERVAL    10000
+/**< The interval before reseed is performed by default. */
 #endif
 #endif
 
 
 #if !defined(MBEDTLS_CTR_DRBG_MAX_INPUT)
 #if !defined(MBEDTLS_CTR_DRBG_MAX_INPUT)
-#define MBEDTLS_CTR_DRBG_MAX_INPUT          256     /**< Maximum number of additional input bytes */
+#define MBEDTLS_CTR_DRBG_MAX_INPUT          256
+/**< The maximum number of additional input Bytes. */
 #endif
 #endif
 
 
 #if !defined(MBEDTLS_CTR_DRBG_MAX_REQUEST)
 #if !defined(MBEDTLS_CTR_DRBG_MAX_REQUEST)
-#define MBEDTLS_CTR_DRBG_MAX_REQUEST        1024    /**< Maximum number of requested bytes per call */
+#define MBEDTLS_CTR_DRBG_MAX_REQUEST        1024
+/**< The maximum number of requested Bytes per call. */
 #endif
 #endif
 
 
 #if !defined(MBEDTLS_CTR_DRBG_MAX_SEED_INPUT)
 #if !defined(MBEDTLS_CTR_DRBG_MAX_SEED_INPUT)
-#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT     384     /**< Maximum size of (re)seed buffer */
+#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT     384
+/**< The maximum size of seed or reseed buffer. */
 #endif
 #endif
 
 
 /* \} name SECTION: Module settings */
 /* \} name SECTION: Module settings */
 
 
-#define MBEDTLS_CTR_DRBG_PR_OFF             0       /**< No prediction resistance       */
-#define MBEDTLS_CTR_DRBG_PR_ON              1       /**< Prediction resistance enabled  */
+#define MBEDTLS_CTR_DRBG_PR_OFF             0
+/**< Prediction resistance is disabled. */
+#define MBEDTLS_CTR_DRBG_PR_ON              1
+/**< Prediction resistance is enabled. */
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
 extern "C" {
 extern "C" {
 #endif
 #endif
 
 
 /**
 /**
- * \brief          CTR_DRBG context structure
+ * \brief          The CTR_DRBG context structure.
  */
  */
 typedef struct
 typedef struct
 {
 {
-    unsigned char counter[16];  /*!<  counter (V)       */
-    int reseed_counter;         /*!<  reseed counter    */
-    int prediction_resistance;  /*!<  enable prediction resistance (Automatic
-                                      reseed before every random generation)  */
-    size_t entropy_len;         /*!<  amount of entropy grabbed on each
-                                      (re)seed          */
-    int reseed_interval;        /*!<  reseed interval   */
-
-    mbedtls_aes_context aes_ctx;        /*!<  AES context       */
+    unsigned char counter[16];  /*!< The counter (V). */
+    int reseed_counter;         /*!< The reseed counter. */
+    int prediction_resistance;  /*!< This determines whether prediction
+                                     resistance is enabled, that is
+                                     whether to systematically reseed before
+                                     each random generation. */
+    size_t entropy_len;         /*!< The amount of entropy grabbed on each
+                                     seed or reseed operation. */
+    int reseed_interval;        /*!< The reseed interval. */
+
+    mbedtls_aes_context aes_ctx;        /*!< The AES context. */
 
 
     /*
     /*
      * Callbacks (Entropy)
      * Callbacks (Entropy)
      */
      */
     int (*f_entropy)(void *, unsigned char *, size_t);
     int (*f_entropy)(void *, unsigned char *, size_t);
+                                /*!< The entropy callback function. */
 
 
-    void *p_entropy;            /*!<  context for the entropy function */
+    void *p_entropy;            /*!< The context for the entropy function. */
 
 
 #if defined(MBEDTLS_THREADING_C)
 #if defined(MBEDTLS_THREADING_C)
     mbedtls_threading_mutex_t mutex;
     mbedtls_threading_mutex_t mutex;
@@ -110,31 +142,32 @@ typedef struct
 mbedtls_ctr_drbg_context;
 mbedtls_ctr_drbg_context;
 
 
 /**
 /**
- * \brief               CTR_DRBG context initialization
- *                      Makes the context ready for mbedtls_ctr_drbg_seed() or
- *                      mbedtls_ctr_drbg_free().
+ * \brief               This function initializes the CTR_DRBG context,
+ *                      and prepares it for mbedtls_ctr_drbg_seed()
+ *                      or mbedtls_ctr_drbg_free().
  *
  *
- * \param ctx           CTR_DRBG context to be initialized
+ * \param ctx           The CTR_DRBG context to initialize.
  */
  */
 void mbedtls_ctr_drbg_init( mbedtls_ctr_drbg_context *ctx );
 void mbedtls_ctr_drbg_init( mbedtls_ctr_drbg_context *ctx );
 
 
 /**
 /**
- * \brief               CTR_DRBG initial seeding
- *                      Seed and setup 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.
- *
- * \param ctx           CTR_DRBG context to be seeded
- * \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
- *
- * \return              0 if successful, or
- *                      MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED
+ * \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.
+ *
+ * \param ctx           The CTR_DRBG context to seed.
+ * \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.
+ *
+ * \return              \c 0 on success, or
+ *                      #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure.
  */
  */
 int mbedtls_ctr_drbg_seed( mbedtls_ctr_drbg_context *ctx,
 int mbedtls_ctr_drbg_seed( mbedtls_ctr_drbg_context *ctx,
                    int (*f_entropy)(void *, unsigned char *, size_t),
                    int (*f_entropy)(void *, unsigned char *, size_t),
@@ -143,138 +176,170 @@ int mbedtls_ctr_drbg_seed( mbedtls_ctr_drbg_context *ctx,
                    size_t len );
                    size_t len );
 
 
 /**
 /**
- * \brief               Clear CTR_CRBG context data
+ * \brief               This function clears CTR_CRBG context data.
  *
  *
- * \param ctx           CTR_DRBG context to clear
+ * \param ctx           The CTR_DRBG context to clear.
  */
  */
 void mbedtls_ctr_drbg_free( mbedtls_ctr_drbg_context *ctx );
 void mbedtls_ctr_drbg_free( mbedtls_ctr_drbg_context *ctx );
 
 
 /**
 /**
- * \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_ctr_drbg_random_with_add().
+ *                      Only use this if your entropy source has sufficient
+ *                      throughput.
  *
  *
- * \param ctx           CTR_DRBG context
- * \param resistance    MBEDTLS_CTR_DRBG_PR_ON or MBEDTLS_CTR_DRBG_PR_OFF
+ * \param ctx           The CTR_DRBG context.
+ * \param resistance    #MBEDTLS_CTR_DRBG_PR_ON or #MBEDTLS_CTR_DRBG_PR_OFF.
  */
  */
 void mbedtls_ctr_drbg_set_prediction_resistance( mbedtls_ctr_drbg_context *ctx,
 void mbedtls_ctr_drbg_set_prediction_resistance( mbedtls_ctr_drbg_context *ctx,
                                          int resistance );
                                          int resistance );
 
 
 /**
 /**
- * \brief               Set the amount of entropy grabbed on each (re)seed
- *                      (Default: MBEDTLS_CTR_DRBG_ENTROPY_LEN)
+ * \brief               This function sets the amount of entropy grabbed on each
+ *                      seed or reseed. The default value is
+ *                      #MBEDTLS_CTR_DRBG_ENTROPY_LEN.
  *
  *
- * \param ctx           CTR_DRBG context
- * \param len           Amount of entropy to grab
+ * \param ctx           The CTR_DRBG context.
+ * \param len           The amount of entropy to grab.
  */
  */
 void mbedtls_ctr_drbg_set_entropy_len( mbedtls_ctr_drbg_context *ctx,
 void mbedtls_ctr_drbg_set_entropy_len( mbedtls_ctr_drbg_context *ctx,
                                size_t len );
                                size_t len );
 
 
 /**
 /**
- * \brief               Set the reseed interval
- *                      (Default: MBEDTLS_CTR_DRBG_RESEED_INTERVAL)
+ * \brief               This function sets the reseed interval.
+ *                      The default value is #MBEDTLS_CTR_DRBG_RESEED_INTERVAL.
  *
  *
- * \param ctx           CTR_DRBG context
- * \param interval      Reseed interval
+ * \param ctx           The CTR_DRBG context.
+ * \param interval      The reseed interval.
  */
  */
 void mbedtls_ctr_drbg_set_reseed_interval( mbedtls_ctr_drbg_context *ctx,
 void mbedtls_ctr_drbg_set_reseed_interval( mbedtls_ctr_drbg_context *ctx,
                                    int interval );
                                    int interval );
 
 
 /**
 /**
- * \brief               CTR_DRBG reseeding (extracts data from entropy source)
+ * \brief               This function reseeds the CTR_DRBG context, that is
+ *                      extracts data from the entropy source.
  *
  *
- * \param ctx           CTR_DRBG context
- * \param additional    Additional data to add to state (Can be NULL)
- * \param len           Length of additional data
+ * \param ctx           The CTR_DRBG context.
+ * \param additional    Additional data to add to the state. Can be NULL.
+ * \param len           The length of the additional data.
  *
  *
- * \return              0 if successful, or
- *                      MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED
+ * \return   \c 0 on success, or
+ *           #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure.
  */
  */
 int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx,
 int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx,
                      const unsigned char *additional, size_t len );
                      const unsigned char *additional, size_t len );
 
 
 /**
 /**
- * \brief               CTR_DRBG update state
+ * \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 add_len       Length of \p additional in bytes. This must be at
+ *                      most #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT.
+ *
+ * \return              \c 0 on success.
+ * \return              #MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG if
+ *                      \p add_len is more than
+ *                      #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT.
+ * \return              An error from the underlying AES cipher on failure.
+ */
+int mbedtls_ctr_drbg_update_ret( mbedtls_ctr_drbg_context *ctx,
+                                 const unsigned char *additional,
+                                 size_t add_len );
+
+/**
+ * \brief               This function updates the state of the CTR_DRBG context.
+ *
+ * \warning             This function cannot report errors. You should use
+ *                      mbedtls_ctr_drbg_update_ret() instead.
  *
  *
- * \param ctx           CTR_DRBG context
- * \param additional    Additional data to update state with
- * \param add_len       Length of additional data
+ * \note                If \p add_len is greater than
+ *                      #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT, only the first
+ *                      #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT Bytes are used.
+ *                      The remaining Bytes are silently discarded.
  *
  *
- * \note                If add_len is greater than MBEDTLS_CTR_DRBG_MAX_SEED_INPUT,
- *                      only the first MBEDTLS_CTR_DRBG_MAX_SEED_INPUT bytes are used,
- *                      the remaining ones are silently discarded.
+ * \param ctx           The CTR_DRBG context.
+ * \param additional    The data to update the state with.
+ * \param add_len       Length of \p additional data.
  */
  */
 void mbedtls_ctr_drbg_update( mbedtls_ctr_drbg_context *ctx,
 void mbedtls_ctr_drbg_update( mbedtls_ctr_drbg_context *ctx,
-                      const unsigned char *additional, size_t add_len );
+                              const unsigned char *additional,
+                              size_t add_len );
 
 
 /**
 /**
- * \brief               CTR_DRBG generate random with additional update input
+ * \brief   This function updates a CTR_DRBG instance with additional
+ *          data and uses it to generate random data.
  *
  *
- * Note: Automatically reseeds if reseed_counter is reached.
+ * \note    The function automatically reseeds if the reseed counter is exceeded.
  *
  *
- * \param p_rng         CTR_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
+ * \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.
  *
  *
- * \return              0 if successful, or
- *                      MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED, or
- *                      MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG
+ * \return    \c 0 on success, or
+ *            #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or
+ *            #MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG on failure.
  */
  */
 int mbedtls_ctr_drbg_random_with_add( void *p_rng,
 int mbedtls_ctr_drbg_random_with_add( void *p_rng,
                               unsigned char *output, size_t output_len,
                               unsigned char *output, size_t output_len,
                               const unsigned char *additional, size_t add_len );
                               const unsigned char *additional, size_t add_len );
 
 
 /**
 /**
- * \brief               CTR_DRBG generate random
+ * \brief   This function uses CTR_DRBG to generate random data.
  *
  *
- * Note: Automatically reseeds if reseed_counter is reached.
+ * \note    The function automatically reseeds if the reseed counter is exceeded.
  *
  *
- * \param p_rng         CTR_DRBG context
- * \param output        Buffer to fill
- * \param output_len    Length of the buffer
+ * \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.
  *
  *
- * \return              0 if successful, or
- *                      MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED, or
- *                      MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG
+ * \return              \c 0 on success, or
+ *                      #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or
+ *                      #MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG on failure.
  */
  */
 int mbedtls_ctr_drbg_random( void *p_rng,
 int mbedtls_ctr_drbg_random( void *p_rng,
                      unsigned char *output, size_t output_len );
                      unsigned char *output, size_t output_len );
 
 
 #if defined(MBEDTLS_FS_IO)
 #if defined(MBEDTLS_FS_IO)
 /**
 /**
- * \brief               Write a seed file
+ * \brief               This function writes a seed file.
  *
  *
- * \param ctx           CTR_DRBG context
- * \param path          Name of the file
+ * \param ctx           The CTR_DRBG context.
+ * \param path          The name of the file.
  *
  *
- * \return              0 if successful,
- *                      MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error, or
- *                      MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED
+ * \return              \c 0 on success,
+ *                      #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error, or
+ *                      #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on
+ *                      failure.
  */
  */
 int mbedtls_ctr_drbg_write_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path );
 int mbedtls_ctr_drbg_write_seed_file( mbedtls_ctr_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           CTR_DRBG context
- * \param path          Name of the file
+ * \param ctx           The CTR_DRBG context.
+ * \param path          The name of the file.
  *
  *
- * \return              0 if successful,
- *                      MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error,
- *                      MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or
- *                      MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG
+ * \return              \c 0 on success,
+ *                      #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error,
+ *                      #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or
+ *                      #MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG on failure.
  */
  */
 int mbedtls_ctr_drbg_update_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path );
 int mbedtls_ctr_drbg_update_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path );
 #endif /* MBEDTLS_FS_IO */
 #endif /* MBEDTLS_FS_IO */
 
 
 /**
 /**
- * \brief               Checkup routine
+ * \brief               The CTR_DRBG checkup routine.
  *
  *
- * \return              0 if successful, or 1 if the test failed
+ * \return              \c 0 on success, or \c 1 on failure.
  */
  */
 int mbedtls_ctr_drbg_self_test( int verbose );
 int mbedtls_ctr_drbg_self_test( int verbose );
 
 

+ 2 - 1
mbedtls/include/mbedtls/debug.h

@@ -2,7 +2,8 @@
  * \file debug.h
  * \file debug.h
  *
  *
  * \brief Functions for controlling and providing debug output from the library.
  * \brief Functions for controlling and providing debug output from the library.
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *

+ 51 - 0
mbedtls/include/mbedtls/des.h

@@ -3,6 +3,11 @@
  *
  *
  * \brief DES block cipher
  * \brief DES block cipher
  *
  *
+ * \warning   DES is considered a weak cipher and its use constitutes a
+ *            security risk. We recommend considering stronger ciphers
+ *            instead.
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -19,6 +24,7 @@
  *  limitations under the License.
  *  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_DES_H
 #ifndef MBEDTLS_DES_H
 #define MBEDTLS_DES_H
 #define MBEDTLS_DES_H
@@ -36,6 +42,7 @@
 #define MBEDTLS_DES_DECRYPT     0
 #define MBEDTLS_DES_DECRYPT     0
 
 
 #define MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH              -0x0032  /**< The data input has an invalid length. */
 #define MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH              -0x0032  /**< The data input has an invalid length. */
+#define MBEDTLS_ERR_DES_HW_ACCEL_FAILED                   -0x0033  /**< DES hardware accelerator failed. */
 
 
 #define MBEDTLS_DES_KEY_SIZE    8
 #define MBEDTLS_DES_KEY_SIZE    8
 
 
@@ -49,6 +56,10 @@ extern "C" {
 
 
 /**
 /**
  * \brief          DES context structure
  * \brief          DES context structure
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
  */
 typedef struct
 typedef struct
 {
 {
@@ -69,6 +80,10 @@ mbedtls_des3_context;
  * \brief          Initialize DES context
  * \brief          Initialize DES context
  *
  *
  * \param ctx      DES context to be initialized
  * \param ctx      DES context to be initialized
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
  */
 void mbedtls_des_init( mbedtls_des_context *ctx );
 void mbedtls_des_init( mbedtls_des_context *ctx );
 
 
@@ -76,6 +91,10 @@ void mbedtls_des_init( mbedtls_des_context *ctx );
  * \brief          Clear DES context
  * \brief          Clear DES context
  *
  *
  * \param ctx      DES context to be cleared
  * \param ctx      DES context to be cleared
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
  */
 void mbedtls_des_free( mbedtls_des_context *ctx );
 void mbedtls_des_free( mbedtls_des_context *ctx );
 
 
@@ -100,6 +119,10 @@ void mbedtls_des3_free( mbedtls_des3_context *ctx );
  *                 a parity bit to allow verification.
  *                 a parity bit to allow verification.
  *
  *
  * \param key      8-byte secret key
  * \param key      8-byte secret key
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
  */
 void mbedtls_des_key_set_parity( unsigned char key[MBEDTLS_DES_KEY_SIZE] );
 void mbedtls_des_key_set_parity( unsigned char key[MBEDTLS_DES_KEY_SIZE] );
 
 
@@ -112,6 +135,10 @@ void mbedtls_des_key_set_parity( unsigned char key[MBEDTLS_DES_KEY_SIZE] );
  * \param key      8-byte secret key
  * \param key      8-byte secret key
  *
  *
  * \return         0 is parity was ok, 1 if parity was not correct.
  * \return         0 is parity was ok, 1 if parity was not correct.
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
  */
 int mbedtls_des_key_check_key_parity( const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
 int mbedtls_des_key_check_key_parity( const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
 
 
@@ -121,6 +148,10 @@ int mbedtls_des_key_check_key_parity( const unsigned char key[MBEDTLS_DES_KEY_SI
  * \param key      8-byte secret key
  * \param key      8-byte secret key
  *
  *
  * \return         0 if no weak key was found, 1 if a weak key was identified.
  * \return         0 if no weak key was found, 1 if a weak key was identified.
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
  */
 int mbedtls_des_key_check_weak( const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
 int mbedtls_des_key_check_weak( const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
 
 
@@ -131,6 +162,10 @@ int mbedtls_des_key_check_weak( const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
  * \param key      8-byte secret key
  * \param key      8-byte secret key
  *
  *
  * \return         0
  * \return         0
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
  */
 int mbedtls_des_setkey_enc( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
 int mbedtls_des_setkey_enc( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
 
 
@@ -141,6 +176,10 @@ int mbedtls_des_setkey_enc( mbedtls_des_context *ctx, const unsigned char key[MB
  * \param key      8-byte secret key
  * \param key      8-byte secret key
  *
  *
  * \return         0
  * \return         0
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
  */
 int mbedtls_des_setkey_dec( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
 int mbedtls_des_setkey_dec( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
 
 
@@ -196,6 +235,10 @@ int mbedtls_des3_set3key_dec( mbedtls_des3_context *ctx,
  * \param output   64-bit output block
  * \param output   64-bit output block
  *
  *
  * \return         0 if successful
  * \return         0 if successful
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
  */
 int mbedtls_des_crypt_ecb( mbedtls_des_context *ctx,
 int mbedtls_des_crypt_ecb( mbedtls_des_context *ctx,
                     const unsigned char input[8],
                     const unsigned char input[8],
@@ -219,6 +262,10 @@ int mbedtls_des_crypt_ecb( mbedtls_des_context *ctx,
  * \param iv       initialization vector (updated after use)
  * \param iv       initialization vector (updated after use)
  * \param input    buffer holding the input data
  * \param input    buffer holding the input data
  * \param output   buffer holding the output data
  * \param output   buffer holding the output data
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
  */
 int mbedtls_des_crypt_cbc( mbedtls_des_context *ctx,
 int mbedtls_des_crypt_cbc( mbedtls_des_context *ctx,
                     int mode,
                     int mode,
@@ -277,6 +324,10 @@ int mbedtls_des3_crypt_cbc( mbedtls_des3_context *ctx,
  *
  *
  * \param SK       Round keys
  * \param SK       Round keys
  * \param key      Base key
  * \param key      Base key
+ *
+ * \warning        DES is considered a weak cipher and its use constitutes a
+ *                 security risk. We recommend considering stronger ciphers
+ *                 instead.
  */
  */
 void mbedtls_des_setkey( uint32_t SK[32],
 void mbedtls_des_setkey( uint32_t SK[32],
                          const unsigned char key[MBEDTLS_DES_KEY_SIZE] );
                          const unsigned char key[MBEDTLS_DES_KEY_SIZE] );

+ 935 - 179
mbedtls/include/mbedtls/dhm.h

@@ -1,9 +1,44 @@
 /**
 /**
  * \file dhm.h
  * \file dhm.h
  *
  *
- * \brief Diffie-Hellman-Merkle key exchange
+ * \brief Diffie-Hellman-Merkle key exchange.
  *
  *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * <em>RFC-3526: More Modular Exponential (MODP) Diffie-Hellman groups for
+ * Internet Key Exchange (IKE)</em> defines a number of standardized
+ * Diffie-Hellman groups for IKE.
+ *
+ * <em>RFC-5114: Additional Diffie-Hellman Groups for Use with IETF
+ * Standards</em> defines a number of standardized Diffie-Hellman
+ * groups that can be used.
+ *
+ * \warning  The security of the DHM key exchange relies on the proper choice
+ *           of prime modulus - optimally, it should be a safe prime. The usage
+ *           of non-safe primes both decreases the difficulty of the underlying
+ *           discrete logarithm problem and can lead to small subgroup attacks
+ *           leaking private exponent bits when invalid public keys are used
+ *           and not detected. This is especially relevant if the same DHM
+ *           parameters are reused for multiple key exchanges as in static DHM,
+ *           while the criticality of small-subgroup attacks is lower for
+ *           ephemeral DHM.
+ *
+ * \warning  For performance reasons, the code does neither perform primality
+ *           nor safe primality tests, nor the expensive checks for invalid
+ *           subgroups. Moreover, even if these were performed, non-standardized
+ *           primes cannot be trusted because of the possibility of backdoors
+ *           that can't be effectively checked for.
+ *
+ * \warning  Diffie-Hellman-Merkle is therefore a security risk when not using
+ *           standardized primes generated using a trustworthy ("nothing up
+ *           my sleeve") method, such as the RFC 3526 / 7919 primes. In the TLS
+ *           protocol, DH parameters need to be negotiated, so using the default
+ *           primes systematically is not always an option. If possible, use
+ *           Elliptic Curve Diffie-Hellman (ECDH), which has better performance,
+ *           and for which the TLS protocol mandates the use of standard
+ *           parameters.
+ *
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,17 +53,24 @@
  *  See the License for the specific language governing permissions and
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *  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_DHM_H
 #ifndef MBEDTLS_DHM_H
 #define MBEDTLS_DHM_H
 #define MBEDTLS_DHM_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
 #include "bignum.h"
 #include "bignum.h"
+#if !defined(MBEDTLS_DHM_ALT)
 
 
 /*
 /*
  * DHM Error codes
  * DHM Error codes
  */
  */
-#define MBEDTLS_ERR_DHM_BAD_INPUT_DATA                    -0x3080  /**< Bad input parameters to function. */
+#define MBEDTLS_ERR_DHM_BAD_INPUT_DATA                    -0x3080  /**< Bad input parameters. */
 #define MBEDTLS_ERR_DHM_READ_PARAMS_FAILED                -0x3100  /**< Reading of the DHM parameters failed. */
 #define MBEDTLS_ERR_DHM_READ_PARAMS_FAILED                -0x3100  /**< Reading of the DHM parameters failed. */
 #define MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED                -0x3180  /**< Making of the DHM parameters failed. */
 #define MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED                -0x3180  /**< Making of the DHM parameters failed. */
 #define MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED                -0x3200  /**< Reading of the public values failed. */
 #define MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED                -0x3200  /**< Reading of the public values failed. */
@@ -36,167 +78,85 @@
 #define MBEDTLS_ERR_DHM_CALC_SECRET_FAILED                -0x3300  /**< Calculation of the DHM secret failed. */
 #define MBEDTLS_ERR_DHM_CALC_SECRET_FAILED                -0x3300  /**< Calculation of the DHM secret failed. */
 #define MBEDTLS_ERR_DHM_INVALID_FORMAT                    -0x3380  /**< The ASN.1 data is not formatted correctly. */
 #define MBEDTLS_ERR_DHM_INVALID_FORMAT                    -0x3380  /**< The ASN.1 data is not formatted correctly. */
 #define MBEDTLS_ERR_DHM_ALLOC_FAILED                      -0x3400  /**< Allocation of memory failed. */
 #define MBEDTLS_ERR_DHM_ALLOC_FAILED                      -0x3400  /**< Allocation of memory failed. */
-#define MBEDTLS_ERR_DHM_FILE_IO_ERROR                     -0x3480  /**< Read/write of file failed. */
-
-/**
- * RFC 3526 defines a number of standardized Diffie-Hellman groups
- * for IKE.
- * RFC 5114 defines a number of standardized Diffie-Hellman groups
- * that can be used.
- *
- * Some are included here for convenience.
- *
- * Included are:
- *  RFC 3526 3.    2048-bit MODP Group
- *  RFC 3526 4.    3072-bit MODP Group
- *  RFC 3526 5.    4096-bit MODP Group
- *  RFC 5114 2.2.  2048-bit MODP Group with 224-bit Prime Order Subgroup
- */
-#define MBEDTLS_DHM_RFC3526_MODP_2048_P               \
-    "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \
-    "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \
-    "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \
-    "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \
-    "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \
-    "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \
-    "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \
-    "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \
-    "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \
-    "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \
-    "15728E5A8AACAA68FFFFFFFFFFFFFFFF"
-
-#define MBEDTLS_DHM_RFC3526_MODP_2048_G          "02"
-
-#define MBEDTLS_DHM_RFC3526_MODP_3072_P               \
-    "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \
-    "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \
-    "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \
-    "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \
-    "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \
-    "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \
-    "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \
-    "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \
-    "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \
-    "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \
-    "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \
-    "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \
-    "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \
-    "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \
-    "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \
-    "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF"
-
-#define MBEDTLS_DHM_RFC3526_MODP_3072_G          "02"
-
-#define MBEDTLS_DHM_RFC3526_MODP_4096_P                \
-    "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \
-    "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \
-    "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \
-    "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \
-    "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \
-    "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \
-    "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \
-    "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \
-    "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \
-    "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \
-    "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \
-    "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \
-    "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \
-    "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \
-    "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \
-    "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" \
-    "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" \
-    "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" \
-    "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" \
-    "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" \
-    "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" \
-    "FFFFFFFFFFFFFFFF"
-
-#define MBEDTLS_DHM_RFC3526_MODP_4096_G          "02"
-
-#define MBEDTLS_DHM_RFC5114_MODP_2048_P               \
-    "AD107E1E9123A9D0D660FAA79559C51FA20D64E5683B9FD1" \
-    "B54B1597B61D0A75E6FA141DF95A56DBAF9A3C407BA1DF15" \
-    "EB3D688A309C180E1DE6B85A1274A0A66D3F8152AD6AC212" \
-    "9037C9EDEFDA4DF8D91E8FEF55B7394B7AD5B7D0B6C12207" \
-    "C9F98D11ED34DBF6C6BA0B2C8BBC27BE6A00E0A0B9C49708" \
-    "B3BF8A317091883681286130BC8985DB1602E714415D9330" \
-    "278273C7DE31EFDC7310F7121FD5A07415987D9ADC0A486D" \
-    "CDF93ACC44328387315D75E198C641A480CD86A1B9E587E8" \
-    "BE60E69CC928B2B9C52172E413042E9B23F10B0E16E79763" \
-    "C9B53DCF4BA80A29E3FB73C16B8E75B97EF363E2FFA31F71" \
-    "CF9DE5384E71B81C0AC4DFFE0C10E64F"
-
-#define MBEDTLS_DHM_RFC5114_MODP_2048_G              \
-    "AC4032EF4F2D9AE39DF30B5C8FFDAC506CDEBE7B89998CAF"\
-    "74866A08CFE4FFE3A6824A4E10B9A6F0DD921F01A70C4AFA"\
-    "AB739D7700C29F52C57DB17C620A8652BE5E9001A8D66AD7"\
-    "C17669101999024AF4D027275AC1348BB8A762D0521BC98A"\
-    "E247150422EA1ED409939D54DA7460CDB5F6C6B250717CBE"\
-    "F180EB34118E98D119529A45D6F834566E3025E316A330EF"\
-    "BB77A86F0C1AB15B051AE3D428C8F8ACB70A8137150B8EEB"\
-    "10E183EDD19963DDD9E263E4770589EF6AA21E7F5F2FF381"\
-    "B539CCE3409D13CD566AFBB48D6C019181E1BCFE94B30269"\
-    "EDFE72FE9B6AA4BD7B5A0F1C71CFFF4C19C418E1F6EC0179"\
-    "81BC087F2A7065B384B890D3191F2BFA"
+#define MBEDTLS_ERR_DHM_FILE_IO_ERROR                     -0x3480  /**< Read or write of file failed. */
+#define MBEDTLS_ERR_DHM_HW_ACCEL_FAILED                   -0x3500  /**< DHM hardware accelerator failed. */
+#define MBEDTLS_ERR_DHM_SET_GROUP_FAILED                  -0x3580  /**< Setting the modulus and generator failed. */
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
 extern "C" {
 extern "C" {
 #endif
 #endif
 
 
 /**
 /**
- * \brief          DHM context structure
+ * \brief          The DHM context structure.
  */
  */
 typedef struct
 typedef struct
 {
 {
-    size_t len; /*!<  size(P) in chars  */
-    mbedtls_mpi P;      /*!<  prime modulus     */
-    mbedtls_mpi G;      /*!<  generator         */
-    mbedtls_mpi X;      /*!<  secret value      */
-    mbedtls_mpi GX;     /*!<  self = G^X mod P  */
-    mbedtls_mpi GY;     /*!<  peer = G^Y mod P  */
-    mbedtls_mpi K;      /*!<  key = GY^X mod P  */
-    mbedtls_mpi RP;     /*!<  cached R^2 mod P  */
-    mbedtls_mpi Vi;     /*!<  blinding value    */
-    mbedtls_mpi Vf;     /*!<  un-blinding value */
-    mbedtls_mpi pX;     /*!<  previous X        */
+    size_t len;         /*!<  The size of \p P in Bytes. */
+    mbedtls_mpi P;      /*!<  The prime modulus. */
+    mbedtls_mpi G;      /*!<  The generator. */
+    mbedtls_mpi X;      /*!<  Our secret value. */
+    mbedtls_mpi GX;     /*!<  Our public key = \c G^X mod \c P. */
+    mbedtls_mpi GY;     /*!<  The public key of the peer = \c G^Y mod \c P. */
+    mbedtls_mpi K;      /*!<  The shared secret = \c G^(XY) mod \c P. */
+    mbedtls_mpi RP;     /*!<  The cached value = \c R^2 mod \c P. */
+    mbedtls_mpi Vi;     /*!<  The blinding value. */
+    mbedtls_mpi Vf;     /*!<  The unblinding value. */
+    mbedtls_mpi pX;     /*!<  The previous \c X. */
 }
 }
 mbedtls_dhm_context;
 mbedtls_dhm_context;
 
 
 /**
 /**
- * \brief          Initialize DHM context
+ * \brief          This function initializes the DHM context.
  *
  *
- * \param ctx      DHM context to be initialized
+ * \param ctx      The DHM context to initialize.
  */
  */
 void mbedtls_dhm_init( mbedtls_dhm_context *ctx );
 void mbedtls_dhm_init( mbedtls_dhm_context *ctx );
 
 
 /**
 /**
- * \brief          Parse the ServerKeyExchange parameters
+ * \brief          This function parses the ServerKeyExchange parameters.
  *
  *
- * \param ctx      DHM context
- * \param p        &(start of input buffer)
- * \param end      end of buffer
+ * \param ctx      The DHM context.
+ * \param p        On input, *p must be the start of the input buffer.
+ *                 On output, *p is updated to point to the end of the data
+ *                 that has been read. On success, this is the first byte
+ *                 past the end of the ServerKeyExchange parameters.
+ *                 On error, this is the point at which an error has been
+ *                 detected, which is usually not useful except to debug
+ *                 failures.
+ * \param end      The end of the input buffer.
  *
  *
- * \return         0 if successful, or an MBEDTLS_ERR_DHM_XXX error code
+ * \return         \c 0 on success, or an \c MBEDTLS_ERR_DHM_XXX error code
+ *                 on failure.
  */
  */
 int mbedtls_dhm_read_params( mbedtls_dhm_context *ctx,
 int mbedtls_dhm_read_params( mbedtls_dhm_context *ctx,
                      unsigned char **p,
                      unsigned char **p,
                      const unsigned char *end );
                      const unsigned char *end );
 
 
 /**
 /**
- * \brief          Setup and write the ServerKeyExchange parameters
+ * \brief          This function sets up and writes the ServerKeyExchange
+ *                 parameters.
  *
  *
- * \param ctx      DHM context
- * \param x_size   private value size in bytes
- * \param output   destination buffer
- * \param olen     number of chars written
- * \param f_rng    RNG function
- * \param p_rng    RNG parameter
+ * \param ctx      The DHM context.
+ * \param x_size   The private value size in Bytes.
+ * \param olen     The number of characters written.
+ * \param output   The destination buffer.
+ * \param f_rng    The RNG function.
+ * \param p_rng    The RNG parameter.
  *
  *
- * \note           This function assumes that ctx->P and ctx->G
- *                 have already been properly set (for example
- *                 using mbedtls_mpi_read_string or mbedtls_mpi_read_binary).
+ * \note           The destination buffer must be large enough to hold
+ *                 the reduced binary presentation of the modulus, the generator
+ *                 and the public key, each wrapped with a 2-byte length field.
+ *                 It is the responsibility of the caller to ensure that enough
+ *                 space is available. Refer to \c mbedtls_mpi_size to computing
+ *                 the byte-size of an MPI.
  *
  *
- * \return         0 if successful, or an MBEDTLS_ERR_DHM_XXX error code
+ * \note           This function assumes that \c ctx->P and \c ctx->G
+ *                 have already been properly set. For that, use
+ *                 mbedtls_dhm_set_group() below in conjunction with
+ *                 mbedtls_mpi_read_binary() and mbedtls_mpi_read_string().
+ *
+ * \return         \c 0 on success, or an \c MBEDTLS_ERR_DHM_XXX error code
+ *                 on failure.
  */
  */
 int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size,
 int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size,
                      unsigned char *output, size_t *olen,
                      unsigned char *output, size_t *olen,
@@ -204,28 +164,54 @@ int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size,
                      void *p_rng );
                      void *p_rng );
 
 
 /**
 /**
- * \brief          Import the peer's public value G^Y
+ * \brief          Set prime modulus and generator
+ *
+ * \param ctx      The DHM context.
+ * \param P        The MPI holding DHM prime modulus.
+ * \param G        The MPI holding DHM generator.
  *
  *
- * \param ctx      DHM context
- * \param input    input buffer
- * \param ilen     size of buffer
+ * \note           This function can be used to set P, G
+ *                 in preparation for \c mbedtls_dhm_make_params.
  *
  *
- * \return         0 if successful, or an MBEDTLS_ERR_DHM_XXX error code
+ * \return         \c 0 if successful, or an \c MBEDTLS_ERR_DHM_XXX error code
+ *                 on failure.
+ */
+int mbedtls_dhm_set_group( mbedtls_dhm_context *ctx,
+                           const mbedtls_mpi *P,
+                           const mbedtls_mpi *G );
+
+/**
+ * \brief          This function imports the public value G^Y of the peer.
+ *
+ * \param ctx      The DHM context.
+ * \param input    The input buffer.
+ * \param ilen     The size of the input buffer.
+ *
+ * \return         \c 0 on success, or an \c MBEDTLS_ERR_DHM_XXX error code
+ *                 on failure.
  */
  */
 int mbedtls_dhm_read_public( mbedtls_dhm_context *ctx,
 int mbedtls_dhm_read_public( mbedtls_dhm_context *ctx,
                      const unsigned char *input, size_t ilen );
                      const unsigned char *input, size_t ilen );
 
 
 /**
 /**
- * \brief          Create own private value X and export G^X
+ * \brief          This function creates its own private value \c X and
+ *                 exports \c G^X.
+ *
+ * \param ctx      The DHM context.
+ * \param x_size   The private value size in Bytes.
+ * \param output   The destination buffer.
+ * \param olen     The length of the destination buffer. Must be at least
+                   equal to ctx->len (the size of \c P).
+ * \param f_rng    The RNG function.
+ * \param p_rng    The RNG parameter.
  *
  *
- * \param ctx      DHM context
- * \param x_size   private value size in bytes
- * \param output   destination buffer
- * \param olen     must be at least equal to the size of P, ctx->len
- * \param f_rng    RNG function
- * \param p_rng    RNG parameter
+ * \note           The destination buffer will always be fully written
+ *                 so as to contain a big-endian presentation of G^X mod P.
+ *                 If it is larger than ctx->len, it will accordingly be
+ *                 padded with zero-bytes in the beginning.
  *
  *
- * \return         0 if successful, or an MBEDTLS_ERR_DHM_XXX error code
+ * \return         \c 0 on success, or an \c MBEDTLS_ERR_DHM_XXX error code
+ *                 on failure.
  */
  */
 int mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size,
 int mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size,
                      unsigned char *output, size_t olen,
                      unsigned char *output, size_t olen,
@@ -233,22 +219,25 @@ int mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size,
                      void *p_rng );
                      void *p_rng );
 
 
 /**
 /**
- * \brief          Derive and export the shared secret (G^Y)^X mod P
- *
- * \param ctx      DHM context
- * \param output   destination buffer
- * \param output_size   size of the destination buffer
- * \param olen     on exit, holds the actual number of bytes written
- * \param f_rng    RNG function, for blinding purposes
- * \param p_rng    RNG parameter
- *
- * \return         0 if successful, or an MBEDTLS_ERR_DHM_XXX error code
- *
- * \note           If non-NULL, f_rng is used to blind the input as
- *                 countermeasure against timing attacks. Blinding is
- *                 automatically used if and only if our secret value X is
- *                 re-used and costs nothing otherwise, so it is recommended
- *                 to always pass a non-NULL f_rng argument.
+ * \brief               This function derives and exports the shared secret
+ *                      \c (G^Y)^X mod \c P.
+ *
+ * \param ctx           The DHM context.
+ * \param output        The destination buffer.
+ * \param output_size   The size of the destination buffer. Must be at least
+ *                      the size of ctx->len.
+ * \param olen          On exit, holds the actual number of Bytes written.
+ * \param f_rng         The RNG function, for blinding purposes.
+ * \param p_rng         The RNG parameter.
+ *
+ * \return         \c 0 on success, or an \c MBEDTLS_ERR_DHM_XXX error code
+ *                 on failure.
+ *
+ * \note           If non-NULL, \p f_rng is used to blind the input as
+ *                 a countermeasure against timing attacks. Blinding is used
+ *                 only if our secret value \p X is re-used and omitted
+ *                 otherwise. Therefore, we recommend always passing a
+ *                 non-NULL \p f_rng argument.
  */
  */
 int mbedtls_dhm_calc_secret( mbedtls_dhm_context *ctx,
 int mbedtls_dhm_calc_secret( mbedtls_dhm_context *ctx,
                      unsigned char *output, size_t output_size, size_t *olen,
                      unsigned char *output, size_t output_size, size_t *olen,
@@ -256,23 +245,24 @@ int mbedtls_dhm_calc_secret( mbedtls_dhm_context *ctx,
                      void *p_rng );
                      void *p_rng );
 
 
 /**
 /**
- * \brief          Free and clear the components of a DHM key
+ * \brief          This function frees and clears the components of a DHM key.
  *
  *
- * \param ctx      DHM context to free and clear
+ * \param ctx      The DHM context to free and clear.
  */
  */
 void mbedtls_dhm_free( mbedtls_dhm_context *ctx );
 void mbedtls_dhm_free( mbedtls_dhm_context *ctx );
 
 
 #if defined(MBEDTLS_ASN1_PARSE_C)
 #if defined(MBEDTLS_ASN1_PARSE_C)
 /** \ingroup x509_module */
 /** \ingroup x509_module */
 /**
 /**
- * \brief          Parse DHM parameters in PEM or DER format
+ * \brief             This function parses DHM parameters in PEM or DER format.
  *
  *
- * \param dhm      DHM context to be initialized
- * \param dhmin    input buffer
- * \param dhminlen size of the buffer
- *                 (including the terminating null byte for PEM data)
+ * \param dhm         The DHM context to initialize.
+ * \param dhmin       The input buffer.
+ * \param dhminlen    The size of the buffer, including the terminating null
+ *                    Byte for PEM data.
  *
  *
- * \return         0 if successful, or a specific DHM or PEM error code
+ * \return            \c 0 on success, or a specific DHM or PEM error code
+ *                    on failure.
  */
  */
 int mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin,
 int mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin,
                    size_t dhminlen );
                    size_t dhminlen );
@@ -280,21 +270,34 @@ int mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin,
 #if defined(MBEDTLS_FS_IO)
 #if defined(MBEDTLS_FS_IO)
 /** \ingroup x509_module */
 /** \ingroup x509_module */
 /**
 /**
- * \brief          Load and parse DHM parameters
+ * \brief          This function loads and parses DHM parameters from a file.
  *
  *
- * \param dhm      DHM context to be initialized
- * \param path     filename to read the DHM Parameters from
+ * \param dhm      The DHM context to load the parameters to.
+ * \param path     The filename to read the DHM parameters from.
  *
  *
- * \return         0 if successful, or a specific DHM or PEM error code
+ * \return         \c 0 on success, or a specific DHM or PEM error code
+ *                 on failure.
  */
  */
 int mbedtls_dhm_parse_dhmfile( mbedtls_dhm_context *dhm, const char *path );
 int mbedtls_dhm_parse_dhmfile( mbedtls_dhm_context *dhm, const char *path );
 #endif /* MBEDTLS_FS_IO */
 #endif /* MBEDTLS_FS_IO */
 #endif /* MBEDTLS_ASN1_PARSE_C */
 #endif /* MBEDTLS_ASN1_PARSE_C */
 
 
+#ifdef __cplusplus
+}
+#endif
+
+#else /* MBEDTLS_DHM_ALT */
+#include "dhm_alt.h"
+#endif /* MBEDTLS_DHM_ALT */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 /**
 /**
- * \brief          Checkup routine
+ * \brief          The DMH checkup routine.
  *
  *
- * \return         0 if successful, or 1 if the test failed
+ * \return         \c 0 on success, or \c 1 on failure.
  */
  */
 int mbedtls_dhm_self_test( int verbose );
 int mbedtls_dhm_self_test( int verbose );
 
 
@@ -302,4 +305,757 @@ int mbedtls_dhm_self_test( int verbose );
 }
 }
 #endif
 #endif
 
 
+/**
+ * RFC 3526, RFC 5114 and RFC 7919 standardize a number of
+ * Diffie-Hellman groups, some of which are included here
+ * for use within the SSL/TLS module and the user's convenience
+ * when configuring the Diffie-Hellman parameters by hand
+ * through \c mbedtls_ssl_conf_dh_param.
+ *
+ * The following lists the source of the above groups in the standards:
+ * - RFC 5114 section 2.2:  2048-bit MODP Group with 224-bit Prime Order Subgroup
+ * - RFC 3526 section 3:    2048-bit MODP Group
+ * - RFC 3526 section 4:    3072-bit MODP Group
+ * - RFC 3526 section 5:    4096-bit MODP Group
+ * - RFC 7919 section A.1:  ffdhe2048
+ * - RFC 7919 section A.2:  ffdhe3072
+ * - RFC 7919 section A.3:  ffdhe4096
+ * - RFC 7919 section A.4:  ffdhe6144
+ * - RFC 7919 section A.5:  ffdhe8192
+ *
+ * The constants with suffix "_p" denote the chosen prime moduli, while
+ * the constants with suffix "_g" denote the chosen generator
+ * of the associated prime field.
+ *
+ * The constants further suffixed with "_bin" are provided in binary format,
+ * while all other constants represent null-terminated strings holding the
+ * hexadecimal presentation of the respective numbers.
+ *
+ * The primes from RFC 3526 and RFC 7919 have been generating by the following
+ * trust-worthy procedure:
+ * - Fix N in { 2048, 3072, 4096, 6144, 8192 } and consider the N-bit number
+ *   the first and last 64 bits are all 1, and the remaining N - 128 bits of
+ *   which are 0x7ff...ff.
+ * - Add the smallest multiple of the first N - 129 bits of the binary expansion
+ *   of pi (for RFC 5236) or e (for RFC 7919) to this intermediate bit-string
+ *   such that the resulting integer is a safe-prime.
+ * - The result is the respective RFC 3526 / 7919 prime, and the corresponding
+ *   generator is always chosen to be 2 (which is a square for these prime,
+ *   hence the corresponding subgroup has order (p-1)/2 and avoids leaking a
+ *   bit in the private exponent).
+ *
+ */
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED __attribute__((deprecated))
+MBEDTLS_DEPRECATED typedef char const * mbedtls_deprecated_constant_t;
+#define MBEDTLS_DEPRECATED_STRING_CONSTANT( VAL )       \
+    ( (mbedtls_deprecated_constant_t) ( VAL ) )
+#else
+#define MBEDTLS_DEPRECATED_STRING_CONSTANT( VAL ) VAL
+#endif /* ! MBEDTLS_DEPRECATED_WARNING */
+
+/**
+ * \warning The origin of the primes in RFC 5114 is not documented and
+ *          their use therefore constitutes a security risk!
+ *
+ * \deprecated The hex-encoded primes from RFC 5114 are deprecated and are
+ *             likely to be removed in a future version of the library without
+ *             replacement.
+ */
+
+/**
+ * The hexadecimal presentation of the prime underlying the
+ * 2048-bit MODP Group with 224-bit Prime Order Subgroup, as defined
+ * in <em>RFC-5114: Additional Diffie-Hellman Groups for Use with
+ * IETF Standards</em>.
+ */
+#define MBEDTLS_DHM_RFC5114_MODP_2048_P                         \
+    MBEDTLS_DEPRECATED_STRING_CONSTANT(                         \
+        "AD107E1E9123A9D0D660FAA79559C51FA20D64E5683B9FD1"      \
+        "B54B1597B61D0A75E6FA141DF95A56DBAF9A3C407BA1DF15"      \
+        "EB3D688A309C180E1DE6B85A1274A0A66D3F8152AD6AC212"      \
+        "9037C9EDEFDA4DF8D91E8FEF55B7394B7AD5B7D0B6C12207"      \
+        "C9F98D11ED34DBF6C6BA0B2C8BBC27BE6A00E0A0B9C49708"      \
+        "B3BF8A317091883681286130BC8985DB1602E714415D9330"      \
+        "278273C7DE31EFDC7310F7121FD5A07415987D9ADC0A486D"      \
+        "CDF93ACC44328387315D75E198C641A480CD86A1B9E587E8"      \
+        "BE60E69CC928B2B9C52172E413042E9B23F10B0E16E79763"      \
+        "C9B53DCF4BA80A29E3FB73C16B8E75B97EF363E2FFA31F71"      \
+        "CF9DE5384E71B81C0AC4DFFE0C10E64F" )
+
+/**
+ * The hexadecimal presentation of the chosen generator of the 2048-bit MODP
+ * Group with 224-bit Prime Order Subgroup, as defined in <em>RFC-5114:
+ * Additional Diffie-Hellman Groups for Use with IETF Standards</em>.
+ */
+#define MBEDTLS_DHM_RFC5114_MODP_2048_G                         \
+    MBEDTLS_DEPRECATED_STRING_CONSTANT(                         \
+        "AC4032EF4F2D9AE39DF30B5C8FFDAC506CDEBE7B89998CAF"      \
+        "74866A08CFE4FFE3A6824A4E10B9A6F0DD921F01A70C4AFA"      \
+        "AB739D7700C29F52C57DB17C620A8652BE5E9001A8D66AD7"      \
+        "C17669101999024AF4D027275AC1348BB8A762D0521BC98A"      \
+        "E247150422EA1ED409939D54DA7460CDB5F6C6B250717CBE"      \
+        "F180EB34118E98D119529A45D6F834566E3025E316A330EF"      \
+        "BB77A86F0C1AB15B051AE3D428C8F8ACB70A8137150B8EEB"      \
+        "10E183EDD19963DDD9E263E4770589EF6AA21E7F5F2FF381"      \
+        "B539CCE3409D13CD566AFBB48D6C019181E1BCFE94B30269"      \
+        "EDFE72FE9B6AA4BD7B5A0F1C71CFFF4C19C418E1F6EC0179"      \
+        "81BC087F2A7065B384B890D3191F2BFA" )
+
+/**
+ * The hexadecimal presentation of the prime underlying the 2048-bit MODP
+ * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP)
+ * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>.
+ *
+ * \deprecated The hex-encoded primes from RFC 3625 are deprecated and
+ *             superseded by the corresponding macros providing them as
+ *             binary constants. Their hex-encoded constants are likely
+ *             to be removed in a future version of the library.
+ *
+ */
+#define MBEDTLS_DHM_RFC3526_MODP_2048_P                         \
+    MBEDTLS_DEPRECATED_STRING_CONSTANT(                         \
+        "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"      \
+        "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"      \
+        "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"      \
+        "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"      \
+        "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"      \
+        "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"      \
+        "83655D23DCA3AD961C62F356208552BB9ED529077096966D"      \
+        "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"      \
+        "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"      \
+        "DE2BCBF6955817183995497CEA956AE515D2261898FA0510"      \
+        "15728E5A8AACAA68FFFFFFFFFFFFFFFF" )
+
+/**
+ * The hexadecimal presentation of the chosen generator of the 2048-bit MODP
+ * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP)
+ * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>.
+ */
+#define MBEDTLS_DHM_RFC3526_MODP_2048_G                         \
+    MBEDTLS_DEPRECATED_STRING_CONSTANT( "02" )
+
+/**
+ * The hexadecimal presentation of the prime underlying the 3072-bit MODP
+ * Group, as defined in <em>RFC-3072: More Modular Exponential (MODP)
+ * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>.
+ */
+#define MBEDTLS_DHM_RFC3526_MODP_3072_P                         \
+    MBEDTLS_DEPRECATED_STRING_CONSTANT(                         \
+        "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"      \
+        "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"      \
+        "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"      \
+        "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"      \
+        "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"      \
+        "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"      \
+        "83655D23DCA3AD961C62F356208552BB9ED529077096966D"      \
+        "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"      \
+        "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"      \
+        "DE2BCBF6955817183995497CEA956AE515D2261898FA0510"      \
+        "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"      \
+        "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"      \
+        "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"      \
+        "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"      \
+        "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"      \
+        "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF" )
+
+/**
+ * The hexadecimal presentation of the chosen generator of the 3072-bit MODP
+ * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP)
+ * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>.
+ */
+#define MBEDTLS_DHM_RFC3526_MODP_3072_G                      \
+    MBEDTLS_DEPRECATED_STRING_CONSTANT( "02" )
+
+/**
+ * The hexadecimal presentation of the prime underlying the 4096-bit MODP
+ * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP)
+ * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>.
+ */
+#define MBEDTLS_DHM_RFC3526_MODP_4096_P                      \
+    MBEDTLS_DEPRECATED_STRING_CONSTANT(                      \
+        "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"   \
+        "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"   \
+        "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"   \
+        "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"   \
+        "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"   \
+        "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"   \
+        "83655D23DCA3AD961C62F356208552BB9ED529077096966D"   \
+        "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"   \
+        "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9"   \
+        "DE2BCBF6955817183995497CEA956AE515D2261898FA0510"   \
+        "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64"   \
+        "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"   \
+        "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B"   \
+        "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"   \
+        "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31"   \
+        "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7"   \
+        "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA"   \
+        "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6"   \
+        "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED"   \
+        "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9"   \
+        "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199"   \
+        "FFFFFFFFFFFFFFFF" )
+
+/**
+ * The hexadecimal presentation of the chosen generator of the 4096-bit MODP
+ * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP)
+ * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>.
+ */
+#define MBEDTLS_DHM_RFC3526_MODP_4096_G                      \
+    MBEDTLS_DEPRECATED_STRING_CONSTANT( "02" )
+
+#endif /* MBEDTLS_DEPRECATED_REMOVED */
+
+/*
+ * Trustworthy DHM parameters in binary form
+ */
+
+#define MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN {        \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+     0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, \
+     0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, \
+     0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, \
+     0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, \
+     0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, \
+     0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, \
+     0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, \
+     0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, \
+     0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, \
+     0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, \
+     0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, \
+     0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, \
+     0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, \
+     0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, \
+     0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, \
+     0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, \
+     0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, \
+     0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, \
+     0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, \
+     0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, \
+     0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, \
+     0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, \
+     0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, \
+     0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, \
+     0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, \
+     0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, \
+     0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, \
+     0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, \
+     0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, \
+     0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAC, 0xAA, 0x68, \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC3526_MODP_3072_P_BIN {       \
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+    0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, \
+    0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, \
+    0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, \
+    0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, \
+    0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, \
+    0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, \
+    0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, \
+    0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, \
+    0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, \
+    0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, \
+    0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, \
+    0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, \
+    0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, \
+    0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, \
+    0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, \
+    0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, \
+    0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, \
+    0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, \
+    0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, \
+    0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, \
+    0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, \
+    0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, \
+    0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, \
+    0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, \
+    0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, \
+    0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, \
+    0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, \
+    0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, \
+    0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, \
+    0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D, \
+    0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33, \
+    0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64, \
+    0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A, \
+    0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D, \
+    0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7, \
+    0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7, \
+    0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D, \
+    0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B, \
+    0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64, \
+    0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64, \
+    0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C, \
+    0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C, \
+    0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2, \
+    0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31, \
+    0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E, \
+    0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x3A, 0xD2, 0xCA, \
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC3526_MODP_3072_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC3526_MODP_4096_P_BIN  {       \
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  \
+    0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,  \
+    0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1,  \
+    0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,  \
+    0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22,  \
+    0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,  \
+    0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B,  \
+    0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,  \
+    0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45,  \
+    0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,  \
+    0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B,  \
+    0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,  \
+    0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5,  \
+    0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,  \
+    0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D,  \
+    0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05,  \
+    0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A,  \
+    0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F,  \
+    0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96,  \
+    0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB,  \
+    0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D,  \
+    0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04,  \
+    0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C,  \
+    0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B,  \
+    0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03,  \
+    0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F,  \
+    0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9,  \
+    0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18,  \
+    0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5,  \
+    0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10,  \
+    0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D,  \
+    0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33,  \
+    0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64,  \
+    0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A,  \
+    0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D,  \
+    0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7,  \
+    0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7,  \
+    0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D,  \
+    0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B,  \
+    0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64,  \
+    0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64,  \
+    0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C,  \
+    0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C,  \
+    0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2,  \
+    0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31,  \
+    0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E,  \
+    0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x21, 0x08, 0x01,  \
+    0x1A, 0x72, 0x3C, 0x12, 0xA7, 0x87, 0xE6, 0xD7,  \
+    0x88, 0x71, 0x9A, 0x10, 0xBD, 0xBA, 0x5B, 0x26,  \
+    0x99, 0xC3, 0x27, 0x18, 0x6A, 0xF4, 0xE2, 0x3C,  \
+    0x1A, 0x94, 0x68, 0x34, 0xB6, 0x15, 0x0B, 0xDA,  \
+    0x25, 0x83, 0xE9, 0xCA, 0x2A, 0xD4, 0x4C, 0xE8,  \
+    0xDB, 0xBB, 0xC2, 0xDB, 0x04, 0xDE, 0x8E, 0xF9,  \
+    0x2E, 0x8E, 0xFC, 0x14, 0x1F, 0xBE, 0xCA, 0xA6,  \
+    0x28, 0x7C, 0x59, 0x47, 0x4E, 0x6B, 0xC0, 0x5D,  \
+    0x99, 0xB2, 0x96, 0x4F, 0xA0, 0x90, 0xC3, 0xA2,  \
+    0x23, 0x3B, 0xA1, 0x86, 0x51, 0x5B, 0xE7, 0xED,  \
+    0x1F, 0x61, 0x29, 0x70, 0xCE, 0xE2, 0xD7, 0xAF,  \
+    0xB8, 0x1B, 0xDD, 0x76, 0x21, 0x70, 0x48, 0x1C,  \
+    0xD0, 0x06, 0x91, 0x27, 0xD5, 0xB0, 0x5A, 0xA9,  \
+    0x93, 0xB4, 0xEA, 0x98, 0x8D, 0x8F, 0xDD, 0xC1,  \
+    0x86, 0xFF, 0xB7, 0xDC, 0x90, 0xA6, 0xC0, 0x8F,  \
+    0x4D, 0xF4, 0x35, 0xC9, 0x34, 0x06, 0x31, 0x99,  \
+    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC3526_MODP_4096_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE2048_P_BIN {        \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+     0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \
+     0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \
+     0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \
+     0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \
+     0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \
+     0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \
+     0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \
+     0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \
+     0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \
+     0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \
+     0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \
+     0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \
+     0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \
+     0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \
+     0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \
+     0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \
+     0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \
+     0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \
+     0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \
+     0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \
+     0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \
+     0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \
+     0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \
+     0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \
+     0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \
+     0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \
+     0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \
+     0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \
+     0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \
+     0x88, 0x6B, 0x42, 0x38, 0x61, 0x28, 0x5C, 0x97, \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE2048_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE3072_P_BIN { \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+     0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \
+     0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \
+     0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \
+     0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \
+     0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \
+     0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \
+     0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \
+     0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \
+     0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \
+     0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \
+     0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \
+     0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \
+     0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \
+     0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \
+     0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \
+     0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \
+     0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \
+     0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \
+     0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \
+     0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \
+     0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \
+     0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \
+     0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \
+     0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \
+     0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \
+     0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \
+     0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \
+     0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \
+     0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \
+     0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \
+     0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \
+     0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \
+     0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \
+     0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \
+     0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \
+     0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \
+     0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \
+     0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \
+     0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \
+     0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \
+     0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \
+     0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \
+     0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \
+     0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \
+     0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \
+     0x25, 0xE4, 0x1D, 0x2B, 0x66, 0xC6, 0x2E, 0x37, \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE3072_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE4096_P_BIN {        \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+     0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \
+     0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \
+     0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \
+     0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \
+     0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \
+     0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \
+     0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \
+     0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \
+     0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \
+     0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \
+     0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \
+     0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \
+     0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \
+     0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \
+     0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \
+     0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \
+     0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \
+     0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \
+     0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \
+     0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \
+     0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \
+     0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \
+     0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \
+     0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \
+     0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \
+     0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \
+     0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \
+     0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \
+     0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \
+     0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \
+     0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \
+     0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \
+     0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \
+     0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \
+     0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \
+     0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \
+     0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \
+     0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \
+     0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \
+     0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \
+     0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \
+     0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \
+     0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \
+     0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \
+     0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \
+     0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \
+     0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \
+     0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \
+     0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \
+     0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \
+     0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \
+     0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \
+     0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \
+     0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \
+     0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \
+     0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \
+     0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \
+     0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \
+     0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \
+     0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \
+     0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \
+     0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x65, 0x5F, 0x6A, \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE4096_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE6144_P_BIN {        \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+     0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \
+     0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \
+     0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \
+     0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \
+     0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \
+     0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \
+     0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \
+     0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \
+     0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \
+     0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \
+     0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \
+     0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \
+     0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \
+     0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \
+     0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \
+     0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \
+     0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \
+     0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \
+     0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \
+     0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \
+     0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \
+     0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \
+     0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \
+     0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \
+     0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \
+     0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \
+     0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \
+     0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \
+     0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \
+     0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \
+     0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \
+     0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \
+     0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \
+     0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \
+     0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \
+     0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \
+     0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \
+     0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \
+     0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \
+     0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \
+     0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \
+     0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \
+     0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \
+     0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \
+     0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \
+     0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \
+     0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \
+     0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \
+     0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \
+     0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \
+     0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \
+     0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \
+     0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \
+     0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \
+     0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \
+     0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \
+     0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \
+     0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \
+     0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \
+     0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \
+     0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \
+     0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x0D, 0xD9, 0x02, \
+     0x0B, 0xFD, 0x64, 0xB6, 0x45, 0x03, 0x6C, 0x7A, \
+     0x4E, 0x67, 0x7D, 0x2C, 0x38, 0x53, 0x2A, 0x3A, \
+     0x23, 0xBA, 0x44, 0x42, 0xCA, 0xF5, 0x3E, 0xA6, \
+     0x3B, 0xB4, 0x54, 0x32, 0x9B, 0x76, 0x24, 0xC8, \
+     0x91, 0x7B, 0xDD, 0x64, 0xB1, 0xC0, 0xFD, 0x4C, \
+     0xB3, 0x8E, 0x8C, 0x33, 0x4C, 0x70, 0x1C, 0x3A, \
+     0xCD, 0xAD, 0x06, 0x57, 0xFC, 0xCF, 0xEC, 0x71, \
+     0x9B, 0x1F, 0x5C, 0x3E, 0x4E, 0x46, 0x04, 0x1F, \
+     0x38, 0x81, 0x47, 0xFB, 0x4C, 0xFD, 0xB4, 0x77, \
+     0xA5, 0x24, 0x71, 0xF7, 0xA9, 0xA9, 0x69, 0x10, \
+     0xB8, 0x55, 0x32, 0x2E, 0xDB, 0x63, 0x40, 0xD8, \
+     0xA0, 0x0E, 0xF0, 0x92, 0x35, 0x05, 0x11, 0xE3, \
+     0x0A, 0xBE, 0xC1, 0xFF, 0xF9, 0xE3, 0xA2, 0x6E, \
+     0x7F, 0xB2, 0x9F, 0x8C, 0x18, 0x30, 0x23, 0xC3, \
+     0x58, 0x7E, 0x38, 0xDA, 0x00, 0x77, 0xD9, 0xB4, \
+     0x76, 0x3E, 0x4E, 0x4B, 0x94, 0xB2, 0xBB, 0xC1, \
+     0x94, 0xC6, 0x65, 0x1E, 0x77, 0xCA, 0xF9, 0x92, \
+     0xEE, 0xAA, 0xC0, 0x23, 0x2A, 0x28, 0x1B, 0xF6, \
+     0xB3, 0xA7, 0x39, 0xC1, 0x22, 0x61, 0x16, 0x82, \
+     0x0A, 0xE8, 0xDB, 0x58, 0x47, 0xA6, 0x7C, 0xBE, \
+     0xF9, 0xC9, 0x09, 0x1B, 0x46, 0x2D, 0x53, 0x8C, \
+     0xD7, 0x2B, 0x03, 0x74, 0x6A, 0xE7, 0x7F, 0x5E, \
+     0x62, 0x29, 0x2C, 0x31, 0x15, 0x62, 0xA8, 0x46, \
+     0x50, 0x5D, 0xC8, 0x2D, 0xB8, 0x54, 0x33, 0x8A, \
+     0xE4, 0x9F, 0x52, 0x35, 0xC9, 0x5B, 0x91, 0x17, \
+     0x8C, 0xCF, 0x2D, 0xD5, 0xCA, 0xCE, 0xF4, 0x03, \
+     0xEC, 0x9D, 0x18, 0x10, 0xC6, 0x27, 0x2B, 0x04, \
+     0x5B, 0x3B, 0x71, 0xF9, 0xDC, 0x6B, 0x80, 0xD6, \
+     0x3F, 0xDD, 0x4A, 0x8E, 0x9A, 0xDB, 0x1E, 0x69, \
+     0x62, 0xA6, 0x95, 0x26, 0xD4, 0x31, 0x61, 0xC1, \
+     0xA4, 0x1D, 0x57, 0x0D, 0x79, 0x38, 0xDA, 0xD4, \
+     0xA4, 0x0E, 0x32, 0x9C, 0xD0, 0xE4, 0x0E, 0x65, \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE6144_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE8192_P_BIN {        \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+     0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \
+     0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \
+     0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \
+     0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \
+     0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \
+     0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \
+     0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \
+     0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \
+     0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \
+     0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \
+     0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \
+     0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \
+     0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \
+     0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \
+     0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \
+     0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \
+     0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \
+     0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \
+     0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \
+     0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \
+     0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \
+     0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \
+     0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \
+     0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \
+     0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \
+     0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \
+     0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \
+     0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \
+     0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \
+     0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \
+     0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \
+     0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \
+     0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \
+     0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \
+     0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \
+     0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \
+     0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \
+     0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \
+     0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \
+     0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \
+     0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \
+     0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \
+     0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \
+     0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \
+     0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \
+     0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \
+     0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \
+     0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \
+     0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \
+     0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \
+     0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \
+     0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \
+     0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \
+     0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \
+     0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \
+     0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \
+     0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \
+     0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \
+     0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \
+     0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \
+     0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \
+     0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x0D, 0xD9, 0x02, \
+     0x0B, 0xFD, 0x64, 0xB6, 0x45, 0x03, 0x6C, 0x7A, \
+     0x4E, 0x67, 0x7D, 0x2C, 0x38, 0x53, 0x2A, 0x3A, \
+     0x23, 0xBA, 0x44, 0x42, 0xCA, 0xF5, 0x3E, 0xA6, \
+     0x3B, 0xB4, 0x54, 0x32, 0x9B, 0x76, 0x24, 0xC8, \
+     0x91, 0x7B, 0xDD, 0x64, 0xB1, 0xC0, 0xFD, 0x4C, \
+     0xB3, 0x8E, 0x8C, 0x33, 0x4C, 0x70, 0x1C, 0x3A, \
+     0xCD, 0xAD, 0x06, 0x57, 0xFC, 0xCF, 0xEC, 0x71, \
+     0x9B, 0x1F, 0x5C, 0x3E, 0x4E, 0x46, 0x04, 0x1F, \
+     0x38, 0x81, 0x47, 0xFB, 0x4C, 0xFD, 0xB4, 0x77, \
+     0xA5, 0x24, 0x71, 0xF7, 0xA9, 0xA9, 0x69, 0x10, \
+     0xB8, 0x55, 0x32, 0x2E, 0xDB, 0x63, 0x40, 0xD8, \
+     0xA0, 0x0E, 0xF0, 0x92, 0x35, 0x05, 0x11, 0xE3, \
+     0x0A, 0xBE, 0xC1, 0xFF, 0xF9, 0xE3, 0xA2, 0x6E, \
+     0x7F, 0xB2, 0x9F, 0x8C, 0x18, 0x30, 0x23, 0xC3, \
+     0x58, 0x7E, 0x38, 0xDA, 0x00, 0x77, 0xD9, 0xB4, \
+     0x76, 0x3E, 0x4E, 0x4B, 0x94, 0xB2, 0xBB, 0xC1, \
+     0x94, 0xC6, 0x65, 0x1E, 0x77, 0xCA, 0xF9, 0x92, \
+     0xEE, 0xAA, 0xC0, 0x23, 0x2A, 0x28, 0x1B, 0xF6, \
+     0xB3, 0xA7, 0x39, 0xC1, 0x22, 0x61, 0x16, 0x82, \
+     0x0A, 0xE8, 0xDB, 0x58, 0x47, 0xA6, 0x7C, 0xBE, \
+     0xF9, 0xC9, 0x09, 0x1B, 0x46, 0x2D, 0x53, 0x8C, \
+     0xD7, 0x2B, 0x03, 0x74, 0x6A, 0xE7, 0x7F, 0x5E, \
+     0x62, 0x29, 0x2C, 0x31, 0x15, 0x62, 0xA8, 0x46, \
+     0x50, 0x5D, 0xC8, 0x2D, 0xB8, 0x54, 0x33, 0x8A, \
+     0xE4, 0x9F, 0x52, 0x35, 0xC9, 0x5B, 0x91, 0x17, \
+     0x8C, 0xCF, 0x2D, 0xD5, 0xCA, 0xCE, 0xF4, 0x03, \
+     0xEC, 0x9D, 0x18, 0x10, 0xC6, 0x27, 0x2B, 0x04, \
+     0x5B, 0x3B, 0x71, 0xF9, 0xDC, 0x6B, 0x80, 0xD6, \
+     0x3F, 0xDD, 0x4A, 0x8E, 0x9A, 0xDB, 0x1E, 0x69, \
+     0x62, 0xA6, 0x95, 0x26, 0xD4, 0x31, 0x61, 0xC1, \
+     0xA4, 0x1D, 0x57, 0x0D, 0x79, 0x38, 0xDA, 0xD4, \
+     0xA4, 0x0E, 0x32, 0x9C, 0xCF, 0xF4, 0x6A, 0xAA, \
+     0x36, 0xAD, 0x00, 0x4C, 0xF6, 0x00, 0xC8, 0x38, \
+     0x1E, 0x42, 0x5A, 0x31, 0xD9, 0x51, 0xAE, 0x64, \
+     0xFD, 0xB2, 0x3F, 0xCE, 0xC9, 0x50, 0x9D, 0x43, \
+     0x68, 0x7F, 0xEB, 0x69, 0xED, 0xD1, 0xCC, 0x5E, \
+     0x0B, 0x8C, 0xC3, 0xBD, 0xF6, 0x4B, 0x10, 0xEF, \
+     0x86, 0xB6, 0x31, 0x42, 0xA3, 0xAB, 0x88, 0x29, \
+     0x55, 0x5B, 0x2F, 0x74, 0x7C, 0x93, 0x26, 0x65, \
+     0xCB, 0x2C, 0x0F, 0x1C, 0xC0, 0x1B, 0xD7, 0x02, \
+     0x29, 0x38, 0x88, 0x39, 0xD2, 0xAF, 0x05, 0xE4, \
+     0x54, 0x50, 0x4A, 0xC7, 0x8B, 0x75, 0x82, 0x82, \
+     0x28, 0x46, 0xC0, 0xBA, 0x35, 0xC3, 0x5F, 0x5C, \
+     0x59, 0x16, 0x0C, 0xC0, 0x46, 0xFD, 0x82, 0x51, \
+     0x54, 0x1F, 0xC6, 0x8C, 0x9C, 0x86, 0xB0, 0x22, \
+     0xBB, 0x70, 0x99, 0x87, 0x6A, 0x46, 0x0E, 0x74, \
+     0x51, 0xA8, 0xA9, 0x31, 0x09, 0x70, 0x3F, 0xEE, \
+     0x1C, 0x21, 0x7E, 0x6C, 0x38, 0x26, 0xE5, 0x2C, \
+     0x51, 0xAA, 0x69, 0x1E, 0x0E, 0x42, 0x3C, 0xFC, \
+     0x99, 0xE9, 0xE3, 0x16, 0x50, 0xC1, 0x21, 0x7B, \
+     0x62, 0x48, 0x16, 0xCD, 0xAD, 0x9A, 0x95, 0xF9, \
+     0xD5, 0xB8, 0x01, 0x94, 0x88, 0xD9, 0xC0, 0xA0, \
+     0xA1, 0xFE, 0x30, 0x75, 0xA5, 0x77, 0xE2, 0x31, \
+     0x83, 0xF8, 0x1D, 0x4A, 0x3F, 0x2F, 0xA4, 0x57, \
+     0x1E, 0xFC, 0x8C, 0xE0, 0xBA, 0x8A, 0x4F, 0xE8, \
+     0xB6, 0x85, 0x5D, 0xFE, 0x72, 0xB0, 0xA6, 0x6E, \
+     0xDE, 0xD2, 0xFB, 0xAB, 0xFB, 0xE5, 0x8A, 0x30, \
+     0xFA, 0xFA, 0xBE, 0x1C, 0x5D, 0x71, 0xA8, 0x7E, \
+     0x2F, 0x74, 0x1E, 0xF8, 0xC1, 0xFE, 0x86, 0xFE, \
+     0xA6, 0xBB, 0xFD, 0xE5, 0x30, 0x67, 0x7F, 0x0D, \
+     0x97, 0xD1, 0x1D, 0x49, 0xF7, 0xA8, 0x44, 0x3D, \
+     0x08, 0x22, 0xE5, 0x06, 0xA9, 0xF4, 0x61, 0x4E, \
+     0x01, 0x1E, 0x2A, 0x94, 0x83, 0x8F, 0xF8, 0x8C, \
+     0xD6, 0x8C, 0x8B, 0xB7, 0xC5, 0xC6, 0x42, 0x4C, \
+     0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE8192_G_BIN { 0x02 }
+
 #endif /* dhm.h */
 #endif /* dhm.h */

+ 157 - 88
mbedtls/include/mbedtls/ecdh.h

@@ -1,9 +1,18 @@
 /**
 /**
  * \file ecdh.h
  * \file ecdh.h
  *
  *
- * \brief Elliptic curve Diffie-Hellman
+ * \brief The Elliptic Curve Diffie-Hellman (ECDH) protocol APIs.
  *
  *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * ECDH is an anonymous key agreement protocol allowing two parties to
+ * establish a shared secret over an insecure channel. Each party must have an
+ * elliptic-curve public–private key pair.
+ *
+ * For more information, see <em>NIST SP 800-56A Rev. 2: Recommendation for
+ * Pair-Wise Key Establishment Schemes Using Discrete Logarithm
+ * Cryptography</em>.
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,11 +27,18 @@
  *  See the License for the specific language governing permissions and
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *  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_ECDH_H
 #ifndef MBEDTLS_ECDH_H
 #define MBEDTLS_ECDH_H
 #define MBEDTLS_ECDH_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include "ecp.h"
 #include "ecp.h"
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
@@ -30,7 +46,9 @@ extern "C" {
 #endif
 #endif
 
 
 /**
 /**
- * When importing from an EC key, select if it is our key or the peer's key
+ * Defines the source of the imported EC key:
+ * <ul><li>Our key.</li>
+ * <li>The key of the peer.</li></ul>
  */
  */
 typedef enum
 typedef enum
 {
 {
@@ -39,56 +57,67 @@ typedef enum
 } mbedtls_ecdh_side;
 } mbedtls_ecdh_side;
 
 
 /**
 /**
- * \brief           ECDH context structure
+ * \brief           The ECDH context structure.
  */
  */
 typedef struct
 typedef struct
 {
 {
-    mbedtls_ecp_group grp;      /*!<  elliptic curve used                           */
-    mbedtls_mpi d;              /*!<  our secret value (private key)                */
-    mbedtls_ecp_point Q;        /*!<  our public value (public key)                 */
-    mbedtls_ecp_point Qp;       /*!<  peer's public value (public key)              */
-    mbedtls_mpi z;              /*!<  shared secret                                 */
-    int point_format;   /*!<  format for point export in TLS messages       */
-    mbedtls_ecp_point Vi;       /*!<  blinding value (for later)                    */
-    mbedtls_ecp_point Vf;       /*!<  un-blinding value (for later)                 */
-    mbedtls_mpi _d;             /*!<  previous d (for later)                        */
+    mbedtls_ecp_group grp;   /*!< The elliptic curve used. */
+    mbedtls_mpi d;           /*!< The private key. */
+    mbedtls_ecp_point Q;     /*!< The public key. */
+    mbedtls_ecp_point Qp;    /*!< The value of the public key of the peer. */
+    mbedtls_mpi z;           /*!< The shared secret. */
+    int point_format;        /*!< The format of point export in TLS messages. */
+    mbedtls_ecp_point Vi;    /*!< The blinding value. */
+    mbedtls_ecp_point Vf;    /*!< The unblinding value. */
+    mbedtls_mpi _d;          /*!< The previous \p d. */
 }
 }
 mbedtls_ecdh_context;
 mbedtls_ecdh_context;
 
 
 /**
 /**
- * \brief           Generate a public key.
- *                  Raw function that only does the core computation.
+ * \brief           This function generates an ECDH keypair on an elliptic
+ *                  curve.
+ *
+ *                  This function performs the first of two core computations
+ *                  implemented during the ECDH key exchange. The second core
+ *                  computation is performed by mbedtls_ecdh_compute_shared().
  *
  *
- * \param grp       ECP group
- * \param d         Destination MPI (secret exponent, aka private key)
- * \param Q         Destination point (public key)
- * \param f_rng     RNG function
- * \param p_rng     RNG parameter
+ * \param grp       The ECP group.
+ * \param d         The destination MPI (private key).
+ * \param Q         The destination point (public key).
+ * \param f_rng     The RNG function.
+ * \param p_rng     The RNG parameter.
  *
  *
- * \return          0 if successful,
- *                  or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code
+ * \return          \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX or
+ *                  \c MBEDTLS_MPI_XXX error code on failure.
+ *
+ * \see             ecp.h
  */
  */
 int mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q,
 int mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q,
                      int (*f_rng)(void *, unsigned char *, size_t),
                      int (*f_rng)(void *, unsigned char *, size_t),
                      void *p_rng );
                      void *p_rng );
 
 
 /**
 /**
- * \brief           Compute shared secret
- *                  Raw function that only does the core computation.
+ * \brief           This function computes the shared secret.
+ *
+ *                  This function performs the second of two core computations
+ *                  implemented during the ECDH key exchange. The first core
+ *                  computation is performed by mbedtls_ecdh_gen_public().
+ *
+ * \param grp       The ECP group.
+ * \param z         The destination MPI (shared secret).
+ * \param Q         The public key from another party.
+ * \param d         Our secret exponent (private key).
+ * \param f_rng     The RNG function.
+ * \param p_rng     The RNG parameter.
  *
  *
- * \param grp       ECP group
- * \param z         Destination MPI (shared secret)
- * \param Q         Public key from other party
- * \param d         Our secret exponent (private key)
- * \param f_rng     RNG function (see notes)
- * \param p_rng     RNG parameter
+ * \return          \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX or
+ *                  \c MBEDTLS_MPI_XXX error code on failure.
  *
  *
- * \return          0 if successful,
- *                  or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code
+ * \see             ecp.h
  *
  *
- * \note            If f_rng is not NULL, it is used to implement
+ * \note            If \p f_rng is not NULL, it is used to implement
  *                  countermeasures against potential elaborate timing
  *                  countermeasures against potential elaborate timing
- *                  attacks, see \c mbedtls_ecp_mul() for details.
+ *                  attacks. For more information, see mbedtls_ecp_mul().
  */
  */
 int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z,
 int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z,
                          const mbedtls_ecp_point *Q, const mbedtls_mpi *d,
                          const mbedtls_ecp_point *Q, const mbedtls_mpi *d,
@@ -96,34 +125,41 @@ int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z,
                          void *p_rng );
                          void *p_rng );
 
 
 /**
 /**
- * \brief           Initialize context
+ * \brief           This function initializes an ECDH context.
  *
  *
- * \param ctx       Context to initialize
+ * \param ctx       The ECDH context to initialize.
  */
  */
 void mbedtls_ecdh_init( mbedtls_ecdh_context *ctx );
 void mbedtls_ecdh_init( mbedtls_ecdh_context *ctx );
 
 
 /**
 /**
- * \brief           Free context
+ * \brief           This function frees a context.
  *
  *
- * \param ctx       Context to free
+ * \param ctx       The context to free.
  */
  */
 void mbedtls_ecdh_free( mbedtls_ecdh_context *ctx );
 void mbedtls_ecdh_free( mbedtls_ecdh_context *ctx );
 
 
 /**
 /**
- * \brief           Generate a public key and a TLS ServerKeyExchange payload.
- *                  (First function used by a TLS server for ECDHE.)
+ * \brief           This function generates a public key and a TLS
+ *                  ServerKeyExchange payload.
  *
  *
- * \param ctx       ECDH context
- * \param olen      number of chars written
- * \param buf       destination buffer
- * \param blen      length of buffer
- * \param f_rng     RNG function
- * \param p_rng     RNG parameter
+ *                  This is the first function used by a TLS server for ECDHE
+ *                  ciphersuites.
  *
  *
- * \note            This function assumes that ctx->grp has already been
- *                  properly set (for example using mbedtls_ecp_group_load).
+ * \param ctx       The ECDH context.
+ * \param olen      The number of characters written.
+ * \param buf       The destination buffer.
+ * \param blen      The length of the destination buffer.
+ * \param f_rng     The RNG function.
+ * \param p_rng     The RNG parameter.
  *
  *
- * \return          0 if successful, or an MBEDTLS_ERR_ECP_XXX error code
+ * \note            This function assumes that the ECP group (grp) of the
+ *                  \p ctx context has already been properly set,
+ *                  for example, using mbedtls_ecp_group_load().
+ *
+ * \return          \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX error code
+ *                  on failure.
+ *
+ * \see             ecp.h
  */
  */
 int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen,
 int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen,
                       unsigned char *buf, size_t blen,
                       unsigned char *buf, size_t blen,
@@ -131,45 +167,63 @@ int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen,
                       void *p_rng );
                       void *p_rng );
 
 
 /**
 /**
- * \brief           Parse and procress a TLS ServerKeyExhange payload.
- *                  (First function used by a TLS client for ECDHE.)
+ * \brief           This function parses and processes a TLS ServerKeyExhange
+ *                  payload.
+ *
+ *                  This is the first function used by a TLS client for ECDHE
+ *                  ciphersuites.
  *
  *
- * \param ctx       ECDH context
- * \param buf       pointer to start of input buffer
- * \param end       one past end of buffer
+ * \param ctx       The ECDH context.
+ * \param buf       The pointer to the start of the input buffer.
+ * \param end       The address for one Byte past the end of the buffer.
  *
  *
- * \return          0 if successful, or an MBEDTLS_ERR_ECP_XXX error code
+ * \return          \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX error code
+ *                  on failure.
+ *
+ * \see             ecp.h
  */
  */
 int mbedtls_ecdh_read_params( mbedtls_ecdh_context *ctx,
 int mbedtls_ecdh_read_params( mbedtls_ecdh_context *ctx,
                       const unsigned char **buf, const unsigned char *end );
                       const unsigned char **buf, const unsigned char *end );
 
 
 /**
 /**
- * \brief           Setup an ECDH context from an EC key.
- *                  (Used by clients and servers in place of the
- *                  ServerKeyEchange for static ECDH: import ECDH parameters
- *                  from a certificate's EC key information.)
+ * \brief           This function sets up an ECDH context from an EC key.
+ *
+ *                  It is used by clients and servers in place of the
+ *                  ServerKeyEchange for static ECDH, and imports ECDH
+ *                  parameters from the EC key information of a certificate.
+ *
+ * \param ctx       The ECDH context to set up.
+ * \param key       The EC key to use.
+ * \param side      Defines the source of the key:
+ *                  <ul><li>1: Our key.</li>
+                    <li>0: The key of the peer.</li></ul>
  *
  *
- * \param ctx       ECDH constext to set
- * \param key       EC key to use
- * \param side      Is it our key (1) or the peer's key (0) ?
+ * \return          \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX error code
+ *                  on failure.
  *
  *
- * \return          0 if successful, or an MBEDTLS_ERR_ECP_XXX error code
+ * \see             ecp.h
  */
  */
 int mbedtls_ecdh_get_params( mbedtls_ecdh_context *ctx, const mbedtls_ecp_keypair *key,
 int mbedtls_ecdh_get_params( mbedtls_ecdh_context *ctx, const mbedtls_ecp_keypair *key,
                      mbedtls_ecdh_side side );
                      mbedtls_ecdh_side side );
 
 
 /**
 /**
- * \brief           Generate a public key and a TLS ClientKeyExchange payload.
- *                  (Second function used by a TLS client for ECDH(E).)
+ * \brief           This function generates a public key and a TLS
+ *                  ClientKeyExchange payload.
  *
  *
- * \param ctx       ECDH context
- * \param olen      number of bytes actually written
- * \param buf       destination buffer
- * \param blen      size of destination buffer
- * \param f_rng     RNG function
- * \param p_rng     RNG parameter
+ *                  This is the second function used by a TLS client for ECDH(E)
+ *                  ciphersuites.
  *
  *
- * \return          0 if successful, or an MBEDTLS_ERR_ECP_XXX error code
+ * \param ctx       The ECDH context.
+ * \param olen      The number of Bytes written.
+ * \param buf       The destination buffer.
+ * \param blen      The size of the destination buffer.
+ * \param f_rng     The RNG function.
+ * \param p_rng     The RNG parameter.
+ *
+ * \return          \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX error code
+ *                  on failure.
+ *
+ * \see             ecp.h
  */
  */
 int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen,
 int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen,
                       unsigned char *buf, size_t blen,
                       unsigned char *buf, size_t blen,
@@ -177,30 +231,45 @@ int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen,
                       void *p_rng );
                       void *p_rng );
 
 
 /**
 /**
- * \brief           Parse and process a TLS ClientKeyExchange payload.
- *                  (Second function used by a TLS server for ECDH(E).)
+ * \brief       This function parses and processes a TLS ClientKeyExchange
+ *              payload.
+ *
+ *              This is the second function used by a TLS server for ECDH(E)
+ *              ciphersuites.
  *
  *
- * \param ctx       ECDH context
- * \param buf       start of input buffer
- * \param blen      length of input buffer
+ * \param ctx   The ECDH context.
+ * \param buf   The start of the input buffer.
+ * \param blen  The length of the input buffer.
  *
  *
- * \return          0 if successful, or an MBEDTLS_ERR_ECP_XXX error code
+ * \return      \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX error code
+ *              on failure.
+ *
+ * \see         ecp.h
  */
  */
 int mbedtls_ecdh_read_public( mbedtls_ecdh_context *ctx,
 int mbedtls_ecdh_read_public( mbedtls_ecdh_context *ctx,
                       const unsigned char *buf, size_t blen );
                       const unsigned char *buf, size_t blen );
 
 
 /**
 /**
- * \brief           Derive and export the shared secret.
- *                  (Last function used by both TLS client en servers.)
+ * \brief           This function derives and exports the shared secret.
+ *
+ *                  This is the last function used by both TLS client
+ *                  and servers.
+ *
+ * \param ctx       The ECDH context.
+ * \param olen      The number of Bytes written.
+ * \param buf       The destination buffer.
+ * \param blen      The length of the destination buffer.
+ * \param f_rng     The RNG function.
+ * \param p_rng     The RNG parameter.
  *
  *
- * \param ctx       ECDH context
- * \param olen      number of bytes written
- * \param buf       destination buffer
- * \param blen      buffer length
- * \param f_rng     RNG function, see notes for \c mbedtls_ecdh_compute_shared()
- * \param p_rng     RNG parameter
+ * \return          \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX error code
+ *                  on failure.
  *
  *
- * \return          0 if successful, or an MBEDTLS_ERR_ECP_XXX error code
+ * \see             ecp.h
+ *
+ * \note            If \p f_rng is not NULL, it is used to implement
+ *                  countermeasures against potential elaborate timing
+ *                  attacks. For more information, see mbedtls_ecp_mul().
  */
  */
 int mbedtls_ecdh_calc_secret( mbedtls_ecdh_context *ctx, size_t *olen,
 int mbedtls_ecdh_calc_secret( mbedtls_ecdh_context *ctx, size_t *olen,
                       unsigned char *buf, size_t blen,
                       unsigned char *buf, size_t blen,

+ 180 - 112
mbedtls/include/mbedtls/ecdsa.h

@@ -1,9 +1,16 @@
 /**
 /**
  * \file ecdsa.h
  * \file ecdsa.h
  *
  *
- * \brief Elliptic curve DSA
+ * \brief The Elliptic Curve Digital Signature Algorithm (ECDSA).
  *
  *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * ECDSA is defined in <em>Standards for Efficient Cryptography Group (SECG):
+ * SEC1 Elliptic Curve Cryptography</em>.
+ * The use of ECDSA for TLS is defined in <em>RFC-4492: Elliptic Curve
+ * Cryptography (ECC) Cipher Suites for Transport Layer Security (TLS)</em>.
+ *
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,16 +25,23 @@
  *  See the License for the specific language governing permissions and
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *  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_ECDSA_H
 #ifndef MBEDTLS_ECDSA_H
 #define MBEDTLS_ECDSA_H
 #define MBEDTLS_ECDSA_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include "ecp.h"
 #include "ecp.h"
 #include "md.h"
 #include "md.h"
 
 
 /*
 /*
- * RFC 4492 page 20:
+ * RFC-4492 page 20:
  *
  *
  *     Ecdsa-Sig-Value ::= SEQUENCE {
  *     Ecdsa-Sig-Value ::= SEQUENCE {
  *         r       INTEGER,
  *         r       INTEGER,
@@ -43,11 +57,11 @@
 #if MBEDTLS_ECP_MAX_BYTES > 124
 #if MBEDTLS_ECP_MAX_BYTES > 124
 #error "MBEDTLS_ECP_MAX_BYTES bigger than expected, please fix MBEDTLS_ECDSA_MAX_LEN"
 #error "MBEDTLS_ECP_MAX_BYTES bigger than expected, please fix MBEDTLS_ECDSA_MAX_LEN"
 #endif
 #endif
-/** Maximum size of an ECDSA signature in bytes */
+/** The maximal size of an ECDSA signature in Bytes. */
 #define MBEDTLS_ECDSA_MAX_LEN  ( 3 + 2 * ( 3 + MBEDTLS_ECP_MAX_BYTES ) )
 #define MBEDTLS_ECDSA_MAX_LEN  ( 3 + 2 * ( 3 + MBEDTLS_ECP_MAX_BYTES ) )
 
 
 /**
 /**
- * \brief           ECDSA context structure
+ * \brief           The ECDSA context structure.
  */
  */
 typedef mbedtls_ecp_keypair mbedtls_ecdsa_context;
 typedef mbedtls_ecp_keypair mbedtls_ecdsa_context;
 
 
@@ -56,25 +70,30 @@ extern "C" {
 #endif
 #endif
 
 
 /**
 /**
- * \brief           Compute ECDSA signature of a previously hashed message
+ * \brief           This function computes the ECDSA signature of a
+ *                  previously-hashed message.
  *
  *
- * \note            The deterministic version is usually prefered.
+ * \note            The deterministic version is usually preferred.
  *
  *
- * \param grp       ECP group
- * \param r         First output integer
- * \param s         Second output integer
- * \param d         Private signing key
- * \param buf       Message hash
- * \param blen      Length of buf
- * \param f_rng     RNG function
- * \param p_rng     RNG parameter
+ * \param grp       The ECP group.
+ * \param r         The first output integer.
+ * \param s         The second output integer.
+ * \param d         The private signing key.
+ * \param buf       The message hash.
+ * \param blen      The length of \p buf.
+ * \param f_rng     The RNG function.
+ * \param p_rng     The RNG parameter.
  *
  *
  * \note            If the bitlength of the message hash is larger than the
  * \note            If the bitlength of the message hash is larger than the
- *                  bitlength of the group order, then the hash is truncated as
- *                  prescribed by SEC1 4.1.3 step 5.
+ *                  bitlength of the group order, then the hash is truncated
+ *                  as defined in <em>Standards for Efficient Cryptography Group
+ *                  (SECG): SEC1 Elliptic Curve Cryptography</em>, section
+ *                  4.1.3, step 5.
  *
  *
- * \return          0 if successful,
- *                  or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code
+ * \return          \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX
+ *                  or \c MBEDTLS_MPI_XXX error code on failure.
+ *
+ * \see             ecp.h
  */
  */
 int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
 int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
                 const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
                 const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
@@ -82,23 +101,31 @@ int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
 
 
 #if defined(MBEDTLS_ECDSA_DETERMINISTIC)
 #if defined(MBEDTLS_ECDSA_DETERMINISTIC)
 /**
 /**
- * \brief           Compute ECDSA signature of a previously hashed message,
- *                  deterministic version (RFC 6979).
- *
- * \param grp       ECP group
- * \param r         First output integer
- * \param s         Second output integer
- * \param d         Private signing key
- * \param buf       Message hash
- * \param blen      Length of buf
- * \param md_alg    MD algorithm used to hash the message
+ * \brief           This function computes the ECDSA signature of a
+ *                  previously-hashed message, deterministic version.
+ *                  For more information, see <em>RFC-6979: Deterministic
+ *                  Usage of the Digital Signature Algorithm (DSA) and Elliptic
+ *                  Curve Digital Signature Algorithm (ECDSA)</em>.
+ *
+ * \param grp       The ECP group.
+ * \param r         The first output integer.
+ * \param s         The second output integer.
+ * \param d         The private signing key.
+ * \param buf       The message hash.
+ * \param blen      The length of \p buf.
+ * \param md_alg    The MD algorithm used to hash the message.
  *
  *
  * \note            If the bitlength of the message hash is larger than the
  * \note            If the bitlength of the message hash is larger than the
  *                  bitlength of the group order, then the hash is truncated as
  *                  bitlength of the group order, then the hash is truncated as
- *                  prescribed by SEC1 4.1.3 step 5.
+ *                  defined in <em>Standards for Efficient Cryptography Group
+ *                  (SECG): SEC1 Elliptic Curve Cryptography</em>, section
+ *                  4.1.3, step 5.
  *
  *
- * \return          0 if successful,
- *                  or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code
+ * \return          \c 0 on success,
+ *                  or an \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX
+ *                  error code on failure.
+ *
+ * \see             ecp.h
  */
  */
 int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
 int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
                     const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
                     const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
@@ -106,55 +133,73 @@ int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi
 #endif /* MBEDTLS_ECDSA_DETERMINISTIC */
 #endif /* MBEDTLS_ECDSA_DETERMINISTIC */
 
 
 /**
 /**
- * \brief           Verify ECDSA signature of a previously hashed message
+ * \brief           This function verifies the ECDSA signature of a
+ *                  previously-hashed message.
  *
  *
- * \param grp       ECP group
- * \param buf       Message hash
- * \param blen      Length of buf
- * \param Q         Public key to use for verification
- * \param r         First integer of the signature
- * \param s         Second integer of the signature
+ * \param grp       The ECP group.
+ * \param buf       The message hash.
+ * \param blen      The length of \p buf.
+ * \param Q         The public key to use for verification.
+ * \param r         The first integer of the signature.
+ * \param s         The second integer of the signature.
  *
  *
  * \note            If the bitlength of the message hash is larger than the
  * \note            If the bitlength of the message hash is larger than the
  *                  bitlength of the group order, then the hash is truncated as
  *                  bitlength of the group order, then the hash is truncated as
- *                  prescribed by SEC1 4.1.4 step 3.
+ *                  defined in <em>Standards for Efficient Cryptography Group
+ *                  (SECG): SEC1 Elliptic Curve Cryptography</em>, section
+ *                  4.1.4, step 3.
+ *
+ * \return          \c 0 on success,
+ *                  #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid,
+ *                  or an \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX
+ *                  error code on failure for any other reason.
  *
  *
- * \return          0 if successful,
- *                  MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid
- *                  or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_MPI_XXX error code
+ * \see             ecp.h
  */
  */
 int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp,
 int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp,
                   const unsigned char *buf, size_t blen,
                   const unsigned char *buf, size_t blen,
                   const mbedtls_ecp_point *Q, const mbedtls_mpi *r, const mbedtls_mpi *s);
                   const mbedtls_ecp_point *Q, const mbedtls_mpi *r, const mbedtls_mpi *s);
 
 
 /**
 /**
- * \brief           Compute ECDSA signature and write it to buffer,
- *                  serialized as defined in RFC 4492 page 20.
- *                  (Not thread-safe to use same context in multiple threads)
- *
- * \note            The deterministic version (RFC 6979) is used if
- *                  MBEDTLS_ECDSA_DETERMINISTIC is defined.
- *
- * \param ctx       ECDSA context
- * \param md_alg    Algorithm that was used to hash the message
- * \param hash      Message hash
- * \param hlen      Length of hash
- * \param sig       Buffer that will hold the signature
- * \param slen      Length of the signature written
- * \param f_rng     RNG function
- * \param p_rng     RNG parameter
- *
- * \note            The "sig" buffer must be at least as large as twice the
- *                  size of the curve used, plus 9 (eg. 73 bytes if a 256-bit
- *                  curve is used). MBEDTLS_ECDSA_MAX_LEN is always safe.
+ * \brief           This function computes the ECDSA signature and writes it
+ *                  to a buffer, serialized as defined in <em>RFC-4492:
+ *                  Elliptic Curve Cryptography (ECC) Cipher Suites for
+ *                  Transport Layer Security (TLS)</em>.
+ *
+ * \warning         It is not thread-safe to use the same context in
+ *                  multiple threads.
+ *
+ * \note            The deterministic version is used if
+ *                  #MBEDTLS_ECDSA_DETERMINISTIC is defined. For more
+ *                  information, see <em>RFC-6979: Deterministic Usage
+ *                  of the Digital Signature Algorithm (DSA) and Elliptic
+ *                  Curve Digital Signature Algorithm (ECDSA)</em>.
+ *
+ * \param ctx       The ECDSA context.
+ * \param md_alg    The message digest that was used to hash the message.
+ * \param hash      The message hash.
+ * \param hlen      The length of the hash.
+ * \param sig       The buffer that holds the signature.
+ * \param slen      The length of the signature written.
+ * \param f_rng     The RNG function.
+ * \param p_rng     The RNG parameter.
+ *
+ * \note            The \p sig buffer must be at least twice as large as the
+ *                  size of the curve used, plus 9. For example, 73 Bytes if
+ *                  a 256-bit curve is used. A buffer length of
+ *                  #MBEDTLS_ECDSA_MAX_LEN is always safe.
  *
  *
  * \note            If the bitlength of the message hash is larger than the
  * \note            If the bitlength of the message hash is larger than the
  *                  bitlength of the group order, then the hash is truncated as
  *                  bitlength of the group order, then the hash is truncated as
- *                  prescribed by SEC1 4.1.3 step 5.
+ *                  defined in <em>Standards for Efficient Cryptography Group
+ *                  (SECG): SEC1 Elliptic Curve Cryptography</em>, section
+ *                  4.1.3, step 5.
+ *
+ * \return          \c 0 on success,
+ *                  or an \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or
+ *                  \c MBEDTLS_ERR_ASN1_XXX error code on failure.
  *
  *
- * \return          0 if successful,
- *                  or a MBEDTLS_ERR_ECP_XXX, MBEDTLS_ERR_MPI_XXX or
- *                  MBEDTLS_ERR_ASN1_XXX error code
+ * \see             ecp.h
  */
  */
 int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg,
 int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg,
                            const unsigned char *hash, size_t hlen,
                            const unsigned char *hash, size_t hlen,
@@ -170,31 +215,43 @@ int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t
 #define MBEDTLS_DEPRECATED
 #define MBEDTLS_DEPRECATED
 #endif
 #endif
 /**
 /**
- * \brief           Compute ECDSA signature and write it to buffer,
- *                  serialized as defined in RFC 4492 page 20.
- *                  Deterministic version, RFC 6979.
- *                  (Not thread-safe to use same context in multiple threads)
+ * \brief   This function computes an ECDSA signature and writes it to a buffer,
+ *          serialized as defined in <em>RFC-4492: Elliptic Curve Cryptography
+ *          (ECC) Cipher Suites for Transport Layer Security (TLS)</em>.
+ *
+ *          The deterministic version is defined in <em>RFC-6979:
+ *          Deterministic Usage of the Digital Signature Algorithm (DSA) and
+ *          Elliptic Curve Digital Signature Algorithm (ECDSA)</em>.
+ *
+ * \warning         It is not thread-safe to use the same context in
+ *                  multiple threads.
+
  *
  *
  * \deprecated      Superseded by mbedtls_ecdsa_write_signature() in 2.0.0
  * \deprecated      Superseded by mbedtls_ecdsa_write_signature() in 2.0.0
  *
  *
- * \param ctx       ECDSA context
- * \param hash      Message hash
- * \param hlen      Length of hash
- * \param sig       Buffer that will hold the signature
- * \param slen      Length of the signature written
- * \param md_alg    MD algorithm used to hash the message
+ * \param ctx       The ECDSA context.
+ * \param hash      The Message hash.
+ * \param hlen      The length of the hash.
+ * \param sig       The buffer that holds the signature.
+ * \param slen      The length of the signature written.
+ * \param md_alg    The MD algorithm used to hash the message.
  *
  *
- * \note            The "sig" buffer must be at least as large as twice the
- *                  size of the curve used, plus 9 (eg. 73 bytes if a 256-bit
- *                  curve is used). MBEDTLS_ECDSA_MAX_LEN is always safe.
+ * \note            The \p sig buffer must be at least twice as large as the
+ *                  size of the curve used, plus 9. For example, 73 Bytes if a
+ *                  256-bit curve is used. A buffer length of
+ *                  #MBEDTLS_ECDSA_MAX_LEN is always safe.
  *
  *
  * \note            If the bitlength of the message hash is larger than the
  * \note            If the bitlength of the message hash is larger than the
  *                  bitlength of the group order, then the hash is truncated as
  *                  bitlength of the group order, then the hash is truncated as
- *                  prescribed by SEC1 4.1.3 step 5.
+ *                  defined in <em>Standards for Efficient Cryptography Group
+ *                  (SECG): SEC1 Elliptic Curve Cryptography</em>, section
+ *                  4.1.3, step 5.
+ *
+ * \return          \c 0 on success,
+ *                  or an \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or
+ *                  \c MBEDTLS_ERR_ASN1_XXX error code on failure.
  *
  *
- * \return          0 if successful,
- *                  or a MBEDTLS_ERR_ECP_XXX, MBEDTLS_ERR_MPI_XXX or
- *                  MBEDTLS_ERR_ASN1_XXX error code
+ * \see             ecp.h
  */
  */
 int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx,
 int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx,
                                const unsigned char *hash, size_t hlen,
                                const unsigned char *hash, size_t hlen,
@@ -205,63 +262,74 @@ int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx,
 #endif /* MBEDTLS_ECDSA_DETERMINISTIC */
 #endif /* MBEDTLS_ECDSA_DETERMINISTIC */
 
 
 /**
 /**
- * \brief           Read and verify an ECDSA signature
+ * \brief           This function reads and verifies an ECDSA signature.
  *
  *
- * \param ctx       ECDSA context
- * \param hash      Message hash
- * \param hlen      Size of hash
- * \param sig       Signature to read and verify
- * \param slen      Size of sig
+ * \param ctx       The ECDSA context.
+ * \param hash      The message hash.
+ * \param hlen      The size of the hash.
+ * \param sig       The signature to read and verify.
+ * \param slen      The size of \p sig.
  *
  *
  * \note            If the bitlength of the message hash is larger than the
  * \note            If the bitlength of the message hash is larger than the
  *                  bitlength of the group order, then the hash is truncated as
  *                  bitlength of the group order, then the hash is truncated as
- *                  prescribed by SEC1 4.1.4 step 3.
- *
- * \return          0 if successful,
- *                  MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid,
- *                  MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if the signature is
- *                  valid but its actual length is less than siglen,
- *                  or a MBEDTLS_ERR_ECP_XXX or MBEDTLS_ERR_MPI_XXX error code
+ *                  defined in <em>Standards for Efficient Cryptography Group
+ *                  (SECG): SEC1 Elliptic Curve Cryptography</em>, section
+ *                  4.1.4, step 3.
+ *
+ * \return          \c 0 on success,
+ *                  #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid,
+ *                  #MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if there is a valid
+ *                  signature in sig but its length is less than \p siglen,
+ *                  or an \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_ERR_MPI_XXX
+ *                  error code on failure for any other reason.
+ *
+ * \see             ecp.h
  */
  */
 int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx,
 int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx,
                           const unsigned char *hash, size_t hlen,
                           const unsigned char *hash, size_t hlen,
                           const unsigned char *sig, size_t slen );
                           const unsigned char *sig, size_t slen );
 
 
 /**
 /**
- * \brief           Generate an ECDSA keypair on the given curve
+ * \brief          This function generates an ECDSA keypair on the given curve.
  *
  *
- * \param ctx       ECDSA context in which the keypair should be stored
- * \param gid       Group (elliptic curve) to use. One of the various
- *                  MBEDTLS_ECP_DP_XXX macros depending on configuration.
- * \param f_rng     RNG function
- * \param p_rng     RNG parameter
+ * \param ctx      The ECDSA context to store the keypair in.
+ * \param gid      The elliptic curve to use. One of the various
+ *                 \c MBEDTLS_ECP_DP_XXX macros depending on configuration.
+ * \param f_rng    The RNG function.
+ * \param p_rng    The RNG parameter.
  *
  *
- * \return          0 on success, or a MBEDTLS_ERR_ECP_XXX code.
+ * \return         \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX code on
+ *                 failure.
+ *
+ * \see            ecp.h
  */
  */
 int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid,
 int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid,
                   int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );
                   int (*f_rng)(void *, unsigned char *, size_t), void *p_rng );
 
 
 /**
 /**
- * \brief           Set an ECDSA context from an EC key pair
+ * \brief           This function sets an ECDSA context from an EC key pair.
+ *
+ * \param ctx       The ECDSA context to set.
+ * \param key       The EC key to use.
  *
  *
- * \param ctx       ECDSA context to set
- * \param key       EC key to use
+ * \return          \c 0 on success, or an \c MBEDTLS_ERR_ECP_XXX code on
+ *                  failure.
  *
  *
- * \return          0 on success, or a MBEDTLS_ERR_ECP_XXX code.
+ * \see             ecp.h
  */
  */
 int mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, const mbedtls_ecp_keypair *key );
 int mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, const mbedtls_ecp_keypair *key );
 
 
 /**
 /**
- * \brief           Initialize context
+ * \brief           This function initializes an ECDSA context.
  *
  *
- * \param ctx       Context to initialize
+ * \param ctx       The ECDSA context to initialize.
  */
  */
 void mbedtls_ecdsa_init( mbedtls_ecdsa_context *ctx );
 void mbedtls_ecdsa_init( mbedtls_ecdsa_context *ctx );
 
 
 /**
 /**
- * \brief           Free context
+ * \brief           This function frees an ECDSA context.
  *
  *
- * \param ctx       Context to free
+ * \param ctx       The ECDSA context to free.
  */
  */
 void mbedtls_ecdsa_free( mbedtls_ecdsa_context *ctx );
 void mbedtls_ecdsa_free( mbedtls_ecdsa_context *ctx );
 
 

+ 24 - 2
mbedtls/include/mbedtls/ecjpake.h

@@ -2,7 +2,8 @@
  * \file ecjpake.h
  * \file ecjpake.h
  *
  *
  * \brief Elliptic curve J-PAKE
  * \brief Elliptic curve J-PAKE
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -39,10 +40,17 @@
  * The payloads are serialized in a way suitable for use in TLS, but could
  * The payloads are serialized in a way suitable for use in TLS, but could
  * also be use outside TLS.
  * also be use outside TLS.
  */
  */
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
 
 
 #include "ecp.h"
 #include "ecp.h"
 #include "md.h"
 #include "md.h"
 
 
+#if !defined(MBEDTLS_ECJPAKE_ALT)
+
 #ifdef __cplusplus
 #ifdef __cplusplus
 extern "C" {
 extern "C" {
 #endif
 #endif
@@ -222,17 +230,31 @@ int mbedtls_ecjpake_derive_secret( mbedtls_ecjpake_context *ctx,
  */
  */
 void mbedtls_ecjpake_free( mbedtls_ecjpake_context *ctx );
 void mbedtls_ecjpake_free( mbedtls_ecjpake_context *ctx );
 
 
+#ifdef __cplusplus
+}
+#endif
+
+#else  /* MBEDTLS_ECJPAKE_ALT */
+#include "ecjpake_alt.h"
+#endif /* MBEDTLS_ECJPAKE_ALT */
+
 #if defined(MBEDTLS_SELF_TEST)
 #if defined(MBEDTLS_SELF_TEST)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 /**
 /**
  * \brief          Checkup routine
  * \brief          Checkup routine
  *
  *
  * \return         0 if successful, or 1 if a test failed
  * \return         0 if successful, or 1 if a test failed
  */
  */
 int mbedtls_ecjpake_self_test( int verbose );
 int mbedtls_ecjpake_self_test( int verbose );
-#endif
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
 }
 }
 #endif
 #endif
 
 
+#endif /* MBEDTLS_SELF_TEST */
+
 #endif /* ecjpake.h */
 #endif /* ecjpake.h */

+ 10 - 2
mbedtls/include/mbedtls/ecp.h

@@ -2,7 +2,8 @@
  * \file ecp.h
  * \file ecp.h
  *
  *
  * \brief Elliptic curves over GF(p)
  * \brief Elliptic curves over GF(p)
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -23,6 +24,12 @@
 #ifndef MBEDTLS_ECP_H
 #ifndef MBEDTLS_ECP_H
 #define MBEDTLS_ECP_H
 #define MBEDTLS_ECP_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include "bignum.h"
 #include "bignum.h"
 
 
 /*
 /*
@@ -35,7 +42,8 @@
 #define MBEDTLS_ERR_ECP_ALLOC_FAILED                      -0x4D80  /**< Memory allocation failed. */
 #define MBEDTLS_ERR_ECP_ALLOC_FAILED                      -0x4D80  /**< Memory allocation failed. */
 #define MBEDTLS_ERR_ECP_RANDOM_FAILED                     -0x4D00  /**< Generation of random value, such as (ephemeral) key, failed. */
 #define MBEDTLS_ERR_ECP_RANDOM_FAILED                     -0x4D00  /**< Generation of random value, such as (ephemeral) key, failed. */
 #define MBEDTLS_ERR_ECP_INVALID_KEY                       -0x4C80  /**< Invalid private or public key. */
 #define MBEDTLS_ERR_ECP_INVALID_KEY                       -0x4C80  /**< Invalid private or public key. */
-#define MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH                  -0x4C00  /**< Signature is valid but shorter than the user-supplied length. */
+#define MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH                  -0x4C00  /**< The buffer contains a valid signature followed by more data. */
+#define MBEDTLS_ERR_ECP_HW_ACCEL_FAILED                   -0x4B80  /**< ECP hardware accelerator failed. */
 
 
 #if !defined(MBEDTLS_ECP_ALT)
 #if !defined(MBEDTLS_ECP_ALT)
 /*
 /*

+ 9 - 2
mbedtls/include/mbedtls/ecp_internal.h

@@ -3,7 +3,8 @@
  *
  *
  * \brief Function declarations for alternative implementation of elliptic curve
  * \brief Function declarations for alternative implementation of elliptic curve
  * point arithmetic.
  * point arithmetic.
- *
+ */
+/*
  *  Copyright (C) 2016, ARM Limited, All Rights Reserved
  *  Copyright (C) 2016, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -47,7 +48,7 @@
  * [6] Digital Signature Standard (DSS), FIPS 186-4.
  * [6] Digital Signature Standard (DSS), FIPS 186-4.
  *     <http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf>
  *     <http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf>
  *
  *
- * [7] Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer 
+ * [7] Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer
  *     Security (TLS), RFC 4492.
  *     Security (TLS), RFC 4492.
  *     <https://tools.ietf.org/search/rfc4492>
  *     <https://tools.ietf.org/search/rfc4492>
  *
  *
@@ -60,6 +61,12 @@
 #ifndef MBEDTLS_ECP_INTERNAL_H
 #ifndef MBEDTLS_ECP_INTERNAL_H
 #define MBEDTLS_ECP_INTERNAL_H
 #define MBEDTLS_ECP_INTERNAL_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
 
 
 /**
 /**

+ 3 - 1
mbedtls/include/mbedtls/entropy.h

@@ -2,7 +2,8 @@
  * \file entropy.h
  * \file entropy.h
  *
  *
  * \brief Entropy accumulator implementation
  * \brief Entropy accumulator implementation
- *
+ */
+/*
  *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -121,6 +122,7 @@ mbedtls_entropy_source_state;
  */
  */
 typedef struct
 typedef struct
 {
 {
+    int accumulator_started;
 #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
 #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
     mbedtls_sha512_context  accumulator;
     mbedtls_sha512_context  accumulator;
 #else
 #else

+ 2 - 1
mbedtls/include/mbedtls/entropy_poll.h

@@ -2,7 +2,8 @@
  * \file entropy_poll.h
  * \file entropy_poll.h
  *
  *
  * \brief Platform-specific and custom entropy polling functions
  * \brief Platform-specific and custom entropy polling functions
- *
+ */
+/*
  *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *

+ 31 - 15
mbedtls/include/mbedtls/error.h

@@ -2,7 +2,8 @@
  * \file error.h
  * \file error.h
  *
  *
  * \brief Error to string translation
  * \brief Error to string translation
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -23,6 +24,12 @@
 #ifndef MBEDTLS_ERROR_H
 #ifndef MBEDTLS_ERROR_H
 #define MBEDTLS_ERROR_H
 #define MBEDTLS_ERROR_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include <stddef.h>
 #include <stddef.h>
 
 
 /**
 /**
@@ -49,23 +56,32 @@
  *
  *
  * Module   Nr  Codes assigned
  * Module   Nr  Codes assigned
  * MPI       7  0x0002-0x0010
  * MPI       7  0x0002-0x0010
- * GCM       2  0x0012-0x0014
- * BLOWFISH  2  0x0016-0x0018
+ * GCM       3  0x0012-0x0014   0x0013-0x0013
+ * BLOWFISH  3  0x0016-0x0018   0x0017-0x0017
  * THREADING 3  0x001A-0x001E
  * THREADING 3  0x001A-0x001E
- * AES       2  0x0020-0x0022
- * CAMELLIA  2  0x0024-0x0026
- * XTEA      1  0x0028-0x0028
+ * AES       4  0x0020-0x0022   0x0023-0x0025
+ * CAMELLIA  3  0x0024-0x0026   0x0027-0x0027
+ * XTEA      2  0x0028-0x0028   0x0029-0x0029
  * BASE64    2  0x002A-0x002C
  * BASE64    2  0x002A-0x002C
  * OID       1  0x002E-0x002E   0x000B-0x000B
  * OID       1  0x002E-0x002E   0x000B-0x000B
  * PADLOCK   1  0x0030-0x0030
  * PADLOCK   1  0x0030-0x0030
- * DES       1  0x0032-0x0032
+ * DES       2  0x0032-0x0032   0x0033-0x0033
  * CTR_DBRG  4  0x0034-0x003A
  * CTR_DBRG  4  0x0034-0x003A
  * ENTROPY   3  0x003C-0x0040   0x003D-0x003F
  * ENTROPY   3  0x003C-0x0040   0x003D-0x003F
  * NET      11  0x0042-0x0052   0x0043-0x0045
  * NET      11  0x0042-0x0052   0x0043-0x0045
  * ASN1      7  0x0060-0x006C
  * ASN1      7  0x0060-0x006C
+ * CMAC      1  0x007A-0x007A
  * PBKDF2    1  0x007C-0x007C
  * PBKDF2    1  0x007C-0x007C
- * HMAC_DRBG 4  0x0003-0x0009
- * CCM       2                  0x000D-0x000F
+ * HMAC_DRBG 4                  0x0003-0x0009
+ * CCM       3                  0x000D-0x0011
+ * ARC4      1                  0x0019-0x0019
+ * MD2       1                  0x002B-0x002B
+ * MD4       1                  0x002D-0x002D
+ * MD5       1                  0x002F-0x002F
+ * RIPEMD160 1                  0x0031-0x0031
+ * SHA1      1                  0x0035-0x0035
+ * SHA256    1                  0x0037-0x0037
+ * SHA512    1                  0x0039-0x0039
  *
  *
  * High-level module nr (3 bits - 0x0...-0x7...)
  * High-level module nr (3 bits - 0x0...-0x7...)
  * Name      ID  Nr of Errors
  * Name      ID  Nr of Errors
@@ -73,12 +89,12 @@
  * PKCS#12   1   4 (Started from top)
  * PKCS#12   1   4 (Started from top)
  * X509      2   20
  * X509      2   20
  * PKCS5     2   4 (Started from top)
  * PKCS5     2   4 (Started from top)
- * DHM       3   9
- * PK        3   14 (Started from top)
- * RSA       4   9
- * ECP       4   8 (Started from top)
- * MD        5   4
- * CIPHER    6   6
+ * DHM       3   11
+ * PK        3   15 (Started from top)
+ * RSA       4   11
+ * ECP       4   9 (Started from top)
+ * MD        5   5
+ * CIPHER    6   8
  * SSL       6   17 (Started from top)
  * SSL       6   17 (Started from top)
  * SSL       7   31
  * SSL       7   31
  *
  *

+ 161 - 86
mbedtls/include/mbedtls/gcm.h

@@ -1,9 +1,16 @@
 /**
 /**
  * \file gcm.h
  * \file gcm.h
  *
  *
- * \brief Galois/Counter mode for 128-bit block ciphers
+ * \brief Galois/Counter Mode (GCM) for 128-bit block ciphers, as defined
+ *        in <em>D. McGrew, J. Viega, The Galois/Counter Mode of Operation
+ *        (GCM), Natl. Inst. Stand. Technol.</em>
  *
  *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * For more information on GCM, see <em>NIST SP 800-38D: Recommendation for
+ * Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC</em>.
+ *
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,11 +25,18 @@
  *  See the License for the specific language governing permissions and
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *  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_GCM_H
 #ifndef MBEDTLS_GCM_H
 #define MBEDTLS_GCM_H
 #define MBEDTLS_GCM_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include "cipher.h"
 #include "cipher.h"
 
 
 #include <stdint.h>
 #include <stdint.h>
@@ -31,46 +45,59 @@
 #define MBEDTLS_GCM_DECRYPT     0
 #define MBEDTLS_GCM_DECRYPT     0
 
 
 #define MBEDTLS_ERR_GCM_AUTH_FAILED                       -0x0012  /**< Authenticated decryption failed. */
 #define MBEDTLS_ERR_GCM_AUTH_FAILED                       -0x0012  /**< Authenticated decryption failed. */
+#define MBEDTLS_ERR_GCM_HW_ACCEL_FAILED                   -0x0013  /**< GCM hardware accelerator failed. */
 #define MBEDTLS_ERR_GCM_BAD_INPUT                         -0x0014  /**< Bad input parameters to function. */
 #define MBEDTLS_ERR_GCM_BAD_INPUT                         -0x0014  /**< Bad input parameters to function. */
 
 
+#if !defined(MBEDTLS_GCM_ALT)
+
 #ifdef __cplusplus
 #ifdef __cplusplus
 extern "C" {
 extern "C" {
 #endif
 #endif
 
 
 /**
 /**
- * \brief          GCM context structure
+ * \brief          The GCM context structure.
  */
  */
 typedef struct {
 typedef struct {
-    mbedtls_cipher_context_t cipher_ctx;/*!< cipher context used */
-    uint64_t HL[16];            /*!< Precalculated HTable */
-    uint64_t HH[16];            /*!< Precalculated HTable */
-    uint64_t len;               /*!< Total data length */
-    uint64_t add_len;           /*!< Total add length */
-    unsigned char base_ectr[16];/*!< First ECTR for tag */
-    unsigned char y[16];        /*!< Y working value */
-    unsigned char buf[16];      /*!< buf working value */
-    int mode;                   /*!< Encrypt or Decrypt */
+    mbedtls_cipher_context_t cipher_ctx;  /*!< The cipher context used. */
+    uint64_t HL[16];                      /*!< Precalculated HTable low. */
+    uint64_t HH[16];                      /*!< Precalculated HTable high. */
+    uint64_t len;                         /*!< The total length of the encrypted data. */
+    uint64_t add_len;                     /*!< The total length of the additional data. */
+    unsigned char base_ectr[16];          /*!< The first ECTR for tag. */
+    unsigned char y[16];                  /*!< The Y working value. */
+    unsigned char buf[16];                /*!< The buf working value. */
+    int mode;                             /*!< The operation to perform:
+                                               #MBEDTLS_GCM_ENCRYPT or
+                                               #MBEDTLS_GCM_DECRYPT. */
 }
 }
 mbedtls_gcm_context;
 mbedtls_gcm_context;
 
 
 /**
 /**
- * \brief           Initialize GCM context (just makes references valid)
- *                  Makes the context ready for mbedtls_gcm_setkey() or
- *                  mbedtls_gcm_free().
+ * \brief           This function initializes the specified GCM context,
+ *                  to make references valid, and prepares the context
+ *                  for mbedtls_gcm_setkey() or mbedtls_gcm_free().
  *
  *
- * \param ctx       GCM context to initialize
+ *                  The function does not bind the GCM context to a particular
+ *                  cipher, nor set the key. For this purpose, use
+ *                  mbedtls_gcm_setkey().
+ *
+ * \param ctx       The GCM context to initialize.
  */
  */
 void mbedtls_gcm_init( mbedtls_gcm_context *ctx );
 void mbedtls_gcm_init( mbedtls_gcm_context *ctx );
 
 
 /**
 /**
- * \brief           GCM initialization (encryption)
+ * \brief           This function associates a GCM context with a
+ *                  cipher algorithm and a key.
  *
  *
- * \param ctx       GCM context to be initialized
- * \param cipher    cipher to use (a 128-bit block cipher)
- * \param key       encryption key
- * \param keybits   must be 128, 192 or 256
+ * \param ctx       The GCM context to initialize.
+ * \param cipher    The 128-bit block cipher to use.
+ * \param key       The encryption key.
+ * \param keybits   The key size in bits. Valid options are:
+ *                  <ul><li>128 bits</li>
+ *                  <li>192 bits</li>
+ *                  <li>256 bits</li></ul>
  *
  *
- * \return          0 if successful, or a cipher specific error code
+ * \return          \c 0 on success, or a cipher specific error code.
  */
  */
 int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx,
 int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx,
                         mbedtls_cipher_id_t cipher,
                         mbedtls_cipher_id_t cipher,
@@ -78,26 +105,48 @@ int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx,
                         unsigned int keybits );
                         unsigned int keybits );
 
 
 /**
 /**
- * \brief           GCM buffer encryption/decryption using a block cipher
+ * \brief           This function performs GCM encryption or decryption of a buffer.
  *
  *
- * \note On encryption, the output buffer can be the same as the input buffer.
- *       On decryption, the output buffer cannot be the same as input buffer.
- *       If buffers overlap, the output buffer must trail at least 8 bytes
+ * \note For encryption, the output buffer can be the same as the input buffer.
+ *       For decryption, the output buffer cannot be the same as input buffer.
+ *       If the buffers overlap, the output buffer must trail at least 8 Bytes
  *       behind the input buffer.
  *       behind the input buffer.
  *
  *
- * \param ctx       GCM context
- * \param mode      MBEDTLS_GCM_ENCRYPT or MBEDTLS_GCM_DECRYPT
- * \param length    length of the input data
- * \param iv        initialization vector
- * \param iv_len    length of IV
- * \param add       additional data
- * \param add_len   length of additional data
- * \param input     buffer holding the input data
- * \param output    buffer for holding the output data
- * \param tag_len   length of the tag to generate
- * \param tag       buffer for holding the tag
- *
- * \return         0 if successful
+ * \warning         When this function performs a decryption, it outputs the
+ *                  authentication tag and does not verify that the data is
+ *                  authentic. You should use this function to perform encryption
+ *                  only. For decryption, use mbedtls_gcm_auth_decrypt() instead.
+ *
+ * \param ctx       The GCM context to use for encryption or decryption.
+ * \param mode      The operation to perform:
+ *                  - #MBEDTLS_GCM_ENCRYPT to perform authenticated encryption.
+ *                    The ciphertext is written to \p output and the
+ *                    authentication tag is written to \p tag.
+ *                  - #MBEDTLS_GCM_DECRYPT to perform decryption.
+ *                    The plaintext is written to \p output and the
+ *                    authentication tag is written to \p tag.
+ *                    Note that this mode is not recommended, because it does
+ *                    not verify the authenticity of the data. For this reason,
+ *                    you should use mbedtls_gcm_auth_decrypt() instead of
+ *                    calling this function in decryption mode.
+ * \param length    The length of the input data, which is equal to the length
+ *                  of the output data.
+ * \param iv        The initialization vector.
+ * \param iv_len    The length of the IV.
+ * \param add       The buffer holding the additional data.
+ * \param add_len   The length of the additional data.
+ * \param input     The buffer holding the input data. Its size is \b length.
+ * \param output    The buffer for holding the output data. It must have room
+ *                  for \b length bytes.
+ * \param tag_len   The length of the tag to generate.
+ * \param tag       The buffer for holding the tag.
+ *
+ * \return          \c 0 if the encryption or decryption was performed
+ *                  successfully. Note that in #MBEDTLS_GCM_DECRYPT mode,
+ *                  this does not indicate that the data is authentic.
+ * \return          #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths are not valid.
+ * \return          #MBEDTLS_ERR_GCM_HW_ACCEL_FAILED or a cipher-specific
+ *                  error code if the encryption or decryption failed.
  */
  */
 int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx,
 int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx,
                        int mode,
                        int mode,
@@ -112,25 +161,31 @@ int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx,
                        unsigned char *tag );
                        unsigned char *tag );
 
 
 /**
 /**
- * \brief           GCM buffer authenticated decryption using a block cipher
+ * \brief           This function performs a GCM authenticated decryption of a
+ *                  buffer.
  *
  *
- * \note On decryption, the output buffer cannot be the same as input buffer.
- *       If buffers overlap, the output buffer must trail at least 8 bytes
+ * \note For decryption, the output buffer cannot be the same as input buffer.
+ *       If the buffers overlap, the output buffer must trail at least 8 Bytes
  *       behind the input buffer.
  *       behind the input buffer.
  *
  *
- * \param ctx       GCM context
- * \param length    length of the input data
- * \param iv        initialization vector
- * \param iv_len    length of IV
- * \param add       additional data
- * \param add_len   length of additional data
- * \param tag       buffer holding the tag
- * \param tag_len   length of the tag
- * \param input     buffer holding the input data
- * \param output    buffer for holding the output data
- *
- * \return         0 if successful and authenticated,
- *                 MBEDTLS_ERR_GCM_AUTH_FAILED if tag does not match
+ * \param ctx       The GCM context.
+ * \param length    The length of the ciphertext to decrypt, which is also
+ *                  the length of the decrypted plaintext.
+ * \param iv        The initialization vector.
+ * \param iv_len    The length of the IV.
+ * \param add       The buffer holding the additional data.
+ * \param add_len   The length of the additional data.
+ * \param tag       The buffer holding the tag to verify.
+ * \param tag_len   The length of the tag to verify.
+ * \param input     The buffer holding the ciphertext. Its size is \b length.
+ * \param output    The buffer for holding the decrypted plaintext. It must
+ *                  have room for \b length bytes.
+ *
+ * \return          \c 0 if successful and authenticated.
+ * \return          #MBEDTLS_ERR_GCM_AUTH_FAILED if the tag does not match.
+ * \return          #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths are not valid.
+ * \return          #MBEDTLS_ERR_GCM_HW_ACCEL_FAILED or a cipher-specific
+ *                  error code if the decryption failed.
  */
  */
 int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx,
 int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx,
                       size_t length,
                       size_t length,
@@ -144,16 +199,18 @@ int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx,
                       unsigned char *output );
                       unsigned char *output );
 
 
 /**
 /**
- * \brief           Generic GCM stream start function
+ * \brief           This function starts a GCM encryption or decryption
+ *                  operation.
  *
  *
- * \param ctx       GCM context
- * \param mode      MBEDTLS_GCM_ENCRYPT or MBEDTLS_GCM_DECRYPT
- * \param iv        initialization vector
- * \param iv_len    length of IV
- * \param add       additional data (or NULL if length is 0)
- * \param add_len   length of additional data
+ * \param ctx       The GCM context.
+ * \param mode      The operation to perform: #MBEDTLS_GCM_ENCRYPT or
+ *                  #MBEDTLS_GCM_DECRYPT.
+ * \param iv        The initialization vector.
+ * \param iv_len    The length of the IV.
+ * \param add       The buffer holding the additional data, or NULL if \p add_len is 0.
+ * \param add_len   The length of the additional data. If 0, \p  add is NULL.
  *
  *
- * \return         0 if successful
+ * \return         \c 0 on success.
  */
  */
 int mbedtls_gcm_starts( mbedtls_gcm_context *ctx,
 int mbedtls_gcm_starts( mbedtls_gcm_context *ctx,
                 int mode,
                 int mode,
@@ -163,21 +220,23 @@ int mbedtls_gcm_starts( mbedtls_gcm_context *ctx,
                 size_t add_len );
                 size_t add_len );
 
 
 /**
 /**
- * \brief           Generic GCM update function. Encrypts/decrypts using the
- *                  given GCM context. Expects input to be a multiple of 16
- *                  bytes! Only the last call before mbedtls_gcm_finish() can be less
- *                  than 16 bytes!
+ * \brief           This function feeds an input buffer into an ongoing GCM
+ *                  encryption or decryption operation.
+ *
+ *    `             The function expects input to be a multiple of 16
+ *                  Bytes. Only the last call before calling
+ *                  mbedtls_gcm_finish() can be less than 16 Bytes.
  *
  *
- * \note On decryption, the output buffer cannot be the same as input buffer.
- *       If buffers overlap, the output buffer must trail at least 8 bytes
+ * \note For decryption, the output buffer cannot be the same as input buffer.
+ *       If the buffers overlap, the output buffer must trail at least 8 Bytes
  *       behind the input buffer.
  *       behind the input buffer.
  *
  *
- * \param ctx       GCM context
- * \param length    length of the input data
- * \param input     buffer holding the input data
- * \param output    buffer for holding the output data
+ * \param ctx       The GCM context.
+ * \param length    The length of the input data. This must be a multiple of 16 except in the last call before mbedtls_gcm_finish().
+ * \param input     The buffer holding the input data.
+ * \param output    The buffer for holding the output data.
  *
  *
- * \return         0 if successful or MBEDTLS_ERR_GCM_BAD_INPUT
+ * \return         \c 0 on success, or #MBEDTLS_ERR_GCM_BAD_INPUT on failure.
  */
  */
 int mbedtls_gcm_update( mbedtls_gcm_context *ctx,
 int mbedtls_gcm_update( mbedtls_gcm_context *ctx,
                 size_t length,
                 size_t length,
@@ -185,31 +244,46 @@ int mbedtls_gcm_update( mbedtls_gcm_context *ctx,
                 unsigned char *output );
                 unsigned char *output );
 
 
 /**
 /**
- * \brief           Generic GCM finalisation function. Wraps up the GCM stream
- *                  and generates the tag. The tag can have a maximum length of
- *                  16 bytes.
+ * \brief           This function finishes the GCM operation and generates
+ *                  the authentication tag.
  *
  *
- * \param ctx       GCM context
- * \param tag       buffer for holding the tag
- * \param tag_len   length of the tag to generate (must be at least 4)
+ *                  It wraps up the GCM stream, and generates the
+ *                  tag. The tag can have a maximum length of 16 Bytes.
  *
  *
- * \return          0 if successful or MBEDTLS_ERR_GCM_BAD_INPUT
+ * \param ctx       The GCM context.
+ * \param tag       The buffer for holding the tag.
+ * \param tag_len   The length of the tag to generate. Must be at least four.
+ *
+ * \return          \c 0 on success, or #MBEDTLS_ERR_GCM_BAD_INPUT on failure.
  */
  */
 int mbedtls_gcm_finish( mbedtls_gcm_context *ctx,
 int mbedtls_gcm_finish( mbedtls_gcm_context *ctx,
                 unsigned char *tag,
                 unsigned char *tag,
                 size_t tag_len );
                 size_t tag_len );
 
 
 /**
 /**
- * \brief           Free a GCM context and underlying cipher sub-context
+ * \brief           This function clears a GCM context and the underlying
+ *                  cipher sub-context.
  *
  *
- * \param ctx       GCM context to free
+ * \param ctx       The GCM context to clear.
  */
  */
 void mbedtls_gcm_free( mbedtls_gcm_context *ctx );
 void mbedtls_gcm_free( mbedtls_gcm_context *ctx );
 
 
+#ifdef __cplusplus
+}
+#endif
+
+#else  /* !MBEDTLS_GCM_ALT */
+#include "gcm_alt.h"
+#endif /* !MBEDTLS_GCM_ALT */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 /**
 /**
- * \brief          Checkup routine
+ * \brief          The GCM checkup routine.
  *
  *
- * \return         0 if successful, or 1 if the test failed
+ * \return         \c 0 on success, or \c 1 on failure.
  */
  */
 int mbedtls_gcm_self_test( int verbose );
 int mbedtls_gcm_self_test( int verbose );
 
 
@@ -217,4 +291,5 @@ int mbedtls_gcm_self_test( int verbose );
 }
 }
 #endif
 #endif
 
 
+
 #endif /* gcm.h */
 #endif /* gcm.h */

+ 8 - 1
mbedtls/include/mbedtls/havege.h

@@ -2,7 +2,8 @@
  * \file havege.h
  * \file havege.h
  *
  *
  * \brief HAVEGE: HArdware Volatile Entropy Gathering and Expansion
  * \brief HAVEGE: HArdware Volatile Entropy Gathering and Expansion
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -23,6 +24,12 @@
 #ifndef MBEDTLS_HAVEGE_H
 #ifndef MBEDTLS_HAVEGE_H
 #define MBEDTLS_HAVEGE_H
 #define MBEDTLS_HAVEGE_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include <stddef.h>
 #include <stddef.h>
 
 
 #define MBEDTLS_HAVEGE_COLLECT_SIZE 1024
 #define MBEDTLS_HAVEGE_COLLECT_SIZE 1024

+ 30 - 3
mbedtls/include/mbedtls/hmac_drbg.h

@@ -2,7 +2,8 @@
  * \file hmac_drbg.h
  * \file hmac_drbg.h
  *
  *
  * \brief HMAC_DRBG (NIST SP 800-90A)
  * \brief HMAC_DRBG (NIST SP 800-90A)
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -23,10 +24,16 @@
 #ifndef MBEDTLS_HMAC_DRBG_H
 #ifndef MBEDTLS_HMAC_DRBG_H
 #define MBEDTLS_HMAC_DRBG_H
 #define MBEDTLS_HMAC_DRBG_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include "md.h"
 #include "md.h"
 
 
 #if defined(MBEDTLS_THREADING_C)
 #if defined(MBEDTLS_THREADING_C)
-#include "mbedtls/threading.h"
+#include "threading.h"
 #endif
 #endif
 
 
 /*
 /*
@@ -194,12 +201,32 @@ void mbedtls_hmac_drbg_set_reseed_interval( mbedtls_hmac_drbg_context *ctx,
  * \param additional    Additional data to update state with, or NULL
  * \param additional    Additional data to update state with, or NULL
  * \param add_len       Length of additional data, or 0
  * \param add_len       Length of additional data, or 0
  *
  *
+ * \return              \c 0 on success, or an error from the underlying
+ *                      hash calculation.
+ *
  * \note                Additional data is optional, pass NULL and 0 as second
  * \note                Additional data is optional, pass NULL and 0 as second
  *                      third argument if no additional data is being used.
  *                      third argument if no additional data is being used.
  */
  */
-void mbedtls_hmac_drbg_update( mbedtls_hmac_drbg_context *ctx,
+int mbedtls_hmac_drbg_update_ret( mbedtls_hmac_drbg_context *ctx,
                        const unsigned char *additional, size_t add_len );
                        const unsigned char *additional, size_t add_len );
 
 
+/**
+ * \brief               HMAC_DRBG update state
+ *
+ * \warning             This function cannot report errors. You should use
+ *                      mbedtls_hmac_drbg_update_ret() instead.
+ *
+ * \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.
+ */
+void mbedtls_hmac_drbg_update( mbedtls_hmac_drbg_context *ctx,
+                               const unsigned char *additional,
+                               size_t add_len );
+
 /**
 /**
  * \brief               HMAC_DRBG reseeding (extracts data from entropy source)
  * \brief               HMAC_DRBG reseeding (extracts data from entropy source)
  *
  *

+ 235 - 136
mbedtls/include/mbedtls/md.h

@@ -1,11 +1,12 @@
-/**
+ /**
  * \file md.h
  * \file md.h
  *
  *
- * \brief Generic message digest wrapper
+ * \brief The generic message-digest wrapper.
  *
  *
  * \author Adriaan de Jong <dejong@fox-it.com>
  * \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
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -20,22 +21,38 @@
  *  See the License for the specific language governing permissions and
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *  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_H
 #ifndef MBEDTLS_MD_H
 #define MBEDTLS_MD_H
 #define MBEDTLS_MD_H
 
 
 #include <stddef.h>
 #include <stddef.h>
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #define MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE                -0x5080  /**< The selected feature is not available. */
 #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_BAD_INPUT_DATA                     -0x5100  /**< Bad input parameters to function. */
 #define MBEDTLS_ERR_MD_ALLOC_FAILED                       -0x5180  /**< Failed to allocate memory. */
 #define MBEDTLS_ERR_MD_ALLOC_FAILED                       -0x5180  /**< Failed to allocate memory. */
 #define MBEDTLS_ERR_MD_FILE_IO_ERROR                      -0x5200  /**< Opening or reading of file failed. */
 #define MBEDTLS_ERR_MD_FILE_IO_ERROR                      -0x5200  /**< Opening or reading of file failed. */
+#define MBEDTLS_ERR_MD_HW_ACCEL_FAILED                    -0x5280  /**< MD hardware accelerator failed. */
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
 extern "C" {
 extern "C" {
 #endif
 #endif
 
 
+/**
+ * \brief     Enumeration of supported message digests
+ *
+ * \warning   MD2, MD4, MD5 and SHA-1 are considered weak message digests and
+ *            their use constitutes a security risk. We recommend considering
+ *            stronger message digests instead.
+ *
+ */
 typedef enum {
 typedef enum {
     MBEDTLS_MD_NONE=0,
     MBEDTLS_MD_NONE=0,
     MBEDTLS_MD_MD2,
     MBEDTLS_MD_MD2,
@@ -56,65 +73,79 @@ typedef enum {
 #endif
 #endif
 
 
 /**
 /**
- * Opaque struct defined in md_internal.h
+ * Opaque struct defined in md_internal.h.
  */
  */
 typedef struct mbedtls_md_info_t mbedtls_md_info_t;
 typedef struct mbedtls_md_info_t mbedtls_md_info_t;
 
 
 /**
 /**
- * Generic message digest context.
+ * The generic message-digest context.
  */
  */
 typedef struct {
 typedef struct {
-    /** Information about the associated message digest */
+    /** Information about the associated message digest. */
     const mbedtls_md_info_t *md_info;
     const mbedtls_md_info_t *md_info;
 
 
-    /** Digest-specific context */
+    /** The digest-specific context. */
     void *md_ctx;
     void *md_ctx;
 
 
-    /** HMAC part of the context */
+    /** The HMAC part of the context. */
     void *hmac_ctx;
     void *hmac_ctx;
 } mbedtls_md_context_t;
 } mbedtls_md_context_t;
 
 
 /**
 /**
- * \brief Returns the list of digests supported by the generic digest module.
+ * \brief           This function returns the list of digests supported by the
+ *                  generic digest module.
  *
  *
- * \return          a statically allocated array of digests, the last entry
- *                  is 0.
+ * \return          A statically allocated array of digests. Each element
+ *                  in the returned list is an integer belonging to the
+ *                  message-digest enumeration #mbedtls_md_type_t.
+ *                  The last entry is 0.
  */
  */
 const int *mbedtls_md_list( void );
 const int *mbedtls_md_list( void );
 
 
 /**
 /**
- * \brief           Returns the message digest information associated with the
- *                  given digest name.
+ * \brief           This function returns the message-digest information
+ *                  associated with the given digest name.
  *
  *
- * \param md_name   Name of the digest to search for.
+ * \param md_name   The name of the digest to search for.
  *
  *
- * \return          The message digest information associated with md_name or
- *                  NULL if not found.
+ * \return          The message-digest information associated with \p md_name,
+ *                  or NULL if not found.
  */
  */
 const mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name );
 const mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name );
 
 
 /**
 /**
- * \brief           Returns the message digest information associated with the
- *                  given digest type.
+ * \brief           This function returns the message-digest information
+ *                  associated with the given digest type.
  *
  *
- * \param md_type   type of digest to search for.
+ * \param md_type   The type of digest to search for.
  *
  *
- * \return          The message digest information associated with md_type or
- *                  NULL if not found.
+ * \return          The message-digest information associated with \p md_type,
+ *                  or NULL if not found.
  */
  */
 const mbedtls_md_info_t *mbedtls_md_info_from_type( mbedtls_md_type_t md_type );
 const mbedtls_md_info_t *mbedtls_md_info_from_type( mbedtls_md_type_t md_type );
 
 
 /**
 /**
- * \brief           Initialize a md_context (as NONE)
- *                  This should always be called first.
- *                  Prepares the context for mbedtls_md_setup() or mbedtls_md_free().
+ * \brief           This function initializes a message-digest context without
+ *                  binding it to a particular message-digest algorithm.
+ *
+ *                  This function should always be called first. It prepares the
+ *                  context for mbedtls_md_setup() for binding it to a
+ *                  message-digest algorithm.
  */
  */
 void mbedtls_md_init( mbedtls_md_context_t *ctx );
 void mbedtls_md_init( mbedtls_md_context_t *ctx );
 
 
 /**
 /**
- * \brief           Free and clear the internal structures of ctx.
- *                  Can be called at any time after mbedtls_md_init().
- *                  Mandatory once mbedtls_md_setup() has been called.
+ * \brief           This function clears the internal structure of \p ctx and
+ *                  frees any embedded internal structure, but does not free
+ *                  \p ctx itself.
+ *
+ *                  If you have called mbedtls_md_setup() on \p ctx, you must
+ *                  call mbedtls_md_free() when you are no longer using the
+ *                  context.
+ *                  Calling this function if you have previously
+ *                  called mbedtls_md_init() and nothing else is optional.
+ *                  You must not call this function if you have not called
+ *                  mbedtls_md_init().
  */
  */
 void mbedtls_md_free( mbedtls_md_context_t *ctx );
 void mbedtls_md_free( mbedtls_md_context_t *ctx );
 
 
@@ -125,220 +156,288 @@ void mbedtls_md_free( mbedtls_md_context_t *ctx );
 #define MBEDTLS_DEPRECATED
 #define MBEDTLS_DEPRECATED
 #endif
 #endif
 /**
 /**
- * \brief           Select MD to use and allocate internal structures.
- *                  Should be called after mbedtls_md_init() or mbedtls_md_free().
+ * \brief           This function selects the message digest algorithm to use,
+ *                  and allocates internal structures.
+ *
+ *                  It should be called after mbedtls_md_init() or mbedtls_md_free().
  *                  Makes it necessary to call mbedtls_md_free() later.
  *                  Makes it necessary to call mbedtls_md_free() later.
  *
  *
  * \deprecated      Superseded by mbedtls_md_setup() in 2.0.0
  * \deprecated      Superseded by mbedtls_md_setup() in 2.0.0
  *
  *
- * \param ctx       Context to set up.
- * \param md_info   Message digest to use.
+ * \param ctx       The context to set up.
+ * \param md_info   The information structure of the message-digest algorithm
+ *                  to use.
  *
  *
  * \returns         \c 0 on success,
  * \returns         \c 0 on success,
- *                  \c MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure,
- *                  \c MBEDTLS_ERR_MD_ALLOC_FAILED memory allocation failure.
+ *                  #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure,
+ *                  #MBEDTLS_ERR_MD_ALLOC_FAILED 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, const mbedtls_md_info_t *md_info ) MBEDTLS_DEPRECATED;
 #undef MBEDTLS_DEPRECATED
 #undef MBEDTLS_DEPRECATED
 #endif /* MBEDTLS_DEPRECATED_REMOVED */
 #endif /* MBEDTLS_DEPRECATED_REMOVED */
 
 
 /**
 /**
- * \brief           Select MD to use and allocate internal structures.
- *                  Should be called after mbedtls_md_init() or mbedtls_md_free().
- *                  Makes it necessary to call mbedtls_md_free() later.
+ * \brief           This function selects the message digest algorithm to use,
+ *                  and allocates internal structures.
  *
  *
- * \param ctx       Context to set up.
- * \param md_info   Message digest to use.
- * \param hmac      0 to save some memory if HMAC will not be used,
- *                  non-zero is HMAC is going to be used with this context.
+ *                  It should be called after mbedtls_md_init() or
+ *                  mbedtls_md_free(). Makes it necessary to call
+ *                  mbedtls_md_free() later.
+ *
+ * \param ctx       The context to set up.
+ * \param md_info   The information structure of the message-digest algorithm
+ *                  to use.
+ * \param hmac      <ul><li>0: HMAC is not used. Saves some memory.</li>
+ *                  <li>non-zero: HMAC is used with this context.</li></ul>
  *
  *
  * \returns         \c 0 on success,
  * \returns         \c 0 on success,
- *                  \c MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure,
- *                  \c MBEDTLS_ERR_MD_ALLOC_FAILED memory allocation failure.
+ *                  #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure, or
+ *                  #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 );
 int mbedtls_md_setup( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info, int hmac );
 
 
 /**
 /**
- * \brief           Clone the state of an MD context
+ * \brief           This function clones the state of an message-digest
+ *                  context.
+ *
+ * \note            You must call mbedtls_md_setup() on \c dst before calling
+ *                  this function.
  *
  *
- * \note            The two contexts must have been setup to the same type
- *                  (cloning from SHA-256 to SHA-512 make no sense).
+ * \note            The two contexts must have the same type,
+ *                  for example, both are SHA-256.
  *
  *
- * \warning         Only clones the MD state, not the HMAC state! (for now)
+ * \warning         This function clones the message-digest state, not the
+ *                  HMAC state.
  *
  *
- * \param dst       The destination context
- * \param src       The context to be cloned
+ * \param dst       The destination context.
+ * \param src       The context to be cloned.
  *
  *
  * \return          \c 0 on success,
  * \return          \c 0 on success,
- *                  \c MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure.
+ *                  #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter failure.
  */
  */
 int mbedtls_md_clone( mbedtls_md_context_t *dst,
 int mbedtls_md_clone( mbedtls_md_context_t *dst,
                       const mbedtls_md_context_t *src );
                       const mbedtls_md_context_t *src );
 
 
 /**
 /**
- * \brief           Returns the size of the message digest output.
+ * \brief           This function extracts the message-digest size from the
+ *                  message-digest information structure.
  *
  *
- * \param md_info   message digest info
+ * \param md_info   The information structure of the message-digest algorithm
+ *                  to use.
  *
  *
- * \return          size of the message digest output in bytes.
+ * \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( const mbedtls_md_info_t *md_info );
 
 
 /**
 /**
- * \brief           Returns the type of the message digest output.
+ * \brief           This function extracts the message-digest type from the
+ *                  message-digest information structure.
  *
  *
- * \param md_info   message digest info
+ * \param md_info   The information structure of the message-digest algorithm
+ *                  to use.
  *
  *
- * \return          type of the message digest output.
+ * \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( const mbedtls_md_info_t *md_info );
 
 
 /**
 /**
- * \brief           Returns the name of the message digest output.
+ * \brief           This function extracts the message-digest name from the
+ *                  message-digest information structure.
  *
  *
- * \param md_info   message digest info
+ * \param md_info   The information structure of the message-digest algorithm
+ *                  to use.
  *
  *
- * \return          name of the message digest output.
+ * \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( const mbedtls_md_info_t *md_info );
 
 
 /**
 /**
- * \brief           Prepare the context to digest a new message.
- *                  Generally called after mbedtls_md_setup() or mbedtls_md_finish().
- *                  Followed by mbedtls_md_update().
+ * \brief           This function starts a message-digest computation.
  *
  *
- * \param ctx       generic message digest context.
+ *                  You must call this function after setting up the context
+ *                  with mbedtls_md_setup(), and before passing data with
+ *                  mbedtls_md_update().
  *
  *
- * \returns         0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                  verification fails.
+ * \param ctx       The generic message-digest context.
+ *
+ * \returns         \c 0 on success, #MBEDTLS_ERR_MD_BAD_INPUT_DATA if
+ *                  parameter verification fails.
  */
  */
 int mbedtls_md_starts( mbedtls_md_context_t *ctx );
 int mbedtls_md_starts( mbedtls_md_context_t *ctx );
 
 
 /**
 /**
- * \brief           Generic message digest process buffer
- *                  Called between mbedtls_md_starts() and mbedtls_md_finish().
- *                  May be called repeatedly.
+ * \brief           This function feeds an input buffer into an ongoing
+ *                  message-digest computation.
+ *
+ *                  You must call mbedtls_md_starts() before calling this
+ *                  function. You may call this function multiple times.
+ *                  Afterwards, call mbedtls_md_finish().
  *
  *
- * \param ctx       Generic message digest context
- * \param input     buffer holding the  datal
- * \param ilen      length of the input data
+ * \param ctx       The generic message-digest context.
+ * \param input     The buffer holding the input data.
+ * \param ilen      The length of the input data.
  *
  *
- * \returns         0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                  verification fails.
+ * \returns         \c 0 on success, #MBEDTLS_ERR_MD_BAD_INPUT_DATA if
+ *                  parameter verification fails.
  */
  */
 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 );
 
 
 /**
 /**
- * \brief           Generic message digest final digest
- *                  Called after mbedtls_md_update().
- *                  Usually followed by mbedtls_md_free() or mbedtls_md_starts().
+ * \brief           This function finishes the digest operation,
+ *                  and writes the result to the output buffer.
  *
  *
- * \param ctx       Generic message digest context
- * \param output    Generic message digest checksum result
+ *                  Call this function after a call to mbedtls_md_starts(),
+ *                  followed by any number of calls to mbedtls_md_update().
+ *                  Afterwards, you may either clear the context with
+ *                  mbedtls_md_free(), or call mbedtls_md_starts() to reuse
+ *                  the context for another digest operation with the same
+ *                  algorithm.
  *
  *
- * \returns         0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                  verification fails.
+ * \param ctx       The generic message-digest context.
+ * \param output    The buffer for the generic message-digest checksum result.
+ *
+ * \returns         \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if
+ *                  parameter verification fails.
  */
  */
 int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output );
 int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output );
 
 
 /**
 /**
- * \brief          Output = message_digest( input buffer )
+ * \brief          This function calculates the message-digest of a buffer,
+ *                 with respect to a configurable message-digest algorithm
+ *                 in a single call.
+ *
+ *                 The result is calculated as
+ *                 Output = message_digest(input buffer).
  *
  *
- * \param md_info  message digest info
- * \param input    buffer holding the  data
- * \param ilen     length of the input data
- * \param output   Generic message digest checksum result
+ * \param md_info  The information structure of the message-digest algorithm
+ *                 to use.
+ * \param input    The buffer holding the data.
+ * \param ilen     The length of the input data.
+ * \param output   The generic message-digest checksum result.
  *
  *
- * \returns        0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                 verification fails.
+ * \returns        \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if
+ *                 parameter verification fails.
  */
  */
 int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, size_t ilen,
 int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, size_t ilen,
         unsigned char *output );
         unsigned char *output );
 
 
 #if defined(MBEDTLS_FS_IO)
 #if defined(MBEDTLS_FS_IO)
 /**
 /**
- * \brief          Output = message_digest( file contents )
+ * \brief          This function calculates the message-digest checksum
+ *                 result of the contents of the provided file.
+ *
+ *                 The result is calculated as
+ *                 Output = message_digest(file contents).
  *
  *
- * \param md_info  message digest info
- * \param path     input file name
- * \param output   generic message digest checksum result
+ * \param md_info  The information structure of the message-digest algorithm
+ *                 to use.
+ * \param path     The input file name.
+ * \param output   The generic message-digest checksum result.
  *
  *
- * \return         0 if successful,
- *                 MBEDTLS_ERR_MD_FILE_IO_ERROR if file input failed,
- *                 MBEDTLS_ERR_MD_BAD_INPUT_DATA if md_info was NULL.
+ * \return         \c 0 on success,
+ *                 #MBEDTLS_ERR_MD_FILE_IO_ERROR if file input failed, or
+ *                 #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( const mbedtls_md_info_t *md_info, const char *path,
                      unsigned char *output );
                      unsigned char *output );
 #endif /* MBEDTLS_FS_IO */
 #endif /* MBEDTLS_FS_IO */
 
 
 /**
 /**
- * \brief           Set HMAC key and prepare to authenticate a new message.
- *                  Usually called after mbedtls_md_setup() or mbedtls_md_hmac_finish().
+ * \brief           This function sets the HMAC key and prepares to
+ *                  authenticate a new message.
  *
  *
- * \param ctx       HMAC context
- * \param key       HMAC secret key
- * \param keylen    length of the HMAC key in bytes
+ *                  Call this function after mbedtls_md_setup(), to use
+ *                  the MD context for an HMAC calculation, then call
+ *                  mbedtls_md_hmac_update() to provide the input data, and
+ *                  mbedtls_md_hmac_finish() to get the HMAC value.
  *
  *
- * \returns         0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                  verification fails.
+ * \param ctx       The message digest context containing an embedded HMAC
+ *                  context.
+ * \param key       The HMAC secret key.
+ * \param keylen    The length of the HMAC key in Bytes.
+ *
+ * \returns         \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if
+ *                  parameter verification fails.
  */
  */
 int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key,
 int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key,
                     size_t keylen );
                     size_t keylen );
 
 
 /**
 /**
- * \brief           Generic HMAC process buffer.
- *                  Called between mbedtls_md_hmac_starts() or mbedtls_md_hmac_reset()
- *                  and mbedtls_md_hmac_finish().
- *                  May be called repeatedly.
- *
- * \param ctx       HMAC context
- * \param input     buffer holding the  data
- * \param ilen      length of the input data
- *
- * \returns         0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                  verification fails.
+ * \brief           This function feeds an input buffer into an ongoing HMAC
+ *                  computation.
+ *
+ *                  Call mbedtls_md_hmac_starts() or mbedtls_md_hmac_reset()
+ *                  before calling this function.
+ *                  You may call this function multiple times to pass the
+ *                  input piecewise.
+ *                  Afterwards, call mbedtls_md_hmac_finish().
+ *
+ * \param ctx       The message digest context containing an embedded HMAC
+ *                  context.
+ * \param input     The buffer holding the input data.
+ * \param ilen      The length of the input data.
+ *
+ * \returns         \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if
+ *                  parameter verification fails.
  */
  */
 int mbedtls_md_hmac_update( mbedtls_md_context_t *ctx, const unsigned char *input,
 int mbedtls_md_hmac_update( mbedtls_md_context_t *ctx, const unsigned char *input,
                     size_t ilen );
                     size_t ilen );
 
 
 /**
 /**
- * \brief           Output HMAC.
- *                  Called after mbedtls_md_hmac_update().
- *                  Usually followed by mbedtls_md_hmac_reset(),
- *                  mbedtls_md_hmac_starts(), or mbedtls_md_free().
+ * \brief           This function finishes the HMAC operation, and writes
+ *                  the result to the output buffer.
+ *
+ *                  Call this function after mbedtls_md_hmac_starts() and
+ *                  mbedtls_md_hmac_update() to get the HMAC value. Afterwards
+ *                  you may either call mbedtls_md_free() to clear the context,
+ *                  or call mbedtls_md_hmac_reset() to reuse the context with
+ *                  the same HMAC key.
  *
  *
- * \param ctx       HMAC context
- * \param output    Generic HMAC checksum result
+ * \param ctx       The message digest context containing an embedded HMAC
+ *                  context.
+ * \param output    The generic HMAC checksum result.
  *
  *
- * \returns         0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                  verification fails.
+ * \returns         \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if
+ *                  parameter verification fails.
  */
  */
 int mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output);
 int mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output);
 
 
 /**
 /**
- * \brief           Prepare to authenticate a new message with the same key.
- *                  Called after mbedtls_md_hmac_finish() and before
- *                  mbedtls_md_hmac_update().
+ * \brief           This function prepares to authenticate a new message with
+ *                  the same key as the previous HMAC operation.
  *
  *
- * \param ctx       HMAC context to be reset
+ *                  You may call this function after mbedtls_md_hmac_finish().
+ *                  Afterwards call mbedtls_md_hmac_update() to pass the new
+ *                  input.
  *
  *
- * \returns         0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                  verification fails.
+ * \param ctx       The message digest context containing an embedded HMAC
+ *                  context.
+ *
+ * \returns         \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if
+ *                  parameter verification fails.
  */
  */
 int mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx );
 int mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx );
 
 
 /**
 /**
- * \brief          Output = Generic_HMAC( hmac key, input buffer )
+ * \brief          This function calculates the full generic HMAC
+ *                 on the input buffer with the provided key.
+ *
+ *                 The function allocates the context, performs the
+ *                 calculation, and frees the context.
+ *
+ *                 The HMAC result is calculated as
+ *                 output = generic HMAC(hmac key, input buffer).
  *
  *
- * \param md_info  message digest info
- * \param key      HMAC secret key
- * \param keylen   length of the HMAC key in bytes
- * \param input    buffer holding the  data
- * \param ilen     length of the input data
- * \param output   Generic HMAC-result
+ * \param md_info  The information structure of the message-digest algorithm
+ *                 to use.
+ * \param key      The HMAC secret key.
+ * \param keylen   The length of the HMAC secret key in Bytes.
+ * \param input    The buffer holding the input data.
+ * \param ilen     The length of the input data.
+ * \param output   The generic HMAC result.
  *
  *
- * \returns        0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
- *                 verification fails.
+ * \returns        \c 0 on success, or #MBEDTLS_ERR_MD_BAD_INPUT_DATA if
+ *                 parameter verification fails.
  */
  */
 int mbedtls_md_hmac( const mbedtls_md_info_t *md_info, const unsigned char *key, size_t keylen,
 int mbedtls_md_hmac( const mbedtls_md_info_t *md_info, const unsigned char *key, size_t keylen,
                 const unsigned char *input, size_t ilen,
                 const unsigned char *input, size_t ilen,

+ 182 - 9
mbedtls/include/mbedtls/md2.h

@@ -3,6 +3,11 @@
  *
  *
  * \brief MD2 message digest algorithm (hash function)
  * \brief MD2 message digest algorithm (hash function)
  *
  *
+ * \warning MD2 is considered a weak message digest and its use constitutes a
+ *          security risk. We recommend considering stronger message digests
+ *          instead.
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -19,6 +24,7 @@
  *  limitations under the License.
  *  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_MD2_H
 #ifndef MBEDTLS_MD2_H
 #define MBEDTLS_MD2_H
 #define MBEDTLS_MD2_H
@@ -31,6 +37,8 @@
 
 
 #include <stddef.h>
 #include <stddef.h>
 
 
+#define MBEDTLS_ERR_MD2_HW_ACCEL_FAILED                   -0x002B  /**< MD2 hardware accelerator failed */
+
 #if !defined(MBEDTLS_MD2_ALT)
 #if !defined(MBEDTLS_MD2_ALT)
 // Regular implementation
 // Regular implementation
 //
 //
@@ -41,6 +49,11 @@ extern "C" {
 
 
 /**
 /**
  * \brief          MD2 context structure
  * \brief          MD2 context structure
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
 typedef struct
 typedef struct
 {
 {
@@ -55,6 +68,11 @@ mbedtls_md2_context;
  * \brief          Initialize MD2 context
  * \brief          Initialize MD2 context
  *
  *
  * \param ctx      MD2 context to be initialized
  * \param ctx      MD2 context to be initialized
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
 void mbedtls_md2_init( mbedtls_md2_context *ctx );
 void mbedtls_md2_init( mbedtls_md2_context *ctx );
 
 
@@ -62,6 +80,11 @@ void mbedtls_md2_init( mbedtls_md2_context *ctx );
  * \brief          Clear MD2 context
  * \brief          Clear MD2 context
  *
  *
  * \param ctx      MD2 context to be cleared
  * \param ctx      MD2 context to be cleared
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
 void mbedtls_md2_free( mbedtls_md2_context *ctx );
 void mbedtls_md2_free( mbedtls_md2_context *ctx );
 
 
@@ -70,6 +93,11 @@ void mbedtls_md2_free( mbedtls_md2_context *ctx );
  *
  *
  * \param dst      The destination context
  * \param dst      The destination context
  * \param src      The context to be cloned
  * \param src      The context to be cloned
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
 void mbedtls_md2_clone( mbedtls_md2_context *dst,
 void mbedtls_md2_clone( mbedtls_md2_context *dst,
                         const mbedtls_md2_context *src );
                         const mbedtls_md2_context *src );
@@ -78,25 +106,134 @@ void mbedtls_md2_clone( mbedtls_md2_context *dst,
  * \brief          MD2 context setup
  * \brief          MD2 context setup
  *
  *
  * \param ctx      context to be initialized
  * \param ctx      context to be initialized
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md2_starts_ret( mbedtls_md2_context *ctx );
+
+/**
+ * \brief          MD2 process buffer
+ *
+ * \param ctx      MD2 context
+ * \param input    buffer holding the data
+ * \param ilen     length of the input data
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md2_update_ret( mbedtls_md2_context *ctx,
+                            const unsigned char *input,
+                            size_t ilen );
+
+/**
+ * \brief          MD2 final digest
+ *
+ * \param ctx      MD2 context
+ * \param output   MD2 checksum result
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md2_finish_ret( mbedtls_md2_context *ctx,
+                            unsigned char output[16] );
+
+/**
+ * \brief          MD2 process data block (internal use only)
+ *
+ * \param ctx      MD2 context
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_internal_md2_process( mbedtls_md2_context *ctx );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          MD2 context setup
+ *
+ * \deprecated     Superseded by mbedtls_md2_starts_ret() in 2.7.0
+ *
+ * \param ctx      context to be initialized
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
-void mbedtls_md2_starts( mbedtls_md2_context *ctx );
+MBEDTLS_DEPRECATED void mbedtls_md2_starts( mbedtls_md2_context *ctx );
 
 
 /**
 /**
  * \brief          MD2 process buffer
  * \brief          MD2 process buffer
  *
  *
+ * \deprecated     Superseded by mbedtls_md2_update_ret() in 2.7.0
+ *
  * \param ctx      MD2 context
  * \param ctx      MD2 context
- * \param input    buffer holding the  data
+ * \param input    buffer holding the data
  * \param ilen     length of the input data
  * \param ilen     length of the input data
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
-void mbedtls_md2_update( mbedtls_md2_context *ctx, const unsigned char *input, size_t ilen );
+MBEDTLS_DEPRECATED void mbedtls_md2_update( mbedtls_md2_context *ctx,
+                                            const unsigned char *input,
+                                            size_t ilen );
 
 
 /**
 /**
  * \brief          MD2 final digest
  * \brief          MD2 final digest
  *
  *
+ * \deprecated     Superseded by mbedtls_md2_finish_ret() in 2.7.0
+ *
  * \param ctx      MD2 context
  * \param ctx      MD2 context
  * \param output   MD2 checksum result
  * \param output   MD2 checksum result
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
-void mbedtls_md2_finish( mbedtls_md2_context *ctx, unsigned char output[16] );
+MBEDTLS_DEPRECATED void mbedtls_md2_finish( mbedtls_md2_context *ctx,
+                                            unsigned char output[16] );
+
+/**
+ * \brief          MD2 process data block (internal use only)
+ *
+ * \deprecated     Superseded by mbedtls_internal_md2_process() in 2.7.0
+ *
+ * \param ctx      MD2 context
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+MBEDTLS_DEPRECATED void mbedtls_md2_process( mbedtls_md2_context *ctx );
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
 }
 }
@@ -113,22 +250,58 @@ extern "C" {
 /**
 /**
  * \brief          Output = MD2( input buffer )
  * \brief          Output = MD2( input buffer )
  *
  *
- * \param input    buffer holding the  data
+ * \param input    buffer holding the data
  * \param ilen     length of the input data
  * \param ilen     length of the input data
  * \param output   MD2 checksum result
  * \param output   MD2 checksum result
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
-void mbedtls_md2( const unsigned char *input, size_t ilen, unsigned char output[16] );
+int mbedtls_md2_ret( const unsigned char *input,
+                     size_t ilen,
+                     unsigned char output[16] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          Output = MD2( input buffer )
+ *
+ * \deprecated     Superseded by mbedtls_md2_ret() in 2.7.0
+ *
+ * \param input    buffer holding the data
+ * \param ilen     length of the input data
+ * \param output   MD2 checksum result
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+MBEDTLS_DEPRECATED void mbedtls_md2( const unsigned char *input,
+                                     size_t ilen,
+                                     unsigned char output[16] );
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 
 /**
 /**
  * \brief          Checkup routine
  * \brief          Checkup routine
  *
  *
  * \return         0 if successful, or 1 if the test failed
  * \return         0 if successful, or 1 if the test failed
+ *
+ * \warning        MD2 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
 int mbedtls_md2_self_test( int verbose );
 int mbedtls_md2_self_test( int verbose );
 
 
-/* Internal use */
-void mbedtls_md2_process( mbedtls_md2_context *ctx );
-
 #ifdef __cplusplus
 #ifdef __cplusplus
 }
 }
 #endif
 #endif

+ 187 - 9
mbedtls/include/mbedtls/md4.h

@@ -3,6 +3,11 @@
  *
  *
  * \brief MD4 message digest algorithm (hash function)
  * \brief MD4 message digest algorithm (hash function)
  *
  *
+ * \warning MD4 is considered a weak message digest and its use constitutes a
+ *          security risk. We recommend considering stronger message digests
+ *          instead.
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -19,6 +24,7 @@
  *  limitations under the License.
  *  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_MD4_H
 #ifndef MBEDTLS_MD4_H
 #define MBEDTLS_MD4_H
 #define MBEDTLS_MD4_H
@@ -32,6 +38,8 @@
 #include <stddef.h>
 #include <stddef.h>
 #include <stdint.h>
 #include <stdint.h>
 
 
+#define MBEDTLS_ERR_MD4_HW_ACCEL_FAILED                   -0x002D  /**< MD4 hardware accelerator failed */
+
 #if !defined(MBEDTLS_MD4_ALT)
 #if !defined(MBEDTLS_MD4_ALT)
 // Regular implementation
 // Regular implementation
 //
 //
@@ -42,6 +50,11 @@ extern "C" {
 
 
 /**
 /**
  * \brief          MD4 context structure
  * \brief          MD4 context structure
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
 typedef struct
 typedef struct
 {
 {
@@ -55,6 +68,11 @@ mbedtls_md4_context;
  * \brief          Initialize MD4 context
  * \brief          Initialize MD4 context
  *
  *
  * \param ctx      MD4 context to be initialized
  * \param ctx      MD4 context to be initialized
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
 void mbedtls_md4_init( mbedtls_md4_context *ctx );
 void mbedtls_md4_init( mbedtls_md4_context *ctx );
 
 
@@ -62,6 +80,11 @@ void mbedtls_md4_init( mbedtls_md4_context *ctx );
  * \brief          Clear MD4 context
  * \brief          Clear MD4 context
  *
  *
  * \param ctx      MD4 context to be cleared
  * \param ctx      MD4 context to be cleared
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
 void mbedtls_md4_free( mbedtls_md4_context *ctx );
 void mbedtls_md4_free( mbedtls_md4_context *ctx );
 
 
@@ -70,6 +93,11 @@ void mbedtls_md4_free( mbedtls_md4_context *ctx );
  *
  *
  * \param dst      The destination context
  * \param dst      The destination context
  * \param src      The context to be cloned
  * \param src      The context to be cloned
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
 void mbedtls_md4_clone( mbedtls_md4_context *dst,
 void mbedtls_md4_clone( mbedtls_md4_context *dst,
                         const mbedtls_md4_context *src );
                         const mbedtls_md4_context *src );
@@ -78,25 +106,137 @@ void mbedtls_md4_clone( mbedtls_md4_context *dst,
  * \brief          MD4 context setup
  * \brief          MD4 context setup
  *
  *
  * \param ctx      context to be initialized
  * \param ctx      context to be initialized
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ */
+int mbedtls_md4_starts_ret( mbedtls_md4_context *ctx );
+
+/**
+ * \brief          MD4 process buffer
+ *
+ * \param ctx      MD4 context
+ * \param input    buffer holding the data
+ * \param ilen     length of the input data
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md4_update_ret( mbedtls_md4_context *ctx,
+                            const unsigned char *input,
+                            size_t ilen );
+
+/**
+ * \brief          MD4 final digest
+ *
+ * \param ctx      MD4 context
+ * \param output   MD4 checksum result
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md4_finish_ret( mbedtls_md4_context *ctx,
+                            unsigned char output[16] );
+
+/**
+ * \brief          MD4 process data block (internal use only)
+ *
+ * \param ctx      MD4 context
+ * \param data     buffer holding one block of data
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_internal_md4_process( mbedtls_md4_context *ctx,
+                                  const unsigned char data[64] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          MD4 context setup
+ *
+ * \deprecated     Superseded by mbedtls_md4_starts_ret() in 2.7.0
+ *
+ * \param ctx      context to be initialized
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
-void mbedtls_md4_starts( mbedtls_md4_context *ctx );
+MBEDTLS_DEPRECATED void mbedtls_md4_starts( mbedtls_md4_context *ctx );
 
 
 /**
 /**
  * \brief          MD4 process buffer
  * \brief          MD4 process buffer
  *
  *
+ * \deprecated     Superseded by mbedtls_md4_update_ret() in 2.7.0
+ *
  * \param ctx      MD4 context
  * \param ctx      MD4 context
- * \param input    buffer holding the  data
+ * \param input    buffer holding the data
  * \param ilen     length of the input data
  * \param ilen     length of the input data
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
-void mbedtls_md4_update( mbedtls_md4_context *ctx, const unsigned char *input, size_t ilen );
+MBEDTLS_DEPRECATED void mbedtls_md4_update( mbedtls_md4_context *ctx,
+                                            const unsigned char *input,
+                                            size_t ilen );
 
 
 /**
 /**
  * \brief          MD4 final digest
  * \brief          MD4 final digest
  *
  *
+ * \deprecated     Superseded by mbedtls_md4_finish_ret() in 2.7.0
+ *
  * \param ctx      MD4 context
  * \param ctx      MD4 context
  * \param output   MD4 checksum result
  * \param output   MD4 checksum result
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
-void mbedtls_md4_finish( mbedtls_md4_context *ctx, unsigned char output[16] );
+MBEDTLS_DEPRECATED void mbedtls_md4_finish( mbedtls_md4_context *ctx,
+                                            unsigned char output[16] );
+
+/**
+ * \brief          MD4 process data block (internal use only)
+ *
+ * \deprecated     Superseded by mbedtls_internal_md4_process() in 2.7.0
+ *
+ * \param ctx      MD4 context
+ * \param data     buffer holding one block of data
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+MBEDTLS_DEPRECATED void mbedtls_md4_process( mbedtls_md4_context *ctx,
+                                             const unsigned char data[64] );
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
 }
 }
@@ -113,22 +253,60 @@ extern "C" {
 /**
 /**
  * \brief          Output = MD4( input buffer )
  * \brief          Output = MD4( input buffer )
  *
  *
- * \param input    buffer holding the  data
+ * \param input    buffer holding the data
  * \param ilen     length of the input data
  * \param ilen     length of the input data
  * \param output   MD4 checksum result
  * \param output   MD4 checksum result
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
-void mbedtls_md4( const unsigned char *input, size_t ilen, unsigned char output[16] );
+int mbedtls_md4_ret( const unsigned char *input,
+                     size_t ilen,
+                     unsigned char output[16] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          Output = MD4( input buffer )
+ *
+ * \deprecated     Superseded by mbedtls_md4_ret() in 2.7.0
+ *
+ * \param input    buffer holding the data
+ * \param ilen     length of the input data
+ * \param output   MD4 checksum result
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+MBEDTLS_DEPRECATED void mbedtls_md4( const unsigned char *input,
+                                     size_t ilen,
+                                     unsigned char output[16] );
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 
 /**
 /**
  * \brief          Checkup routine
  * \brief          Checkup routine
  *
  *
  * \return         0 if successful, or 1 if the test failed
  * \return         0 if successful, or 1 if the test failed
+ *
+ * \warning        MD4 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
 int mbedtls_md4_self_test( int verbose );
 int mbedtls_md4_self_test( int verbose );
 
 
-/* Internal use */
-void mbedtls_md4_process( mbedtls_md4_context *ctx, const unsigned char data[64] );
-
 #ifdef __cplusplus
 #ifdef __cplusplus
 }
 }
 #endif
 #endif

+ 186 - 8
mbedtls/include/mbedtls/md5.h

@@ -3,6 +3,11 @@
  *
  *
  * \brief MD5 message digest algorithm (hash function)
  * \brief MD5 message digest algorithm (hash function)
  *
  *
+ * \warning   MD5 is considered a weak message digest and its use constitutes a
+ *            security risk. We recommend considering stronger message
+ *            digests instead.
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -32,6 +37,8 @@
 #include <stddef.h>
 #include <stddef.h>
 #include <stdint.h>
 #include <stdint.h>
 
 
+#define MBEDTLS_ERR_MD5_HW_ACCEL_FAILED                   -0x002F  /**< MD5 hardware accelerator failed */
+
 #if !defined(MBEDTLS_MD5_ALT)
 #if !defined(MBEDTLS_MD5_ALT)
 // Regular implementation
 // Regular implementation
 //
 //
@@ -42,6 +49,11 @@ extern "C" {
 
 
 /**
 /**
  * \brief          MD5 context structure
  * \brief          MD5 context structure
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
 typedef struct
 typedef struct
 {
 {
@@ -55,6 +67,11 @@ mbedtls_md5_context;
  * \brief          Initialize MD5 context
  * \brief          Initialize MD5 context
  *
  *
  * \param ctx      MD5 context to be initialized
  * \param ctx      MD5 context to be initialized
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
 void mbedtls_md5_init( mbedtls_md5_context *ctx );
 void mbedtls_md5_init( mbedtls_md5_context *ctx );
 
 
@@ -62,6 +79,11 @@ void mbedtls_md5_init( mbedtls_md5_context *ctx );
  * \brief          Clear MD5 context
  * \brief          Clear MD5 context
  *
  *
  * \param ctx      MD5 context to be cleared
  * \param ctx      MD5 context to be cleared
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
 void mbedtls_md5_free( mbedtls_md5_context *ctx );
 void mbedtls_md5_free( mbedtls_md5_context *ctx );
 
 
@@ -70,6 +92,11 @@ void mbedtls_md5_free( mbedtls_md5_context *ctx );
  *
  *
  * \param dst      The destination context
  * \param dst      The destination context
  * \param src      The context to be cloned
  * \param src      The context to be cloned
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
 void mbedtls_md5_clone( mbedtls_md5_context *dst,
 void mbedtls_md5_clone( mbedtls_md5_context *dst,
                         const mbedtls_md5_context *src );
                         const mbedtls_md5_context *src );
@@ -78,28 +105,138 @@ void mbedtls_md5_clone( mbedtls_md5_context *dst,
  * \brief          MD5 context setup
  * \brief          MD5 context setup
  *
  *
  * \param ctx      context to be initialized
  * \param ctx      context to be initialized
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md5_starts_ret( mbedtls_md5_context *ctx );
+
+/**
+ * \brief          MD5 process buffer
+ *
+ * \param ctx      MD5 context
+ * \param input    buffer holding the data
+ * \param ilen     length of the input data
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md5_update_ret( mbedtls_md5_context *ctx,
+                            const unsigned char *input,
+                            size_t ilen );
+
+/**
+ * \brief          MD5 final digest
+ *
+ * \param ctx      MD5 context
+ * \param output   MD5 checksum result
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_md5_finish_ret( mbedtls_md5_context *ctx,
+                            unsigned char output[16] );
+
+/**
+ * \brief          MD5 process data block (internal use only)
+ *
+ * \param ctx      MD5 context
+ * \param data     buffer holding one block of data
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_internal_md5_process( mbedtls_md5_context *ctx,
+                                  const unsigned char data[64] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          MD5 context setup
+ *
+ * \deprecated     Superseded by mbedtls_md5_starts_ret() in 2.7.0
+ *
+ * \param ctx      context to be initialized
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
-void mbedtls_md5_starts( mbedtls_md5_context *ctx );
+MBEDTLS_DEPRECATED void mbedtls_md5_starts( mbedtls_md5_context *ctx );
 
 
 /**
 /**
  * \brief          MD5 process buffer
  * \brief          MD5 process buffer
  *
  *
+ * \deprecated     Superseded by mbedtls_md5_update_ret() in 2.7.0
+ *
  * \param ctx      MD5 context
  * \param ctx      MD5 context
- * \param input    buffer holding the  data
+ * \param input    buffer holding the data
  * \param ilen     length of the input data
  * \param ilen     length of the input data
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
-void mbedtls_md5_update( mbedtls_md5_context *ctx, const unsigned char *input, size_t ilen );
+MBEDTLS_DEPRECATED void mbedtls_md5_update( mbedtls_md5_context *ctx,
+                                            const unsigned char *input,
+                                            size_t ilen );
 
 
 /**
 /**
  * \brief          MD5 final digest
  * \brief          MD5 final digest
  *
  *
+ * \deprecated     Superseded by mbedtls_md5_finish_ret() in 2.7.0
+ *
  * \param ctx      MD5 context
  * \param ctx      MD5 context
  * \param output   MD5 checksum result
  * \param output   MD5 checksum result
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+MBEDTLS_DEPRECATED void mbedtls_md5_finish( mbedtls_md5_context *ctx,
+                                            unsigned char output[16] );
+
+/**
+ * \brief          MD5 process data block (internal use only)
+ *
+ * \deprecated     Superseded by mbedtls_internal_md5_process() in 2.7.0
+ *
+ * \param ctx      MD5 context
+ * \param data     buffer holding one block of data
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
-void mbedtls_md5_finish( mbedtls_md5_context *ctx, unsigned char output[16] );
+MBEDTLS_DEPRECATED void mbedtls_md5_process( mbedtls_md5_context *ctx,
+                                             const unsigned char data[64] );
 
 
-/* Internal use */
-void mbedtls_md5_process( mbedtls_md5_context *ctx, const unsigned char data[64] );
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
 }
 }
@@ -116,16 +253,57 @@ extern "C" {
 /**
 /**
  * \brief          Output = MD5( input buffer )
  * \brief          Output = MD5( input buffer )
  *
  *
- * \param input    buffer holding the  data
+ * \param input    buffer holding the data
  * \param ilen     length of the input data
  * \param ilen     length of the input data
  * \param output   MD5 checksum result
  * \param output   MD5 checksum result
+ *
+ * \return         0 if successful
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
-void mbedtls_md5( const unsigned char *input, size_t ilen, unsigned char output[16] );
+int mbedtls_md5_ret( const unsigned char *input,
+                     size_t ilen,
+                     unsigned char output[16] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          Output = MD5( input buffer )
+ *
+ * \deprecated     Superseded by mbedtls_md5_ret() in 2.7.0
+ *
+ * \param input    buffer holding the data
+ * \param ilen     length of the input data
+ * \param output   MD5 checksum result
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+MBEDTLS_DEPRECATED void mbedtls_md5( const unsigned char *input,
+                                     size_t ilen,
+                                     unsigned char output[16] );
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 
 /**
 /**
  * \brief          Checkup routine
  * \brief          Checkup routine
  *
  *
  * \return         0 if successful, or 1 if the test failed
  * \return         0 if successful, or 1 if the test failed
+ *
+ * \warning        MD5 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
 int mbedtls_md5_self_test( int verbose );
 int mbedtls_md5_self_test( int verbose );
 
 

+ 8 - 7
mbedtls/include/mbedtls/md_internal.h

@@ -6,7 +6,8 @@
  * \warning This in an internal header. Do not include directly.
  * \warning This in an internal header. Do not include directly.
  *
  *
  * \author Adriaan de Jong <dejong@fox-it.com>
  * \author Adriaan de Jong <dejong@fox-it.com>
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -58,17 +59,17 @@ struct mbedtls_md_info_t
     int block_size;
     int block_size;
 
 
     /** Digest initialisation function */
     /** Digest initialisation function */
-    void (*starts_func)( void *ctx );
+    int (*starts_func)( void *ctx );
 
 
     /** Digest update function */
     /** Digest update function */
-    void (*update_func)( void *ctx, const unsigned char *input, size_t ilen );
+    int (*update_func)( void *ctx, const unsigned char *input, size_t ilen );
 
 
     /** Digest finalisation function */
     /** Digest finalisation function */
-    void (*finish_func)( void *ctx, unsigned char *output );
+    int (*finish_func)( void *ctx, unsigned char *output );
 
 
     /** Generic digest function */
     /** Generic digest function */
-    void (*digest_func)( const unsigned char *input, size_t ilen,
-                         unsigned char *output );
+    int (*digest_func)( const unsigned char *input, size_t ilen,
+                        unsigned char *output );
 
 
     /** Allocate a new context */
     /** Allocate a new context */
     void * (*ctx_alloc_func)( void );
     void * (*ctx_alloc_func)( void );
@@ -80,7 +81,7 @@ struct mbedtls_md_info_t
     void (*clone_func)( void *dst, const void *src );
     void (*clone_func)( void *dst, const void *src );
 
 
     /** Internal use only */
     /** Internal use only */
-    void (*process_func)( void *ctx, const unsigned char *input );
+    int (*process_func)( void *ctx, const unsigned char *input );
 };
 };
 
 
 #if defined(MBEDTLS_MD2_C)
 #if defined(MBEDTLS_MD2_C)

+ 2 - 1
mbedtls/include/mbedtls/memory_buffer_alloc.h

@@ -2,7 +2,8 @@
  * \file memory_buffer_alloc.h
  * \file memory_buffer_alloc.h
  *
  *
  * \brief Buffer-based memory allocator
  * \brief Buffer-based memory allocator
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *

+ 10 - 4
mbedtls/include/mbedtls/net.h

@@ -1,8 +1,11 @@
 /**
 /**
  * \file net.h
  * \file net.h
  *
  *
- * \brief Deprecated header file that includes mbedtls/net_sockets.h
+ * \brief Deprecated header file that includes net_sockets.h
  *
  *
+ * \deprecated Superseded by mbedtls/net_sockets.h
+ */
+/*
  *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -19,12 +22,15 @@
  *  limitations under the License.
  *  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)
- *
- * \deprecated Superseded by mbedtls/net_sockets.h
  */
  */
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
 
 
 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
-#include "mbedtls/net_sockets.h"
+#include "net_sockets.h"
 #if defined(MBEDTLS_DEPRECATED_WARNING)
 #if defined(MBEDTLS_DEPRECATED_WARNING)
 #warning "Deprecated header file: Superseded by mbedtls/net_sockets.h"
 #warning "Deprecated header file: Superseded by mbedtls/net_sockets.h"
 #endif /* MBEDTLS_DEPRECATED_WARNING */
 #endif /* MBEDTLS_DEPRECATED_WARNING */

+ 5 - 3
mbedtls/include/mbedtls/net_sockets.h

@@ -2,7 +2,8 @@
  * \file net_sockets.h
  * \file net_sockets.h
  *
  *
  * \brief Network communication functions
  * \brief Network communication functions
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -117,9 +118,10 @@ int mbedtls_net_bind( mbedtls_net_context *ctx, const char *bind_ip, const char
  *
  *
  * \param bind_ctx  Relevant socket
  * \param bind_ctx  Relevant socket
  * \param client_ctx Will contain the connected client socket
  * \param client_ctx Will contain the connected client socket
- * \param client_ip Will contain the client IP address
+ * \param client_ip Will contain the client IP address, can be NULL
  * \param buf_size  Size of the client_ip buffer
  * \param buf_size  Size of the client_ip buffer
- * \param ip_len    Will receive the size of the client IP written
+ * \param ip_len    Will receive the size of the client IP written,
+ *                  can be NULL if client_ip is null
  *
  *
  * \return          0 if successful, or
  * \return          0 if successful, or
  *                  MBEDTLS_ERR_NET_ACCEPT_FAILED, or
  *                  MBEDTLS_ERR_NET_ACCEPT_FAILED, or

+ 20 - 1
mbedtls/include/mbedtls/oid.h

@@ -2,7 +2,8 @@
  * \file oid.h
  * \file oid.h
  *
  *
  * \brief Object Identifier (OID) database
  * \brief Object Identifier (OID) database
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -227,6 +228,14 @@
 
 
 #define MBEDTLS_OID_HMAC_SHA1                   MBEDTLS_OID_RSA_COMPANY "\x02\x07" /**< id-hmacWithSHA1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 7 } */
 #define MBEDTLS_OID_HMAC_SHA1                   MBEDTLS_OID_RSA_COMPANY "\x02\x07" /**< id-hmacWithSHA1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 7 } */
 
 
+#define MBEDTLS_OID_HMAC_SHA224                 MBEDTLS_OID_RSA_COMPANY "\x02\x08" /**< id-hmacWithSHA224 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 8 } */
+
+#define MBEDTLS_OID_HMAC_SHA256                 MBEDTLS_OID_RSA_COMPANY "\x02\x09" /**< id-hmacWithSHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 9 } */
+
+#define MBEDTLS_OID_HMAC_SHA384                 MBEDTLS_OID_RSA_COMPANY "\x02\x0A" /**< id-hmacWithSHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 10 } */
+
+#define MBEDTLS_OID_HMAC_SHA512                 MBEDTLS_OID_RSA_COMPANY "\x02\x0B" /**< id-hmacWithSHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 11 } */
+
 /*
 /*
  * Encryption algorithms
  * Encryption algorithms
  */
  */
@@ -513,6 +522,16 @@ int mbedtls_oid_get_oid_by_sig_alg( mbedtls_pk_type_t pk_alg, mbedtls_md_type_t
  * \return         0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
  * \return         0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
  */
  */
 int mbedtls_oid_get_md_alg( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_alg );
 int mbedtls_oid_get_md_alg( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_alg );
+
+/**
+ * \brief          Translate hmac algorithm OID into md_type
+ *
+ * \param oid      OID to use
+ * \param md_hmac  place to store message hmac algorithm
+ *
+ * \return         0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_md_hmac( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_hmac );
 #endif /* MBEDTLS_MD_C */
 #endif /* MBEDTLS_MD_C */
 
 
 /**
 /**

+ 8 - 1
mbedtls/include/mbedtls/padlock.h

@@ -3,7 +3,8 @@
  *
  *
  * \brief VIA PadLock ACE for HW encryption/decryption supported by some
  * \brief VIA PadLock ACE for HW encryption/decryption supported by some
  *        processors
  *        processors
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -24,6 +25,12 @@
 #ifndef MBEDTLS_PADLOCK_H
 #ifndef MBEDTLS_PADLOCK_H
 #define MBEDTLS_PADLOCK_H
 #define MBEDTLS_PADLOCK_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include "aes.h"
 #include "aes.h"
 
 
 #define MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED               -0x0030  /**< Input data should be aligned. */
 #define MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED               -0x0030  /**< Input data should be aligned. */

+ 8 - 1
mbedtls/include/mbedtls/pem.h

@@ -2,7 +2,8 @@
  * \file pem.h
  * \file pem.h
  *
  *
  * \brief Privacy Enhanced Mail (PEM) decoding
  * \brief Privacy Enhanced Mail (PEM) decoding
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -23,6 +24,12 @@
 #ifndef MBEDTLS_PEM_H
 #ifndef MBEDTLS_PEM_H
 #define MBEDTLS_PEM_H
 #define MBEDTLS_PEM_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include <stddef.h>
 #include <stddef.h>
 
 
 /**
 /**

+ 9 - 7
mbedtls/include/mbedtls/pk.h

@@ -2,7 +2,8 @@
  * \file pk.h
  * \file pk.h
  *
  *
  * \brief Public Key abstraction layer
  * \brief Public Key abstraction layer
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -62,7 +63,8 @@
 #define MBEDTLS_ERR_PK_INVALID_ALG         -0x3A80  /**< The algorithm tag or value is invalid. */
 #define MBEDTLS_ERR_PK_INVALID_ALG         -0x3A80  /**< The algorithm tag or value is invalid. */
 #define MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE -0x3A00  /**< Elliptic curve is unsupported (only NIST curves are supported). */
 #define MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE -0x3A00  /**< Elliptic curve is unsupported (only NIST curves are supported). */
 #define MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE -0x3980  /**< Unavailable feature, e.g. RSA disabled for RSA key. */
 #define MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE -0x3980  /**< Unavailable feature, e.g. RSA disabled for RSA key. */
-#define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH    -0x3900  /**< The signature is valid but its length is less than expected. */
+#define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH    -0x3900  /**< The buffer contains a valid signature followed by more data. */
+#define MBEDTLS_ERR_PK_HW_ACCEL_FAILED     -0x3880  /**< PK hardware accelerator failed. */
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
 extern "C" {
 extern "C" {
@@ -267,8 +269,8 @@ int mbedtls_pk_can_do( const mbedtls_pk_context *ctx, mbedtls_pk_type_t type );
  * \param sig_len   Signature length
  * \param sig_len   Signature length
  *
  *
  * \return          0 on success (signature is valid),
  * \return          0 on success (signature is valid),
- *                  MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if the signature is
- *                  valid but its actual length is less than sig_len,
+ *                  #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid
+ *                  signature in sig but its length is less than \p siglen,
  *                  or a specific error code.
  *                  or a specific error code.
  *
  *
  * \note            For RSA keys, the default padding type is PKCS#1 v1.5.
  * \note            For RSA keys, the default padding type is PKCS#1 v1.5.
@@ -298,10 +300,10 @@ int mbedtls_pk_verify( mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
  * \param sig_len   Signature length
  * \param sig_len   Signature length
  *
  *
  * \return          0 on success (signature is valid),
  * \return          0 on success (signature is valid),
- *                  MBEDTLS_ERR_PK_TYPE_MISMATCH if the PK context can't be
+ *                  #MBEDTLS_ERR_PK_TYPE_MISMATCH if the PK context can't be
  *                  used for this type of signatures,
  *                  used for this type of signatures,
- *                  MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if the signature is
- *                  valid but its actual length is less than sig_len,
+ *                  #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid
+ *                  signature in sig but its length is less than \p siglen,
  *                  or a specific error code.
  *                  or a specific error code.
  *
  *
  * \note            If hash_len is 0, then the length associated with md_alg
  * \note            If hash_len is 0, then the length associated with md_alg

+ 3 - 2
mbedtls/include/mbedtls/pk_internal.h

@@ -1,8 +1,9 @@
 /**
 /**
- * \file pk.h
+ * \file pk_internal.h
  *
  *
  * \brief Public Key abstraction layer: wrapper functions
  * \brief Public Key abstraction layer: wrapper functions
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *

+ 2 - 1
mbedtls/include/mbedtls/pkcs11.h

@@ -4,7 +4,8 @@
  * \brief Wrapper for PKCS#11 library libpkcs11-helper
  * \brief Wrapper for PKCS#11 library libpkcs11-helper
  *
  *
  * \author Adriaan de Jong <dejong@fox-it.com>
  * \author Adriaan de Jong <dejong@fox-it.com>
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *

+ 12 - 1
mbedtls/include/mbedtls/pkcs12.h

@@ -2,7 +2,8 @@
  * \file pkcs12.h
  * \file pkcs12.h
  *
  *
  * \brief PKCS#12 Personal Information Exchange Syntax
  * \brief PKCS#12 Personal Information Exchange Syntax
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -23,6 +24,12 @@
 #ifndef MBEDTLS_PKCS12_H
 #ifndef MBEDTLS_PKCS12_H
 #define MBEDTLS_PKCS12_H
 #define MBEDTLS_PKCS12_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include "md.h"
 #include "md.h"
 #include "cipher.h"
 #include "cipher.h"
 #include "asn1.h"
 #include "asn1.h"
@@ -45,6 +52,8 @@
 extern "C" {
 extern "C" {
 #endif
 #endif
 
 
+#if defined(MBEDTLS_ASN1_PARSE_C)
+
 /**
 /**
  * \brief            PKCS12 Password Based function (encryption / decryption)
  * \brief            PKCS12 Password Based function (encryption / decryption)
  *                   for pbeWithSHAAnd128BitRC4
  *                   for pbeWithSHAAnd128BitRC4
@@ -86,6 +95,8 @@ int mbedtls_pkcs12_pbe( mbedtls_asn1_buf *pbe_params, int mode,
                 const unsigned char *input, size_t len,
                 const unsigned char *input, size_t len,
                 unsigned char *output );
                 unsigned char *output );
 
 
+#endif /* MBEDTLS_ASN1_PARSE_C */
+
 /**
 /**
  * \brief            The PKCS#12 derivation function uses a password and a salt
  * \brief            The PKCS#12 derivation function uses a password and a salt
  *                   to produce pseudo-random bits for a particular "purpose".
  *                   to produce pseudo-random bits for a particular "purpose".

+ 12 - 1
mbedtls/include/mbedtls/pkcs5.h

@@ -4,7 +4,8 @@
  * \brief PKCS#5 functions
  * \brief PKCS#5 functions
  *
  *
  * \author Mathias Olsson <mathias@kompetensum.com>
  * \author Mathias Olsson <mathias@kompetensum.com>
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -25,6 +26,12 @@
 #ifndef MBEDTLS_PKCS5_H
 #ifndef MBEDTLS_PKCS5_H
 #define MBEDTLS_PKCS5_H
 #define MBEDTLS_PKCS5_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include "asn1.h"
 #include "asn1.h"
 #include "md.h"
 #include "md.h"
 
 
@@ -43,6 +50,8 @@
 extern "C" {
 extern "C" {
 #endif
 #endif
 
 
+#if defined(MBEDTLS_ASN1_PARSE_C)
+
 /**
 /**
  * \brief          PKCS#5 PBES2 function
  * \brief          PKCS#5 PBES2 function
  *
  *
@@ -61,6 +70,8 @@ int mbedtls_pkcs5_pbes2( const mbedtls_asn1_buf *pbe_params, int mode,
                  const unsigned char *data, size_t datalen,
                  const unsigned char *data, size_t datalen,
                  unsigned char *output );
                  unsigned char *output );
 
 
+#endif /* MBEDTLS_ASN1_PARSE_C */
+
 /**
 /**
  * \brief          PKCS#5 PBKDF2 using HMAC
  * \brief          PKCS#5 PBKDF2 using HMAC
  *
  *

+ 58 - 53
mbedtls/include/mbedtls/platform.h

@@ -1,9 +1,10 @@
 /**
 /**
  * \file platform.h
  * \file platform.h
  *
  *
- * \brief mbed TLS Platform abstraction layer
- *
- *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
+ * \brief The Mbed TLS platform abstraction layer.
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,7 +19,7 @@
  *  See the License for the specific language governing permissions and
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *  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_PLATFORM_H
 #ifndef MBEDTLS_PLATFORM_H
 #define MBEDTLS_PLATFORM_H
 #define MBEDTLS_PLATFORM_H
@@ -30,7 +31,7 @@
 #endif
 #endif
 
 
 #if defined(MBEDTLS_HAVE_TIME)
 #if defined(MBEDTLS_HAVE_TIME)
-#include "mbedtls/platform_time.h"
+#include "platform_time.h"
 #endif
 #endif
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
@@ -51,34 +52,34 @@ extern "C" {
 #include <time.h>
 #include <time.h>
 #if !defined(MBEDTLS_PLATFORM_STD_SNPRINTF)
 #if !defined(MBEDTLS_PLATFORM_STD_SNPRINTF)
 #if defined(_WIN32)
 #if defined(_WIN32)
-#define MBEDTLS_PLATFORM_STD_SNPRINTF   mbedtls_platform_win32_snprintf /**< Default snprintf to use  */
+#define MBEDTLS_PLATFORM_STD_SNPRINTF   mbedtls_platform_win32_snprintf /**< The default \c snprintf function to use.  */
 #else
 #else
-#define MBEDTLS_PLATFORM_STD_SNPRINTF   snprintf /**< Default snprintf to use  */
+#define MBEDTLS_PLATFORM_STD_SNPRINTF   snprintf /**< The default \c snprintf function to use.  */
 #endif
 #endif
 #endif
 #endif
 #if !defined(MBEDTLS_PLATFORM_STD_PRINTF)
 #if !defined(MBEDTLS_PLATFORM_STD_PRINTF)
-#define MBEDTLS_PLATFORM_STD_PRINTF   printf /**< Default printf to use  */
+#define MBEDTLS_PLATFORM_STD_PRINTF   printf /**< The default \c printf function to use. */
 #endif
 #endif
 #if !defined(MBEDTLS_PLATFORM_STD_FPRINTF)
 #if !defined(MBEDTLS_PLATFORM_STD_FPRINTF)
-#define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< Default fprintf to use */
+#define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< The default \c fprintf function to use. */
 #endif
 #endif
 #if !defined(MBEDTLS_PLATFORM_STD_CALLOC)
 #if !defined(MBEDTLS_PLATFORM_STD_CALLOC)
-#define MBEDTLS_PLATFORM_STD_CALLOC   calloc /**< Default allocator to use */
+#define MBEDTLS_PLATFORM_STD_CALLOC   calloc /**< The default \c calloc function to use. */
 #endif
 #endif
 #if !defined(MBEDTLS_PLATFORM_STD_FREE)
 #if !defined(MBEDTLS_PLATFORM_STD_FREE)
-#define MBEDTLS_PLATFORM_STD_FREE       free /**< Default free to use */
+#define MBEDTLS_PLATFORM_STD_FREE       free /**< The default \c free function to use. */
 #endif
 #endif
 #if !defined(MBEDTLS_PLATFORM_STD_EXIT)
 #if !defined(MBEDTLS_PLATFORM_STD_EXIT)
-#define MBEDTLS_PLATFORM_STD_EXIT      exit /**< Default exit to use */
+#define MBEDTLS_PLATFORM_STD_EXIT      exit /**< The default \c exit function to use. */
 #endif
 #endif
 #if !defined(MBEDTLS_PLATFORM_STD_TIME)
 #if !defined(MBEDTLS_PLATFORM_STD_TIME)
-#define MBEDTLS_PLATFORM_STD_TIME       time    /**< Default time to use */
+#define MBEDTLS_PLATFORM_STD_TIME       time    /**< The default \c time function to use. */
 #endif
 #endif
 #if !defined(MBEDTLS_PLATFORM_STD_EXIT_SUCCESS)
 #if !defined(MBEDTLS_PLATFORM_STD_EXIT_SUCCESS)
-#define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS  EXIT_SUCCESS /**< Default exit value to use */
+#define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS  EXIT_SUCCESS /**< The default exit value to use. */
 #endif
 #endif
 #if !defined(MBEDTLS_PLATFORM_STD_EXIT_FAILURE)
 #if !defined(MBEDTLS_PLATFORM_STD_EXIT_FAILURE)
-#define MBEDTLS_PLATFORM_STD_EXIT_FAILURE  EXIT_FAILURE /**< Default exit value to use */
+#define MBEDTLS_PLATFORM_STD_EXIT_FAILURE  EXIT_FAILURE /**< The default exit value to use. */
 #endif
 #endif
 #if defined(MBEDTLS_FS_IO)
 #if defined(MBEDTLS_FS_IO)
 #if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ)
 #if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ)
@@ -115,12 +116,12 @@ extern void * (*mbedtls_calloc)( size_t n, size_t size );
 extern void (*mbedtls_free)( void *ptr );
 extern void (*mbedtls_free)( void *ptr );
 
 
 /**
 /**
- * \brief   Set your own memory implementation function pointers
+ * \brief   This function allows configuring custom memory-management functions.
  *
  *
- * \param calloc_func   the calloc function implementation
- * \param free_func     the free function implementation
+ * \param calloc_func   The \c calloc function implementation.
+ * \param free_func     The \c free function implementation.
  *
  *
- * \return              0 if successful
+ * \return              \c 0.
  */
  */
 int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ),
 int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ),
                               void (*free_func)( void * ) );
                               void (*free_func)( void * ) );
@@ -139,11 +140,11 @@ int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ),
 extern int (*mbedtls_fprintf)( FILE *stream, const char *format, ... );
 extern int (*mbedtls_fprintf)( FILE *stream, const char *format, ... );
 
 
 /**
 /**
- * \brief   Set your own fprintf function pointer
+ * \brief   This function allows configuring a custom \p fprintf function pointer.
  *
  *
- * \param fprintf_func   the fprintf function implementation
+ * \param fprintf_func   The \c fprintf function implementation.
  *
  *
- * \return              0
+ * \return               \c 0.
  */
  */
 int mbedtls_platform_set_fprintf( int (*fprintf_func)( FILE *stream, const char *,
 int mbedtls_platform_set_fprintf( int (*fprintf_func)( FILE *stream, const char *,
                                                ... ) );
                                                ... ) );
@@ -162,11 +163,12 @@ int mbedtls_platform_set_fprintf( int (*fprintf_func)( FILE *stream, const char
 extern int (*mbedtls_printf)( const char *format, ... );
 extern int (*mbedtls_printf)( const char *format, ... );
 
 
 /**
 /**
- * \brief   Set your own printf function pointer
+ * \brief    This function allows configuring a custom \c printf function
+ *           pointer.
  *
  *
- * \param printf_func   the printf function implementation
+ * \param printf_func   The \c printf function implementation.
  *
  *
- * \return              0
+ * \return              \c 0 on success.
  */
  */
 int mbedtls_platform_set_printf( int (*printf_func)( const char *, ... ) );
 int mbedtls_platform_set_printf( int (*printf_func)( const char *, ... ) );
 #else /* !MBEDTLS_PLATFORM_PRINTF_ALT */
 #else /* !MBEDTLS_PLATFORM_PRINTF_ALT */
@@ -195,11 +197,12 @@ int mbedtls_platform_win32_snprintf( char *s, size_t n, const char *fmt, ... );
 extern int (*mbedtls_snprintf)( char * s, size_t n, const char * format, ... );
 extern int (*mbedtls_snprintf)( char * s, size_t n, const char * format, ... );
 
 
 /**
 /**
- * \brief   Set your own snprintf function pointer
+ * \brief   This function allows configuring a custom \c snprintf function
+ *          pointer.
  *
  *
- * \param snprintf_func   the snprintf function implementation
+ * \param snprintf_func   The \c snprintf function implementation.
  *
  *
- * \return              0
+ * \return    \c 0 on success.
  */
  */
 int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n,
 int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n,
                                                  const char * format, ... ) );
                                                  const char * format, ... ) );
@@ -207,7 +210,7 @@ int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n,
 #if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO)
 #if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO)
 #define mbedtls_snprintf   MBEDTLS_PLATFORM_SNPRINTF_MACRO
 #define mbedtls_snprintf   MBEDTLS_PLATFORM_SNPRINTF_MACRO
 #else
 #else
-#define mbedtls_snprintf   snprintf
+#define mbedtls_snprintf   MBEDTLS_PLATFORM_STD_SNPRINTF
 #endif /* MBEDTLS_PLATFORM_SNPRINTF_MACRO */
 #endif /* MBEDTLS_PLATFORM_SNPRINTF_MACRO */
 #endif /* MBEDTLS_PLATFORM_SNPRINTF_ALT */
 #endif /* MBEDTLS_PLATFORM_SNPRINTF_ALT */
 
 
@@ -218,11 +221,12 @@ int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n,
 extern void (*mbedtls_exit)( int status );
 extern void (*mbedtls_exit)( int status );
 
 
 /**
 /**
- * \brief   Set your own exit function pointer
+ * \brief   This function allows configuring a custom \c exit function
+ *          pointer.
  *
  *
- * \param exit_func   the exit function implementation
+ * \param exit_func   The \c exit function implementation.
  *
  *
- * \return              0
+ * \return  \c 0 on success.
  */
  */
 int mbedtls_platform_set_exit( void (*exit_func)( int status ) );
 int mbedtls_platform_set_exit( void (*exit_func)( int status ) );
 #else
 #else
@@ -265,12 +269,13 @@ extern int (*mbedtls_nv_seed_read)( unsigned char *buf, size_t buf_len );
 extern int (*mbedtls_nv_seed_write)( unsigned char *buf, size_t buf_len );
 extern int (*mbedtls_nv_seed_write)( unsigned char *buf, size_t buf_len );
 
 
 /**
 /**
- * \brief   Set your own seed file writing/reading functions
+ * \brief   This function allows configuring custom seed file writing and
+ *          reading functions.
  *
  *
- * \param   nv_seed_read_func   the seed reading function implementation
- * \param   nv_seed_write_func  the seed writing function implementation
+ * \param   nv_seed_read_func   The seed reading function implementation.
+ * \param   nv_seed_write_func  The seed writing function implementation.
  *
  *
- * \return              0
+ * \return  \c 0 on success.
  */
  */
 int mbedtls_platform_set_nv_seed(
 int mbedtls_platform_set_nv_seed(
             int (*nv_seed_read_func)( unsigned char *buf, size_t buf_len ),
             int (*nv_seed_read_func)( unsigned char *buf, size_t buf_len ),
@@ -291,13 +296,13 @@ int mbedtls_platform_set_nv_seed(
 #if !defined(MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT)
 #if !defined(MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT)
 
 
 /**
 /**
- * \brief   Platform context structure
+ * \brief   The platform context structure.
  *
  *
  * \note    This structure may be used to assist platform-specific
  * \note    This structure may be used to assist platform-specific
- *          setup/teardown operations.
+ *          setup or teardown operations.
  */
  */
 typedef struct {
 typedef struct {
-    char dummy; /**< Placeholder member as empty structs are not portable */
+    char dummy; /**< Placeholder member, as empty structs are not portable. */
 }
 }
 mbedtls_platform_context;
 mbedtls_platform_context;
 
 
@@ -306,32 +311,32 @@ mbedtls_platform_context;
 #endif /* !MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */
 #endif /* !MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */
 
 
 /**
 /**
- * \brief   Perform any platform initialisation operations
+ * \brief   This function performs any platform initialization operations.
  *
  *
- * \param   ctx     mbed TLS context
+ * \param   ctx     The Mbed TLS context.
  *
  *
- * \return  0 if successful
+ * \return  \c 0 on success.
  *
  *
- * \note    This function is intended to allow platform specific initialisation,
+ * \note    This function is intended to allow platform-specific initialization,
  *          and should be called before any other library functions. Its
  *          and should be called before any other library functions. Its
- *          implementation is platform specific, and by default, unless platform
- *          specific code is provided, it does nothing.
+ *          implementation is platform-specific, and unless
+ *          platform-specific code is provided, it does nothing.
  *
  *
- *          Its use and whether its necessary to be called is dependent on the
+ *          Its use and whether it is necessary to call it is dependent on the
  *          platform.
  *          platform.
  */
  */
 int mbedtls_platform_setup( mbedtls_platform_context *ctx );
 int mbedtls_platform_setup( mbedtls_platform_context *ctx );
 /**
 /**
- * \brief   Perform any platform teardown operations
+ * \brief   This function performs any platform teardown operations.
  *
  *
- * \param   ctx     mbed TLS context
+ * \param   ctx     The Mbed TLS context.
  *
  *
- * \note    This function should be called after every other mbed TLS module has
- *          been correctly freed using the appropriate free function.
- *          Its implementation is platform specific, and by default, unless
- *          platform specific code is provided, it does nothing.
+ * \note    This function should be called after every other Mbed TLS module
+ *          has been correctly freed using the appropriate free function.
+ *          Its implementation is platform-specific, and unless
+ *          platform-specific code is provided, it does nothing.
  *
  *
- *          Its use and whether its necessary to be called is dependent on the
+ *          Its use and whether it is necessary to call it is dependent on the
  *          platform.
  *          platform.
  */
  */
 void mbedtls_platform_teardown( mbedtls_platform_context *ctx );
 void mbedtls_platform_teardown( mbedtls_platform_context *ctx );

+ 2 - 1
mbedtls/include/mbedtls/platform_time.h

@@ -2,7 +2,8 @@
  * \file platform_time.h
  * \file platform_time.h
  *
  *
  * \brief mbed TLS Platform time abstraction
  * \brief mbed TLS Platform time abstraction
- *
+ */
+/*
  *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *

+ 113 - 12
mbedtls/include/mbedtls/ripemd160.h

@@ -2,7 +2,8 @@
  * \file ripemd160.h
  * \file ripemd160.h
  *
  *
  * \brief RIPE MD-160 message digest
  * \brief RIPE MD-160 message digest
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -32,6 +33,8 @@
 #include <stddef.h>
 #include <stddef.h>
 #include <stdint.h>
 #include <stdint.h>
 
 
+#define MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED             -0x0031  /**< RIPEMD160 hardware accelerator failed */
+
 #if !defined(MBEDTLS_RIPEMD160_ALT)
 #if !defined(MBEDTLS_RIPEMD160_ALT)
 // Regular implementation
 // Regular implementation
 //
 //
@@ -78,36 +81,109 @@ void mbedtls_ripemd160_clone( mbedtls_ripemd160_context *dst,
  * \brief          RIPEMD-160 context setup
  * \brief          RIPEMD-160 context setup
  *
  *
  * \param ctx      context to be initialized
  * \param ctx      context to be initialized
+ *
+ * \return         0 if successful
  */
  */
-void mbedtls_ripemd160_starts( mbedtls_ripemd160_context *ctx );
+int mbedtls_ripemd160_starts_ret( mbedtls_ripemd160_context *ctx );
 
 
 /**
 /**
  * \brief          RIPEMD-160 process buffer
  * \brief          RIPEMD-160 process buffer
  *
  *
  * \param ctx      RIPEMD-160 context
  * \param ctx      RIPEMD-160 context
- * \param input    buffer holding the  data
+ * \param input    buffer holding the data
  * \param ilen     length of the input data
  * \param ilen     length of the input data
+ *
+ * \return         0 if successful
  */
  */
-void mbedtls_ripemd160_update( mbedtls_ripemd160_context *ctx,
-                       const unsigned char *input, size_t ilen );
+int mbedtls_ripemd160_update_ret( mbedtls_ripemd160_context *ctx,
+                                  const unsigned char *input,
+                                  size_t ilen );
 
 
 /**
 /**
  * \brief          RIPEMD-160 final digest
  * \brief          RIPEMD-160 final digest
  *
  *
  * \param ctx      RIPEMD-160 context
  * \param ctx      RIPEMD-160 context
  * \param output   RIPEMD-160 checksum result
  * \param output   RIPEMD-160 checksum result
+ *
+ * \return         0 if successful
+ */
+int mbedtls_ripemd160_finish_ret( mbedtls_ripemd160_context *ctx,
+                                  unsigned char output[20] );
+
+/**
+ * \brief          RIPEMD-160 process data block (internal use only)
+ *
+ * \param ctx      RIPEMD-160 context
+ * \param data     buffer holding one block of data
+ *
+ * \return         0 if successful
+ */
+int mbedtls_internal_ripemd160_process( mbedtls_ripemd160_context *ctx,
+                                        const unsigned char data[64] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          RIPEMD-160 context setup
+ *
+ * \deprecated     Superseded by mbedtls_ripemd160_starts_ret() in 2.7.0
+ *
+ * \param ctx      context to be initialized
  */
  */
-void mbedtls_ripemd160_finish( mbedtls_ripemd160_context *ctx, unsigned char output[20] );
+MBEDTLS_DEPRECATED void mbedtls_ripemd160_starts(
+                                            mbedtls_ripemd160_context *ctx );
 
 
-/* Internal use */
-void mbedtls_ripemd160_process( mbedtls_ripemd160_context *ctx, const unsigned char data[64] );
+/**
+ * \brief          RIPEMD-160 process buffer
+ *
+ * \deprecated     Superseded by mbedtls_ripemd160_update_ret() in 2.7.0
+ *
+ * \param ctx      RIPEMD-160 context
+ * \param input    buffer holding the data
+ * \param ilen     length of the input data
+ */
+MBEDTLS_DEPRECATED void mbedtls_ripemd160_update(
+                                                mbedtls_ripemd160_context *ctx,
+                                                const unsigned char *input,
+                                                size_t ilen );
+
+/**
+ * \brief          RIPEMD-160 final digest
+ *
+ * \deprecated     Superseded by mbedtls_ripemd160_finish_ret() in 2.7.0
+ *
+ * \param ctx      RIPEMD-160 context
+ * \param output   RIPEMD-160 checksum result
+ */
+MBEDTLS_DEPRECATED void mbedtls_ripemd160_finish(
+                                                mbedtls_ripemd160_context *ctx,
+                                                unsigned char output[20] );
+
+/**
+ * \brief          RIPEMD-160 process data block (internal use only)
+ *
+ * \deprecated     Superseded by mbedtls_internal_ripemd160_process() in 2.7.0
+ *
+ * \param ctx      RIPEMD-160 context
+ * \param data     buffer holding one block of data
+ */
+MBEDTLS_DEPRECATED void mbedtls_ripemd160_process(
+                                            mbedtls_ripemd160_context *ctx,
+                                            const unsigned char data[64] );
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
 }
 }
 #endif
 #endif
 
 
 #else  /* MBEDTLS_RIPEMD160_ALT */
 #else  /* MBEDTLS_RIPEMD160_ALT */
-#include "ripemd160.h"
+#include "ripemd160_alt.h"
 #endif /* MBEDTLS_RIPEMD160_ALT */
 #endif /* MBEDTLS_RIPEMD160_ALT */
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
@@ -117,12 +193,37 @@ extern "C" {
 /**
 /**
  * \brief          Output = RIPEMD-160( input buffer )
  * \brief          Output = RIPEMD-160( input buffer )
  *
  *
- * \param input    buffer holding the  data
+ * \param input    buffer holding the data
  * \param ilen     length of the input data
  * \param ilen     length of the input data
  * \param output   RIPEMD-160 checksum result
  * \param output   RIPEMD-160 checksum result
+ *
+ * \return         0 if successful
  */
  */
-void mbedtls_ripemd160( const unsigned char *input, size_t ilen,
-                unsigned char output[20] );
+int mbedtls_ripemd160_ret( const unsigned char *input,
+                           size_t ilen,
+                           unsigned char output[20] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          Output = RIPEMD-160( input buffer )
+ *
+ * \deprecated     Superseded by mbedtls_ripemd160_ret() in 2.7.0
+ *
+ * \param input    buffer holding the data
+ * \param ilen     length of the input data
+ * \param output   RIPEMD-160 checksum result
+ */
+MBEDTLS_DEPRECATED void mbedtls_ripemd160( const unsigned char *input,
+                                           size_t ilen,
+                                           unsigned char output[20] );
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 
 /**
 /**
  * \brief          Checkup routine
  * \brief          Checkup routine

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 603 - 218
mbedtls/include/mbedtls/rsa.h


+ 226 - 0
mbedtls/include/mbedtls/rsa_internal.h

@@ -0,0 +1,226 @@
+/**
+ * \file rsa_internal.h
+ *
+ * \brief Context-independent RSA helper functions
+ *
+ *  This module declares some RSA-related helper functions useful when
+ *  implementing the RSA interface. These functions are provided in a separate
+ *  compilation unit in order to make it easy for designers of alternative RSA
+ *  implementations to use them in their own code, as it is conceived that the
+ *  functionality they provide will be necessary for most complete
+ *  implementations.
+ *
+ *  End-users of Mbed TLS who are not providing their own alternative RSA
+ *  implementations should not use these functions directly, and should instead
+ *  use only the functions declared in rsa.h.
+ *
+ *  The interface provided by this module will be maintained through LTS (Long
+ *  Term Support) branches of Mbed TLS, but may otherwise be subject to change,
+ *  and must be considered an internal interface of the library.
+ *
+ *  There are two classes of helper functions:
+ *
+ *  (1) Parameter-generating helpers. These are:
+ *      - mbedtls_rsa_deduce_primes
+ *      - mbedtls_rsa_deduce_private_exponent
+ *      - mbedtls_rsa_deduce_crt
+ *       Each of these functions takes a set of core RSA parameters and
+ *       generates some other, or CRT related parameters.
+ *
+ *  (2) Parameter-checking helpers. These are:
+ *      - mbedtls_rsa_validate_params
+ *      - mbedtls_rsa_validate_crt
+ *      They take a set of core or CRT related RSA parameters and check their
+ *      validity.
+ *
+ */
+/*
+ *  Copyright (C) 2006-2017, 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_RSA_INTERNAL_H
+#define MBEDTLS_RSA_INTERNAL_H
+
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
+#include "bignum.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/**
+ * \brief          Compute RSA prime moduli P, Q from public modulus N=PQ
+ *                 and a pair of private and public key.
+ *
+ * \note           This is a 'static' helper function not operating on
+ *                 an RSA context. Alternative implementations need not
+ *                 overwrite it.
+ *
+ * \param N        RSA modulus N = PQ, with P, Q to be found
+ * \param E        RSA public exponent
+ * \param D        RSA private exponent
+ * \param P        Pointer to MPI holding first prime factor of N on success
+ * \param Q        Pointer to MPI holding second prime factor of N on success
+ *
+ * \return
+ *                 - 0 if successful. In this case, P and Q constitute a
+ *                   factorization of N.
+ *                 - A non-zero error code otherwise.
+ *
+ * \note           It is neither checked that P, Q are prime nor that
+ *                 D, E are modular inverses wrt. P-1 and Q-1. For that,
+ *                 use the helper function \c mbedtls_rsa_validate_params.
+ *
+ */
+int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N, mbedtls_mpi const *E,
+                               mbedtls_mpi const *D,
+                               mbedtls_mpi *P, mbedtls_mpi *Q );
+
+/**
+ * \brief          Compute RSA private exponent from
+ *                 prime moduli and public key.
+ *
+ * \note           This is a 'static' helper function not operating on
+ *                 an RSA context. Alternative implementations need not
+ *                 overwrite it.
+ *
+ * \param P        First prime factor of RSA modulus
+ * \param Q        Second prime factor of RSA modulus
+ * \param E        RSA public exponent
+ * \param D        Pointer to MPI holding the private exponent on success.
+ *
+ * \return
+ *                 - 0 if successful. In this case, D is set to a simultaneous
+ *                   modular inverse of E modulo both P-1 and Q-1.
+ *                 - A non-zero error code otherwise.
+ *
+ * \note           This function does not check whether P and Q are primes.
+ *
+ */
+int mbedtls_rsa_deduce_private_exponent( mbedtls_mpi const *P,
+                                         mbedtls_mpi const *Q,
+                                         mbedtls_mpi const *E,
+                                         mbedtls_mpi *D );
+
+
+/**
+ * \brief          Generate RSA-CRT parameters
+ *
+ * \note           This is a 'static' helper function not operating on
+ *                 an RSA context. Alternative implementations need not
+ *                 overwrite it.
+ *
+ * \param P        First prime factor of N
+ * \param Q        Second prime factor of N
+ * \param D        RSA private exponent
+ * \param DP       Output variable for D modulo P-1
+ * \param DQ       Output variable for D modulo Q-1
+ * \param QP       Output variable for the modular inverse of Q modulo P.
+ *
+ * \return         0 on success, non-zero error code otherwise.
+ *
+ * \note           This function does not check whether P, Q are
+ *                 prime and whether D is a valid private exponent.
+ *
+ */
+int mbedtls_rsa_deduce_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q,
+                            const mbedtls_mpi *D, mbedtls_mpi *DP,
+                            mbedtls_mpi *DQ, mbedtls_mpi *QP );
+
+
+/**
+ * \brief          Check validity of core RSA parameters
+ *
+ * \note           This is a 'static' helper function not operating on
+ *                 an RSA context. Alternative implementations need not
+ *                 overwrite it.
+ *
+ * \param N        RSA modulus N = PQ
+ * \param P        First prime factor of N
+ * \param Q        Second prime factor of N
+ * \param D        RSA private exponent
+ * \param E        RSA public exponent
+ * \param f_rng    PRNG to be used for primality check, or NULL
+ * \param p_rng    PRNG context for f_rng, or NULL
+ *
+ * \return
+ *                 - 0 if the following conditions are satisfied
+ *                   if all relevant parameters are provided:
+ *                    - P prime if f_rng != NULL (%)
+ *                    - Q prime if f_rng != NULL (%)
+ *                    - 1 < N = P * Q
+ *                    - 1 < D, E < N
+ *                    - D and E are modular inverses modulo P-1 and Q-1
+ *                   (%) This is only done if MBEDTLS_GENPRIME is defined.
+ *                 - A non-zero error code otherwise.
+ *
+ * \note           The function can be used with a restricted set of arguments
+ *                 to perform specific checks only. E.g., calling it with
+ *                 (-,P,-,-,-) and a PRNG amounts to a primality check for P.
+ */
+int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P,
+                                 const mbedtls_mpi *Q, const mbedtls_mpi *D,
+                                 const mbedtls_mpi *E,
+                                 int (*f_rng)(void *, unsigned char *, size_t),
+                                 void *p_rng );
+
+/**
+ * \brief          Check validity of RSA CRT parameters
+ *
+ * \note           This is a 'static' helper function not operating on
+ *                 an RSA context. Alternative implementations need not
+ *                 overwrite it.
+ *
+ * \param P        First prime factor of RSA modulus
+ * \param Q        Second prime factor of RSA modulus
+ * \param D        RSA private exponent
+ * \param DP       MPI to check for D modulo P-1
+ * \param DQ       MPI to check for D modulo P-1
+ * \param QP       MPI to check for the modular inverse of Q modulo P.
+ *
+ * \return
+ *                 - 0 if the following conditions are satisfied:
+ *                    - D = DP mod P-1 if P, D, DP != NULL
+ *                    - Q = DQ mod P-1 if P, D, DQ != NULL
+ *                    - QP = Q^-1 mod P if P, Q, QP != NULL
+ *                 - \c MBEDTLS_ERR_RSA_KEY_CHECK_FAILED if check failed,
+ *                   potentially including \c MBEDTLS_ERR_MPI_XXX if some
+ *                   MPI calculations failed.
+ *                 - \c MBEDTLS_ERR_RSA_BAD_INPUT_DATA if insufficient
+ *                   data was provided to check DP, DQ or QP.
+ *
+ * \note           The function can be used with a restricted set of arguments
+ *                 to perform specific checks only. E.g., calling it with the
+ *                 parameters (P, -, D, DP, -, -) will check DP = D mod P-1.
+ */
+int mbedtls_rsa_validate_crt( const mbedtls_mpi *P,  const mbedtls_mpi *Q,
+                              const mbedtls_mpi *D,  const mbedtls_mpi *DP,
+                              const mbedtls_mpi *DQ, const mbedtls_mpi *QP );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* rsa_internal.h */

+ 217 - 31
mbedtls/include/mbedtls/sha1.h

@@ -1,9 +1,14 @@
 /**
 /**
  * \file sha1.h
  * \file sha1.h
  *
  *
- * \brief SHA-1 cryptographic hash function
+ * \brief The SHA-1 cryptographic hash function.
  *
  *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * \warning   SHA-1 is considered a weak message digest and its use constitutes
+ *            a security risk. We recommend considering stronger message
+ *            digests instead.
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,7 +23,7 @@
  *  See the License for the specific language governing permissions and
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *  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_SHA1_H
 #ifndef MBEDTLS_SHA1_H
 #define MBEDTLS_SHA1_H
 #define MBEDTLS_SHA1_H
@@ -32,6 +37,8 @@
 #include <stddef.h>
 #include <stddef.h>
 #include <stdint.h>
 #include <stdint.h>
 
 
+#define MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED                  -0x0035  /**< SHA-1 hardware accelerator failed */
+
 #if !defined(MBEDTLS_SHA1_ALT)
 #if !defined(MBEDTLS_SHA1_ALT)
 // Regular implementation
 // Regular implementation
 //
 //
@@ -41,65 +48,197 @@ extern "C" {
 #endif
 #endif
 
 
 /**
 /**
- * \brief          SHA-1 context structure
+ * \brief          The SHA-1 context structure.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
 typedef struct
 typedef struct
 {
 {
-    uint32_t total[2];          /*!< number of bytes processed  */
-    uint32_t state[5];          /*!< intermediate digest state  */
-    unsigned char buffer[64];   /*!< data block being processed */
+    uint32_t total[2];          /*!< The number of Bytes processed.  */
+    uint32_t state[5];          /*!< The intermediate digest state.  */
+    unsigned char buffer[64];   /*!< The data block being processed. */
 }
 }
 mbedtls_sha1_context;
 mbedtls_sha1_context;
 
 
 /**
 /**
- * \brief          Initialize SHA-1 context
+ * \brief          This function initializes a SHA-1 context.
+ *
+ * \param ctx      The SHA-1 context to initialize.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
  *
  *
- * \param ctx      SHA-1 context to be initialized
  */
  */
 void mbedtls_sha1_init( mbedtls_sha1_context *ctx );
 void mbedtls_sha1_init( mbedtls_sha1_context *ctx );
 
 
 /**
 /**
- * \brief          Clear SHA-1 context
+ * \brief          This function clears a SHA-1 context.
+ *
+ * \param ctx      The SHA-1 context to clear.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
  *
  *
- * \param ctx      SHA-1 context to be cleared
  */
  */
 void mbedtls_sha1_free( mbedtls_sha1_context *ctx );
 void mbedtls_sha1_free( mbedtls_sha1_context *ctx );
 
 
 /**
 /**
- * \brief          Clone (the state of) a SHA-1 context
+ * \brief          This function clones the state of a SHA-1 context.
+ *
+ * \param dst      The destination context.
+ * \param src      The context to clone.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
  *
  *
- * \param dst      The destination context
- * \param src      The context to be cloned
  */
  */
 void mbedtls_sha1_clone( mbedtls_sha1_context *dst,
 void mbedtls_sha1_clone( mbedtls_sha1_context *dst,
                          const mbedtls_sha1_context *src );
                          const mbedtls_sha1_context *src );
 
 
+/**
+ * \brief          This function starts a SHA-1 checksum calculation.
+ *
+ * \param ctx      The context to initialize.
+ *
+ * \return         \c 0 if successful
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_sha1_starts_ret( mbedtls_sha1_context *ctx );
+
+/**
+ * \brief          This function feeds an input buffer into an ongoing SHA-1
+ *                 checksum calculation.
+ *
+ * \param ctx      The SHA-1 context.
+ * \param input    The buffer holding the input data.
+ * \param ilen     The length of the input data.
+ *
+ * \return         \c 0 if successful
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_sha1_update_ret( mbedtls_sha1_context *ctx,
+                             const unsigned char *input,
+                             size_t ilen );
+
+/**
+ * \brief          This function finishes the SHA-1 operation, and writes
+ *                 the result to the output buffer.
+ *
+ * \param ctx      The SHA-1 context.
+ * \param output   The SHA-1 checksum result.
+ *
+ * \return         \c 0 if successful
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_sha1_finish_ret( mbedtls_sha1_context *ctx,
+                             unsigned char output[20] );
+
+/**
+ * \brief          SHA-1 process data block (internal use only)
+ *
+ * \param ctx      SHA-1 context
+ * \param data     The data block being processed.
+ *
+ * \return         \c 0 if successful
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_internal_sha1_process( mbedtls_sha1_context *ctx,
+                                   const unsigned char data[64] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
 /**
 /**
  * \brief          SHA-1 context setup
  * \brief          SHA-1 context setup
  *
  *
- * \param ctx      context to be initialized
+ * \deprecated     Superseded by mbedtls_sha1_starts_ret() in 2.7.0
+ *
+ * \param ctx      The SHA-1 context to be initialized.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
-void mbedtls_sha1_starts( mbedtls_sha1_context *ctx );
+MBEDTLS_DEPRECATED void mbedtls_sha1_starts( mbedtls_sha1_context *ctx );
 
 
 /**
 /**
  * \brief          SHA-1 process buffer
  * \brief          SHA-1 process buffer
  *
  *
- * \param ctx      SHA-1 context
- * \param input    buffer holding the  data
- * \param ilen     length of the input data
+ * \deprecated     Superseded by mbedtls_sha1_update_ret() in 2.7.0
+ *
+ * \param ctx      The SHA-1 context.
+ * \param input    The buffer holding the input data.
+ * \param ilen     The length of the input data.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
-void mbedtls_sha1_update( mbedtls_sha1_context *ctx, const unsigned char *input, size_t ilen );
+MBEDTLS_DEPRECATED void mbedtls_sha1_update( mbedtls_sha1_context *ctx,
+                                             const unsigned char *input,
+                                             size_t ilen );
 
 
 /**
 /**
  * \brief          SHA-1 final digest
  * \brief          SHA-1 final digest
  *
  *
- * \param ctx      SHA-1 context
- * \param output   SHA-1 checksum result
+ * \deprecated     Superseded by mbedtls_sha1_finish_ret() in 2.7.0
+ *
+ * \param ctx      The SHA-1 context.
+ * \param output   The SHA-1 checksum result.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+MBEDTLS_DEPRECATED void mbedtls_sha1_finish( mbedtls_sha1_context *ctx,
+                                             unsigned char output[20] );
+
+/**
+ * \brief          SHA-1 process data block (internal use only)
+ *
+ * \deprecated     Superseded by mbedtls_internal_sha1_process() in 2.7.0
+ *
+ * \param ctx      The SHA-1 context.
+ * \param data     The data block being processed.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
-void mbedtls_sha1_finish( mbedtls_sha1_context *ctx, unsigned char output[20] );
+MBEDTLS_DEPRECATED void mbedtls_sha1_process( mbedtls_sha1_context *ctx,
+                                              const unsigned char data[64] );
 
 
-/* Internal use */
-void mbedtls_sha1_process( mbedtls_sha1_context *ctx, const unsigned char data[64] );
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
 }
 }
@@ -113,19 +252,66 @@ void mbedtls_sha1_process( mbedtls_sha1_context *ctx, const unsigned char data[6
 extern "C" {
 extern "C" {
 #endif
 #endif
 
 
+/**
+ * \brief          This function calculates the SHA-1 checksum of a buffer.
+ *
+ *                 The function allocates the context, performs the
+ *                 calculation, and frees the context.
+ *
+ *                 The SHA-1 result is calculated as
+ *                 output = SHA-1(input buffer).
+ *
+ * \param input    The buffer holding the input data.
+ * \param ilen     The length of the input data.
+ * \param output   The SHA-1 checksum result.
+ *
+ * \return         \c 0 if successful
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
+ */
+int mbedtls_sha1_ret( const unsigned char *input,
+                      size_t ilen,
+                      unsigned char output[20] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
 /**
 /**
  * \brief          Output = SHA-1( input buffer )
  * \brief          Output = SHA-1( input buffer )
  *
  *
- * \param input    buffer holding the  data
- * \param ilen     length of the input data
- * \param output   SHA-1 checksum result
+ * \deprecated     Superseded by mbedtls_sha1_ret() in 2.7.0
+ *
+ * \param input    The buffer holding the input data.
+ * \param ilen     The length of the input data.
+ * \param output   The SHA-1 checksum result.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
+ *
  */
  */
-void mbedtls_sha1( const unsigned char *input, size_t ilen, unsigned char output[20] );
+MBEDTLS_DEPRECATED void mbedtls_sha1( const unsigned char *input,
+                                      size_t ilen,
+                                      unsigned char output[20] );
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 
 /**
 /**
- * \brief          Checkup routine
+ * \brief          The SHA-1 checkup routine.
+ *
+ * \return         \c 0 on success, or \c 1 on failure.
+ *
+ * \warning        SHA-1 is considered a weak message digest and its use
+ *                 constitutes a security risk. We recommend considering
+ *                 stronger message digests instead.
  *
  *
- * \return         0 if successful, or 1 if the test failed
  */
  */
 int mbedtls_sha1_self_test( int verbose );
 int mbedtls_sha1_self_test( int verbose );
 
 

+ 176 - 39
mbedtls/include/mbedtls/sha256.h

@@ -1,9 +1,10 @@
 /**
 /**
  * \file sha256.h
  * \file sha256.h
  *
  *
- * \brief SHA-224 and SHA-256 cryptographic hash function
- *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * \brief The SHA-224 and SHA-256 cryptographic hash function.
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,7 +19,7 @@
  *  See the License for the specific language governing permissions and
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *  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_SHA256_H
 #ifndef MBEDTLS_SHA256_H
 #define MBEDTLS_SHA256_H
 #define MBEDTLS_SHA256_H
@@ -32,6 +33,8 @@
 #include <stddef.h>
 #include <stddef.h>
 #include <stdint.h>
 #include <stdint.h>
 
 
+#define MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED                -0x0037  /**< SHA-256 hardware accelerator failed */
+
 #if !defined(MBEDTLS_SHA256_ALT)
 #if !defined(MBEDTLS_SHA256_ALT)
 // Regular implementation
 // Regular implementation
 //
 //
@@ -41,69 +44,158 @@ extern "C" {
 #endif
 #endif
 
 
 /**
 /**
- * \brief          SHA-256 context structure
+ * \brief          The SHA-256 context structure.
+ *
+ *                 The structure is used both for SHA-256 and for SHA-224
+ *                 checksum calculations. The choice between these two is
+ *                 made in the call to mbedtls_sha256_starts_ret().
  */
  */
 typedef struct
 typedef struct
 {
 {
-    uint32_t total[2];          /*!< number of bytes processed  */
-    uint32_t state[8];          /*!< intermediate digest state  */
-    unsigned char buffer[64];   /*!< data block being processed */
-    int is224;                  /*!< 0 => SHA-256, else SHA-224 */
+    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. */
+    int is224;                  /*!< Determines which function to use.
+                                     <ul><li>0: Use SHA-256.</li>
+                                     <li>1: Use SHA-224.</li></ul> */
 }
 }
 mbedtls_sha256_context;
 mbedtls_sha256_context;
 
 
 /**
 /**
- * \brief          Initialize SHA-256 context
+ * \brief          This function initializes a SHA-256 context.
  *
  *
- * \param ctx      SHA-256 context to be initialized
+ * \param ctx      The SHA-256 context to initialize.
  */
  */
 void mbedtls_sha256_init( mbedtls_sha256_context *ctx );
 void mbedtls_sha256_init( mbedtls_sha256_context *ctx );
 
 
 /**
 /**
- * \brief          Clear SHA-256 context
+ * \brief          This function clears a SHA-256 context.
  *
  *
- * \param ctx      SHA-256 context to be cleared
+ * \param ctx      The SHA-256 context to clear.
  */
  */
 void mbedtls_sha256_free( mbedtls_sha256_context *ctx );
 void mbedtls_sha256_free( mbedtls_sha256_context *ctx );
 
 
 /**
 /**
- * \brief          Clone (the state of) a SHA-256 context
+ * \brief          This function clones the state of a SHA-256 context.
  *
  *
- * \param dst      The destination context
- * \param src      The context to be cloned
+ * \param dst      The destination context.
+ * \param src      The context to clone.
  */
  */
 void mbedtls_sha256_clone( mbedtls_sha256_context *dst,
 void mbedtls_sha256_clone( mbedtls_sha256_context *dst,
                            const mbedtls_sha256_context *src );
                            const mbedtls_sha256_context *src );
 
 
 /**
 /**
- * \brief          SHA-256 context setup
+ * \brief          This function starts a SHA-224 or SHA-256 checksum
+ *                 calculation.
+ *
+ * \param ctx      The context to initialize.
+ * \param is224    Determines which function to use.
+ *                 <ul><li>0: Use SHA-256.</li>
+ *                 <li>1: Use SHA-224.</li></ul>
  *
  *
- * \param ctx      context to be initialized
- * \param is224    0 = use SHA256, 1 = use SHA224
+ * \return         \c 0 on success.
  */
  */
-void mbedtls_sha256_starts( mbedtls_sha256_context *ctx, int is224 );
+int mbedtls_sha256_starts_ret( mbedtls_sha256_context *ctx, int is224 );
 
 
 /**
 /**
- * \brief          SHA-256 process buffer
+ * \brief          This function feeds an input buffer into an ongoing
+ *                 SHA-256 checksum calculation.
  *
  *
  * \param ctx      SHA-256 context
  * \param ctx      SHA-256 context
- * \param input    buffer holding the  data
+ * \param input    buffer holding the data
  * \param ilen     length of the input data
  * \param ilen     length of the input data
+ *
+ * \return         \c 0 on success.
  */
  */
-void mbedtls_sha256_update( mbedtls_sha256_context *ctx, const unsigned char *input,
-                    size_t ilen );
+int mbedtls_sha256_update_ret( mbedtls_sha256_context *ctx,
+                               const unsigned char *input,
+                               size_t ilen );
 
 
 /**
 /**
- * \brief          SHA-256 final digest
+ * \brief          This function finishes the SHA-256 operation, and writes
+ *                 the result to the output buffer.
  *
  *
- * \param ctx      SHA-256 context
- * \param output   SHA-224/256 checksum result
+ * \param ctx      The SHA-256 context.
+ * \param output   The SHA-224 or SHA-256 checksum result.
+ *
+ * \return         \c 0 on success.
+ */
+int mbedtls_sha256_finish_ret( mbedtls_sha256_context *ctx,
+                               unsigned char output[32] );
+
+/**
+ * \brief          This function processes a single data block within
+ *                 the ongoing SHA-256 computation. This function is for
+ *                 internal use only.
+ *
+ * \param ctx      The SHA-256 context.
+ * \param data     The buffer holding one block of data.
+ *
+ * \return         \c 0 on success.
+ */
+int mbedtls_internal_sha256_process( mbedtls_sha256_context *ctx,
+                                     const unsigned char data[64] );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          This function starts a SHA-256 checksum calculation.
+ *
+ * \deprecated     Superseded by mbedtls_sha256_starts_ret() in 2.7.0.
+ *
+ * \param ctx      The SHA-256 context to initialize.
+ * \param is224    Determines which function to use.
+ *                 <ul><li>0: Use SHA-256.</li>
+ *                 <li>1: Use SHA-224.</li></ul>
+ */
+MBEDTLS_DEPRECATED void mbedtls_sha256_starts( mbedtls_sha256_context *ctx,
+                                               int is224 );
+
+/**
+ * \brief          This function feeds an input buffer into an ongoing
+ *                 SHA-256 checksum calculation.
+ *
+ * \deprecated     Superseded by mbedtls_sha256_update_ret() in 2.7.0.
+ *
+ * \param ctx      The SHA-256 context to initialize.
+ * \param input    The buffer holding the data.
+ * \param ilen     The length of the input data.
+ */
+MBEDTLS_DEPRECATED void mbedtls_sha256_update( mbedtls_sha256_context *ctx,
+                                               const unsigned char *input,
+                                               size_t ilen );
+
+/**
+ * \brief          This function finishes the SHA-256 operation, and writes
+ *                 the result to the output buffer.
+ *
+ * \deprecated     Superseded by mbedtls_sha256_finish_ret() in 2.7.0.
+ *
+ * \param ctx      The SHA-256 context.
+ * \param output   The SHA-224or SHA-256 checksum result.
  */
  */
-void mbedtls_sha256_finish( mbedtls_sha256_context *ctx, unsigned char output[32] );
+MBEDTLS_DEPRECATED void mbedtls_sha256_finish( mbedtls_sha256_context *ctx,
+                                               unsigned char output[32] );
 
 
-/* Internal use */
-void mbedtls_sha256_process( mbedtls_sha256_context *ctx, const unsigned char data[64] );
+/**
+ * \brief          This function processes a single data block within
+ *                 the ongoing SHA-256 computation. This function is for
+ *                 internal use only.
+ *
+ * \deprecated     Superseded by mbedtls_internal_sha256_process() in 2.7.0.
+ *
+ * \param ctx      The SHA-256 context.
+ * \param data     The buffer holding one block of data.
+ */
+MBEDTLS_DEPRECATED void mbedtls_sha256_process( mbedtls_sha256_context *ctx,
+                                                const unsigned char data[64] );
 
 
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 #ifdef __cplusplus
 #ifdef __cplusplus
 }
 }
 #endif
 #endif
@@ -117,20 +209,65 @@ extern "C" {
 #endif
 #endif
 
 
 /**
 /**
- * \brief          Output = SHA-256( input buffer )
+ * \brief          This function calculates the SHA-224 or SHA-256
+ *                 checksum of a buffer.
  *
  *
- * \param input    buffer holding the  data
- * \param ilen     length of the input data
- * \param output   SHA-224/256 checksum result
- * \param is224    0 = use SHA256, 1 = use SHA224
+ *                 The function allocates the context, performs the
+ *                 calculation, and frees the context.
+ *
+ *                 The SHA-256 result is calculated as
+ *                 output = SHA-256(input buffer).
+ *
+ * \param input    The buffer holding the input data.
+ * \param ilen     The length of the input data.
+ * \param output   The SHA-224 or SHA-256 checksum result.
+ * \param is224    Determines which function to use.
+ *                 <ul><li>0: Use SHA-256.</li>
+ *                 <li>1: Use SHA-224.</li></ul>
+ */
+int mbedtls_sha256_ret( const unsigned char *input,
+                        size_t ilen,
+                        unsigned char output[32],
+                        int is224 );
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+
+/**
+ * \brief          This function calculates the SHA-224 or SHA-256 checksum
+ *                 of a buffer.
+ *
+ *                 The function allocates the context, performs the
+ *                 calculation, and frees the context.
+ *
+ *                 The SHA-256 result is calculated as
+ *                 output = SHA-256(input buffer).
+ *
+ * \deprecated     Superseded by mbedtls_sha256_ret() in 2.7.0.
+ *
+ * \param input    The buffer holding the data.
+ * \param ilen     The length of the input data.
+ * \param output   The SHA-224 or SHA-256 checksum result.
+ * \param is224    Determines which function to use.
+ *                 <ul><li>0: Use SHA-256.</li>
+ *                 <li>1: Use SHA-224.</li></ul>
  */
  */
-void mbedtls_sha256( const unsigned char *input, size_t ilen,
-           unsigned char output[32], int is224 );
+MBEDTLS_DEPRECATED void mbedtls_sha256( const unsigned char *input,
+                                        size_t ilen,
+                                        unsigned char output[32],
+                                        int is224 );
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 
 /**
 /**
- * \brief          Checkup routine
+ * \brief          The SHA-224 and SHA-256 checkup routine.
  *
  *
- * \return         0 if successful, or 1 if the test failed
+ * \return         \c 0 on success, or \c 1 on failure.
  */
  */
 int mbedtls_sha256_self_test( int verbose );
 int mbedtls_sha256_self_test( int verbose );
 
 

+ 180 - 41
mbedtls/include/mbedtls/sha512.h

@@ -1,9 +1,10 @@
 /**
 /**
  * \file sha512.h
  * \file sha512.h
  *
  *
- * \brief SHA-384 and SHA-512 cryptographic hash function
- *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ * \brief The SHA-384 and SHA-512 cryptographic hash function.
+ */
+/*
+ *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -18,7 +19,7 @@
  *  See the License for the specific language governing permissions and
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  *  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_SHA512_H
 #ifndef MBEDTLS_SHA512_H
 #define MBEDTLS_SHA512_H
 #define MBEDTLS_SHA512_H
@@ -32,6 +33,8 @@
 #include <stddef.h>
 #include <stddef.h>
 #include <stdint.h>
 #include <stdint.h>
 
 
+#define MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED                -0x0039  /**< SHA-512 hardware accelerator failed */
+
 #if !defined(MBEDTLS_SHA512_ALT)
 #if !defined(MBEDTLS_SHA512_ALT)
 // Regular implementation
 // Regular implementation
 //
 //
@@ -41,65 +44,159 @@ extern "C" {
 #endif
 #endif
 
 
 /**
 /**
- * \brief          SHA-512 context structure
+ * \brief          The SHA-512 context structure.
+ *
+ *                 The structure is used both for SHA-384 and for SHA-512
+ *                 checksum calculations. The choice between these two is
+ *                 made in the call to mbedtls_sha512_starts_ret().
  */
  */
 typedef struct
 typedef struct
 {
 {
-    uint64_t total[2];          /*!< number of bytes processed  */
-    uint64_t state[8];          /*!< intermediate digest state  */
-    unsigned char buffer[128];  /*!< data block being processed */
-    int is384;                  /*!< 0 => SHA-512, else SHA-384 */
+    uint64_t total[2];          /*!< The number of Bytes processed. */
+    uint64_t state[8];          /*!< The intermediate digest state. */
+    unsigned char buffer[128];  /*!< The data block being processed. */
+    int is384;                  /*!< Determines which function to use.
+                                 *   <ul><li>0: Use SHA-512.</li>
+                                 *   <li>1: Use SHA-384.</li></ul> */
 }
 }
 mbedtls_sha512_context;
 mbedtls_sha512_context;
 
 
 /**
 /**
- * \brief          Initialize SHA-512 context
+ * \brief          This function initializes a SHA-512 context.
  *
  *
- * \param ctx      SHA-512 context to be initialized
+ * \param ctx      The SHA-512 context to initialize.
  */
  */
 void mbedtls_sha512_init( mbedtls_sha512_context *ctx );
 void mbedtls_sha512_init( mbedtls_sha512_context *ctx );
 
 
 /**
 /**
- * \brief          Clear SHA-512 context
+ * \brief          This function clears a SHA-512 context.
  *
  *
- * \param ctx      SHA-512 context to be cleared
+ * \param ctx      The SHA-512 context to clear.
  */
  */
 void mbedtls_sha512_free( mbedtls_sha512_context *ctx );
 void mbedtls_sha512_free( mbedtls_sha512_context *ctx );
 
 
 /**
 /**
- * \brief          Clone (the state of) a SHA-512 context
+ * \brief          This function clones the state of a SHA-512 context.
  *
  *
- * \param dst      The destination context
- * \param src      The context to be cloned
+ * \param dst      The destination context.
+ * \param src      The context to clone.
  */
  */
 void mbedtls_sha512_clone( mbedtls_sha512_context *dst,
 void mbedtls_sha512_clone( mbedtls_sha512_context *dst,
                            const mbedtls_sha512_context *src );
                            const mbedtls_sha512_context *src );
 
 
 /**
 /**
- * \brief          SHA-512 context setup
+ * \brief          This function starts a SHA-384 or SHA-512 checksum
+ *                 calculation.
+ *
+ * \param ctx      The SHA-512 context to initialize.
+ * \param is384    Determines which function to use.
+ *                 <ul><li>0: Use SHA-512.</li>
+ *                 <li>1: Use SHA-384.</li></ul>
  *
  *
- * \param ctx      context to be initialized
- * \param is384    0 = use SHA512, 1 = use SHA384
+ * \return         \c 0 on success.
  */
  */
-void mbedtls_sha512_starts( mbedtls_sha512_context *ctx, int is384 );
+int mbedtls_sha512_starts_ret( mbedtls_sha512_context *ctx, int is384 );
 
 
 /**
 /**
- * \brief          SHA-512 process buffer
+ * \brief          This function feeds an input buffer into an ongoing
+ *                 SHA-512 checksum calculation.
+ *
+ * \param ctx      The SHA-512 context.
+ * \param input    The buffer holding the input data.
+ * \param ilen     The length of the input data.
  *
  *
- * \param ctx      SHA-512 context
- * \param input    buffer holding the  data
- * \param ilen     length of the input data
+ * \return         \c 0 on success.
  */
  */
-void mbedtls_sha512_update( mbedtls_sha512_context *ctx, const unsigned char *input,
+int mbedtls_sha512_update_ret( mbedtls_sha512_context *ctx,
+                    const unsigned char *input,
                     size_t ilen );
                     size_t ilen );
 
 
 /**
 /**
- * \brief          SHA-512 final digest
+ * \brief          This function finishes the SHA-512 operation, and writes
+ *                 the result to the output buffer. This function is for
+ *                 internal use only.
+ *
+ * \param ctx      The SHA-512 context.
+ * \param output   The SHA-384 or SHA-512 checksum result.
+ *
+ * \return         \c 0 on success.
+ */
+int mbedtls_sha512_finish_ret( mbedtls_sha512_context *ctx,
+                               unsigned char output[64] );
+
+/**
+ * \brief          This function processes a single data block within
+ *                 the ongoing SHA-512 computation.
+ *
+ * \param ctx      The SHA-512 context.
+ * \param data     The buffer holding one block of data.
+ *
+ * \return         \c 0 on success.
+ */
+int mbedtls_internal_sha512_process( mbedtls_sha512_context *ctx,
+                                     const unsigned char data[128] );
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+/**
+ * \brief          This function starts a SHA-384 or SHA-512 checksum
+ *                 calculation.
+ *
+ * \deprecated     Superseded by mbedtls_sha512_starts_ret() in 2.7.0
+ *
+ * \param ctx      The SHA-512 context to initialize.
+ * \param is384    Determines which function to use.
+ *                 <ul><li>0: Use SHA-512.</li>
+ *                 <li>1: Use SHA-384.</li></ul>
+ */
+MBEDTLS_DEPRECATED void mbedtls_sha512_starts( mbedtls_sha512_context *ctx,
+                                               int is384 );
+
+/**
+ * \brief          This function feeds an input buffer into an ongoing
+ *                 SHA-512 checksum calculation.
+ *
+ * \deprecated     Superseded by mbedtls_sha512_update_ret() in 2.7.0
+ *
+ * \param ctx      The SHA-512 context.
+ * \param input    The buffer holding the data.
+ * \param ilen     The length of the input data.
+ */
+MBEDTLS_DEPRECATED void mbedtls_sha512_update( mbedtls_sha512_context *ctx,
+                                               const unsigned char *input,
+                                               size_t ilen );
+
+/**
+ * \brief          This function finishes the SHA-512 operation, and writes
+ *                 the result to the output buffer.
+ *
+ * \deprecated     Superseded by mbedtls_sha512_finish_ret() in 2.7.0
+ *
+ * \param ctx      The SHA-512 context.
+ * \param output   The SHA-384 or SHA-512 checksum result.
+ */
+MBEDTLS_DEPRECATED void mbedtls_sha512_finish( mbedtls_sha512_context *ctx,
+                                               unsigned char output[64] );
+
+/**
+ * \brief          This function processes a single data block within
+ *                 the ongoing SHA-512 computation. This function is for
+ *                 internal use only.
  *
  *
- * \param ctx      SHA-512 context
- * \param output   SHA-384/512 checksum result
+ * \deprecated     Superseded by mbedtls_internal_sha512_process() in 2.7.0
+ *
+ * \param ctx      The SHA-512 context.
+ * \param data     The buffer holding one block of data.
  */
  */
-void mbedtls_sha512_finish( mbedtls_sha512_context *ctx, unsigned char output[64] );
+MBEDTLS_DEPRECATED void mbedtls_sha512_process(
+                                            mbedtls_sha512_context *ctx,
+                                            const unsigned char data[128] );
+
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
 }
 }
@@ -114,25 +211,67 @@ extern "C" {
 #endif
 #endif
 
 
 /**
 /**
- * \brief          Output = SHA-512( input buffer )
+ * \brief          This function calculates the SHA-512 or SHA-384
+ *                 checksum of a buffer.
+ *
+ *                 The function allocates the context, performs the
+ *                 calculation, and frees the context.
  *
  *
- * \param input    buffer holding the  data
- * \param ilen     length of the input data
- * \param output   SHA-384/512 checksum result
- * \param is384    0 = use SHA512, 1 = use SHA384
+ *                 The SHA-512 result is calculated as
+ *                 output = SHA-512(input buffer).
+ *
+ * \param input    The buffer holding the input data.
+ * \param ilen     The length of the input data.
+ * \param output   The SHA-384 or SHA-512 checksum result.
+ * \param is384    Determines which function to use.
+ *                 <ul><li>0: Use SHA-512.</li>
+ *                 <li>1: Use SHA-384.</li></ul>
+ *
+ * \return         \c 0 on success.
  */
  */
-void mbedtls_sha512( const unsigned char *input, size_t ilen,
-             unsigned char output[64], int is384 );
+int mbedtls_sha512_ret( const unsigned char *input,
+                        size_t ilen,
+                        unsigned char output[64],
+                        int is384 );
 
 
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED      __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
 /**
 /**
- * \brief          Checkup routine
+ * \brief          This function calculates the SHA-512 or SHA-384
+ *                 checksum of a buffer.
+ *
+ *                 The function allocates the context, performs the
+ *                 calculation, and frees the context.
+ *
+ *                 The SHA-512 result is calculated as
+ *                 output = SHA-512(input buffer).
  *
  *
- * \return         0 if successful, or 1 if the test failed
+ * \deprecated     Superseded by mbedtls_sha512_ret() in 2.7.0
+ *
+ * \param input    The buffer holding the data.
+ * \param ilen     The length of the input data.
+ * \param output   The SHA-384 or SHA-512 checksum result.
+ * \param is384    Determines which function to use.
+ *                 <ul><li>0: Use SHA-512.</li>
+ *                 <li>1: Use SHA-384.</li></ul>
  */
  */
-int mbedtls_sha512_self_test( int verbose );
+MBEDTLS_DEPRECATED void mbedtls_sha512( const unsigned char *input,
+                                        size_t ilen,
+                                        unsigned char output[64],
+                                        int is384 );
 
 
-/* Internal use */
-void mbedtls_sha512_process( mbedtls_sha512_context *ctx, const unsigned char data[128] );
+#undef MBEDTLS_DEPRECATED
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
+ /**
+ * \brief          The SHA-384 or SHA-512 checkup routine.
+ *
+ * \return         \c 0 on success, or \c 1 on failure.
+ */
+int mbedtls_sha512_self_test( int verbose );
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus
 }
 }

+ 104 - 34
mbedtls/include/mbedtls/ssl.h

@@ -2,7 +2,8 @@
  * \file ssl.h
  * \file ssl.h
  *
  *
  * \brief SSL/TLS functions.
  * \brief SSL/TLS functions.
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -52,7 +53,7 @@
 #endif
 #endif
 
 
 #if defined(MBEDTLS_HAVE_TIME)
 #if defined(MBEDTLS_HAVE_TIME)
-#include "mbedtls/platform_time.h"
+#include "platform_time.h"
 #endif
 #endif
 
 
 /*
 /*
@@ -927,14 +928,6 @@ extern int (*mbedtls_ssl_hw_record_read)(mbedtls_ssl_context *ssl);
 extern int (*mbedtls_ssl_hw_record_finish)(mbedtls_ssl_context *ssl);
 extern int (*mbedtls_ssl_hw_record_finish)(mbedtls_ssl_context *ssl);
 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
 
 
-/**
- * \brief Returns the list of ciphersuites supported by the SSL/TLS module.
- *
- * \return              a statically allocated array of ciphersuites, the last
- *                      entry is 0.
- */
-const int *mbedtls_ssl_list_ciphersuites( void );
-
 /**
 /**
  * \brief               Return the name of the ciphersuite associated with the
  * \brief               Return the name of the ciphersuite associated with the
  *                      given ID
  *                      given ID
@@ -970,8 +963,13 @@ void mbedtls_ssl_init( mbedtls_ssl_context *ssl );
  * \note           No copy of the configuration context is made, it can be
  * \note           No copy of the configuration context is made, it can be
  *                 shared by many mbedtls_ssl_context structures.
  *                 shared by many mbedtls_ssl_context structures.
  *
  *
- * \warning        Modifying the conf structure after it has been used in this
- *                 function is unsupported!
+ * \warning        The conf structure will be accessed during the session.
+ *                 It must not be modified or freed as long as the session
+ *                 is active.
+ *
+ * \warning        This function must be called exactly once per context.
+ *                 Calling mbedtls_ssl_setup again is not supported, even
+ *                 if no session is active.
  *
  *
  * \param ssl      SSL context
  * \param ssl      SSL context
  * \param conf     SSL configuration to use
  * \param conf     SSL configuration to use
@@ -1586,6 +1584,10 @@ void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf,
 /**
 /**
  * \brief          Set the data required to verify peer certificate
  * \brief          Set the data required to verify peer certificate
  *
  *
+ * \note           See \c mbedtls_x509_crt_verify() for notes regarding the
+ *                 parameters ca_chain (maps to trust_ca for that function)
+ *                 and ca_crl.
+ *
  * \param conf     SSL configuration
  * \param conf     SSL configuration
  * \param ca_chain trusted CA chain (meaning all fully trusted top-level CAs)
  * \param ca_chain trusted CA chain (meaning all fully trusted top-level CAs)
  * \param ca_crl   trusted CA CRLs
  * \param ca_crl   trusted CA CRLs
@@ -1616,6 +1618,14 @@ void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf,
  *                 whether it matches those preferences - the server can then
  *                 whether it matches those preferences - the server can then
  *                 decide what it wants to do with it.
  *                 decide what it wants to do with it.
  *
  *
+ * \note           The provided \p pk_key needs to match the public key in the
+ *                 first certificate in \p own_cert, or all handshakes using
+ *                 that certificate will fail. It is your responsibility
+ *                 to ensure that; this function will not perform any check.
+ *                 You may use mbedtls_pk_check_pair() in order to perform
+ *                 this check yourself, but be aware that this function can
+ *                 be computationally expensive on some key types.
+ *
  * \param conf     SSL configuration
  * \param conf     SSL configuration
  * \param own_cert own public certificate chain
  * \param own_cert own public certificate chain
  * \param pk_key   own private key
  * \param pk_key   own private key
@@ -1699,18 +1709,50 @@ void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf,
 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
 
 
 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED    __attribute__((deprecated))
+#else
+#define MBEDTLS_DEPRECATED
+#endif
+
 /**
 /**
  * \brief          Set the Diffie-Hellman public P and G values,
  * \brief          Set the Diffie-Hellman public P and G values,
  *                 read as hexadecimal strings (server-side only)
  *                 read as hexadecimal strings (server-side only)
- *                 (Default: MBEDTLS_DHM_RFC5114_MODP_2048_[PG])
+ *                 (Default values: MBEDTLS_DHM_RFC3526_MODP_2048_[PG])
  *
  *
  * \param conf     SSL configuration
  * \param conf     SSL configuration
  * \param dhm_P    Diffie-Hellman-Merkle modulus
  * \param dhm_P    Diffie-Hellman-Merkle modulus
  * \param dhm_G    Diffie-Hellman-Merkle generator
  * \param dhm_G    Diffie-Hellman-Merkle generator
  *
  *
+ * \deprecated     Superseded by \c mbedtls_ssl_conf_dh_param_bin.
+ *
+ * \return         0 if successful
+ */
+MBEDTLS_DEPRECATED int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf,
+                                                  const char *dhm_P,
+                                                  const char *dhm_G );
+
+#endif /* MBEDTLS_DEPRECATED_REMOVED */
+
+/**
+ * \brief          Set the Diffie-Hellman public P and G values
+ *                 from big-endian binary presentations.
+ *                 (Default values: MBEDTLS_DHM_RFC3526_MODP_2048_[PG]_BIN)
+ *
+ * \param conf     SSL configuration
+ * \param dhm_P    Diffie-Hellman-Merkle modulus in big-endian binary form
+ * \param P_len    Length of DHM modulus
+ * \param dhm_G    Diffie-Hellman-Merkle generator in big-endian binary form
+ * \param G_len    Length of DHM generator
+ *
  * \return         0 if successful
  * \return         0 if successful
  */
  */
-int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G );
+int mbedtls_ssl_conf_dh_param_bin( mbedtls_ssl_config *conf,
+                                   const unsigned char *dhm_P, size_t P_len,
+                                   const unsigned char *dhm_G,  size_t G_len );
 
 
 /**
 /**
  * \brief          Set the Diffie-Hellman public P and G values,
  * \brief          Set the Diffie-Hellman public P and G values,
@@ -1794,15 +1836,22 @@ void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf,
 
 
 #if defined(MBEDTLS_X509_CRT_PARSE_C)
 #if defined(MBEDTLS_X509_CRT_PARSE_C)
 /**
 /**
- * \brief          Set the hostname to check against the received server
- *                 certificate. It sets the ServerName TLS extension too,
- *                 if the extension is enabled.
- *                 (client-side only)
+ * \brief          Set or reset the hostname to check against the received
+ *                 server certificate. It sets the ServerName TLS extension,
+ *                 too, if that extension is enabled. (client-side only)
  *
  *
  * \param ssl      SSL context
  * \param ssl      SSL context
- * \param hostname the server hostname
+ * \param hostname the server hostname, may be NULL to clear hostname
  *
  *
- * \return         0 if successful or MBEDTLS_ERR_SSL_ALLOC_FAILED
+ * \note           Maximum hostname length MBEDTLS_SSL_MAX_HOST_NAME_LEN.
+ *
+ * \return         0 if successful, MBEDTLS_ERR_SSL_ALLOC_FAILED on
+ *                 allocation failure, MBEDTLS_ERR_SSL_BAD_INPUT_DATA on
+ *                 too long input hostname.
+ *
+ *                 Hostname set to the one provided on success (cleared
+ *                 when NULL). On allocation failure hostname is cleared.
+ *                 On too long input failure, old hostname is unchanged.
  */
  */
 int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname );
 int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname );
 #endif /* MBEDTLS_X509_CRT_PARSE_C */
 #endif /* MBEDTLS_X509_CRT_PARSE_C */
@@ -2246,13 +2295,14 @@ size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl );
 /**
 /**
  * \brief          Return the result of the certificate verification
  * \brief          Return the result of the certificate verification
  *
  *
- * \param ssl      SSL context
+ * \param ssl      The SSL context to use.
  *
  *
- * \return         0 if successful,
- *                 -1 if result is not available (eg because the handshake was
- *                 aborted too early), or
- *                 a combination of BADCERT_xxx and BADCRL_xxx flags, see
- *                 x509.h
+ * \return         \c 0 if the certificate verification was successful.
+ * \return         \c -1u if the result is not available. This may happen
+ *                 e.g. if the handshake aborts early, or a verification
+ *                 callback returned a fatal error.
+ * \return         A bitwise combination of \c MBEDTLS_X509_BADCERT_XXX
+ *                 and \c MBEDTLS_X509_BADCRL_XXX failure flags; see x509.h.
  */
  */
 uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl );
 uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl );
 
 
@@ -2329,7 +2379,6 @@ const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ss
  * \brief          Save session in order to resume it later (client-side only)
  * \brief          Save session in order to resume it later (client-side only)
  *                 Session data is copied to presented session structure.
  *                 Session data is copied to presented session structure.
  *
  *
- * \warning        Currently, peer certificate is lost in the operation.
  *
  *
  * \param ssl      SSL context
  * \param ssl      SSL context
  * \param session  session context
  * \param session  session context
@@ -2337,7 +2386,18 @@ const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ss
  * \return         0 if successful,
  * \return         0 if successful,
  *                 MBEDTLS_ERR_SSL_ALLOC_FAILED if memory allocation failed,
  *                 MBEDTLS_ERR_SSL_ALLOC_FAILED if memory allocation failed,
  *                 MBEDTLS_ERR_SSL_BAD_INPUT_DATA if used server-side or
  *                 MBEDTLS_ERR_SSL_BAD_INPUT_DATA if used server-side or
- *                 arguments are otherwise invalid
+ *                 arguments are otherwise invalid.
+ *
+ * \note           Only the server certificate is copied, and not the full chain,
+ *                 so you should not attempt to validate the certificate again
+ *                 by calling \c mbedtls_x509_crt_verify() on it.
+ *                 Instead, you should use the results from the verification
+ *                 in the original handshake by calling \c mbedtls_ssl_get_verify_result()
+ *                 after loading the session again into a new SSL context
+ *                 using \c mbedtls_ssl_set_session().
+ *
+ * \note           Once the session object is not needed anymore, you should
+ *                 free it by calling \c mbedtls_ssl_session_free().
  *
  *
  * \sa             mbedtls_ssl_set_session()
  * \sa             mbedtls_ssl_set_session()
  */
  */
@@ -2463,15 +2523,19 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )
  *                 or MBEDTLS_ERR_SSL_WANT_WRITE or MBEDTLS_ERR_SSL_WANT_READ,
  *                 or MBEDTLS_ERR_SSL_WANT_WRITE or MBEDTLS_ERR_SSL_WANT_READ,
  *                 or another negative error code.
  *                 or another negative error code.
  *
  *
- * \note           If this function returns something other than a positive
- *                 value or MBEDTLS_ERR_SSL_WANT_READ/WRITE, the ssl context
- *                 becomes unusable, and you should either free it or call
- *                 \c mbedtls_ssl_session_reset() on it before re-using it for
- *                 a new connection; the current connection must be closed.
+ * \note           If this function returns something other than 0, a positive
+ *                 value or MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop
+ *                 using the SSL context for reading or writing, and either
+ *                 free it or call \c mbedtls_ssl_session_reset() on it before
+ *                 re-using it for a new connection; the current connection
+ *                 must be closed.
  *
  *
  * \note           When this function returns MBEDTLS_ERR_SSL_WANT_WRITE/READ,
  * \note           When this function returns MBEDTLS_ERR_SSL_WANT_WRITE/READ,
  *                 it must be called later with the *same* arguments,
  *                 it must be called later with the *same* arguments,
- *                 until it returns a positive value.
+ *                 until it returns a value greater that or equal to 0. When
+ *                 the function returns MBEDTLS_ERR_SSL_WANT_WRITE there may be
+ *                 some partial data in the output buffer, however this is not
+ *                 yet sent.
  *
  *
  * \note           If the requested length is greater than the maximum
  * \note           If the requested length is greater than the maximum
  *                 fragment length (either the built-in limit or the one set
  *                 fragment length (either the built-in limit or the one set
@@ -2480,6 +2544,9 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )
  *                 - with DTLS, MBEDTLS_ERR_SSL_BAD_INPUT_DATA is returned.
  *                 - with DTLS, MBEDTLS_ERR_SSL_BAD_INPUT_DATA is returned.
  *                 \c mbedtls_ssl_get_max_frag_len() may be used to query the
  *                 \c mbedtls_ssl_get_max_frag_len() may be used to query the
  *                 active maximum fragment length.
  *                 active maximum fragment length.
+ *
+ * \note           Attempting to write 0 bytes will result in an empty TLS
+ *                 application record being sent.
  */
  */
 int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len );
 int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len );
 
 
@@ -2572,6 +2639,9 @@ void mbedtls_ssl_session_init( mbedtls_ssl_session *session );
  * \brief          Free referenced items in an SSL session including the
  * \brief          Free referenced items in an SSL session including the
  *                 peer certificate and clear memory
  *                 peer certificate and clear memory
  *
  *
+ * \note           A session object can be freed even if the SSL context
+ *                 that was used to retrieve the session is still in use.
+ *
  * \param session  SSL session
  * \param session  SSL session
  */
  */
 void mbedtls_ssl_session_free( mbedtls_ssl_session *session );
 void mbedtls_ssl_session_free( mbedtls_ssl_session *session );

+ 8 - 1
mbedtls/include/mbedtls/ssl_cache.h

@@ -2,7 +2,8 @@
  * \file ssl_cache.h
  * \file ssl_cache.h
  *
  *
  * \brief SSL session cache implementation
  * \brief SSL session cache implementation
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -23,6 +24,12 @@
 #ifndef MBEDTLS_SSL_CACHE_H
 #ifndef MBEDTLS_SSL_CACHE_H
 #define MBEDTLS_SSL_CACHE_H
 #define MBEDTLS_SSL_CACHE_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include "ssl.h"
 #include "ssl.h"
 
 
 #if defined(MBEDTLS_THREADING_C)
 #if defined(MBEDTLS_THREADING_C)

+ 9 - 2
mbedtls/include/mbedtls/ssl_ciphersuites.h

@@ -2,7 +2,8 @@
  * \file ssl_ciphersuites.h
  * \file ssl_ciphersuites.h
  *
  *
  * \brief SSL Ciphersuites for mbed TLS
  * \brief SSL Ciphersuites for mbed TLS
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -23,6 +24,12 @@
 #ifndef MBEDTLS_SSL_CIPHERSUITES_H
 #ifndef MBEDTLS_SSL_CIPHERSUITES_H
 #define MBEDTLS_SSL_CIPHERSUITES_H
 #define MBEDTLS_SSL_CIPHERSUITES_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include "pk.h"
 #include "pk.h"
 #include "cipher.h"
 #include "cipher.h"
 #include "md.h"
 #include "md.h"
@@ -266,7 +273,7 @@ typedef enum {
     defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)      ||       \
     defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)      ||       \
     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)     ||       \
     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)     ||       \
     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)    ||       \
     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)    ||       \
-    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) 
+    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
 #define MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED
 #define MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED
 #endif
 #endif
 
 

+ 8 - 1
mbedtls/include/mbedtls/ssl_cookie.h

@@ -2,7 +2,8 @@
  * \file ssl_cookie.h
  * \file ssl_cookie.h
  *
  *
  * \brief DTLS cookie callbacks implementation
  * \brief DTLS cookie callbacks implementation
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -23,6 +24,12 @@
 #ifndef MBEDTLS_SSL_COOKIE_H
 #ifndef MBEDTLS_SSL_COOKIE_H
 #define MBEDTLS_SSL_COOKIE_H
 #define MBEDTLS_SSL_COOKIE_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include "ssl.h"
 #include "ssl.h"
 
 
 #if defined(MBEDTLS_THREADING_C)
 #if defined(MBEDTLS_THREADING_C)

+ 65 - 11
mbedtls/include/mbedtls/ssl_internal.h

@@ -1,8 +1,9 @@
 /**
 /**
- * \file ssl_ticket.h
+ * \file ssl_internal.h
  *
  *
  * \brief Internal functions shared by the SSL modules
  * \brief Internal functions shared by the SSL modules
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -23,7 +24,14 @@
 #ifndef MBEDTLS_SSL_INTERNAL_H
 #ifndef MBEDTLS_SSL_INTERNAL_H
 #define MBEDTLS_SSL_INTERNAL_H
 #define MBEDTLS_SSL_INTERNAL_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 #include "ssl.h"
 #include "ssl.h"
+#include "cipher.h"
 
 
 #if defined(MBEDTLS_MD5_C)
 #if defined(MBEDTLS_MD5_C)
 #include "md5.h"
 #include "md5.h"
@@ -69,6 +77,9 @@
 #endif /* MBEDTLS_SSL_PROTO_TLS1   */
 #endif /* MBEDTLS_SSL_PROTO_TLS1   */
 #endif /* MBEDTLS_SSL_PROTO_SSL3   */
 #endif /* MBEDTLS_SSL_PROTO_SSL3   */
 
 
+#define MBEDTLS_SSL_MIN_VALID_MINOR_VERSION MBEDTLS_SSL_MINOR_VERSION_1
+#define MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION MBEDTLS_SSL_MAJOR_VERSION_3
+
 /* Determine maximum supported version */
 /* Determine maximum supported version */
 #define MBEDTLS_SSL_MAX_MAJOR_VERSION           MBEDTLS_SSL_MAJOR_VERSION_3
 #define MBEDTLS_SSL_MAX_MAJOR_VERSION           MBEDTLS_SSL_MAJOR_VERSION_3
 
 
@@ -138,13 +149,33 @@
 #define MBEDTLS_SSL_PADDING_ADD              0
 #define MBEDTLS_SSL_PADDING_ADD              0
 #endif
 #endif
 
 
-#define MBEDTLS_SSL_BUFFER_LEN  ( MBEDTLS_SSL_MAX_CONTENT_LEN               \
-                        + MBEDTLS_SSL_COMPRESSION_ADD               \
-                        + 29 /* counter + header + IV */    \
-                        + MBEDTLS_SSL_MAC_ADD                       \
-                        + MBEDTLS_SSL_PADDING_ADD                   \
+#define MBEDTLS_SSL_PAYLOAD_LEN ( MBEDTLS_SSL_MAX_CONTENT_LEN    \
+                        + MBEDTLS_SSL_COMPRESSION_ADD            \
+                        + MBEDTLS_MAX_IV_LENGTH                  \
+                        + MBEDTLS_SSL_MAC_ADD                    \
+                        + MBEDTLS_SSL_PADDING_ADD                \
                         )
                         )
 
 
+/*
+ * Check that we obey the standard's message size bounds
+ */
+
+#if MBEDTLS_SSL_MAX_CONTENT_LEN > 16384
+#error Bad configuration - record content too large.
+#endif
+
+#if MBEDTLS_SSL_PAYLOAD_LEN > 16384 + 2048
+#error Bad configuration - protected record payload too large.
+#endif
+
+/* Note: Even though the TLS record header is only 5 bytes
+   long, we're internally using 8 bytes to store the
+   implicit sequence number. */
+#define MBEDTLS_SSL_HEADER_LEN 13
+
+#define MBEDTLS_SSL_BUFFER_LEN  \
+    ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_PAYLOAD_LEN ) )
+
 /*
 /*
  * TLS extension flags (for extensions with outgoing ServerHello content
  * TLS extension flags (for extensions with outgoing ServerHello content
  * that need it (e.g. for RENEGOTIATION_INFO the server already knows because
  * that need it (e.g. for RENEGOTIATION_INFO the server already knows because
@@ -600,16 +631,39 @@ void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl );
 static inline int mbedtls_ssl_safer_memcmp( const void *a, const void *b, size_t n )
 static inline int mbedtls_ssl_safer_memcmp( const void *a, const void *b, size_t n )
 {
 {
     size_t i;
     size_t i;
-    const unsigned char *A = (const unsigned char *) a;
-    const unsigned char *B = (const unsigned char *) b;
-    unsigned char diff = 0;
+    volatile const unsigned char *A = (volatile const unsigned char *) a;
+    volatile const unsigned char *B = (volatile const unsigned char *) b;
+    volatile unsigned char diff = 0;
 
 
     for( i = 0; i < n; i++ )
     for( i = 0; i < n; i++ )
-        diff |= A[i] ^ B[i];
+    {
+        /* Read volatile data in order before computing diff.
+         * This avoids IAR compiler warning:
+         * 'the order of volatile accesses is undefined ..' */
+        unsigned char x = A[i], y = B[i];
+        diff |= x ^ y;
+    }
 
 
     return( diff );
     return( diff );
 }
 }
 
 
+#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
+    defined(MBEDTLS_SSL_PROTO_TLS1_1)
+int mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl,
+                                        unsigned char *output,
+                                        unsigned char *data, size_t data_len );
+#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
+          MBEDTLS_SSL_PROTO_TLS1_1 */
+
+#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
+    defined(MBEDTLS_SSL_PROTO_TLS1_2)
+int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl,
+                                        unsigned char *output,
+                                        unsigned char *data, size_t data_len,
+                                        mbedtls_md_type_t md_alg );
+#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
+          MBEDTLS_SSL_PROTO_TLS1_2 */
+
 #ifdef __cplusplus
 #ifdef __cplusplus
 }
 }
 #endif
 #endif

+ 8 - 1
mbedtls/include/mbedtls/ssl_ticket.h

@@ -2,7 +2,8 @@
  * \file ssl_ticket.h
  * \file ssl_ticket.h
  *
  *
  * \brief TLS server ticket callbacks implementation
  * \brief TLS server ticket callbacks implementation
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -23,6 +24,12 @@
 #ifndef MBEDTLS_SSL_TICKET_H
 #ifndef MBEDTLS_SSL_TICKET_H
 #define MBEDTLS_SSL_TICKET_H
 #define MBEDTLS_SSL_TICKET_H
 
 
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
 /*
 /*
  * This implementation of the session ticket callbacks includes key
  * This implementation of the session ticket callbacks includes key
  * management, rotating the keys periodically in order to preserve forward
  * management, rotating the keys periodically in order to preserve forward

+ 6 - 1
mbedtls/include/mbedtls/threading.h

@@ -2,7 +2,8 @@
  * \file threading.h
  * \file threading.h
  *
  *
  * \brief Threading abstraction layer
  * \brief Threading abstraction layer
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -95,8 +96,12 @@ extern int (*mbedtls_mutex_unlock)( mbedtls_threading_mutex_t *mutex );
 /*
 /*
  * Global mutexes
  * Global mutexes
  */
  */
+#if defined(MBEDTLS_FS_IO)
 extern mbedtls_threading_mutex_t mbedtls_threading_readdir_mutex;
 extern mbedtls_threading_mutex_t mbedtls_threading_readdir_mutex;
+#endif
+#if defined(MBEDTLS_HAVE_TIME_DATE)
 extern mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex;
 extern mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex;
+#endif
 #endif /* MBEDTLS_THREADING_C */
 #endif /* MBEDTLS_THREADING_C */
 
 
 #ifdef __cplusplus
 #ifdef __cplusplus

+ 25 - 5
mbedtls/include/mbedtls/timing.h

@@ -1,8 +1,9 @@
 /**
 /**
  * \file timing.h
  * \file timing.h
  *
  *
- * \brief Portable interface to the CPU cycle counter
- *
+ * \brief Portable interface to timeouts and to the CPU cycle counter
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -65,6 +66,9 @@ extern volatile int mbedtls_timing_alarmed;
  * \warning        This is only a best effort! Do not rely on this!
  * \warning        This is only a best effort! Do not rely on this!
  *                 In particular, it is known to be unreliable on virtual
  *                 In particular, it is known to be unreliable on virtual
  *                 machines.
  *                 machines.
+ *
+ * \note           This value starts at an unspecified origin and
+ *                 may wrap around.
  */
  */
 unsigned long mbedtls_timing_hardclock( void );
 unsigned long mbedtls_timing_hardclock( void );
 
 
@@ -72,7 +76,18 @@ unsigned long mbedtls_timing_hardclock( void );
  * \brief          Return the elapsed time in milliseconds
  * \brief          Return the elapsed time in milliseconds
  *
  *
  * \param val      points to a timer structure
  * \param val      points to a timer structure
- * \param reset    if set to 1, the timer is restarted
+ * \param reset    If 0, query the elapsed time. Otherwise (re)start the timer.
+ *
+ * \return         Elapsed time since the previous reset in ms. When
+ *                 restarting, this is always 0.
+ *
+ * \note           To initialize a timer, call this function with reset=1.
+ *
+ *                 Determining the elapsed time and resetting the timer is not
+ *                 atomic on all platforms, so after the sequence
+ *                 `{ get_timer(1); ...; time1 = get_timer(1); ...; time2 =
+ *                 get_timer(0) }` the value time1+time2 is only approximately
+ *                 the delay since the first reset.
  */
  */
 unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset );
 unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset );
 
 
@@ -80,6 +95,7 @@ unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int
  * \brief          Setup an alarm clock
  * \brief          Setup an alarm clock
  *
  *
  * \param seconds  delay before the "mbedtls_timing_alarmed" flag is set
  * \param seconds  delay before the "mbedtls_timing_alarmed" flag is set
+ *                 (must be >=0)
  *
  *
  * \warning        Only one alarm at a time  is supported. In a threaded
  * \warning        Only one alarm at a time  is supported. In a threaded
  *                 context, this means one for the whole process, not one per
  *                 context, this means one for the whole process, not one per
@@ -91,11 +107,15 @@ void mbedtls_set_alarm( int seconds );
  * \brief          Set a pair of delays to watch
  * \brief          Set a pair of delays to watch
  *                 (See \c mbedtls_timing_get_delay().)
  *                 (See \c mbedtls_timing_get_delay().)
  *
  *
- * \param data     Pointer to timing data
+ * \param data     Pointer to timing data.
  *                 Must point to a valid \c mbedtls_timing_delay_context struct.
  *                 Must point to a valid \c mbedtls_timing_delay_context struct.
  * \param int_ms   First (intermediate) delay in milliseconds.
  * \param int_ms   First (intermediate) delay in milliseconds.
+ *                 The effect if int_ms > fin_ms is unspecified.
  * \param fin_ms   Second (final) delay in milliseconds.
  * \param fin_ms   Second (final) delay in milliseconds.
  *                 Pass 0 to cancel the current delay.
  *                 Pass 0 to cancel the current delay.
+ *
+ * \note           To set a single delay, either use \c mbedtls_timing_set_timer
+ *                 directly or use this function with int_ms == fin_ms.
  */
  */
 void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms );
 void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms );
 
 
@@ -106,7 +126,7 @@ void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms );
  * \param data     Pointer to timing data
  * \param data     Pointer to timing data
  *                 Must point to a valid \c mbedtls_timing_delay_context struct.
  *                 Must point to a valid \c mbedtls_timing_delay_context struct.
  *
  *
- * \return         -1 if cancelled (fin_ms = 0)
+ * \return         -1 if cancelled (fin_ms = 0),
  *                  0 if none of the delays are passed,
  *                  0 if none of the delays are passed,
  *                  1 if only the intermediate delay is passed,
  *                  1 if only the intermediate delay is passed,
  *                  2 if the final delay is passed.
  *                  2 if the final delay is passed.

+ 7 - 6
mbedtls/include/mbedtls/version.h

@@ -2,7 +2,8 @@
  * \file version.h
  * \file version.h
  *
  *
  * \brief Run-time version information
  * \brief Run-time version information
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -38,17 +39,17 @@
  * Major, Minor, Patchlevel
  * Major, Minor, Patchlevel
  */
  */
 #define MBEDTLS_VERSION_MAJOR  2
 #define MBEDTLS_VERSION_MAJOR  2
-#define MBEDTLS_VERSION_MINOR  6
-#define MBEDTLS_VERSION_PATCH  0
+#define MBEDTLS_VERSION_MINOR  7
+#define MBEDTLS_VERSION_PATCH  10
 
 
 /**
 /**
  * The single version number has the following structure:
  * The single version number has the following structure:
  *    MMNNPP00
  *    MMNNPP00
  *    Major version | Minor version | Patch version
  *    Major version | Minor version | Patch version
  */
  */
-#define MBEDTLS_VERSION_NUMBER         0x02060000
-#define MBEDTLS_VERSION_STRING         "2.6.0"
-#define MBEDTLS_VERSION_STRING_FULL    "mbed TLS 2.6.0"
+#define MBEDTLS_VERSION_NUMBER         0x02070A00
+#define MBEDTLS_VERSION_STRING         "2.7.10"
+#define MBEDTLS_VERSION_STRING_FULL    "mbed TLS 2.7.10"
 
 
 #if defined(MBEDTLS_VERSION_C)
 #if defined(MBEDTLS_VERSION_C)
 
 

+ 2 - 1
mbedtls/include/mbedtls/x509.h

@@ -2,7 +2,8 @@
  * \file x509.h
  * \file x509.h
  *
  *
  * \brief X.509 generic defines and structures
  * \brief X.509 generic defines and structures
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *

+ 2 - 1
mbedtls/include/mbedtls/x509_crl.h

@@ -2,7 +2,8 @@
  * \file x509_crl.h
  * \file x509_crl.h
  *
  *
  * \brief X.509 certificate revocation list parsing
  * \brief X.509 certificate revocation list parsing
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *

+ 46 - 22
mbedtls/include/mbedtls/x509_crt.h

@@ -2,7 +2,8 @@
  * \file x509_crt.h
  * \file x509_crt.h
  *
  *
  * \brief X.509 certificate parsing and writing
  * \brief X.509 certificate parsing and writing
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -174,19 +175,34 @@ int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *bu
                         size_t buflen );
                         size_t buflen );
 
 
 /**
 /**
- * \brief          Parse one or more certificates and add them
- *                 to the chained list. Parses permissively. If some
- *                 certificates can be parsed, the result is the number
- *                 of failed certificates it encountered. If none complete
- *                 correctly, the first error is returned.
+ * \brief          Parse one DER-encoded or one or more concatenated PEM-encoded
+ *                 certificates and add them to the chained list.
  *
  *
- * \param chain    points to the start of the chain
- * \param buf      buffer holding the certificate data in PEM or DER format
- * \param buflen   size of the buffer
- *                 (including the terminating null byte for PEM data)
+ *                 For CRTs in PEM encoding, the function parses permissively:
+ *                 if at least one certificate can be parsed, the function
+ *                 returns the number of certificates for which parsing failed
+ *                 (hence \c 0 if all certificates were parsed successfully).
+ *                 If no certificate could be parsed, the function returns
+ *                 the first (negative) error encountered during parsing.
+ *
+ *                 PEM encoded certificates may be interleaved by other data
+ *                 such as human readable descriptions of their content, as
+ *                 long as the certificates are enclosed in the PEM specific
+ *                 '-----{BEGIN/END} CERTIFICATE-----' delimiters.
+ *
+ * \param chain    The chain to which to add the parsed certificates.
+ * \param buf      The buffer holding the certificate data in PEM or DER format.
+ *                 For certificates in PEM encoding, this may be a concatenation
+ *                 of multiple certificates; for DER encoding, the buffer must
+ *                 comprise exactly one certificate.
+ * \param buflen   The size of \p buf, including the terminating \c NULL byte
+ *                 in case of PEM encoded data.
+ *
+ * \return         \c 0 if all certificates were parsed successfully.
+ * \return         The (positive) number of certificates that couldn't
+ *                 be parsed if parsing was partly successful (see above).
+ * \return         A negative X509 or PEM error code otherwise.
  *
  *
- * \return         0 if all certificates parsed successfully, a positive number
- *                 if partly successful or a specific X509 or PEM error code
  */
  */
 int mbedtls_x509_crt_parse( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen );
 int mbedtls_x509_crt_parse( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen );
 
 
@@ -286,8 +302,15 @@ int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
  *                 used to sign the certificate, CRL verification is skipped
  *                 used to sign the certificate, CRL verification is skipped
  *                 silently, that is *without* setting any flag.
  *                 silently, that is *without* setting any flag.
  *
  *
+ * \note           The \c trust_ca list can contain two types of certificates:
+ *                 (1) those of trusted root CAs, so that certificates
+ *                 chaining up to those CAs will be trusted, and (2)
+ *                 self-signed end-entity certificates to be trusted (for
+ *                 specific peers you know) - in that case, the self-signed
+ *                 certificate doesn't need to have the CA bit set.
+ *
  * \param crt      a certificate (chain) to be verified
  * \param crt      a certificate (chain) to be verified
- * \param trust_ca the list of trusted CAs
+ * \param trust_ca the list of trusted CAs (see note above)
  * \param ca_crl   the list of CRLs for trusted CAs (see note above)
  * \param ca_crl   the list of CRLs for trusted CAs (see note above)
  * \param cn       expected Common Name (can be set to
  * \param cn       expected Common Name (can be set to
  *                 NULL if the CN must not be verified)
  *                 NULL if the CN must not be verified)
@@ -373,21 +396,22 @@ int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,
 
 
 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
 /**
 /**
- * \brief          Check usage of certificate against extentedJeyUsage.
+ * \brief           Check usage of certificate against extendedKeyUsage.
  *
  *
- * \param crt      Leaf certificate used.
- * \param usage_oid Intended usage (eg MBEDTLS_OID_SERVER_AUTH or MBEDTLS_OID_CLIENT_AUTH).
+ * \param crt       Leaf certificate used.
+ * \param usage_oid Intended usage (eg MBEDTLS_OID_SERVER_AUTH or
+ *                  MBEDTLS_OID_CLIENT_AUTH).
  * \param usage_len Length of usage_oid (eg given by MBEDTLS_OID_SIZE()).
  * \param usage_len Length of usage_oid (eg given by MBEDTLS_OID_SIZE()).
  *
  *
- * \return         0 if this use of the certificate is allowed,
- *                 MBEDTLS_ERR_X509_BAD_INPUT_DATA if not.
+ * \return          0 if this use of the certificate is allowed,
+ *                  MBEDTLS_ERR_X509_BAD_INPUT_DATA if not.
  *
  *
- * \note           Usually only makes sense on leaf certificates.
+ * \note            Usually only makes sense on leaf certificates.
  */
  */
 int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt,
 int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt,
-                                       const char *usage_oid,
-                                       size_t usage_len );
-#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) */
+                                               const char *usage_oid,
+                                               size_t usage_len );
+#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
 
 
 #if defined(MBEDTLS_X509_CRL_PARSE_C)
 #if defined(MBEDTLS_X509_CRL_PARSE_C)
 /**
 /**

+ 10 - 1
mbedtls/include/mbedtls/x509_csr.h

@@ -2,7 +2,8 @@
  * \file x509_csr.h
  * \file x509_csr.h
  *
  *
  * \brief X.509 certificate signing request parsing and writing
  * \brief X.509 certificate signing request parsing and writing
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -204,6 +205,14 @@ void mbedtls_x509write_csr_set_md_alg( mbedtls_x509write_csr *ctx, mbedtls_md_ty
  * \param key_usage key usage flags to set
  * \param key_usage key usage flags to set
  *
  *
  * \return          0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
  * \return          0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
+ *
+ * \note            The <code>decipherOnly</code> flag from the Key Usage
+ *                  extension is represented by bit 8 (i.e.
+ *                  <code>0x8000</code>), which cannot typically be represented
+ *                  in an unsigned char. Therefore, the flag
+ *                  <code>decipherOnly</code> (i.e.
+ *                  #MBEDTLS_X509_KU_DECIPHER_ONLY) cannot be set using this
+ *                  function.
  */
  */
 int mbedtls_x509write_csr_set_key_usage( mbedtls_x509write_csr *ctx, unsigned char key_usage );
 int mbedtls_x509write_csr_set_key_usage( mbedtls_x509write_csr *ctx, unsigned char key_usage );
 
 

+ 3 - 1
mbedtls/include/mbedtls/xtea.h

@@ -2,7 +2,8 @@
  * \file xtea.h
  * \file xtea.h
  *
  *
  * \brief XTEA block cipher (32-bit)
  * \brief XTEA block cipher (32-bit)
- *
+ */
+/*
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *  SPDX-License-Identifier: Apache-2.0
  *
  *
@@ -36,6 +37,7 @@
 #define MBEDTLS_XTEA_DECRYPT     0
 #define MBEDTLS_XTEA_DECRYPT     0
 
 
 #define MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH             -0x0028  /**< The data input has an invalid length. */
 #define MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH             -0x0028  /**< The data input has an invalid length. */
+#define MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED                  -0x0029  /**< XTEA hardware accelerator failed. */
 
 
 #if !defined(MBEDTLS_XTEA_ALT)
 #if !defined(MBEDTLS_XTEA_ALT)
 // Regular implementation
 // Regular implementation

+ 10 - 3
mbedtls/library/CMakeLists.txt

@@ -48,6 +48,7 @@ set(src_crypto
     platform.c
     platform.c
     ripemd160.c
     ripemd160.c
     rsa.c
     rsa.c
+    rsa_internal.c
     sha1.c
     sha1.c
     sha256.c
     sha256.c
     sha512.c
     sha512.c
@@ -90,6 +91,12 @@ if(CMAKE_COMPILER_IS_CLANG)
     set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wmissing-declarations -Wmissing-prototypes -Wdocumentation -Wno-documentation-deprecated-sync -Wunreachable-code")
     set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wmissing-declarations -Wmissing-prototypes -Wdocumentation -Wno-documentation-deprecated-sync -Wunreachable-code")
 endif(CMAKE_COMPILER_IS_CLANG)
 endif(CMAKE_COMPILER_IS_CLANG)
 
 
+if(UNSAFE_BUILD)
+    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-error")
+    set(CMAKE_C_FLAGS_ASAN "${CMAKE_C_FLAGS_ASAN} -Wno-error")
+    set(CMAKE_C_FLAGS_ASANDBG "${CMAKE_C_FLAGS_ASANDBG} -Wno-error")
+endif(UNSAFE_BUILD)
+
 if(WIN32)
 if(WIN32)
     set(libs ${libs} ws2_32)
     set(libs ${libs} ws2_32)
 endif(WIN32)
 endif(WIN32)
@@ -140,15 +147,15 @@ endif(USE_STATIC_MBEDTLS_LIBRARY)
 
 
 if(USE_SHARED_MBEDTLS_LIBRARY)
 if(USE_SHARED_MBEDTLS_LIBRARY)
     add_library(mbedcrypto SHARED ${src_crypto})
     add_library(mbedcrypto SHARED ${src_crypto})
-    set_target_properties(mbedcrypto PROPERTIES VERSION 2.6.0 SOVERSION 0)
+    set_target_properties(mbedcrypto PROPERTIES VERSION 2.7.10 SOVERSION 2)
     target_link_libraries(mbedcrypto ${libs})
     target_link_libraries(mbedcrypto ${libs})
 
 
     add_library(mbedx509 SHARED ${src_x509})
     add_library(mbedx509 SHARED ${src_x509})
-    set_target_properties(mbedx509 PROPERTIES VERSION 2.6.0 SOVERSION 0)
+    set_target_properties(mbedx509 PROPERTIES VERSION 2.7.10 SOVERSION 0)
     target_link_libraries(mbedx509 ${libs} mbedcrypto)
     target_link_libraries(mbedx509 ${libs} mbedcrypto)
 
 
     add_library(mbedtls SHARED ${src_tls})
     add_library(mbedtls SHARED ${src_tls})
-    set_target_properties(mbedtls PROPERTIES VERSION 2.6.0 SOVERSION 10)
+    set_target_properties(mbedtls PROPERTIES VERSION 2.7.10 SOVERSION 10)
     target_link_libraries(mbedtls ${libs} mbedx509)
     target_link_libraries(mbedtls ${libs} mbedx509)
 
 
     install(TARGETS mbedtls mbedx509 mbedcrypto
     install(TARGETS mbedtls mbedx509 mbedcrypto

+ 20 - 17
mbedtls/library/Makefile

@@ -33,11 +33,14 @@ endif
 
 
 SOEXT_TLS=so.10
 SOEXT_TLS=so.10
 SOEXT_X509=so.0
 SOEXT_X509=so.0
-SOEXT_CRYPTO=so.0
+SOEXT_CRYPTO=so.2
 
 
-DLEXT=so
-# OSX shared library extension:
-# DLEXT=dylib
+# Set DLEXT=dylib to compile as a shared library for Mac OS X
+DLEXT ?= so
+
+# Set AR_DASH= (empty string) to use an ar implentation that does not accept
+# the - prefix for command line options (e.g. llvm-ar)
+AR_DASH ?= -
 
 
 # Windows shared library extension:
 # Windows shared library extension:
 ifdef WINDOWS_BUILD
 ifdef WINDOWS_BUILD
@@ -59,9 +62,9 @@ OBJS_CRYPTO=	aes.o		aesni.o		arc4.o		\
 		padlock.o	pem.o		pk.o		\
 		padlock.o	pem.o		pk.o		\
 		pk_wrap.o	pkcs12.o	pkcs5.o		\
 		pk_wrap.o	pkcs12.o	pkcs5.o		\
 		pkparse.o	pkwrite.o	platform.o	\
 		pkparse.o	pkwrite.o	platform.o	\
-		ripemd160.o	rsa.o		sha1.o		\
-		sha256.o	sha512.o	threading.o	\
-		timing.o	version.o			\
+		ripemd160.o	rsa_internal.o	rsa.o  		\
+		sha1.o		sha256.o	sha512.o	\
+		threading.o	timing.o	version.o	\
 		version_features.o		xtea.o
 		version_features.o		xtea.o
 
 
 OBJS_X509=	certs.o		pkcs11.o	x509.o		\
 OBJS_X509=	certs.o		pkcs11.o	x509.o		\
@@ -91,9 +94,9 @@ shared: libmbedcrypto.$(DLEXT) libmbedx509.$(DLEXT) libmbedtls.$(DLEXT)
 # tls
 # tls
 libmbedtls.a: $(OBJS_TLS)
 libmbedtls.a: $(OBJS_TLS)
 	echo "  AR    $@"
 	echo "  AR    $@"
-	$(AR) -rc $@ $(OBJS_TLS)
+	$(AR) $(AR_DASH)rc $@ $(OBJS_TLS)
 	echo "  RL    $@"
 	echo "  RL    $@"
-	$(AR) -s $@
+	$(AR) $(AR_DASH)s $@
 
 
 libmbedtls.$(SOEXT_TLS): $(OBJS_TLS) libmbedx509.so
 libmbedtls.$(SOEXT_TLS): $(OBJS_TLS) libmbedx509.so
 	echo "  LD    $@"
 	echo "  LD    $@"
@@ -103,9 +106,9 @@ libmbedtls.so: libmbedtls.$(SOEXT_TLS)
 	echo "  LN    $@ -> $<"
 	echo "  LN    $@ -> $<"
 	ln -sf $< $@
 	ln -sf $< $@
 
 
-libmbedtls.dylib: $(OBJS_TLS)
+libmbedtls.dylib: $(OBJS_TLS) libmbedx509.dylib
 	echo "  LD    $@"
 	echo "  LD    $@"
-	$(CC) -dynamiclib $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@ $(OBJS_TLS)
+	$(CC) -dynamiclib -L. -lmbedcrypto -lmbedx509 $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@ $(OBJS_TLS)
 
 
 libmbedtls.dll: $(OBJS_TLS) libmbedx509.dll
 libmbedtls.dll: $(OBJS_TLS) libmbedx509.dll
 	echo "  LD    $@"
 	echo "  LD    $@"
@@ -114,9 +117,9 @@ libmbedtls.dll: $(OBJS_TLS) libmbedx509.dll
 # x509
 # x509
 libmbedx509.a: $(OBJS_X509)
 libmbedx509.a: $(OBJS_X509)
 	echo "  AR    $@"
 	echo "  AR    $@"
-	$(AR) -rc $@ $(OBJS_X509)
+	$(AR) $(AR_DASH)rc $@ $(OBJS_X509)
 	echo "  RL    $@"
 	echo "  RL    $@"
-	$(AR) -s $@
+	$(AR) $(AR_DASH)s $@
 
 
 libmbedx509.$(SOEXT_X509): $(OBJS_X509) libmbedcrypto.so
 libmbedx509.$(SOEXT_X509): $(OBJS_X509) libmbedcrypto.so
 	echo "  LD    $@"
 	echo "  LD    $@"
@@ -126,9 +129,9 @@ libmbedx509.so: libmbedx509.$(SOEXT_X509)
 	echo "  LN    $@ -> $<"
 	echo "  LN    $@ -> $<"
 	ln -sf $< $@
 	ln -sf $< $@
 
 
-libmbedx509.dylib: $(OBJS_X509)
+libmbedx509.dylib: $(OBJS_X509) libmbedcrypto.dylib
 	echo "  LD    $@"
 	echo "  LD    $@"
-	$(CC) -dynamiclib $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@ $(OBJS_X509)
+	$(CC) -dynamiclib -L. -lmbedcrypto  $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@ $(OBJS_X509)
 
 
 libmbedx509.dll: $(OBJS_X509) libmbedcrypto.dll
 libmbedx509.dll: $(OBJS_X509) libmbedcrypto.dll
 	echo "  LD    $@"
 	echo "  LD    $@"
@@ -137,9 +140,9 @@ libmbedx509.dll: $(OBJS_X509) libmbedcrypto.dll
 # crypto
 # crypto
 libmbedcrypto.a: $(OBJS_CRYPTO)
 libmbedcrypto.a: $(OBJS_CRYPTO)
 	echo "  AR    $@"
 	echo "  AR    $@"
-	$(AR) -rc $@ $(OBJS_CRYPTO)
+	$(AR) $(AR_DASH)rc $@ $(OBJS_CRYPTO)
 	echo "  RL    $@"
 	echo "  RL    $@"
-	$(AR) -s $@
+	$(AR) $(AR_DASH)s $@
 
 
 libmbedcrypto.$(SOEXT_CRYPTO): $(OBJS_CRYPTO)
 libmbedcrypto.$(SOEXT_CRYPTO): $(OBJS_CRYPTO)
 	echo "  LD    $@"
 	echo "  LD    $@"

+ 130 - 108
mbedtls/library/aes.c

@@ -765,12 +765,14 @@ int mbedtls_internal_aes_encrypt( mbedtls_aes_context *ctx,
 }
 }
 #endif /* !MBEDTLS_AES_ENCRYPT_ALT */
 #endif /* !MBEDTLS_AES_ENCRYPT_ALT */
 
 
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
 void mbedtls_aes_encrypt( mbedtls_aes_context *ctx,
 void mbedtls_aes_encrypt( mbedtls_aes_context *ctx,
                           const unsigned char input[16],
                           const unsigned char input[16],
                           unsigned char output[16] )
                           unsigned char output[16] )
 {
 {
     mbedtls_internal_aes_encrypt( ctx, input, output );
     mbedtls_internal_aes_encrypt( ctx, input, output );
 }
 }
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 
 /*
 /*
  * AES-ECB block decryption
  * AES-ECB block decryption
@@ -831,12 +833,14 @@ int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx,
 }
 }
 #endif /* !MBEDTLS_AES_DECRYPT_ALT */
 #endif /* !MBEDTLS_AES_DECRYPT_ALT */
 
 
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
 void mbedtls_aes_decrypt( mbedtls_aes_context *ctx,
 void mbedtls_aes_decrypt( mbedtls_aes_context *ctx,
                           const unsigned char input[16],
                           const unsigned char input[16],
                           unsigned char output[16] )
                           unsigned char output[16] )
 {
 {
     mbedtls_internal_aes_decrypt( ctx, input, output );
     mbedtls_internal_aes_decrypt( ctx, input, output );
 }
 }
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
 
 
 /*
 /*
  * AES-ECB block encryption/decryption
  * AES-ECB block encryption/decryption
@@ -1235,9 +1239,11 @@ static const int aes_test_ctr_len[3] =
  */
  */
 int mbedtls_aes_self_test( int verbose )
 int mbedtls_aes_self_test( int verbose )
 {
 {
-    int ret = 0, i, j, u, v;
+    int ret = 0, i, j, u, mode;
+    unsigned int keybits;
     unsigned char key[32];
     unsigned char key[32];
     unsigned char buf[64];
     unsigned char buf[64];
+    const unsigned char *aes_tests;
 #if defined(MBEDTLS_CIPHER_MODE_CBC) || defined(MBEDTLS_CIPHER_MODE_CFB)
 #if defined(MBEDTLS_CIPHER_MODE_CBC) || defined(MBEDTLS_CIPHER_MODE_CFB)
     unsigned char iv[16];
     unsigned char iv[16];
 #endif
 #endif
@@ -1263,45 +1269,52 @@ int mbedtls_aes_self_test( int verbose )
     for( i = 0; i < 6; i++ )
     for( i = 0; i < 6; i++ )
     {
     {
         u = i >> 1;
         u = i >> 1;
-        v = i  & 1;
+        keybits = 128 + u * 64;
+        mode = i & 1;
 
 
         if( verbose != 0 )
         if( verbose != 0 )
-            mbedtls_printf( "  AES-ECB-%3d (%s): ", 128 + u * 64,
-                             ( v == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" );
+            mbedtls_printf( "  AES-ECB-%3d (%s): ", keybits,
+                            ( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" );
 
 
         memset( buf, 0, 16 );
         memset( buf, 0, 16 );
 
 
-        if( v == MBEDTLS_AES_DECRYPT )
+        if( mode == MBEDTLS_AES_DECRYPT )
         {
         {
-            mbedtls_aes_setkey_dec( &ctx, key, 128 + u * 64 );
-
-            for( j = 0; j < 10000; j++ )
-                mbedtls_aes_crypt_ecb( &ctx, v, buf, buf );
-
-            if( memcmp( buf, aes_test_ecb_dec[u], 16 ) != 0 )
-            {
-                if( verbose != 0 )
-                    mbedtls_printf( "failed\n" );
-
-                ret = 1;
-                goto exit;
-            }
+            ret = mbedtls_aes_setkey_dec( &ctx, key, keybits );
+            aes_tests = aes_test_ecb_dec[u];
         }
         }
         else
         else
         {
         {
-            mbedtls_aes_setkey_enc( &ctx, key, 128 + u * 64 );
-
-            for( j = 0; j < 10000; j++ )
-                mbedtls_aes_crypt_ecb( &ctx, v, buf, buf );
+            ret = mbedtls_aes_setkey_enc( &ctx, key, keybits );
+            aes_tests = aes_test_ecb_enc[u];
+        }
 
 
-            if( memcmp( buf, aes_test_ecb_enc[u], 16 ) != 0 )
-            {
-                if( verbose != 0 )
-                    mbedtls_printf( "failed\n" );
+        /*
+         * AES-192 is an optional feature that may be unavailable when
+         * there is an alternative underlying implementation i.e. when
+         * MBEDTLS_AES_ALT is defined.
+         */
+        if( ret == MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE && keybits == 192 )
+        {
+            mbedtls_printf( "skipped\n" );
+            continue;
+        }
+        else if( ret != 0 )
+        {
+            goto exit;
+        }
 
 
-                ret = 1;
+        for( j = 0; j < 10000; j++ )
+        {
+            ret = mbedtls_aes_crypt_ecb( &ctx, mode, buf, buf );
+            if( ret != 0 )
                 goto exit;
                 goto exit;
-            }
+        }
+
+        if( memcmp( buf, aes_tests, 16 ) != 0 )
+        {
+            ret = 1;
+            goto exit;
         }
         }
 
 
         if( verbose != 0 )
         if( verbose != 0 )
@@ -1318,55 +1331,64 @@ int mbedtls_aes_self_test( int verbose )
     for( i = 0; i < 6; i++ )
     for( i = 0; i < 6; i++ )
     {
     {
         u = i >> 1;
         u = i >> 1;
-        v = i  & 1;
+        keybits = 128 + u * 64;
+        mode = i & 1;
 
 
         if( verbose != 0 )
         if( verbose != 0 )
-            mbedtls_printf( "  AES-CBC-%3d (%s): ", 128 + u * 64,
-                             ( v == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" );
+            mbedtls_printf( "  AES-CBC-%3d (%s): ", keybits,
+                            ( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" );
 
 
         memset( iv , 0, 16 );
         memset( iv , 0, 16 );
         memset( prv, 0, 16 );
         memset( prv, 0, 16 );
         memset( buf, 0, 16 );
         memset( buf, 0, 16 );
 
 
-        if( v == MBEDTLS_AES_DECRYPT )
+        if( mode == MBEDTLS_AES_DECRYPT )
         {
         {
-            mbedtls_aes_setkey_dec( &ctx, key, 128 + u * 64 );
-
-            for( j = 0; j < 10000; j++ )
-                mbedtls_aes_crypt_cbc( &ctx, v, 16, iv, buf, buf );
-
-            if( memcmp( buf, aes_test_cbc_dec[u], 16 ) != 0 )
-            {
-                if( verbose != 0 )
-                    mbedtls_printf( "failed\n" );
-
-                ret = 1;
-                goto exit;
-            }
+            ret = mbedtls_aes_setkey_dec( &ctx, key, keybits );
+            aes_tests = aes_test_cbc_dec[u];
         }
         }
         else
         else
         {
         {
-            mbedtls_aes_setkey_enc( &ctx, key, 128 + u * 64 );
+            ret = mbedtls_aes_setkey_enc( &ctx, key, keybits );
+            aes_tests = aes_test_cbc_enc[u];
+        }
+
+        /*
+         * AES-192 is an optional feature that may be unavailable when
+         * there is an alternative underlying implementation i.e. when
+         * MBEDTLS_AES_ALT is defined.
+         */
+        if( ret == MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE && keybits == 192 )
+        {
+            mbedtls_printf( "skipped\n" );
+            continue;
+        }
+        else if( ret != 0 )
+        {
+            goto exit;
+        }
 
 
-            for( j = 0; j < 10000; j++ )
+        for( j = 0; j < 10000; j++ )
+        {
+            if( mode == MBEDTLS_AES_ENCRYPT )
             {
             {
                 unsigned char tmp[16];
                 unsigned char tmp[16];
 
 
-                mbedtls_aes_crypt_cbc( &ctx, v, 16, iv, buf, buf );
-
                 memcpy( tmp, prv, 16 );
                 memcpy( tmp, prv, 16 );
                 memcpy( prv, buf, 16 );
                 memcpy( prv, buf, 16 );
                 memcpy( buf, tmp, 16 );
                 memcpy( buf, tmp, 16 );
             }
             }
 
 
-            if( memcmp( prv, aes_test_cbc_enc[u], 16 ) != 0 )
-            {
-                if( verbose != 0 )
-                    mbedtls_printf( "failed\n" );
-
-                ret = 1;
+            ret = mbedtls_aes_crypt_cbc( &ctx, mode, 16, iv, buf, buf );
+            if( ret != 0 )
                 goto exit;
                 goto exit;
-            }
+
+        }
+
+        if( memcmp( buf, aes_tests, 16 ) != 0 )
+        {
+            ret = 1;
+            goto exit;
         }
         }
 
 
         if( verbose != 0 )
         if( verbose != 0 )
@@ -1384,45 +1406,52 @@ int mbedtls_aes_self_test( int verbose )
     for( i = 0; i < 6; i++ )
     for( i = 0; i < 6; i++ )
     {
     {
         u = i >> 1;
         u = i >> 1;
-        v = i  & 1;
+        keybits = 128 + u * 64;
+        mode = i & 1;
 
 
         if( verbose != 0 )
         if( verbose != 0 )
-            mbedtls_printf( "  AES-CFB128-%3d (%s): ", 128 + u * 64,
-                             ( v == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" );
+            mbedtls_printf( "  AES-CFB128-%3d (%s): ", keybits,
+                            ( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" );
 
 
         memcpy( iv,  aes_test_cfb128_iv, 16 );
         memcpy( iv,  aes_test_cfb128_iv, 16 );
-        memcpy( key, aes_test_cfb128_key[u], 16 + u * 8 );
+        memcpy( key, aes_test_cfb128_key[u], keybits / 8 );
 
 
         offset = 0;
         offset = 0;
-        mbedtls_aes_setkey_enc( &ctx, key, 128 + u * 64 );
+        ret = mbedtls_aes_setkey_enc( &ctx, key, keybits );
+        /*
+         * AES-192 is an optional feature that may be unavailable when
+         * there is an alternative underlying implementation i.e. when
+         * MBEDTLS_AES_ALT is defined.
+         */
+        if( ret == MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE && keybits == 192 )
+        {
+            mbedtls_printf( "skipped\n" );
+            continue;
+        }
+        else if( ret != 0 )
+        {
+            goto exit;
+        }
 
 
-        if( v == MBEDTLS_AES_DECRYPT )
+        if( mode == MBEDTLS_AES_DECRYPT )
         {
         {
             memcpy( buf, aes_test_cfb128_ct[u], 64 );
             memcpy( buf, aes_test_cfb128_ct[u], 64 );
-            mbedtls_aes_crypt_cfb128( &ctx, v, 64, &offset, iv, buf, buf );
-
-            if( memcmp( buf, aes_test_cfb128_pt, 64 ) != 0 )
-            {
-                if( verbose != 0 )
-                    mbedtls_printf( "failed\n" );
-
-                ret = 1;
-                goto exit;
-            }
+            aes_tests = aes_test_cfb128_pt;
         }
         }
         else
         else
         {
         {
             memcpy( buf, aes_test_cfb128_pt, 64 );
             memcpy( buf, aes_test_cfb128_pt, 64 );
-            mbedtls_aes_crypt_cfb128( &ctx, v, 64, &offset, iv, buf, buf );
+            aes_tests = aes_test_cfb128_ct[u];
+        }
 
 
-            if( memcmp( buf, aes_test_cfb128_ct[u], 64 ) != 0 )
-            {
-                if( verbose != 0 )
-                    mbedtls_printf( "failed\n" );
+        ret = mbedtls_aes_crypt_cfb128( &ctx, mode, 64, &offset, iv, buf, buf );
+        if( ret != 0 )
+            goto exit;
 
 
-                ret = 1;
-                goto exit;
-            }
+        if( memcmp( buf, aes_tests, 64 ) != 0 )
+        {
+            ret = 1;
+            goto exit;
         }
         }
 
 
         if( verbose != 0 )
         if( verbose != 0 )
@@ -1440,51 +1469,41 @@ int mbedtls_aes_self_test( int verbose )
     for( i = 0; i < 6; i++ )
     for( i = 0; i < 6; i++ )
     {
     {
         u = i >> 1;
         u = i >> 1;
-        v = i  & 1;
+        mode = i & 1;
 
 
         if( verbose != 0 )
         if( verbose != 0 )
             mbedtls_printf( "  AES-CTR-128 (%s): ",
             mbedtls_printf( "  AES-CTR-128 (%s): ",
-                             ( v == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" );
+                            ( mode == MBEDTLS_AES_DECRYPT ) ? "dec" : "enc" );
 
 
         memcpy( nonce_counter, aes_test_ctr_nonce_counter[u], 16 );
         memcpy( nonce_counter, aes_test_ctr_nonce_counter[u], 16 );
         memcpy( key, aes_test_ctr_key[u], 16 );
         memcpy( key, aes_test_ctr_key[u], 16 );
 
 
         offset = 0;
         offset = 0;
-        mbedtls_aes_setkey_enc( &ctx, key, 128 );
+        if( ( ret = mbedtls_aes_setkey_enc( &ctx, key, 128 ) ) != 0 )
+            goto exit;
+
+        len = aes_test_ctr_len[u];
 
 
-        if( v == MBEDTLS_AES_DECRYPT )
+        if( mode == MBEDTLS_AES_DECRYPT )
         {
         {
-            len = aes_test_ctr_len[u];
             memcpy( buf, aes_test_ctr_ct[u], len );
             memcpy( buf, aes_test_ctr_ct[u], len );
-
-            mbedtls_aes_crypt_ctr( &ctx, len, &offset, nonce_counter, stream_block,
-                           buf, buf );
-
-            if( memcmp( buf, aes_test_ctr_pt[u], len ) != 0 )
-            {
-                if( verbose != 0 )
-                    mbedtls_printf( "failed\n" );
-
-                ret = 1;
-                goto exit;
-            }
+            aes_tests = aes_test_ctr_pt[u];
         }
         }
         else
         else
         {
         {
-            len = aes_test_ctr_len[u];
             memcpy( buf, aes_test_ctr_pt[u], len );
             memcpy( buf, aes_test_ctr_pt[u], len );
+            aes_tests = aes_test_ctr_ct[u];
+        }
 
 
-            mbedtls_aes_crypt_ctr( &ctx, len, &offset, nonce_counter, stream_block,
-                           buf, buf );
-
-            if( memcmp( buf, aes_test_ctr_ct[u], len ) != 0 )
-            {
-                if( verbose != 0 )
-                    mbedtls_printf( "failed\n" );
+        ret = mbedtls_aes_crypt_ctr( &ctx, len, &offset, nonce_counter,
+                                     stream_block, buf, buf );
+        if( ret != 0 )
+            goto exit;
 
 
-                ret = 1;
-                goto exit;
-            }
+        if( memcmp( buf, aes_tests, len ) != 0 )
+        {
+            ret = 1;
+            goto exit;
         }
         }
 
 
         if( verbose != 0 )
         if( verbose != 0 )
@@ -1498,6 +1517,9 @@ int mbedtls_aes_self_test( int verbose )
     ret = 0;
     ret = 0;
 
 
 exit:
 exit:
+    if( ret != 0 && verbose != 0 )
+        mbedtls_printf( "failed\n" );
+
     mbedtls_aes_free( &ctx );
     mbedtls_aes_free( &ctx );
 
 
     return( ret );
     return( ret );

+ 45 - 14
mbedtls/library/asn1write.c

@@ -83,7 +83,9 @@ int mbedtls_asn1_write_len( unsigned char **p, unsigned char *start, size_t len
         return( 4 );
         return( 4 );
     }
     }
 
 
+#if SIZE_MAX > 0xFFFFFFFF
     if( len <= 0xFFFFFFFF )
     if( len <= 0xFFFFFFFF )
+#endif
     {
     {
         if( *p - start < 5 )
         if( *p - start < 5 )
             return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
             return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
@@ -96,7 +98,9 @@ int mbedtls_asn1_write_len( unsigned char **p, unsigned char *start, size_t len
         return( 5 );
         return( 5 );
     }
     }
 
 
+#if SIZE_MAX > 0xFFFFFFFF
     return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );
     return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );
+#endif
 }
 }
 
 
 int mbedtls_asn1_write_tag( unsigned char **p, unsigned char *start, unsigned char tag )
 int mbedtls_asn1_write_tag( unsigned char **p, unsigned char *start, unsigned char tag )
@@ -232,7 +236,6 @@ int mbedtls_asn1_write_int( unsigned char **p, unsigned char *start, int val )
     int ret;
     int ret;
     size_t len = 0;
     size_t len = 0;
 
 
-    // TODO negative values and values larger than 128
     // DER format assumes 2s complement for numbers, so the leftmost bit
     // DER format assumes 2s complement for numbers, so the leftmost bit
     // should be 0 for positive numbers and 1 for negative numbers.
     // should be 0 for positive numbers and 1 for negative numbers.
     //
     //
@@ -291,22 +294,28 @@ int mbedtls_asn1_write_bitstring( unsigned char **p, unsigned char *start,
                           const unsigned char *buf, size_t bits )
                           const unsigned char *buf, size_t bits )
 {
 {
     int ret;
     int ret;
-    size_t len = 0, size;
+    size_t len = 0;
+    size_t unused_bits, byte_len;
 
 
-    size = ( bits / 8 ) + ( ( bits % 8 ) ? 1 : 0 );
+    byte_len = ( bits + 7 ) / 8;
+    unused_bits = ( byte_len * 8 ) - bits;
 
 
-    // Calculate byte length
-    //
-    if( *p < start || (size_t)( *p - start ) < size + 1 )
+    if( *p < start || (size_t)( *p - start ) < byte_len + 1 )
         return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
         return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL );
 
 
-    len = size + 1;
-    (*p) -= size;
-    memcpy( *p, buf, size );
+    len = byte_len + 1;
 
 
-    // Write unused bits
-    //
-    *--(*p) = (unsigned char) (size * 8 - bits);
+    /* Write the bitstring. Ensure the unused bits are zeroed */
+    if( byte_len > 0 )
+    {
+        byte_len--;
+        *--( *p ) = buf[byte_len] & ~( ( 0x1 << unused_bits ) - 1 );
+        ( *p ) -= byte_len;
+        memcpy( *p, buf, byte_len );
+    }
+
+    /* Write unused bits */
+    *--( *p ) = (unsigned char)unused_bits;
 
 
     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_BIT_STRING ) );
     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start, MBEDTLS_ASN1_BIT_STRING ) );
@@ -328,14 +337,36 @@ int mbedtls_asn1_write_octet_string( unsigned char **p, unsigned char *start,
     return( (int) len );
     return( (int) len );
 }
 }
 
 
-mbedtls_asn1_named_data *mbedtls_asn1_store_named_data( mbedtls_asn1_named_data **head,
+
+/* This is a copy of the ASN.1 parsing function mbedtls_asn1_find_named_data(),
+ * which is replicated to avoid a dependency ASN1_WRITE_C on ASN1_PARSE_C. */
+static mbedtls_asn1_named_data *asn1_find_named_data(
+                                               mbedtls_asn1_named_data *list,
+                                               const char *oid, size_t len )
+{
+    while( list != NULL )
+    {
+        if( list->oid.len == len &&
+            memcmp( list->oid.p, oid, len ) == 0 )
+        {
+            break;
+        }
+
+        list = list->next;
+    }
+
+    return( list );
+}
+
+mbedtls_asn1_named_data *mbedtls_asn1_store_named_data(
+                                        mbedtls_asn1_named_data **head,
                                         const char *oid, size_t oid_len,
                                         const char *oid, size_t oid_len,
                                         const unsigned char *val,
                                         const unsigned char *val,
                                         size_t val_len )
                                         size_t val_len )
 {
 {
     mbedtls_asn1_named_data *cur;
     mbedtls_asn1_named_data *cur;
 
 
-    if( ( cur = mbedtls_asn1_find_named_data( *head, oid, oid_len ) ) == NULL )
+    if( ( cur = asn1_find_named_data( *head, oid, oid_len ) ) == NULL )
     {
     {
         // Add new entry if not present yet based on OID
         // Add new entry if not present yet based on OID
         //
         //

+ 106 - 54
mbedtls/library/bignum.c

@@ -63,6 +63,11 @@ static void mbedtls_mpi_zeroize( mbedtls_mpi_uint *v, size_t n ) {
     volatile mbedtls_mpi_uint *p = v; while( n-- ) *p++ = 0;
     volatile mbedtls_mpi_uint *p = v; while( n-- ) *p++ = 0;
 }
 }
 
 
+/* Implementation that should never be optimized out by the compiler */
+static void mbedtls_zeroize( void *v, size_t n ) {
+    volatile unsigned char *p = v; while( n-- ) *p++ = 0;
+}
+
 #define ciL    (sizeof(mbedtls_mpi_uint))         /* chars in limb  */
 #define ciL    (sizeof(mbedtls_mpi_uint))         /* chars in limb  */
 #define biL    (ciL << 3)               /* bits  in limb  */
 #define biL    (ciL << 3)               /* bits  in limb  */
 #define biH    (ciL << 2)               /* half limb size */
 #define biH    (ciL << 2)               /* half limb size */
@@ -313,6 +318,10 @@ int mbedtls_mpi_get_bit( const mbedtls_mpi *X, size_t pos )
     return( ( X->p[pos / biL] >> ( pos % biL ) ) & 0x01 );
     return( ( X->p[pos / biL] >> ( pos % biL ) ) & 0x01 );
 }
 }
 
 
+/* Get a specific byte, without range checks. */
+#define GET_BYTE( X, i )                                \
+    ( ( ( X )->p[( i ) / ciL] >> ( ( ( i ) % ciL ) * 8 ) ) & 0xff )
+
 /*
 /*
  * Set a bit to a specific value of 0 or 1
  * Set a bit to a specific value of 0 or 1
  */
  */
@@ -491,26 +500,38 @@ cleanup:
 }
 }
 
 
 /*
 /*
- * Helper to write the digits high-order first
+ * Helper to write the digits high-order first.
  */
  */
-static int mpi_write_hlp( mbedtls_mpi *X, int radix, char **p )
+static int mpi_write_hlp( mbedtls_mpi *X, int radix,
+                          char **p, const size_t buflen )
 {
 {
     int ret;
     int ret;
     mbedtls_mpi_uint r;
     mbedtls_mpi_uint r;
+    size_t length = 0;
+    char *p_end = *p + buflen;
 
 
-    if( radix < 2 || radix > 16 )
-        return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
+    do
+    {
+        if( length >= buflen )
+        {
+            return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
+        }
 
 
-    MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, radix ) );
-    MBEDTLS_MPI_CHK( mbedtls_mpi_div_int( X, NULL, X, radix ) );
+        MBEDTLS_MPI_CHK( mbedtls_mpi_mod_int( &r, X, radix ) );
+        MBEDTLS_MPI_CHK( mbedtls_mpi_div_int( X, NULL, X, radix ) );
+        /*
+         * Write the residue in the current position, as an ASCII character.
+         */
+        if( r < 0xA )
+            *(--p_end) = (char)( '0' + r );
+        else
+            *(--p_end) = (char)( 'A' + ( r - 0xA ) );
 
 
-    if( mbedtls_mpi_cmp_int( X, 0 ) != 0 )
-        MBEDTLS_MPI_CHK( mpi_write_hlp( X, radix, p ) );
+        length++;
+    } while( mbedtls_mpi_cmp_int( X, 0 ) != 0 );
 
 
-    if( r < 10 )
-        *(*p)++ = (char)( r + 0x30 );
-    else
-        *(*p)++ = (char)( r + 0x37 );
+    memmove( *p, p_end, length );
+    *p += length;
 
 
 cleanup:
 cleanup:
 
 
@@ -580,7 +601,7 @@ int mbedtls_mpi_write_string( const mbedtls_mpi *X, int radix,
         if( T.s == -1 )
         if( T.s == -1 )
             T.s = 1;
             T.s = 1;
 
 
-        MBEDTLS_MPI_CHK( mpi_write_hlp( &T, radix, &p ) );
+        MBEDTLS_MPI_CHK( mpi_write_hlp( &T, radix, &p, buflen ) );
     }
     }
 
 
     *p++ = '\0';
     *p++ = '\0';
@@ -672,16 +693,20 @@ cleanup:
 int mbedtls_mpi_read_binary( mbedtls_mpi *X, const unsigned char *buf, size_t buflen )
 int mbedtls_mpi_read_binary( mbedtls_mpi *X, const unsigned char *buf, size_t buflen )
 {
 {
     int ret;
     int ret;
-    size_t i, j, n;
+    size_t i, j;
+    size_t const limbs = CHARS_TO_LIMBS( buflen );
 
 
-    for( n = 0; n < buflen; n++ )
-        if( buf[n] != 0 )
-            break;
+    /* Ensure that target MPI has exactly the necessary number of limbs */
+    if( X->n != limbs )
+    {
+        mbedtls_mpi_free( X );
+        mbedtls_mpi_init( X );
+        MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, limbs ) );
+    }
 
 
-    MBEDTLS_MPI_CHK( mbedtls_mpi_grow( X, CHARS_TO_LIMBS( buflen - n ) ) );
     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );
     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( X, 0 ) );
 
 
-    for( i = buflen, j = 0; i > n; i--, j++ )
+    for( i = buflen, j = 0; i > 0; i--, j++ )
         X->p[j / ciL] |= ((mbedtls_mpi_uint) buf[i - 1]) << ((j % ciL) << 3);
         X->p[j / ciL] |= ((mbedtls_mpi_uint) buf[i - 1]) << ((j % ciL) << 3);
 
 
 cleanup:
 cleanup:
@@ -692,19 +717,40 @@ cleanup:
 /*
 /*
  * Export X into unsigned binary data, big endian
  * Export X into unsigned binary data, big endian
  */
  */
-int mbedtls_mpi_write_binary( const mbedtls_mpi *X, unsigned char *buf, size_t buflen )
+int mbedtls_mpi_write_binary( const mbedtls_mpi *X,
+                              unsigned char *buf, size_t buflen )
 {
 {
-    size_t i, j, n;
-
-    n = mbedtls_mpi_size( X );
-
-    if( buflen < n )
-        return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
+    size_t stored_bytes = X->n * ciL;
+    size_t bytes_to_copy;
+    unsigned char *p;
+    size_t i;
 
 
-    memset( buf, 0, buflen );
+    if( stored_bytes < buflen )
+    {
+        /* There is enough space in the output buffer. Write initial
+         * null bytes and record the position at which to start
+         * writing the significant bytes. In this case, the execution
+         * trace of this function does not depend on the value of the
+         * number. */
+        bytes_to_copy = stored_bytes;
+        p = buf + buflen - stored_bytes;
+        memset( buf, 0, buflen - stored_bytes );
+    }
+    else
+    {
+        /* The output buffer is smaller than the allocated size of X.
+         * However X may fit if its leading bytes are zero. */
+        bytes_to_copy = buflen;
+        p = buf;
+        for( i = bytes_to_copy; i < stored_bytes; i++ )
+        {
+            if( GET_BYTE( X, i ) != 0 )
+                return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
+        }
+    }
 
 
-    for( i = buflen - 1, j = 0; n > 0; i--, j++, n-- )
-        buf[i] = (unsigned char)( X->p[j / ciL] >> ((j % ciL) << 3) );
+    for( i = 0; i < bytes_to_copy; i++ )
+        p[bytes_to_copy - i - 1] = GET_BYTE( X, i );
 
 
     return( 0 );
     return( 0 );
 }
 }
@@ -1614,7 +1660,7 @@ int mbedtls_mpi_exp_mod( mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi
     mbedtls_mpi RR, T, W[ 2 << MBEDTLS_MPI_WINDOW_SIZE ], Apos;
     mbedtls_mpi RR, T, W[ 2 << MBEDTLS_MPI_WINDOW_SIZE ], Apos;
     int neg;
     int neg;
 
 
-    if( mbedtls_mpi_cmp_int( N, 0 ) < 0 || ( N->p[0] & 1 ) == 0 )
+    if( mbedtls_mpi_cmp_int( N, 0 ) <= 0 || ( N->p[0] & 1 ) == 0 )
         return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
         return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
 
 
     if( mbedtls_mpi_cmp_int( E, 0 ) < 0 )
     if( mbedtls_mpi_cmp_int( E, 0 ) < 0 )
@@ -1882,6 +1928,7 @@ int mbedtls_mpi_fill_random( mbedtls_mpi *X, size_t size,
     MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( X, buf, size ) );
     MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( X, buf, size ) );
 
 
 cleanup:
 cleanup:
+    mbedtls_zeroize( buf, sizeof( buf ) );
     return( ret );
     return( ret );
 }
 }
 
 
@@ -2043,12 +2090,12 @@ cleanup:
 /*
 /*
  * Miller-Rabin pseudo-primality test  (HAC 4.24)
  * Miller-Rabin pseudo-primality test  (HAC 4.24)
  */
  */
-static int mpi_miller_rabin( const mbedtls_mpi *X,
+static int mpi_miller_rabin( const mbedtls_mpi *X, size_t rounds,
                              int (*f_rng)(void *, unsigned char *, size_t),
                              int (*f_rng)(void *, unsigned char *, size_t),
                              void *p_rng )
                              void *p_rng )
 {
 {
     int ret, count;
     int ret, count;
-    size_t i, j, k, n, s;
+    size_t i, j, k, s;
     mbedtls_mpi W, R, T, A, RR;
     mbedtls_mpi W, R, T, A, RR;
 
 
     mbedtls_mpi_init( &W ); mbedtls_mpi_init( &R ); mbedtls_mpi_init( &T ); mbedtls_mpi_init( &A );
     mbedtls_mpi_init( &W ); mbedtls_mpi_init( &R ); mbedtls_mpi_init( &T ); mbedtls_mpi_init( &A );
@@ -2064,27 +2111,12 @@ static int mpi_miller_rabin( const mbedtls_mpi *X,
     MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &R, s ) );
     MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &R, s ) );
 
 
     i = mbedtls_mpi_bitlen( X );
     i = mbedtls_mpi_bitlen( X );
-    /*
-     * HAC, table 4.4
-     */
-    n = ( ( i >= 1300 ) ?  2 : ( i >=  850 ) ?  3 :
-          ( i >=  650 ) ?  4 : ( i >=  350 ) ?  8 :
-          ( i >=  250 ) ? 12 : ( i >=  150 ) ? 18 : 27 );
 
 
-    for( i = 0; i < n; i++ )
+    for( i = 0; i < rounds; i++ )
     {
     {
         /*
         /*
          * pick a random A, 1 < A < |X| - 1
          * pick a random A, 1 < A < |X| - 1
          */
          */
-        MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &A, X->n * ciL, f_rng, p_rng ) );
-
-        if( mbedtls_mpi_cmp_mpi( &A, &W ) >= 0 )
-        {
-            j = mbedtls_mpi_bitlen( &A ) - mbedtls_mpi_bitlen( &W );
-            MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &A, j + 1 ) );
-        }
-        A.p[0] |= 3;
-
         count = 0;
         count = 0;
         do {
         do {
             MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &A, X->n * ciL, f_rng, p_rng ) );
             MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &A, X->n * ciL, f_rng, p_rng ) );
@@ -2092,7 +2124,7 @@ static int mpi_miller_rabin( const mbedtls_mpi *X,
             j = mbedtls_mpi_bitlen( &A );
             j = mbedtls_mpi_bitlen( &A );
             k = mbedtls_mpi_bitlen( &W );
             k = mbedtls_mpi_bitlen( &W );
             if (j > k) {
             if (j > k) {
-                MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &A, j - k ) );
+                A.p[A.n - 1] &= ( (mbedtls_mpi_uint) 1 << ( k - ( A.n - 1 ) * biL - 1 ) ) - 1;
             }
             }
 
 
             if (count++ > 30) {
             if (count++ > 30) {
@@ -2147,7 +2179,7 @@ cleanup:
 /*
 /*
  * Pseudo-primality test: small factors, then Miller-Rabin
  * Pseudo-primality test: small factors, then Miller-Rabin
  */
  */
-int mbedtls_mpi_is_prime( const mbedtls_mpi *X,
+static int mpi_is_prime_internal( const mbedtls_mpi *X, int rounds,
                   int (*f_rng)(void *, unsigned char *, size_t),
                   int (*f_rng)(void *, unsigned char *, size_t),
                   void *p_rng )
                   void *p_rng )
 {
 {
@@ -2173,7 +2205,17 @@ int mbedtls_mpi_is_prime( const mbedtls_mpi *X,
         return( ret );
         return( ret );
     }
     }
 
 
-    return( mpi_miller_rabin( &XX, f_rng, p_rng ) );
+    return( mpi_miller_rabin( &XX, rounds, f_rng, p_rng ) );
+}
+
+/*
+ * Pseudo-primality test, error probability 2^-80
+ */
+int mbedtls_mpi_is_prime( const mbedtls_mpi *X,
+                  int (*f_rng)(void *, unsigned char *, size_t),
+                  void *p_rng )
+{
+    return mpi_is_prime_internal( X, 40, f_rng, p_rng );
 }
 }
 
 
 /*
 /*
@@ -2185,6 +2227,7 @@ int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int dh_flag,
 {
 {
     int ret;
     int ret;
     size_t k, n;
     size_t k, n;
+    int rounds;
     mbedtls_mpi_uint r;
     mbedtls_mpi_uint r;
     mbedtls_mpi Y;
     mbedtls_mpi Y;
 
 
@@ -2195,6 +2238,13 @@ int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int dh_flag,
 
 
     n = BITS_TO_LIMBS( nbits );
     n = BITS_TO_LIMBS( nbits );
 
 
+    /*
+     * 2^-80 error probability, number of rounds chosen per HAC, table 4.4
+     */
+    rounds = ( ( nbits >= 1300 ) ?  2 : ( nbits >=  850 ) ?  3 :
+               ( nbits >=  650 ) ?  4 : ( nbits >=  350 ) ?  8 :
+               ( nbits >=  250 ) ? 12 : ( nbits >=  150 ) ? 18 : 27 );
+
     MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( X, n * ciL, f_rng, p_rng ) );
     MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( X, n * ciL, f_rng, p_rng ) );
 
 
     k = mbedtls_mpi_bitlen( X );
     k = mbedtls_mpi_bitlen( X );
@@ -2206,7 +2256,7 @@ int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int dh_flag,
 
 
     if( dh_flag == 0 )
     if( dh_flag == 0 )
     {
     {
-        while( ( ret = mbedtls_mpi_is_prime( X, f_rng, p_rng ) ) != 0 )
+        while( ( ret = mpi_is_prime_internal( X, rounds, f_rng, p_rng ) ) != 0 )
         {
         {
             if( ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )
             if( ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )
                 goto cleanup;
                 goto cleanup;
@@ -2242,8 +2292,10 @@ int mbedtls_mpi_gen_prime( mbedtls_mpi *X, size_t nbits, int dh_flag,
              */
              */
             if( ( ret = mpi_check_small_factors(  X         ) ) == 0 &&
             if( ( ret = mpi_check_small_factors(  X         ) ) == 0 &&
                 ( ret = mpi_check_small_factors( &Y         ) ) == 0 &&
                 ( ret = mpi_check_small_factors( &Y         ) ) == 0 &&
-                ( ret = mpi_miller_rabin(  X, f_rng, p_rng  ) ) == 0 &&
-                ( ret = mpi_miller_rabin( &Y, f_rng, p_rng  ) ) == 0 )
+                ( ret = mpi_miller_rabin(  X, rounds, f_rng, p_rng  ) )
+                                                                == 0 &&
+                ( ret = mpi_miller_rabin( &Y, rounds, f_rng, p_rng  ) )
+                                                                == 0 )
             {
             {
                 break;
                 break;
             }
             }

+ 27 - 12
mbedtls/library/ccm.c

@@ -49,6 +49,8 @@
 #endif /* MBEDTLS_PLATFORM_C */
 #endif /* MBEDTLS_PLATFORM_C */
 #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
 #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
 
 
+#if !defined(MBEDTLS_CCM_ALT)
+
 /* Implementation that should never be optimized out by the compiler */
 /* Implementation that should never be optimized out by the compiler */
 static void mbedtls_zeroize( void *v, size_t n ) {
 static void mbedtls_zeroize( void *v, size_t n ) {
     volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0;
     volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0;
@@ -348,6 +350,7 @@ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
     return( 0 );
     return( 0 );
 }
 }
 
 
+#endif /* !MBEDTLS_CCM_ALT */
 
 
 #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
 #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
 /*
 /*
@@ -355,7 +358,8 @@ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
  */
  */
 
 
 #define NB_TESTS 3
 #define NB_TESTS 3
-
+#define CCM_SELFTEST_PT_MAX_LEN 24
+#define CCM_SELFTEST_CT_MAX_LEN 32
 /*
 /*
  * The data is the same for all tests, only the used length changes
  * The data is the same for all tests, only the used length changes
  */
  */
@@ -375,7 +379,7 @@ static const unsigned char ad[] = {
     0x10, 0x11, 0x12, 0x13
     0x10, 0x11, 0x12, 0x13
 };
 };
 
 
-static const unsigned char msg[] = {
+static const unsigned char msg[CCM_SELFTEST_PT_MAX_LEN] = {
     0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
     0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
     0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
     0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
     0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
     0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
@@ -386,7 +390,7 @@ static const size_t add_len[NB_TESTS] = { 8, 16, 20 };
 static const size_t msg_len[NB_TESTS] = { 4, 16, 24 };
 static const size_t msg_len[NB_TESTS] = { 4, 16, 24 };
 static const size_t tag_len[NB_TESTS] = { 4, 6,  8  };
 static const size_t tag_len[NB_TESTS] = { 4, 6,  8  };
 
 
-static const unsigned char res[NB_TESTS][32] = {
+static const unsigned char res[NB_TESTS][CCM_SELFTEST_CT_MAX_LEN] = {
     {   0x71, 0x62, 0x01, 0x5b, 0x4d, 0xac, 0x25, 0x5d },
     {   0x71, 0x62, 0x01, 0x5b, 0x4d, 0xac, 0x25, 0x5d },
     {   0xd2, 0xa1, 0xf0, 0xe0, 0x51, 0xea, 0x5f, 0x62,
     {   0xd2, 0xa1, 0xf0, 0xe0, 0x51, 0xea, 0x5f, 0x62,
         0x08, 0x1a, 0x77, 0x92, 0x07, 0x3d, 0x59, 0x3d,
         0x08, 0x1a, 0x77, 0x92, 0x07, 0x3d, 0x59, 0x3d,
@@ -400,7 +404,13 @@ static const unsigned char res[NB_TESTS][32] = {
 int mbedtls_ccm_self_test( int verbose )
 int mbedtls_ccm_self_test( int verbose )
 {
 {
     mbedtls_ccm_context ctx;
     mbedtls_ccm_context ctx;
-    unsigned char out[32];
+    /*
+     * Some hardware accelerators require the input and output buffers
+     * would be in RAM, because the flash is not accessible.
+     * Use buffers on the stack to hold the test vectors data.
+     */
+    unsigned char plaintext[CCM_SELFTEST_PT_MAX_LEN];
+    unsigned char ciphertext[CCM_SELFTEST_CT_MAX_LEN];
     size_t i;
     size_t i;
     int ret;
     int ret;
 
 
@@ -419,27 +429,32 @@ int mbedtls_ccm_self_test( int verbose )
         if( verbose != 0 )
         if( verbose != 0 )
             mbedtls_printf( "  CCM-AES #%u: ", (unsigned int) i + 1 );
             mbedtls_printf( "  CCM-AES #%u: ", (unsigned int) i + 1 );
 
 
+        memset( plaintext, 0, CCM_SELFTEST_PT_MAX_LEN );
+        memset( ciphertext, 0, CCM_SELFTEST_CT_MAX_LEN );
+        memcpy( plaintext, msg, msg_len[i] );
+
         ret = mbedtls_ccm_encrypt_and_tag( &ctx, msg_len[i],
         ret = mbedtls_ccm_encrypt_and_tag( &ctx, msg_len[i],
-                                   iv, iv_len[i], ad, add_len[i],
-                                   msg, out,
-                                   out + msg_len[i], tag_len[i] );
+                                           iv, iv_len[i], ad, add_len[i],
+                                           plaintext, ciphertext,
+                                           ciphertext + msg_len[i], tag_len[i] );
 
 
         if( ret != 0 ||
         if( ret != 0 ||
-            memcmp( out, res[i], msg_len[i] + tag_len[i] ) != 0 )
+            memcmp( ciphertext, res[i], msg_len[i] + tag_len[i] ) != 0 )
         {
         {
             if( verbose != 0 )
             if( verbose != 0 )
                 mbedtls_printf( "failed\n" );
                 mbedtls_printf( "failed\n" );
 
 
             return( 1 );
             return( 1 );
         }
         }
+        memset( plaintext, 0, CCM_SELFTEST_PT_MAX_LEN );
 
 
         ret = mbedtls_ccm_auth_decrypt( &ctx, msg_len[i],
         ret = mbedtls_ccm_auth_decrypt( &ctx, msg_len[i],
-                                iv, iv_len[i], ad, add_len[i],
-                                res[i], out,
-                                res[i] + msg_len[i], tag_len[i] );
+                                        iv, iv_len[i], ad, add_len[i],
+                                        ciphertext, plaintext,
+                                        ciphertext + msg_len[i], tag_len[i] );
 
 
         if( ret != 0 ||
         if( ret != 0 ||
-            memcmp( out, msg, msg_len[i] ) != 0 )
+            memcmp( plaintext, msg, msg_len[i] ) != 0 )
         {
         {
             if( verbose != 0 )
             if( verbose != 0 )
                 mbedtls_printf( "failed\n" );
                 mbedtls_printf( "failed\n" );

+ 26 - 14
mbedtls/library/cipher.c

@@ -56,10 +56,6 @@
 #define mbedtls_free   free
 #define mbedtls_free   free
 #endif
 #endif
 
 
-#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
-#define MBEDTLS_CIPHER_MODE_STREAM
-#endif
-
 /* Implementation that should never be optimized out by the compiler */
 /* Implementation that should never be optimized out by the compiler */
 static void mbedtls_zeroize( void *v, size_t n ) {
 static void mbedtls_zeroize( void *v, size_t n ) {
     volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0;
     volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0;
@@ -215,9 +211,13 @@ int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx,
                    const unsigned char *iv, size_t iv_len )
                    const unsigned char *iv, size_t iv_len )
 {
 {
     size_t actual_iv_size;
     size_t actual_iv_size;
-
-    if( NULL == ctx || NULL == ctx->cipher_info || NULL == iv )
+    if( NULL == ctx || NULL == ctx->cipher_info )
         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
+    else if( NULL == iv && iv_len != 0  )
+        return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
+
+    if( NULL == iv && iv_len == 0 )
+        ctx->iv_size = 0;
 
 
     /* avoid buffer overflow in ctx->iv */
     /* avoid buffer overflow in ctx->iv */
     if( iv_len > MBEDTLS_MAX_IV_LENGTH )
     if( iv_len > MBEDTLS_MAX_IV_LENGTH )
@@ -233,9 +233,11 @@ int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx,
         if( actual_iv_size > iv_len )
         if( actual_iv_size > iv_len )
             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
     }
     }
-
-    memcpy( ctx->iv, iv, actual_iv_size );
-    ctx->iv_size = actual_iv_size;
+    if ( actual_iv_size != 0 )
+    {
+        memcpy( ctx->iv, iv, actual_iv_size );
+        ctx->iv_size = actual_iv_size;
+    }
 
 
     return( 0 );
     return( 0 );
 }
 }
@@ -325,8 +327,10 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i
         /*
         /*
          * If there is not enough data for a full block, cache it.
          * If there is not enough data for a full block, cache it.
          */
          */
-        if( ( ctx->operation == MBEDTLS_DECRYPT &&
+        if( ( ctx->operation == MBEDTLS_DECRYPT && NULL != ctx->add_padding &&
                 ilen <= block_size - ctx->unprocessed_len ) ||
                 ilen <= block_size - ctx->unprocessed_len ) ||
+            ( ctx->operation == MBEDTLS_DECRYPT && NULL == ctx->add_padding &&
+                ilen < block_size - ctx->unprocessed_len ) ||
              ( ctx->operation == MBEDTLS_ENCRYPT &&
              ( ctx->operation == MBEDTLS_ENCRYPT &&
                 ilen < block_size - ctx->unprocessed_len ) )
                 ilen < block_size - ctx->unprocessed_len ) )
         {
         {
@@ -372,9 +376,17 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i
                 return MBEDTLS_ERR_CIPHER_INVALID_CONTEXT;
                 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
+             */
             copy_len = ilen % block_size;
             copy_len = ilen % block_size;
-            if( copy_len == 0 && ctx->operation == MBEDTLS_DECRYPT )
+            if( copy_len == 0 &&
+                ctx->operation == MBEDTLS_DECRYPT &&
+                NULL != ctx->add_padding)
+            {
                 copy_len = block_size;
                 copy_len = block_size;
+            }
 
 
             memcpy( ctx->unprocessed_data, &( input[ilen - copy_len] ),
             memcpy( ctx->unprocessed_data, &( input[ilen - copy_len] ),
                     copy_len );
                     copy_len );
@@ -516,14 +528,14 @@ static int get_one_and_zeros_padding( unsigned char *input, size_t input_len,
     if( NULL == input || NULL == data_len )
     if( NULL == input || NULL == data_len )
         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
 
 
-    bad = 0xFF;
+    bad = 0x80;
     *data_len = 0;
     *data_len = 0;
     for( i = input_len; i > 0; i-- )
     for( i = input_len; i > 0; i-- )
     {
     {
         prev_done = done;
         prev_done = done;
-        done |= ( input[i-1] != 0 );
+        done |= ( input[i - 1] != 0 );
         *data_len |= ( i - 1 ) * ( done != prev_done );
         *data_len |= ( i - 1 ) * ( done != prev_done );
-        bad &= ( input[i-1] ^ 0x80 ) | ( done == prev_done );
+        bad ^= input[i - 1] * ( done != prev_done );
     }
     }
 
 
     return( MBEDTLS_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) );
     return( MBEDTLS_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) );

+ 3 - 3
mbedtls/library/cipher_wrap.c

@@ -204,7 +204,7 @@ static const mbedtls_cipher_info_t aes_128_ecb_info = {
     MBEDTLS_MODE_ECB,
     MBEDTLS_MODE_ECB,
     128,
     128,
     "AES-128-ECB",
     "AES-128-ECB",
-    16,
+    0,
     0,
     0,
     16,
     16,
     &aes_info
     &aes_info
@@ -215,7 +215,7 @@ static const mbedtls_cipher_info_t aes_192_ecb_info = {
     MBEDTLS_MODE_ECB,
     MBEDTLS_MODE_ECB,
     192,
     192,
     "AES-192-ECB",
     "AES-192-ECB",
-    16,
+    0,
     0,
     0,
     16,
     16,
     &aes_info
     &aes_info
@@ -226,7 +226,7 @@ static const mbedtls_cipher_info_t aes_256_ecb_info = {
     MBEDTLS_MODE_ECB,
     MBEDTLS_MODE_ECB,
     256,
     256,
     "AES-256-ECB",
     "AES-256-ECB",
-    16,
+    0,
     0,
     0,
     16,
     16,
     &aes_info
     &aes_info

+ 10 - 2
mbedtls/library/cmac.c

@@ -65,6 +65,8 @@
 #endif /* MBEDTLS_SELF_TEST */
 #endif /* MBEDTLS_SELF_TEST */
 #endif /* MBEDTLS_PLATFORM_C */
 #endif /* MBEDTLS_PLATFORM_C */
 
 
+#if !defined(MBEDTLS_CMAC_ALT) || defined(MBEDTLS_SELF_TEST)
+
 /* Implementation that should never be optimized out by the compiler */
 /* Implementation that should never be optimized out by the compiler */
 static void mbedtls_zeroize( void *v, size_t n ) {
 static void mbedtls_zeroize( void *v, size_t n ) {
     volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0;
     volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0;
@@ -164,7 +166,9 @@ exit:
 
 
     return( ret );
     return( ret );
 }
 }
+#endif /* !defined(MBEDTLS_CMAC_ALT) || defined(MBEDTLS_SELF_TEST) */
 
 
+#if !defined(MBEDTLS_CMAC_ALT)
 static void cmac_xor_block( unsigned char *output, const unsigned char *input1,
 static void cmac_xor_block( unsigned char *output, const unsigned char *input1,
                             const unsigned char *input2,
                             const unsigned char *input2,
                             const size_t block_size )
                             const size_t block_size )
@@ -468,6 +472,8 @@ exit:
 }
 }
 #endif /* MBEDTLS_AES_C */
 #endif /* MBEDTLS_AES_C */
 
 
+#endif /* !MBEDTLS_CMAC_ALT */
+
 #if defined(MBEDTLS_SELF_TEST)
 #if defined(MBEDTLS_SELF_TEST)
 /*
 /*
  * CMAC test data for SP800-38B
  * CMAC test data for SP800-38B
@@ -765,7 +771,7 @@ static int cmac_test_subkeys( int verbose,
                               int block_size,
                               int block_size,
                               int num_tests )
                               int num_tests )
 {
 {
-    int i, ret;
+    int i, ret = 0;
     mbedtls_cipher_context_t ctx;
     mbedtls_cipher_context_t ctx;
     const mbedtls_cipher_info_t *cipher_info;
     const mbedtls_cipher_info_t *cipher_info;
     unsigned char K1[MBEDTLS_CIPHER_BLKSIZE_MAX];
     unsigned char K1[MBEDTLS_CIPHER_BLKSIZE_MAX];
@@ -826,6 +832,7 @@ static int cmac_test_subkeys( int verbose,
         mbedtls_cipher_free( &ctx );
         mbedtls_cipher_free( &ctx );
     }
     }
 
 
+    ret = 0;
     goto exit;
     goto exit;
 
 
 cleanup:
 cleanup:
@@ -847,7 +854,7 @@ static int cmac_test_wth_cipher( int verbose,
                                  int num_tests )
                                  int num_tests )
 {
 {
     const mbedtls_cipher_info_t *cipher_info;
     const mbedtls_cipher_info_t *cipher_info;
-    int i, ret;
+    int i, ret = 0;
     unsigned char output[MBEDTLS_CIPHER_BLKSIZE_MAX];
     unsigned char output[MBEDTLS_CIPHER_BLKSIZE_MAX];
 
 
     cipher_info = mbedtls_cipher_info_from_type( cipher_type );
     cipher_info = mbedtls_cipher_info_from_type( cipher_type );
@@ -881,6 +888,7 @@ static int cmac_test_wth_cipher( int verbose,
         if( verbose != 0 )
         if( verbose != 0 )
             mbedtls_printf( "passed\n" );
             mbedtls_printf( "passed\n" );
     }
     }
+    ret = 0;
 
 
 exit:
 exit:
     return( ret );
     return( ret );

+ 107 - 41
mbedtls/library/ctr_drbg.c

@@ -19,7 +19,7 @@
  *  This file is part of mbed TLS (https://tls.mbed.org)
  *  This file is part of mbed TLS (https://tls.mbed.org)
  */
  */
 /*
 /*
- *  The NIST SP 800-90 DRBGs are described in the following publucation.
+ *  The NIST SP 800-90 DRBGs are described in the following publication.
  *
  *
  *  http://csrc.nist.gov/publications/nistpubs/800-90/SP800-90revised_March2007.pdf
  *  http://csrc.nist.gov/publications/nistpubs/800-90/SP800-90revised_March2007.pdf
  */
  */
@@ -94,11 +94,15 @@ int mbedtls_ctr_drbg_seed_entropy_len(
     /*
     /*
      * Initialize with an empty key
      * Initialize with an empty key
      */
      */
-    mbedtls_aes_setkey_enc( &ctx->aes_ctx, key, MBEDTLS_CTR_DRBG_KEYBITS );
+    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 )
     if( ( ret = mbedtls_ctr_drbg_reseed( ctx, custom, len ) ) != 0 )
+    {
         return( ret );
         return( ret );
-
+    }
     return( 0 );
     return( 0 );
 }
 }
 
 
@@ -148,6 +152,7 @@ static int block_cipher_df( unsigned char *output,
     unsigned char chain[MBEDTLS_CTR_DRBG_BLOCKSIZE];
     unsigned char chain[MBEDTLS_CTR_DRBG_BLOCKSIZE];
     unsigned char *p, *iv;
     unsigned char *p, *iv;
     mbedtls_aes_context aes_ctx;
     mbedtls_aes_context aes_ctx;
+    int ret = 0;
 
 
     int i, j;
     int i, j;
     size_t buf_len, use_len;
     size_t buf_len, use_len;
@@ -180,7 +185,10 @@ static int block_cipher_df( unsigned char *output,
     for( i = 0; i < MBEDTLS_CTR_DRBG_KEYSIZE; i++ )
     for( i = 0; i < MBEDTLS_CTR_DRBG_KEYSIZE; i++ )
         key[i] = i;
         key[i] = i;
 
 
-    mbedtls_aes_setkey_enc( &aes_ctx, key, MBEDTLS_CTR_DRBG_KEYBITS );
+    if( ( ret = mbedtls_aes_setkey_enc( &aes_ctx, key, MBEDTLS_CTR_DRBG_KEYBITS ) ) != 0 )
+    {
+        goto exit;
+    }
 
 
     /*
     /*
      * Reduce data to MBEDTLS_CTR_DRBG_SEEDLEN bytes of data
      * Reduce data to MBEDTLS_CTR_DRBG_SEEDLEN bytes of data
@@ -199,7 +207,10 @@ static int block_cipher_df( unsigned char *output,
             use_len -= ( use_len >= MBEDTLS_CTR_DRBG_BLOCKSIZE ) ?
             use_len -= ( use_len >= MBEDTLS_CTR_DRBG_BLOCKSIZE ) ?
                        MBEDTLS_CTR_DRBG_BLOCKSIZE : use_len;
                        MBEDTLS_CTR_DRBG_BLOCKSIZE : use_len;
 
 
-            mbedtls_aes_crypt_ecb( &aes_ctx, MBEDTLS_AES_ENCRYPT, chain, chain );
+            if( ( ret = mbedtls_aes_crypt_ecb( &aes_ctx, MBEDTLS_AES_ENCRYPT, chain, chain ) ) != 0 )
+            {
+                goto exit;
+            }
         }
         }
 
 
         memcpy( tmp + j, chain, MBEDTLS_CTR_DRBG_BLOCKSIZE );
         memcpy( tmp + j, chain, MBEDTLS_CTR_DRBG_BLOCKSIZE );
@@ -213,20 +224,40 @@ static int block_cipher_df( unsigned char *output,
     /*
     /*
      * Do final encryption with reduced data
      * Do final encryption with reduced data
      */
      */
-    mbedtls_aes_setkey_enc( &aes_ctx, tmp, MBEDTLS_CTR_DRBG_KEYBITS );
+    if( ( ret = mbedtls_aes_setkey_enc( &aes_ctx, tmp, MBEDTLS_CTR_DRBG_KEYBITS ) ) != 0 )
+    {
+        goto exit;
+    }
     iv = tmp + MBEDTLS_CTR_DRBG_KEYSIZE;
     iv = tmp + MBEDTLS_CTR_DRBG_KEYSIZE;
     p = output;
     p = output;
 
 
     for( j = 0; j < MBEDTLS_CTR_DRBG_SEEDLEN; j += MBEDTLS_CTR_DRBG_BLOCKSIZE )
     for( j = 0; j < MBEDTLS_CTR_DRBG_SEEDLEN; j += MBEDTLS_CTR_DRBG_BLOCKSIZE )
     {
     {
-        mbedtls_aes_crypt_ecb( &aes_ctx, MBEDTLS_AES_ENCRYPT, iv, iv );
+        if( ( ret = mbedtls_aes_crypt_ecb( &aes_ctx, MBEDTLS_AES_ENCRYPT, iv, iv ) ) != 0 )
+        {
+            goto exit;
+        }
         memcpy( p, iv, MBEDTLS_CTR_DRBG_BLOCKSIZE );
         memcpy( p, iv, MBEDTLS_CTR_DRBG_BLOCKSIZE );
         p += MBEDTLS_CTR_DRBG_BLOCKSIZE;
         p += MBEDTLS_CTR_DRBG_BLOCKSIZE;
     }
     }
-
+exit:
     mbedtls_aes_free( &aes_ctx );
     mbedtls_aes_free( &aes_ctx );
+    /*
+    * tidy up the stack
+    */
+    mbedtls_zeroize( buf, sizeof( buf ) );
+    mbedtls_zeroize( tmp, sizeof( tmp ) );
+    mbedtls_zeroize( key, sizeof( key ) );
+    mbedtls_zeroize( chain, sizeof( chain ) );
+    if( 0 != ret )
+    {
+        /*
+        * wipe partial seed from memory
+        */
+        mbedtls_zeroize( output, MBEDTLS_CTR_DRBG_SEEDLEN );
+    }
 
 
-    return( 0 );
+    return( ret );
 }
 }
 
 
 static int ctr_drbg_update_internal( mbedtls_ctr_drbg_context *ctx,
 static int ctr_drbg_update_internal( mbedtls_ctr_drbg_context *ctx,
@@ -235,6 +266,7 @@ static int ctr_drbg_update_internal( mbedtls_ctr_drbg_context *ctx,
     unsigned char tmp[MBEDTLS_CTR_DRBG_SEEDLEN];
     unsigned char tmp[MBEDTLS_CTR_DRBG_SEEDLEN];
     unsigned char *p = tmp;
     unsigned char *p = tmp;
     int i, j;
     int i, j;
+    int ret = 0;
 
 
     memset( tmp, 0, MBEDTLS_CTR_DRBG_SEEDLEN );
     memset( tmp, 0, MBEDTLS_CTR_DRBG_SEEDLEN );
 
 
@@ -250,7 +282,8 @@ static int ctr_drbg_update_internal( mbedtls_ctr_drbg_context *ctx,
         /*
         /*
          * Crypt counter block
          * Crypt counter block
          */
          */
-        mbedtls_aes_crypt_ecb( &ctx->aes_ctx, MBEDTLS_AES_ENCRYPT, ctx->counter, p );
+        if( ( ret = mbedtls_aes_crypt_ecb( &ctx->aes_ctx, MBEDTLS_AES_ENCRYPT, ctx->counter, p ) ) != 0 )
+            goto exit;
 
 
         p += MBEDTLS_CTR_DRBG_BLOCKSIZE;
         p += MBEDTLS_CTR_DRBG_BLOCKSIZE;
     }
     }
@@ -261,27 +294,45 @@ static int ctr_drbg_update_internal( mbedtls_ctr_drbg_context *ctx,
     /*
     /*
      * Update key and counter
      * Update key and counter
      */
      */
-    mbedtls_aes_setkey_enc( &ctx->aes_ctx, tmp, MBEDTLS_CTR_DRBG_KEYBITS );
+    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 );
     memcpy( ctx->counter, tmp + MBEDTLS_CTR_DRBG_KEYSIZE, MBEDTLS_CTR_DRBG_BLOCKSIZE );
 
 
-    return( 0 );
+exit:
+    mbedtls_zeroize( tmp, sizeof( tmp ) );
+    return( ret );
 }
 }
 
 
-void mbedtls_ctr_drbg_update( mbedtls_ctr_drbg_context *ctx,
-                      const unsigned char *additional, size_t add_len )
+int mbedtls_ctr_drbg_update_ret( mbedtls_ctr_drbg_context *ctx,
+                                 const unsigned char *additional,
+                                 size_t add_len )
 {
 {
     unsigned char add_input[MBEDTLS_CTR_DRBG_SEEDLEN];
     unsigned char add_input[MBEDTLS_CTR_DRBG_SEEDLEN];
+    int ret;
 
 
-    if( add_len > 0 )
-    {
-        /* MAX_INPUT would be more logical here, but we have to match
-         * block_cipher_df()'s limits since we can't propagate errors */
-        if( add_len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT )
-            add_len = MBEDTLS_CTR_DRBG_MAX_SEED_INPUT;
+    if( add_len == 0 )
+        return( 0 );
 
 
-        block_cipher_df( add_input, additional, add_len );
-        ctr_drbg_update_internal( ctx, add_input );
-    }
+    if( ( ret = block_cipher_df( add_input, additional, add_len ) ) != 0 )
+        goto exit;
+    if( ( ret = ctr_drbg_update_internal( ctx, add_input ) ) != 0 )
+        goto exit;
+
+exit:
+    mbedtls_zeroize( add_input, sizeof( add_input ) );
+    return( ret );
+}
+
+/* Deprecated function, kept for backward compatibility. */
+void mbedtls_ctr_drbg_update( mbedtls_ctr_drbg_context *ctx,
+                              const unsigned char *additional,
+                              size_t add_len )
+{
+    /* MAX_INPUT would be more logical here, but we have to match
+     * block_cipher_df()'s limits since we can't propagate errors */
+    if( add_len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT )
+        add_len = MBEDTLS_CTR_DRBG_MAX_SEED_INPUT;
+    (void) mbedtls_ctr_drbg_update_ret( ctx, additional, add_len );
 }
 }
 
 
 int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx,
 int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx,
@@ -289,6 +340,7 @@ int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx,
 {
 {
     unsigned char seed[MBEDTLS_CTR_DRBG_MAX_SEED_INPUT];
     unsigned char seed[MBEDTLS_CTR_DRBG_MAX_SEED_INPUT];
     size_t seedlen = 0;
     size_t seedlen = 0;
+    int ret;
 
 
     if( ctx->entropy_len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT ||
     if( ctx->entropy_len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT ||
         len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT - ctx->entropy_len )
         len > MBEDTLS_CTR_DRBG_MAX_SEED_INPUT - ctx->entropy_len )
@@ -319,15 +371,19 @@ int mbedtls_ctr_drbg_reseed( mbedtls_ctr_drbg_context *ctx,
     /*
     /*
      * Reduce to 384 bits
      * Reduce to 384 bits
      */
      */
-    block_cipher_df( seed, seed, seedlen );
+    if( ( ret = block_cipher_df( seed, seed, seedlen ) ) != 0 )
+        goto exit;
 
 
     /*
     /*
      * Update state
      * Update state
      */
      */
-    ctr_drbg_update_internal( ctx, seed );
+    if( ( ret = ctr_drbg_update_internal( ctx, seed ) ) != 0 )
+        goto exit;
     ctx->reseed_counter = 1;
     ctx->reseed_counter = 1;
 
 
-    return( 0 );
+exit:
+    mbedtls_zeroize( seed, sizeof( seed ) );
+    return( ret );
 }
 }
 
 
 int mbedtls_ctr_drbg_random_with_add( void *p_rng,
 int mbedtls_ctr_drbg_random_with_add( void *p_rng,
@@ -354,15 +410,18 @@ int mbedtls_ctr_drbg_random_with_add( void *p_rng,
         ctx->prediction_resistance )
         ctx->prediction_resistance )
     {
     {
         if( ( ret = mbedtls_ctr_drbg_reseed( ctx, additional, add_len ) ) != 0 )
         if( ( ret = mbedtls_ctr_drbg_reseed( ctx, additional, add_len ) ) != 0 )
+        {
             return( ret );
             return( ret );
-
+        }
         add_len = 0;
         add_len = 0;
     }
     }
 
 
     if( add_len > 0 )
     if( add_len > 0 )
     {
     {
-        block_cipher_df( add_input, additional, add_len );
-        ctr_drbg_update_internal( ctx, add_input );
+        if( ( ret = block_cipher_df( add_input, additional, add_len ) ) != 0 )
+            goto exit;
+        if( ( ret = ctr_drbg_update_internal( ctx, add_input ) ) != 0 )
+            goto exit;
     }
     }
 
 
     while( output_len > 0 )
     while( output_len > 0 )
@@ -377,7 +436,8 @@ int mbedtls_ctr_drbg_random_with_add( void *p_rng,
         /*
         /*
          * Crypt counter block
          * Crypt counter block
          */
          */
-        mbedtls_aes_crypt_ecb( &ctx->aes_ctx, MBEDTLS_AES_ENCRYPT, ctx->counter, tmp );
+        if( ( ret = mbedtls_aes_crypt_ecb( &ctx->aes_ctx, MBEDTLS_AES_ENCRYPT, ctx->counter, tmp ) ) != 0 )
+            goto exit;
 
 
         use_len = ( output_len > MBEDTLS_CTR_DRBG_BLOCKSIZE ) ? MBEDTLS_CTR_DRBG_BLOCKSIZE :
         use_len = ( output_len > MBEDTLS_CTR_DRBG_BLOCKSIZE ) ? MBEDTLS_CTR_DRBG_BLOCKSIZE :
                                                        output_len;
                                                        output_len;
@@ -389,10 +449,14 @@ int mbedtls_ctr_drbg_random_with_add( void *p_rng,
         output_len -= use_len;
         output_len -= use_len;
     }
     }
 
 
-    ctr_drbg_update_internal( ctx, add_input );
+    if( ( ret = ctr_drbg_update_internal( ctx, add_input ) ) != 0 )
+        goto exit;
 
 
     ctx->reseed_counter++;
     ctx->reseed_counter++;
 
 
+exit:
+    mbedtls_zeroize( add_input, sizeof( add_input ) );
+    mbedtls_zeroize( tmp, sizeof( tmp ) );
     return( 0 );
     return( 0 );
 }
 }
 
 
@@ -430,20 +494,20 @@ int mbedtls_ctr_drbg_write_seed_file( mbedtls_ctr_drbg_context *ctx, const char
         goto exit;
         goto exit;
 
 
     if( fwrite( buf, 1, MBEDTLS_CTR_DRBG_MAX_INPUT, f ) != MBEDTLS_CTR_DRBG_MAX_INPUT )
     if( fwrite( buf, 1, MBEDTLS_CTR_DRBG_MAX_INPUT, f ) != MBEDTLS_CTR_DRBG_MAX_INPUT )
-    {
         ret = MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR;
         ret = MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR;
-        goto exit;
-    }
-
-    ret = 0;
+    else
+        ret = 0;
 
 
 exit:
 exit:
+    mbedtls_zeroize( buf, sizeof( buf ) );
+
     fclose( f );
     fclose( f );
     return( ret );
     return( ret );
 }
 }
 
 
 int mbedtls_ctr_drbg_update_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path )
 int mbedtls_ctr_drbg_update_seed_file( mbedtls_ctr_drbg_context *ctx, const char *path )
 {
 {
+    int ret = 0;
     FILE *f;
     FILE *f;
     size_t n;
     size_t n;
     unsigned char buf[ MBEDTLS_CTR_DRBG_MAX_INPUT ];
     unsigned char buf[ MBEDTLS_CTR_DRBG_MAX_INPUT ];
@@ -462,14 +526,16 @@ int mbedtls_ctr_drbg_update_seed_file( mbedtls_ctr_drbg_context *ctx, const char
     }
     }
 
 
     if( fread( buf, 1, n, f ) != n )
     if( fread( buf, 1, n, f ) != n )
-    {
-        fclose( f );
-        return( MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR );
-    }
+        ret = MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR;
+    else
+        ret = mbedtls_ctr_drbg_update_ret( ctx, buf, n );
 
 
     fclose( f );
     fclose( f );
 
 
-    mbedtls_ctr_drbg_update( ctx, buf, n );
+    mbedtls_zeroize( buf, sizeof( buf ) );
+
+    if( ret != 0 )
+        return( ret );
 
 
     return( mbedtls_ctr_drbg_write_seed_file( ctx, path ) );
     return( mbedtls_ctr_drbg_write_seed_file( ctx, path ) );
 }
 }

+ 1 - 1
mbedtls/library/debug.c

@@ -91,7 +91,7 @@ void mbedtls_debug_print_msg( const mbedtls_ssl_context *ssl, int level,
 
 
     va_start( argp, format );
     va_start( argp, format );
 #if defined(_WIN32)
 #if defined(_WIN32)
-#if defined(_TRUNCATE)
+#if defined(_TRUNCATE) && !defined(__MINGW32__)
     ret = _vsnprintf_s( str, DEBUG_BUF_SIZE, _TRUNCATE, format, argp );
     ret = _vsnprintf_s( str, DEBUG_BUF_SIZE, _TRUNCATE, format, argp );
 #else
 #else
     ret = _vsnprintf( str, DEBUG_BUF_SIZE, format, argp );
     ret = _vsnprintf( str, DEBUG_BUF_SIZE, format, argp );

+ 49 - 13
mbedtls/library/dhm.c

@@ -57,6 +57,7 @@
 #define mbedtls_free       free
 #define mbedtls_free       free
 #endif
 #endif
 
 
+#if !defined(MBEDTLS_DHM_ALT)
 /* Implementation that should never be optimized out by the compiler */
 /* Implementation that should never be optimized out by the compiler */
 static void mbedtls_zeroize( void *v, size_t n ) {
 static void mbedtls_zeroize( void *v, size_t n ) {
     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
@@ -93,6 +94,9 @@ static int dhm_read_bignum( mbedtls_mpi *X,
  *
  *
  * Parameter should be: 2 <= public_param <= P - 2
  * Parameter should be: 2 <= public_param <= P - 2
  *
  *
+ * This means that we need to return an error if
+ *              public_param < 2 or public_param > P-2
+ *
  * For more information on the attack, see:
  * For more information on the attack, see:
  *  http://www.cl.cam.ac.uk/~rja14/Papers/psandqs.pdf
  *  http://www.cl.cam.ac.uk/~rja14/Papers/psandqs.pdf
  *  http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-2643
  *  http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2005-2643
@@ -100,17 +104,17 @@ static int dhm_read_bignum( mbedtls_mpi *X,
 static int dhm_check_range( const mbedtls_mpi *param, const mbedtls_mpi *P )
 static int dhm_check_range( const mbedtls_mpi *param, const mbedtls_mpi *P )
 {
 {
     mbedtls_mpi L, U;
     mbedtls_mpi L, U;
-    int ret = MBEDTLS_ERR_DHM_BAD_INPUT_DATA;
+    int ret = 0;
 
 
     mbedtls_mpi_init( &L ); mbedtls_mpi_init( &U );
     mbedtls_mpi_init( &L ); mbedtls_mpi_init( &U );
 
 
     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &L, 2 ) );
     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &L, 2 ) );
     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &U, P, 2 ) );
     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &U, P, 2 ) );
 
 
-    if( mbedtls_mpi_cmp_mpi( param, &L ) >= 0 &&
-        mbedtls_mpi_cmp_mpi( param, &U ) <= 0 )
+    if( mbedtls_mpi_cmp_mpi( param, &L ) < 0 ||
+        mbedtls_mpi_cmp_mpi( param, &U ) > 0 )
     {
     {
-        ret = 0;
+        ret = MBEDTLS_ERR_DHM_BAD_INPUT_DATA;
     }
     }
 
 
 cleanup:
 cleanup:
@@ -187,10 +191,15 @@ int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size,
     /*
     /*
      * export P, G, GX
      * export P, G, GX
      */
      */
-#define DHM_MPI_EXPORT(X,n)                     \
-    MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( X, p + 2, n ) ); \
-    *p++ = (unsigned char)( n >> 8 );           \
-    *p++ = (unsigned char)( n      ); p += n;
+#define DHM_MPI_EXPORT( X, n )                                          \
+    do {                                                                \
+        MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( ( X ),               \
+                                                   p + 2,               \
+                                                   ( n ) ) );           \
+        *p++ = (unsigned char)( ( n ) >> 8 );                           \
+        *p++ = (unsigned char)( ( n )      );                           \
+        p += ( n );                                                     \
+    } while( 0 )
 
 
     n1 = mbedtls_mpi_size( &ctx->P  );
     n1 = mbedtls_mpi_size( &ctx->P  );
     n2 = mbedtls_mpi_size( &ctx->G  );
     n2 = mbedtls_mpi_size( &ctx->G  );
@@ -201,7 +210,7 @@ int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size,
     DHM_MPI_EXPORT( &ctx->G , n2 );
     DHM_MPI_EXPORT( &ctx->G , n2 );
     DHM_MPI_EXPORT( &ctx->GX, n3 );
     DHM_MPI_EXPORT( &ctx->GX, n3 );
 
 
-    *olen  = p - output;
+    *olen = p - output;
 
 
     ctx->len = n1;
     ctx->len = n1;
 
 
@@ -213,6 +222,28 @@ cleanup:
     return( 0 );
     return( 0 );
 }
 }
 
 
+/*
+ * Set prime modulus and generator
+ */
+int mbedtls_dhm_set_group( mbedtls_dhm_context *ctx,
+                           const mbedtls_mpi *P,
+                           const mbedtls_mpi *G )
+{
+    int ret;
+
+    if( ctx == NULL || P == NULL || G == NULL )
+        return( MBEDTLS_ERR_DHM_BAD_INPUT_DATA );
+
+    if( ( ret = mbedtls_mpi_copy( &ctx->P, P ) ) != 0 ||
+        ( ret = mbedtls_mpi_copy( &ctx->G, G ) ) != 0 )
+    {
+        return( MBEDTLS_ERR_DHM_SET_GROUP_FAILED + ret );
+    }
+
+    ctx->len = mbedtls_mpi_size( &ctx->P );
+    return( 0 );
+}
+
 /*
 /*
  * Import the peer's public value G^Y
  * Import the peer's public value G^Y
  */
  */
@@ -400,10 +431,11 @@ cleanup:
  */
  */
 void mbedtls_dhm_free( mbedtls_dhm_context *ctx )
 void mbedtls_dhm_free( mbedtls_dhm_context *ctx )
 {
 {
-    mbedtls_mpi_free( &ctx->pX); mbedtls_mpi_free( &ctx->Vf ); mbedtls_mpi_free( &ctx->Vi );
-    mbedtls_mpi_free( &ctx->RP ); mbedtls_mpi_free( &ctx->K ); mbedtls_mpi_free( &ctx->GY );
-    mbedtls_mpi_free( &ctx->GX ); mbedtls_mpi_free( &ctx->X ); mbedtls_mpi_free( &ctx->G );
-    mbedtls_mpi_free( &ctx->P );
+    mbedtls_mpi_free( &ctx->pX ); mbedtls_mpi_free( &ctx->Vf );
+    mbedtls_mpi_free( &ctx->Vi ); mbedtls_mpi_free( &ctx->RP );
+    mbedtls_mpi_free( &ctx->K  ); mbedtls_mpi_free( &ctx->GY );
+    mbedtls_mpi_free( &ctx->GX ); mbedtls_mpi_free( &ctx->X  );
+    mbedtls_mpi_free( &ctx->G  ); mbedtls_mpi_free( &ctx->P  );
 
 
     mbedtls_zeroize( ctx, sizeof( mbedtls_dhm_context ) );
     mbedtls_zeroize( ctx, sizeof( mbedtls_dhm_context ) );
 }
 }
@@ -542,7 +574,10 @@ static int load_file( const char *path, unsigned char **buf, size_t *n )
     if( fread( *buf, 1, *n, f ) != *n )
     if( fread( *buf, 1, *n, f ) != *n )
     {
     {
         fclose( f );
         fclose( f );
+
+        mbedtls_zeroize( *buf, *n + 1 );
         mbedtls_free( *buf );
         mbedtls_free( *buf );
+
         return( MBEDTLS_ERR_DHM_FILE_IO_ERROR );
         return( MBEDTLS_ERR_DHM_FILE_IO_ERROR );
     }
     }
 
 
@@ -577,6 +612,7 @@ int mbedtls_dhm_parse_dhmfile( mbedtls_dhm_context *dhm, const char *path )
 }
 }
 #endif /* MBEDTLS_FS_IO */
 #endif /* MBEDTLS_FS_IO */
 #endif /* MBEDTLS_ASN1_PARSE_C */
 #endif /* MBEDTLS_ASN1_PARSE_C */
+#endif /* MBEDTLS_DHM_ALT */
 
 
 #if defined(MBEDTLS_SELF_TEST)
 #if defined(MBEDTLS_SELF_TEST)
 
 

+ 4 - 0
mbedtls/library/ecdh.c

@@ -38,6 +38,7 @@
 
 
 #include <string.h>
 #include <string.h>
 
 
+#if !defined(MBEDTLS_ECDH_GEN_PUBLIC_ALT)
 /*
 /*
  * Generate public key: simple wrapper around mbedtls_ecp_gen_keypair
  * Generate public key: simple wrapper around mbedtls_ecp_gen_keypair
  */
  */
@@ -47,7 +48,9 @@ int mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp
 {
 {
     return mbedtls_ecp_gen_keypair( grp, d, Q, f_rng, p_rng );
     return mbedtls_ecp_gen_keypair( grp, d, Q, f_rng, p_rng );
 }
 }
+#endif /* MBEDTLS_ECDH_GEN_PUBLIC_ALT */
 
 
+#if !defined(MBEDTLS_ECDH_COMPUTE_SHARED_ALT)
 /*
 /*
  * Compute shared secret (SEC1 3.3.1)
  * Compute shared secret (SEC1 3.3.1)
  */
  */
@@ -81,6 +84,7 @@ cleanup:
 
 
     return( ret );
     return( ret );
 }
 }
+#endif /* MBEDTLS_ECDH_COMPUTE_SHARED_ALT */
 
 
 /*
 /*
  * Initialize context
  * Initialize context

+ 20 - 2
mbedtls/library/ecdsa.c

@@ -65,6 +65,7 @@ cleanup:
     return( ret );
     return( ret );
 }
 }
 
 
+#if !defined(MBEDTLS_ECDSA_SIGN_ALT)
 /*
 /*
  * Compute ECDSA signature of a hashed message (SEC1 4.1.3)
  * Compute ECDSA signature of a hashed message (SEC1 4.1.3)
  * Obviously, compared to SEC1 4.1.3, we skip step 4 (hash message)
  * Obviously, compared to SEC1 4.1.3, we skip step 4 (hash message)
@@ -81,6 +82,10 @@ int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
     if( grp->N.p == NULL )
     if( grp->N.p == NULL )
         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
 
 
+    /* Make sure d is in range 1..n-1 */
+    if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 )
+        return( MBEDTLS_ERR_ECP_INVALID_KEY );
+
     mbedtls_ecp_point_init( &R );
     mbedtls_ecp_point_init( &R );
     mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t );
     mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t );
 
 
@@ -153,6 +158,7 @@ cleanup:
 
 
     return( ret );
     return( ret );
 }
 }
+#endif /* MBEDTLS_ECDSA_SIGN_ALT */
 
 
 #if defined(MBEDTLS_ECDSA_DETERMINISTIC)
 #if defined(MBEDTLS_ECDSA_DETERMINISTIC)
 /*
 /*
@@ -192,6 +198,7 @@ cleanup:
 }
 }
 #endif /* MBEDTLS_ECDSA_DETERMINISTIC */
 #endif /* MBEDTLS_ECDSA_DETERMINISTIC */
 
 
+#if !defined(MBEDTLS_ECDSA_VERIFY_ALT)
 /*
 /*
  * Verify ECDSA signature of hashed message (SEC1 4.1.4)
  * Verify ECDSA signature of hashed message (SEC1 4.1.4)
  * Obviously, compared to SEC1 4.1.3, we skip step 2 (hash message)
  * Obviously, compared to SEC1 4.1.3, we skip step 2 (hash message)
@@ -277,6 +284,7 @@ cleanup:
 
 
     return( ret );
     return( ret );
 }
 }
+#endif /* MBEDTLS_ECDSA_VERIFY_ALT */
 
 
 /*
 /*
  * Convert a signature (given by context) to ASN.1
  * Convert a signature (given by context) to ASN.1
@@ -392,6 +400,9 @@ int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx,
                               &ctx->Q, &r, &s ) ) != 0 )
                               &ctx->Q, &r, &s ) ) != 0 )
         goto cleanup;
         goto cleanup;
 
 
+    /* At this point we know that the buffer starts with a valid signature.
+     * Return 0 if the buffer just contains the signature, and a specific
+     * error code if the valid signature is followed by more data. */
     if( p != end )
     if( p != end )
         ret = MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH;
         ret = MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH;
 
 
@@ -402,15 +413,22 @@ cleanup:
     return( ret );
     return( ret );
 }
 }
 
 
+#if !defined(MBEDTLS_ECDSA_GENKEY_ALT)
 /*
 /*
  * Generate key pair
  * Generate key pair
  */
  */
 int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid,
 int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid,
                   int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
                   int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
 {
 {
-    return( mbedtls_ecp_group_load( &ctx->grp, gid ) ||
-            mbedtls_ecp_gen_keypair( &ctx->grp, &ctx->d, &ctx->Q, f_rng, p_rng ) );
+    int ret = 0;
+    ret = mbedtls_ecp_group_load( &ctx->grp, gid );
+    if( ret != 0 )
+        return( ret );
+
+   return( mbedtls_ecp_gen_keypair( &ctx->grp, &ctx->d,
+                                    &ctx->Q, f_rng, p_rng ) );
 }
 }
+#endif /* MBEDTLS_ECDSA_GENKEY_ALT */
 
 
 /*
 /*
  * Set context from an mbedtls_ecp_keypair
  * Set context from an mbedtls_ecp_keypair

+ 4 - 1
mbedtls/library/ecjpake.c

@@ -36,6 +36,8 @@
 
 
 #include <string.h>
 #include <string.h>
 
 
+#if !defined(MBEDTLS_ECJPAKE_ALT)
+
 /*
 /*
  * Convert a mbedtls_ecjpake_role to identifier string
  * Convert a mbedtls_ecjpake_role to identifier string
  */
  */
@@ -299,7 +301,7 @@ cleanup:
  */
  */
 static int ecjpake_zkp_write( const mbedtls_md_info_t *md_info,
 static int ecjpake_zkp_write( const mbedtls_md_info_t *md_info,
                               const mbedtls_ecp_group *grp,
                               const mbedtls_ecp_group *grp,
-                              const int pf, 
+                              const int pf,
                               const mbedtls_ecp_point *G,
                               const mbedtls_ecp_point *G,
                               const mbedtls_mpi *x,
                               const mbedtls_mpi *x,
                               const mbedtls_ecp_point *X,
                               const mbedtls_ecp_point *X,
@@ -764,6 +766,7 @@ cleanup:
 #undef ID_MINE
 #undef ID_MINE
 #undef ID_PEER
 #undef ID_PEER
 
 
+#endif /* ! MBEDTLS_ECJPAKE_ALT */
 
 
 #if defined(MBEDTLS_SELF_TEST)
 #if defined(MBEDTLS_SELF_TEST)
 
 

+ 8 - 5
mbedtls/library/ecp.c

@@ -409,7 +409,7 @@ int mbedtls_ecp_is_zero( mbedtls_ecp_point *pt )
 }
 }
 
 
 /*
 /*
- * Compare two points lazyly
+ * Compare two points lazily
  */
  */
 int mbedtls_ecp_point_cmp( const mbedtls_ecp_point *P,
 int mbedtls_ecp_point_cmp( const mbedtls_ecp_point *P,
                            const mbedtls_ecp_point *Q )
                            const mbedtls_ecp_point *Q )
@@ -1448,7 +1448,12 @@ static int ecp_mul_comb( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
 
 
 cleanup:
 cleanup:
 
 
-    if( T != NULL && ! p_eq_g )
+    /* There are two cases where T is not stored in grp:
+     * - P != G
+     * - An intermediate operation failed before setting grp->T
+     * In either case, T must be freed.
+     */
+    if( T != NULL && T != grp->T )
     {
     {
         for( i = 0; i < pre_len; i++ )
         for( i = 0; i < pre_len; i++ )
             mbedtls_ecp_point_free( &T[i] );
             mbedtls_ecp_point_free( &T[i] );
@@ -1953,7 +1958,6 @@ int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp,
     {
     {
         /* SEC1 3.2.1: Generate d such that 1 <= n < N */
         /* SEC1 3.2.1: Generate d such that 1 <= n < N */
         int count = 0;
         int count = 0;
-        unsigned char rnd[MBEDTLS_ECP_MAX_BYTES];
 
 
         /*
         /*
          * Match the procedure given in RFC 6979 (deterministic ECDSA):
          * Match the procedure given in RFC 6979 (deterministic ECDSA):
@@ -1964,8 +1968,7 @@ int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp,
          */
          */
         do
         do
         {
         {
-            MBEDTLS_MPI_CHK( f_rng( p_rng, rnd, n_size ) );
-            MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( d, rnd, n_size ) );
+            MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );
             MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_size - grp->nbits ) );
             MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_size - grp->nbits ) );
 
 
             /*
             /*

+ 103 - 33
mbedtls/library/entropy.c

@@ -68,21 +68,26 @@ static void mbedtls_zeroize( void *v, size_t n ) {
 
 
 void mbedtls_entropy_init( mbedtls_entropy_context *ctx )
 void mbedtls_entropy_init( mbedtls_entropy_context *ctx )
 {
 {
-    memset( ctx, 0, sizeof(mbedtls_entropy_context) );
+    ctx->source_count = 0;
+    memset( ctx->source, 0, sizeof( ctx->source ) );
 
 
 #if defined(MBEDTLS_THREADING_C)
 #if defined(MBEDTLS_THREADING_C)
     mbedtls_mutex_init( &ctx->mutex );
     mbedtls_mutex_init( &ctx->mutex );
 #endif
 #endif
 
 
+    ctx->accumulator_started = 0;
 #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
 #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
-    mbedtls_sha512_starts( &ctx->accumulator, 0 );
+    mbedtls_sha512_init( &ctx->accumulator );
 #else
 #else
-    mbedtls_sha256_starts( &ctx->accumulator, 0 );
+    mbedtls_sha256_init( &ctx->accumulator );
 #endif
 #endif
 #if defined(MBEDTLS_HAVEGE_C)
 #if defined(MBEDTLS_HAVEGE_C)
     mbedtls_havege_init( &ctx->havege_data );
     mbedtls_havege_init( &ctx->havege_data );
 #endif
 #endif
 
 
+    /* Reminder: Update ENTROPY_HAVE_STRONG in the test files
+     *           when adding more strong entropy sources here. */
+
 #if defined(MBEDTLS_TEST_NULL_ENTROPY)
 #if defined(MBEDTLS_TEST_NULL_ENTROPY)
     mbedtls_entropy_add_source( ctx, mbedtls_null_entropy_poll, NULL,
     mbedtls_entropy_add_source( ctx, mbedtls_null_entropy_poll, NULL,
                                 1, MBEDTLS_ENTROPY_SOURCE_STRONG );
                                 1, MBEDTLS_ENTROPY_SOURCE_STRONG );
@@ -113,6 +118,7 @@ void mbedtls_entropy_init( mbedtls_entropy_context *ctx )
     mbedtls_entropy_add_source( ctx, mbedtls_nv_seed_poll, NULL,
     mbedtls_entropy_add_source( ctx, mbedtls_nv_seed_poll, NULL,
                                 MBEDTLS_ENTROPY_BLOCK_SIZE,
                                 MBEDTLS_ENTROPY_BLOCK_SIZE,
                                 MBEDTLS_ENTROPY_SOURCE_STRONG );
                                 MBEDTLS_ENTROPY_SOURCE_STRONG );
+    ctx->initial_entropy_run = 0;
 #endif
 #endif
 #endif /* MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES */
 #endif /* MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES */
 }
 }
@@ -125,7 +131,17 @@ void mbedtls_entropy_free( mbedtls_entropy_context *ctx )
 #if defined(MBEDTLS_THREADING_C)
 #if defined(MBEDTLS_THREADING_C)
     mbedtls_mutex_free( &ctx->mutex );
     mbedtls_mutex_free( &ctx->mutex );
 #endif
 #endif
-    mbedtls_zeroize( ctx, sizeof( mbedtls_entropy_context ) );
+#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
+    mbedtls_sha512_free( &ctx->accumulator );
+#else
+    mbedtls_sha256_free( &ctx->accumulator );
+#endif
+#if defined(MBEDTLS_ENTROPY_NV_SEED)
+    ctx->initial_entropy_run = 0;
+#endif
+    ctx->source_count = 0;
+    mbedtls_zeroize( ctx->source, sizeof( ctx->source ) );
+    ctx->accumulator_started = 0;
 }
 }
 
 
 int mbedtls_entropy_add_source( mbedtls_entropy_context *ctx,
 int mbedtls_entropy_add_source( mbedtls_entropy_context *ctx,
@@ -172,13 +188,16 @@ static int entropy_update( mbedtls_entropy_context *ctx, unsigned char source_id
     unsigned char tmp[MBEDTLS_ENTROPY_BLOCK_SIZE];
     unsigned char tmp[MBEDTLS_ENTROPY_BLOCK_SIZE];
     size_t use_len = len;
     size_t use_len = len;
     const unsigned char *p = data;
     const unsigned char *p = data;
+    int ret = 0;
 
 
     if( use_len > MBEDTLS_ENTROPY_BLOCK_SIZE )
     if( use_len > MBEDTLS_ENTROPY_BLOCK_SIZE )
     {
     {
 #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
 #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
-        mbedtls_sha512( data, len, tmp, 0 );
+        if( ( ret = mbedtls_sha512_ret( data, len, tmp, 0 ) ) != 0 )
+            goto cleanup;
 #else
 #else
-        mbedtls_sha256( data, len, tmp, 0 );
+        if( ( ret = mbedtls_sha256_ret( data, len, tmp, 0 ) ) != 0 )
+            goto cleanup;
 #endif
 #endif
         p = tmp;
         p = tmp;
         use_len = MBEDTLS_ENTROPY_BLOCK_SIZE;
         use_len = MBEDTLS_ENTROPY_BLOCK_SIZE;
@@ -187,15 +206,35 @@ static int entropy_update( mbedtls_entropy_context *ctx, unsigned char source_id
     header[0] = source_id;
     header[0] = source_id;
     header[1] = use_len & 0xFF;
     header[1] = use_len & 0xFF;
 
 
+    /*
+     * Start the accumulator if this has not already happened. Note that
+     * it is sufficient to start the accumulator here only because all calls to
+     * gather entropy eventually execute this code.
+     */
 #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
 #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
-    mbedtls_sha512_update( &ctx->accumulator, header, 2 );
-    mbedtls_sha512_update( &ctx->accumulator, p, use_len );
+    if( ctx->accumulator_started == 0 &&
+        ( ret = mbedtls_sha512_starts_ret( &ctx->accumulator, 0 ) ) != 0 )
+        goto cleanup;
+    else
+        ctx->accumulator_started = 1;
+    if( ( ret = mbedtls_sha512_update_ret( &ctx->accumulator, header, 2 ) ) != 0 )
+        goto cleanup;
+    ret = mbedtls_sha512_update_ret( &ctx->accumulator, p, use_len );
 #else
 #else
-    mbedtls_sha256_update( &ctx->accumulator, header, 2 );
-    mbedtls_sha256_update( &ctx->accumulator, p, use_len );
+    if( ctx->accumulator_started == 0 &&
+        ( ret = mbedtls_sha256_starts_ret( &ctx->accumulator, 0 ) ) != 0 )
+        goto cleanup;
+    else
+        ctx->accumulator_started = 1;
+    if( ( ret = mbedtls_sha256_update_ret( &ctx->accumulator, header, 2 ) ) != 0 )
+        goto cleanup;
+    ret = mbedtls_sha256_update_ret( &ctx->accumulator, p, use_len );
 #endif
 #endif
 
 
-    return( 0 );
+cleanup:
+    mbedtls_zeroize( tmp, sizeof( tmp ) );
+
+    return( ret );
 }
 }
 
 
 int mbedtls_entropy_update_manual( mbedtls_entropy_context *ctx,
 int mbedtls_entropy_update_manual( mbedtls_entropy_context *ctx,
@@ -242,7 +281,7 @@ static int entropy_gather_internal( mbedtls_entropy_context *ctx )
         if( ( ret = ctx->source[i].f_source( ctx->source[i].p_source,
         if( ( ret = ctx->source[i].f_source( ctx->source[i].p_source,
                         buf, MBEDTLS_ENTROPY_MAX_GATHER, &olen ) ) != 0 )
                         buf, MBEDTLS_ENTROPY_MAX_GATHER, &olen ) ) != 0 )
         {
         {
-            return( ret );
+            goto cleanup;
         }
         }
 
 
         /*
         /*
@@ -250,15 +289,20 @@ static int entropy_gather_internal( mbedtls_entropy_context *ctx )
          */
          */
         if( olen > 0 )
         if( olen > 0 )
         {
         {
-            entropy_update( ctx, (unsigned char) i, buf, olen );
+            if( ( ret = entropy_update( ctx, (unsigned char) i,
+                                        buf, olen ) ) != 0 )
+                return( ret );
             ctx->source[i].size += olen;
             ctx->source[i].size += olen;
         }
         }
     }
     }
 
 
     if( have_one_strong == 0 )
     if( have_one_strong == 0 )
-        return( MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE );
+        ret = MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE;
 
 
-    return( 0 );
+cleanup:
+    mbedtls_zeroize( buf, sizeof( buf ) );
+
+    return( ret );
 }
 }
 
 
 /*
 /*
@@ -333,33 +377,52 @@ int mbedtls_entropy_func( void *data, unsigned char *output, size_t len )
     memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
     memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
 
 
 #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
 #if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
-    mbedtls_sha512_finish( &ctx->accumulator, buf );
+    /*
+     * Note that at this stage it is assumed that the accumulator was started
+     * in a previous call to entropy_update(). If this is not guaranteed, the
+     * code below will fail.
+     */
+    if( ( ret = mbedtls_sha512_finish_ret( &ctx->accumulator, buf ) ) != 0 )
+        goto exit;
 
 
     /*
     /*
      * Reset accumulator and counters and recycle existing entropy
      * Reset accumulator and counters and recycle existing entropy
      */
      */
-    memset( &ctx->accumulator, 0, sizeof( mbedtls_sha512_context ) );
-    mbedtls_sha512_starts( &ctx->accumulator, 0 );
-    mbedtls_sha512_update( &ctx->accumulator, buf, MBEDTLS_ENTROPY_BLOCK_SIZE );
+    mbedtls_sha512_free( &ctx->accumulator );
+    mbedtls_sha512_init( &ctx->accumulator );
+    if( ( ret = mbedtls_sha512_starts_ret( &ctx->accumulator, 0 ) ) != 0 )
+        goto exit;
+    if( ( ret = mbedtls_sha512_update_ret( &ctx->accumulator, buf,
+                                           MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )
+        goto exit;
 
 
     /*
     /*
      * Perform second SHA-512 on entropy
      * Perform second SHA-512 on entropy
      */
      */
-    mbedtls_sha512( buf, MBEDTLS_ENTROPY_BLOCK_SIZE, buf, 0 );
+    if( ( ret = mbedtls_sha512_ret( buf, MBEDTLS_ENTROPY_BLOCK_SIZE,
+                                    buf, 0 ) ) != 0 )
+        goto exit;
 #else /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */
 #else /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */
-    mbedtls_sha256_finish( &ctx->accumulator, buf );
+    if( ( ret = mbedtls_sha256_finish_ret( &ctx->accumulator, buf ) ) != 0 )
+        goto exit;
 
 
     /*
     /*
      * Reset accumulator and counters and recycle existing entropy
      * Reset accumulator and counters and recycle existing entropy
      */
      */
-    memset( &ctx->accumulator, 0, sizeof( mbedtls_sha256_context ) );
-    mbedtls_sha256_starts( &ctx->accumulator, 0 );
-    mbedtls_sha256_update( &ctx->accumulator, buf, MBEDTLS_ENTROPY_BLOCK_SIZE );
+    mbedtls_sha256_free( &ctx->accumulator );
+    mbedtls_sha256_init( &ctx->accumulator );
+    if( ( ret = mbedtls_sha256_starts_ret( &ctx->accumulator, 0 ) ) != 0 )
+        goto exit;
+    if( ( ret = mbedtls_sha256_update_ret( &ctx->accumulator, buf,
+                                           MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )
+        goto exit;
 
 
     /*
     /*
      * Perform second SHA-256 on entropy
      * Perform second SHA-256 on entropy
      */
      */
-    mbedtls_sha256( buf, MBEDTLS_ENTROPY_BLOCK_SIZE, buf, 0 );
+    if( ( ret = mbedtls_sha256_ret( buf, MBEDTLS_ENTROPY_BLOCK_SIZE,
+                                    buf, 0 ) ) != 0 )
+        goto exit;
 #endif /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */
 #endif /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */
 
 
     for( i = 0; i < ctx->source_count; i++ )
     for( i = 0; i < ctx->source_count; i++ )
@@ -370,6 +433,8 @@ int mbedtls_entropy_func( void *data, unsigned char *output, size_t len )
     ret = 0;
     ret = 0;
 
 
 exit:
 exit:
+    mbedtls_zeroize( buf, sizeof( buf ) );
+
 #if defined(MBEDTLS_THREADING_C)
 #if defined(MBEDTLS_THREADING_C)
     if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
     if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
         return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
         return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
@@ -382,7 +447,7 @@ exit:
 int mbedtls_entropy_update_nv_seed( mbedtls_entropy_context *ctx )
 int mbedtls_entropy_update_nv_seed( mbedtls_entropy_context *ctx )
 {
 {
     int ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR;
     int ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR;
-    unsigned char buf[ MBEDTLS_ENTROPY_MAX_SEED_SIZE ];
+    unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];
 
 
     /* Read new seed  and write it to NV */
     /* Read new seed  and write it to NV */
     if( ( ret = mbedtls_entropy_func( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )
     if( ( ret = mbedtls_entropy_func( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) ) != 0 )
@@ -393,9 +458,9 @@ int mbedtls_entropy_update_nv_seed( mbedtls_entropy_context *ctx )
 
 
     /* Manually update the remaining stream with a separator value to diverge */
     /* Manually update the remaining stream with a separator value to diverge */
     memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
     memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
-    mbedtls_entropy_update_manual( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE );
+    ret = mbedtls_entropy_update_manual( ctx, buf, MBEDTLS_ENTROPY_BLOCK_SIZE );
 
 
-    return( 0 );
+    return( ret );
 }
 }
 #endif /* MBEDTLS_ENTROPY_NV_SEED */
 #endif /* MBEDTLS_ENTROPY_NV_SEED */
 
 
@@ -421,12 +486,15 @@ int mbedtls_entropy_write_seed_file( mbedtls_entropy_context *ctx, const char *p
     ret = 0;
     ret = 0;
 
 
 exit:
 exit:
+    mbedtls_zeroize( buf, sizeof( buf ) );
+
     fclose( f );
     fclose( f );
     return( ret );
     return( ret );
 }
 }
 
 
 int mbedtls_entropy_update_seed_file( mbedtls_entropy_context *ctx, const char *path )
 int mbedtls_entropy_update_seed_file( mbedtls_entropy_context *ctx, const char *path )
 {
 {
+    int ret = 0;
     FILE *f;
     FILE *f;
     size_t n;
     size_t n;
     unsigned char buf[ MBEDTLS_ENTROPY_MAX_SEED_SIZE ];
     unsigned char buf[ MBEDTLS_ENTROPY_MAX_SEED_SIZE ];
@@ -442,14 +510,16 @@ int mbedtls_entropy_update_seed_file( mbedtls_entropy_context *ctx, const char *
         n = MBEDTLS_ENTROPY_MAX_SEED_SIZE;
         n = MBEDTLS_ENTROPY_MAX_SEED_SIZE;
 
 
     if( fread( buf, 1, n, f ) != n )
     if( fread( buf, 1, n, f ) != n )
-    {
-        fclose( f );
-        return( MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR );
-    }
+        ret = MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR;
+    else
+        ret = mbedtls_entropy_update_manual( ctx, buf, n );
 
 
     fclose( f );
     fclose( f );
 
 
-    mbedtls_entropy_update_manual( ctx, buf, n );
+    mbedtls_zeroize( buf, sizeof( buf ) );
+
+    if( ret != 0 )
+        return( ret );
 
 
     return( mbedtls_entropy_write_seed_file( ctx, path ) );
     return( mbedtls_entropy_write_seed_file( ctx, path ) );
 }
 }

+ 9 - 48
mbedtls/library/entropy_poll.c

@@ -92,6 +92,7 @@ int mbedtls_platform_entropy_poll( void *data, unsigned char *output, size_t len
 #include <sys/syscall.h>
 #include <sys/syscall.h>
 #if defined(SYS_getrandom)
 #if defined(SYS_getrandom)
 #define HAVE_GETRANDOM
 #define HAVE_GETRANDOM
+#include <errno.h>
 
 
 static int getrandom_wrapper( void *buf, size_t buflen, unsigned int flags )
 static int getrandom_wrapper( void *buf, size_t buflen, unsigned int flags )
 {
 {
@@ -101,47 +102,8 @@ static int getrandom_wrapper( void *buf, size_t buflen, unsigned int flags )
     memset( buf, 0, buflen );
     memset( buf, 0, buflen );
 #endif
 #endif
 #endif
 #endif
-
     return( syscall( SYS_getrandom, buf, buflen, flags ) );
     return( syscall( SYS_getrandom, buf, buflen, flags ) );
 }
 }
-
-#include <sys/utsname.h>
-/* Check if version is at least 3.17.0 */
-static int check_version_3_17_plus( void )
-{
-    int minor;
-    struct utsname un;
-    const char *ver;
-
-    /* Get version information */
-    uname(&un);
-    ver = un.release;
-
-    /* Check major version; assume a single digit */
-    if( ver[0] < '3' || ver[0] > '9' || ver [1] != '.' )
-        return( -1 );
-
-    if( ver[0] - '0' > 3 )
-        return( 0 );
-
-    /* Ok, so now we know major == 3, check minor.
-     * Assume 1 or 2 digits. */
-    if( ver[2] < '0' || ver[2] > '9' )
-        return( -1 );
-
-    minor = ver[2] - '0';
-
-    if( ver[3] >= '0' && ver[3] <= '9' )
-        minor = 10 * minor + ver[3] - '0';
-    else if( ver [3] != '.' )
-        return( -1 );
-
-    if( minor < 17 )
-        return( -1 );
-
-    return( 0 );
-}
-static int has_getrandom = -1;
 #endif /* SYS_getrandom */
 #endif /* SYS_getrandom */
 #endif /* __linux__ */
 #endif /* __linux__ */
 
 
@@ -152,22 +114,21 @@ int mbedtls_platform_entropy_poll( void *data,
 {
 {
     FILE *file;
     FILE *file;
     size_t read_len;
     size_t read_len;
+    int ret;
     ((void) data);
     ((void) data);
 
 
 #if defined(HAVE_GETRANDOM)
 #if defined(HAVE_GETRANDOM)
-    if( has_getrandom == -1 )
-        has_getrandom = ( check_version_3_17_plus() == 0 );
-
-    if( has_getrandom )
+    ret = getrandom_wrapper( output, len, 0 );
+    if( ret >= 0 )
     {
     {
-        int ret;
-
-        if( ( ret = getrandom_wrapper( output, len, 0 ) ) < 0 )
-            return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
-
         *olen = ret;
         *olen = ret;
         return( 0 );
         return( 0 );
     }
     }
+    else if( errno != ENOSYS )
+        return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
+    /* Fall through if the system call isn't known. */
+#else
+    ((void) ret);
 #endif /* HAVE_GETRANDOM */
 #endif /* HAVE_GETRANDOM */
 
 
     *olen = 0;
     *olen = 0;

+ 124 - 11
mbedtls/library/error.c

@@ -45,6 +45,10 @@
 #include "mbedtls/aes.h"
 #include "mbedtls/aes.h"
 #endif
 #endif
 
 
+#if defined(MBEDTLS_ARC4_C)
+#include "mbedtls/arc4.h"
+#endif
+
 #if defined(MBEDTLS_BASE64_C)
 #if defined(MBEDTLS_BASE64_C)
 #include "mbedtls/base64.h"
 #include "mbedtls/base64.h"
 #endif
 #endif
@@ -69,6 +73,10 @@
 #include "mbedtls/cipher.h"
 #include "mbedtls/cipher.h"
 #endif
 #endif
 
 
+#if defined(MBEDTLS_CMAC_C)
+#include "mbedtls/cmac.h"
+#endif
+
 #if defined(MBEDTLS_CTR_DRBG_C)
 #if defined(MBEDTLS_CTR_DRBG_C)
 #include "mbedtls/ctr_drbg.h"
 #include "mbedtls/ctr_drbg.h"
 #endif
 #endif
@@ -101,6 +109,18 @@
 #include "mbedtls/md.h"
 #include "mbedtls/md.h"
 #endif
 #endif
 
 
+#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_NET_C)
 #if defined(MBEDTLS_NET_C)
 #include "mbedtls/net_sockets.h"
 #include "mbedtls/net_sockets.h"
 #endif
 #endif
@@ -129,10 +149,26 @@
 #include "mbedtls/pkcs5.h"
 #include "mbedtls/pkcs5.h"
 #endif
 #endif
 
 
+#if defined(MBEDTLS_RIPEMD160_C)
+#include "mbedtls/ripemd160.h"
+#endif
+
 #if defined(MBEDTLS_RSA_C)
 #if defined(MBEDTLS_RSA_C)
 #include "mbedtls/rsa.h"
 #include "mbedtls/rsa.h"
 #endif
 #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_SSL_TLS_C)
 #if defined(MBEDTLS_SSL_TLS_C)
 #include "mbedtls/ssl.h"
 #include "mbedtls/ssl.h"
 #endif
 #endif
@@ -174,7 +210,7 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
         if( use_ret == -(MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE) )
         if( use_ret == -(MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE) )
             mbedtls_snprintf( buf, buflen, "CIPHER - The selected feature is not available" );
             mbedtls_snprintf( buf, buflen, "CIPHER - The selected feature is not available" );
         if( use_ret == -(MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA) )
         if( use_ret == -(MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA) )
-            mbedtls_snprintf( buf, buflen, "CIPHER - Bad input parameters to function" );
+            mbedtls_snprintf( buf, buflen, "CIPHER - Bad input parameters" );
         if( use_ret == -(MBEDTLS_ERR_CIPHER_ALLOC_FAILED) )
         if( use_ret == -(MBEDTLS_ERR_CIPHER_ALLOC_FAILED) )
             mbedtls_snprintf( buf, buflen, "CIPHER - Failed to allocate memory" );
             mbedtls_snprintf( buf, buflen, "CIPHER - Failed to allocate memory" );
         if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_PADDING) )
         if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_PADDING) )
@@ -184,12 +220,14 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
         if( use_ret == -(MBEDTLS_ERR_CIPHER_AUTH_FAILED) )
         if( use_ret == -(MBEDTLS_ERR_CIPHER_AUTH_FAILED) )
             mbedtls_snprintf( buf, buflen, "CIPHER - Authentication failed (for AEAD modes)" );
             mbedtls_snprintf( buf, buflen, "CIPHER - Authentication failed (for AEAD modes)" );
         if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_CONTEXT) )
         if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_CONTEXT) )
-            mbedtls_snprintf( buf, buflen, "CIPHER - The context is invalid, eg because it was free()ed" );
+            mbedtls_snprintf( buf, buflen, "CIPHER - The context is invalid. For example, because it was freed" );
+        if( use_ret == -(MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED) )
+            mbedtls_snprintf( buf, buflen, "CIPHER - Cipher hardware accelerator failed" );
 #endif /* MBEDTLS_CIPHER_C */
 #endif /* MBEDTLS_CIPHER_C */
 
 
 #if defined(MBEDTLS_DHM_C)
 #if defined(MBEDTLS_DHM_C)
         if( use_ret == -(MBEDTLS_ERR_DHM_BAD_INPUT_DATA) )
         if( use_ret == -(MBEDTLS_ERR_DHM_BAD_INPUT_DATA) )
-            mbedtls_snprintf( buf, buflen, "DHM - Bad input parameters to function" );
+            mbedtls_snprintf( buf, buflen, "DHM - Bad input parameters" );
         if( use_ret == -(MBEDTLS_ERR_DHM_READ_PARAMS_FAILED) )
         if( use_ret == -(MBEDTLS_ERR_DHM_READ_PARAMS_FAILED) )
             mbedtls_snprintf( buf, buflen, "DHM - Reading of the DHM parameters failed" );
             mbedtls_snprintf( buf, buflen, "DHM - Reading of the DHM parameters failed" );
         if( use_ret == -(MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED) )
         if( use_ret == -(MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED) )
@@ -205,7 +243,11 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
         if( use_ret == -(MBEDTLS_ERR_DHM_ALLOC_FAILED) )
         if( use_ret == -(MBEDTLS_ERR_DHM_ALLOC_FAILED) )
             mbedtls_snprintf( buf, buflen, "DHM - Allocation of memory failed" );
             mbedtls_snprintf( buf, buflen, "DHM - Allocation of memory failed" );
         if( use_ret == -(MBEDTLS_ERR_DHM_FILE_IO_ERROR) )
         if( use_ret == -(MBEDTLS_ERR_DHM_FILE_IO_ERROR) )
-            mbedtls_snprintf( buf, buflen, "DHM - Read/write of file failed" );
+            mbedtls_snprintf( buf, buflen, "DHM - Read or write of file failed" );
+        if( use_ret == -(MBEDTLS_ERR_DHM_HW_ACCEL_FAILED) )
+            mbedtls_snprintf( buf, buflen, "DHM - DHM hardware accelerator failed" );
+        if( use_ret == -(MBEDTLS_ERR_DHM_SET_GROUP_FAILED) )
+            mbedtls_snprintf( buf, buflen, "DHM - Setting the modulus and generator failed" );
 #endif /* MBEDTLS_DHM_C */
 #endif /* MBEDTLS_DHM_C */
 
 
 #if defined(MBEDTLS_ECP_C)
 #if defined(MBEDTLS_ECP_C)
@@ -224,7 +266,9 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
         if( use_ret == -(MBEDTLS_ERR_ECP_INVALID_KEY) )
         if( use_ret == -(MBEDTLS_ERR_ECP_INVALID_KEY) )
             mbedtls_snprintf( buf, buflen, "ECP - Invalid private or public key" );
             mbedtls_snprintf( buf, buflen, "ECP - Invalid private or public key" );
         if( use_ret == -(MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH) )
         if( use_ret == -(MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH) )
-            mbedtls_snprintf( buf, buflen, "ECP - Signature is valid but shorter than the user-supplied length" );
+            mbedtls_snprintf( buf, buflen, "ECP - The buffer contains a valid signature followed by more data" );
+        if( use_ret == -(MBEDTLS_ERR_ECP_HW_ACCEL_FAILED) )
+            mbedtls_snprintf( buf, buflen, "ECP - ECP hardware accelerator failed" );
 #endif /* MBEDTLS_ECP_C */
 #endif /* MBEDTLS_ECP_C */
 
 
 #if defined(MBEDTLS_MD_C)
 #if defined(MBEDTLS_MD_C)
@@ -236,6 +280,8 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
             mbedtls_snprintf( buf, buflen, "MD - Failed to allocate memory" );
             mbedtls_snprintf( buf, buflen, "MD - Failed to allocate memory" );
         if( use_ret == -(MBEDTLS_ERR_MD_FILE_IO_ERROR) )
         if( use_ret == -(MBEDTLS_ERR_MD_FILE_IO_ERROR) )
             mbedtls_snprintf( buf, buflen, "MD - Opening or reading of file failed" );
             mbedtls_snprintf( buf, buflen, "MD - Opening or reading of file failed" );
+        if( use_ret == -(MBEDTLS_ERR_MD_HW_ACCEL_FAILED) )
+            mbedtls_snprintf( buf, buflen, "MD - MD hardware accelerator failed" );
 #endif /* MBEDTLS_MD_C */
 #endif /* MBEDTLS_MD_C */
 
 
 #if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C)
 #if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C)
@@ -287,7 +333,9 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
         if( use_ret == -(MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE) )
         if( use_ret == -(MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE) )
             mbedtls_snprintf( buf, buflen, "PK - Unavailable feature, e.g. RSA disabled for RSA key" );
             mbedtls_snprintf( buf, buflen, "PK - Unavailable feature, e.g. RSA disabled for RSA key" );
         if( use_ret == -(MBEDTLS_ERR_PK_SIG_LEN_MISMATCH) )
         if( use_ret == -(MBEDTLS_ERR_PK_SIG_LEN_MISMATCH) )
-            mbedtls_snprintf( buf, buflen, "PK - The signature is valid but its length is less than expected" );
+            mbedtls_snprintf( buf, buflen, "PK - The buffer contains a valid signature followed by more data" );
+        if( use_ret == -(MBEDTLS_ERR_PK_HW_ACCEL_FAILED) )
+            mbedtls_snprintf( buf, buflen, "PK - PK hardware accelerator failed" );
 #endif /* MBEDTLS_PK_C */
 #endif /* MBEDTLS_PK_C */
 
 
 #if defined(MBEDTLS_PKCS12_C)
 #if defined(MBEDTLS_PKCS12_C)
@@ -320,7 +368,7 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
         if( use_ret == -(MBEDTLS_ERR_RSA_KEY_GEN_FAILED) )
         if( use_ret == -(MBEDTLS_ERR_RSA_KEY_GEN_FAILED) )
             mbedtls_snprintf( buf, buflen, "RSA - Something failed during generation of a key" );
             mbedtls_snprintf( buf, buflen, "RSA - Something failed during generation of a key" );
         if( use_ret == -(MBEDTLS_ERR_RSA_KEY_CHECK_FAILED) )
         if( use_ret == -(MBEDTLS_ERR_RSA_KEY_CHECK_FAILED) )
-            mbedtls_snprintf( buf, buflen, "RSA - Key failed to pass the library's validity check" );
+            mbedtls_snprintf( buf, buflen, "RSA - Key failed to pass the validity check of the library" );
         if( use_ret == -(MBEDTLS_ERR_RSA_PUBLIC_FAILED) )
         if( use_ret == -(MBEDTLS_ERR_RSA_PUBLIC_FAILED) )
             mbedtls_snprintf( buf, buflen, "RSA - The public key operation failed" );
             mbedtls_snprintf( buf, buflen, "RSA - The public key operation failed" );
         if( use_ret == -(MBEDTLS_ERR_RSA_PRIVATE_FAILED) )
         if( use_ret == -(MBEDTLS_ERR_RSA_PRIVATE_FAILED) )
@@ -331,6 +379,10 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
             mbedtls_snprintf( buf, buflen, "RSA - The output buffer for decryption is not large enough" );
             mbedtls_snprintf( buf, buflen, "RSA - The output buffer for decryption is not large enough" );
         if( use_ret == -(MBEDTLS_ERR_RSA_RNG_FAILED) )
         if( use_ret == -(MBEDTLS_ERR_RSA_RNG_FAILED) )
             mbedtls_snprintf( buf, buflen, "RSA - The random generator failed to generate non-zeros" );
             mbedtls_snprintf( buf, buflen, "RSA - The random generator failed to generate non-zeros" );
+        if( use_ret == -(MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION) )
+            mbedtls_snprintf( buf, buflen, "RSA - The implementation does not offer the requested operation, for example, because of security violations or lack of functionality" );
+        if( use_ret == -(MBEDTLS_ERR_RSA_HW_ACCEL_FAILED) )
+            mbedtls_snprintf( buf, buflen, "RSA - RSA hardware accelerator failed" );
 #endif /* MBEDTLS_RSA_C */
 #endif /* MBEDTLS_RSA_C */
 
 
 #if defined(MBEDTLS_SSL_TLS_C)
 #if defined(MBEDTLS_SSL_TLS_C)
@@ -518,8 +570,17 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
         mbedtls_snprintf( buf, buflen, "AES - Invalid key length" );
         mbedtls_snprintf( buf, buflen, "AES - Invalid key length" );
     if( use_ret == -(MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH) )
     if( use_ret == -(MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH) )
         mbedtls_snprintf( buf, buflen, "AES - Invalid data input length" );
         mbedtls_snprintf( buf, buflen, "AES - Invalid data input length" );
+    if( use_ret == -(MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE) )
+        mbedtls_snprintf( buf, buflen, "AES - Feature not available. For example, an unsupported AES key size" );
+    if( use_ret == -(MBEDTLS_ERR_AES_HW_ACCEL_FAILED) )
+        mbedtls_snprintf( buf, buflen, "AES - AES hardware accelerator failed" );
 #endif /* MBEDTLS_AES_C */
 #endif /* MBEDTLS_AES_C */
 
 
+#if defined(MBEDTLS_ARC4_C)
+    if( use_ret == -(MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED) )
+        mbedtls_snprintf( buf, buflen, "ARC4 - ARC4 hardware accelerator failed" );
+#endif /* MBEDTLS_ARC4_C */
+
 #if defined(MBEDTLS_ASN1_PARSE_C)
 #if defined(MBEDTLS_ASN1_PARSE_C)
     if( use_ret == -(MBEDTLS_ERR_ASN1_OUT_OF_DATA) )
     if( use_ret == -(MBEDTLS_ERR_ASN1_OUT_OF_DATA) )
         mbedtls_snprintf( buf, buflen, "ASN1 - Out of data when parsing an ASN1 data structure" );
         mbedtls_snprintf( buf, buflen, "ASN1 - Out of data when parsing an ASN1 data structure" );
@@ -566,6 +627,8 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
 #if defined(MBEDTLS_BLOWFISH_C)
 #if defined(MBEDTLS_BLOWFISH_C)
     if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH) )
     if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH) )
         mbedtls_snprintf( buf, buflen, "BLOWFISH - Invalid key length" );
         mbedtls_snprintf( buf, buflen, "BLOWFISH - Invalid key length" );
+    if( use_ret == -(MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED) )
+        mbedtls_snprintf( buf, buflen, "BLOWFISH - Blowfish hardware accelerator failed" );
     if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH) )
     if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH) )
         mbedtls_snprintf( buf, buflen, "BLOWFISH - Invalid data input length" );
         mbedtls_snprintf( buf, buflen, "BLOWFISH - Invalid data input length" );
 #endif /* MBEDTLS_BLOWFISH_C */
 #endif /* MBEDTLS_BLOWFISH_C */
@@ -575,29 +638,40 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
         mbedtls_snprintf( buf, buflen, "CAMELLIA - Invalid key length" );
         mbedtls_snprintf( buf, buflen, "CAMELLIA - Invalid key length" );
     if( use_ret == -(MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH) )
     if( use_ret == -(MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH) )
         mbedtls_snprintf( buf, buflen, "CAMELLIA - Invalid data input length" );
         mbedtls_snprintf( buf, buflen, "CAMELLIA - Invalid data input length" );
+    if( use_ret == -(MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED) )
+        mbedtls_snprintf( buf, buflen, "CAMELLIA - Camellia hardware accelerator failed" );
 #endif /* MBEDTLS_CAMELLIA_C */
 #endif /* MBEDTLS_CAMELLIA_C */
 
 
 #if defined(MBEDTLS_CCM_C)
 #if defined(MBEDTLS_CCM_C)
     if( use_ret == -(MBEDTLS_ERR_CCM_BAD_INPUT) )
     if( use_ret == -(MBEDTLS_ERR_CCM_BAD_INPUT) )
-        mbedtls_snprintf( buf, buflen, "CCM - Bad input parameters to function" );
+        mbedtls_snprintf( buf, buflen, "CCM - Bad input parameters to the function" );
     if( use_ret == -(MBEDTLS_ERR_CCM_AUTH_FAILED) )
     if( use_ret == -(MBEDTLS_ERR_CCM_AUTH_FAILED) )
         mbedtls_snprintf( buf, buflen, "CCM - Authenticated decryption failed" );
         mbedtls_snprintf( buf, buflen, "CCM - Authenticated decryption failed" );
+    if( use_ret == -(MBEDTLS_ERR_CCM_HW_ACCEL_FAILED) )
+        mbedtls_snprintf( buf, buflen, "CCM - CCM hardware accelerator failed" );
 #endif /* MBEDTLS_CCM_C */
 #endif /* MBEDTLS_CCM_C */
 
 
+#if defined(MBEDTLS_CMAC_C)
+    if( use_ret == -(MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED) )
+        mbedtls_snprintf( buf, buflen, "CMAC - CMAC hardware accelerator failed" );
+#endif /* MBEDTLS_CMAC_C */
+
 #if defined(MBEDTLS_CTR_DRBG_C)
 #if defined(MBEDTLS_CTR_DRBG_C)
     if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED) )
     if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED) )
         mbedtls_snprintf( buf, buflen, "CTR_DRBG - The entropy source failed" );
         mbedtls_snprintf( buf, buflen, "CTR_DRBG - The entropy source failed" );
     if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG) )
     if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG) )
-        mbedtls_snprintf( buf, buflen, "CTR_DRBG - Too many random requested in single call" );
+        mbedtls_snprintf( buf, buflen, "CTR_DRBG - The requested random buffer length is too big" );
     if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG) )
     if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG) )
-        mbedtls_snprintf( buf, buflen, "CTR_DRBG - Input too large (Entropy + additional)" );
+        mbedtls_snprintf( buf, buflen, "CTR_DRBG - The input (entropy + additional data) is too large" );
     if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR) )
     if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR) )
-        mbedtls_snprintf( buf, buflen, "CTR_DRBG - Read/write error in file" );
+        mbedtls_snprintf( buf, buflen, "CTR_DRBG - Read or write error in file" );
 #endif /* MBEDTLS_CTR_DRBG_C */
 #endif /* MBEDTLS_CTR_DRBG_C */
 
 
 #if defined(MBEDTLS_DES_C)
 #if defined(MBEDTLS_DES_C)
     if( use_ret == -(MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH) )
     if( use_ret == -(MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH) )
         mbedtls_snprintf( buf, buflen, "DES - The data input has an invalid length" );
         mbedtls_snprintf( buf, buflen, "DES - The data input has an invalid length" );
+    if( use_ret == -(MBEDTLS_ERR_DES_HW_ACCEL_FAILED) )
+        mbedtls_snprintf( buf, buflen, "DES - DES hardware accelerator failed" );
 #endif /* MBEDTLS_DES_C */
 #endif /* MBEDTLS_DES_C */
 
 
 #if defined(MBEDTLS_ENTROPY_C)
 #if defined(MBEDTLS_ENTROPY_C)
@@ -616,6 +690,8 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
 #if defined(MBEDTLS_GCM_C)
 #if defined(MBEDTLS_GCM_C)
     if( use_ret == -(MBEDTLS_ERR_GCM_AUTH_FAILED) )
     if( use_ret == -(MBEDTLS_ERR_GCM_AUTH_FAILED) )
         mbedtls_snprintf( buf, buflen, "GCM - Authenticated decryption failed" );
         mbedtls_snprintf( buf, buflen, "GCM - Authenticated decryption failed" );
+    if( use_ret == -(MBEDTLS_ERR_GCM_HW_ACCEL_FAILED) )
+        mbedtls_snprintf( buf, buflen, "GCM - GCM hardware accelerator failed" );
     if( use_ret == -(MBEDTLS_ERR_GCM_BAD_INPUT) )
     if( use_ret == -(MBEDTLS_ERR_GCM_BAD_INPUT) )
         mbedtls_snprintf( buf, buflen, "GCM - Bad input parameters to function" );
         mbedtls_snprintf( buf, buflen, "GCM - Bad input parameters to function" );
 #endif /* MBEDTLS_GCM_C */
 #endif /* MBEDTLS_GCM_C */
@@ -631,6 +707,21 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
         mbedtls_snprintf( buf, buflen, "HMAC_DRBG - The entropy source failed" );
         mbedtls_snprintf( buf, buflen, "HMAC_DRBG - The entropy source failed" );
 #endif /* MBEDTLS_HMAC_DRBG_C */
 #endif /* MBEDTLS_HMAC_DRBG_C */
 
 
+#if defined(MBEDTLS_MD2_C)
+    if( use_ret == -(MBEDTLS_ERR_MD2_HW_ACCEL_FAILED) )
+        mbedtls_snprintf( buf, buflen, "MD2 - MD2 hardware accelerator failed" );
+#endif /* MBEDTLS_MD2_C */
+
+#if defined(MBEDTLS_MD4_C)
+    if( use_ret == -(MBEDTLS_ERR_MD4_HW_ACCEL_FAILED) )
+        mbedtls_snprintf( buf, buflen, "MD4 - MD4 hardware accelerator failed" );
+#endif /* MBEDTLS_MD4_C */
+
+#if defined(MBEDTLS_MD5_C)
+    if( use_ret == -(MBEDTLS_ERR_MD5_HW_ACCEL_FAILED) )
+        mbedtls_snprintf( buf, buflen, "MD5 - MD5 hardware accelerator failed" );
+#endif /* MBEDTLS_MD5_C */
+
 #if defined(MBEDTLS_NET_C)
 #if defined(MBEDTLS_NET_C)
     if( use_ret == -(MBEDTLS_ERR_NET_SOCKET_FAILED) )
     if( use_ret == -(MBEDTLS_ERR_NET_SOCKET_FAILED) )
         mbedtls_snprintf( buf, buflen, "NET - Failed to open a socket" );
         mbedtls_snprintf( buf, buflen, "NET - Failed to open a socket" );
@@ -668,6 +759,26 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
         mbedtls_snprintf( buf, buflen, "PADLOCK - Input data should be aligned" );
         mbedtls_snprintf( buf, buflen, "PADLOCK - Input data should be aligned" );
 #endif /* MBEDTLS_PADLOCK_C */
 #endif /* MBEDTLS_PADLOCK_C */
 
 
+#if defined(MBEDTLS_RIPEMD160_C)
+    if( use_ret == -(MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED) )
+        mbedtls_snprintf( buf, buflen, "RIPEMD160 - RIPEMD160 hardware accelerator failed" );
+#endif /* MBEDTLS_RIPEMD160_C */
+
+#if defined(MBEDTLS_SHA1_C)
+    if( use_ret == -(MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED) )
+        mbedtls_snprintf( buf, buflen, "SHA1 - SHA-1 hardware accelerator failed" );
+#endif /* MBEDTLS_SHA1_C */
+
+#if defined(MBEDTLS_SHA256_C)
+    if( use_ret == -(MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED) )
+        mbedtls_snprintf( buf, buflen, "SHA256 - SHA-256 hardware accelerator failed" );
+#endif /* MBEDTLS_SHA256_C */
+
+#if defined(MBEDTLS_SHA512_C)
+    if( use_ret == -(MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED) )
+        mbedtls_snprintf( buf, buflen, "SHA512 - SHA-512 hardware accelerator failed" );
+#endif /* MBEDTLS_SHA512_C */
+
 #if defined(MBEDTLS_THREADING_C)
 #if defined(MBEDTLS_THREADING_C)
     if( use_ret == -(MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE) )
     if( use_ret == -(MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE) )
         mbedtls_snprintf( buf, buflen, "THREADING - The selected feature is not available" );
         mbedtls_snprintf( buf, buflen, "THREADING - The selected feature is not available" );
@@ -680,6 +791,8 @@ void mbedtls_strerror( int ret, char *buf, size_t buflen )
 #if defined(MBEDTLS_XTEA_C)
 #if defined(MBEDTLS_XTEA_C)
     if( use_ret == -(MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH) )
     if( use_ret == -(MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH) )
         mbedtls_snprintf( buf, buflen, "XTEA - The data input has an invalid length" );
         mbedtls_snprintf( buf, buflen, "XTEA - The data input has an invalid length" );
+    if( use_ret == -(MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED) )
+        mbedtls_snprintf( buf, buflen, "XTEA - XTEA hardware accelerator failed" );
 #endif /* MBEDTLS_XTEA_C */
 #endif /* MBEDTLS_XTEA_C */
     // END generated code
     // END generated code
 
 

+ 102 - 98
mbedtls/library/gcm.c

@@ -46,6 +46,7 @@
 #endif
 #endif
 
 
 #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
 #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
+#include "mbedtls/aes.h"
 #if defined(MBEDTLS_PLATFORM_C)
 #if defined(MBEDTLS_PLATFORM_C)
 #include "mbedtls/platform.h"
 #include "mbedtls/platform.h"
 #else
 #else
@@ -54,6 +55,8 @@
 #endif /* MBEDTLS_PLATFORM_C */
 #endif /* MBEDTLS_PLATFORM_C */
 #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
 #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
 
 
+#if !defined(MBEDTLS_GCM_ALT)
+
 /*
 /*
  * 32-bit integer manipulation macros (big endian)
  * 32-bit integer manipulation macros (big endian)
  */
  */
@@ -508,6 +511,8 @@ void mbedtls_gcm_free( mbedtls_gcm_context *ctx )
     mbedtls_zeroize( ctx, sizeof( mbedtls_gcm_context ) );
     mbedtls_zeroize( ctx, sizeof( mbedtls_gcm_context ) );
 }
 }
 
 
+#endif /* !MBEDTLS_GCM_ALT */
+
 #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
 #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
 /*
 /*
  * AES-GCM test vectors from:
  * AES-GCM test vectors from:
@@ -744,34 +749,48 @@ int mbedtls_gcm_self_test( int verbose )
     int i, j, ret;
     int i, j, ret;
     mbedtls_cipher_id_t cipher = MBEDTLS_CIPHER_ID_AES;
     mbedtls_cipher_id_t cipher = MBEDTLS_CIPHER_ID_AES;
 
 
-    mbedtls_gcm_init( &ctx );
-
     for( j = 0; j < 3; j++ )
     for( j = 0; j < 3; j++ )
     {
     {
         int key_len = 128 + 64 * j;
         int key_len = 128 + 64 * j;
 
 
         for( i = 0; i < MAX_TESTS; i++ )
         for( i = 0; i < MAX_TESTS; i++ )
         {
         {
+            mbedtls_gcm_init( &ctx );
+
             if( verbose != 0 )
             if( verbose != 0 )
                 mbedtls_printf( "  AES-GCM-%3d #%d (%s): ",
                 mbedtls_printf( "  AES-GCM-%3d #%d (%s): ",
-                                 key_len, i, "enc" );
-
-            mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]], key_len );
+                                key_len, i, "enc" );
+
+            ret = mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]],
+                                      key_len );
+            /*
+             * AES-192 is an optional feature that may be unavailable when
+             * there is an alternative underlying implementation i.e. when
+             * MBEDTLS_AES_ALT is defined.
+             */
+            if( ret == MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE && key_len == 192 )
+            {
+                mbedtls_printf( "skipped\n" );
+                break;
+            }
+            else if( ret != 0 )
+            {
+                goto exit;
+            }
 
 
             ret = mbedtls_gcm_crypt_and_tag( &ctx, MBEDTLS_GCM_ENCRYPT,
             ret = mbedtls_gcm_crypt_and_tag( &ctx, MBEDTLS_GCM_ENCRYPT,
-                                     pt_len[i],
-                                     iv[iv_index[i]], iv_len[i],
-                                     additional[add_index[i]], add_len[i],
-                                     pt[pt_index[i]], buf, 16, tag_buf );
+                                        pt_len[i],
+                                        iv[iv_index[i]], iv_len[i],
+                                        additional[add_index[i]], add_len[i],
+                                        pt[pt_index[i]], buf, 16, tag_buf );
+            if( ret != 0 )
+                goto exit;
 
 
-            if( ret != 0 ||
-                memcmp( buf, ct[j * 6 + i], pt_len[i] ) != 0 ||
-                memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )
+            if ( memcmp( buf, ct[j * 6 + i], pt_len[i] ) != 0 ||
+                 memcmp( tag_buf, tag[j * 6 + i], 16 ) != 0 )
             {
             {
-                if( verbose != 0 )
-                    mbedtls_printf( "failed\n" );
-
-                return( 1 );
+                ret = 1;
+                goto exit;
             }
             }
 
 
             mbedtls_gcm_free( &ctx );
             mbedtls_gcm_free( &ctx );
@@ -779,26 +798,31 @@ int mbedtls_gcm_self_test( int verbose )
             if( verbose != 0 )
             if( verbose != 0 )
                 mbedtls_printf( "passed\n" );
                 mbedtls_printf( "passed\n" );
 
 
+            mbedtls_gcm_init( &ctx );
+
             if( verbose != 0 )
             if( verbose != 0 )
                 mbedtls_printf( "  AES-GCM-%3d #%d (%s): ",
                 mbedtls_printf( "  AES-GCM-%3d #%d (%s): ",
-                                 key_len, i, "dec" );
+                                key_len, i, "dec" );
 
 
-            mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]], key_len );
+            ret = mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]],
+                                      key_len );
+            if( ret != 0 )
+                goto exit;
 
 
             ret = mbedtls_gcm_crypt_and_tag( &ctx, MBEDTLS_GCM_DECRYPT,
             ret = mbedtls_gcm_crypt_and_tag( &ctx, MBEDTLS_GCM_DECRYPT,
-                                     pt_len[i],
-                                     iv[iv_index[i]], iv_len[i],
-                                     additional[add_index[i]], add_len[i],
-                                     ct[j * 6 + i], buf, 16, tag_buf );
+                                        pt_len[i],
+                                        iv[iv_index[i]], iv_len[i],
+                                        additional[add_index[i]], add_len[i],
+                                        ct[j * 6 + i], buf, 16, tag_buf );
+
+            if( ret != 0 )
+                goto exit;
 
 
-            if( ret != 0 ||
-                memcmp( buf, pt[pt_index[i]], pt_len[i] ) != 0 ||
+            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 )
             {
             {
-                if( verbose != 0 )
-                    mbedtls_printf( "failed\n" );
-
-                return( 1 );
+                ret = 1;
+                goto exit;
             }
             }
 
 
             mbedtls_gcm_free( &ctx );
             mbedtls_gcm_free( &ctx );
@@ -806,66 +830,51 @@ int mbedtls_gcm_self_test( int verbose )
             if( verbose != 0 )
             if( verbose != 0 )
                 mbedtls_printf( "passed\n" );
                 mbedtls_printf( "passed\n" );
 
 
+            mbedtls_gcm_init( &ctx );
+
             if( verbose != 0 )
             if( verbose != 0 )
                 mbedtls_printf( "  AES-GCM-%3d #%d split (%s): ",
                 mbedtls_printf( "  AES-GCM-%3d #%d split (%s): ",
-                                 key_len, i, "enc" );
+                                key_len, i, "enc" );
 
 
-            mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]], key_len );
+            ret = mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]],
+                                      key_len );
+            if( ret != 0 )
+                goto exit;
 
 
             ret = mbedtls_gcm_starts( &ctx, MBEDTLS_GCM_ENCRYPT,
             ret = mbedtls_gcm_starts( &ctx, MBEDTLS_GCM_ENCRYPT,
-                              iv[iv_index[i]], iv_len[i],
-                              additional[add_index[i]], add_len[i] );
+                                      iv[iv_index[i]], iv_len[i],
+                                      additional[add_index[i]], add_len[i] );
             if( ret != 0 )
             if( ret != 0 )
-            {
-                if( verbose != 0 )
-                    mbedtls_printf( "failed\n" );
-
-                return( 1 );
-            }
+                goto exit;
 
 
             if( pt_len[i] > 32 )
             if( pt_len[i] > 32 )
             {
             {
                 size_t rest_len = pt_len[i] - 32;
                 size_t rest_len = pt_len[i] - 32;
                 ret = mbedtls_gcm_update( &ctx, 32, pt[pt_index[i]], buf );
                 ret = mbedtls_gcm_update( &ctx, 32, pt[pt_index[i]], buf );
                 if( ret != 0 )
                 if( ret != 0 )
-                {
-                    if( verbose != 0 )
-                        mbedtls_printf( "failed\n" );
-
-                    return( 1 );
-                }
+                    goto exit;
 
 
                 ret = mbedtls_gcm_update( &ctx, rest_len, pt[pt_index[i]] + 32,
                 ret = mbedtls_gcm_update( &ctx, rest_len, pt[pt_index[i]] + 32,
                                   buf + 32 );
                                   buf + 32 );
                 if( ret != 0 )
                 if( ret != 0 )
-                {
-                    if( verbose != 0 )
-                        mbedtls_printf( "failed\n" );
-
-                    return( 1 );
-                }
+                    goto exit;
             }
             }
             else
             else
             {
             {
                 ret = mbedtls_gcm_update( &ctx, pt_len[i], pt[pt_index[i]], buf );
                 ret = mbedtls_gcm_update( &ctx, pt_len[i], pt[pt_index[i]], buf );
                 if( ret != 0 )
                 if( ret != 0 )
-                {
-                    if( verbose != 0 )
-                        mbedtls_printf( "failed\n" );
-
-                    return( 1 );
-                }
+                    goto exit;
             }
             }
 
 
             ret = mbedtls_gcm_finish( &ctx, tag_buf, 16 );
             ret = mbedtls_gcm_finish( &ctx, tag_buf, 16 );
-            if( ret != 0 ||
-                memcmp( buf, ct[j * 6 + i], pt_len[i] ) != 0 ||
+            if( ret != 0 )
+                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 )
             {
             {
-                if( verbose != 0 )
-                    mbedtls_printf( "failed\n" );
-
-                return( 1 );
+                ret = 1;
+                goto exit;
             }
             }
 
 
             mbedtls_gcm_free( &ctx );
             mbedtls_gcm_free( &ctx );
@@ -873,80 +882,75 @@ int mbedtls_gcm_self_test( int verbose )
             if( verbose != 0 )
             if( verbose != 0 )
                 mbedtls_printf( "passed\n" );
                 mbedtls_printf( "passed\n" );
 
 
+            mbedtls_gcm_init( &ctx );
+
             if( verbose != 0 )
             if( verbose != 0 )
                 mbedtls_printf( "  AES-GCM-%3d #%d split (%s): ",
                 mbedtls_printf( "  AES-GCM-%3d #%d split (%s): ",
-                                 key_len, i, "dec" );
+                                key_len, i, "dec" );
 
 
-            mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]], key_len );
+            ret = mbedtls_gcm_setkey( &ctx, cipher, key[key_index[i]],
+                                      key_len );
+            if( ret != 0 )
+                goto exit;
 
 
             ret = mbedtls_gcm_starts( &ctx, MBEDTLS_GCM_DECRYPT,
             ret = mbedtls_gcm_starts( &ctx, MBEDTLS_GCM_DECRYPT,
                               iv[iv_index[i]], iv_len[i],
                               iv[iv_index[i]], iv_len[i],
                               additional[add_index[i]], add_len[i] );
                               additional[add_index[i]], add_len[i] );
             if( ret != 0 )
             if( ret != 0 )
-            {
-                if( verbose != 0 )
-                    mbedtls_printf( "failed\n" );
-
-                return( 1 );
-            }
+                goto exit;
 
 
             if( pt_len[i] > 32 )
             if( pt_len[i] > 32 )
             {
             {
                 size_t rest_len = pt_len[i] - 32;
                 size_t rest_len = pt_len[i] - 32;
                 ret = mbedtls_gcm_update( &ctx, 32, ct[j * 6 + i], buf );
                 ret = mbedtls_gcm_update( &ctx, 32, ct[j * 6 + i], buf );
                 if( ret != 0 )
                 if( ret != 0 )
-                {
-                    if( verbose != 0 )
-                        mbedtls_printf( "failed\n" );
-
-                    return( 1 );
-                }
+                    goto exit;
 
 
                 ret = mbedtls_gcm_update( &ctx, rest_len, ct[j * 6 + i] + 32,
                 ret = mbedtls_gcm_update( &ctx, rest_len, ct[j * 6 + i] + 32,
-                                  buf + 32 );
+                                          buf + 32 );
                 if( ret != 0 )
                 if( ret != 0 )
-                {
-                    if( verbose != 0 )
-                        mbedtls_printf( "failed\n" );
-
-                    return( 1 );
-                }
+                    goto exit;
             }
             }
             else
             else
             {
             {
-                ret = mbedtls_gcm_update( &ctx, pt_len[i], ct[j * 6 + i], buf );
+                ret = mbedtls_gcm_update( &ctx, pt_len[i], ct[j * 6 + i],
+                                          buf );
                 if( ret != 0 )
                 if( ret != 0 )
-                {
-                    if( verbose != 0 )
-                        mbedtls_printf( "failed\n" );
-
-                    return( 1 );
-                }
+                    goto exit;
             }
             }
 
 
             ret = mbedtls_gcm_finish( &ctx, tag_buf, 16 );
             ret = mbedtls_gcm_finish( &ctx, tag_buf, 16 );
-            if( ret != 0 ||
-                memcmp( buf, pt[pt_index[i]], pt_len[i] ) != 0 ||
+            if( ret != 0 )
+                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 )
             {
             {
-                if( verbose != 0 )
-                    mbedtls_printf( "failed\n" );
-
-                return( 1 );
+                ret = 1;
+                goto exit;
             }
             }
 
 
             mbedtls_gcm_free( &ctx );
             mbedtls_gcm_free( &ctx );
 
 
             if( verbose != 0 )
             if( verbose != 0 )
                 mbedtls_printf( "passed\n" );
                 mbedtls_printf( "passed\n" );
-
         }
         }
     }
     }
 
 
     if( verbose != 0 )
     if( verbose != 0 )
         mbedtls_printf( "\n" );
         mbedtls_printf( "\n" );
 
 
-    return( 0 );
+    ret = 0;
+
+exit:
+    if( ret != 0 )
+    {
+        if( verbose != 0 )
+            mbedtls_printf( "failed\n" );
+        mbedtls_gcm_free( &ctx );
+    }
+
+    return( ret );
 }
 }
 
 
 #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
 #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */

+ 79 - 27
mbedtls/library/hmac_drbg.c

@@ -70,29 +70,56 @@ void mbedtls_hmac_drbg_init( mbedtls_hmac_drbg_context *ctx )
 /*
 /*
  * HMAC_DRBG update, using optional additional data (10.1.2.2)
  * HMAC_DRBG update, using optional additional data (10.1.2.2)
  */
  */
-void mbedtls_hmac_drbg_update( mbedtls_hmac_drbg_context *ctx,
-                       const unsigned char *additional, size_t add_len )
+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( ctx->md_ctx.md_info );
     unsigned char rounds = ( additional != NULL && add_len != 0 ) ? 2 : 1;
     unsigned char rounds = ( additional != NULL && add_len != 0 ) ? 2 : 1;
     unsigned char sep[1];
     unsigned char sep[1];
     unsigned char K[MBEDTLS_MD_MAX_SIZE];
     unsigned char K[MBEDTLS_MD_MAX_SIZE];
+    int ret;
 
 
     for( sep[0] = 0; sep[0] < rounds; sep[0]++ )
     for( sep[0] = 0; sep[0] < rounds; sep[0]++ )
     {
     {
         /* Step 1 or 4 */
         /* Step 1 or 4 */
-        mbedtls_md_hmac_reset( &ctx->md_ctx );
-        mbedtls_md_hmac_update( &ctx->md_ctx, ctx->V, md_len );
-        mbedtls_md_hmac_update( &ctx->md_ctx, sep, 1 );
+        if( ( ret = mbedtls_md_hmac_reset( &ctx->md_ctx ) ) != 0 )
+            goto exit;
+        if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx,
+                                            ctx->V, md_len ) ) != 0 )
+            goto exit;
+        if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx,
+                                            sep, 1 ) ) != 0 )
+            goto exit;
         if( rounds == 2 )
         if( rounds == 2 )
-            mbedtls_md_hmac_update( &ctx->md_ctx, additional, add_len );
-        mbedtls_md_hmac_finish( &ctx->md_ctx, K );
+        {
+            if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx,
+                                                additional, add_len ) ) != 0 )
+            goto exit;
+        }
+        if( ( ret = mbedtls_md_hmac_finish( &ctx->md_ctx, K ) ) != 0 )
+            goto exit;
 
 
         /* Step 2 or 5 */
         /* Step 2 or 5 */
-        mbedtls_md_hmac_starts( &ctx->md_ctx, K, md_len );
-        mbedtls_md_hmac_update( &ctx->md_ctx, ctx->V, md_len );
-        mbedtls_md_hmac_finish( &ctx->md_ctx, ctx->V );
+        if( ( ret = mbedtls_md_hmac_starts( &ctx->md_ctx, K, md_len ) ) != 0 )
+            goto exit;
+        if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx,
+                                            ctx->V, md_len ) ) != 0 )
+            goto exit;
+        if( ( ret = mbedtls_md_hmac_finish( &ctx->md_ctx, ctx->V ) ) != 0 )
+            goto exit;
     }
     }
+
+exit:
+    mbedtls_zeroize( K, sizeof( K ) );
+    return( ret );
+}
+
+void mbedtls_hmac_drbg_update( mbedtls_hmac_drbg_context *ctx,
+                               const unsigned char *additional,
+                               size_t add_len )
+{
+    (void) mbedtls_hmac_drbg_update_ret( ctx, additional, add_len );
 }
 }
 
 
 /*
 /*
@@ -112,10 +139,13 @@ int mbedtls_hmac_drbg_seed_buf( mbedtls_hmac_drbg_context *ctx,
      * Use the V memory location, which is currently all 0, to initialize the
      * Use the V memory location, which is currently all 0, to initialize the
      * MD context with an all-zero key. Then set V to its initial value.
      * MD context with an all-zero key. Then set V to its initial value.
      */
      */
-    mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V, mbedtls_md_get_size( md_info ) );
+    if( ( ret = mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V,
+                                        mbedtls_md_get_size( md_info ) ) ) != 0 )
+        return( ret );
     memset( ctx->V, 0x01, mbedtls_md_get_size( md_info ) );
     memset( ctx->V, 0x01, mbedtls_md_get_size( md_info ) );
 
 
-    mbedtls_hmac_drbg_update( ctx, data, data_len );
+    if( ( ret = mbedtls_hmac_drbg_update_ret( ctx, data, data_len ) ) != 0 )
+        return( ret );
 
 
     return( 0 );
     return( 0 );
 }
 }
@@ -128,6 +158,7 @@ int mbedtls_hmac_drbg_reseed( mbedtls_hmac_drbg_context *ctx,
 {
 {
     unsigned char seed[MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT];
     unsigned char seed[MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT];
     size_t seedlen;
     size_t seedlen;
+    int ret;
 
 
     /* III. Check input length */
     /* III. Check input length */
     if( len > MBEDTLS_HMAC_DRBG_MAX_INPUT ||
     if( len > MBEDTLS_HMAC_DRBG_MAX_INPUT ||
@@ -139,7 +170,8 @@ int mbedtls_hmac_drbg_reseed( mbedtls_hmac_drbg_context *ctx,
     memset( seed, 0, MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT );
     memset( seed, 0, MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT );
 
 
     /* IV. Gather entropy_len bytes of entropy for the seed */
     /* IV. Gather entropy_len bytes of entropy for the seed */
-    if( ctx->f_entropy( ctx->p_entropy, seed, ctx->entropy_len ) != 0 )
+    if( ( ret = ctx->f_entropy( ctx->p_entropy,
+                                seed, ctx->entropy_len ) ) != 0 )
         return( MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED );
         return( MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED );
 
 
     seedlen = ctx->entropy_len;
     seedlen = ctx->entropy_len;
@@ -152,13 +184,16 @@ int mbedtls_hmac_drbg_reseed( mbedtls_hmac_drbg_context *ctx,
     }
     }
 
 
     /* 2. Update state */
     /* 2. Update state */
-    mbedtls_hmac_drbg_update( ctx, seed, seedlen );
+    if( ( ret = mbedtls_hmac_drbg_update_ret( ctx, seed, seedlen ) ) != 0 )
+        goto exit;
 
 
     /* 3. Reset reseed_counter */
     /* 3. Reset reseed_counter */
     ctx->reseed_counter = 1;
     ctx->reseed_counter = 1;
 
 
+exit:
     /* 4. Done */
     /* 4. Done */
-    return( 0 );
+    mbedtls_zeroize( seed, seedlen );
+    return( ret );
 }
 }
 
 
 /*
 /*
@@ -184,7 +219,8 @@ int mbedtls_hmac_drbg_seed( mbedtls_hmac_drbg_context *ctx,
      * Use the V memory location, which is currently all 0, to initialize the
      * Use the V memory location, which is currently all 0, to initialize the
      * MD context with an all-zero key. Then set V to its initial value.
      * MD context with an all-zero key. Then set V to its initial value.
      */
      */
-    mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V, md_size );
+    if( ( ret = mbedtls_md_hmac_starts( &ctx->md_ctx, ctx->V, md_size ) ) != 0 )
+        return( ret );
     memset( ctx->V, 0x01, md_size );
     memset( ctx->V, 0x01, md_size );
 
 
     ctx->f_entropy = f_entropy;
     ctx->f_entropy = f_entropy;
@@ -277,16 +313,24 @@ int mbedtls_hmac_drbg_random_with_add( void *p_rng,
 
 
     /* 2. Use additional data if any */
     /* 2. Use additional data if any */
     if( additional != NULL && add_len != 0 )
     if( additional != NULL && add_len != 0 )
-        mbedtls_hmac_drbg_update( ctx, additional, add_len );
+    {
+        if( ( ret = mbedtls_hmac_drbg_update_ret( ctx,
+                                                  additional, add_len ) ) != 0 )
+            goto exit;
+    }
 
 
     /* 3, 4, 5. Generate bytes */
     /* 3, 4, 5. Generate bytes */
     while( left != 0 )
     while( left != 0 )
     {
     {
         size_t use_len = left > md_len ? md_len : left;
         size_t use_len = left > md_len ? md_len : left;
 
 
-        mbedtls_md_hmac_reset( &ctx->md_ctx );
-        mbedtls_md_hmac_update( &ctx->md_ctx, ctx->V, md_len );
-        mbedtls_md_hmac_finish( &ctx->md_ctx, ctx->V );
+        if( ( ret = mbedtls_md_hmac_reset( &ctx->md_ctx ) ) != 0 )
+            goto exit;
+        if( ( ret = mbedtls_md_hmac_update( &ctx->md_ctx,
+                                            ctx->V, md_len ) ) != 0 )
+            goto exit;
+        if( ( ret = mbedtls_md_hmac_finish( &ctx->md_ctx, ctx->V ) ) != 0 )
+            goto exit;
 
 
         memcpy( out, ctx->V, use_len );
         memcpy( out, ctx->V, use_len );
         out += use_len;
         out += use_len;
@@ -294,13 +338,16 @@ int mbedtls_hmac_drbg_random_with_add( void *p_rng,
     }
     }
 
 
     /* 6. Update */
     /* 6. Update */
-    mbedtls_hmac_drbg_update( ctx, additional, add_len );
+    if( ( ret = mbedtls_hmac_drbg_update_ret( ctx,
+                                              additional, add_len ) ) != 0 )
+        goto exit;
 
 
     /* 7. Update reseed counter */
     /* 7. Update reseed counter */
     ctx->reseed_counter++;
     ctx->reseed_counter++;
 
 
+exit:
     /* 8. Done */
     /* 8. Done */
-    return( 0 );
+    return( ret );
 }
 }
 
 
 /*
 /*
@@ -364,11 +411,14 @@ int mbedtls_hmac_drbg_write_seed_file( mbedtls_hmac_drbg_context *ctx, const cha
 
 
 exit:
 exit:
     fclose( f );
     fclose( f );
+    mbedtls_zeroize( buf, sizeof( buf ) );
+
     return( ret );
     return( ret );
 }
 }
 
 
 int mbedtls_hmac_drbg_update_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path )
 int mbedtls_hmac_drbg_update_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path )
 {
 {
+    int ret = 0;
     FILE *f;
     FILE *f;
     size_t n;
     size_t n;
     unsigned char buf[ MBEDTLS_HMAC_DRBG_MAX_INPUT ];
     unsigned char buf[ MBEDTLS_HMAC_DRBG_MAX_INPUT ];
@@ -387,14 +437,16 @@ int mbedtls_hmac_drbg_update_seed_file( mbedtls_hmac_drbg_context *ctx, const ch
     }
     }
 
 
     if( fread( buf, 1, n, f ) != n )
     if( fread( buf, 1, n, f ) != n )
-    {
-        fclose( f );
-        return( MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR );
-    }
+        ret = MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR;
+    else
+        ret = mbedtls_hmac_drbg_update_ret( ctx, buf, n );
 
 
     fclose( f );
     fclose( f );
 
 
-    mbedtls_hmac_drbg_update( ctx, buf, n );
+    mbedtls_zeroize( buf, sizeof( buf ) );
+
+    if( ret != 0 )
+        return( ret );
 
 
     return( mbedtls_hmac_drbg_write_seed_file( ctx, path ) );
     return( mbedtls_hmac_drbg_write_seed_file( ctx, path ) );
 }
 }

+ 58 - 51
mbedtls/library/md.c

@@ -250,9 +250,7 @@ int mbedtls_md_starts( mbedtls_md_context_t *ctx )
     if( ctx == NULL || ctx->md_info == NULL )
     if( ctx == NULL || ctx->md_info == NULL )
         return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
         return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
 
 
-    ctx->md_info->starts_func( ctx->md_ctx );
-
-    return( 0 );
+    return( ctx->md_info->starts_func( ctx->md_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 )
@@ -260,9 +258,7 @@ int mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, si
     if( ctx == NULL || ctx->md_info == NULL )
     if( ctx == NULL || ctx->md_info == NULL )
         return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
         return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
 
 
-    ctx->md_info->update_func( ctx->md_ctx, input, ilen );
-
-    return( 0 );
+    return( ctx->md_info->update_func( ctx->md_ctx, input, ilen ) );
 }
 }
 
 
 int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output )
 int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output )
@@ -270,9 +266,7 @@ int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output )
     if( ctx == NULL || ctx->md_info == NULL )
     if( ctx == NULL || ctx->md_info == NULL )
         return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
         return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
 
 
-    ctx->md_info->finish_func( ctx->md_ctx, output );
-
-    return( 0 );
+    return( ctx->md_info->finish_func( ctx->md_ctx, output ) );
 }
 }
 
 
 int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, size_t ilen,
 int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, size_t ilen,
@@ -281,9 +275,7 @@ int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, si
     if( md_info == NULL )
     if( md_info == NULL )
         return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
         return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
 
 
-    md_info->digest_func( input, ilen, output );
-
-    return( 0 );
+    return( md_info->digest_func( input, ilen, output ) );
 }
 }
 
 
 #if defined(MBEDTLS_FS_IO)
 #if defined(MBEDTLS_FS_IO)
@@ -306,20 +298,20 @@ 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 )
     if( ( ret = mbedtls_md_setup( &ctx, md_info, 0 ) ) != 0 )
         goto cleanup;
         goto cleanup;
 
 
-    md_info->starts_func( ctx.md_ctx );
+    if( ( ret = md_info->starts_func( ctx.md_ctx ) ) != 0 )
+        goto cleanup;
 
 
     while( ( n = fread( buf, 1, sizeof( buf ), f ) ) > 0 )
     while( ( n = fread( buf, 1, sizeof( buf ), f ) ) > 0 )
-        md_info->update_func( ctx.md_ctx, buf, n );
+        if( ( ret = md_info->update_func( ctx.md_ctx, buf, n ) ) != 0 )
+            goto cleanup;
 
 
     if( ferror( f ) != 0 )
     if( ferror( f ) != 0 )
-    {
         ret = MBEDTLS_ERR_MD_FILE_IO_ERROR;
         ret = MBEDTLS_ERR_MD_FILE_IO_ERROR;
-        goto cleanup;
-    }
-
-    md_info->finish_func( ctx.md_ctx, output );
+    else
+        ret = md_info->finish_func( ctx.md_ctx, output );
 
 
 cleanup:
 cleanup:
+    mbedtls_zeroize( buf, sizeof( buf ) );
     fclose( f );
     fclose( f );
     mbedtls_md_free( &ctx );
     mbedtls_md_free( &ctx );
 
 
@@ -329,6 +321,7 @@ cleanup:
 
 
 int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key, size_t keylen )
 int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key, size_t keylen )
 {
 {
+    int ret;
     unsigned char sum[MBEDTLS_MD_MAX_SIZE];
     unsigned char sum[MBEDTLS_MD_MAX_SIZE];
     unsigned char *ipad, *opad;
     unsigned char *ipad, *opad;
     size_t i;
     size_t i;
@@ -338,9 +331,12 @@ int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key,
 
 
     if( keylen > (size_t) ctx->md_info->block_size )
     if( keylen > (size_t) ctx->md_info->block_size )
     {
     {
-        ctx->md_info->starts_func( ctx->md_ctx );
-        ctx->md_info->update_func( ctx->md_ctx, key, keylen );
-        ctx->md_info->finish_func( ctx->md_ctx, sum );
+        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 )
+            goto cleanup;
 
 
         keylen = ctx->md_info->size;
         keylen = ctx->md_info->size;
         key = sum;
         key = sum;
@@ -358,12 +354,16 @@ int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key,
         opad[i] = (unsigned char)( opad[i] ^ key[i] );
         opad[i] = (unsigned char)( opad[i] ^ key[i] );
     }
     }
 
 
-    mbedtls_zeroize( sum, sizeof( sum ) );
+    if( ( ret = ctx->md_info->starts_func( ctx->md_ctx ) ) != 0 )
+        goto cleanup;
+    if( ( ret = ctx->md_info->update_func( ctx->md_ctx, ipad,
+                                           ctx->md_info->block_size ) ) != 0 )
+        goto cleanup;
 
 
-    ctx->md_info->starts_func( ctx->md_ctx );
-    ctx->md_info->update_func( ctx->md_ctx, ipad, ctx->md_info->block_size );
+cleanup:
+    mbedtls_zeroize( sum, sizeof( sum ) );
 
 
-    return( 0 );
+    return( ret );
 }
 }
 
 
 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 )
@@ -371,13 +371,12 @@ int mbedtls_md_hmac_update( mbedtls_md_context_t *ctx, const unsigned char *inpu
     if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )
     if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )
         return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
         return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
 
 
-    ctx->md_info->update_func( ctx->md_ctx, input, ilen );
-
-    return( 0 );
+    return( ctx->md_info->update_func( ctx->md_ctx, input, ilen ) );
 }
 }
 
 
 int mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output )
 int mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output )
 {
 {
+    int ret;
     unsigned char tmp[MBEDTLS_MD_MAX_SIZE];
     unsigned char tmp[MBEDTLS_MD_MAX_SIZE];
     unsigned char *opad;
     unsigned char *opad;
 
 
@@ -386,17 +385,22 @@ int mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output )
 
 
     opad = (unsigned char *) ctx->hmac_ctx + ctx->md_info->block_size;
     opad = (unsigned char *) ctx->hmac_ctx + ctx->md_info->block_size;
 
 
-    ctx->md_info->finish_func( ctx->md_ctx, tmp );
-    ctx->md_info->starts_func( ctx->md_ctx );
-    ctx->md_info->update_func( ctx->md_ctx, opad, ctx->md_info->block_size );
-    ctx->md_info->update_func( ctx->md_ctx, tmp, ctx->md_info->size );
-    ctx->md_info->finish_func( ctx->md_ctx, output );
-
-    return( 0 );
+    if( ( ret = ctx->md_info->finish_func( ctx->md_ctx, tmp ) ) != 0 )
+        return( ret );
+    if( ( ret = ctx->md_info->starts_func( ctx->md_ctx ) ) != 0 )
+        return( ret );
+    if( ( ret = ctx->md_info->update_func( ctx->md_ctx, opad,
+                                           ctx->md_info->block_size ) ) != 0 )
+        return( ret );
+    if( ( ret = ctx->md_info->update_func( ctx->md_ctx, tmp,
+                                           ctx->md_info->size ) ) != 0 )
+        return( ret );
+    return( ctx->md_info->finish_func( ctx->md_ctx, output ) );
 }
 }
 
 
 int mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx )
 int mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx )
 {
 {
+    int ret;
     unsigned char *ipad;
     unsigned char *ipad;
 
 
     if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )
     if( ctx == NULL || ctx->md_info == NULL || ctx->hmac_ctx == NULL )
@@ -404,15 +408,16 @@ int mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx )
 
 
     ipad = (unsigned char *) ctx->hmac_ctx;
     ipad = (unsigned char *) ctx->hmac_ctx;
 
 
-    ctx->md_info->starts_func( ctx->md_ctx );
-    ctx->md_info->update_func( ctx->md_ctx, ipad, ctx->md_info->block_size );
-
-    return( 0 );
+    if( ( ret = ctx->md_info->starts_func( ctx->md_ctx ) ) != 0 )
+        return( ret );
+    return( ctx->md_info->update_func( ctx->md_ctx, ipad,
+                                       ctx->md_info->block_size ) );
 }
 }
 
 
-int mbedtls_md_hmac( const mbedtls_md_info_t *md_info, const unsigned char *key, size_t keylen,
-                const unsigned char *input, size_t ilen,
-                unsigned char *output )
+int mbedtls_md_hmac( const mbedtls_md_info_t *md_info,
+                     const unsigned char *key, size_t keylen,
+                     const unsigned char *input, size_t ilen,
+                     unsigned char *output )
 {
 {
     mbedtls_md_context_t ctx;
     mbedtls_md_context_t ctx;
     int ret;
     int ret;
@@ -423,15 +428,19 @@ int mbedtls_md_hmac( const mbedtls_md_info_t *md_info, const unsigned char *key,
     mbedtls_md_init( &ctx );
     mbedtls_md_init( &ctx );
 
 
     if( ( ret = mbedtls_md_setup( &ctx, md_info, 1 ) ) != 0 )
     if( ( ret = mbedtls_md_setup( &ctx, md_info, 1 ) ) != 0 )
-        return( ret );
+        goto cleanup;
 
 
-    mbedtls_md_hmac_starts( &ctx, key, keylen );
-    mbedtls_md_hmac_update( &ctx, input, ilen );
-    mbedtls_md_hmac_finish( &ctx, output );
+    if( ( ret = mbedtls_md_hmac_starts( &ctx, key, keylen ) ) != 0 )
+        goto cleanup;
+    if( ( ret = mbedtls_md_hmac_update( &ctx, input, ilen ) ) != 0 )
+        goto cleanup;
+    if( ( ret = mbedtls_md_hmac_finish( &ctx, output ) ) != 0 )
+        goto cleanup;
 
 
+cleanup:
     mbedtls_md_free( &ctx );
     mbedtls_md_free( &ctx );
 
 
-    return( 0 );
+    return( ret );
 }
 }
 
 
 int mbedtls_md_process( mbedtls_md_context_t *ctx, const unsigned char *data )
 int mbedtls_md_process( mbedtls_md_context_t *ctx, const unsigned char *data )
@@ -439,9 +448,7 @@ int mbedtls_md_process( mbedtls_md_context_t *ctx, const unsigned char *data )
     if( ctx == NULL || ctx->md_info == NULL )
     if( ctx == NULL || ctx->md_info == NULL )
         return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
         return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
 
 
-    ctx->md_info->process_func( ctx->md_ctx, data );
-
-    return( 0 );
+    return( ctx->md_info->process_func( ctx->md_ctx, data ) );
 }
 }
 
 
 unsigned char mbedtls_md_get_size( const mbedtls_md_info_t *md_info )
 unsigned char mbedtls_md_get_size( const mbedtls_md_info_t *md_info )

+ 99 - 20
mbedtls/library/md2.c

@@ -105,16 +105,25 @@ void mbedtls_md2_clone( mbedtls_md2_context *dst,
 /*
 /*
  * MD2 context setup
  * MD2 context setup
  */
  */
-void mbedtls_md2_starts( mbedtls_md2_context *ctx )
+int mbedtls_md2_starts_ret( mbedtls_md2_context *ctx )
 {
 {
     memset( ctx->cksum, 0, 16 );
     memset( ctx->cksum, 0, 16 );
     memset( ctx->state, 0, 46 );
     memset( ctx->state, 0, 46 );
     memset( ctx->buffer, 0, 16 );
     memset( ctx->buffer, 0, 16 );
     ctx->left = 0;
     ctx->left = 0;
+
+    return( 0 );
 }
 }
 
 
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+void mbedtls_md2_starts( mbedtls_md2_context *ctx )
+{
+    mbedtls_md2_starts_ret( ctx );
+}
+#endif
+
 #if !defined(MBEDTLS_MD2_PROCESS_ALT)
 #if !defined(MBEDTLS_MD2_PROCESS_ALT)
-void mbedtls_md2_process( mbedtls_md2_context *ctx )
+int mbedtls_internal_md2_process( mbedtls_md2_context *ctx )
 {
 {
     int i, j;
     int i, j;
     unsigned char t = 0;
     unsigned char t = 0;
@@ -146,14 +155,26 @@ void mbedtls_md2_process( mbedtls_md2_context *ctx )
            ( ctx->cksum[i] ^ PI_SUBST[ctx->buffer[i] ^ t] );
            ( ctx->cksum[i] ^ PI_SUBST[ctx->buffer[i] ^ t] );
         t  = ctx->cksum[i];
         t  = ctx->cksum[i];
     }
     }
+
+    return( 0 );
 }
 }
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+void mbedtls_md2_process( mbedtls_md2_context *ctx )
+{
+    mbedtls_internal_md2_process( ctx );
+}
+#endif
 #endif /* !MBEDTLS_MD2_PROCESS_ALT */
 #endif /* !MBEDTLS_MD2_PROCESS_ALT */
 
 
 /*
 /*
  * MD2 process buffer
  * MD2 process buffer
  */
  */
-void mbedtls_md2_update( mbedtls_md2_context *ctx, const unsigned char *input, size_t ilen )
+int mbedtls_md2_update_ret( mbedtls_md2_context *ctx,
+                            const unsigned char *input,
+                            size_t ilen )
 {
 {
+    int ret;
     size_t fill;
     size_t fill;
 
 
     while( ilen > 0 )
     while( ilen > 0 )
@@ -172,16 +193,30 @@ void mbedtls_md2_update( mbedtls_md2_context *ctx, const unsigned char *input, s
         if( ctx->left == 16 )
         if( ctx->left == 16 )
         {
         {
             ctx->left = 0;
             ctx->left = 0;
-            mbedtls_md2_process( ctx );
+            if( ( ret = mbedtls_internal_md2_process( ctx ) ) != 0 )
+                return( ret );
         }
         }
     }
     }
+
+    return( 0 );
 }
 }
 
 
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+void mbedtls_md2_update( mbedtls_md2_context *ctx,
+                         const unsigned char *input,
+                         size_t ilen )
+{
+    mbedtls_md2_update_ret( ctx, input, ilen );
+}
+#endif
+
 /*
 /*
  * MD2 final digest
  * MD2 final digest
  */
  */
-void mbedtls_md2_finish( mbedtls_md2_context *ctx, unsigned char output[16] )
+int mbedtls_md2_finish_ret( mbedtls_md2_context *ctx,
+                            unsigned char output[16] )
 {
 {
+    int ret;
     size_t i;
     size_t i;
     unsigned char x;
     unsigned char x;
 
 
@@ -190,36 +225,70 @@ void mbedtls_md2_finish( mbedtls_md2_context *ctx, unsigned char output[16] )
     for( i = ctx->left; i < 16; i++ )
     for( i = ctx->left; i < 16; i++ )
         ctx->buffer[i] = x;
         ctx->buffer[i] = x;
 
 
-    mbedtls_md2_process( ctx );
+    if( ( ret = mbedtls_internal_md2_process( ctx ) ) != 0 )
+        return( ret );
 
 
     memcpy( ctx->buffer, ctx->cksum, 16 );
     memcpy( ctx->buffer, ctx->cksum, 16 );
-    mbedtls_md2_process( ctx );
+    if( ( ret = mbedtls_internal_md2_process( ctx ) ) != 0 )
+        return( ret );
 
 
     memcpy( output, ctx->state, 16 );
     memcpy( output, ctx->state, 16 );
+
+    return( 0 );
+}
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+void mbedtls_md2_finish( mbedtls_md2_context *ctx,
+                         unsigned char output[16] )
+{
+    mbedtls_md2_finish_ret( ctx, output );
 }
 }
+#endif
 
 
 #endif /* !MBEDTLS_MD2_ALT */
 #endif /* !MBEDTLS_MD2_ALT */
 
 
 /*
 /*
  * output = MD2( input buffer )
  * output = MD2( input buffer )
  */
  */
-void mbedtls_md2( const unsigned char *input, size_t ilen, unsigned char output[16] )
+int mbedtls_md2_ret( const unsigned char *input,
+                     size_t ilen,
+                     unsigned char output[16] )
 {
 {
+    int ret;
     mbedtls_md2_context ctx;
     mbedtls_md2_context ctx;
 
 
     mbedtls_md2_init( &ctx );
     mbedtls_md2_init( &ctx );
-    mbedtls_md2_starts( &ctx );
-    mbedtls_md2_update( &ctx, input, ilen );
-    mbedtls_md2_finish( &ctx, output );
+
+    if( ( ret = mbedtls_md2_starts_ret( &ctx ) ) != 0 )
+        goto exit;
+
+    if( ( ret = mbedtls_md2_update_ret( &ctx, input, ilen ) ) != 0 )
+        goto exit;
+
+    if( ( ret = mbedtls_md2_finish_ret( &ctx, output ) ) != 0 )
+        goto exit;
+
+exit:
     mbedtls_md2_free( &ctx );
     mbedtls_md2_free( &ctx );
+
+    return( ret );
 }
 }
 
 
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+void mbedtls_md2( const unsigned char *input,
+                  size_t ilen,
+                  unsigned char output[16] )
+{
+    mbedtls_md2_ret( input, ilen, output );
+}
+#endif
+
 #if defined(MBEDTLS_SELF_TEST)
 #if defined(MBEDTLS_SELF_TEST)
 
 
 /*
 /*
  * RFC 1319 test vectors
  * RFC 1319 test vectors
  */
  */
-static const char md2_test_str[7][81] =
+static const unsigned char md2_test_str[7][81] =
 {
 {
     { "" },
     { "" },
     { "a" },
     { "a" },
@@ -227,10 +296,15 @@ static const char md2_test_str[7][81] =
     { "message digest" },
     { "message digest" },
     { "abcdefghijklmnopqrstuvwxyz" },
     { "abcdefghijklmnopqrstuvwxyz" },
     { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" },
     { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" },
-    { "12345678901234567890123456789012345678901234567890123456789012" \
+    { "12345678901234567890123456789012345678901234567890123456789012"
       "345678901234567890" }
       "345678901234567890" }
 };
 };
 
 
+static const size_t md2_test_strlen[7] =
+{
+    0, 1, 3, 14, 26, 62, 80
+};
+
 static const unsigned char md2_test_sum[7][16] =
 static const unsigned char md2_test_sum[7][16] =
 {
 {
     { 0x83, 0x50, 0xE5, 0xA3, 0xE2, 0x4C, 0x15, 0x3D,
     { 0x83, 0x50, 0xE5, 0xA3, 0xE2, 0x4C, 0x15, 0x3D,
@@ -254,7 +328,7 @@ static const unsigned char md2_test_sum[7][16] =
  */
  */
 int mbedtls_md2_self_test( int verbose )
 int mbedtls_md2_self_test( int verbose )
 {
 {
-    int i;
+    int i, ret = 0;
     unsigned char md2sum[16];
     unsigned char md2sum[16];
 
 
     for( i = 0; i < 7; i++ )
     for( i = 0; i < 7; i++ )
@@ -262,15 +336,14 @@ int mbedtls_md2_self_test( int verbose )
         if( verbose != 0 )
         if( verbose != 0 )
             mbedtls_printf( "  MD2 test #%d: ", i + 1 );
             mbedtls_printf( "  MD2 test #%d: ", i + 1 );
 
 
-        mbedtls_md2( (unsigned char *) md2_test_str[i],
-             strlen( md2_test_str[i] ), md2sum );
+        ret = mbedtls_md2_ret( md2_test_str[i], md2_test_strlen[i], md2sum );
+        if( ret != 0 )
+            goto fail;
 
 
         if( memcmp( md2sum, md2_test_sum[i], 16 ) != 0 )
         if( memcmp( md2sum, md2_test_sum[i], 16 ) != 0 )
         {
         {
-            if( verbose != 0 )
-                mbedtls_printf( "failed\n" );
-
-            return( 1 );
+            ret = 1;
+            goto fail;
         }
         }
 
 
         if( verbose != 0 )
         if( verbose != 0 )
@@ -281,6 +354,12 @@ int mbedtls_md2_self_test( int verbose )
         mbedtls_printf( "\n" );
         mbedtls_printf( "\n" );
 
 
     return( 0 );
     return( 0 );
+
+fail:
+    if( verbose != 0 )
+        mbedtls_printf( "failed\n" );
+
+    return( ret );
 }
 }
 
 
 #endif /* MBEDTLS_SELF_TEST */
 #endif /* MBEDTLS_SELF_TEST */

+ 110 - 22
mbedtls/library/md4.c

@@ -98,7 +98,7 @@ void mbedtls_md4_clone( mbedtls_md4_context *dst,
 /*
 /*
  * MD4 context setup
  * MD4 context setup
  */
  */
-void mbedtls_md4_starts( mbedtls_md4_context *ctx )
+int mbedtls_md4_starts_ret( mbedtls_md4_context *ctx )
 {
 {
     ctx->total[0] = 0;
     ctx->total[0] = 0;
     ctx->total[1] = 0;
     ctx->total[1] = 0;
@@ -107,10 +107,20 @@ void mbedtls_md4_starts( mbedtls_md4_context *ctx )
     ctx->state[1] = 0xEFCDAB89;
     ctx->state[1] = 0xEFCDAB89;
     ctx->state[2] = 0x98BADCFE;
     ctx->state[2] = 0x98BADCFE;
     ctx->state[3] = 0x10325476;
     ctx->state[3] = 0x10325476;
+
+    return( 0 );
+}
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+void mbedtls_md4_starts( mbedtls_md4_context *ctx )
+{
+    mbedtls_md4_starts_ret( ctx );
 }
 }
+#endif
 
 
 #if !defined(MBEDTLS_MD4_PROCESS_ALT)
 #if !defined(MBEDTLS_MD4_PROCESS_ALT)
-void mbedtls_md4_process( mbedtls_md4_context *ctx, const unsigned char data[64] )
+int mbedtls_internal_md4_process( mbedtls_md4_context *ctx,
+                                  const unsigned char data[64] )
 {
 {
     uint32_t X[16], A, B, C, D;
     uint32_t X[16], A, B, C, D;
 
 
@@ -211,19 +221,32 @@ void mbedtls_md4_process( mbedtls_md4_context *ctx, const unsigned char data[64]
     ctx->state[1] += B;
     ctx->state[1] += B;
     ctx->state[2] += C;
     ctx->state[2] += C;
     ctx->state[3] += D;
     ctx->state[3] += D;
+
+    return( 0 );
+}
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+void mbedtls_md4_process( mbedtls_md4_context *ctx,
+                          const unsigned char data[64] )
+{
+    mbedtls_internal_md4_process( ctx, data );
 }
 }
+#endif
 #endif /* !MBEDTLS_MD4_PROCESS_ALT */
 #endif /* !MBEDTLS_MD4_PROCESS_ALT */
 
 
 /*
 /*
  * MD4 process buffer
  * MD4 process buffer
  */
  */
-void mbedtls_md4_update( mbedtls_md4_context *ctx, const unsigned char *input, size_t ilen )
+int mbedtls_md4_update_ret( mbedtls_md4_context *ctx,
+                            const unsigned char *input,
+                            size_t ilen )
 {
 {
+    int ret;
     size_t fill;
     size_t fill;
     uint32_t left;
     uint32_t left;
 
 
     if( ilen == 0 )
     if( ilen == 0 )
-        return;
+        return( 0 );
 
 
     left = ctx->total[0] & 0x3F;
     left = ctx->total[0] & 0x3F;
     fill = 64 - left;
     fill = 64 - left;
@@ -238,7 +261,10 @@ void mbedtls_md4_update( mbedtls_md4_context *ctx, const unsigned char *input, s
     {
     {
         memcpy( (void *) (ctx->buffer + left),
         memcpy( (void *) (ctx->buffer + left),
                 (void *) input, fill );
                 (void *) input, fill );
-        mbedtls_md4_process( ctx, ctx->buffer );
+
+        if( ( ret = mbedtls_internal_md4_process( ctx, ctx->buffer ) ) != 0 )
+            return( ret );
+
         input += fill;
         input += fill;
         ilen  -= fill;
         ilen  -= fill;
         left = 0;
         left = 0;
@@ -246,7 +272,9 @@ void mbedtls_md4_update( mbedtls_md4_context *ctx, const unsigned char *input, s
 
 
     while( ilen >= 64 )
     while( ilen >= 64 )
     {
     {
-        mbedtls_md4_process( ctx, input );
+        if( ( ret = mbedtls_internal_md4_process( ctx, input ) ) != 0 )
+            return( ret );
+
         input += 64;
         input += 64;
         ilen  -= 64;
         ilen  -= 64;
     }
     }
@@ -256,7 +284,18 @@ void mbedtls_md4_update( mbedtls_md4_context *ctx, const unsigned char *input, s
         memcpy( (void *) (ctx->buffer + left),
         memcpy( (void *) (ctx->buffer + left),
                 (void *) input, ilen );
                 (void *) input, ilen );
     }
     }
+
+    return( 0 );
+}
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+void mbedtls_md4_update( mbedtls_md4_context *ctx,
+                         const unsigned char *input,
+                         size_t ilen )
+{
+    mbedtls_md4_update_ret( ctx, input, ilen );
 }
 }
+#endif
 
 
 static const unsigned char md4_padding[64] =
 static const unsigned char md4_padding[64] =
 {
 {
@@ -269,8 +308,10 @@ static const unsigned char md4_padding[64] =
 /*
 /*
  * MD4 final digest
  * MD4 final digest
  */
  */
-void mbedtls_md4_finish( mbedtls_md4_context *ctx, unsigned char output[16] )
+int mbedtls_md4_finish_ret( mbedtls_md4_context *ctx,
+                            unsigned char output[16] )
 {
 {
+    int ret;
     uint32_t last, padn;
     uint32_t last, padn;
     uint32_t high, low;
     uint32_t high, low;
     unsigned char msglen[8];
     unsigned char msglen[8];
@@ -285,37 +326,74 @@ void mbedtls_md4_finish( mbedtls_md4_context *ctx, unsigned char output[16] )
     last = ctx->total[0] & 0x3F;
     last = ctx->total[0] & 0x3F;
     padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );
     padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );
 
 
-    mbedtls_md4_update( ctx, (unsigned char *) md4_padding, padn );
-    mbedtls_md4_update( ctx, msglen, 8 );
+    ret = mbedtls_md4_update_ret( ctx, (unsigned char *)md4_padding, padn );
+    if( ret != 0 )
+        return( ret );
+
+    if( ( ret = mbedtls_md4_update_ret( ctx, msglen, 8 ) ) != 0 )
+        return( ret );
+
 
 
     PUT_UINT32_LE( ctx->state[0], output,  0 );
     PUT_UINT32_LE( ctx->state[0], output,  0 );
     PUT_UINT32_LE( ctx->state[1], output,  4 );
     PUT_UINT32_LE( ctx->state[1], output,  4 );
     PUT_UINT32_LE( ctx->state[2], output,  8 );
     PUT_UINT32_LE( ctx->state[2], output,  8 );
     PUT_UINT32_LE( ctx->state[3], output, 12 );
     PUT_UINT32_LE( ctx->state[3], output, 12 );
+
+    return( 0 );
+}
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+void mbedtls_md4_finish( mbedtls_md4_context *ctx,
+                         unsigned char output[16] )
+{
+    mbedtls_md4_finish_ret( ctx, output );
 }
 }
+#endif
 
 
 #endif /* !MBEDTLS_MD4_ALT */
 #endif /* !MBEDTLS_MD4_ALT */
 
 
 /*
 /*
  * output = MD4( input buffer )
  * output = MD4( input buffer )
  */
  */
-void mbedtls_md4( const unsigned char *input, size_t ilen, unsigned char output[16] )
+int mbedtls_md4_ret( const unsigned char *input,
+                     size_t ilen,
+                     unsigned char output[16] )
 {
 {
+    int ret;
     mbedtls_md4_context ctx;
     mbedtls_md4_context ctx;
 
 
     mbedtls_md4_init( &ctx );
     mbedtls_md4_init( &ctx );
-    mbedtls_md4_starts( &ctx );
-    mbedtls_md4_update( &ctx, input, ilen );
-    mbedtls_md4_finish( &ctx, output );
+
+    if( ( ret = mbedtls_md4_starts_ret( &ctx ) ) != 0 )
+        goto exit;
+
+    if( ( ret = mbedtls_md4_update_ret( &ctx, input, ilen ) ) != 0 )
+        goto exit;
+
+    if( ( ret = mbedtls_md4_finish_ret( &ctx, output ) ) != 0 )
+        goto exit;
+
+exit:
     mbedtls_md4_free( &ctx );
     mbedtls_md4_free( &ctx );
+
+    return( ret );
+}
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+void mbedtls_md4( const unsigned char *input,
+                  size_t ilen,
+                  unsigned char output[16] )
+{
+    mbedtls_md4_ret( input, ilen, output );
 }
 }
+#endif
 
 
 #if defined(MBEDTLS_SELF_TEST)
 #if defined(MBEDTLS_SELF_TEST)
 
 
 /*
 /*
  * RFC 1320 test vectors
  * RFC 1320 test vectors
  */
  */
-static const char md4_test_str[7][81] =
+static const unsigned char md4_test_str[7][81] =
 {
 {
     { "" },
     { "" },
     { "a" },
     { "a" },
@@ -323,10 +401,15 @@ static const char md4_test_str[7][81] =
     { "message digest" },
     { "message digest" },
     { "abcdefghijklmnopqrstuvwxyz" },
     { "abcdefghijklmnopqrstuvwxyz" },
     { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" },
     { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" },
-    { "12345678901234567890123456789012345678901234567890123456789012" \
+    { "12345678901234567890123456789012345678901234567890123456789012"
       "345678901234567890" }
       "345678901234567890" }
 };
 };
 
 
+static const size_t md4_test_strlen[7] =
+{
+    0, 1, 3, 14, 26, 62, 80
+};
+
 static const unsigned char md4_test_sum[7][16] =
 static const unsigned char md4_test_sum[7][16] =
 {
 {
     { 0x31, 0xD6, 0xCF, 0xE0, 0xD1, 0x6A, 0xE9, 0x31,
     { 0x31, 0xD6, 0xCF, 0xE0, 0xD1, 0x6A, 0xE9, 0x31,
@@ -350,7 +433,7 @@ static const unsigned char md4_test_sum[7][16] =
  */
  */
 int mbedtls_md4_self_test( int verbose )
 int mbedtls_md4_self_test( int verbose )
 {
 {
-    int i;
+    int i, ret = 0;
     unsigned char md4sum[16];
     unsigned char md4sum[16];
 
 
     for( i = 0; i < 7; i++ )
     for( i = 0; i < 7; i++ )
@@ -358,15 +441,14 @@ int mbedtls_md4_self_test( int verbose )
         if( verbose != 0 )
         if( verbose != 0 )
             mbedtls_printf( "  MD4 test #%d: ", i + 1 );
             mbedtls_printf( "  MD4 test #%d: ", i + 1 );
 
 
-        mbedtls_md4( (unsigned char *) md4_test_str[i],
-             strlen( md4_test_str[i] ), md4sum );
+        ret = mbedtls_md4_ret( md4_test_str[i], md4_test_strlen[i], md4sum );
+        if( ret != 0 )
+            goto fail;
 
 
         if( memcmp( md4sum, md4_test_sum[i], 16 ) != 0 )
         if( memcmp( md4sum, md4_test_sum[i], 16 ) != 0 )
         {
         {
-            if( verbose != 0 )
-                mbedtls_printf( "failed\n" );
-
-            return( 1 );
+            ret = 1;
+            goto fail;
         }
         }
 
 
         if( verbose != 0 )
         if( verbose != 0 )
@@ -377,6 +459,12 @@ int mbedtls_md4_self_test( int verbose )
         mbedtls_printf( "\n" );
         mbedtls_printf( "\n" );
 
 
     return( 0 );
     return( 0 );
+
+fail:
+    if( verbose != 0 )
+        mbedtls_printf( "failed\n" );
+
+    return( ret );
 }
 }
 
 
 #endif /* MBEDTLS_SELF_TEST */
 #endif /* MBEDTLS_SELF_TEST */

Algúns arquivos non se mostraron porque demasiados arquivos cambiaron neste cambio