Browse Source

Swap out the wolfssl SHA256 implementation with mbedtls. This also introduces a wrapper layer for pal crypto functions, which should make experimenting with different libraries easier.

Don Porter 6 years ago
parent
commit
fd73358f59
39 changed files with 3036 additions and 769 deletions
  1. 1 1
      LibOS/shim/test/regression/90_large-mmap.py
  2. 6 1
      Pal/lib/Makefile
  3. 51 0
      Pal/lib/crypto/adapters/mbedtls_adapter.c
  4. 41 0
      Pal/lib/crypto/adapters/wolfssl_adapter.c
  5. 17 2
      Pal/lib/crypto/aes.c
  6. 0 0
      Pal/lib/crypto/aes.h
  7. 0 0
      Pal/lib/crypto/aes_ni.S
  8. 0 2
      Pal/lib/crypto/cmac.c
  9. 0 0
      Pal/lib/crypto/cmac.h
  10. 0 0
      Pal/lib/crypto/dh.c
  11. 0 0
      Pal/lib/crypto/dh.h
  12. 0 0
      Pal/lib/crypto/error-crypt.h
  13. 0 0
      Pal/lib/crypto/integer.c
  14. 0 0
      Pal/lib/crypto/integer.h
  15. 2152 0
      Pal/lib/crypto/mbedtls/ChangeLog
  16. 2 0
      Pal/lib/crypto/mbedtls/LICENSE
  17. 23 0
      Pal/lib/crypto/mbedtls/mbedtls/config.h
  18. 141 0
      Pal/lib/crypto/mbedtls/mbedtls/sha256.h
  19. 458 0
      Pal/lib/crypto/mbedtls/sha256.c
  20. 7 2
      Pal/lib/crypto/rsa.c
  21. 0 0
      Pal/lib/crypto/rsa.h
  22. 0 0
      Pal/lib/crypto/udivmodti4.c
  23. 63 0
      Pal/lib/pal_crypto.h
  24. 2 3
      Pal/src/host/Linux-SGX/Makefile
  25. 2 2
      Pal/src/host/Linux-SGX/Makefile.am
  26. 0 238
      Pal/src/host/Linux-SGX/crypto/sha256.c
  27. 0 50
      Pal/src/host/Linux-SGX/crypto/sha256.h
  28. 0 326
      Pal/src/host/Linux-SGX/crypto/sha512.c
  29. 0 58
      Pal/src/host/Linux-SGX/crypto/sha512.h
  30. 3 3
      Pal/src/host/Linux-SGX/db_files.c
  31. 3 1
      Pal/src/host/Linux-SGX/db_main.c
  32. 1 2
      Pal/src/host/Linux-SGX/db_process.c
  33. 3 1
      Pal/src/host/Linux-SGX/db_threading.c
  34. 6 4
      Pal/src/host/Linux-SGX/enclave_ecalls.c
  35. 40 51
      Pal/src/host/Linux-SGX/enclave_framework.c
  36. 4 7
      Pal/src/host/Linux-SGX/pal_linux.h
  37. 1 1
      Pal/src/host/Linux-SGX/pal_linux_defs.h
  38. 1 1
      Pal/src/host/Linux-SGX/sgx_main.c
  39. 8 13
      Pal/src/host/Linux-SGX/signer/pal-sgx-sign

+ 1 - 1
LibOS/shim/test/regression/90_large-mmap.py

@@ -6,7 +6,7 @@ from regression import Regression
 loader = sys.argv[1]
 
 # Running Bootstrap
-regression = Regression(loader, "large-mmap", None, 30000)
+regression = Regression(loader, "large-mmap", None, 60000)
 
 regression.add_check(name="Ftruncate",
     check=lambda res: "large-mmap: ftruncate OK" in res[0].out)

+ 6 - 1
Pal/lib/Makefile

@@ -11,10 +11,15 @@ ARFLAGS	=
 include ../src/host/$(PAL_HOST)/Makefile.am
 
 CFLAGS += -I. -I../include -I../src
-subdirs = string stdlib network graphene
+subdirs = string stdlib network graphene util crypto crypto/mbedtls
 objs	= $(foreach dir,$(subdirs),$(patsubst %.c,%.o,$(wildcard $(dir)/*.c)))
 headers = asm-errlist.h api.h
 
+# Select which crypto adpater you want to use here. This has to match
+# the #define in pal_crypto.h.
+objs += crypto/adapters/mbedtls_adapter.o
+#objs += crypto/adapters/wolfssl_adapter.o
+
 all: $(target)graphene-lib.a
 
 ifeq ($(DEBUG),1)

+ 51 - 0
Pal/lib/crypto/adapters/mbedtls_adapter.c

@@ -0,0 +1,51 @@
+/* Copyright (C) 2017 Fortanix, Inc.
+
+   This file is part of Graphene Library OS.
+
+   Graphene Library OS is free software: you can redistribute it and/or
+   modify it under the terms of the GNU General Public License
+   as published by the Free Software Foundation, either version 3 of the
+   License, or (at your option) any later version.
+
+   Graphene Library OS is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <stdint.h>
+#include "pal.h"
+#include "pal_crypto.h"
+#include "crypto/mbedtls/mbedtls/sha256.h"
+
+int DkSHA256Init(PAL_SHA256_CONTEXT *context)
+{
+    mbedtls_sha256_init(context);
+    mbedtls_sha256_starts(context, 0 /* 0 = use SSH256 */);
+    return 0;
+}
+
+int DkSHA256Update(PAL_SHA256_CONTEXT *context, const uint8_t *data,
+                   PAL_NUM len)
+{
+    /* For compatibility with other SHA256 providers, don't support
+     * large lengths. */
+    if (len > UINT32_MAX) {
+        return -1;
+    }
+    mbedtls_sha256_update(context, data, len);
+    return 0;
+}
+
+int DkSHA256Final(PAL_SHA256_CONTEXT *context, uint8_t *output)
+{
+    mbedtls_sha256_finish(context, output);
+    /* This function is called free, but it doesn't actually free the memory.
+     * It zeroes out the context to avoid potentially leaking information
+     * about the hash that was just performed. */
+    mbedtls_sha256_free(context);
+    return 0;
+}
+

+ 41 - 0
Pal/lib/crypto/adapters/wolfssl_adapter.c

@@ -0,0 +1,41 @@
+/* Copyright (C) 2017 Fortanix, Inc.
+
+   This file is part of Graphene Library OS.
+
+   Graphene Library OS is free software: you can redistribute it and/or
+   modify it under the terms of the GNU General Public License
+   as published by the Free Software Foundation, either version 3 of the
+   License, or (at your option) any later version.
+
+   Graphene Library OS is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#include <stdint.h>
+#include "pal.h"
+#include "pal_crypto.h"
+#include "../sha256.h"
+
+int DkSHA256Init(PAL_SHA256_CONTEXT *context)
+{
+    return SHA256Init(context);
+}
+
+int DkSHA256Update(PAL_SHA256_CONTEXT *context, const uint8_t *data,
+                   PAL_NUM len)
+{
+    /* PAL_NUM is a 64-bit value, but SHA256Update takes a 32-bit len. */
+    if (len > UINT32_MAX) {
+        return -1;
+    }
+    return SHA256Update(context, data, len);
+}
+
+int DkSHA256Final(PAL_SHA256_CONTEXT *context, uint8_t *output)
+{
+    return SHA256Final(context, output);
+}

+ 17 - 2
Pal/src/host/Linux-SGX/crypto/aes.c → Pal/lib/crypto/aes.c

@@ -25,7 +25,6 @@
 #include "aes.h"
 #include "error-crypt.h"
 #include "api.h"
-#include "pal_linux_defs.h"
 
 #define XMEMSET memset
 #define XMEMCPY memcpy
@@ -866,7 +865,15 @@ void AESEncrypt(AES *aes, const byte *inBlock, byte *outBlock)
     if (r > 7 || r == 0)
         return;  /* stop instead of segfaulting, set up your keys! */
 
-   /*
+#if USE_AES_NI == 1
+    /* check alignment, decrypt doesn't need alignment */
+    if (!((uint64_t) inBlock % 16)) {
+        AES_ECB_encrypt(inBlock, outBlock, AES_BLOCK_SIZE, (byte*)aes->key,
+                        aes->rounds);
+        return;
+    }
+#endif
+    /*
       *map byte array block to cipher state
       *and add initial round key:
      */
@@ -998,6 +1005,14 @@ void AESDecrypt(AES *aes, const byte *inBlock, byte *outBlock)
     if (r > 7 || r == 0)
         return;  /* stop instead of segfaulting, set up your keys! */
 
+#if USE_AES_NI == 1
+    /* if input and output same will overwrite input iv */
+    XMEMCPY(aes->tmp, inBlock, AES_BLOCK_SIZE);
+    AES_ECB_decrypt(inBlock, outBlock, AES_BLOCK_SIZE, (byte*)aes->key,
+                    aes->rounds);
+    return;
+#endif
+
     /*
       *map byte array block to cipher state
       *and add initial round key:

+ 0 - 0
Pal/src/host/Linux-SGX/crypto/aes.h → Pal/lib/crypto/aes.h


+ 0 - 0
Pal/src/host/Linux-SGX/crypto/aes_ni.S → Pal/lib/crypto/aes_ni.S


+ 0 - 2
Pal/src/host/Linux-SGX/crypto/cmac.c → Pal/lib/crypto/cmac.c

@@ -110,8 +110,6 @@ void padding (unsigned char *lastb, unsigned char *pad, int length)
     }
 }
 
-#include "pal_linux.h"
-#include "pal_internal.h"
 #include "api.h"
 
 void AES_CMAC (unsigned char *key, unsigned char *input, int length,

+ 0 - 0
Pal/src/host/Linux-SGX/crypto/cmac.h → Pal/lib/crypto/cmac.h


+ 0 - 0
Pal/src/host/Linux-SGX/crypto/dh.c → Pal/lib/crypto/dh.c


+ 0 - 0
Pal/src/host/Linux-SGX/crypto/dh.h → Pal/lib/crypto/dh.h


+ 0 - 0
Pal/src/host/Linux-SGX/crypto/error-crypt.h → Pal/lib/crypto/error-crypt.h


+ 0 - 0
Pal/src/host/Linux-SGX/crypto/integer.c → Pal/lib/crypto/integer.c


+ 0 - 0
Pal/src/host/Linux-SGX/crypto/integer.h → Pal/lib/crypto/integer.h


+ 2152 - 0
Pal/lib/crypto/mbedtls/ChangeLog

@@ -0,0 +1,2152 @@
+mbed TLS ChangeLog (Sorted per branch, date)
+
+= mbed TLS 2.4.2 branch released 2017-03-08
+
+Security
+   * Add checks to prevent signature forgeries for very large messages while
+     using RSA through the PK module in 64-bit systems. The issue was caused by
+     some data loss when casting a size_t to an unsigned int value in the
+     functions rsa_verify_wrap(), rsa_sign_wrap(), rsa_alt_sign_wrap() and
+     mbedtls_pk_sign(). Found by Jean-Philippe Aumasson.
+   * Fixed potential livelock during the parsing of a CRL in PEM format in
+     mbedtls_x509_crl_parse(). A string containing a CRL followed by trailing
+     characters after the footer could result in the execution of an infinite
+     loop. The issue can be triggered remotely. Found by Greg Zaverucha,
+     Microsoft.
+   * Removed MD5 from the allowed hash algorithms for CertificateRequest and
+     CertificateVerify messages, to prevent SLOTH attacks against TLS 1.2.
+     Introduced by interoperability fix for #513.
+   * Fixed a bug that caused freeing a buffer that was allocated on the stack,
+     when verifying the validity of a key on secp224k1. This could be
+     triggered remotely for example with a maliciously constructed certificate
+     and potentially could lead to remote code execution on some platforms.
+     Reported independently by rongsaws and Aleksandar Nikolic, Cisco Talos
+     team. #569 CVE-2017-2784
+
+Bugfix
+   * Fix output certificate verification flags set by x509_crt_verify_top() when
+     traversing a chain of trusted CA. The issue would cause both flags,
+     MBEDTLS_X509_BADCERT_NOT_TRUSTED and MBEDTLS_X509_BADCERT_EXPIRED, to be
+     set when the verification conditions are not met regardless of the cause.
+     Found by Harm Verhagen and inestlerode. #665 #561
+   * Fix the redefinition of macro ssl_set_bio to an undefined symbol
+     mbedtls_ssl_set_bio_timeout in compat-1.3.h, by removing it.
+     Found by omlib-lin. #673
+   * Fix unused variable/function compilation warnings in pem.c, x509_crt.c and
+     x509_csr.c that are reported when building mbed TLS with a config.h that
+     does not define MBEDTLS_PEM_PARSE_C. Found by omnium21. #562
+   * Fix incorrect renegotiation condition in ssl_check_ctr_renegotiate() that
+     would compare 64 bits of the record counter instead of 48 bits as indicated
+     in RFC 6347 Section 4.3.1. This could cause the execution of the
+     renegotiation routines at unexpected times when the protocol is DTLS. Found
+     by wariua. #687
+   * Fixed multiple buffer overreads in mbedtls_pem_read_buffer() when parsing
+     the input string in PEM format to extract the different components. Found
+     by Eyal Itkin.
+   * Fixed potential arithmetic overflow in mbedtls_ctr_drbg_reseed() that could
+     cause buffer bound checks to be bypassed. Found by Eyal Itkin.
+   * Fixed potential arithmetic overflows in mbedtls_cipher_update() that could
+     cause buffer bound checks to be bypassed. Found by Eyal Itkin.
+   * Fixed potential arithmetic overflow in mbedtls_md2_update() that could
+     cause buffer bound checks to be bypassed. Found by Eyal Itkin.
+   * Fixed potential arithmetic overflow in mbedtls_base64_decode() that could
+     cause buffer bound checks to be bypassed. Found by Eyal Itkin.
+   * Fixed heap overreads in mbedtls_x509_get_time(). Found by Peng
+     Li/Yueh-Hsun Lin, KNOX Security, Samsung Research America.
+   * Fix potential memory leak in mbedtls_x509_crl_parse(). The leak was caused
+     by missing calls to mbedtls_pem_free() in cases when a
+     MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT error was encountered. Found and
+     fix proposed by Guido Vranken. #722
+   * Fixed the templates used to generate project and solution files for Visual
+     Studio 2015 as well as the files themselves, to remove a build warning
+     generated in Visual Studio 2015. Reported by Steve Valliere. #742
+   * Fix a resource leak in ssl_cookie, when using MBEDTLS_THREADING_C.
+     Raised and fix suggested by Alan Gillingham in the mbed TLS forum. #771
+   * Fix 1 byte buffer overflow in mbedtls_mpi_write_string() when the MPI
+     number to write in hexadecimal is negative and requires an odd number of
+     digits. Found and fixed by Guido Vranken.
+   * Fix unlisted DES configuration dependency in some pkparse test cases. Found
+     by inestlerode. #555
+
+= mbed TLS 2.4.1 branch released 2016-12-13
+
+Changes
+   * Update to CMAC test data, taken from - NIST Special Publication 800-38B -
+     Recommendation for Block Cipher Modes of Operation: The CMAC Mode for
+     Authentication – October  2016
+
+= mbed TLS 2.4.0 branch released 2016-10-17
+
+Security
+   * Removed the MBEDTLS_SSL_AEAD_RANDOM_IV option, because it was not compliant
+     with RFC-5116 and could lead to session key recovery in very long TLS
+     sessions. "Nonce-Disrespecting Adversaries Practical Forgery Attacks on GCM in
+     TLS" - H. Bock, A. Zauner, S. Devlin, J. Somorovsky, P. Jovanovic.
+     https://eprint.iacr.org/2016/475.pdf
+   * Fixed potential stack corruption in mbedtls_x509write_crt_der() and
+     mbedtls_x509write_csr_der() when the signature is copied to the buffer
+     without checking whether there is enough space in the destination. The
+     issue cannot be triggered remotely. Found by Jethro Beekman.
+
+Features
+   * Added support for CMAC for AES and 3DES and AES-CMAC-PRF-128, as defined by
+     NIST SP 800-38B, RFC-4493 and RFC-4615.
+   * Added hardware entropy selftest to verify that the hardware entropy source
+     is functioning correctly.
+   * Added a script to print build environment info for diagnostic use in test
+     scripts, which is also now called by all.sh.
+   * Added the macro MBEDTLS_X509_MAX_FILE_PATH_LEN that enables the user to
+     configure the maximum length of a file path that can be buffered when
+     calling mbedtls_x509_crt_parse_path().
+   * Added a configuration file config-no-entropy.h that configures the subset of
+     library features that do not require an entropy source.
+   * Added the macro MBEDTLS_ENTROPY_MIN_HARDWARE in config.h. This allows users
+     to configure the minimum number of bytes for entropy sources using the
+     mbedtls_hardware_poll() function.
+
+Bugfix
+   * Fix for platform time abstraction to avoid dependency issues where a build
+     may need time but not the standard C library abstraction, and added
+     configuration consistency checks to check_config.h
+   * Fix dependency issue in Makefile to allow parallel builds.
+   * Fix incorrect handling of block lengths in crypt_and_hash.c sample program,
+     when GCM is used. Found by udf2457. #441
+   * Fix for key exchanges based on ECDH-RSA or ECDH-ECDSA which weren't
+     enabled unless others were also present. Found by David Fernandez. #428
+   * Fix for out-of-tree builds using CMake. Found by jwurzer, and fix based on
+     a contribution from Tobias Tangemann. #541
+   * Fixed cert_app.c sample program for debug output and for use when no root
+     certificates are provided.
+   * Fix conditional statement that would cause a 1 byte overread in
+     mbedtls_asn1_get_int(). Found and fixed by Guido Vranken. #599
+   * Fixed pthread implementation to avoid unintended double initialisations
+     and double frees. Found by Niklas Amnebratt.
+   * Fixed the sample applications gen_key.c, cert_req.c and cert_write.c for
+     builds where the configuration MBEDTLS_PEM_WRITE_C is not defined. Found
+     by inestlerode. #559.
+   * Fix mbedtls_x509_get_sig() to update the ASN1 type in the mbedtls_x509_buf
+     data structure until after error checks are successful. Found by
+     subramanyam-c. #622
+   * Fix documentation and implementation missmatch for function arguments of
+     mbedtls_gcm_finish(). Found by cmiatpaar. #602
+   * Guarantee that P>Q at RSA key generation. Found by inestlerode. #558
+   * Fix potential byte overread when verifying malformed SERVER_HELLO in
+     ssl_parse_hello_verify_request() for DTLS. Found by Guido Vranken.
+   * Fix check for validity of date when parsing in mbedtls_x509_get_time().
+     Found by subramanyam-c. #626
+   * Fix compatibility issue with Internet Explorer client authentication,
+     where the limited hash choices prevented the client from sending its
+     certificate. Found by teumas. #513
+   * Fix compilation without MBEDTLS_SELF_TEST enabled.
+
+Changes
+   * Extended test coverage of special cases, and added new timing test suite.
+   * Removed self-tests from the basic-built-test.sh script, and added all
+     missing self-tests to the test suites, to ensure self-tests are only
+     executed once.
+   * Added support for 3 and 4 byte lengths to mbedtls_asn1_write_len().
+   * Added support for a Yotta specific configuration file -
+     through the symbol YOTTA_CFG_MBEDTLS_TARGET_CONFIG_FILE.
+   * Added optimization for code space for X.509/OID based on configured
+     features. Contributed by Aviv Palivoda.
+   * Renamed source file library/net.c to library/net_sockets.c to avoid
+     naming collision in projects which also have files with the common name
+     net.c. For consistency, the corresponding header file, net.h, is marked as
+     deprecated, and its contents moved to net_sockets.h.
+   * Changed the strategy for X.509 certificate parsing and validation, to no
+     longer disregard certificates with unrecognised fields.
+
+= mbed TLS 2.3.0 branch released 2016-06-28
+
+Security
+   * Fix missing padding length check in mbedtls_rsa_rsaes_pkcs1_v15_decrypt
+     required by PKCS1 v2.2
+   * Fix potential integer overflow to buffer overflow in
+     mbedtls_rsa_rsaes_pkcs1_v15_encrypt and mbedtls_rsa_rsaes_oaep_encrypt
+     (not triggerable remotely in (D)TLS).
+   * Fix a potential integer underflow to buffer overread in 
+     mbedtls_rsa_rsaes_oaep_decrypt. It is not triggerable remotely in
+     SSL/TLS.
+
+Features
+   * Support for platform abstraction of the standard C library time()
+     function.
+
+Bugfix
+   * Fix bug in mbedtls_mpi_add_mpi() that caused wrong results when the three
+     arguments where the same (in-place doubling). Found and fixed by Janos
+     Follath. #309
+   * Fix potential build failures related to the 'apidoc' target, introduced
+     in the previous patch release. Found by Robert Scheck. #390 #391
+   * Fix issue in Makefile that prevented building using armar. #386
+   * Fix memory leak that occured only when ECJPAKE was enabled and ECDHE and
+     ECDSA was disabled in config.h . The leak didn't occur by default.
+   * Fix an issue that caused valid certificates to be rejected whenever an
+     expired or not yet valid certificate was parsed before a valid certificate
+     in the trusted certificate list.
+   * Fix bug in mbedtls_x509_crt_parse that caused trailing extra data in the 
+     buffer after DER certificates to be included in the raw representation.
+   * Fix issue that caused a hang when generating RSA keys of odd bitlength
+   * Fix bug in mbedtls_rsa_rsaes_pkcs1_v15_encrypt that made null pointer
+     dereference possible.
+   * Fix issue that caused a crash if invalid curves were passed to
+     mbedtls_ssl_conf_curves. #373
+   * Fix issue in ssl_fork_server which was preventing it from functioning. #429
+   * Fix memory leaks in test framework
+   * Fix test in ssl-opt.sh that does not run properly with valgrind
+   * Fix unchecked calls to mmbedtls_md_setup(). Fix by Brian Murray. #502
+
+Changes
+   * On ARM platforms, when compiling with -O0 with GCC, Clang or armcc5,
+     don't use the optimized assembly for bignum multiplication. This removes
+     the need to pass -fomit-frame-pointer to avoid a build error with -O0.
+   * Disabled SSLv3 in the default configuration.
+   * Optimized mbedtls_mpi_zeroize() for MPI integer size. (Fix by Alexey
+     Skalozub).
+   * Fix non-compliance server extension handling. Extensions for SSLv3 are now
+     ignored, as required by RFC6101.
+
+= mbed TLS 2.2.1 released 2016-01-05
+
+Security
+   * Fix potential double free when mbedtls_asn1_store_named_data() fails to
+     allocate memory. Only used for certificate generation, not triggerable
+     remotely in SSL/TLS. Found by Rafał Przywara. #367
+   * Disable MD5 handshake signatures in TLS 1.2 by default to prevent the
+     SLOTH attack on TLS 1.2 server authentication (other attacks from the
+     SLOTH paper do not apply to any version of mbed TLS or PolarSSL).
+     https://www.mitls.org/pages/attacks/SLOTH
+
+Bugfix
+   * Fix over-restrictive length limit in GCM. Found by Andreas-N. #362
+   * Fix bug in certificate validation that caused valid chains to be rejected
+     when the first intermediate certificate has pathLenConstraint=0. Found by
+     Nicholas Wilson. Introduced in mbed TLS 2.2.0. #280
+   * Removed potential leak in mbedtls_rsa_rsassa_pkcs1_v15_sign(), found by
+     JayaraghavendranK. #372
+   * Fix suboptimal handling of unexpected records that caused interop issues
+     with some peers over unreliable links. Avoid dropping an entire DTLS
+     datagram if a single record in a datagram is unexpected, instead only
+     drop the record and look at subsequent records (if any are present) in
+     the same datagram. Found by jeannotlapin. #345
+
+= mbed TLS 2.2.0 released 2015-11-04
+
+Security
+   * Fix potential double free if mbedtls_ssl_conf_psk() is called more than
+     once and some allocation fails. Cannot be forced remotely. Found by Guido
+     Vranken, Intelworks.
+   * Fix potential heap corruption on Windows when
+     mbedtls_x509_crt_parse_path() is passed a path longer than 2GB. Cannot be
+     triggered remotely. Found by Guido Vranken, Intelworks.
+   * Fix potential buffer overflow in some asn1_write_xxx() functions.
+     Cannot be triggered remotely unless you create X.509 certificates based
+     on untrusted input or write keys of untrusted origin. Found by Guido
+     Vranken, Intelworks.
+   * The X509 max_pathlen constraint was not enforced on intermediate
+     certificates. Found by Nicholas Wilson, fix and tests provided by
+     Janos Follath. #280 and #319
+
+Features
+   * Experimental support for EC J-PAKE as defined in Thread 1.0.0.
+     Disabled by default as the specification might still change.
+   * Added a key extraction callback to accees the master secret and key
+     block. (Potential uses include EAP-TLS and Thread.)
+
+Bugfix
+   * Self-signed certificates were not excluded from pathlen counting,
+     resulting in some valid X.509 being incorrectly rejected. Found and fix
+     provided by Janos Follath. #319
+   * Fix build error with configurations where ECDHE-PSK is the only key
+     exchange. Found and fix provided by Chris Hammond. #270
+   * Fix build error with configurations where RSA, RSA-PSK, ECDH-RSA or
+     ECHD-ECDSA if the only key exchange. Multiple reports. #310
+   * Fixed a bug causing some handshakes to fail due to some non-fatal alerts
+     not being properly ignored. Found by mancha and Kasom Koht-arsa, #308
+   * mbedtls_x509_crt_verify(_with_profile)() now also checks the key type and
+     size/curve against the profile. Before that, there was no way to set a
+     minimum key size for end-entity certificates with RSA keys. Found by
+     Matthew Page of Scannex Electronics Ltd.
+   * Fix failures in MPI on Sparc(64) due to use of bad assembly code.
+     Found by Kurt Danielson. #292
+   * Fix typo in name of the extKeyUsage OID. Found by inestlerode, #314
+   * Fix bug in ASN.1 encoding of booleans that caused generated CA
+     certificates to be rejected by some applications, including OS X
+     Keychain. Found and fixed by Jonathan Leroy, Inikup.
+
+Changes
+   * Improved performance of mbedtls_ecp_muladd() when one of the scalars is 1
+     or -1.
+
+= mbed TLS 2.1.2 released 2015-10-06
+
+Security
+   * Added fix for CVE-2015-5291 to prevent heap corruption due to buffer
+     overflow of the hostname or session ticket. Found by Guido Vranken,
+     Intelworks.
+   * Fix potential double-free if mbedtls_ssl_set_hs_psk() is called more than
+     once in the same handhake and mbedtls_ssl_conf_psk() was used.
+     Found and patch provided by Guido Vranken, Intelworks. Cannot be forced
+     remotely.
+   * Fix stack buffer overflow in pkcs12 decryption (used by
+     mbedtls_pk_parse_key(file)() when the password is > 129 bytes.
+     Found by Guido Vranken, Intelworks. Not triggerable remotely.
+   * Fix potential buffer overflow in mbedtls_mpi_read_string().
+     Found by Guido Vranken, Intelworks. Not exploitable remotely in the context
+     of TLS, but might be in other uses. On 32 bit machines, requires reading a
+     string of close to or larger than 1GB to exploit; on 64 bit machines, would
+     require reading a string of close to or larger than 2^62 bytes.
+   * Fix potential random memory allocation in mbedtls_pem_read_buffer()
+     on crafted PEM input data. Found and fix provided by Guido Vranken,
+     Intelworks. Not triggerable remotely in TLS. Triggerable remotely if you
+     accept PEM data from an untrusted source.
+   * Fix possible heap buffer overflow in base64_encoded() when the input
+     buffer is 512MB or larger on 32-bit platforms. Found by Guido Vranken,
+     Intelworks. Not trigerrable remotely in TLS.
+   * Fix potential double-free if mbedtls_conf_psk() is called repeatedly on
+     the same mbedtls_ssl_config object and memory allocation fails. Found by
+     Guido Vranken, Intelworks. Cannot be forced remotely.
+   * Fix potential heap buffer overflow in servers that perform client
+     authentication against a crafted CA cert. Cannot be triggered remotely
+     unless you allow third parties to pick trust CAs for client auth.
+     Found by Guido Vranken, Intelworks.
+
+Bugfix
+   * Fix compile error in net.c with musl libc. Found and patch provided by
+     zhasha (#278).
+   * Fix macroization of 'inline' keyword when building as C++. (#279)
+
+Changes
+   * Added checking of hostname length in mbedtls_ssl_set_hostname() to ensure
+     domain names are compliant with RFC 1035.
+   * Fixed paths for check_config.h in example config files. (Found by bachp)
+     (#291)
+
+= mbed TLS 2.1.1 released 2015-09-17
+
+Security
+   * Add countermeasure against Lenstra's RSA-CRT attack for PKCS#1 v1.5
+     signatures. (Found by Florian Weimer, Red Hat.)
+     https://securityblog.redhat.com/2015/09/02/factoring-rsa-keys-with-tls-perfect-forward-secrecy/
+   * Fix possible client-side NULL pointer dereference (read) when the client
+     tries to continue the handshake after it failed (a misuse of the API).
+     (Found and patch provided by Fabian Foerg, Gotham Digital Science using
+     afl-fuzz.)
+
+Bugfix
+   * Fix warning when using a 64bit platform. (found by embedthis) (#275)
+   * Fix off-by-one error in parsing Supported Point Format extension that
+     caused some handshakes to fail.
+
+Changes
+   * Made X509 profile pointer const in mbedtls_ssl_conf_cert_profile() to allow
+     use of mbedtls_x509_crt_profile_next. (found by NWilson)
+   * When a client initiates a reconnect from the same port as a live
+     connection, if cookie verification is available
+     (MBEDTLS_SSL_DTLS_HELLO_VERIFY defined in config.h, and usable cookie
+     callbacks set with mbedtls_ssl_conf_dtls_cookies()), this will be
+     detected and mbedtls_ssl_read() will return
+     MBEDTLS_ERR_SSL_CLIENT_RECONNECT - it is then possible to start a new
+     handshake with the same context. (See RFC 6347 section 4.2.8.)
+
+= mbed TLS 2.1.0 released 2015-09-04
+
+Features
+   * Added support for yotta as a build system.
+   * Primary open source license changed to Apache 2.0 license.
+
+Bugfix
+   * Fix segfault in the benchmark program when benchmarking DHM.
+   * Fix build error with CMake and pre-4.5 versions of GCC (found by Hugo
+     Leisink).
+   * Fix bug when parsing a ServerHello without extensions (found by David
+     Sears).
+   * Fix bug in CMake lists that caused libmbedcrypto.a not to be installed
+     (found by Benoit Lecocq).
+   * Fix bug in Makefile that caused libmbedcrypto and libmbedx509 not to be
+     installed (found by Rawi666).
+   * Fix compile error with armcc 5 with --gnu option.
+   * Fix bug in Makefile that caused programs not to be installed correctly
+     (found by robotanarchy) (#232).
+   * Fix bug in Makefile that prevented from installing without building the
+     tests (found by robotanarchy) (#232).
+   * Fix missing -static-libgcc when building shared libraries for Windows
+     with make.
+   * Fix link error when building shared libraries for Windows with make.
+   * Fix error when loading libmbedtls.so.
+   * Fix bug in mbedtls_ssl_conf_default() that caused the default preset to
+     be always used (found by dcb314) (#235)
+   * Fix bug in mbedtls_rsa_public() and mbedtls_rsa_private() that could
+     result trying to unlock an unlocked mutex on invalid input (found by
+     Fredrik Axelsson) (#257)
+   * Fix -Wshadow warnings (found by hnrkp) (#240)
+   * Fix memory corruption on client with overlong PSK identity, around
+     SSL_MAX_CONTENT_LEN or higher - not triggerrable remotely (found by
+     Aleksandrs Saveljevs) (#238)
+   * Fix unused function warning when using MBEDTLS_MDx_ALT or
+     MBEDTLS_SHAxxx_ALT (found by Henrik) (#239)
+   * Fix memory corruption in pkey programs (found by yankuncheng) (#210)
+
+Changes
+   * The PEM parser now accepts a trailing space at end of lines (#226).
+   * It is now possible to #include a user-provided configuration file at the
+     end of the default config.h by defining MBEDTLS_USER_CONFIG_FILE on the
+     compiler's command line.
+   * When verifying a certificate chain, if an intermediate certificate is
+     trusted, no later cert is checked. (suggested by hannes-landeholm)
+     (#220).
+   * Prepend a "thread identifier" to debug messages (issue pointed out by
+     Hugo Leisink) (#210).
+   * Add mbedtls_ssl_get_max_frag_len() to query the current maximum fragment
+     length.
+
+= mbed TLS 2.0.0 released 2015-07-13
+
+Features
+   * Support for DTLS 1.0 and 1.2 (RFC 6347).
+   * Ability to override core functions from MDx, SHAx, AES and DES modules
+     with custom implementation (eg hardware accelerated), complementing the
+     ability to override the whole module.
+   * New server-side implementation of session tickets that rotate keys to
+     preserve forward secrecy, and allows sharing across multiple contexts.
+   * Added a concept of X.509 cerificate verification profile that controls
+     which algorithms and key sizes (curves for ECDSA) are acceptable.
+   * Expanded configurability of security parameters in the SSL module with
+     mbedtls_ssl_conf_dhm_min_bitlen() and mbedtls_ssl_conf_sig_hashes().
+   * Introduced a concept of presets for SSL security-relevant configuration
+     parameters.
+
+API Changes
+   * The library has been split into libmbedcrypto, libmbedx509, libmbedtls.
+     You now need to link to all of them if you use TLS for example.
+   * All public identifiers moved to the mbedtls_* or MBEDTLS_* namespace.
+     Some names have been further changed to make them more consistent.
+     Migration helpers scripts/rename.pl and include/mbedlts/compat-1.3.h are
+     provided. Full list of renamings in scripts/data_files/rename-1.3-2.0.txt
+   * Renamings of fields inside structures, not covered by the previous list:
+     mbedtls_cipher_info_t.key_length -> key_bitlen
+     mbedtls_cipher_context_t.key_length -> key_bitlen
+     mbedtls_ecp_curve_info.size -> bit_size
+   * Headers are now found in the 'mbedtls' directory (previously 'polarssl').
+   * The following _init() functions that could return errors have
+     been split into an _init() that returns void and another function that
+     should generally be the first function called on this context after init:
+     mbedtls_ssl_init() -> mbedtls_ssl_setup()
+     mbedtls_ccm_init() -> mbedtls_ccm_setkey()
+     mbedtls_gcm_init() -> mbedtls_gcm_setkey()
+     mbedtls_hmac_drbg_init() -> mbedtls_hmac_drbg_seed(_buf)()
+     mbedtls_ctr_drbg_init()  -> mbedtls_ctr_drbg_seed()
+     Note that for mbedtls_ssl_setup(), you need to be done setting up the
+     ssl_config structure before calling it.
+   * Most ssl_set_xxx() functions (all except ssl_set_bio(), ssl_set_hostname(),
+     ssl_set_session() and ssl_set_client_transport_id(), plus
+     ssl_legacy_renegotiation()) have been renamed to mbedtls_ssl_conf_xxx()
+     (see rename.pl and compat-1.3.h above) and their first argument's type
+     changed from ssl_context to ssl_config.
+   * ssl_set_bio() changed signature (contexts merged, order switched, one
+     additional callback for read-with-timeout).
+   * The following functions have been introduced and must be used in callback
+     implementations (SNI, PSK) instead of their *conf counterparts:
+     mbedtls_ssl_set_hs_own_cert()
+     mbedtls_ssl_set_hs_ca_chain()
+     mbedtls_ssl_set_hs_psk()
+   * mbedtls_ssl_conf_ca_chain() lost its last argument (peer_cn), now set
+     using mbedtls_ssl_set_hostname().
+   * mbedtls_ssl_conf_session_cache() changed prototype (only one context
+     pointer, parameters reordered).
+   * On server, mbedtls_ssl_conf_session_tickets_cb() must now be used in
+     place of mbedtls_ssl_conf_session_tickets() to enable session tickets.
+   * The SSL debug callback gained two new arguments (file name, line number).
+   * Debug modes were removed.
+   * mbedtls_ssl_conf_truncated_hmac() now returns void.
+   * mbedtls_memory_buffer_alloc_init() now returns void.
+   * X.509 verification flags are now an uint32_t. Affect the signature of:
+     mbedtls_ssl_get_verify_result()
+     mbedtls_x509_ctr_verify_info()
+     mbedtls_x509_crt_verify() (flags, f_vrfy -> needs to be updated)
+     mbedtls_ssl_conf_verify() (f_vrfy -> needs to be updated)
+   * The following functions changed prototype to avoid an in-out length
+     parameter:
+     mbedtls_base64_encode()
+     mbedtls_base64_decode()
+     mbedtls_mpi_write_string()
+     mbedtls_dhm_calc_secret()
+   * In the NET module, all "int" and "int *" arguments for file descriptors
+     changed type to "mbedtls_net_context *".
+   * net_accept() gained new arguments for the size of the client_ip buffer.
+   * In the threading layer, mbedtls_mutex_init() and mbedtls_mutex_free() now
+     return void.
+   * ecdsa_write_signature() gained an addtional md_alg argument and
+     ecdsa_write_signature_det() was deprecated.
+   * pk_sign() no longer accepts md_alg == POLARSSL_MD_NONE with ECDSA.
+   * Last argument of x509_crt_check_key_usage() and
+     mbedtls_x509write_crt_set_key_usage() changed from int to unsigned.
+   * test_ca_list (from certs.h) is renamed to test_cas_pem and is only
+     available if POLARSSL_PEM_PARSE_C is defined (it never worked without).
+   * Test certificates in certs.c are no longer guaranteed to be nul-terminated
+     strings; use the new *_len variables instead of strlen().
+   * Functions mbedtls_x509_xxx_parse(), mbedtls_pk_parse_key(),
+     mbedtls_pk_parse_public_key() and mbedtls_dhm_parse_dhm() now expect the
+     length parameter to include the terminating null byte for PEM input.
+   * Signature of mpi_mul_mpi() changed to make the last argument unsigned
+   * calloc() is now used instead of malloc() everywhere. API of platform
+     layer and the memory_buffer_alloc module changed accordingly.
+     (Thanks to Mansour Moufid for helping with the replacement.)
+   * Change SSL_DISABLE_RENEGOTIATION config.h flag to SSL_RENEGOTIATION
+     (support for renegotiation now needs explicit enabling in config.h).
+   * Split MBEDTLS_HAVE_TIME into MBEDTLS_HAVE_TIME and MBEDTLS_HAVE_TIME_DATE
+     in config.h
+   * net_connect() and net_bind() have a new 'proto' argument to choose
+     between TCP and UDP, using the macros NET_PROTO_TCP or NET_PROTO_UDP.
+     Their 'port' argument type is changed to a string.
+   * Some constness fixes
+
+Removals
+   * Removed mbedtls_ecp_group_read_string(). Only named groups are supported.
+   * Removed mbedtls_ecp_sub() and mbedtls_ecp_add(), use
+     mbedtls_ecp_muladd().
+   * Removed individual mdX_hmac, shaX_hmac, mdX_file and shaX_file functions
+     (use generic functions from md.h)
+   * Removed mbedtls_timing_msleep(). Use mbedtls_net_usleep() or a custom
+     waiting function.
+   * Removed test DHM parameters from the test certs module.
+   * Removed the PBKDF2 module (use PKCS5).
+   * Removed POLARSSL_ERROR_STRERROR_BC (use mbedtls_strerror()).
+   * Removed compat-1.2.h (helper for migrating from 1.2 to 1.3).
+   * Removed openssl.h (very partial OpenSSL compatibility layer).
+   * Configuration options POLARSSL_HAVE_LONGLONG was removed (now always on).
+   * Configuration options POLARSSL_HAVE_INT8 and POLARSSL_HAVE_INT16 have
+     been removed (compiler is required to support 32-bit operations).
+   * Configuration option POLARSSL_HAVE_IPV6 was removed (always enabled).
+   * Removed test program o_p_test, the script compat.sh does more.
+   * Removed test program ssl_test, superseded by ssl-opt.sh.
+   * Removed helper script active-config.pl
+
+New deprecations
+   * md_init_ctx() is deprecated in favour of md_setup(), that adds a third
+     argument (allowing memory savings if HMAC is not used)
+
+Semi-API changes (technically public, morally private)
+   * Renamed a few headers to include _internal in the name. Those headers are
+     not supposed to be included by users.
+   * Changed md_info_t into an opaque structure (use md_get_xxx() accessors).
+   * Changed pk_info_t into an opaque structure.
+   * Changed cipher_base_t into an opaque structure.
+   * Removed sig_oid2 and rename sig_oid1 to sig_oid in x509_crt and x509_crl.
+   * x509_crt.key_usage changed from unsigned char to unsigned int.
+   * Removed r and s from ecdsa_context
+   * Removed mode from des_context and des3_context
+
+Default behavior changes
+   * The default minimum TLS version is now TLS 1.0.
+   * RC4 is now blacklisted by default in the SSL/TLS layer, and excluded from the
+     default ciphersuite list returned by ssl_list_ciphersuites()
+   * Support for receiving SSLv2 ClientHello is now disabled by default at
+     compile time.
+   * The default authmode for SSL/TLS clients is now REQUIRED.
+   * Support for RSA_ALT contexts in the PK layer is now optional. Since is is
+     enabled in the default configuration, this is only noticeable if using a
+     custom config.h
+   * Default DHM parameters server-side upgraded from 1024 to 2048 bits.
+   * A minimum RSA key size of 2048 bits is now enforced during ceritificate
+     chain verification.
+   * Negotiation of truncated HMAC is now disabled by default on server too.
+   * The following functions are now case-sensitive:
+     mbedtls_cipher_info_from_string()
+     mbedtls_ecp_curve_info_from_name()
+     mbedtls_md_info_from_string()
+     mbedtls_ssl_ciphersuite_from_string()
+     mbedtls_version_check_feature()
+
+Requirement changes
+   * The minimum MSVC version required is now 2010 (better C99 support).
+   * The NET layer now unconditionnaly relies on getaddrinfo() and select().
+   * Compiler is required to support C99 types such as long long and uint32_t.
+
+API changes from the 1.4 preview branch
+   * ssl_set_bio_timeout() was removed, split into mbedtls_ssl_set_bio() with
+     new prototype, and mbedtls_ssl_set_read_timeout().
+   * The following functions now return void:
+     mbedtls_ssl_conf_transport()
+     mbedtls_ssl_conf_max_version()
+     mbedtls_ssl_conf_min_version()
+   * DTLS no longer hard-depends on TIMING_C, but uses a callback interface
+     instead, see mbedtls_ssl_set_timer_cb(), with the Timing module providing
+     an example implementation, see mbedtls_timing_delay_context and
+     mbedtls_timing_set/get_delay().
+   * With UDP sockets, it is no longer necessary to call net_bind() again
+     after a successful net_accept().
+
+Changes
+   * mbedtls_ctr_drbg_random() and mbedtls_hmac_drbg_random() are now
+     thread-safe if MBEDTLS_THREADING_C is enabled.
+   * Reduced ROM fooprint of SHA-256 and added an option to reduce it even
+     more (at the expense of performance) MBEDTLS_SHA256_SMALLER.
+
+= mbed TLS 1.3 branch
+
+Security
+   * With authmode set to SSL_VERIFY_OPTIONAL, verification of keyUsage and
+     extendedKeyUsage on the leaf certificate was lost (results not accessible
+     via ssl_get_verify_results()).
+   * Add countermeasure against "Lucky 13 strikes back" cache-based attack,
+     https://dl.acm.org/citation.cfm?id=2714625
+
+Features
+   * Improve ECC performance by using more efficient doubling formulas
+     (contributed by Peter Dettman).
+   * Add x509_crt_verify_info() to display certificate verification results.
+   * Add support for reading DH parameters with privateValueLength included
+     (contributed by Daniel Kahn Gillmor).
+   * Add support for bit strings in X.509 names (request by Fredrik Axelsson).
+   * Add support for id-at-uniqueIdentifier in X.509 names.
+   * Add support for overriding snprintf() (except on Windows) and exit() in
+     the platform layer.
+   * Add an option to use macros instead of function pointers in the platform
+     layer (helps get rid of unwanted references).
+   * Improved Makefiles for Windows targets by fixing library targets and making
+     cross-compilation easier (thanks to Alon Bar-Lev).
+   * The benchmark program also prints heap usage for public-key primitives
+     if POLARSSL_MEMORY_BUFFER_ALLOC_C and POLARSSL_MEMORY_DEBUG are defined.
+   * New script ecc-heap.sh helps measuring the impact of ECC parameters on
+     speed and RAM (heap only for now) usage.
+   * New script memory.sh helps measuring the ROM and RAM requirements of two
+     reduced configurations (PSK-CCM and NSA suite B).
+   * Add config flag POLARSSL_DEPRECATED_WARNING (off by default) to produce
+     warnings on use of deprecated functions (with GCC and Clang only).
+   * Add config flag POLARSSL_DEPRECATED_REMOVED (off by default) to produce
+     errors on use of deprecated functions.
+
+Bugfix
+   * Fix compile errors with PLATFORM_NO_STD_FUNCTIONS.
+   * Fix compile error with PLATFORM_EXIT_ALT (thanks to Rafał Przywara).
+   * Fix bug in entropy.c when THREADING_C is also enabled that caused
+     entropy_free() to crash (thanks to Rafał Przywara).
+   * Fix memory leak when gcm_setkey() and ccm_setkey() are used more than
+     once on the same context.
+   * Fix bug in ssl_mail_client when password is longer that username (found
+     by Bruno Pape).
+   * Fix undefined behaviour (memcmp( NULL, NULL, 0 );) in X.509 modules
+     (detected by Clang's 3.6 UBSan).
+   * mpi_size() and mpi_msb() would segfault when called on an mpi that is
+     initialized but not set (found by pravic).
+   * Fix detection of support for getrandom() on Linux (reported by syzzer) by
+     doing it at runtime (using uname) rather that compile time.
+   * Fix handling of symlinks by "make install" (found by Gaël PORTAY).
+   * Fix potential NULL pointer dereference (not trigerrable remotely) when
+     ssl_write() is called before the handshake is finished (introduced in
+     1.3.10) (first reported by Martin Blumenstingl).
+   * Fix bug in pk_parse_key() that caused some valid private EC keys to be
+     rejected.
+   * Fix bug in Via Padlock support (found by Nikos Mavrogiannopoulos).
+   * Fix thread safety bug in RSA operations (found by Fredrik Axelsson).
+   * Fix hardclock() (only used in the benchmarking program) with some
+     versions of mingw64 (found by kxjhlele).
+   * Fix warnings from mingw64 in timing.c (found by kxjklele).
+   * Fix potential unintended sign extension in asn1_get_len() on 64-bit
+     platforms.
+   * Fix potential memory leak in ssl_set_psk() (found by Mansour Moufid).
+   * Fix compile error when POLARSSL_SSL_DISABLE_RENEGOTATION and
+     POLARSSL_SSL_SSESSION_TICKETS where both enabled in config.h (introduced
+     in 1.3.10).
+   * Add missing extern "C" guard in aesni.h (reported by amir zamani).
+   * Add missing dependency on SHA-256 in some x509 programs (reported by
+     Gergely Budai).
+   * Fix bug related to ssl_set_curves(): the client didn't check that the
+     curve picked by the server was actually allowed.
+
+Changes
+   * Remove bias in mpi_gen_prime (contributed by Pascal Junod).
+   * Remove potential sources of timing variations (some contributed by Pascal
+     Junod).
+   * Options POLARSSL_HAVE_INT8 and POLARSSL_HAVE_INT16 are deprecated.
+   * Enabling POLARSSL_NET_C without POLARSSL_HAVE_IPV6 is deprecated.
+   * compat-1.2.h and openssl.h are deprecated.
+   * Adjusting/overriding CFLAGS and LDFLAGS with the make build system is now
+     more flexible (warning: OFLAGS is not used any more) (see the README)
+     (contributed by Alon Bar-Lev).
+   * ssl_set_own_cert() no longer calls pk_check_pair() since the
+     performance impact was bad for some users (this was introduced in 1.3.10).
+   * Move from SHA-1 to SHA-256 in example programs using signatures
+     (suggested by Thorsten Mühlfelder).
+   * Remove some unneeded inclusions of header files from the standard library
+     "minimize" others (eg use stddef.h if only size_t is needed).
+   * Change #include lines in test files to use double quotes instead of angle
+     brackets for uniformity with the rest of the code.
+   * Remove dependency on sscanf() in X.509 parsing modules.
+
+= mbed TLS 1.3.10 released 2015-02-09
+Security
+   * NULL pointer dereference in the buffer-based allocator when the buffer is
+     full and polarssl_free() is called (found by Mark Hasemeyer)
+     (only possible if POLARSSL_MEMORY_BUFFER_ALLOC_C is enabled, which it is
+     not by default).
+   * Fix remotely-triggerable uninitialised pointer dereference caused by
+     crafted X.509 certificate (TLS server is not affected if it doesn't ask for a
+     client certificate) (found using Codenomicon Defensics).
+   * Fix remotely-triggerable memory leak caused by crafted X.509 certificates
+     (TLS server is not affected if it doesn't ask for a client certificate)
+     (found using Codenomicon Defensics).
+   * Fix potential stack overflow while parsing crafted X.509 certificates
+     (TLS server is not affected if it doesn't ask for a client certificate)
+     (found using Codenomicon Defensics).
+   * Fix timing difference that could theoretically lead to a
+     Bleichenbacher-style attack in the RSA and RSA-PSK key exchanges
+     (reported by Sebastian Schinzel).
+
+Features
+   * Add support for FALLBACK_SCSV (draft-ietf-tls-downgrade-scsv).
+   * Add support for Extended Master Secret (draft-ietf-tls-session-hash).
+   * Add support for Encrypt-then-MAC (RFC 7366).
+   * Add function pk_check_pair() to test if public and private keys match.
+   * Add x509_crl_parse_der().
+   * Add compile-time option POLARSSL_X509_MAX_INTERMEDIATE_CA to limit the
+     length of an X.509 verification chain.
+   * Support for renegotiation can now be disabled at compile-time
+   * Support for 1/n-1 record splitting, a countermeasure against BEAST.
+   * Certificate selection based on signature hash, preferring SHA-1 over SHA-2
+     for pre-1.2 clients when multiple certificates are available.
+   * Add support for getrandom() syscall on recent Linux kernels with Glibc or
+     a compatible enough libc (eg uClibc).
+   * Add ssl_set_arc4_support() to make it easier to disable RC4 at runtime
+     while using the default ciphersuite list.
+   * Added new error codes and debug messages about selection of
+     ciphersuite/certificate.
+
+Bugfix
+   * Stack buffer overflow if ctr_drbg_update() is called with too large
+     add_len (found by Jean-Philippe Aumasson) (not triggerable remotely).
+   * Possible buffer overflow of length at most POLARSSL_MEMORY_ALIGN_MULTIPLE
+     if memory_buffer_alloc_init() was called with buf not aligned and len not
+     a multiple of POLARSSL_MEMORY_ALIGN_MULTIPLE (not triggerable remotely).
+   * User set CFLAGS were ignored by Cmake with gcc (introduced in 1.3.9, found
+     by Julian Ospald).
+   * Fix potential undefined behaviour in Camellia.
+   * Fix potential failure in ECDSA signatures when POLARSSL_ECP_MAX_BITS is a
+     multiple of 8 (found by Gergely Budai).
+   * Fix unchecked return code in x509_crt_parse_path() on Windows (found by
+     Peter Vaskovic).
+   * Fix assembly selection for MIPS64 (thanks to James Cowgill).
+   * ssl_get_verify_result() now works even if the handshake was aborted due
+     to a failed verification (found by Fredrik Axelsson).
+   * Skip writing and parsing signature_algorithm extension if none of the
+     key exchanges enabled needs certificates. This fixes a possible interop
+     issue with some servers when a zero-length extension was sent. (Reported
+     by Peter Dettman.)
+   * On a 0-length input, base64_encode() did not correctly set output length
+     (found by Hendrik van den Boogaard).
+
+Changes
+   * Use deterministic nonces for AEAD ciphers in TLS by default (possible to
+     switch back to random with POLARSSL_SSL_AEAD_RANDOM_IV in config.h).
+   * Blind RSA private operations even when POLARSSL_RSA_NO_CRT is defined.
+   * ssl_set_own_cert() now returns an error on key-certificate mismatch.
+   * Forbid repeated extensions in X.509 certificates.
+   * debug_print_buf() now prints a text view in addition to hexadecimal.
+   * A specific error is now returned when there are ciphersuites in common
+     but none of them is usable due to external factors such as no certificate
+     with a suitable (extended)KeyUsage or curve or no PSK set.
+   * It is now possible to disable negotiation of truncated HMAC server-side
+     at runtime with ssl_set_truncated_hmac().
+   * Example programs for SSL client and server now disable SSLv3 by default.
+   * Example programs for SSL client and server now disable RC4 by default.
+   * Use platform.h in all test suites and programs.
+
+= PolarSSL 1.3.9 released 2014-10-20
+Security
+   * Lowest common hash was selected from signature_algorithms extension in
+     TLS 1.2 (found by Darren Bane) (introduced in 1.3.8).
+   * Remotely-triggerable memory leak when parsing some X.509 certificates
+     (server is not affected if it doesn't ask for a client certificate)
+     (found using Codenomicon Defensics).
+   * Remotely-triggerable memory leak when parsing crafted ClientHello
+     (not affected if ECC support was compiled out) (found using Codenomicon
+     Defensics).
+
+Bugfix
+   * Support escaping of commas in x509_string_to_names()
+   * Fix compile error in ssl_pthread_server (found by Julian Ospald).
+   * Fix net_accept() regarding non-blocking sockets (found by Luca Pesce).
+   * Don't print uninitialised buffer in ssl_mail_client (found by Marc Abel).
+   * Fix warnings from Clang's scan-build (contributed by Alfred Klomp).
+   * Fix compile error in timing.c when POLARSSL_NET_C and POLARSSL_SELFTEST
+     are defined but not POLARSSL_HAVE_TIME (found by Stephane Di Vito).
+   * Remove non-existent file from VS projects (found by Peter Vaskovic).
+   * ssl_read() could return non-application data records on server while
+     renegotation was pending, and on client when a HelloRequest was received.
+   * Server-initiated renegotiation would fail with non-blocking I/O if the
+     write callback returned WANT_WRITE when requesting renegotiation.
+   * ssl_close_notify() could send more than one message in some circumstances
+     with non-blocking I/O.
+   * Fix compiler warnings on iOS (found by Sander Niemeijer).
+   * x509_crt_parse() did not increase total_failed on PEM error
+   * Fix compile error with armcc in mpi_is_prime()
+   * Fix potential bad read in parsing ServerHello (found by Adrien
+     Vialletelle).
+
+Changes
+   * Ciphersuites using SHA-256 or SHA-384 now require TLS 1.x (there is no
+     standard defining how to use SHA-2 with SSL 3.0).
+   * Ciphersuites using RSA-PSK key exchange new require TLS 1.x (the spec is
+     ambiguous on how to encode some packets with SSL 3.0).
+   * Made buffer size in pk_write_(pub)key_pem() more dynamic, eg smaller if
+     RSA is disabled, larger if POLARSSL_MPI_MAX_SIZE is larger.
+   * ssl_read() now returns POLARSSL_ERR_NET_WANT_READ rather than
+     POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE on harmless alerts.
+   * POLARSSL_MPI_MAX_SIZE now defaults to 1024 in order to allow 8192 bits
+     RSA keys.
+   * Accept spaces at end of line or end of buffer in base64_decode().
+   * X.509 certificates with more than one AttributeTypeAndValue per
+     RelativeDistinguishedName are not accepted any more.
+
+= PolarSSL 1.3.8 released 2014-07-11
+Security
+   * Fix length checking for AEAD ciphersuites (found by Codenomicon).
+     It was possible to crash the server (and client) using crafted messages
+     when a GCM suite was chosen.
+
+Features
+   * Add CCM module and cipher mode to Cipher Layer
+   * Support for CCM and CCM_8 ciphersuites
+   * Support for parsing and verifying RSASSA-PSS signatures in the X.509
+     modules (certificates, CRLs and CSRs).
+   * Blowfish in the cipher layer now supports variable length keys.
+   * Add example config.h for PSK with CCM, optimized for low RAM usage.
+   * Optimize for RAM usage in example config.h for NSA Suite B profile.
+   * Add POLARSSL_REMOVE_ARC4_CIPHERSUITES to allow removing RC4 ciphersuites
+     from the default list (inactive by default).
+   * Add server-side enforcement of sent renegotiation requests
+     (ssl_set_renegotiation_enforced())
+   * Add SSL_CIPHERSUITES config.h flag to allow specifying a list of
+     ciphersuites to use and save some memory if the list is small.
+
+Changes
+   * Add LINK_WITH_PTHREAD option in CMake for explicit linking that is
+     required on some platforms (e.g. OpenBSD)
+   * Migrate zeroizing of data to polarssl_zeroize() instead of memset()
+     against unwanted compiler optimizations
+   * md_list() now returns hashes strongest first
+   * Selection of hash for signing ServerKeyExchange in TLS 1.2 now picks
+     strongest offered by client.
+   * All public contexts have _init() and _free() functions now for simpler
+     usage pattern
+
+Bugfix
+   * Fix in debug_print_msg()
+   * Enforce alignment in the buffer allocator even if buffer is not aligned
+   * Remove less-than-zero checks on unsigned numbers
+   * Stricter check on SSL ClientHello internal sizes compared to actual packet
+     size (found by TrustInSoft)
+   * Fix WSAStartup() return value check (found by Peter Vaskovic)
+   * Other minor issues (found by Peter Vaskovic)
+   * Fix symlink command for cross compiling with CMake (found by Andre
+     Heinecke)
+   * Fix DER output of gen_key app (found by Gergely Budai)
+   * Very small records were incorrectly rejected when truncated HMAC was in
+     use with some ciphersuites and versions (RC4 in all versions, CBC with
+     versions < TLS 1.1).
+   * Very large records using more than 224 bytes of padding were incorrectly
+     rejected with CBC-based ciphersuites and TLS >= 1.1
+   * Very large records using less padding could cause a buffer overread of up
+     to 32 bytes with CBC-based ciphersuites and TLS >= 1.1
+   * Restore ability to use a v1 cert as a CA if trusted locally. (This had
+     been removed in 1.3.6.)
+   * Restore ability to locally trust a self-signed cert that is not a proper
+     CA for use as an end entity certificate. (This had been removed in
+     1.3.6.)
+   * Fix preprocessor checks for bn_mul PPC asm (found by Barry K. Nathan).
+   * Use \n\t rather than semicolons for bn_mul asm, since some assemblers
+     interpret semicolons as comment delimiters (found by Barry K. Nathan).
+   * Fix off-by-one error in parsing Supported Point Format extension that
+     caused some handshakes to fail.
+   * Fix possible miscomputation of the premaster secret with DHE-PSK key
+     exchange that caused some handshakes to fail with other implementations.
+     (Failure rate <= 1/255 with common DHM moduli.)
+   * Disable broken Sparc64 bn_mul assembly (found by Florian Obser).
+   * Fix base64_decode() to return and check length correctly (in case of
+     tight buffers)
+   * Fix mpi_write_string() to write "00" as hex output for empty MPI (found
+     by Hui Dong)
+
+= PolarSSL 1.3.7 released on 2014-05-02
+Features
+   * debug_set_log_mode() added to determine raw or full logging
+   * debug_set_threshold() added to ignore messages over threshold level
+   * version_check_feature() added to check for compile-time options at
+     run-time
+
+Changes
+   * POLARSSL_CONFIG_OPTIONS has been removed. All values are individually
+     checked and filled in the relevant module headers
+   * Debug module only outputs full lines instead of parts
+   * Better support for the different Attribute Types from IETF PKIX (RFC 5280)
+   * AES-NI now compiles with "old" assemblers too
+   * Ciphersuites based on RC4 now have the lowest priority by default
+
+Bugfix
+   * Only iterate over actual certificates in ssl_write_certificate_request()
+     (found by Matthew Page)
+   * Typos in platform.c and pkcs11.c (found by Daniel Phillips and Steffan
+     Karger)
+   * cert_write app should use subject of issuer certificate as issuer of cert
+   * Fix false reject in padding check in ssl_decrypt_buf() for CBC
+     ciphersuites, for full SSL frames of data.
+   * Improve interoperability by not writing extension length in ClientHello /
+     ServerHello when no extensions are present (found by Matthew Page)
+   * rsa_check_pubkey() now allows an E up to N
+   * On OpenBSD, use arc4random_buf() instead of rand() to prevent warnings
+   * mpi_fill_random() was creating numbers larger than requested on
+     big-endian platform when size was not an integer number of limbs
+   * Fix dependencies issues in X.509 test suite.
+   * Some parts of ssl_tls.c were compiled even when the module was disabled.
+   * Fix detection of DragonflyBSD in net.c (found by Markus Pfeiffer)
+   * Fix detection of Clang on some Apple platforms with CMake
+     (found by Barry K. Nathan)
+
+= PolarSSL 1.3.6 released on 2014-04-11
+
+Features
+   * Support for the ALPN SSL extension
+   * Add option 'use_dev_random' to gen_key application
+   * Enable verification of the keyUsage extension for CA and leaf
+     certificates (POLARSSL_X509_CHECK_KEY_USAGE)
+   * Enable verification of the extendedKeyUsage extension
+     (POLARSSL_X509_CHECK_EXTENDED_KEY_USAGE)
+
+Changes
+   * x509_crt_info() now prints information about parsed extensions as well
+   * pk_verify() now returns a specific error code when the signature is valid
+     but shorter than the supplied length.
+   * Use UTC time to check certificate validity.
+   * Reject certificates with times not in UTC, per RFC 5280.
+
+Security
+   * Avoid potential timing leak in ecdsa_sign() by blinding modular division.
+     (Found by Watson Ladd.)
+   * The notAfter date of some certificates was no longer checked since 1.3.5.
+     This affects certificates in the user-supplied chain except the top
+     certificate. If the user-supplied chain contains only one certificates,
+     it is not affected (ie, its notAfter date is properly checked).
+   * Prevent potential NULL pointer dereference in ssl_read_record() (found by
+     TrustInSoft)
+
+Bugfix
+   * The length of various ClientKeyExchange messages was not properly checked.
+   * Some example server programs were not sending the close_notify alert.
+   * Potential memory leak in mpi_exp_mod() when error occurs during
+     calculation of RR.
+   * Fixed malloc/free default #define in platform.c (found by Gergely Budai).
+   * Fixed type which made POLARSSL_ENTROPY_FORCE_SHA256 uneffective (found by
+     Gergely Budai).
+   * Fix #include path in ecdsa.h which wasn't accepted by some compilers.
+     (found by Gergely Budai)
+   * Fix compile errors when POLARSSL_ERROR_STRERROR_BC is undefined (found by
+     Shuo Chen).
+   * oid_get_numeric_string() used to truncate the output without returning an
+     error if the output buffer was just 1 byte too small.
+   * dhm_parse_dhm() (hence dhm_parse_dhmfile()) did not set dhm->len.
+   * Calling pk_debug() on an RSA-alt key would segfault.
+   * pk_get_size() and pk_get_len() were off by a factor 8 for RSA-alt keys.
+   * Potential buffer overwrite in pem_write_buffer() because of low length
+     indication (found by Thijs Alkemade)
+   * EC curves constants, which should be only in ROM since 1.3.3, were also
+     stored in RAM due to missing 'const's (found by Gergely Budai).
+
+= PolarSSL 1.3.5 released on 2014-03-26
+Features
+   * HMAC-DRBG as a separate module
+   * Option to set the Curve preference order (disabled by default)
+   * Single Platform compatilibity layer (for memory / printf / fprintf)
+   * Ability to provide alternate timing implementation
+   * Ability to force the entropy module to use SHA-256 as its basis
+     (POLARSSL_ENTROPY_FORCE_SHA256)
+   * Testing script ssl-opt.sh added for testing 'live' ssl option
+     interoperability against OpenSSL and PolarSSL
+   * Support for reading EC keys that use SpecifiedECDomain in some cases.
+   * Entropy module now supports seed writing and reading
+
+Changes
+   * Deprecated the Memory layer
+   * entropy_add_source(), entropy_update_manual() and entropy_gather()
+     now thread-safe if POLARSSL_THREADING_C defined
+   * Improvements to the CMake build system, contributed by Julian Ospald.
+   * Work around a bug of the version of Clang shipped by Apple with Mavericks
+     that prevented bignum.c from compiling. (Reported by Rafael Baptista.)
+   * Revamped the compat.sh interoperatibility script to include support for
+     testing against GnuTLS
+   * Deprecated ssl_set_own_cert_rsa() and ssl_set_own_cert_rsa_alt()
+   * Improvements to tests/Makefile, contributed by Oden Eriksson.
+
+Security
+   * Forbid change of server certificate during renegotiation to prevent
+     "triple handshake" attack when authentication mode is 'optional' (the
+     attack was already impossible when authentication is required).
+   * Check notBefore timestamp of certificates and CRLs from the future.
+   * Forbid sequence number wrapping
+   * Fixed possible buffer overflow with overlong PSK
+   * Possible remotely-triggered out-of-bounds memory access fixed (found by
+     TrustInSoft)
+
+Bugfix
+   * ecp_gen_keypair() does more tries to prevent failure because of
+     statistics
+   * Fixed bug in RSA PKCS#1 v1.5 "reversed" operations
+   * Fixed testing with out-of-source builds using cmake
+   * Fixed version-major intolerance in server
+   * Fixed CMake symlinking on out-of-source builds
+   * Fixed dependency issues in test suite
+   * Programs rsa_sign_pss and rsa_verify_pss were not using PSS since 1.3.0
+   * Bignum's MIPS-32 assembly was used on MIPS-64, causing chaos. (Found by
+     Alex Wilson.)
+   * ssl_cache was creating entries when max_entries=0 if TIMING_C was enabled.
+   * m_sleep() was sleeping twice too long on most Unix platforms.
+   * Fixed bug with session tickets and non-blocking I/O in the unlikely case
+     send() would return an EAGAIN error when sending the ticket.
+   * ssl_cache was leaking memory when reusing a timed out entry containing a
+     client certificate.
+   * ssl_srv was leaking memory when client presented a timed out ticket
+     containing a client certificate
+   * ssl_init() was leaving a dirty pointer in ssl_context if malloc of
+     out_ctr failed
+   * ssl_handshake_init() was leaving dirty pointers in subcontexts if malloc
+     of one of them failed
+   * Fix typo in rsa_copy() that impacted PKCS#1 v2 contexts
+   * x509_get_current_time() uses localtime_r() to prevent thread issues
+
+= PolarSSL 1.3.4 released on 2014-01-27
+Features
+   * Support for the Koblitz curves: secp192k1, secp224k1, secp256k1
+   * Support for RIPEMD-160
+   * Support for AES CFB8 mode
+   * Support for deterministic ECDSA (RFC 6979)
+
+Bugfix
+   * Potential memory leak in bignum_selftest()
+   * Replaced expired test certificate
+   * ssl_mail_client now terminates lines with CRLF, instead of LF
+   * net module handles timeouts on blocking sockets better (found by Tilman
+     Sauerbeck)
+   * Assembly format fixes in bn_mul.h
+
+Security
+   * Missing MPI_CHK calls added around unguarded mpi calls (found by
+     TrustInSoft)
+
+= PolarSSL 1.3.3 released on 2013-12-31
+Features
+   * EC key generation support in gen_key app
+   * Support for adhering to client ciphersuite order preference
+     (POLARSSL_SSL_SRV_RESPECT_CLIENT_PREFERENCE)
+   * Support for Curve25519
+   * Support for ECDH-RSA and ECDH-ECDSA key exchanges and ciphersuites
+   * Support for IPv6 in the NET module
+   * AES-NI support for AES, AES-GCM and AES key scheduling
+   * SSL Pthread-based server example added (ssl_pthread_server)
+
+Changes
+   * gen_prime() speedup
+   * Speedup of ECP multiplication operation
+   * Relaxed some SHA2 ciphersuite's version requirements
+   * Dropped use of readdir_r() instead of readdir() with threading support
+   * More constant-time checks in the RSA module
+   * Split off curves from ecp.c into ecp_curves.c
+   * Curves are now stored fully in ROM
+   * Memory usage optimizations in ECP module
+   * Removed POLARSSL_THREADING_DUMMY
+
+Bugfix
+   * Fixed bug in mpi_set_bit() on platforms where t_uint is wider than int
+   * Fixed X.509 hostname comparison (with non-regular characters)
+   * SSL now gracefully handles missing RNG
+   * Missing defines / cases for RSA_PSK key exchange
+   * crypt_and_hash app checks MAC before final decryption
+   * Potential memory leak in ssl_ticket_keys_init()
+   * Memory leak in benchmark application
+   * Fixed x509_crt_parse_path() bug on Windows platforms
+   * Added missing MPI_CHK() around some statements in mpi_div_mpi() (found by
+     TrustInSoft)
+   * Fixed potential overflow in certificate size verification in
+     ssl_write_certificate() (found by TrustInSoft)
+
+Security
+   * Possible remotely-triggered out-of-bounds memory access fixed (found by
+     TrustInSoft)
+
+= PolarSSL 1.3.2 released on 2013-11-04
+Features
+   * PK tests added to test framework
+   * Added optional optimization for NIST MODP curves (POLARSSL_ECP_NIST_OPTIM)
+   * Support for Camellia-GCM mode and ciphersuites
+
+Changes
+   * Padding checks in cipher layer are now constant-time
+   * Value comparisons in SSL layer are now constant-time
+   * Support for serialNumber, postalAddress and postalCode in X509 names
+   * SSL Renegotiation was refactored
+
+Bugfix
+   * More stringent checks in cipher layer
+   * Server does not send out extensions not advertised by client
+   * Prevent possible alignment warnings on casting from char * to 'aligned *'
+   * Misc fixes and additions to dependency checks
+   * Const correctness
+   * cert_write with selfsign should use issuer_name as subject_name
+   * Fix ECDSA corner case: missing reduction mod N (found by DualTachyon)
+   * Defines to handle UEFI environment under MSVC
+   * Server-side initiated renegotiations send HelloRequest
+
+= PolarSSL 1.3.1 released on 2013-10-15
+Features
+   * Support for Brainpool curves and TLS ciphersuites (RFC 7027)
+   * Support for ECDHE-PSK key-exchange and ciphersuites
+   * Support for RSA-PSK key-exchange and ciphersuites
+
+Changes
+   * RSA blinding locks for a smaller amount of time
+   * TLS compression only allocates working buffer once
+   * Introduced POLARSSL_HAVE_READDIR_R for systems without it
+   * config.h is more script-friendly
+
+Bugfix
+   * Missing MSVC defines added
+   * Compile errors with POLARSSL_RSA_NO_CRT
+   * Header files with 'polarssl/'
+   * Const correctness
+   * Possible naming collision in dhm_context
+   * Better support for MSVC
+   * threading_set_alt() name
+   * Added missing x509write_crt_set_version()
+
+= PolarSSL 1.3.0 released on 2013-10-01
+Features
+   * Elliptic Curve Cryptography module added
+   * Elliptic Curve Diffie Hellman module added
+   * Ephemeral Elliptic Curve Diffie Hellman support for SSL/TLS
+    (ECDHE-based ciphersuites)
+   * Ephemeral Elliptic Curve Digital Signature Algorithm support for SSL/TLS
+    (ECDSA-based ciphersuites)
+   * Ability to specify allowed ciphersuites based on the protocol version.
+   * PSK and DHE-PSK based ciphersuites added
+   * Memory allocation abstraction layer added
+   * Buffer-based memory allocator added (no malloc() / free() / HEAP usage)
+   * Threading abstraction layer added (dummy / pthread / alternate)
+   * Public Key abstraction layer added
+   * Parsing Elliptic Curve keys
+   * Parsing Elliptic Curve certificates
+   * Support for max_fragment_length extension (RFC 6066)
+   * Support for truncated_hmac extension (RFC 6066)
+   * Support for zeros-and-length (ANSI X.923) padding, one-and-zeros
+     (ISO/IEC 7816-4) padding and zero padding in the cipher layer
+   * Support for session tickets (RFC 5077)
+   * Certificate Request (CSR) generation with extensions (key_usage,
+     ns_cert_type)
+   * X509 Certificate writing with extensions (basic_constraints,
+     issuer_key_identifier, etc)
+   * Optional blinding for RSA, DHM and EC
+   * Support for multiple active certificate / key pairs in SSL servers for
+   	 the same host (Not to be confused with SNI!)
+
+Changes
+   * Ability to enable / disable SSL v3 / TLS 1.0 / TLS 1.1 / TLS 1.2
+     individually
+   * Introduced separate SSL Ciphersuites module that is based on
+     Cipher and MD information
+   * Internals for SSL module adapted to have separate IV pointer that is
+     dynamically set (Better support for hardware acceleration)
+   * Moved all OID functionality to a separate module. RSA function
+     prototypes for the RSA sign and verify functions changed as a result
+   * Split up the GCM module into a starts/update/finish cycle
+   * Client and server now filter sent and accepted ciphersuites on minimum
+     and maximum protocol version
+   * Ability to disable server_name extension (RFC 6066)
+   * Renamed error_strerror() to the less conflicting polarssl_strerror()
+     (Ability to keep old as well with POLARSSL_ERROR_STRERROR_BC)
+   * SHA2 renamed to SHA256, SHA4 renamed to SHA512 and functions accordingly
+   * All RSA operations require a random generator for blinding purposes
+   * X509 core refactored
+   * x509_crt_verify() now case insensitive for cn (RFC 6125 6.4)
+   * Also compiles / runs without time-based functions (!POLARSSL_HAVE_TIME)
+   * Support faulty X509 v1 certificates with extensions
+     (POLARSSL_X509_ALLOW_EXTENSIONS_NON_V3)
+
+Bugfix
+   * Fixed parse error in ssl_parse_certificate_request()
+   * zlib compression/decompression skipped on empty blocks
+   * Support for AIX header locations in net.c module
+   * Fixed file descriptor leaks
+
+Security
+   * RSA blinding on CRT operations to counter timing attacks
+     (found by Cyril Arnaud and Pierre-Alain Fouque)
+
+
+= Version 1.2.14 released 2015-05-??
+
+Security
+   * Fix potential invalid memory read in the server, that allows a client to
+     crash it remotely (found by Caj Larsson).
+   * Fix potential invalid memory read in certificate parsing, that allows a
+     client to crash the server remotely if client authentication is enabled
+     (found using Codenomicon Defensics).
+   * Add countermeasure against "Lucky 13 strikes back" cache-based attack,
+     https://dl.acm.org/citation.cfm?id=2714625
+
+Bugfix
+   * Fix bug in Via Padlock support (found by Nikos Mavrogiannopoulos).
+   * Fix hardclock() (only used in the benchmarking program) with some
+     versions of mingw64 (found by kxjhlele).
+   * Fix warnings from mingw64 in timing.c (found by kxjklele).
+   * Fix potential unintended sign extension in asn1_get_len() on 64-bit
+     platforms (found with Coverity Scan).
+
+= Version 1.2.13 released 2015-02-16
+Note: Although PolarSSL has been renamed to mbed TLS, no changes reflecting
+      this will be made in the 1.2 branch at this point.
+
+Security
+   * Fix remotely-triggerable uninitialised pointer dereference caused by
+     crafted X.509 certificate (TLS server is not affected if it doesn't ask
+     for a client certificate) (found using Codenomicon Defensics).
+   * Fix remotely-triggerable memory leak caused by crafted X.509 certificates
+     (TLS server is not affected if it doesn't ask for a client certificate)
+     (found using Codenomicon Defensics).
+   * Fix potential stack overflow while parsing crafted X.509 certificates
+     (TLS server is not affected if it doesn't ask for a client certificate)
+     found using Codenomicon Defensics).
+   * Fix buffer overread of size 1 when parsing crafted X.509 certificates
+     (TLS server is not affected if it doesn't ask for a client certificate).
+
+Bugfix
+   * Fix potential undefined behaviour in Camellia.
+   * Fix memory leaks in PKCS#5 and PKCS#12.
+   * Stack buffer overflow if ctr_drbg_update() is called with too large
+     add_len (found by Jean-Philippe Aumasson) (not triggerable remotely).
+   * Fix bug in MPI/bignum on s390/s390x (reported by Dan Horák) (introduced
+     in 1.2.12).
+   * Fix unchecked return code in x509_crt_parse_path() on Windows (found by
+     Peter Vaskovic).
+   * Fix assembly selection for MIPS64 (thanks to James Cowgill).
+   * ssl_get_verify_result() now works even if the handshake was aborted due
+     to a failed verification (found by Fredrik Axelsson).
+   * Skip writing and parsing signature_algorithm extension if none of the
+     key exchanges enabled needs certificates. This fixes a possible interop
+     issue with some servers when a zero-length extension was sent. (Reported
+     by Peter Dettman.)
+   * On a 0-length input, base64_encode() did not correctly set output length
+     (found by Hendrik van den Boogaard).
+
+Changes
+   * Blind RSA private operations even when POLARSSL_RSA_NO_CRT is defined.
+   * Forbid repeated extensions in X.509 certificates.
+   * Add compile-time option POLARSSL_X509_MAX_INTERMEDIATE_CA to limit the
+     length of an X.509 verification chain (default = 8).
+= Version 1.2.12 released 2014-10-24
+
+Security
+   * Remotely-triggerable memory leak when parsing some X.509 certificates
+     (server is not affected if it doesn't ask for a client certificate).
+     (Found using Codenomicon Defensics.)
+
+Bugfix
+   * Fix potential bad read in parsing ServerHello (found by Adrien
+     Vialletelle).
+   * ssl_close_notify() could send more than one message in some circumstances
+     with non-blocking I/O.
+   * x509_crt_parse() did not increase total_failed on PEM error
+   * Fix compiler warnings on iOS (found by Sander Niemeijer).
+   * Don't print uninitialised buffer in ssl_mail_client (found by Marc Abel).
+   * Fix net_accept() regarding non-blocking sockets (found by Luca Pesce).
+   * ssl_read() could return non-application data records on server while
+     renegotation was pending, and on client when a HelloRequest was received.
+   * Fix warnings from Clang's scan-build (contributed by Alfred Klomp).
+
+Changes
+   * X.509 certificates with more than one AttributeTypeAndValue per
+     RelativeDistinguishedName are not accepted any more.
+   * ssl_read() now returns POLARSSL_ERR_NET_WANT_READ rather than
+     POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE on harmless alerts.
+   * Accept spaces at end of line or end of buffer in base64_decode().
+
+= Version 1.2.11 released 2014-07-11
+Features
+   * Entropy module now supports seed writing and reading
+
+Changes
+   * Introduced POLARSSL_HAVE_READDIR_R for systems without it
+   * Improvements to the CMake build system, contributed by Julian Ospald.
+   * Work around a bug of the version of Clang shipped by Apple with Mavericks
+     that prevented bignum.c from compiling. (Reported by Rafael Baptista.)
+   * Improvements to tests/Makefile, contributed by Oden Eriksson.
+   * Use UTC time to check certificate validity.
+   * Reject certificates with times not in UTC, per RFC 5280.
+   * Migrate zeroizing of data to polarssl_zeroize() instead of memset()
+     against unwanted compiler optimizations
+
+Security
+   * Forbid change of server certificate during renegotiation to prevent
+     "triple handshake" attack when authentication mode is optional (the
+     attack was already impossible when authentication is required).
+   * Check notBefore timestamp of certificates and CRLs from the future.
+   * Forbid sequence number wrapping
+   * Prevent potential NULL pointer dereference in ssl_read_record() (found by
+     TrustInSoft)
+   * Fix length checking for AEAD ciphersuites (found by Codenomicon).
+     It was possible to crash the server (and client) using crafted messages
+     when a GCM suite was chosen.
+
+Bugfix
+   * Fixed X.509 hostname comparison (with non-regular characters)
+   * SSL now gracefully handles missing RNG
+   * crypt_and_hash app checks MAC before final decryption
+   * Fixed x509_crt_parse_path() bug on Windows platforms
+   * Added missing MPI_CHK() around some statements in mpi_div_mpi() (found by
+     TrustInSoft)
+   * Fixed potential overflow in certificate size verification in
+     ssl_write_certificate() (found by TrustInSoft)
+   * Fix ASM format in bn_mul.h
+   * Potential memory leak in bignum_selftest()
+   * Replaced expired test certificate
+   * ssl_mail_client now terminates lines with CRLF, instead of LF
+   * Fix bug in RSA PKCS#1 v1.5 "reversed" operations
+   * Fixed testing with out-of-source builds using cmake
+   * Fixed version-major intolerance in server
+   * Fixed CMake symlinking on out-of-source builds
+   * Bignum's MIPS-32 assembly was used on MIPS-64, causing chaos. (Found by
+     Alex Wilson.)
+   * ssl_init() was leaving a dirty pointer in ssl_context if malloc of
+     out_ctr failed
+   * ssl_handshake_init() was leaving dirty pointers in subcontexts if malloc
+     of one of them failed
+   * x509_get_current_time() uses localtime_r() to prevent thread issues
+   * Some example server programs were not sending the close_notify alert.
+   * Potential memory leak in mpi_exp_mod() when error occurs during
+     calculation of RR.
+   * Improve interoperability by not writing extension length in ClientHello
+     when no extensions are present (found by Matthew Page)
+   * rsa_check_pubkey() now allows an E up to N
+   * On OpenBSD, use arc4random_buf() instead of rand() to prevent warnings
+   * mpi_fill_random() was creating numbers larger than requested on
+     big-endian platform when size was not an integer number of limbs
+   * Fix detection of DragonflyBSD in net.c (found by Markus Pfeiffer)
+   * Stricter check on SSL ClientHello internal sizes compared to actual packet
+     size (found by TrustInSoft)
+   * Fix preprocessor checks for bn_mul PPC asm (found by Barry K. Nathan).
+   * Use \n\t rather than semicolons for bn_mul asm, since some assemblers
+     interpret semicolons as comment delimiters (found by Barry K. Nathan).
+   * Disable broken Sparc64 bn_mul assembly (found by Florian Obser).
+   * Fix base64_decode() to return and check length correctly (in case of
+     tight buffers)
+
+= Version 1.2.10 released 2013-10-07
+Changes
+   * Changed RSA blinding to a slower but thread-safe version
+
+Bugfix
+   * Fixed memory leak in RSA as a result of introduction of blinding
+   * Fixed ssl_pkcs11_decrypt() prototype
+   * Fixed MSVC project files
+
+= Version 1.2.9 released 2013-10-01
+Changes
+   * x509_verify() now case insensitive for cn (RFC 6125 6.4)
+
+Bugfix
+   * Fixed potential memory leak when failing to resume a session
+   * Fixed potential file descriptor leaks (found by Remi Gacogne)
+   * Minor fixes
+
+Security
+   * Fixed potential heap buffer overflow on large hostname setting
+   * Fixed potential negative value misinterpretation in load_file()
+   * RSA blinding on CRT operations to counter timing attacks
+     (found by Cyril Arnaud and Pierre-Alain Fouque)
+
+= Version 1.2.8 released 2013-06-19
+Features
+   * Parsing of PKCS#8 encrypted private key files
+   * PKCS#12 PBE and derivation functions
+   * Centralized module option values in config.h to allow user-defined
+     settings without editing header files by using POLARSSL_CONFIG_OPTIONS
+
+Changes
+   * HAVEGE random generator disabled by default
+   * Internally split up x509parse_key() into a (PEM) handler function
+     and specific DER parser functions for the PKCS#1 and unencrypted
+     PKCS#8 private key formats
+   * Added mechanism to provide alternative implementations for all
+     symmetric cipher and hash algorithms (e.g. POLARSSL_AES_ALT in
+	 config.h)
+   * PKCS#5 module added. Moved PBKDF2 functionality inside and deprecated
+     old PBKDF2 module
+
+Bugfix
+   * Secure renegotiation extension should only be sent in case client
+     supports secure renegotiation
+   * Fixed offset for cert_type list in ssl_parse_certificate_request()
+   * Fixed const correctness issues that have no impact on the ABI
+   * x509parse_crt() now better handles PEM error situations
+   * ssl_parse_certificate() now calls x509parse_crt_der() directly
+     instead of the x509parse_crt() wrapper that can also parse PEM
+	 certificates
+   * x509parse_crtpath() is now reentrant and uses more portable stat()
+   * Fixed bignum.c and bn_mul.h to support Thumb2 and LLVM compiler
+   * Fixed values for 2-key Triple DES in cipher layer
+   * ssl_write_certificate_request() can handle empty ca_chain
+
+Security
+   * A possible DoS during the SSL Handshake, due to faulty parsing of
+     PEM-encoded certificates has been fixed (found by Jack Lloyd)
+
+= Version 1.2.7 released 2013-04-13
+Features
+   * Ability to specify allowed ciphersuites based on the protocol version.
+
+Changes
+   * Default Blowfish keysize is now 128-bits
+   * Test suites made smaller to accommodate Raspberry Pi
+
+Bugfix
+   * Fix for MPI assembly for ARM
+   * GCM adapted to support sizes > 2^29
+
+= Version 1.2.6 released 2013-03-11
+Bugfix
+   * Fixed memory leak in ssl_free() and ssl_reset() for active session
+   * Corrected GCM counter incrementation to use only 32-bits instead of
+     128-bits (found by Yawning Angel)
+   * Fixes for 64-bit compilation with MS Visual Studio
+   * Fixed net_bind() for specified IP addresses on little endian systems
+   * Fixed assembly code for ARM (Thumb and regular) for some compilers
+
+Changes
+   * Internally split up rsa_pkcs1_encrypt(), rsa_pkcs1_decrypt(),
+     rsa_pkcs1_sign() and rsa_pkcs1_verify() to separate PKCS#1 v1.5 and
+     PKCS#1 v2.1 functions
+   * Added support for custom labels when using rsa_rsaes_oaep_encrypt()
+     or rsa_rsaes_oaep_decrypt()
+   * Re-added handling for SSLv2 Client Hello when the define
+     POLARSSL_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO is set
+   * The SSL session cache module (ssl_cache) now also retains peer_cert
+     information (not the entire chain)
+
+Security
+   * Removed further timing differences during SSL message decryption in
+     ssl_decrypt_buf()
+   * Removed timing differences due to bad padding from
+     rsa_rsaes_pkcs1_v15_decrypt() and rsa_pkcs1_decrypt() for PKCS#1 v1.5
+     operations
+
+= Version 1.2.5 released 2013-02-02
+Changes
+   * Allow enabling of dummy error_strerror() to support some use-cases
+   * Debug messages about padding errors during SSL message decryption are
+     disabled by default and can be enabled with POLARSSL_SSL_DEBUG_ALL 
+   * Sending of security-relevant alert messages that do not break
+     interoperability can be switched on/off with the flag
+     POLARSSL_SSL_ALL_ALERT_MESSAGES
+
+Security
+   * Removed timing differences during SSL message decryption in
+     ssl_decrypt_buf() due to badly formatted padding
+
+= Version 1.2.4 released 2013-01-25
+Changes
+   * More advanced SSL ciphersuite representation and moved to more dynamic
+     SSL core
+   * Added ssl_handshake_step() to allow single stepping the handshake process
+
+Bugfix
+   * Memory leak when using RSA_PKCS_V21 operations fixed
+   * Handle future version properly in ssl_write_certificate_request()
+   * Correctly handle CertificateRequest message in client for <= TLS 1.1
+     without DN list
+
+= Version 1.2.3 released 2012-11-26
+Bugfix
+   * Server not always sending correct CertificateRequest message
+
+= Version 1.2.2 released 2012-11-24
+Changes
+   * Added p_hw_data to ssl_context for context specific hardware acceleration
+     data
+   * During verify trust-CA is only checked for expiration and CRL presence  
+
+Bugfixes
+   * Fixed client authentication compatibility
+   * Fixed dependency on POLARSSL_SHA4_C in SSL modules
+
+= Version 1.2.1 released 2012-11-20
+Changes
+   * Depth that the certificate verify callback receives is now numbered
+     bottom-up (Peer cert depth is 0)
+
+Bugfixes
+   * Fixes for MSVC6
+   * Moved mpi_inv_mod() outside POLARSSL_GENPRIME
+   * Allow R and A to point to same mpi in mpi_div_mpi (found by Manuel
+     Pégourié-Gonnard)
+   * Fixed possible segfault in mpi_shift_r() (found by Manuel
+     Pégourié-Gonnard)
+   * Added max length check for rsa_pkcs1_sign with PKCS#1 v2.1
+
+= Version 1.2.0 released 2012-10-31
+Features
+   * Added support for NULL cipher (POLARSSL_CIPHER_NULL_CIPHER) and weak
+     ciphersuites (POLARSSL_ENABLE_WEAK_CIPHERSUITES). They are disabled by
+     default!
+   * Added support for wildcard certificates
+   * Added support for multi-domain certificates through the X509 Subject
+     Alternative Name extension
+   * Added preliminary ASN.1 buffer writing support
+   * Added preliminary X509 Certificate Request writing support
+   * Added key_app_writer example application
+   * Added cert_req example application
+   * Added base Galois Counter Mode (GCM) for AES
+   * Added TLS 1.2 support (RFC 5246)
+   * Added GCM suites to TLS 1.2 (RFC 5288)
+   * Added commandline error code convertor (util/strerror)
+   * Added support for Hardware Acceleration hooking in SSL/TLS
+   * Added OpenSSL / PolarSSL compatibility script (tests/compat.sh) and
+     example application (programs/ssl/o_p_test) (requires OpenSSL)
+   * Added X509 CA Path support
+   * Added Thumb assembly optimizations
+   * Added DEFLATE compression support as per RFC3749 (requires zlib)
+   * Added blowfish algorithm (Generic and cipher layer)
+   * Added PKCS#5 PBKDF2 key derivation function
+   * Added Secure Renegotiation (RFC 5746)
+   * Added predefined DHM groups from RFC 5114
+   * Added simple SSL session cache implementation
+   * Added ServerName extension parsing (SNI) at server side
+   * Added option to add minimum accepted SSL/TLS protocol version
+
+Changes
+   * Removed redundant POLARSSL_DEBUG_MSG define
+   * AES code only check for Padlock once
+   * Fixed const-correctness mpi_get_bit()
+   * Documentation for mpi_lsb() and mpi_msb()
+   * Moved out_msg to out_hdr + 32 to support hardware acceleration
+   * Changed certificate verify behaviour to comply with RFC 6125 section 6.3
+     to not match CN if subjectAltName extension is present (Closes ticket #56)
+   * Cipher layer cipher_mode_t POLARSSL_MODE_CFB128 is renamed to
+     POLARSSL_MODE_CFB, to also handle different block size CFB modes.
+   * Removed handling for SSLv2 Client Hello (as per RFC 5246 recommendation)
+   * Revamped session resumption handling
+   * Generalized external private key implementation handling (like PKCS#11)
+     in SSL/TLS
+   * Revamped x509_verify() and the SSL f_vrfy callback implementations
+   * Moved from unsigned long to fixed width uint32_t types throughout code
+   * Renamed ciphersuites naming scheme to IANA reserved names
+
+Bugfix
+   * Fixed handling error in mpi_cmp_mpi() on longer B values (found by
+     Hui Dong)
+   * Fixed potential heap corruption in x509_name allocation
+   * Fixed single RSA test that failed on Big Endian systems (Closes ticket #54)
+   * mpi_exp_mod() now correctly handles negative base numbers (Closes ticket
+     #52)
+   * Handle encryption with private key and decryption with public key as per
+   	 RFC 2313
+   * Handle empty certificate subject names
+   * Prevent reading over buffer boundaries on X509 certificate parsing
+   * mpi_add_abs() now correctly handles adding short numbers to long numbers
+     with carry rollover (found by Ruslan Yushchenko)
+   * Handle existence of OpenSSL Trust Extensions at end of X.509 DER blob
+   * Fixed MPI assembly for SPARC64 platform
+
+Security
+   * Fixed potential memory zeroization on miscrafted RSA key (found by Eloi
+     Vanderbeken)
+
+= Version 1.1.8 released on 2013-10-01
+Bugfix
+   * Fixed potential memory leak when failing to resume a session
+   * Fixed potential file descriptor leaks
+
+Security
+   * Potential buffer-overflow for ssl_read_record() (independently found by
+     both TrustInSoft and Paul Brodeur of Leviathan Security Group)
+   * Potential negative value misinterpretation in load_file()
+   * Potential heap buffer overflow on large hostname setting
+
+= Version 1.1.7 released on 2013-06-19
+Changes
+   * HAVEGE random generator disabled by default
+
+Bugfix
+   * x509parse_crt() now better handles PEM error situations
+   * ssl_parse_certificate() now calls x509parse_crt_der() directly
+     instead of the x509parse_crt() wrapper that can also parse PEM
+	 certificates
+   * Fixed values for 2-key Triple DES in cipher layer
+   * ssl_write_certificate_request() can handle empty ca_chain
+
+Security
+   * A possible DoS during the SSL Handshake, due to faulty parsing of
+     PEM-encoded certificates has been fixed (found by Jack Lloyd)
+
+= Version 1.1.6 released on 2013-03-11
+Bugfix
+   * Fixed net_bind() for specified IP addresses on little endian systems
+
+Changes
+   * Allow enabling of dummy error_strerror() to support some use-cases
+   * Debug messages about padding errors during SSL message decryption are
+     disabled by default and can be enabled with POLARSSL_SSL_DEBUG_ALL
+
+Security
+   * Removed timing differences during SSL message decryption in
+     ssl_decrypt_buf()
+   * Removed timing differences due to bad padding from
+     rsa_rsaes_pkcs1_v15_decrypt() and rsa_pkcs1_decrypt() for PKCS#1 v1.5
+     operations
+
+= Version 1.1.5 released on 2013-01-16
+Bugfix
+   * Fixed MPI assembly for SPARC64 platform
+   * Handle existence of OpenSSL Trust Extensions at end of X.509 DER blob
+   * mpi_add_abs() now correctly handles adding short numbers to long numbers
+     with carry rollover
+   * Moved mpi_inv_mod() outside POLARSSL_GENPRIME
+   * Prevent reading over buffer boundaries on X509 certificate parsing
+   * mpi_exp_mod() now correctly handles negative base numbers (Closes ticket
+     #52)
+   * Fixed possible segfault in mpi_shift_r() (found by Manuel
+     Pégourié-Gonnard)
+   * Allow R and A to point to same mpi in mpi_div_mpi (found by Manuel
+     Pégourié-Gonnard)
+   * Added max length check for rsa_pkcs1_sign with PKCS#1 v2.1
+   * Memory leak when using RSA_PKCS_V21 operations fixed
+   * Handle encryption with private key and decryption with public key as per
+     RFC 2313
+   * Fixes for MSVC6
+
+Security
+   * Fixed potential memory zeroization on miscrafted RSA key (found by Eloi
+     Vanderbeken)
+
+= Version 1.1.4 released on 2012-05-31
+Bugfix
+   * Correctly handle empty SSL/TLS packets (Found by James Yonan)
+   * Fixed potential heap corruption in x509_name allocation
+   * Fixed single RSA test that failed on Big Endian systems (Closes ticket #54)
+
+= Version 1.1.3 released on 2012-04-29
+Bugfix
+   * Fixed random MPI generation to not generate more size than requested.
+
+= Version 1.1.2 released on 2012-04-26
+Bugfix
+   * Fixed handling error in mpi_cmp_mpi() on longer B values (found by
+     Hui Dong)
+
+Security
+   * Fixed potential memory corruption on miscrafted client messages (found by
+     Frama-C team at CEA LIST)
+   * Fixed generation of DHM parameters to correct length (found by Ruslan
+     Yushchenko)
+
+= Version 1.1.1 released on 2012-01-23
+Bugfix
+   * Check for failed malloc() in ssl_set_hostname() and x509_get_entries()
+     (Closes ticket #47, found by Hugo Leisink)
+   * Fixed issues with Intel compiler on 64-bit systems (Closes ticket #50)
+   * Fixed multiple compiler warnings for VS6 and armcc
+   * Fixed bug in CTR_CRBG selftest
+
+= Version 1.1.0 released on 2011-12-22
+Features
+   * Added ssl_session_reset() to allow better multi-connection pools of
+     SSL contexts without needing to set all non-connection-specific
+	 data and pointers again. Adapted ssl_server to use this functionality.
+   * Added ssl_set_max_version() to allow clients to offer a lower maximum
+     supported version to a server to help buggy server implementations.
+	 (Closes ticket #36)
+   * Added cipher_get_cipher_mode() and cipher_get_cipher_operation()
+     introspection functions (Closes ticket #40)
+   * Added CTR_DRBG based on AES-256-CTR (NIST SP 800-90) random generator
+   * Added a generic entropy accumulator that provides support for adding
+     custom entropy sources and added some generic and platform dependent
+	 entropy sources
+
+Changes
+   * Documentation for AES and Camellia in modes CTR and CFB128 clarified.
+   * Fixed rsa_encrypt and rsa_decrypt examples to use public key for
+     encryption and private key for decryption. (Closes ticket #34)
+   * Inceased maximum size of ASN1 length reads to 32-bits.
+   * Added an EXPLICIT tag number parameter to x509_get_ext()
+   * Added a separate CRL entry extension parsing function
+   * Separated the ASN.1 parsing code from the X.509 specific parsing code.
+     So now there is a module that is controlled with POLARSSL_ASN1_PARSE_C.
+   * Changed the defined key-length of DES ciphers in cipher.h to include the
+     parity bits, to prevent mistakes in copying data. (Closes ticket #33)
+   * Loads of minimal changes to better support WINCE as a build target
+     (Credits go to Marco Lizza)
+   * Added POLARSSL_MPI_WINDOW_SIZE definition to allow easier time to memory
+     trade-off
+   * Introduced POLARSSL_MPI_MAX_SIZE and POLARSSL_MPI_MAX_BITS for MPI size
+     management (Closes ticket #44)
+   * Changed the used random function pointer to more flexible format. Renamed
+     havege_rand() to havege_random() to prevent mistakes. Lots of changes as
+     a consequence in library code and programs
+   * Moved all examples programs to use the new entropy and CTR_DRBG
+   * Added permissive certificate parsing to x509parse_crt() and
+     x509parse_crtfile(). With permissive parsing the parsing does not stop on
+     encountering a parse-error. Beware that the meaning of return values has
+     changed!
+   * All error codes are now negative. Even on mermory failures and IO errors.
+
+Bugfix
+   * Fixed faulty HMAC-MD2 implementation. Found by dibac. (Closes
+     ticket #37)
+   * Fixed a bug where the CRL parser expected an EXPLICIT ASN.1 tag
+     before version numbers
+   * Allowed X509 key usage parsing to accept 4 byte values instead of the
+     standard 1 byte version sometimes used by Microsoft. (Closes ticket #38)
+   * Fixed incorrect behaviour in case of RSASSA-PSS with a salt length
+     smaller than the hash length. (Closes ticket #41)
+   * If certificate serial is longer than 32 octets, serial number is now
+     appended with '....' after first 28 octets
+   * Improved build support for s390x and sparc64 in bignum.h
+   * Fixed MS Visual C++ name clash with int64 in sha4.h
+   * Corrected removal of leading "00:" in printing serial numbers in
+     certificates and CRLs
+
+= Version 1.0.0 released on 2011-07-27
+Features
+   * Expanded cipher layer with support for CFB128 and CTR mode
+   * Added rsa_encrypt and rsa_decrypt simple example programs.
+
+Changes
+   * The generic cipher and message digest layer now have normal error
+     codes instead of integers
+
+Bugfix
+   * Undid faulty bug fix in ssl_write() when flushing old data (Ticket
+     #18)
+
+= Version 0.99-pre5 released on 2011-05-26
+Features
+   * Added additional Cipher Block Modes to symmetric ciphers
+     (AES CTR, Camellia CTR, XTEA CBC) including the option to
+     enable and disable individual modes when needed
+   * Functions requiring File System functions can now be disabled
+     by undefining POLARSSL_FS_IO
+   * A error_strerror function() has been added to translate between
+     error codes and their description.
+   * Added mpi_get_bit() and mpi_set_bit() individual bit setter/getter
+     functions.
+   * Added ssl_mail_client and ssl_fork_server as example programs.
+
+Changes
+   * Major argument / variable rewrite. Introduced use of size_t
+     instead of int for buffer lengths and loop variables for
+     better unsigned / signed use. Renamed internal bigint types
+     t_int and t_dbl to t_uint and t_udbl in the process
+   * mpi_init() and mpi_free() now only accept a single MPI
+     argument and do not accept variable argument lists anymore.
+   * The error codes have been remapped and combining error codes
+     is now done with a PLUS instead of an OR as error codes
+     used are negative.
+   * Changed behaviour of net_read(), ssl_fetch_input() and ssl_recv().
+     net_recv() now returns 0 on EOF instead of
+     POLARSSL_ERR_NET_CONN_RESET. ssl_fetch_input() returns
+     POLARSSL_ERR_SSL_CONN_EOF on an EOF from its f_recv() function.
+     ssl_read() returns 0 if a POLARSSL_ERR_SSL_CONN_EOF is received
+     after the handshake.
+   * Network functions now return POLARSSL_ERR_NET_WANT_READ or
+     POLARSSL_ERR_NET_WANT_WRITE instead of the ambiguous
+     POLARSSL_ERR_NET_TRY_AGAIN
+
+= Version 0.99-pre4 released on 2011-04-01
+Features
+   * Added support for PKCS#1 v2.1 encoding and thus support
+     for the RSAES-OAEP and RSASSA-PSS operations.
+   * Reading of Public Key files incorporated into default x509
+     functionality as well.
+   * Added mpi_fill_random() for centralized filling of big numbers
+     with random data (Fixed ticket #10)
+
+Changes
+   * Debug print of MPI now removes leading zero octets and 
+     displays actual bit size of the value.
+   * x509parse_key() (and as a consequence x509parse_keyfile()) 
+     does not zeroize memory in advance anymore. Use rsa_init()
+     before parsing a key or keyfile!
+
+Bugfix
+   * Debug output of MPI's now the same independent of underlying
+     platform (32-bit / 64-bit) (Fixes ticket #19, found by Mads
+     Kiilerich and Mihai Militaru)
+   * Fixed bug in ssl_write() when flushing old data (Fixed ticket
+     #18, found by Nikolay Epifanov)
+   * Fixed proper handling of RSASSA-PSS verification with variable
+     length salt lengths
+
+= Version 0.99-pre3 released on 2011-02-28
+This release replaces version 0.99-pre2 which had possible copyright issues.
+Features
+   * Parsing PEM private keys encrypted with DES and AES
+     are now supported as well (Fixes ticket #5)
+   * Added crl_app program to allow easy reading and
+     printing of X509 CRLs from file
+
+Changes
+   * Parsing of PEM files moved to separate module (Fixes 
+     ticket #13). Also possible to remove PEM support for
+     systems only using DER encoding
+
+Bugfixes
+   * Corrected parsing of UTCTime dates before 1990 and
+     after 1950
+   * Support more exotic OID's when parsing certificates
+   	 (found by Mads Kiilerich)
+   * Support more exotic name representations when parsing
+     certificates (found by Mads Kiilerich)
+   * Replaced the expired test certificates
+   * Do not bail out if no client certificate specified. Try
+     to negotiate anonymous connection (Fixes ticket #12,
+     found by Boris Krasnovskiy)
+
+Security fixes
+   * Fixed a possible Man-in-the-Middle attack on the
+     Diffie Hellman key exchange (thanks to Larry Highsmith,
+     Subreption LLC)
+
+= Version 0.99-pre1 released on 2011-01-30
+Features
+Note: Most of these features have been donated by Fox-IT
+   * Added Doxygen source code documentation parts
+   * Added reading of DHM context from memory and file
+   * Improved X509 certificate parsing to include extended
+     certificate fields, including Key Usage
+   * Improved certificate verification and verification
+     against the available CRLs
+   * Detection for DES weak keys and parity bits added
+   * Improvements to support integration in other
+     applications:
+       + Added generic message digest and cipher wrapper
+       + Improved information about current capabilities,
+         status, objects and configuration
+       + Added verification callback on certificate chain
+         verification to allow external blacklisting
+	   + Additional example programs to show usage
+   * Added support for PKCS#11 through the use of the
+     libpkcs11-helper library
+
+Changes
+   * x509parse_time_expired() checks time in addition to
+     the existing date check
+   * The ciphers member of ssl_context and the cipher member
+     of ssl_session have been renamed to ciphersuites and
+     ciphersuite respectively. This clarifies the difference
+     with the generic cipher layer and is better naming
+     altogether
+
+= Version 0.14.0 released on 2010-08-16
+Features
+   * Added support for SSL_EDH_RSA_AES_128_SHA and
+     SSL_EDH_RSA_CAMELLIA_128_SHA ciphersuites
+   * Added compile-time and run-time version information
+   * Expanded ssl_client2 arguments for more flexibility
+   * Added support for TLS v1.1
+
+Changes
+   * Made Makefile cleaner
+   * Removed dependency on rand() in rsa_pkcs1_encrypt().
+     Now using random fuction provided to function and
+     changed the prototype of rsa_pkcs1_encrypt(),
+     rsa_init() and rsa_gen_key().
+   * Some SSL defines were renamed in order to avoid
+     future confusion
+
+Bug fixes
+   * Fixed CMake out of source build for tests (found by
+     kkert)
+   * rsa_check_private() now supports PKCS1v2 keys as well
+   * Fixed deadlock in rsa_pkcs1_encrypt() on failing random
+     generator
+
+= Version 0.13.1 released on 2010-03-24
+Bug fixes
+   * Fixed Makefile in library that was mistakenly merged
+   * Added missing const string fixes
+
+= Version 0.13.0 released on 2010-03-21
+Features
+   * Added option parsing for host and port selection to
+     ssl_client2
+   * Added support for GeneralizedTime in X509 parsing
+   * Added cert_app program to allow easy reading and
+     printing of X509 certificates from file or SSL
+     connection.
+
+Changes
+   * Added const correctness for main code base
+   * X509 signature algorithm determination is now
+     in a function to allow easy future expansion
+   * Changed symmetric cipher functions to
+     identical interface (returning int result values)
+   * Changed ARC4 to use separate input/output buffer
+   * Added reset function for HMAC context as speed-up
+     for specific use-cases
+
+Bug fixes
+   * Fixed bug resulting in failure to send the last
+     certificate in the chain in ssl_write_certificate() and
+     ssl_write_certificate_request() (found by fatbob)
+   * Added small fixes for compiler warnings on a Mac
+     (found by Frank de Brabander)
+   * Fixed algorithmic bug in mpi_is_prime() (found by
+     Smbat Tonoyan)
+
+= Version 0.12.1 released on 2009-10-04
+Changes
+   * Coverage test definitions now support 'depends_on'
+     tagging system.
+   * Tests requiring specific hashing algorithms now honor
+     the defines.
+
+Bug fixes
+   * Changed typo in #ifdef in x509parse.c (found
+     by Eduardo)
+
+= Version 0.12.0 released on 2009-07-28
+Features
+   * Added CMake makefiles as alternative to regular Makefiles.
+   * Added preliminary Code Coverage tests for AES, ARC4,
+     Base64, MPI, SHA-family, MD-family, HMAC-SHA-family,
+     Camellia, DES, 3-DES, RSA PKCS#1, XTEA, Diffie-Hellman
+     and X509parse.
+
+Changes
+   * Error codes are not (necessarily) negative. Keep
+     this is mind when checking for errors.
+   * RSA_RAW renamed to SIG_RSA_RAW for consistency.
+   * Fixed typo in name of POLARSSL_ERR_RSA_OUTPUT_TOO_LARGE.
+   * Changed interface for AES and Camellia setkey functions
+     to indicate invalid key lengths.
+
+Bug fixes
+   * Fixed include location of endian.h on FreeBSD (found by
+     Gabriel)
+   * Fixed include location of endian.h and name clash on
+     Apples (found by Martin van Hensbergen)
+   * Fixed HMAC-MD2 by modifying md2_starts(), so that the
+     required HMAC ipad and opad variables are not cleared.
+     (found by code coverage tests)
+   * Prevented use of long long in bignum if 
+     POLARSSL_HAVE_LONGLONG not defined (found by Giles
+     Bathgate).
+   * Fixed incorrect handling of negative strings in
+     mpi_read_string() (found by code coverage tests).
+   * Fixed segfault on handling empty rsa_context in
+     rsa_check_pubkey() and rsa_check_privkey() (found by
+     code coverage tests).
+   * Fixed incorrect handling of one single negative input
+     value in mpi_add_abs() (found by code coverage tests).
+   * Fixed incorrect handling of negative first input
+     value in mpi_sub_abs() (found by code coverage tests).
+   * Fixed incorrect handling of negative first input
+     value in mpi_mod_mpi() and mpi_mod_int(). Resulting
+     change also affects mpi_write_string() (found by code
+     coverage tests).
+   * Corrected is_prime() results for 0, 1 and 2 (found by
+     code coverage tests).
+   * Fixed Camellia and XTEA for 64-bit Windows systems.
+
+= Version 0.11.1 released on 2009-05-17
+   * Fixed missing functionality for SHA-224, SHA-256, SHA384,
+     SHA-512 in rsa_pkcs1_sign()
+
+= Version 0.11.0 released on 2009-05-03
+   * Fixed a bug in mpi_gcd() so that it also works when both
+     input numbers are even and added testcases to check
+     (found by Pierre Habouzit).
+   * Added support for SHA-224, SHA-256, SHA-384 and SHA-512
+     one way hash functions with the PKCS#1 v1.5 signing and
+     verification.
+   * Fixed minor bug regarding mpi_gcd located within the
+     POLARSSL_GENPRIME block.
+   * Fixed minor memory leak in x509parse_crt() and added better
+     handling of 'full' certificate chains (found by Mathias
+     Olsson).
+   * Centralized file opening and reading for x509 files into
+     load_file()
+   * Made definition of net_htons() endian-clean for big endian
+     systems (Found by Gernot).
+   * Undefining POLARSSL_HAVE_ASM now also handles prevents asm in
+     padlock and timing code. 
+   * Fixed an off-by-one buffer allocation in ssl_set_hostname()
+     responsible for crashes and unwanted behaviour.
+   * Added support for Certificate Revocation List (CRL) parsing.
+   * Added support for CRL revocation to x509parse_verify() and
+     SSL/TLS code.
+   * Fixed compatibility of XTEA and Camellia on a 64-bit system
+     (found by Felix von Leitner).
+
+= Version 0.10.0 released on 2009-01-12
+   * Migrated XySSL to PolarSSL
+   * Added XTEA symmetric cipher
+   * Added Camellia symmetric cipher
+   * Added support for ciphersuites: SSL_RSA_CAMELLIA_128_SHA,
+     SSL_RSA_CAMELLIA_256_SHA and SSL_EDH_RSA_CAMELLIA_256_SHA
+   * Fixed dangerous bug that can cause a heap overflow in
+     rsa_pkcs1_decrypt (found by Christophe Devine)
+
+================================================================
+XySSL ChangeLog
+
+= Version 0.9 released on 2008-03-16
+
+    * Added support for ciphersuite: SSL_RSA_AES_128_SHA
+    * Enabled support for large files by default in aescrypt2.c
+    * Preliminary openssl wrapper contributed by David Barrett
+    * Fixed a bug in ssl_write() that caused the same payload to
+      be sent twice in non-blocking mode when send returns EAGAIN
+    * Fixed ssl_parse_client_hello(): session id and challenge must
+      not be swapped in the SSLv2 ClientHello (found by Greg Robson)
+    * Added user-defined callback debug function (Krystian Kolodziej)
+    * Before freeing a certificate, properly zero out all cert. data
+    * Fixed the "mode" parameter so that encryption/decryption are
+      not swapped on PadLock; also fixed compilation on older versions
+      of gcc (bug reported by David Barrett)
+    * Correctly handle the case in padlock_xcryptcbc() when input or
+      ouput data is non-aligned by falling back to the software
+      implementation, as VIA Nehemiah cannot handle non-aligned buffers
+    * Fixed a memory leak in x509parse_crt() which was reported by Greg
+      Robson-Garth; some x509write.c fixes by Pascal Vizeli, thanks to
+      Matthew Page who reported several bugs
+    * Fixed x509_get_ext() to accept some rare certificates which have
+      an INTEGER instead of a BOOLEAN for BasicConstraints::cA.
+    * Added support on the client side for the TLS "hostname" extension
+      (patch contributed by David Patino)
+    * Make x509parse_verify() return BADCERT_CN_MISMATCH when an empty
+      string is passed as the CN (bug reported by spoofy)
+    * Added an option to enable/disable the BN assembly code
+    * Updated rsa_check_privkey() to verify that (D*E) = 1 % (P-1)*(Q-1)
+    * Disabled obsolete hash functions by default (MD2, MD4); updated
+      selftest and benchmark to not test ciphers that have been disabled
+    * Updated x509parse_cert_info() to correctly display byte 0 of the
+      serial number, setup correct server port in the ssl client example
+    * Fixed a critical denial-of-service with X.509 cert. verification:
+      peer may cause xyssl to loop indefinitely by sending a certificate
+      for which the RSA signature check fails (bug reported by Benoit)
+    * Added test vectors for: AES-CBC, AES-CFB, DES-CBC and 3DES-CBC,
+      HMAC-MD5, HMAC-SHA1, HMAC-SHA-256, HMAC-SHA-384, and HMAC-SHA-512
+    * Fixed HMAC-SHA-384 and HMAC-SHA-512 (thanks to Josh Sinykin)
+    * Modified ssl_parse_client_key_exchange() to protect against
+      Daniel Bleichenbacher attack on PKCS#1 v1.5 padding, as well
+      as the Klima-Pokorny-Rosa extension of Bleichenbacher's attack
+    * Updated rsa_gen_key() so that ctx->N is always nbits in size
+    * Fixed assembly PPC compilation errors on Mac OS X, thanks to
+      David Barrett and Dusan Semen
+
+= Version 0.8 released on 2007-10-20
+
+    * Modified the HMAC functions to handle keys larger
+      than 64 bytes, thanks to Stephane Desneux and gary ng
+    * Fixed ssl_read_record() to properly update the handshake
+      message digests, which fixes IE6/IE7 client authentication
+    * Cleaned up the XYSSL* #defines, suggested by Azriel Fasten
+    * Fixed net_recv(), thanks to Lorenz Schori and Egon Kocjan
+    * Added user-defined callbacks for handling I/O and sessions
+    * Added lots of debugging output in the SSL/TLS functions
+    * Added preliminary X.509 cert. writing by Pascal Vizeli
+    * Added preliminary support for the VIA PadLock routines
+    * Added AES-CFB mode of operation, contributed by chmike
+    * Added an SSL/TLS stress testing program (ssl_test.c)
+    * Updated the RSA PKCS#1 code to allow choosing between
+      RSA_PUBLIC and RSA_PRIVATE, as suggested by David Barrett
+    * Updated ssl_read() to skip 0-length records from OpenSSL
+    * Fixed the make install target to comply with *BSD make
+    * Fixed a bug in mpi_read_binary() on 64-bit platforms
+    * mpi_is_prime() speedups, thanks to Kevin McLaughlin
+    * Fixed a long standing memory leak in mpi_is_prime()
+    * Replaced realloc with malloc in mpi_grow(), and set
+      the sign of zero as positive in mpi_init() (reported
+      by Jonathan M. McCune)
+
+= Version 0.7 released on 2007-07-07
+
+    * Added support for the MicroBlaze soft-core processor
+    * Fixed a bug in ssl_tls.c which sometimes prevented SSL
+      connections from being established with non-blocking I/O
+    * Fixed a couple bugs in the VS6 and UNIX Makefiles
+    * Fixed the "PIC register ebx clobbered in asm" bug
+    * Added HMAC starts/update/finish support functions
+    * Added the SHA-224, SHA-384 and SHA-512 hash functions
+    * Fixed the net_set_*block routines, thanks to Andreas
+    * Added a few demonstration programs: md5sum, sha1sum,
+      dh_client, dh_server, rsa_genkey, rsa_sign, rsa_verify
+    * Added new bignum import and export helper functions
+    * Rewrote README.txt in program/ssl/ca to better explain
+      how to create a test PKI
+
+= Version 0.6 released on 2007-04-01
+
+    * Ciphers used in SSL/TLS can now be disabled at compile
+      time, to reduce the memory footprint on embedded systems
+    * Added multiply assembly code for the TriCore and modified
+      havege_struct for this processor, thanks to David Patiño
+    * Added multiply assembly code for 64-bit PowerPCs,
+      thanks to Peking University and the OSU Open Source Lab
+    * Added experimental support of Quantum Cryptography
+    * Added support for autoconf, contributed by Arnaud Cornet
+    * Fixed "long long" compilation issues on IA-64 and PPC64
+    * Fixed a bug introduced in xyssl-0.5/timing.c: hardclock
+      was not being correctly defined on ARM and MIPS
+
+= Version 0.5 released on 2007-03-01
+
+    * Added multiply assembly code for SPARC and Alpha
+    * Added (beta) support for non-blocking I/O operations
+    * Implemented session resuming and client authentication
+    * Fixed some portability issues on WinCE, MINIX 3, Plan9
+      (thanks to Benjamin Newman), HP-UX, FreeBSD and Solaris
+    * Improved the performance of the EDH key exchange
+    * Fixed a bug that caused valid packets with a payload
+      size of 16384 bytes to be rejected
+
+= Version 0.4 released on 2007-02-01
+
+    * Added support for Ephemeral Diffie-Hellman key exchange
+    * Added multiply asm code for SSE2, ARM, PPC, MIPS and M68K
+    * Various improvement to the modular exponentiation code
+    * Rewrote the headers to generate the API docs with doxygen
+    * Fixed a bug in ssl_encrypt_buf (incorrect padding was
+      generated) and in ssl_parse_client_hello (max. client
+      version was not properly set), thanks to Didier Rebeix
+    * Fixed another bug in ssl_parse_client_hello: clients with
+      cipherlists larger than 96 bytes were incorrectly rejected
+    * Fixed a couple memory leak in x509_read.c
+
+= Version 0.3 released on 2007-01-01
+
+    * Added server-side SSLv3 and TLSv1.0 support
+    * Multiple fixes to enhance the compatibility with g++,
+      thanks to Xosé Antón Otero Ferreira
+    * Fixed a bug in the CBC code, thanks to dowst; also,
+      the bignum code is no longer dependent on long long
+    * Updated rsa_pkcs1_sign to handle arbitrary large inputs
+    * Updated timing.c for improved compatibility with i386
+      and 486 processors, thanks to Arnaud Cornet
+
+= Version 0.2 released on 2006-12-01
+
+    * Updated timing.c to support ARM and MIPS arch
+    * Updated the MPI code to support 8086 on MSVC 1.5
+    * Added the copyright notice at the top of havege.h
+    * Fixed a bug in sha2_hmac, thanks to newsoft/Wenfang Zhang
+    * Fixed a bug reported by Adrian Rüegsegger in x509_read_key
+    * Fixed a bug reported by Torsten Lauter in ssl_read_record
+    * Fixed a bug in rsa_check_privkey that would wrongly cause
+      valid RSA keys to be dismissed (thanks to oldwolf)
+    * Fixed a bug in mpi_is_prime that caused some primes to fail
+      the Miller-Rabin primality test
+
+    I'd also like to thank Younès Hafri for the CRUX linux port,
+    Khalil Petit who added XySSL into pkgsrc and Arnaud Cornet
+    who maintains the Debian package :-)
+
+= Version 0.1 released on 2006-11-01
+

+ 2 - 0
Pal/lib/crypto/mbedtls/LICENSE

@@ -0,0 +1,2 @@
+Unless specifically indicated otherwise in a file, files are licensed
+under the Apache 2.0 license, as can be found in: apache-2.0.txt

+ 23 - 0
Pal/lib/crypto/mbedtls/mbedtls/config.h

@@ -0,0 +1,23 @@
+/* Copyright (C) 2017 Fortanix, Inc.
+
+   This file is part of Graphene Library OS.
+
+   Graphene Library OS is free software: you can redistribute it and/or
+   modify it under the terms of the GNU General Public License
+   as published by the Free Software Foundation, either version 3 of the
+   License, or (at your option) any later version.
+
+   Graphene Library OS is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+#ifndef MBEDTLS_CONFIG_H
+#define MBEDTLS_CONFIG_H
+
+#define MBEDTLS_SHA256_C
+
+#endif

+ 141 - 0
Pal/lib/crypto/mbedtls/mbedtls/sha256.h

@@ -0,0 +1,141 @@
+/**
+ * \file sha256.h
+ *
+ * \brief SHA-224 and SHA-256 cryptographic hash function
+ *
+ *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ *  SPDX-License-Identifier: Apache-2.0
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License"); you may
+ *  not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ *  This file is part of mbed TLS (https://tls.mbed.org)
+ */
+#ifndef MBEDTLS_SHA256_H
+#define MBEDTLS_SHA256_H
+
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
+#include <stddef.h>
+#include <stdint.h>
+
+#if !defined(MBEDTLS_SHA256_ALT)
+// Regular implementation
+//
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief          SHA-256 context structure
+ */
+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 */
+}
+mbedtls_sha256_context;
+
+/**
+ * \brief          Initialize SHA-256 context
+ *
+ * \param ctx      SHA-256 context to be initialized
+ */
+void mbedtls_sha256_init( mbedtls_sha256_context *ctx );
+
+/**
+ * \brief          Clear SHA-256 context
+ *
+ * \param ctx      SHA-256 context to be cleared
+ */
+void mbedtls_sha256_free( mbedtls_sha256_context *ctx );
+
+/**
+ * \brief          Clone (the state of) a SHA-256 context
+ *
+ * \param dst      The destination context
+ * \param src      The context to be cloned
+ */
+void mbedtls_sha256_clone( mbedtls_sha256_context *dst,
+                           const mbedtls_sha256_context *src );
+
+/**
+ * \brief          SHA-256 context setup
+ *
+ * \param ctx      context to be initialized
+ * \param is224    0 = use SHA256, 1 = use SHA224
+ */
+void mbedtls_sha256_starts( mbedtls_sha256_context *ctx, int is224 );
+
+/**
+ * \brief          SHA-256 process buffer
+ *
+ * \param ctx      SHA-256 context
+ * \param input    buffer holding the  data
+ * \param ilen     length of the input data
+ */
+void mbedtls_sha256_update( mbedtls_sha256_context *ctx, const unsigned char *input,
+                    size_t ilen );
+
+/**
+ * \brief          SHA-256 final digest
+ *
+ * \param ctx      SHA-256 context
+ * \param output   SHA-224/256 checksum result
+ */
+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] );
+
+#ifdef __cplusplus
+}
+#endif
+
+#else  /* MBEDTLS_SHA256_ALT */
+#include "sha256_alt.h"
+#endif /* MBEDTLS_SHA256_ALT */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief          Output = SHA-256( input 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
+ */
+void mbedtls_sha256( const unsigned char *input, size_t ilen,
+           unsigned char output[32], int is224 );
+
+/**
+ * \brief          Checkup routine
+ *
+ * \return         0 if successful, or 1 if the test failed
+ */
+int mbedtls_sha256_self_test( int verbose );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* mbedtls_sha256.h */

+ 458 - 0
Pal/lib/crypto/mbedtls/sha256.c

@@ -0,0 +1,458 @@
+/*
+ *  FIPS-180-2 compliant SHA-256 implementation
+ *
+ *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ *  SPDX-License-Identifier: Apache-2.0
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License"); you may
+ *  not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ *  This file is part of mbed TLS (https://tls.mbed.org)
+ */
+/*
+ *  The SHA-256 Secure Hash Standard was published by NIST in 2002.
+ *
+ *  http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
+ */
+
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "mbedtls/config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
+#if defined(MBEDTLS_SHA256_C)
+
+#include "mbedtls/sha256.h"
+
+#include <string.h>
+
+#if defined(MBEDTLS_SELF_TEST)
+#if defined(MBEDTLS_PLATFORM_C)
+#include "mbedtls/platform.h"
+#else
+#include <stdio.h>
+#include <stdlib.h>
+#define mbedtls_printf printf
+#define mbedtls_calloc    calloc
+#define mbedtls_free       free
+#endif /* MBEDTLS_PLATFORM_C */
+#endif /* MBEDTLS_SELF_TEST */
+
+#if !defined(MBEDTLS_SHA256_ALT)
+
+/* 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;
+}
+
+/*
+ * 32-bit integer manipulation macros (big endian)
+ */
+#ifndef GET_UINT32_BE
+#define GET_UINT32_BE(n,b,i)                            \
+do {                                                    \
+    (n) = ( (uint32_t) (b)[(i)    ] << 24 )             \
+        | ( (uint32_t) (b)[(i) + 1] << 16 )             \
+        | ( (uint32_t) (b)[(i) + 2] <<  8 )             \
+        | ( (uint32_t) (b)[(i) + 3]       );            \
+} while( 0 )
+#endif
+
+#ifndef PUT_UINT32_BE
+#define PUT_UINT32_BE(n,b,i)                            \
+do {                                                    \
+    (b)[(i)    ] = (unsigned char) ( (n) >> 24 );       \
+    (b)[(i) + 1] = (unsigned char) ( (n) >> 16 );       \
+    (b)[(i) + 2] = (unsigned char) ( (n) >>  8 );       \
+    (b)[(i) + 3] = (unsigned char) ( (n)       );       \
+} while( 0 )
+#endif
+
+void mbedtls_sha256_init( mbedtls_sha256_context *ctx )
+{
+    memset( ctx, 0, sizeof( mbedtls_sha256_context ) );
+}
+
+void mbedtls_sha256_free( mbedtls_sha256_context *ctx )
+{
+    if( ctx == NULL )
+        return;
+
+    mbedtls_zeroize( ctx, sizeof( mbedtls_sha256_context ) );
+}
+
+void mbedtls_sha256_clone( mbedtls_sha256_context *dst,
+                           const mbedtls_sha256_context *src )
+{
+    *dst = *src;
+}
+
+/*
+ * SHA-256 context setup
+ */
+void mbedtls_sha256_starts( mbedtls_sha256_context *ctx, int is224 )
+{
+    ctx->total[0] = 0;
+    ctx->total[1] = 0;
+
+    if( is224 == 0 )
+    {
+        /* SHA-256 */
+        ctx->state[0] = 0x6A09E667;
+        ctx->state[1] = 0xBB67AE85;
+        ctx->state[2] = 0x3C6EF372;
+        ctx->state[3] = 0xA54FF53A;
+        ctx->state[4] = 0x510E527F;
+        ctx->state[5] = 0x9B05688C;
+        ctx->state[6] = 0x1F83D9AB;
+        ctx->state[7] = 0x5BE0CD19;
+    }
+    else
+    {
+        /* SHA-224 */
+        ctx->state[0] = 0xC1059ED8;
+        ctx->state[1] = 0x367CD507;
+        ctx->state[2] = 0x3070DD17;
+        ctx->state[3] = 0xF70E5939;
+        ctx->state[4] = 0xFFC00B31;
+        ctx->state[5] = 0x68581511;
+        ctx->state[6] = 0x64F98FA7;
+        ctx->state[7] = 0xBEFA4FA4;
+    }
+
+    ctx->is224 = is224;
+}
+
+#if !defined(MBEDTLS_SHA256_PROCESS_ALT)
+static const uint32_t K[] =
+{
+    0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
+    0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
+    0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
+    0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
+    0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
+    0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
+    0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
+    0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
+    0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
+    0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
+    0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
+    0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
+    0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
+    0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
+    0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
+    0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2,
+};
+
+#define  SHR(x,n) ((x & 0xFFFFFFFF) >> n)
+#define ROTR(x,n) (SHR(x,n) | (x << (32 - n)))
+
+#define S0(x) (ROTR(x, 7) ^ ROTR(x,18) ^  SHR(x, 3))
+#define S1(x) (ROTR(x,17) ^ ROTR(x,19) ^  SHR(x,10))
+
+#define S2(x) (ROTR(x, 2) ^ ROTR(x,13) ^ ROTR(x,22))
+#define S3(x) (ROTR(x, 6) ^ ROTR(x,11) ^ ROTR(x,25))
+
+#define F0(x,y,z) ((x & y) | (z & (x | y)))
+#define F1(x,y,z) (z ^ (x & (y ^ z)))
+
+#define R(t)                                    \
+(                                               \
+    W[t] = S1(W[t -  2]) + W[t -  7] +          \
+           S0(W[t - 15]) + W[t - 16]            \
+)
+
+#define P(a,b,c,d,e,f,g,h,x,K)                  \
+{                                               \
+    temp1 = h + S3(e) + F1(e,f,g) + K + x;      \
+    temp2 = S2(a) + F0(a,b,c);                  \
+    d += temp1; h = temp1 + temp2;              \
+}
+
+void mbedtls_sha256_process( mbedtls_sha256_context *ctx, const unsigned char data[64] )
+{
+    uint32_t temp1, temp2, W[64];
+    uint32_t A[8];
+    unsigned int i;
+
+    for( i = 0; i < 8; i++ )
+        A[i] = ctx->state[i];
+
+#if defined(MBEDTLS_SHA256_SMALLER)
+    for( i = 0; i < 64; i++ )
+    {
+        if( i < 16 )
+            GET_UINT32_BE( W[i], data, 4 * i );
+        else
+            R( i );
+
+        P( A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], W[i], K[i] );
+
+        temp1 = A[7]; A[7] = A[6]; A[6] = A[5]; A[5] = A[4]; A[4] = A[3];
+        A[3] = A[2]; A[2] = A[1]; A[1] = A[0]; A[0] = temp1;
+    }
+#else /* MBEDTLS_SHA256_SMALLER */
+    for( i = 0; i < 16; i++ )
+        GET_UINT32_BE( W[i], data, 4 * i );
+
+    for( i = 0; i < 16; i += 8 )
+    {
+        P( A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], W[i+0], K[i+0] );
+        P( A[7], A[0], A[1], A[2], A[3], A[4], A[5], A[6], W[i+1], K[i+1] );
+        P( A[6], A[7], A[0], A[1], A[2], A[3], A[4], A[5], W[i+2], K[i+2] );
+        P( A[5], A[6], A[7], A[0], A[1], A[2], A[3], A[4], W[i+3], K[i+3] );
+        P( A[4], A[5], A[6], A[7], A[0], A[1], A[2], A[3], W[i+4], K[i+4] );
+        P( A[3], A[4], A[5], A[6], A[7], A[0], A[1], A[2], W[i+5], K[i+5] );
+        P( A[2], A[3], A[4], A[5], A[6], A[7], A[0], A[1], W[i+6], K[i+6] );
+        P( A[1], A[2], A[3], A[4], A[5], A[6], A[7], A[0], W[i+7], K[i+7] );
+    }
+
+    for( i = 16; i < 64; i += 8 )
+    {
+        P( A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], R(i+0), K[i+0] );
+        P( A[7], A[0], A[1], A[2], A[3], A[4], A[5], A[6], R(i+1), K[i+1] );
+        P( A[6], A[7], A[0], A[1], A[2], A[3], A[4], A[5], R(i+2), K[i+2] );
+        P( A[5], A[6], A[7], A[0], A[1], A[2], A[3], A[4], R(i+3), K[i+3] );
+        P( A[4], A[5], A[6], A[7], A[0], A[1], A[2], A[3], R(i+4), K[i+4] );
+        P( A[3], A[4], A[5], A[6], A[7], A[0], A[1], A[2], R(i+5), K[i+5] );
+        P( A[2], A[3], A[4], A[5], A[6], A[7], A[0], A[1], R(i+6), K[i+6] );
+        P( A[1], A[2], A[3], A[4], A[5], A[6], A[7], A[0], R(i+7), K[i+7] );
+    }
+#endif /* MBEDTLS_SHA256_SMALLER */
+
+    for( i = 0; i < 8; i++ )
+        ctx->state[i] += A[i];
+}
+#endif /* !MBEDTLS_SHA256_PROCESS_ALT */
+
+/*
+ * SHA-256 process buffer
+ */
+void mbedtls_sha256_update( mbedtls_sha256_context *ctx, const unsigned char *input,
+                    size_t ilen )
+{
+    size_t fill;
+    uint32_t left;
+
+    if( ilen == 0 )
+        return;
+
+    left = ctx->total[0] & 0x3F;
+    fill = 64 - left;
+
+    ctx->total[0] += (uint32_t) ilen;
+    ctx->total[0] &= 0xFFFFFFFF;
+
+    if( ctx->total[0] < (uint32_t) ilen )
+        ctx->total[1]++;
+
+    if( left && ilen >= fill )
+    {
+        memcpy( (void *) (ctx->buffer + left), input, fill );
+        mbedtls_sha256_process( ctx, ctx->buffer );
+        input += fill;
+        ilen  -= fill;
+        left = 0;
+    }
+
+    while( ilen >= 64 )
+    {
+        mbedtls_sha256_process( ctx, input );
+        input += 64;
+        ilen  -= 64;
+    }
+
+    if( ilen > 0 )
+        memcpy( (void *) (ctx->buffer + left), input, ilen );
+}
+
+static const unsigned char sha256_padding[64] =
+{
+ 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+/*
+ * SHA-256 final digest
+ */
+void mbedtls_sha256_finish( mbedtls_sha256_context *ctx, unsigned char output[32] )
+{
+    uint32_t last, padn;
+    uint32_t high, low;
+    unsigned char msglen[8];
+
+    high = ( ctx->total[0] >> 29 )
+         | ( ctx->total[1] <<  3 );
+    low  = ( ctx->total[0] <<  3 );
+
+    PUT_UINT32_BE( high, msglen, 0 );
+    PUT_UINT32_BE( low,  msglen, 4 );
+
+    last = ctx->total[0] & 0x3F;
+    padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );
+
+    mbedtls_sha256_update( ctx, sha256_padding, padn );
+    mbedtls_sha256_update( ctx, msglen, 8 );
+
+    PUT_UINT32_BE( ctx->state[0], output,  0 );
+    PUT_UINT32_BE( ctx->state[1], output,  4 );
+    PUT_UINT32_BE( ctx->state[2], output,  8 );
+    PUT_UINT32_BE( ctx->state[3], output, 12 );
+    PUT_UINT32_BE( ctx->state[4], output, 16 );
+    PUT_UINT32_BE( ctx->state[5], output, 20 );
+    PUT_UINT32_BE( ctx->state[6], output, 24 );
+
+    if( ctx->is224 == 0 )
+        PUT_UINT32_BE( ctx->state[7], output, 28 );
+}
+
+#endif /* !MBEDTLS_SHA256_ALT */
+
+/*
+ * output = SHA-256( input buffer )
+ */
+void mbedtls_sha256( const unsigned char *input, size_t ilen,
+             unsigned char output[32], int is224 )
+{
+    mbedtls_sha256_context ctx;
+
+    mbedtls_sha256_init( &ctx );
+    mbedtls_sha256_starts( &ctx, is224 );
+    mbedtls_sha256_update( &ctx, input, ilen );
+    mbedtls_sha256_finish( &ctx, output );
+    mbedtls_sha256_free( &ctx );
+}
+
+#if defined(MBEDTLS_SELF_TEST)
+/*
+ * FIPS-180-2 test vectors
+ */
+static const unsigned char sha256_test_buf[3][57] =
+{
+    { "abc" },
+    { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" },
+    { "" }
+};
+
+static const int sha256_test_buflen[3] =
+{
+    3, 56, 1000
+};
+
+static const unsigned char sha256_test_sum[6][32] =
+{
+    /*
+     * SHA-224 test vectors
+     */
+    { 0x23, 0x09, 0x7D, 0x22, 0x34, 0x05, 0xD8, 0x22,
+      0x86, 0x42, 0xA4, 0x77, 0xBD, 0xA2, 0x55, 0xB3,
+      0x2A, 0xAD, 0xBC, 0xE4, 0xBD, 0xA0, 0xB3, 0xF7,
+      0xE3, 0x6C, 0x9D, 0xA7 },
+    { 0x75, 0x38, 0x8B, 0x16, 0x51, 0x27, 0x76, 0xCC,
+      0x5D, 0xBA, 0x5D, 0xA1, 0xFD, 0x89, 0x01, 0x50,
+      0xB0, 0xC6, 0x45, 0x5C, 0xB4, 0xF5, 0x8B, 0x19,
+      0x52, 0x52, 0x25, 0x25 },
+    { 0x20, 0x79, 0x46, 0x55, 0x98, 0x0C, 0x91, 0xD8,
+      0xBB, 0xB4, 0xC1, 0xEA, 0x97, 0x61, 0x8A, 0x4B,
+      0xF0, 0x3F, 0x42, 0x58, 0x19, 0x48, 0xB2, 0xEE,
+      0x4E, 0xE7, 0xAD, 0x67 },
+
+    /*
+     * SHA-256 test vectors
+     */
+    { 0xBA, 0x78, 0x16, 0xBF, 0x8F, 0x01, 0xCF, 0xEA,
+      0x41, 0x41, 0x40, 0xDE, 0x5D, 0xAE, 0x22, 0x23,
+      0xB0, 0x03, 0x61, 0xA3, 0x96, 0x17, 0x7A, 0x9C,
+      0xB4, 0x10, 0xFF, 0x61, 0xF2, 0x00, 0x15, 0xAD },
+    { 0x24, 0x8D, 0x6A, 0x61, 0xD2, 0x06, 0x38, 0xB8,
+      0xE5, 0xC0, 0x26, 0x93, 0x0C, 0x3E, 0x60, 0x39,
+      0xA3, 0x3C, 0xE4, 0x59, 0x64, 0xFF, 0x21, 0x67,
+      0xF6, 0xEC, 0xED, 0xD4, 0x19, 0xDB, 0x06, 0xC1 },
+    { 0xCD, 0xC7, 0x6E, 0x5C, 0x99, 0x14, 0xFB, 0x92,
+      0x81, 0xA1, 0xC7, 0xE2, 0x84, 0xD7, 0x3E, 0x67,
+      0xF1, 0x80, 0x9A, 0x48, 0xA4, 0x97, 0x20, 0x0E,
+      0x04, 0x6D, 0x39, 0xCC, 0xC7, 0x11, 0x2C, 0xD0 }
+};
+
+/*
+ * Checkup routine
+ */
+int mbedtls_sha256_self_test( int verbose )
+{
+    int i, j, k, buflen, ret = 0;
+    unsigned char *buf;
+    unsigned char sha256sum[32];
+    mbedtls_sha256_context ctx;
+
+    buf = mbedtls_calloc( 1024, sizeof(unsigned char) );
+    if( NULL == buf )
+    {
+        if( verbose != 0 )
+            mbedtls_printf( "Buffer allocation failed\n" );
+
+        return( 1 );
+    }
+
+    mbedtls_sha256_init( &ctx );
+
+    for( i = 0; i < 6; i++ )
+    {
+        j = i % 3;
+        k = i < 3;
+
+        if( verbose != 0 )
+            mbedtls_printf( "  SHA-%d test #%d: ", 256 - k * 32, j + 1 );
+
+        mbedtls_sha256_starts( &ctx, k );
+
+        if( j == 2 )
+        {
+            memset( buf, 'a', buflen = 1000 );
+
+            for( j = 0; j < 1000; j++ )
+                mbedtls_sha256_update( &ctx, buf, buflen );
+        }
+        else
+            mbedtls_sha256_update( &ctx, sha256_test_buf[j],
+                                 sha256_test_buflen[j] );
+
+        mbedtls_sha256_finish( &ctx, sha256sum );
+
+        if( memcmp( sha256sum, sha256_test_sum[i], 32 - k * 4 ) != 0 )
+        {
+            if( verbose != 0 )
+                mbedtls_printf( "failed\n" );
+
+            ret = 1;
+            goto exit;
+        }
+
+        if( verbose != 0 )
+            mbedtls_printf( "passed\n" );
+    }
+
+    if( verbose != 0 )
+        mbedtls_printf( "\n" );
+
+exit:
+    mbedtls_sha256_free( &ctx );
+    mbedtls_free( buf );
+
+    return( ret );
+}
+
+#endif /* MBEDTLS_SELF_TEST */
+
+#endif /* MBEDTLS_SHA256_C */

+ 7 - 2
Pal/src/host/Linux-SGX/crypto/rsa.c → Pal/lib/crypto/rsa.c

@@ -23,7 +23,12 @@
 #include "error-crypt.h"
 #include "api.h"
 
+#ifdef IN_PAL
 int _DkRandomBitsRead (void  *buffer, int size);
+#define DkRandomBitsRead _DkRandomBitsRead
+#else
+int DkRandomBitsRead (void  *buffer, int size);
+#endif
 
 void * malloc (int size);
 void free (void * mem);
@@ -95,7 +100,7 @@ static int RSAPad(const byte *input, word32 inputLen, byte *pkcsBlock,
     else {
         /* pad with non-zero random bytes */
         word32 padLen = pkcsBlockLen - inputLen - 1, i;
-        int    ret    = _DkRandomBitsRead(&pkcsBlock[1], padLen);
+        int    ret    = DkRandomBitsRead(&pkcsBlock[1], padLen);
 
         if (ret < 0)
             return ret;
@@ -454,7 +459,7 @@ static int rand_prime(mp_int *N, int len)
 
     do {
         /* generate value */
-        err = _DkRandomBitsRead(buf, len);
+        err = DkRandomBitsRead(buf, len);
         if (err < 0) {
             XFREE(buf);
             return err;

+ 0 - 0
Pal/src/host/Linux-SGX/crypto/rsa.h → Pal/lib/crypto/rsa.h


+ 0 - 0
Pal/src/host/Linux-SGX/crypto/udivmodti4.c → Pal/lib/crypto/udivmodti4.c


+ 63 - 0
Pal/lib/pal_crypto.h

@@ -0,0 +1,63 @@
+/* Copyright (C) 2014 OSCAR lab, Stony Brook University
+   Copyright (C) 2017 Fortanix, Inc.
+
+   This file is part of Graphene Library OS.
+
+   Graphene Library OS is free software: you can redistribute it and/or
+   modify it under the terms of the GNU General Public License
+   as published by the Free Software Foundation, either version 3 of the
+   License, or (at your option) any later version.
+
+   Graphene Library OS is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+/*
+ * Cryptographic primitive abstractions. This layer provides a way to
+ * change the crypto library without changing the rest of Graphene code 
+ * by providing a small crypto library adaptor implementing these methods.
+ */
+
+#ifndef PAL_CRYPTO_H
+#define PAL_CRYPTO_H
+
+/*
+ * You can change which crypto library will be used by changing this
+ * define. Currently supported options:
+ * - wolfSSL
+ */
+#define PAL_CRYPTO_PROVIDER PAL_CRYPTO_MBEDTLS
+
+/* These cryptosystems are still unconditionally provided by WolfSSL. */
+#include "crypto/cmac.h"
+#include "crypto/dh.h"
+#include "crypto/rsa.h"
+
+#define PAL_CRYPTO_WOLFSSL 1
+#define PAL_CRYPTO_MBEDTLS 2
+
+#define SHA256_DIGEST_LEN 32
+
+#if PAL_CRYPTO_PROVIDER == PAL_CRYPTO_WOLFSSL
+#include "crypto/sha256.h"
+typedef SHA256 PAL_SHA256_CONTEXT;
+
+#elif PAL_CRYPTO_PROVIDER == PAL_CRYPTO_MBEDTLS
+#include "crypto/mbedtls/mbedtls/sha256.h"
+typedef mbedtls_sha256_context PAL_SHA256_CONTEXT;
+
+#else
+# error "Unknown crypto provider. Set PAL_CRYPTO_PROVIDER in pal_crypto.h"
+#endif
+
+int DkSHA256Init(PAL_SHA256_CONTEXT *context);
+int DkSHA256Update(PAL_SHA256_CONTEXT *context, const uint8_t *data,
+                   PAL_NUM len);
+int DkSHA256Final(PAL_SHA256_CONTEXT *context, uint8_t *output);
+                  
+
+#endif

+ 2 - 3
Pal/src/host/Linux-SGX/Makefile

@@ -9,9 +9,8 @@ defs	= -DIN_PAL -DPAL_DIR=$(PAL_DIR) -DRUNTIME_DIR=$(RUNTIME_DIR)
 enclave-objs = $(addprefix db_,files devices pipes sockets streams memory \
 		 threading semaphore mutex events process object main rtld \
 		 exception misc ipc spinlock) \
-	       $(addprefix enclave_,ocalls ecalls framework pages untrusted) \
-	       $(patsubst %.c,%,$(wildcard crypto/*.c))
-enclave-asm-objs = enclave_entry $(patsubst %.S,%,$(wildcard crypto/*.S))
+	       $(addprefix enclave_,ocalls ecalls framework pages untrusted) 
+enclave-asm-objs = enclave_entry 
 urts-objs = $(addprefix sgx_,enclave framework main rtld thread process exception graphene)
 urts-asm-objs = sgx_entry
 graphene_lib = ../../.lib/graphene-lib.a

+ 2 - 2
Pal/src/host/Linux-SGX/Makefile.am

@@ -18,8 +18,8 @@ ARFLAGS	=
 
 pal_loader = $(HOST_DIR)/pal-sgx
 pal_sec =
-pal_lib = libpal-enclave.so
+pal_lib = libpal.so
 pal_lib_deps = $(HOST_DIR)/enclave.lds $(HOST_DIR)/pal.map
-pal_lib_post = libpal.so
 pal_static = libpal.a
 pal_gdb = $(HOST_DIR)/debugger/gdb
+pal_signer = pal-sgx-get-token pal-sgx-sign aesm_pb2.py

+ 0 - 238
Pal/src/host/Linux-SGX/crypto/sha256.c

@@ -1,238 +0,0 @@
-/* -*- mode:c; c-file-style:"k&r"; c-basic-offset: 4; tab-width:4; indent-tabs-mode:nil; mode:auto-fill; fill-column:78; -*- */
-/* vim: set ts=4 sw=4 et tw=78 fo=cqt wm=0: */
-
-/* sha256.c
- *
- * Copyright (C) 2006-2014 wolfSSL Inc.
- *
- * This file is part of CyaSSL.
- *
- * CyaSSL is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * CyaSSL is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-#include "sha256.h"
-#include "api.h"
-
-#define XMEMSET memset
-#define XMEMCPY memcpy
-
-#ifndef rotlFixed
-static inline word32 rotlFixed(word32 x, word32 y)
-{
-    return (x << y) | (x >> (sizeof(y) * 8 - y));
-}
-#endif /* rotlFixed */
-
-#ifndef rotrFixed
-static inline word32 rotrFixed(word32 x, word32 y)
-{
-    return (x >> y) | (x << (sizeof(y) * 8 - y));
-}
-#endif /* rotrFixed */
-
-#ifndef min
-static inline word32 min(word32 a, word32 b)
-{
-     return a > b ? b : a;
-}
-#endif /* min */
-
-static inline word32 ByteReverseWord32(word32 value)
-{
-    /* 6 instructions with rotate instruction, 8 without */
-    value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
-    return rotlFixed(value, 16U);
-}
-
-static inline void ByteReverseWords(word32 *out, const word32 *in,
-                                    word32 byteCount)
-{
-    word32 count = byteCount/(word32)sizeof(word32), i;
-
-    for (i = 0; i < count; i++)
-        out[i] = ByteReverseWord32(in[i]);
-}
-
-int SHA256Init(SHA256 *sha256)
-{
-    sha256->digest[0] = 0x6A09E667L;
-    sha256->digest[1] = 0xBB67AE85L;
-    sha256->digest[2] = 0x3C6EF372L;
-    sha256->digest[3] = 0xA54FF53AL;
-    sha256->digest[4] = 0x510E527FL;
-    sha256->digest[5] = 0x9B05688CL;
-    sha256->digest[6] = 0x1F83D9ABL;
-    sha256->digest[7] = 0x5BE0CD19L;
-
-    sha256->buffLen = 0;
-    sha256->loLen   = 0;
-    sha256->hiLen   = 0;
-
-    return 0;
-}
-
-#define XTRANSFORM(S,B)  Transform((S))
-
-static const word32 K[64] = {
-    0x428A2F98L, 0x71374491L, 0xB5C0FBCFL, 0xE9B5DBA5L, 0x3956C25BL,
-    0x59F111F1L, 0x923F82A4L, 0xAB1C5ED5L, 0xD807AA98L, 0x12835B01L,
-    0x243185BEL, 0x550C7DC3L, 0x72BE5D74L, 0x80DEB1FEL, 0x9BDC06A7L,
-    0xC19BF174L, 0xE49B69C1L, 0xEFBE4786L, 0x0FC19DC6L, 0x240CA1CCL,
-    0x2DE92C6FL, 0x4A7484AAL, 0x5CB0A9DCL, 0x76F988DAL, 0x983E5152L,
-    0xA831C66DL, 0xB00327C8L, 0xBF597FC7L, 0xC6E00BF3L, 0xD5A79147L,
-    0x06CA6351L, 0x14292967L, 0x27B70A85L, 0x2E1B2138L, 0x4D2C6DFCL,
-    0x53380D13L, 0x650A7354L, 0x766A0ABBL, 0x81C2C92EL, 0x92722C85L,
-    0xA2BFE8A1L, 0xA81A664BL, 0xC24B8B70L, 0xC76C51A3L, 0xD192E819L,
-    0xD6990624L, 0xF40E3585L, 0x106AA070L, 0x19A4C116L, 0x1E376C08L,
-    0x2748774CL, 0x34B0BCB5L, 0x391C0CB3L, 0x4ED8AA4AL, 0x5B9CCA4FL,
-    0x682E6FF3L, 0x748F82EEL, 0x78A5636FL, 0x84C87814L, 0x8CC70208L,
-    0x90BEFFFAL, 0xA4506CEBL, 0xBEF9A3F7L, 0xC67178F2L
-};
-
-#define Ch(x,y,z)       (z ^ (x & (y ^ z)))
-#define Maj(x,y,z)      (((x | y) & z) | (x & y))
-#define S(x, n)         rotrFixed(x, n)
-#define R(x, n)         (((x)&0xFFFFFFFFU)>>(n))
-#define Sigma0(x)       (S(x, 2) ^ S(x, 13) ^ S(x, 22))
-#define Sigma1(x)       (S(x, 6) ^ S(x, 11) ^ S(x, 25))
-#define Gamma0(x)       (S(x, 7) ^ S(x, 18) ^ R(x, 3))
-#define Gamma1(x)       (S(x, 17) ^ S(x, 19) ^ R(x, 10))
-
-#define RND(a,b,c,d,e,f,g,h,i) \
-     t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \
-     t1 = Sigma0(a) + Maj(a, b, c); \
-     d += t0; \
-     h  = t0 + t1;
-
-
-static int Transform(SHA256 *sha256)
-{
-    word32 S[8], t0, t1;
-    int i;
-
-    word32 W[64];
-
-    /* Copy context->state[] to working vars */
-    for (i = 0; i < 8; i++)
-        S[i] = sha256->digest[i];
-
-    for (i = 0; i < 16; i++)
-        W[i] = sha256->buffer[i];
-
-    for (i = 16; i < 64; i++)
-        W[i] = Gamma1(W[i-2]) + W[i-7] + Gamma0(W[i-15]) + W[i-16];
-
-    for (i = 0; i < 64; i += 8) {
-        RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i+0);
-        RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],i+1);
-        RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],i+2);
-        RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],i+3);
-        RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],i+4);
-        RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],i+5);
-        RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],i+6);
-        RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],i+7);
-    }
-
-    /* Add the working vars back into digest state[] */
-    for (i = 0; i < 8; i++) {
-        sha256->digest[i] += S[i];
-    }
-
-    return 0;
-}
-
-static inline void AddLength(SHA256 *sha256, word32 len)
-{
-    word32 tmp = sha256->loLen;
-    if ( (sha256->loLen += len) < tmp)
-        sha256->hiLen++;                       /* carry low to high */
-}
-
-int SHA256Update(SHA256 *sha256, const byte *data, word32 len)
-{
-    /* do block size increments */
-    byte *local = (byte*)sha256->buffer;
-
-    while (len) {
-        word32 add = min(len, SHA256_BLOCK_SIZE - sha256->buffLen);
-        XMEMCPY(&local[sha256->buffLen], data, add);
-
-        sha256->buffLen += add;
-        data            += add;
-        len             -= add;
-
-        if (sha256->buffLen == SHA256_BLOCK_SIZE) {
-            int ret;
-
-            ByteReverseWords(sha256->buffer, sha256->buffer,
-                             SHA256_BLOCK_SIZE);
-
-            ret = XTRANSFORM(sha256, local);
-            if (ret != 0)
-                return ret;
-
-            AddLength(sha256, SHA256_BLOCK_SIZE);
-            sha256->buffLen = 0;
-        }
-    }
-
-    return 0;
-}
-
-int SHA256Final(SHA256 *sha256, byte *hash)
-{
-    byte *local = (byte*)sha256->buffer;
-    int ret;
-
-    AddLength(sha256, sha256->buffLen);  /* before adding pads */
-
-    local[sha256->buffLen++] = 0x80;     /* add 1 */
-
-    /* pad with zeros */
-    if (sha256->buffLen > SHA256_PAD_SIZE) {
-        XMEMSET(&local[sha256->buffLen], 0, SHA256_BLOCK_SIZE - sha256->buffLen);
-        sha256->buffLen += SHA256_BLOCK_SIZE - sha256->buffLen;
-
-        ByteReverseWords(sha256->buffer, sha256->buffer, SHA256_BLOCK_SIZE);
-
-        ret = XTRANSFORM(sha256, local);
-        if (ret != 0)
-            return ret;
-
-        sha256->buffLen = 0;
-    }
-    XMEMSET(&local[sha256->buffLen], 0, SHA256_PAD_SIZE - sha256->buffLen);
-
-    /* put lengths in bits */
-    sha256->hiLen = (sha256->loLen >> (8*sizeof(sha256->loLen) - 3)) +
-                 (sha256->hiLen << 3);
-    sha256->loLen = sha256->loLen << 3;
-
-    /* store lengths */
-    ByteReverseWords(sha256->buffer, sha256->buffer, SHA256_BLOCK_SIZE);
-    /* ! length ordering dependent on digest endian type ! */
-    XMEMCPY(&local[SHA256_PAD_SIZE], &sha256->hiLen, sizeof(word32));
-    XMEMCPY(&local[SHA256_PAD_SIZE + sizeof(word32)], &sha256->loLen,
-            sizeof(word32));
-
-    ret = XTRANSFORM(sha256, local);
-    if (ret != 0)
-        return ret;
-
-    ByteReverseWords(sha256->digest, sha256->digest, SHA256_DIGEST_SIZE);
-    XMEMCPY(hash, sha256->digest, SHA256_DIGEST_SIZE);
-
-    return SHA256Init(sha256);  /* reset state */
-}

+ 0 - 50
Pal/src/host/Linux-SGX/crypto/sha256.h

@@ -1,50 +0,0 @@
-/* -*- mode:c; c-file-style:"k&r"; c-basic-offset: 4; tab-width:4; indent-tabs-mode:nil; mode:auto-fill; fill-column:78; -*- */
-/* vim: set ts=4 sw=4 et tw=78 fo=cqt wm=0: */
-
-/* sha256.h
- *
- * Copyright (C) 2006-2014 wolfSSL Inc.
- *
- * This file is part of CyaSSL.
- *
- * CyaSSL is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * CyaSSL is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-#ifndef CTAO_CRYPT_SHA256_H
-#define CTAO_CRYPT_SHA256_H
-
-#include "crypto/integer.h"
-
-/* in bytes */
-enum {
-    SHA256_BLOCK_SIZE   = 64,
-    SHA256_DIGEST_SIZE  = 32,
-    SHA256_PAD_SIZE     = 56
-};
-
-/* SHA256 digest */
-typedef struct SHA256 {
-    word32  buffLen;   /* in bytes          */
-    word32  loLen;     /* length in bytes   */
-    word32  hiLen;     /* length in bytes   */
-    word32  digest[SHA256_DIGEST_SIZE / sizeof(word32)];
-    word32  buffer[SHA256_BLOCK_SIZE  / sizeof(word32)];
-} SHA256;
-
-int SHA256Init(SHA256 *);
-int SHA256Update(SHA256 *, const byte *, word32);
-int SHA256Final(SHA256 *, byte *);
-
-#endif /* CTAO_CRYPT_SHA256_H */

+ 0 - 326
Pal/src/host/Linux-SGX/crypto/sha512.c

@@ -1,326 +0,0 @@
-/* sha512.c
- *
- * Copyright (C) 2006-2014 wolfSSL Inc.
- *
- * This file is part of CyaSSL.
- *
- * CyaSSL is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * CyaSSL is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-#include "sha512.h"
-#include "api.h"
-
-#define XMEMSET memset
-#define XMEMCPY memcpy
-
-#ifndef rotlFixed64
-static inline word64 rotlFixed64(word64 x, word64 y)
-{
-    return (x << y) | (x >> (sizeof(y) * 8 - y));
-}
-#endif /* rotlFixed64 */
-
-#ifndef rotrFixed64
-static inline word64 rotrFixed64(word64 x, word64 y)
-{
-    return (x >> y) | (x << (sizeof(y) * 8 - y));
-}
-#endif /* rotrFixed */
-
-
-#ifndef min
-static inline word32 min(word32 a, word32 b)
-{
-    return a > b ? b : a;
-}
-#endif /* min64 */
-
-
-int SHA512Init(SHA512 * sha512)
-{
-    sha512->digest[0] = W64LIT(0x6a09e667f3bcc908);
-    sha512->digest[1] = W64LIT(0xbb67ae8584caa73b);
-    sha512->digest[2] = W64LIT(0x3c6ef372fe94f82b);
-    sha512->digest[3] = W64LIT(0xa54ff53a5f1d36f1);
-    sha512->digest[4] = W64LIT(0x510e527fade682d1);
-    sha512->digest[5] = W64LIT(0x9b05688c2b3e6c1f);
-    sha512->digest[6] = W64LIT(0x1f83d9abfb41bd6b);
-    sha512->digest[7] = W64LIT(0x5be0cd19137e2179);
-
-    sha512->buffLen = 0;
-    sha512->loLen   = 0;
-    sha512->hiLen   = 0;
-
-    return 0;
-}
-
-
-static const word64 K512[80] = {
-	W64LIT(0x428a2f98d728ae22), W64LIT(0x7137449123ef65cd),
-	W64LIT(0xb5c0fbcfec4d3b2f), W64LIT(0xe9b5dba58189dbbc),
-	W64LIT(0x3956c25bf348b538), W64LIT(0x59f111f1b605d019),
-	W64LIT(0x923f82a4af194f9b), W64LIT(0xab1c5ed5da6d8118),
-	W64LIT(0xd807aa98a3030242), W64LIT(0x12835b0145706fbe),
-	W64LIT(0x243185be4ee4b28c), W64LIT(0x550c7dc3d5ffb4e2),
-	W64LIT(0x72be5d74f27b896f), W64LIT(0x80deb1fe3b1696b1),
-	W64LIT(0x9bdc06a725c71235), W64LIT(0xc19bf174cf692694),
-	W64LIT(0xe49b69c19ef14ad2), W64LIT(0xefbe4786384f25e3),
-	W64LIT(0x0fc19dc68b8cd5b5), W64LIT(0x240ca1cc77ac9c65),
-	W64LIT(0x2de92c6f592b0275), W64LIT(0x4a7484aa6ea6e483),
-	W64LIT(0x5cb0a9dcbd41fbd4), W64LIT(0x76f988da831153b5),
-	W64LIT(0x983e5152ee66dfab), W64LIT(0xa831c66d2db43210),
-	W64LIT(0xb00327c898fb213f), W64LIT(0xbf597fc7beef0ee4),
-	W64LIT(0xc6e00bf33da88fc2), W64LIT(0xd5a79147930aa725),
-	W64LIT(0x06ca6351e003826f), W64LIT(0x142929670a0e6e70),
-	W64LIT(0x27b70a8546d22ffc), W64LIT(0x2e1b21385c26c926),
-	W64LIT(0x4d2c6dfc5ac42aed), W64LIT(0x53380d139d95b3df),
-	W64LIT(0x650a73548baf63de), W64LIT(0x766a0abb3c77b2a8),
-	W64LIT(0x81c2c92e47edaee6), W64LIT(0x92722c851482353b),
-	W64LIT(0xa2bfe8a14cf10364), W64LIT(0xa81a664bbc423001),
-	W64LIT(0xc24b8b70d0f89791), W64LIT(0xc76c51a30654be30),
-	W64LIT(0xd192e819d6ef5218), W64LIT(0xd69906245565a910),
-	W64LIT(0xf40e35855771202a), W64LIT(0x106aa07032bbd1b8),
-	W64LIT(0x19a4c116b8d2d0c8), W64LIT(0x1e376c085141ab53),
-	W64LIT(0x2748774cdf8eeb99), W64LIT(0x34b0bcb5e19b48a8),
-	W64LIT(0x391c0cb3c5c95a63), W64LIT(0x4ed8aa4ae3418acb),
-	W64LIT(0x5b9cca4f7763e373), W64LIT(0x682e6ff3d6b2b8a3),
-	W64LIT(0x748f82ee5defb2fc), W64LIT(0x78a5636f43172f60),
-	W64LIT(0x84c87814a1f0ab72), W64LIT(0x8cc702081a6439ec),
-	W64LIT(0x90befffa23631e28), W64LIT(0xa4506cebde82bde9),
-	W64LIT(0xbef9a3f7b2c67915), W64LIT(0xc67178f2e372532b),
-	W64LIT(0xca273eceea26619c), W64LIT(0xd186b8c721c0c207),
-	W64LIT(0xeada7dd6cde0eb1e), W64LIT(0xf57d4f7fee6ed178),
-	W64LIT(0x06f067aa72176fba), W64LIT(0x0a637dc5a2c898a6),
-	W64LIT(0x113f9804bef90dae), W64LIT(0x1b710b35131c471b),
-	W64LIT(0x28db77f523047d84), W64LIT(0x32caab7b40c72493),
-	W64LIT(0x3c9ebe0a15c9bebc), W64LIT(0x431d67c49c100d4c),
-	W64LIT(0x4cc5d4becb3e42b6), W64LIT(0x597f299cfc657e2a),
-	W64LIT(0x5fcb6fab3ad6faec), W64LIT(0x6c44198c4a475817)
-};
-
-
-#define blk0(i) (W[i] = sha512->buffer[i])
-#define blk2(i) (W[i&15]+=s1(W[(i-2)&15])+W[(i-7)&15]+s0(W[(i-15)&15]))
-
-#define Ch(x,y,z) (z^(x&(y^z)))
-#define Maj(x,y,z) ((x&y)|(z&(x|y)))
-
-#define a(i) T[(0-i)&7]
-#define b(i) T[(1-i)&7]
-#define c(i) T[(2-i)&7]
-#define d(i) T[(3-i)&7]
-#define e(i) T[(4-i)&7]
-#define f(i) T[(5-i)&7]
-#define g(i) T[(6-i)&7]
-#define h(i) T[(7-i)&7]
-
-#define S0(x) (rotrFixed64(x,28)^rotrFixed64(x,34)^rotrFixed64(x,39))
-#define S1(x) (rotrFixed64(x,14)^rotrFixed64(x,18)^rotrFixed64(x,41))
-#define s0(x) (rotrFixed64(x,1)^rotrFixed64(x,8)^(x>>7))
-#define s1(x) (rotrFixed64(x,19)^rotrFixed64(x,61)^(x>>6))
-
-#define R(i) h(i)+=S1(e(i))+Ch(e(i),f(i),g(i))+K[i+j]+(j?blk2(i):blk0(i));\
-	d(i)+=h(i);h(i)+=S0(a(i))+Maj(a(i),b(i),c(i))
-
-#define blk384(i) (W[i] = sha384->buffer[i])
-
-#define R2(i) h(i)+=S1(e(i))+Ch(e(i),f(i),g(i))+K[i+j]+(j?blk2(i):blk384(i));\
-	d(i)+=h(i);h(i)+=S0(a(i))+Maj(a(i),b(i),c(i))
-
-
-static int Transform(SHA512 * sha512)
-{
-    const word64* K = K512;
-
-    word32 j;
-    word64 T[8];
-
-#ifdef CYASSL_SMALL_STACK
-    word64* W;
-
-    W = (word64*) XMALLOC(sizeof(word64) * 16, NULL, DYNAMIC_TYPE_TMP_BUFFER);
-    if (W == NULL)
-        return MEMORY_E;
-#else
-    word64 W[16];
-#endif
-
-    /* Copy digest to working vars */
-    XMEMCPY(T, sha512->digest, sizeof(T));
-
-#ifdef USE_SLOW_SHA2
-    /* over twice as small, but 50% slower */
-    /* 80 operations, not unrolled */
-    for (j = 0; j < 80; j += 16) {
-        int m; 
-        for (m = 0; m < 16; m++) { /* braces needed here for macros {} */
-            R(m);
-        }
-    }
-#else
-    /* 80 operations, partially loop unrolled */
-    for (j = 0; j < 80; j += 16) {
-        R( 0); R( 1); R( 2); R( 3);
-        R( 4); R( 5); R( 6); R( 7);
-        R( 8); R( 9); R(10); R(11);
-        R(12); R(13); R(14); R(15);
-    }
-#endif /* USE_SLOW_SHA2 */
-
-    /* Add the working vars back into digest */
-
-    sha512->digest[0] += a(0);
-    sha512->digest[1] += b(0);
-    sha512->digest[2] += c(0);
-    sha512->digest[3] += d(0);
-    sha512->digest[4] += e(0);
-    sha512->digest[5] += f(0);
-    sha512->digest[6] += g(0);
-    sha512->digest[7] += h(0);
-
-    /* Wipe variables */
-    XMEMSET(W, 0, sizeof(word64) * 16);
-    XMEMSET(T, 0, sizeof(T));
-
-#ifdef CYASSL_SMALL_STACK
-    XFREE(W, NULL, DYNAMIC_TYPE_TMP_BUFFER);
-#endif
-
-    return 0;
-}
-
-
-static inline void AddLength(SHA512 * sha512, word32 len)
-{
-    word32 tmp = sha512->loLen;
-    if ( (sha512->loLen += len) < tmp)
-        sha512->hiLen++;                       /* carry low to high */
-}
-
-
-int SHA512Update(SHA512 * sha512, const byte * data, word32 len)
-{
-    /* do block size increments */
-    byte * local = (byte *)sha512->buffer;
-
-    while (len) {
-        word32 add = min(len, SHA512_BLOCK_SIZE - sha512->buffLen);
-        XMEMCPY(&local[sha512->buffLen], data, add);
-
-        sha512->buffLen += add;
-        data         += add;
-        len          -= add;
-
-        if (sha512->buffLen == SHA512_BLOCK_SIZE) {
-            int ret;
-
-            #ifdef LITTLE_ENDIAN_ORDER
-                ByteReverseWords64(sha512->buffer, sha512->buffer,
-                                   SHA512_BLOCK_SIZE);
-            #endif
-            ret = Transform(sha512);
-            if (ret != 0)
-                return ret;
-
-            AddLength(sha512, SHA512_BLOCK_SIZE);
-            sha512->buffLen = 0;
-        }
-    }
-    return 0;
-}
-
-
-int SHA512Final(SHA512 * sha512, byte * hash)
-{
-    byte * local = (byte*)sha512->buffer;
-    int ret;
-
-    AddLength(sha512, sha512->buffLen);               /* before adding pads */
-
-    local[sha512->buffLen++] = 0x80;  /* add 1 */
-
-    /* pad with zeros */
-    if (sha512->buffLen > SHA512_PAD_SIZE) {
-        XMEMSET(&local[sha512->buffLen], 0, SHA512_BLOCK_SIZE -sha512->buffLen);
-        sha512->buffLen += SHA512_BLOCK_SIZE - sha512->buffLen;
-
-        #ifdef LITTLE_ENDIAN_ORDER
-            ByteReverseWords64(sha512->buffer,sha512->buffer,SHA512_BLOCK_SIZE);
-        #endif
-        ret = Transform(sha512);
-        if (ret != 0)
-            return ret;
-
-        sha512->buffLen = 0;
-    }
-    XMEMSET(&local[sha512->buffLen], 0, SHA512_PAD_SIZE - sha512->buffLen);
-
-    /* put lengths in bits */
-    sha512->hiLen = (sha512->loLen >> (8*sizeof(sha512->loLen) - 3)) + 
-                 (sha512->hiLen << 3);
-    sha512->loLen = sha512->loLen << 3;
-
-    /* store lengths */
-    #ifdef LITTLE_ENDIAN_ORDER
-        ByteReverseWords64(sha512->buffer, sha512->buffer, SHA512_PAD_SIZE);
-    #endif
-    /* ! length ordering dependent on digest endian type ! */
-    sha512->buffer[SHA512_BLOCK_SIZE / sizeof(word64) - 2] = sha512->hiLen;
-    sha512->buffer[SHA512_BLOCK_SIZE / sizeof(word64) - 1] = sha512->loLen;
-
-    ret = Transform(sha512);
-    if (ret != 0)
-        return ret;
-
-    #ifdef LITTLE_ENDIAN_ORDER
-        ByteReverseWords64(sha512->digest, sha512->digest, SHA512_DIGEST_SIZE);
-    #endif
-    XMEMCPY(hash, sha512->digest, SHA512_DIGEST_SIZE);
-
-    return SHA512Init(sha512);  /* reset state */
-}
-
-
-int SHA512Hash(const byte * data, word32 len, byte * hash)
-{
-    int ret = 0;
-#ifdef CYASSL_SMALL_STACK
-    SHA512* sha512;
-#else
-    SHA512 sha512[1];
-#endif
-
-#ifdef CYASSL_SMALL_STACK
-    sha512 = (SHA512*)XMALLOC(sizeof(SHA512), NULL, DYNAMIC_TYPE_TMP_BUFFER);
-    if (sha512 == NULL)
-        return MEMORY_E;
-#endif
-
-    if ((ret = SHA512Init(sha512)) != 0) {
-        printf("SHA512Init failed");
-    }
-    else if ((ret = SHA512Update(sha512, data, len)) != 0) {
-        printf("SHA512Update failed");
-    }
-    else if ((ret = SHA512Final(sha512, hash)) != 0) {
-        printf("SHA512Final failed");
-    }
-
-#ifdef CYASSL_SMALL_STACK
-    XFREE(sha512, NULL, DYNAMIC_TYPE_TMP_BUFFER);
-#endif
-
-    return ret;
-}

+ 0 - 58
Pal/src/host/Linux-SGX/crypto/sha512.h

@@ -1,58 +0,0 @@
-/* sha512.h
- *
- * Copyright (C) 2006-2014 wolfSSL Inc.
- *
- * This file is part of CyaSSL.
- *
- * CyaSSL is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * CyaSSL is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-
-#ifndef CTAO_CRYPT_SHA512_H
-#define CTAO_CRYPT_SHA512_H
-
-#include <stdint.h>
-
-#ifndef W64LIT
-#define WORD64_AVAILABLE
-#define W64LIT(x) x##LL
-#endif
-
-#include "crypto/integer.h"
-
-/* in bytes */
-enum {
-    SHA512_BLOCK_SIZE   = 128,
-    SHA512_DIGEST_SIZE  =  64,
-    SHA512_PAD_SIZE     = 112 
-};
-
-
-/* SHA512 digest */
-typedef struct SHA512 {
-    word32  buffLen;   /* in bytes          */
-    word32  loLen;     /* length in bytes   */
-    word32  hiLen;     /* length in bytes   */
-    word64  digest[SHA512_DIGEST_SIZE / sizeof(word64)];
-    word64  buffer[SHA512_BLOCK_SIZE  / sizeof(word64)];
-} SHA512;
-
-
-int SHA512Init(SHA512 *);
-int SHA512Update(SHA512 *, const byte *, word32);
-int SHA512Final(SHA512 *, byte *);
-int SHA512Hash(const byte *, word32, byte *);
-
-#endif /* CTAO_CRYPT_SHA512_H */

+ 3 - 3
Pal/src/host/Linux-SGX/db_files.c

@@ -65,7 +65,7 @@ static int file_open (PAL_HANDLE * handle, const char * type, const char * uri,
     get_norm_path(uri, path, 0, len + 1);
     hdl->file.realpath = (PAL_STR) path;
 
-    sgx_stub_t * stubs;
+    sgx_arch_mac_t * stubs;
     uint64_t total;
     int ret = load_trusted_file(hdl, &stubs, &total);
     if (ret < 0) {
@@ -86,7 +86,7 @@ static int file_open (PAL_HANDLE * handle, const char * type, const char * uri,
 static int file_read (PAL_HANDLE handle, int offset, int count,
                       void * buffer)
 {
-    sgx_stub_t * stubs = (sgx_stub_t *) handle->file.stubs;
+    sgx_arch_mac_t * stubs = (sgx_arch_mac_t *) handle->file.stubs;
     unsigned int total = handle->file.total;
     int ret;
 
@@ -179,7 +179,7 @@ static int file_delete (PAL_HANDLE handle, int access)
 static int file_map (PAL_HANDLE handle, void ** addr, int prot,
                      uint64_t offset, uint64_t size)
 {
-    sgx_stub_t * stubs = (sgx_stub_t *) handle->file.stubs;
+    sgx_arch_mac_t * stubs = (sgx_arch_mac_t *) handle->file.stubs;
     unsigned int total = handle->file.total;
     void * mem = *addr;
     void * umem;

+ 3 - 1
Pal/src/host/Linux-SGX/db_main.c

@@ -120,6 +120,8 @@ static int loader_filter (const char * key, int len)
     return 1;
 }
 
+extern void * enclave_base;
+
 void pal_linux_main(const char ** arguments, const char ** environments,
                     struct pal_sec * sec_info)
 {
@@ -207,7 +209,7 @@ void pal_linux_main(const char ** arguments, const char ** environments,
     PAL_HANDLE first_thread = malloc(HANDLE_SIZE(thread));
     SET_HANDLE_TYPE(first_thread, thread);
     first_thread->thread.tcs =
-        pal_enclave.enclave_base + GET_ENCLAVE_TLS(tcs_offset);
+        enclave_base + GET_ENCLAVE_TLS(tcs_offset);
     SET_ENCLAVE_TLS(thread, (__pal_control.first_thread = first_thread));
 
     /* call main function */

+ 1 - 2
Pal/src/host/Linux-SGX/db_process.c

@@ -36,6 +36,7 @@
 #include "pal_debug.h"
 #include "pal_error.h"
 #include "pal_security.h"
+#include "pal_crypto.h"
 #include "api.h"
 
 #include <linux/sched.h>
@@ -140,8 +141,6 @@ struct check_child_param {
     const char *    uri;
 };
 
-#include "crypto/cmac.h"
-
 static int check_child_mrenclave (sgx_arch_hash_t * mrenclave,
                                   void * signed_data, void * check_param)
 {

+ 3 - 1
Pal/src/host/Linux-SGX/db_threading.c

@@ -49,6 +49,8 @@ struct thread_param {
     const void * param;
 };
 
+extern void * enclave_base;
+
 void pal_start_thread (void)
 {
     PAL_HANDLE new_thread = NULL, tmp;
@@ -58,7 +60,7 @@ void pal_start_thread (void)
         if (!tmp->thread.tcs) {
             new_thread = tmp;
             new_thread->thread.tcs =
-                pal_enclave.enclave_base + GET_ENCLAVE_TLS(tcs_offset);
+                enclave_base + GET_ENCLAVE_TLS(tcs_offset);
             break;
         }
     _DkInternalUnlock(&thread_list_lock);

+ 6 - 4
Pal/src/host/Linux-SGX/enclave_ecalls.c

@@ -15,15 +15,17 @@ void pal_linux_main (const char ** arguments, const char ** environments,
 
 void pal_start_thread (void);
 
+extern void * enclave_base, * enclave_top;
+
 int handle_ecall (long ecall_index, void * ecall_args, void * exit_target,
-                  void * untrusted_stack, void * enclave_base)
+                  void * untrusted_stack, void * enclave_base_addr)
 {
     if (ecall_index < 0 || ecall_index >= ECALL_NR)
         return -PAL_ERROR_INVAL;
 
-    if (!pal_enclave.enclave_base) {
-        pal_enclave.enclave_base = enclave_base;
-        pal_enclave.enclave_size = GET_ENCLAVE_TLS(enclave_size);
+    if (!enclave_base) {
+        enclave_base = enclave_base_addr;
+        enclave_top = enclave_base_addr + GET_ENCLAVE_TLS(enclave_size);
     }
 
     if (sgx_is_within_enclave(exit_target, 0))

+ 40 - 51
Pal/src/host/Linux-SGX/enclave_framework.c

@@ -5,18 +5,22 @@
 #include <pal_internal.h>
 #include <pal_debug.h>
 #include <pal_security.h>
+#include <pal_crypto.h>
 #include <api.h>
 #include <linux_list.h>
 
 #include "enclave_pages.h"
 
 struct pal_enclave_state pal_enclave_state;
-struct pal_enclave pal_enclave;
+
+void * enclave_base, * enclave_top;
+
+struct pal_enclave_config pal_enclave_config;
 
 bool sgx_is_within_enclave (const void * addr, uint64_t size)
 {
-    return addr >= pal_enclave.enclave_base &&
-           addr + size <= pal_enclave.enclave_base + pal_enclave.enclave_size;
+    return (addr >= enclave_base &&
+            addr + size <= enclave_top) ? 1 : 0;
 }
 
 void * sgx_ocalloc (uint64_t size)
@@ -66,8 +70,6 @@ int sgx_get_report (sgx_arch_hash_t * mrenclave,
     return 0;
 }
 
-#include "crypto/cmac.h"
-
 static sgx_arch_key128_t enclave_key;
 
 int sgx_verify_report (sgx_arch_report_t * report)
@@ -110,17 +112,14 @@ struct trusted_file {
     int             uri_len;
     char            uri[URI_MAX];
     sgx_checksum_t  checksum;
-    sgx_stub_t *    stubs;
+    sgx_arch_mac_t *    stubs;
 };
 
 static LIST_HEAD(trusted_file_list);
 static struct spinlock trusted_file_lock = LOCK_INIT;
 static int trusted_file_indexes = 0;
 
-#include <crypto/sha256.h>
-#include <crypto/sha512.h>
-
-int load_trusted_file (PAL_HANDLE file, sgx_stub_t ** stubptr,
+int load_trusted_file (PAL_HANDLE file, sgx_arch_mac_t ** stubptr,
                        uint64_t * sizeptr)
 {
     struct trusted_file * tf = NULL, * tmp;
@@ -155,10 +154,10 @@ int load_trusted_file (PAL_HANDLE file, sgx_stub_t ** stubptr,
 
     _DkSpinUnlock(&trusted_file_lock);
 
-    if (!tf)
+    if (!tf) 
         return -PAL_ERROR_DENIED;
 
-    if (tf->index < 0)
+    if (tf->index < 0) 
         return tf->index;
 
 #if CACHE_FILE_STUBS == 1
@@ -183,21 +182,16 @@ int load_trusted_file (PAL_HANDLE file, sgx_stub_t ** stubptr,
     int nstubs = tf->size / TRUSTED_STUB_SIZE +
                 (tf->size % TRUSTED_STUB_SIZE ? 1 : 0);
 
-    sgx_stub_t * stubs = malloc(sizeof(sgx_stub_t) * nstubs);
+    sgx_arch_mac_t * stubs = malloc(sizeof(sgx_arch_mac_t) * nstubs);
     if (!stubs)
         return -PAL_ERROR_NOMEM;
 
-    sgx_stub_t * s = stubs;
+    sgx_arch_mac_t * s = stubs;
     uint64_t offset = 0;
-    SHA256 sha;
+    PAL_SHA256_CONTEXT sha;
     void * umem;
-    uint8_t hash[512/8];
 
-    ret = SHA256Init(&sha);
-    if (ret < 0)
-        goto failed;
-
-    ret = ocall_map_untrusted(fd, 0, tf->size, PROT_READ, &umem);
+    ret = DkSHA256Init(&sha);
     if (ret < 0)
         goto failed;
 
@@ -206,20 +200,28 @@ int load_trusted_file (PAL_HANDLE file, sgx_stub_t ** stubptr,
         if (mapping_size > TRUSTED_STUB_SIZE)
             mapping_size = TRUSTED_STUB_SIZE;
 
-        SHA512Hash(umem + offset, mapping_size, hash);
-        memcpy(s, hash, sizeof(sgx_stub_t));
+        ret = ocall_map_untrusted(fd, offset, mapping_size, PROT_READ, &umem);
+        if (ret < 0)
+            goto unmap;
+
+        AES_CMAC((void *) &enclave_key, umem, mapping_size, (uint8_t *) s);
 
         /* update the file checksum */
-        ret = SHA256Update(&sha, umem + offset, mapping_size);
+        ret = DkSHA256Update(&sha, umem, mapping_size);
+
+unmap:
+        ocall_unmap_untrusted(umem, mapping_size);
+        if (ret < 0)
+            goto failed;
     }
 
-    ocall_unmap_untrusted(umem, tf->size);
+    sgx_checksum_t hash;
 
-    ret = SHA256Final(&sha, (uint8_t *) hash);
+    ret = DkSHA256Final(&sha, (uint8_t *) hash.bytes);
     if (ret < 0)
         goto failed;
 
-    if (memcmp(hash, &tf->checksum, sizeof(sgx_checksum_t))) {
+    if (memcmp(&hash, &tf->checksum, sizeof(sgx_checksum_t))) {
         ret = -PAL_ERROR_DENIED;
         goto failed;
     }
@@ -246,26 +248,16 @@ failed:
     }
     _DkSpinUnlock(&trusted_file_lock);
 
-#if PRINT_ENCLAVE_STAT
-    if (!ret) {
-        sgx_stub_t * loaded_stub;
-        uint64_t loaded_size;
-        PAL_HANDLE handle = NULL;
-        if (!_DkStreamOpen(&handle, uri, PAL_ACCESS_RDONLY, 0, 0, 0))
-            load_trusted_file (handle, &loaded_stub, &loaded_size);
-    }
-#endif
-
     return ret;
 }
 
 int verify_trusted_file (const char * uri, void * mem,
                          unsigned int offset, unsigned int size,
-                         sgx_stub_t * stubs,
+                         sgx_arch_mac_t * stubs,
                          unsigned int total_size)
 {
     unsigned long checking = offset;
-    sgx_stub_t * s = stubs + checking / TRUSTED_STUB_SIZE;
+    sgx_arch_mac_t * s = stubs + checking / TRUSTED_STUB_SIZE;
     int ret;
 
     for (; checking < offset + size ; checking += TRUSTED_STUB_SIZE, s++) {
@@ -273,10 +265,11 @@ int verify_trusted_file (const char * uri, void * mem,
         if (checking_size > total_size - checking)
             checking_size = total_size - checking;
 
-        uint8_t hash[512/8];
-        SHA512Hash(mem + checking - offset, checking_size, hash);
+        sgx_arch_mac_t mac;
+        AES_CMAC((void *) &enclave_key, mem + checking - offset,
+                 checking_size, (uint8_t *) &mac);
 
-        if (memcmp(s, hash, sizeof(sgx_stub_t))) {
+        if (memcmp(s, &mac, sizeof(sgx_arch_mac_t))) {
             SGX_DBG(DBG_E, "Accesing file:%s is denied. "
                     "Does not match with its MAC.\n", uri);
             return -PAL_ERROR_DENIED;
@@ -636,25 +629,21 @@ int init_enclave (void)
         goto out_free;
     }
 
-    SHA512 sha512;
-    uint8_t hash[512/8];
+    PAL_SHA256_CONTEXT sha256;
 
-    ret = SHA512Init(&sha512);
+    ret = DkSHA256Init(&sha256);
     if (ret < 0)
         goto out_free;
 
-    ret = SHA512Update(&sha512, n, nsz);
+    ret = DkSHA256Update(&sha256, n, nsz);
     if (ret < 0)
         goto out_free;
 
-    ret = SHA512Final(&sha512, hash);
+    ret = DkSHA256Final(&sha256, (uint8_t *) pal_enclave_state.enclave_keyhash);
     if (ret < 0)
         goto out_free;
 
-    memcpy(&pal_enclave_state.enclave_keyhash, hash,
-           sizeof(sgx_checksum_t));
-
-    pal_enclave.enclave_key = rsa;
+    pal_enclave_config.enclave_key = rsa;
 
     SGX_DBG(DBG_S, "enclave (software) key hash: %s\n",
            hex2str(pal_enclave_state.enclave_keyhash));

+ 4 - 7
Pal/src/host/Linux-SGX/pal_linux.h

@@ -92,14 +92,13 @@ extern char __text_start, __text_end, __data_start, __data_end;
 #define DATA_END   (void *) (&__text_end)
 
 typedef struct { char bytes[32]; } sgx_checksum_t;
-typedef struct { char bytes[16]; } sgx_stub_t;
 
 int init_trusted_files (void);
 int load_trusted_file
-    (PAL_HANDLE file, sgx_stub_t ** stubptr, uint64_t * sizeptr);
+    (PAL_HANDLE file, sgx_arch_mac_t ** stubptr, uint64_t * sizeptr);
 int verify_trusted_file
     (const char * uri, void * mem, unsigned int offset, unsigned int size,
-     sgx_stub_t * stubs, unsigned int total_size);
+     sgx_arch_mac_t * stubs, unsigned int total_size);
 
 int init_trusted_children (void);
 int register_trusted_child (const char * uri, const char * mrenclave_str);
@@ -148,13 +147,11 @@ extern struct pal_enclave_state {
 
 #define PAL_ENCLAVE_INITIALIZED     0x0001ULL
 
-extern struct pal_enclave {
-    void *                 enclave_base;
-    uint64_t               enclave_size;
+extern struct pal_enclave_config {
     sgx_arch_hash_t        mrenclave;
     sgx_arch_attributes_t  enclave_attributes;
     void *                 enclave_key;
-} pal_enclave;
+} pal_enclave_config;
 
 static inline __attribute__((always_inline))
 char * __hex2str(void * hex, int size)

+ 1 - 1
Pal/src/host/Linux-SGX/pal_linux_defs.h

@@ -20,7 +20,7 @@
 
 #define CACHE_FILE_STUBS    (1)
 
-#define USE_AES_NI          (1)
+//#define USE_AES_NI          (1)
 
 #define PRINT_ENCLAVE_STAT  (0)
 

+ 1 - 1
Pal/src/host/Linux-SGX/sgx_main.c

@@ -467,7 +467,7 @@ int initialize_enclave (struct pal_enclave * enclave)
 add_pages:
         TRY(add_pages_to_enclave,
             &enclave_secs, (void *) areas[i].addr, data, areas[i].size,
-            areas[i].type, areas[i].prot, areas[i].skip_eextend,
+            areas[i].type, areas[i].prot, (areas[i].fd == -1),
             areas[i].desc);
 
         if (data)

+ 8 - 13
Pal/src/host/Linux-SGX/signer/pal-sgx-sign

@@ -24,7 +24,7 @@ SSAFRAMENUM = 2
 ENCLAVE_STACK_SIZE = PAGESIZE * 16
 DEFAULT_ENCLAVE_SIZE = '256M'
 DEFAULT_THREAD_NUM = 4
-DEFAULT_HEAP_MIN = '0x10000'
+ENCLAVE_HEAP_MIN = 0x10000
 
 """ Utilities """
 
@@ -352,14 +352,13 @@ def get_memory_areas(manifest, attr, args):
 
 def populate_memory_areas(manifest, attr, areas):
     populating = attr['enclave_size']
-    heap_min = attr['heap_min']
 
     for area in areas:
         if area.addr is not None:
             continue
 
         area.addr = populating - area.size
-        if area.addr < heap_min:
+        if area.addr < ENCLAVE_HEAP_MIN:
             raise Exception("Enclave size is not large enough")
         if area.desc == 'exec':
             populating = area.addr;
@@ -369,17 +368,14 @@ def populate_memory_areas(manifest, attr, areas):
     free_areas = []
     for area in areas:
         if area.addr + area.size < populating:
-            if populating > heap_min:
-                addr = area.addr + area.size
-                if  addr < heap_min:
-                    addr = heap_min
-                free_areas.append(MemoryArea('free', addr=addr, size=populating - addr,
-                                  flags=PAGEINFO_R|PAGEINFO_W|PAGEINFO_X|PAGEINFO_REG))
+            addr = area.addr + area.size
+            free_areas.append(MemoryArea('free', addr=addr, size=populating - addr,
+                                flags=PAGEINFO_R|PAGEINFO_W|PAGEINFO_X|PAGEINFO_REG))
             populating = area.addr
 
-    if populating > heap_min:
-        free_areas.append(MemoryArea('free', addr=heap_min,
-                                     size=populating - heap_min,
+    if populating > ENCLAVE_HEAP_MIN:
+        free_areas.append(MemoryArea('free', addr=ENCLAVE_HEAP_MIN,
+                                     size=populating - ENCLAVE_HEAP_MIN,
                                      flags=PAGEINFO_R|PAGEINFO_W|PAGEINFO_X|PAGEINFO_REG))
 
     return areas + free_areas
@@ -700,7 +696,6 @@ if __name__ == "__main__":
 
     for key, default, parse in [
         ('enclave_size', DEFAULT_ENCLAVE_SIZE,    parse_size),
-        ('heap_min',     DEFAULT_HEAP_MIN,        parse_int),
         ('thread_num',   str(DEFAULT_THREAD_NUM), parse_int),
         ('isvprodid',    '0',                     parse_int),
         ('isvsvn',       '0',                     parse_int),